Passed
Push — master ( aff53d...7aa76a )
by Morris
18:07
created
apps/user_ldap/lib/Access.php 2 patches
Indentation   +1917 added lines, -1917 removed lines patch added patch discarded remove patch
@@ -60,1686 +60,1686 @@  discard block
 block discarded – undo
60 60
  * @package OCA\User_LDAP
61 61
  */
62 62
 class Access extends LDAPUtility implements IUserTools {
63
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
64
-
65
-	/** @var \OCA\User_LDAP\Connection */
66
-	public $connection;
67
-	/** @var Manager */
68
-	public $userManager;
69
-	//never ever check this var directly, always use getPagedSearchResultState
70
-	protected $pagedSearchedSuccessful;
71
-
72
-	/**
73
-	 * @var string[] $cookies an array of returned Paged Result cookies
74
-	 */
75
-	protected $cookies = array();
76
-
77
-	/**
78
-	 * @var string $lastCookie the last cookie returned from a Paged Results
79
-	 * operation, defaults to an empty string
80
-	 */
81
-	protected $lastCookie = '';
82
-
83
-	/**
84
-	 * @var AbstractMapping $userMapper
85
-	 */
86
-	protected $userMapper;
87
-
88
-	/**
89
-	* @var AbstractMapping $userMapper
90
-	*/
91
-	protected $groupMapper;
92
-
93
-	/**
94
-	 * @var \OCA\User_LDAP\Helper
95
-	 */
96
-	private $helper;
97
-	/** @var IConfig */
98
-	private $config;
99
-	/** @var IUserManager */
100
-	private $ncUserManager;
101
-
102
-	public function __construct(
103
-		Connection $connection,
104
-		ILDAPWrapper $ldap,
105
-		Manager $userManager,
106
-		Helper $helper,
107
-		IConfig $config,
108
-		IUserManager $ncUserManager
109
-	) {
110
-		parent::__construct($ldap);
111
-		$this->connection = $connection;
112
-		$this->userManager = $userManager;
113
-		$this->userManager->setLdapAccess($this);
114
-		$this->helper = $helper;
115
-		$this->config = $config;
116
-		$this->ncUserManager = $ncUserManager;
117
-	}
118
-
119
-	/**
120
-	 * sets the User Mapper
121
-	 * @param AbstractMapping $mapper
122
-	 */
123
-	public function setUserMapper(AbstractMapping $mapper) {
124
-		$this->userMapper = $mapper;
125
-	}
126
-
127
-	/**
128
-	 * returns the User Mapper
129
-	 * @throws \Exception
130
-	 * @return AbstractMapping
131
-	 */
132
-	public function getUserMapper() {
133
-		if(is_null($this->userMapper)) {
134
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
135
-		}
136
-		return $this->userMapper;
137
-	}
138
-
139
-	/**
140
-	 * sets the Group Mapper
141
-	 * @param AbstractMapping $mapper
142
-	 */
143
-	public function setGroupMapper(AbstractMapping $mapper) {
144
-		$this->groupMapper = $mapper;
145
-	}
146
-
147
-	/**
148
-	 * returns the Group Mapper
149
-	 * @throws \Exception
150
-	 * @return AbstractMapping
151
-	 */
152
-	public function getGroupMapper() {
153
-		if(is_null($this->groupMapper)) {
154
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
155
-		}
156
-		return $this->groupMapper;
157
-	}
158
-
159
-	/**
160
-	 * @return bool
161
-	 */
162
-	private function checkConnection() {
163
-		return ($this->connection instanceof Connection);
164
-	}
165
-
166
-	/**
167
-	 * returns the Connection instance
168
-	 * @return \OCA\User_LDAP\Connection
169
-	 */
170
-	public function getConnection() {
171
-		return $this->connection;
172
-	}
173
-
174
-	/**
175
-	 * reads a given attribute for an LDAP record identified by a DN
176
-	 *
177
-	 * @param string $dn the record in question
178
-	 * @param string $attr the attribute that shall be retrieved
179
-	 *        if empty, just check the record's existence
180
-	 * @param string $filter
181
-	 * @return array|false an array of values on success or an empty
182
-	 *          array if $attr is empty, false otherwise
183
-	 * @throws ServerNotAvailableException
184
-	 */
185
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
186
-		if(!$this->checkConnection()) {
187
-			\OCP\Util::writeLog('user_ldap',
188
-				'No LDAP Connector assigned, access impossible for readAttribute.',
189
-				ILogger::WARN);
190
-			return false;
191
-		}
192
-		$cr = $this->connection->getConnectionResource();
193
-		if(!$this->ldap->isResource($cr)) {
194
-			//LDAP not available
195
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
196
-			return false;
197
-		}
198
-		//Cancel possibly running Paged Results operation, otherwise we run in
199
-		//LDAP protocol errors
200
-		$this->abandonPagedSearch();
201
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
202
-		// but does not hurt either.
203
-		$pagingSize = (int)$this->connection->ldapPagingSize;
204
-		// 0 won't result in replies, small numbers may leave out groups
205
-		// (cf. #12306), 500 is default for paging and should work everywhere.
206
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
207
-		$attr = mb_strtolower($attr, 'UTF-8');
208
-		// the actual read attribute later may contain parameters on a ranged
209
-		// request, e.g. member;range=99-199. Depends on server reply.
210
-		$attrToRead = $attr;
211
-
212
-		$values = [];
213
-		$isRangeRequest = false;
214
-		do {
215
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
216
-			if(is_bool($result)) {
217
-				// when an exists request was run and it was successful, an empty
218
-				// array must be returned
219
-				return $result ? [] : false;
220
-			}
221
-
222
-			if (!$isRangeRequest) {
223
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
224
-				if (!empty($values)) {
225
-					return $values;
226
-				}
227
-			}
228
-
229
-			$isRangeRequest = false;
230
-			$result = $this->extractRangeData($result, $attr);
231
-			if (!empty($result)) {
232
-				$normalizedResult = $this->extractAttributeValuesFromResult(
233
-					[ $attr => $result['values'] ],
234
-					$attr
235
-				);
236
-				$values = array_merge($values, $normalizedResult);
237
-
238
-				if($result['rangeHigh'] === '*') {
239
-					// when server replies with * as high range value, there are
240
-					// no more results left
241
-					return $values;
242
-				} else {
243
-					$low  = $result['rangeHigh'] + 1;
244
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
245
-					$isRangeRequest = true;
246
-				}
247
-			}
248
-		} while($isRangeRequest);
249
-
250
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
251
-		return false;
252
-	}
253
-
254
-	/**
255
-	 * Runs an read operation against LDAP
256
-	 *
257
-	 * @param resource $cr the LDAP connection
258
-	 * @param string $dn
259
-	 * @param string $attribute
260
-	 * @param string $filter
261
-	 * @param int $maxResults
262
-	 * @return array|bool false if there was any error, true if an exists check
263
-	 *                    was performed and the requested DN found, array with the
264
-	 *                    returned data on a successful usual operation
265
-	 * @throws ServerNotAvailableException
266
-	 */
267
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
268
-		$this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
269
-		$dn = $this->helper->DNasBaseParameter($dn);
270
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
271
-		if (!$this->ldap->isResource($rr)) {
272
-			if ($attribute !== '') {
273
-				//do not throw this message on userExists check, irritates
274
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
275
-			}
276
-			//in case an error occurs , e.g. object does not exist
277
-			return false;
278
-		}
279
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
280
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
281
-			return true;
282
-		}
283
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
284
-		if (!$this->ldap->isResource($er)) {
285
-			//did not match the filter, return false
286
-			return false;
287
-		}
288
-		//LDAP attributes are not case sensitive
289
-		$result = \OCP\Util::mb_array_change_key_case(
290
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
291
-
292
-		return $result;
293
-	}
294
-
295
-	/**
296
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
297
-	 * data if present.
298
-	 *
299
-	 * @param array $result from ILDAPWrapper::getAttributes()
300
-	 * @param string $attribute the attribute name that was read
301
-	 * @return string[]
302
-	 */
303
-	public function extractAttributeValuesFromResult($result, $attribute) {
304
-		$values = [];
305
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
306
-			$lowercaseAttribute = strtolower($attribute);
307
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
308
-				if($this->resemblesDN($attribute)) {
309
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
310
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
311
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
312
-				} else {
313
-					$values[] = $result[$attribute][$i];
314
-				}
315
-			}
316
-		}
317
-		return $values;
318
-	}
319
-
320
-	/**
321
-	 * Attempts to find ranged data in a getAttribute results and extracts the
322
-	 * returned values as well as information on the range and full attribute
323
-	 * name for further processing.
324
-	 *
325
-	 * @param array $result from ILDAPWrapper::getAttributes()
326
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
327
-	 * @return array If a range was detected with keys 'values', 'attributeName',
328
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
329
-	 */
330
-	public function extractRangeData($result, $attribute) {
331
-		$keys = array_keys($result);
332
-		foreach($keys as $key) {
333
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
334
-				$queryData = explode(';', $key);
335
-				if(strpos($queryData[1], 'range=') === 0) {
336
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
337
-					$data = [
338
-						'values' => $result[$key],
339
-						'attributeName' => $queryData[0],
340
-						'attributeFull' => $key,
341
-						'rangeHigh' => $high,
342
-					];
343
-					return $data;
344
-				}
345
-			}
346
-		}
347
-		return [];
348
-	}
63
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
64
+
65
+    /** @var \OCA\User_LDAP\Connection */
66
+    public $connection;
67
+    /** @var Manager */
68
+    public $userManager;
69
+    //never ever check this var directly, always use getPagedSearchResultState
70
+    protected $pagedSearchedSuccessful;
71
+
72
+    /**
73
+     * @var string[] $cookies an array of returned Paged Result cookies
74
+     */
75
+    protected $cookies = array();
76
+
77
+    /**
78
+     * @var string $lastCookie the last cookie returned from a Paged Results
79
+     * operation, defaults to an empty string
80
+     */
81
+    protected $lastCookie = '';
82
+
83
+    /**
84
+     * @var AbstractMapping $userMapper
85
+     */
86
+    protected $userMapper;
87
+
88
+    /**
89
+     * @var AbstractMapping $userMapper
90
+     */
91
+    protected $groupMapper;
92
+
93
+    /**
94
+     * @var \OCA\User_LDAP\Helper
95
+     */
96
+    private $helper;
97
+    /** @var IConfig */
98
+    private $config;
99
+    /** @var IUserManager */
100
+    private $ncUserManager;
101
+
102
+    public function __construct(
103
+        Connection $connection,
104
+        ILDAPWrapper $ldap,
105
+        Manager $userManager,
106
+        Helper $helper,
107
+        IConfig $config,
108
+        IUserManager $ncUserManager
109
+    ) {
110
+        parent::__construct($ldap);
111
+        $this->connection = $connection;
112
+        $this->userManager = $userManager;
113
+        $this->userManager->setLdapAccess($this);
114
+        $this->helper = $helper;
115
+        $this->config = $config;
116
+        $this->ncUserManager = $ncUserManager;
117
+    }
118
+
119
+    /**
120
+     * sets the User Mapper
121
+     * @param AbstractMapping $mapper
122
+     */
123
+    public function setUserMapper(AbstractMapping $mapper) {
124
+        $this->userMapper = $mapper;
125
+    }
126
+
127
+    /**
128
+     * returns the User Mapper
129
+     * @throws \Exception
130
+     * @return AbstractMapping
131
+     */
132
+    public function getUserMapper() {
133
+        if(is_null($this->userMapper)) {
134
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
135
+        }
136
+        return $this->userMapper;
137
+    }
138
+
139
+    /**
140
+     * sets the Group Mapper
141
+     * @param AbstractMapping $mapper
142
+     */
143
+    public function setGroupMapper(AbstractMapping $mapper) {
144
+        $this->groupMapper = $mapper;
145
+    }
146
+
147
+    /**
148
+     * returns the Group Mapper
149
+     * @throws \Exception
150
+     * @return AbstractMapping
151
+     */
152
+    public function getGroupMapper() {
153
+        if(is_null($this->groupMapper)) {
154
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
155
+        }
156
+        return $this->groupMapper;
157
+    }
158
+
159
+    /**
160
+     * @return bool
161
+     */
162
+    private function checkConnection() {
163
+        return ($this->connection instanceof Connection);
164
+    }
165
+
166
+    /**
167
+     * returns the Connection instance
168
+     * @return \OCA\User_LDAP\Connection
169
+     */
170
+    public function getConnection() {
171
+        return $this->connection;
172
+    }
173
+
174
+    /**
175
+     * reads a given attribute for an LDAP record identified by a DN
176
+     *
177
+     * @param string $dn the record in question
178
+     * @param string $attr the attribute that shall be retrieved
179
+     *        if empty, just check the record's existence
180
+     * @param string $filter
181
+     * @return array|false an array of values on success or an empty
182
+     *          array if $attr is empty, false otherwise
183
+     * @throws ServerNotAvailableException
184
+     */
185
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
186
+        if(!$this->checkConnection()) {
187
+            \OCP\Util::writeLog('user_ldap',
188
+                'No LDAP Connector assigned, access impossible for readAttribute.',
189
+                ILogger::WARN);
190
+            return false;
191
+        }
192
+        $cr = $this->connection->getConnectionResource();
193
+        if(!$this->ldap->isResource($cr)) {
194
+            //LDAP not available
195
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
196
+            return false;
197
+        }
198
+        //Cancel possibly running Paged Results operation, otherwise we run in
199
+        //LDAP protocol errors
200
+        $this->abandonPagedSearch();
201
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
202
+        // but does not hurt either.
203
+        $pagingSize = (int)$this->connection->ldapPagingSize;
204
+        // 0 won't result in replies, small numbers may leave out groups
205
+        // (cf. #12306), 500 is default for paging and should work everywhere.
206
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
207
+        $attr = mb_strtolower($attr, 'UTF-8');
208
+        // the actual read attribute later may contain parameters on a ranged
209
+        // request, e.g. member;range=99-199. Depends on server reply.
210
+        $attrToRead = $attr;
211
+
212
+        $values = [];
213
+        $isRangeRequest = false;
214
+        do {
215
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
216
+            if(is_bool($result)) {
217
+                // when an exists request was run and it was successful, an empty
218
+                // array must be returned
219
+                return $result ? [] : false;
220
+            }
221
+
222
+            if (!$isRangeRequest) {
223
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
224
+                if (!empty($values)) {
225
+                    return $values;
226
+                }
227
+            }
228
+
229
+            $isRangeRequest = false;
230
+            $result = $this->extractRangeData($result, $attr);
231
+            if (!empty($result)) {
232
+                $normalizedResult = $this->extractAttributeValuesFromResult(
233
+                    [ $attr => $result['values'] ],
234
+                    $attr
235
+                );
236
+                $values = array_merge($values, $normalizedResult);
237
+
238
+                if($result['rangeHigh'] === '*') {
239
+                    // when server replies with * as high range value, there are
240
+                    // no more results left
241
+                    return $values;
242
+                } else {
243
+                    $low  = $result['rangeHigh'] + 1;
244
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
245
+                    $isRangeRequest = true;
246
+                }
247
+            }
248
+        } while($isRangeRequest);
249
+
250
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
251
+        return false;
252
+    }
253
+
254
+    /**
255
+     * Runs an read operation against LDAP
256
+     *
257
+     * @param resource $cr the LDAP connection
258
+     * @param string $dn
259
+     * @param string $attribute
260
+     * @param string $filter
261
+     * @param int $maxResults
262
+     * @return array|bool false if there was any error, true if an exists check
263
+     *                    was performed and the requested DN found, array with the
264
+     *                    returned data on a successful usual operation
265
+     * @throws ServerNotAvailableException
266
+     */
267
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
268
+        $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
269
+        $dn = $this->helper->DNasBaseParameter($dn);
270
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
271
+        if (!$this->ldap->isResource($rr)) {
272
+            if ($attribute !== '') {
273
+                //do not throw this message on userExists check, irritates
274
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
275
+            }
276
+            //in case an error occurs , e.g. object does not exist
277
+            return false;
278
+        }
279
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
280
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
281
+            return true;
282
+        }
283
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
284
+        if (!$this->ldap->isResource($er)) {
285
+            //did not match the filter, return false
286
+            return false;
287
+        }
288
+        //LDAP attributes are not case sensitive
289
+        $result = \OCP\Util::mb_array_change_key_case(
290
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
291
+
292
+        return $result;
293
+    }
294
+
295
+    /**
296
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
297
+     * data if present.
298
+     *
299
+     * @param array $result from ILDAPWrapper::getAttributes()
300
+     * @param string $attribute the attribute name that was read
301
+     * @return string[]
302
+     */
303
+    public function extractAttributeValuesFromResult($result, $attribute) {
304
+        $values = [];
305
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
306
+            $lowercaseAttribute = strtolower($attribute);
307
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
308
+                if($this->resemblesDN($attribute)) {
309
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
310
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
311
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
312
+                } else {
313
+                    $values[] = $result[$attribute][$i];
314
+                }
315
+            }
316
+        }
317
+        return $values;
318
+    }
319
+
320
+    /**
321
+     * Attempts to find ranged data in a getAttribute results and extracts the
322
+     * returned values as well as information on the range and full attribute
323
+     * name for further processing.
324
+     *
325
+     * @param array $result from ILDAPWrapper::getAttributes()
326
+     * @param string $attribute the attribute name that was read. Without ";range=…"
327
+     * @return array If a range was detected with keys 'values', 'attributeName',
328
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
329
+     */
330
+    public function extractRangeData($result, $attribute) {
331
+        $keys = array_keys($result);
332
+        foreach($keys as $key) {
333
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
334
+                $queryData = explode(';', $key);
335
+                if(strpos($queryData[1], 'range=') === 0) {
336
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
337
+                    $data = [
338
+                        'values' => $result[$key],
339
+                        'attributeName' => $queryData[0],
340
+                        'attributeFull' => $key,
341
+                        'rangeHigh' => $high,
342
+                    ];
343
+                    return $data;
344
+                }
345
+            }
346
+        }
347
+        return [];
348
+    }
349 349
 	
350
-	/**
351
-	 * Set password for an LDAP user identified by a DN
352
-	 *
353
-	 * @param string $userDN the user in question
354
-	 * @param string $password the new password
355
-	 * @return bool
356
-	 * @throws HintException
357
-	 * @throws \Exception
358
-	 */
359
-	public function setPassword($userDN, $password) {
360
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
361
-			throw new \Exception('LDAP password changes are disabled.');
362
-		}
363
-		$cr = $this->connection->getConnectionResource();
364
-		if(!$this->ldap->isResource($cr)) {
365
-			//LDAP not available
366
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
367
-			return false;
368
-		}
369
-		try {
370
-			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
371
-		} catch(ConstraintViolationException $e) {
372
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
373
-		}
374
-	}
375
-
376
-	/**
377
-	 * checks whether the given attributes value is probably a DN
378
-	 * @param string $attr the attribute in question
379
-	 * @return boolean if so true, otherwise false
380
-	 */
381
-	private function resemblesDN($attr) {
382
-		$resemblingAttributes = array(
383
-			'dn',
384
-			'uniquemember',
385
-			'member',
386
-			// memberOf is an "operational" attribute, without a definition in any RFC
387
-			'memberof'
388
-		);
389
-		return in_array($attr, $resemblingAttributes);
390
-	}
391
-
392
-	/**
393
-	 * checks whether the given string is probably a DN
394
-	 * @param string $string
395
-	 * @return boolean
396
-	 */
397
-	public function stringResemblesDN($string) {
398
-		$r = $this->ldap->explodeDN($string, 0);
399
-		// if exploding a DN succeeds and does not end up in
400
-		// an empty array except for $r[count] being 0.
401
-		return (is_array($r) && count($r) > 1);
402
-	}
403
-
404
-	/**
405
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
406
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
407
-	 * becomes dc=foobar,dc=server,dc=org
408
-	 * @param string $dn
409
-	 * @return string
410
-	 */
411
-	public function getDomainDNFromDN($dn) {
412
-		$allParts = $this->ldap->explodeDN($dn, 0);
413
-		if($allParts === false) {
414
-			//not a valid DN
415
-			return '';
416
-		}
417
-		$domainParts = array();
418
-		$dcFound = false;
419
-		foreach($allParts as $part) {
420
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
421
-				$dcFound = true;
422
-			}
423
-			if($dcFound) {
424
-				$domainParts[] = $part;
425
-			}
426
-		}
427
-		return implode(',', $domainParts);
428
-	}
429
-
430
-	/**
431
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
432
-	 * @param string $name the Nextcloud name in question
433
-	 * @return string|false LDAP DN on success, otherwise false
434
-	 */
435
-	public function groupname2dn($name) {
436
-		return $this->groupMapper->getDNByName($name);
437
-	}
438
-
439
-	/**
440
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
441
-	 * @param string $name the Nextcloud name in question
442
-	 * @return string|false with the LDAP DN on success, otherwise false
443
-	 */
444
-	public function username2dn($name) {
445
-		$fdn = $this->userMapper->getDNByName($name);
446
-
447
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
448
-		//server setups
449
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
450
-			return $fdn;
451
-		}
452
-
453
-		return false;
454
-	}
455
-
456
-	/**
457
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
458
-	 * @param string $fdn the dn of the group object
459
-	 * @param string $ldapName optional, the display name of the object
460
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
461
-	 */
462
-	public function dn2groupname($fdn, $ldapName = null) {
463
-		//To avoid bypassing the base DN settings under certain circumstances
464
-		//with the group support, check whether the provided DN matches one of
465
-		//the given Bases
466
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
467
-			return false;
468
-		}
469
-
470
-		return $this->dn2ocname($fdn, $ldapName, false);
471
-	}
472
-
473
-	/**
474
-	 * accepts an array of group DNs and tests whether they match the user
475
-	 * filter by doing read operations against the group entries. Returns an
476
-	 * array of DNs that match the filter.
477
-	 *
478
-	 * @param string[] $groupDNs
479
-	 * @return string[]
480
-	 * @throws ServerNotAvailableException
481
-	 */
482
-	public function groupsMatchFilter($groupDNs) {
483
-		$validGroupDNs = [];
484
-		foreach($groupDNs as $dn) {
485
-			$cacheKey = 'groupsMatchFilter-'.$dn;
486
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
487
-			if(!is_null($groupMatchFilter)) {
488
-				if($groupMatchFilter) {
489
-					$validGroupDNs[] = $dn;
490
-				}
491
-				continue;
492
-			}
493
-
494
-			// Check the base DN first. If this is not met already, we don't
495
-			// need to ask the server at all.
496
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
497
-				$this->connection->writeToCache($cacheKey, false);
498
-				continue;
499
-			}
500
-
501
-			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
502
-			if(is_array($result)) {
503
-				$this->connection->writeToCache($cacheKey, true);
504
-				$validGroupDNs[] = $dn;
505
-			} else {
506
-				$this->connection->writeToCache($cacheKey, false);
507
-			}
508
-
509
-		}
510
-		return $validGroupDNs;
511
-	}
512
-
513
-	/**
514
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
515
-	 * @param string $dn the dn of the user object
516
-	 * @param string $ldapName optional, the display name of the object
517
-	 * @return string|false with with the name to use in Nextcloud
518
-	 */
519
-	public function dn2username($fdn, $ldapName = null) {
520
-		//To avoid bypassing the base DN settings under certain circumstances
521
-		//with the group support, check whether the provided DN matches one of
522
-		//the given Bases
523
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
524
-			return false;
525
-		}
526
-
527
-		return $this->dn2ocname($fdn, $ldapName, true);
528
-	}
529
-
530
-	/**
531
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
532
-	 *
533
-	 * @param string $fdn the dn of the user object
534
-	 * @param string|null $ldapName optional, the display name of the object
535
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
536
-	 * @param bool|null $newlyMapped
537
-	 * @param array|null $record
538
-	 * @return false|string with with the name to use in Nextcloud
539
-	 * @throws \Exception
540
-	 */
541
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
542
-		$newlyMapped = false;
543
-		if($isUser) {
544
-			$mapper = $this->getUserMapper();
545
-			$nameAttribute = $this->connection->ldapUserDisplayName;
546
-			$filter = $this->connection->ldapUserFilter;
547
-		} else {
548
-			$mapper = $this->getGroupMapper();
549
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
550
-			$filter = $this->connection->ldapGroupFilter;
551
-		}
552
-
553
-		//let's try to retrieve the Nextcloud name from the mappings table
554
-		$ncName = $mapper->getNameByDN($fdn);
555
-		if(is_string($ncName)) {
556
-			return $ncName;
557
-		}
558
-
559
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
560
-		$uuid = $this->getUUID($fdn, $isUser, $record);
561
-		if(is_string($uuid)) {
562
-			$ncName = $mapper->getNameByUUID($uuid);
563
-			if(is_string($ncName)) {
564
-				$mapper->setDNbyUUID($fdn, $uuid);
565
-				return $ncName;
566
-			}
567
-		} else {
568
-			//If the UUID can't be detected something is foul.
569
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
570
-			return false;
571
-		}
572
-
573
-		if(is_null($ldapName)) {
574
-			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
575
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
576
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
577
-				return false;
578
-			}
579
-			$ldapName = $ldapName[0];
580
-		}
581
-
582
-		if($isUser) {
583
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
584
-			if ($usernameAttribute !== '') {
585
-				$username = $this->readAttribute($fdn, $usernameAttribute);
586
-				$username = $username[0];
587
-			} else {
588
-				$username = $uuid;
589
-			}
590
-			try {
591
-				$intName = $this->sanitizeUsername($username);
592
-			} catch (\InvalidArgumentException $e) {
593
-				\OC::$server->getLogger()->logException($e, [
594
-					'app' => 'user_ldap',
595
-					'level' => ILogger::WARN,
596
-				]);
597
-				// we don't attempt to set a username here. We can go for
598
-				// for an alternative 4 digit random number as we would append
599
-				// otherwise, however it's likely not enough space in bigger
600
-				// setups, and most importantly: this is not intended.
601
-				return false;
602
-			}
603
-		} else {
604
-			$intName = $ldapName;
605
-		}
606
-
607
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
608
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
609
-		//NOTE: mind, disabling cache affects only this instance! Using it
610
-		// outside of core user management will still cache the user as non-existing.
611
-		$originalTTL = $this->connection->ldapCacheTTL;
612
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
613
-		if(($isUser && $intName !== '' && !$this->ncUserManager->userExists($intName))
614
-			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
615
-			if($mapper->map($fdn, $intName, $uuid)) {
616
-				$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
617
-				if($this->ncUserManager instanceof PublicEmitter && $isUser) {
618
-					$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$intName]);
619
-				}
620
-				$newlyMapped = true;
621
-				return $intName;
622
-			}
623
-		}
624
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
625
-
626
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
627
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
628
-			if($this->ncUserManager instanceof PublicEmitter && $isUser) {
629
-				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$intName]);
630
-			}
631
-			$newlyMapped = true;
632
-			return $altName;
633
-		}
634
-
635
-		//if everything else did not help..
636
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
637
-		return false;
638
-	}
639
-
640
-	/**
641
-	 * gives back the user names as they are used ownClod internally
642
-	 * @param array $ldapUsers as returned by fetchList()
643
-	 * @return array an array with the user names to use in Nextcloud
644
-	 *
645
-	 * gives back the user names as they are used ownClod internally
646
-	 */
647
-	public function nextcloudUserNames($ldapUsers) {
648
-		return $this->ldap2NextcloudNames($ldapUsers, true);
649
-	}
650
-
651
-	/**
652
-	 * gives back the group names as they are used ownClod internally
653
-	 * @param array $ldapGroups as returned by fetchList()
654
-	 * @return array an array with the group names to use in Nextcloud
655
-	 *
656
-	 * gives back the group names as they are used ownClod internally
657
-	 */
658
-	public function nextcloudGroupNames($ldapGroups) {
659
-		return $this->ldap2NextcloudNames($ldapGroups, false);
660
-	}
661
-
662
-	/**
663
-	 * @param array $ldapObjects as returned by fetchList()
664
-	 * @param bool $isUsers
665
-	 * @return array
666
-	 * @throws \Exception
667
-	 */
668
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
669
-		if($isUsers) {
670
-			$nameAttribute = $this->connection->ldapUserDisplayName;
671
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
672
-		} else {
673
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
674
-		}
675
-		$nextcloudNames = [];
676
-
677
-		foreach($ldapObjects as $ldapObject) {
678
-			$nameByLDAP = null;
679
-			if(    isset($ldapObject[$nameAttribute])
680
-				&& is_array($ldapObject[$nameAttribute])
681
-				&& isset($ldapObject[$nameAttribute][0])
682
-			) {
683
-				// might be set, but not necessarily. if so, we use it.
684
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
685
-			}
686
-
687
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
688
-			if($ncName) {
689
-				$nextcloudNames[] = $ncName;
690
-				if($isUsers) {
691
-					$this->updateUserState($ncName);
692
-					//cache the user names so it does not need to be retrieved
693
-					//again later (e.g. sharing dialogue).
694
-					if(is_null($nameByLDAP)) {
695
-						continue;
696
-					}
697
-					$sndName = isset($ldapObject[$sndAttribute][0])
698
-						? $ldapObject[$sndAttribute][0] : '';
699
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
700
-				}
701
-			}
702
-		}
703
-		return $nextcloudNames;
704
-	}
705
-
706
-	/**
707
-	 * removes the deleted-flag of a user if it was set
708
-	 *
709
-	 * @param string $ncname
710
-	 * @throws \Exception
711
-	 */
712
-	public function updateUserState($ncname) {
713
-		$user = $this->userManager->get($ncname);
714
-		if($user instanceof OfflineUser) {
715
-			$user->unmark();
716
-		}
717
-	}
718
-
719
-	/**
720
-	 * caches the user display name
721
-	 * @param string $ocName the internal Nextcloud username
722
-	 * @param string|false $home the home directory path
723
-	 */
724
-	public function cacheUserHome($ocName, $home) {
725
-		$cacheKey = 'getHome'.$ocName;
726
-		$this->connection->writeToCache($cacheKey, $home);
727
-	}
728
-
729
-	/**
730
-	 * caches a user as existing
731
-	 * @param string $ocName the internal Nextcloud username
732
-	 */
733
-	public function cacheUserExists($ocName) {
734
-		$this->connection->writeToCache('userExists'.$ocName, true);
735
-	}
736
-
737
-	/**
738
-	 * caches the user display name
739
-	 * @param string $ocName the internal Nextcloud username
740
-	 * @param string $displayName the display name
741
-	 * @param string $displayName2 the second display name
742
-	 */
743
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
744
-		$user = $this->userManager->get($ocName);
745
-		if($user === null) {
746
-			return;
747
-		}
748
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
749
-		$cacheKeyTrunk = 'getDisplayName';
750
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
751
-	}
752
-
753
-	/**
754
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
755
-	 * @param string $name the display name of the object
756
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
757
-	 *
758
-	 * Instead of using this method directly, call
759
-	 * createAltInternalOwnCloudName($name, true)
760
-	 */
761
-	private function _createAltInternalOwnCloudNameForUsers($name) {
762
-		$attempts = 0;
763
-		//while loop is just a precaution. If a name is not generated within
764
-		//20 attempts, something else is very wrong. Avoids infinite loop.
765
-		while($attempts < 20){
766
-			$altName = $name . '_' . rand(1000,9999);
767
-			if(!$this->ncUserManager->userExists($altName)) {
768
-				return $altName;
769
-			}
770
-			$attempts++;
771
-		}
772
-		return false;
773
-	}
774
-
775
-	/**
776
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
777
-	 * @param string $name the display name of the object
778
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
779
-	 *
780
-	 * Instead of using this method directly, call
781
-	 * createAltInternalOwnCloudName($name, false)
782
-	 *
783
-	 * Group names are also used as display names, so we do a sequential
784
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
785
-	 * "Developers"
786
-	 */
787
-	private function _createAltInternalOwnCloudNameForGroups($name) {
788
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
789
-		if(!$usedNames || count($usedNames) === 0) {
790
-			$lastNo = 1; //will become name_2
791
-		} else {
792
-			natsort($usedNames);
793
-			$lastName = array_pop($usedNames);
794
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
795
-		}
796
-		$altName = $name.'_'. (string)($lastNo+1);
797
-		unset($usedNames);
798
-
799
-		$attempts = 1;
800
-		while($attempts < 21){
801
-			// Check to be really sure it is unique
802
-			// while loop is just a precaution. If a name is not generated within
803
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
804
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
805
-				return $altName;
806
-			}
807
-			$altName = $name . '_' . ($lastNo + $attempts);
808
-			$attempts++;
809
-		}
810
-		return false;
811
-	}
812
-
813
-	/**
814
-	 * creates a unique name for internal Nextcloud use.
815
-	 * @param string $name the display name of the object
816
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
817
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
818
-	 */
819
-	private function createAltInternalOwnCloudName($name, $isUser) {
820
-		$originalTTL = $this->connection->ldapCacheTTL;
821
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
822
-		if($isUser) {
823
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
824
-		} else {
825
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
826
-		}
827
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
828
-
829
-		return $altName;
830
-	}
831
-
832
-	/**
833
-	 * fetches a list of users according to a provided loginName and utilizing
834
-	 * the login filter.
835
-	 *
836
-	 * @param string $loginName
837
-	 * @param array $attributes optional, list of attributes to read
838
-	 * @return array
839
-	 */
840
-	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
841
-		$loginName = $this->escapeFilterPart($loginName);
842
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
843
-		return $this->fetchListOfUsers($filter, $attributes);
844
-	}
845
-
846
-	/**
847
-	 * counts the number of users according to a provided loginName and
848
-	 * utilizing the login filter.
849
-	 *
850
-	 * @param string $loginName
851
-	 * @return int
852
-	 */
853
-	public function countUsersByLoginName($loginName) {
854
-		$loginName = $this->escapeFilterPart($loginName);
855
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
856
-		return $this->countUsers($filter);
857
-	}
858
-
859
-	/**
860
-	 * @param string $filter
861
-	 * @param string|string[] $attr
862
-	 * @param int $limit
863
-	 * @param int $offset
864
-	 * @param bool $forceApplyAttributes
865
-	 * @return array
866
-	 */
867
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
868
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
869
-		$recordsToUpdate = $ldapRecords;
870
-		if(!$forceApplyAttributes) {
871
-			$isBackgroundJobModeAjax = $this->config
872
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
873
-			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
874
-				$newlyMapped = false;
875
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
876
-				if(is_string($uid)) {
877
-					$this->cacheUserExists($uid);
878
-				}
879
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
880
-			});
881
-		}
882
-		$this->batchApplyUserAttributes($recordsToUpdate);
883
-		return $this->fetchList($ldapRecords, count($attr) > 1);
884
-	}
885
-
886
-	/**
887
-	 * provided with an array of LDAP user records the method will fetch the
888
-	 * user object and requests it to process the freshly fetched attributes and
889
-	 * and their values
890
-	 *
891
-	 * @param array $ldapRecords
892
-	 * @throws \Exception
893
-	 */
894
-	public function batchApplyUserAttributes(array $ldapRecords){
895
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
896
-		foreach($ldapRecords as $userRecord) {
897
-			if(!isset($userRecord[$displayNameAttribute])) {
898
-				// displayName is obligatory
899
-				continue;
900
-			}
901
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
902
-			if($ocName === false) {
903
-				continue;
904
-			}
905
-			$this->updateUserState($ocName);
906
-			$user = $this->userManager->get($ocName);
907
-			if ($user !== null) {
908
-				$user->processAttributes($userRecord);
909
-			} else {
910
-				\OC::$server->getLogger()->debug(
911
-					"The ldap user manager returned null for $ocName",
912
-					['app'=>'user_ldap']
913
-				);
914
-			}
915
-		}
916
-	}
917
-
918
-	/**
919
-	 * @param string $filter
920
-	 * @param string|string[] $attr
921
-	 * @param int $limit
922
-	 * @param int $offset
923
-	 * @return array
924
-	 */
925
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
926
-		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), count($attr) > 1);
927
-	}
928
-
929
-	/**
930
-	 * @param array $list
931
-	 * @param bool $manyAttributes
932
-	 * @return array
933
-	 */
934
-	private function fetchList($list, $manyAttributes) {
935
-		if(is_array($list)) {
936
-			if($manyAttributes) {
937
-				return $list;
938
-			} else {
939
-				$list = array_reduce($list, function($carry, $item) {
940
-					$attribute = array_keys($item)[0];
941
-					$carry[] = $item[$attribute][0];
942
-					return $carry;
943
-				}, array());
944
-				return array_unique($list, SORT_LOCALE_STRING);
945
-			}
946
-		}
947
-
948
-		//error cause actually, maybe throw an exception in future.
949
-		return array();
950
-	}
951
-
952
-	/**
953
-	 * executes an LDAP search, optimized for Users
954
-	 * @param string $filter the LDAP filter for the search
955
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
956
-	 * @param integer $limit
957
-	 * @param integer $offset
958
-	 * @return array with the search result
959
-	 *
960
-	 * Executes an LDAP search
961
-	 */
962
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
963
-		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
964
-	}
965
-
966
-	/**
967
-	 * @param string $filter
968
-	 * @param string|string[] $attr
969
-	 * @param int $limit
970
-	 * @param int $offset
971
-	 * @return false|int
972
-	 */
973
-	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
974
-		return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
975
-	}
976
-
977
-	/**
978
-	 * executes an LDAP search, optimized for Groups
979
-	 * @param string $filter the LDAP filter for the search
980
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
981
-	 * @param integer $limit
982
-	 * @param integer $offset
983
-	 * @return array with the search result
984
-	 *
985
-	 * Executes an LDAP search
986
-	 */
987
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
988
-		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
989
-	}
990
-
991
-	/**
992
-	 * returns the number of available groups
993
-	 * @param string $filter the LDAP search filter
994
-	 * @param string[] $attr optional
995
-	 * @param int|null $limit
996
-	 * @param int|null $offset
997
-	 * @return int|bool
998
-	 */
999
-	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
1000
-		return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
1001
-	}
1002
-
1003
-	/**
1004
-	 * returns the number of available objects on the base DN
1005
-	 *
1006
-	 * @param int|null $limit
1007
-	 * @param int|null $offset
1008
-	 * @return int|bool
1009
-	 */
1010
-	public function countObjects($limit = null, $offset = null) {
1011
-		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
1012
-	}
1013
-
1014
-	/**
1015
-	 * Returns the LDAP handler
1016
-	 * @throws \OC\ServerNotAvailableException
1017
-	 */
1018
-
1019
-	/**
1020
-	 * @return mixed
1021
-	 * @throws \OC\ServerNotAvailableException
1022
-	 */
1023
-	private function invokeLDAPMethod() {
1024
-		$arguments = func_get_args();
1025
-		$command = array_shift($arguments);
1026
-		$cr = array_shift($arguments);
1027
-		if (!method_exists($this->ldap, $command)) {
1028
-			return null;
1029
-		}
1030
-		array_unshift($arguments, $cr);
1031
-		// php no longer supports call-time pass-by-reference
1032
-		// thus cannot support controlPagedResultResponse as the third argument
1033
-		// is a reference
1034
-		$doMethod = function () use ($command, &$arguments) {
1035
-			if ($command == 'controlPagedResultResponse') {
1036
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1037
-			} else {
1038
-				return call_user_func_array(array($this->ldap, $command), $arguments);
1039
-			}
1040
-		};
1041
-		try {
1042
-			$ret = $doMethod();
1043
-		} catch (ServerNotAvailableException $e) {
1044
-			/* Server connection lost, attempt to reestablish it
350
+    /**
351
+     * Set password for an LDAP user identified by a DN
352
+     *
353
+     * @param string $userDN the user in question
354
+     * @param string $password the new password
355
+     * @return bool
356
+     * @throws HintException
357
+     * @throws \Exception
358
+     */
359
+    public function setPassword($userDN, $password) {
360
+        if((int)$this->connection->turnOnPasswordChange !== 1) {
361
+            throw new \Exception('LDAP password changes are disabled.');
362
+        }
363
+        $cr = $this->connection->getConnectionResource();
364
+        if(!$this->ldap->isResource($cr)) {
365
+            //LDAP not available
366
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
367
+            return false;
368
+        }
369
+        try {
370
+            return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
371
+        } catch(ConstraintViolationException $e) {
372
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
373
+        }
374
+    }
375
+
376
+    /**
377
+     * checks whether the given attributes value is probably a DN
378
+     * @param string $attr the attribute in question
379
+     * @return boolean if so true, otherwise false
380
+     */
381
+    private function resemblesDN($attr) {
382
+        $resemblingAttributes = array(
383
+            'dn',
384
+            'uniquemember',
385
+            'member',
386
+            // memberOf is an "operational" attribute, without a definition in any RFC
387
+            'memberof'
388
+        );
389
+        return in_array($attr, $resemblingAttributes);
390
+    }
391
+
392
+    /**
393
+     * checks whether the given string is probably a DN
394
+     * @param string $string
395
+     * @return boolean
396
+     */
397
+    public function stringResemblesDN($string) {
398
+        $r = $this->ldap->explodeDN($string, 0);
399
+        // if exploding a DN succeeds and does not end up in
400
+        // an empty array except for $r[count] being 0.
401
+        return (is_array($r) && count($r) > 1);
402
+    }
403
+
404
+    /**
405
+     * returns a DN-string that is cleaned from not domain parts, e.g.
406
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
407
+     * becomes dc=foobar,dc=server,dc=org
408
+     * @param string $dn
409
+     * @return string
410
+     */
411
+    public function getDomainDNFromDN($dn) {
412
+        $allParts = $this->ldap->explodeDN($dn, 0);
413
+        if($allParts === false) {
414
+            //not a valid DN
415
+            return '';
416
+        }
417
+        $domainParts = array();
418
+        $dcFound = false;
419
+        foreach($allParts as $part) {
420
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
421
+                $dcFound = true;
422
+            }
423
+            if($dcFound) {
424
+                $domainParts[] = $part;
425
+            }
426
+        }
427
+        return implode(',', $domainParts);
428
+    }
429
+
430
+    /**
431
+     * returns the LDAP DN for the given internal Nextcloud name of the group
432
+     * @param string $name the Nextcloud name in question
433
+     * @return string|false LDAP DN on success, otherwise false
434
+     */
435
+    public function groupname2dn($name) {
436
+        return $this->groupMapper->getDNByName($name);
437
+    }
438
+
439
+    /**
440
+     * returns the LDAP DN for the given internal Nextcloud name of the user
441
+     * @param string $name the Nextcloud name in question
442
+     * @return string|false with the LDAP DN on success, otherwise false
443
+     */
444
+    public function username2dn($name) {
445
+        $fdn = $this->userMapper->getDNByName($name);
446
+
447
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
448
+        //server setups
449
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
450
+            return $fdn;
451
+        }
452
+
453
+        return false;
454
+    }
455
+
456
+    /**
457
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
458
+     * @param string $fdn the dn of the group object
459
+     * @param string $ldapName optional, the display name of the object
460
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
461
+     */
462
+    public function dn2groupname($fdn, $ldapName = null) {
463
+        //To avoid bypassing the base DN settings under certain circumstances
464
+        //with the group support, check whether the provided DN matches one of
465
+        //the given Bases
466
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
467
+            return false;
468
+        }
469
+
470
+        return $this->dn2ocname($fdn, $ldapName, false);
471
+    }
472
+
473
+    /**
474
+     * accepts an array of group DNs and tests whether they match the user
475
+     * filter by doing read operations against the group entries. Returns an
476
+     * array of DNs that match the filter.
477
+     *
478
+     * @param string[] $groupDNs
479
+     * @return string[]
480
+     * @throws ServerNotAvailableException
481
+     */
482
+    public function groupsMatchFilter($groupDNs) {
483
+        $validGroupDNs = [];
484
+        foreach($groupDNs as $dn) {
485
+            $cacheKey = 'groupsMatchFilter-'.$dn;
486
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
487
+            if(!is_null($groupMatchFilter)) {
488
+                if($groupMatchFilter) {
489
+                    $validGroupDNs[] = $dn;
490
+                }
491
+                continue;
492
+            }
493
+
494
+            // Check the base DN first. If this is not met already, we don't
495
+            // need to ask the server at all.
496
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
497
+                $this->connection->writeToCache($cacheKey, false);
498
+                continue;
499
+            }
500
+
501
+            $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
502
+            if(is_array($result)) {
503
+                $this->connection->writeToCache($cacheKey, true);
504
+                $validGroupDNs[] = $dn;
505
+            } else {
506
+                $this->connection->writeToCache($cacheKey, false);
507
+            }
508
+
509
+        }
510
+        return $validGroupDNs;
511
+    }
512
+
513
+    /**
514
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
515
+     * @param string $dn the dn of the user object
516
+     * @param string $ldapName optional, the display name of the object
517
+     * @return string|false with with the name to use in Nextcloud
518
+     */
519
+    public function dn2username($fdn, $ldapName = null) {
520
+        //To avoid bypassing the base DN settings under certain circumstances
521
+        //with the group support, check whether the provided DN matches one of
522
+        //the given Bases
523
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
524
+            return false;
525
+        }
526
+
527
+        return $this->dn2ocname($fdn, $ldapName, true);
528
+    }
529
+
530
+    /**
531
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
532
+     *
533
+     * @param string $fdn the dn of the user object
534
+     * @param string|null $ldapName optional, the display name of the object
535
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
536
+     * @param bool|null $newlyMapped
537
+     * @param array|null $record
538
+     * @return false|string with with the name to use in Nextcloud
539
+     * @throws \Exception
540
+     */
541
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
542
+        $newlyMapped = false;
543
+        if($isUser) {
544
+            $mapper = $this->getUserMapper();
545
+            $nameAttribute = $this->connection->ldapUserDisplayName;
546
+            $filter = $this->connection->ldapUserFilter;
547
+        } else {
548
+            $mapper = $this->getGroupMapper();
549
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
550
+            $filter = $this->connection->ldapGroupFilter;
551
+        }
552
+
553
+        //let's try to retrieve the Nextcloud name from the mappings table
554
+        $ncName = $mapper->getNameByDN($fdn);
555
+        if(is_string($ncName)) {
556
+            return $ncName;
557
+        }
558
+
559
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
560
+        $uuid = $this->getUUID($fdn, $isUser, $record);
561
+        if(is_string($uuid)) {
562
+            $ncName = $mapper->getNameByUUID($uuid);
563
+            if(is_string($ncName)) {
564
+                $mapper->setDNbyUUID($fdn, $uuid);
565
+                return $ncName;
566
+            }
567
+        } else {
568
+            //If the UUID can't be detected something is foul.
569
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
570
+            return false;
571
+        }
572
+
573
+        if(is_null($ldapName)) {
574
+            $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
575
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
576
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
577
+                return false;
578
+            }
579
+            $ldapName = $ldapName[0];
580
+        }
581
+
582
+        if($isUser) {
583
+            $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
584
+            if ($usernameAttribute !== '') {
585
+                $username = $this->readAttribute($fdn, $usernameAttribute);
586
+                $username = $username[0];
587
+            } else {
588
+                $username = $uuid;
589
+            }
590
+            try {
591
+                $intName = $this->sanitizeUsername($username);
592
+            } catch (\InvalidArgumentException $e) {
593
+                \OC::$server->getLogger()->logException($e, [
594
+                    'app' => 'user_ldap',
595
+                    'level' => ILogger::WARN,
596
+                ]);
597
+                // we don't attempt to set a username here. We can go for
598
+                // for an alternative 4 digit random number as we would append
599
+                // otherwise, however it's likely not enough space in bigger
600
+                // setups, and most importantly: this is not intended.
601
+                return false;
602
+            }
603
+        } else {
604
+            $intName = $ldapName;
605
+        }
606
+
607
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
608
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
609
+        //NOTE: mind, disabling cache affects only this instance! Using it
610
+        // outside of core user management will still cache the user as non-existing.
611
+        $originalTTL = $this->connection->ldapCacheTTL;
612
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
613
+        if(($isUser && $intName !== '' && !$this->ncUserManager->userExists($intName))
614
+            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
615
+            if($mapper->map($fdn, $intName, $uuid)) {
616
+                $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
617
+                if($this->ncUserManager instanceof PublicEmitter && $isUser) {
618
+                    $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$intName]);
619
+                }
620
+                $newlyMapped = true;
621
+                return $intName;
622
+            }
623
+        }
624
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
625
+
626
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
627
+        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
628
+            if($this->ncUserManager instanceof PublicEmitter && $isUser) {
629
+                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$intName]);
630
+            }
631
+            $newlyMapped = true;
632
+            return $altName;
633
+        }
634
+
635
+        //if everything else did not help..
636
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
637
+        return false;
638
+    }
639
+
640
+    /**
641
+     * gives back the user names as they are used ownClod internally
642
+     * @param array $ldapUsers as returned by fetchList()
643
+     * @return array an array with the user names to use in Nextcloud
644
+     *
645
+     * gives back the user names as they are used ownClod internally
646
+     */
647
+    public function nextcloudUserNames($ldapUsers) {
648
+        return $this->ldap2NextcloudNames($ldapUsers, true);
649
+    }
650
+
651
+    /**
652
+     * gives back the group names as they are used ownClod internally
653
+     * @param array $ldapGroups as returned by fetchList()
654
+     * @return array an array with the group names to use in Nextcloud
655
+     *
656
+     * gives back the group names as they are used ownClod internally
657
+     */
658
+    public function nextcloudGroupNames($ldapGroups) {
659
+        return $this->ldap2NextcloudNames($ldapGroups, false);
660
+    }
661
+
662
+    /**
663
+     * @param array $ldapObjects as returned by fetchList()
664
+     * @param bool $isUsers
665
+     * @return array
666
+     * @throws \Exception
667
+     */
668
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
669
+        if($isUsers) {
670
+            $nameAttribute = $this->connection->ldapUserDisplayName;
671
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
672
+        } else {
673
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
674
+        }
675
+        $nextcloudNames = [];
676
+
677
+        foreach($ldapObjects as $ldapObject) {
678
+            $nameByLDAP = null;
679
+            if(    isset($ldapObject[$nameAttribute])
680
+                && is_array($ldapObject[$nameAttribute])
681
+                && isset($ldapObject[$nameAttribute][0])
682
+            ) {
683
+                // might be set, but not necessarily. if so, we use it.
684
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
685
+            }
686
+
687
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
688
+            if($ncName) {
689
+                $nextcloudNames[] = $ncName;
690
+                if($isUsers) {
691
+                    $this->updateUserState($ncName);
692
+                    //cache the user names so it does not need to be retrieved
693
+                    //again later (e.g. sharing dialogue).
694
+                    if(is_null($nameByLDAP)) {
695
+                        continue;
696
+                    }
697
+                    $sndName = isset($ldapObject[$sndAttribute][0])
698
+                        ? $ldapObject[$sndAttribute][0] : '';
699
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
700
+                }
701
+            }
702
+        }
703
+        return $nextcloudNames;
704
+    }
705
+
706
+    /**
707
+     * removes the deleted-flag of a user if it was set
708
+     *
709
+     * @param string $ncname
710
+     * @throws \Exception
711
+     */
712
+    public function updateUserState($ncname) {
713
+        $user = $this->userManager->get($ncname);
714
+        if($user instanceof OfflineUser) {
715
+            $user->unmark();
716
+        }
717
+    }
718
+
719
+    /**
720
+     * caches the user display name
721
+     * @param string $ocName the internal Nextcloud username
722
+     * @param string|false $home the home directory path
723
+     */
724
+    public function cacheUserHome($ocName, $home) {
725
+        $cacheKey = 'getHome'.$ocName;
726
+        $this->connection->writeToCache($cacheKey, $home);
727
+    }
728
+
729
+    /**
730
+     * caches a user as existing
731
+     * @param string $ocName the internal Nextcloud username
732
+     */
733
+    public function cacheUserExists($ocName) {
734
+        $this->connection->writeToCache('userExists'.$ocName, true);
735
+    }
736
+
737
+    /**
738
+     * caches the user display name
739
+     * @param string $ocName the internal Nextcloud username
740
+     * @param string $displayName the display name
741
+     * @param string $displayName2 the second display name
742
+     */
743
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
744
+        $user = $this->userManager->get($ocName);
745
+        if($user === null) {
746
+            return;
747
+        }
748
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
749
+        $cacheKeyTrunk = 'getDisplayName';
750
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
751
+    }
752
+
753
+    /**
754
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
755
+     * @param string $name the display name of the object
756
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
757
+     *
758
+     * Instead of using this method directly, call
759
+     * createAltInternalOwnCloudName($name, true)
760
+     */
761
+    private function _createAltInternalOwnCloudNameForUsers($name) {
762
+        $attempts = 0;
763
+        //while loop is just a precaution. If a name is not generated within
764
+        //20 attempts, something else is very wrong. Avoids infinite loop.
765
+        while($attempts < 20){
766
+            $altName = $name . '_' . rand(1000,9999);
767
+            if(!$this->ncUserManager->userExists($altName)) {
768
+                return $altName;
769
+            }
770
+            $attempts++;
771
+        }
772
+        return false;
773
+    }
774
+
775
+    /**
776
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
777
+     * @param string $name the display name of the object
778
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
779
+     *
780
+     * Instead of using this method directly, call
781
+     * createAltInternalOwnCloudName($name, false)
782
+     *
783
+     * Group names are also used as display names, so we do a sequential
784
+     * numbering, e.g. Developers_42 when there are 41 other groups called
785
+     * "Developers"
786
+     */
787
+    private function _createAltInternalOwnCloudNameForGroups($name) {
788
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
789
+        if(!$usedNames || count($usedNames) === 0) {
790
+            $lastNo = 1; //will become name_2
791
+        } else {
792
+            natsort($usedNames);
793
+            $lastName = array_pop($usedNames);
794
+            $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
795
+        }
796
+        $altName = $name.'_'. (string)($lastNo+1);
797
+        unset($usedNames);
798
+
799
+        $attempts = 1;
800
+        while($attempts < 21){
801
+            // Check to be really sure it is unique
802
+            // while loop is just a precaution. If a name is not generated within
803
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
804
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
805
+                return $altName;
806
+            }
807
+            $altName = $name . '_' . ($lastNo + $attempts);
808
+            $attempts++;
809
+        }
810
+        return false;
811
+    }
812
+
813
+    /**
814
+     * creates a unique name for internal Nextcloud use.
815
+     * @param string $name the display name of the object
816
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
817
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
818
+     */
819
+    private function createAltInternalOwnCloudName($name, $isUser) {
820
+        $originalTTL = $this->connection->ldapCacheTTL;
821
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
822
+        if($isUser) {
823
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
824
+        } else {
825
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
826
+        }
827
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
828
+
829
+        return $altName;
830
+    }
831
+
832
+    /**
833
+     * fetches a list of users according to a provided loginName and utilizing
834
+     * the login filter.
835
+     *
836
+     * @param string $loginName
837
+     * @param array $attributes optional, list of attributes to read
838
+     * @return array
839
+     */
840
+    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
841
+        $loginName = $this->escapeFilterPart($loginName);
842
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
843
+        return $this->fetchListOfUsers($filter, $attributes);
844
+    }
845
+
846
+    /**
847
+     * counts the number of users according to a provided loginName and
848
+     * utilizing the login filter.
849
+     *
850
+     * @param string $loginName
851
+     * @return int
852
+     */
853
+    public function countUsersByLoginName($loginName) {
854
+        $loginName = $this->escapeFilterPart($loginName);
855
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
856
+        return $this->countUsers($filter);
857
+    }
858
+
859
+    /**
860
+     * @param string $filter
861
+     * @param string|string[] $attr
862
+     * @param int $limit
863
+     * @param int $offset
864
+     * @param bool $forceApplyAttributes
865
+     * @return array
866
+     */
867
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
868
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
869
+        $recordsToUpdate = $ldapRecords;
870
+        if(!$forceApplyAttributes) {
871
+            $isBackgroundJobModeAjax = $this->config
872
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
873
+            $recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
874
+                $newlyMapped = false;
875
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
876
+                if(is_string($uid)) {
877
+                    $this->cacheUserExists($uid);
878
+                }
879
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
880
+            });
881
+        }
882
+        $this->batchApplyUserAttributes($recordsToUpdate);
883
+        return $this->fetchList($ldapRecords, count($attr) > 1);
884
+    }
885
+
886
+    /**
887
+     * provided with an array of LDAP user records the method will fetch the
888
+     * user object and requests it to process the freshly fetched attributes and
889
+     * and their values
890
+     *
891
+     * @param array $ldapRecords
892
+     * @throws \Exception
893
+     */
894
+    public function batchApplyUserAttributes(array $ldapRecords){
895
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
896
+        foreach($ldapRecords as $userRecord) {
897
+            if(!isset($userRecord[$displayNameAttribute])) {
898
+                // displayName is obligatory
899
+                continue;
900
+            }
901
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
902
+            if($ocName === false) {
903
+                continue;
904
+            }
905
+            $this->updateUserState($ocName);
906
+            $user = $this->userManager->get($ocName);
907
+            if ($user !== null) {
908
+                $user->processAttributes($userRecord);
909
+            } else {
910
+                \OC::$server->getLogger()->debug(
911
+                    "The ldap user manager returned null for $ocName",
912
+                    ['app'=>'user_ldap']
913
+                );
914
+            }
915
+        }
916
+    }
917
+
918
+    /**
919
+     * @param string $filter
920
+     * @param string|string[] $attr
921
+     * @param int $limit
922
+     * @param int $offset
923
+     * @return array
924
+     */
925
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
926
+        return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), count($attr) > 1);
927
+    }
928
+
929
+    /**
930
+     * @param array $list
931
+     * @param bool $manyAttributes
932
+     * @return array
933
+     */
934
+    private function fetchList($list, $manyAttributes) {
935
+        if(is_array($list)) {
936
+            if($manyAttributes) {
937
+                return $list;
938
+            } else {
939
+                $list = array_reduce($list, function($carry, $item) {
940
+                    $attribute = array_keys($item)[0];
941
+                    $carry[] = $item[$attribute][0];
942
+                    return $carry;
943
+                }, array());
944
+                return array_unique($list, SORT_LOCALE_STRING);
945
+            }
946
+        }
947
+
948
+        //error cause actually, maybe throw an exception in future.
949
+        return array();
950
+    }
951
+
952
+    /**
953
+     * executes an LDAP search, optimized for Users
954
+     * @param string $filter the LDAP filter for the search
955
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
956
+     * @param integer $limit
957
+     * @param integer $offset
958
+     * @return array with the search result
959
+     *
960
+     * Executes an LDAP search
961
+     */
962
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
963
+        return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
964
+    }
965
+
966
+    /**
967
+     * @param string $filter
968
+     * @param string|string[] $attr
969
+     * @param int $limit
970
+     * @param int $offset
971
+     * @return false|int
972
+     */
973
+    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
974
+        return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
975
+    }
976
+
977
+    /**
978
+     * executes an LDAP search, optimized for Groups
979
+     * @param string $filter the LDAP filter for the search
980
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
981
+     * @param integer $limit
982
+     * @param integer $offset
983
+     * @return array with the search result
984
+     *
985
+     * Executes an LDAP search
986
+     */
987
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
988
+        return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
989
+    }
990
+
991
+    /**
992
+     * returns the number of available groups
993
+     * @param string $filter the LDAP search filter
994
+     * @param string[] $attr optional
995
+     * @param int|null $limit
996
+     * @param int|null $offset
997
+     * @return int|bool
998
+     */
999
+    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
1000
+        return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
1001
+    }
1002
+
1003
+    /**
1004
+     * returns the number of available objects on the base DN
1005
+     *
1006
+     * @param int|null $limit
1007
+     * @param int|null $offset
1008
+     * @return int|bool
1009
+     */
1010
+    public function countObjects($limit = null, $offset = null) {
1011
+        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
1012
+    }
1013
+
1014
+    /**
1015
+     * Returns the LDAP handler
1016
+     * @throws \OC\ServerNotAvailableException
1017
+     */
1018
+
1019
+    /**
1020
+     * @return mixed
1021
+     * @throws \OC\ServerNotAvailableException
1022
+     */
1023
+    private function invokeLDAPMethod() {
1024
+        $arguments = func_get_args();
1025
+        $command = array_shift($arguments);
1026
+        $cr = array_shift($arguments);
1027
+        if (!method_exists($this->ldap, $command)) {
1028
+            return null;
1029
+        }
1030
+        array_unshift($arguments, $cr);
1031
+        // php no longer supports call-time pass-by-reference
1032
+        // thus cannot support controlPagedResultResponse as the third argument
1033
+        // is a reference
1034
+        $doMethod = function () use ($command, &$arguments) {
1035
+            if ($command == 'controlPagedResultResponse') {
1036
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1037
+            } else {
1038
+                return call_user_func_array(array($this->ldap, $command), $arguments);
1039
+            }
1040
+        };
1041
+        try {
1042
+            $ret = $doMethod();
1043
+        } catch (ServerNotAvailableException $e) {
1044
+            /* Server connection lost, attempt to reestablish it
1045 1045
 			 * Maybe implement exponential backoff?
1046 1046
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1047 1047
 			 */
1048
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1049
-			$this->connection->resetConnectionResource();
1050
-			$cr = $this->connection->getConnectionResource();
1051
-
1052
-			if(!$this->ldap->isResource($cr)) {
1053
-				// Seems like we didn't find any resource.
1054
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1055
-				throw $e;
1056
-			}
1057
-
1058
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1059
-			$ret = $doMethod();
1060
-		}
1061
-		return $ret;
1062
-	}
1063
-
1064
-	/**
1065
-	 * retrieved. Results will according to the order in the array.
1066
-	 *
1067
-	 * @param $filter
1068
-	 * @param $base
1069
-	 * @param string[]|string|null $attr
1070
-	 * @param int $limit optional, maximum results to be counted
1071
-	 * @param int $offset optional, a starting point
1072
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1073
-	 * second | false if not successful
1074
-	 * @throws ServerNotAvailableException
1075
-	 */
1076
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1077
-		if(!is_null($attr) && !is_array($attr)) {
1078
-			$attr = array(mb_strtolower($attr, 'UTF-8'));
1079
-		}
1080
-
1081
-		// See if we have a resource, in case not cancel with message
1082
-		$cr = $this->connection->getConnectionResource();
1083
-		if(!$this->ldap->isResource($cr)) {
1084
-			// Seems like we didn't find any resource.
1085
-			// Return an empty array just like before.
1086
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1087
-			return false;
1088
-		}
1089
-
1090
-		//check whether paged search should be attempted
1091
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1092
-
1093
-		$linkResources = array_pad(array(), count($base), $cr);
1094
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1095
-		// cannot use $cr anymore, might have changed in the previous call!
1096
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1097
-		if(!is_array($sr) || $error !== 0) {
1098
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1099
-			return false;
1100
-		}
1101
-
1102
-		return array($sr, $pagedSearchOK);
1103
-	}
1104
-
1105
-	/**
1106
-	 * processes an LDAP paged search operation
1107
-	 * @param array $sr the array containing the LDAP search resources
1108
-	 * @param string $filter the LDAP filter for the search
1109
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1110
-	 * @param int $iFoundItems number of results in the single search operation
1111
-	 * @param int $limit maximum results to be counted
1112
-	 * @param int $offset a starting point
1113
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1114
-	 * @param bool $skipHandling required for paged search when cookies to
1115
-	 * prior results need to be gained
1116
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1117
-	 */
1118
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1119
-		$cookie = null;
1120
-		if($pagedSearchOK) {
1121
-			$cr = $this->connection->getConnectionResource();
1122
-			foreach($sr as $key => $res) {
1123
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1124
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1125
-				}
1126
-			}
1127
-
1128
-			//browsing through prior pages to get the cookie for the new one
1129
-			if($skipHandling) {
1130
-				return false;
1131
-			}
1132
-			// if count is bigger, then the server does not support
1133
-			// paged search. Instead, he did a normal search. We set a
1134
-			// flag here, so the callee knows how to deal with it.
1135
-			if($iFoundItems <= $limit) {
1136
-				$this->pagedSearchedSuccessful = true;
1137
-			}
1138
-		} else {
1139
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1140
-				\OC::$server->getLogger()->debug(
1141
-					'Paged search was not available',
1142
-					[ 'app' => 'user_ldap' ]
1143
-				);
1144
-			}
1145
-		}
1146
-		/* ++ Fixing RHDS searches with pages with zero results ++
1048
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1049
+            $this->connection->resetConnectionResource();
1050
+            $cr = $this->connection->getConnectionResource();
1051
+
1052
+            if(!$this->ldap->isResource($cr)) {
1053
+                // Seems like we didn't find any resource.
1054
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1055
+                throw $e;
1056
+            }
1057
+
1058
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1059
+            $ret = $doMethod();
1060
+        }
1061
+        return $ret;
1062
+    }
1063
+
1064
+    /**
1065
+     * retrieved. Results will according to the order in the array.
1066
+     *
1067
+     * @param $filter
1068
+     * @param $base
1069
+     * @param string[]|string|null $attr
1070
+     * @param int $limit optional, maximum results to be counted
1071
+     * @param int $offset optional, a starting point
1072
+     * @return array|false array with the search result as first value and pagedSearchOK as
1073
+     * second | false if not successful
1074
+     * @throws ServerNotAvailableException
1075
+     */
1076
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1077
+        if(!is_null($attr) && !is_array($attr)) {
1078
+            $attr = array(mb_strtolower($attr, 'UTF-8'));
1079
+        }
1080
+
1081
+        // See if we have a resource, in case not cancel with message
1082
+        $cr = $this->connection->getConnectionResource();
1083
+        if(!$this->ldap->isResource($cr)) {
1084
+            // Seems like we didn't find any resource.
1085
+            // Return an empty array just like before.
1086
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1087
+            return false;
1088
+        }
1089
+
1090
+        //check whether paged search should be attempted
1091
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1092
+
1093
+        $linkResources = array_pad(array(), count($base), $cr);
1094
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1095
+        // cannot use $cr anymore, might have changed in the previous call!
1096
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1097
+        if(!is_array($sr) || $error !== 0) {
1098
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1099
+            return false;
1100
+        }
1101
+
1102
+        return array($sr, $pagedSearchOK);
1103
+    }
1104
+
1105
+    /**
1106
+     * processes an LDAP paged search operation
1107
+     * @param array $sr the array containing the LDAP search resources
1108
+     * @param string $filter the LDAP filter for the search
1109
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1110
+     * @param int $iFoundItems number of results in the single search operation
1111
+     * @param int $limit maximum results to be counted
1112
+     * @param int $offset a starting point
1113
+     * @param bool $pagedSearchOK whether a paged search has been executed
1114
+     * @param bool $skipHandling required for paged search when cookies to
1115
+     * prior results need to be gained
1116
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1117
+     */
1118
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1119
+        $cookie = null;
1120
+        if($pagedSearchOK) {
1121
+            $cr = $this->connection->getConnectionResource();
1122
+            foreach($sr as $key => $res) {
1123
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1124
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1125
+                }
1126
+            }
1127
+
1128
+            //browsing through prior pages to get the cookie for the new one
1129
+            if($skipHandling) {
1130
+                return false;
1131
+            }
1132
+            // if count is bigger, then the server does not support
1133
+            // paged search. Instead, he did a normal search. We set a
1134
+            // flag here, so the callee knows how to deal with it.
1135
+            if($iFoundItems <= $limit) {
1136
+                $this->pagedSearchedSuccessful = true;
1137
+            }
1138
+        } else {
1139
+            if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1140
+                \OC::$server->getLogger()->debug(
1141
+                    'Paged search was not available',
1142
+                    [ 'app' => 'user_ldap' ]
1143
+                );
1144
+            }
1145
+        }
1146
+        /* ++ Fixing RHDS searches with pages with zero results ++
1147 1147
 		 * Return cookie status. If we don't have more pages, with RHDS
1148 1148
 		 * cookie is null, with openldap cookie is an empty string and
1149 1149
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1150 1150
 		 */
1151
-		return !empty($cookie) || $cookie === '0';
1152
-	}
1153
-
1154
-	/**
1155
-	 * executes an LDAP search, but counts the results only
1156
-	 *
1157
-	 * @param string $filter the LDAP filter for the search
1158
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1159
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1160
-	 * retrieved. Results will according to the order in the array.
1161
-	 * @param int $limit optional, maximum results to be counted
1162
-	 * @param int $offset optional, a starting point
1163
-	 * @param bool $skipHandling indicates whether the pages search operation is
1164
-	 * completed
1165
-	 * @return int|false Integer or false if the search could not be initialized
1166
-	 * @throws ServerNotAvailableException
1167
-	 */
1168
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1169
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1170
-
1171
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1172
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1173
-			$limitPerPage = $limit;
1174
-		}
1175
-
1176
-		$counter = 0;
1177
-		$count = null;
1178
-		$this->connection->getConnectionResource();
1179
-
1180
-		do {
1181
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1182
-			if($search === false) {
1183
-				return $counter > 0 ? $counter : false;
1184
-			}
1185
-			list($sr, $pagedSearchOK) = $search;
1186
-
1187
-			/* ++ Fixing RHDS searches with pages with zero results ++
1151
+        return !empty($cookie) || $cookie === '0';
1152
+    }
1153
+
1154
+    /**
1155
+     * executes an LDAP search, but counts the results only
1156
+     *
1157
+     * @param string $filter the LDAP filter for the search
1158
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1159
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1160
+     * retrieved. Results will according to the order in the array.
1161
+     * @param int $limit optional, maximum results to be counted
1162
+     * @param int $offset optional, a starting point
1163
+     * @param bool $skipHandling indicates whether the pages search operation is
1164
+     * completed
1165
+     * @return int|false Integer or false if the search could not be initialized
1166
+     * @throws ServerNotAvailableException
1167
+     */
1168
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1169
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1170
+
1171
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1172
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1173
+            $limitPerPage = $limit;
1174
+        }
1175
+
1176
+        $counter = 0;
1177
+        $count = null;
1178
+        $this->connection->getConnectionResource();
1179
+
1180
+        do {
1181
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1182
+            if($search === false) {
1183
+                return $counter > 0 ? $counter : false;
1184
+            }
1185
+            list($sr, $pagedSearchOK) = $search;
1186
+
1187
+            /* ++ Fixing RHDS searches with pages with zero results ++
1188 1188
 			 * countEntriesInSearchResults() method signature changed
1189 1189
 			 * by removing $limit and &$hasHitLimit parameters
1190 1190
 			 */
1191
-			$count = $this->countEntriesInSearchResults($sr);
1192
-			$counter += $count;
1191
+            $count = $this->countEntriesInSearchResults($sr);
1192
+            $counter += $count;
1193 1193
 
1194
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1195
-										$offset, $pagedSearchOK, $skipHandling);
1196
-			$offset += $limitPerPage;
1197
-			/* ++ Fixing RHDS searches with pages with zero results ++
1194
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1195
+                                        $offset, $pagedSearchOK, $skipHandling);
1196
+            $offset += $limitPerPage;
1197
+            /* ++ Fixing RHDS searches with pages with zero results ++
1198 1198
 			 * Continue now depends on $hasMorePages value
1199 1199
 			 */
1200
-			$continue = $pagedSearchOK && $hasMorePages;
1201
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1202
-
1203
-		return $counter;
1204
-	}
1205
-
1206
-	/**
1207
-	 * @param array $searchResults
1208
-	 * @return int
1209
-	 */
1210
-	private function countEntriesInSearchResults($searchResults) {
1211
-		$counter = 0;
1212
-
1213
-		foreach($searchResults as $res) {
1214
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1215
-			$counter += $count;
1216
-		}
1217
-
1218
-		return $counter;
1219
-	}
1220
-
1221
-	/**
1222
-	 * Executes an LDAP search
1223
-	 *
1224
-	 * @param string $filter the LDAP filter for the search
1225
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1226
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1227
-	 * @param int $limit
1228
-	 * @param int $offset
1229
-	 * @param bool $skipHandling
1230
-	 * @return array with the search result
1231
-	 * @throws ServerNotAvailableException
1232
-	 */
1233
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1234
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1235
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1236
-			$limitPerPage = $limit;
1237
-		}
1238
-
1239
-		/* ++ Fixing RHDS searches with pages with zero results ++
1200
+            $continue = $pagedSearchOK && $hasMorePages;
1201
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1202
+
1203
+        return $counter;
1204
+    }
1205
+
1206
+    /**
1207
+     * @param array $searchResults
1208
+     * @return int
1209
+     */
1210
+    private function countEntriesInSearchResults($searchResults) {
1211
+        $counter = 0;
1212
+
1213
+        foreach($searchResults as $res) {
1214
+            $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1215
+            $counter += $count;
1216
+        }
1217
+
1218
+        return $counter;
1219
+    }
1220
+
1221
+    /**
1222
+     * Executes an LDAP search
1223
+     *
1224
+     * @param string $filter the LDAP filter for the search
1225
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1226
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1227
+     * @param int $limit
1228
+     * @param int $offset
1229
+     * @param bool $skipHandling
1230
+     * @return array with the search result
1231
+     * @throws ServerNotAvailableException
1232
+     */
1233
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1234
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1235
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1236
+            $limitPerPage = $limit;
1237
+        }
1238
+
1239
+        /* ++ Fixing RHDS searches with pages with zero results ++
1240 1240
 		 * As we can have pages with zero results and/or pages with less
1241 1241
 		 * than $limit results but with a still valid server 'cookie',
1242 1242
 		 * loops through until we get $continue equals true and
1243 1243
 		 * $findings['count'] < $limit
1244 1244
 		 */
1245
-		$findings = [];
1246
-		$savedoffset = $offset;
1247
-		do {
1248
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1249
-			if($search === false) {
1250
-				return [];
1251
-			}
1252
-			list($sr, $pagedSearchOK) = $search;
1253
-			$cr = $this->connection->getConnectionResource();
1254
-
1255
-			if($skipHandling) {
1256
-				//i.e. result do not need to be fetched, we just need the cookie
1257
-				//thus pass 1 or any other value as $iFoundItems because it is not
1258
-				//used
1259
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1260
-								$offset, $pagedSearchOK,
1261
-								$skipHandling);
1262
-				return array();
1263
-			}
1264
-
1265
-			$iFoundItems = 0;
1266
-			foreach($sr as $res) {
1267
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1268
-				$iFoundItems = max($iFoundItems, $findings['count']);
1269
-				unset($findings['count']);
1270
-			}
1271
-
1272
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1273
-				$limitPerPage, $offset, $pagedSearchOK,
1274
-										$skipHandling);
1275
-			$offset += $limitPerPage;
1276
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1277
-		// reseting offset
1278
-		$offset = $savedoffset;
1279
-
1280
-		// if we're here, probably no connection resource is returned.
1281
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1282
-		if(is_null($findings)) {
1283
-			return array();
1284
-		}
1285
-
1286
-		if(!is_null($attr)) {
1287
-			$selection = [];
1288
-			$i = 0;
1289
-			foreach($findings as $item) {
1290
-				if(!is_array($item)) {
1291
-					continue;
1292
-				}
1293
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1294
-				foreach($attr as $key) {
1295
-					if(isset($item[$key])) {
1296
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1297
-							unset($item[$key]['count']);
1298
-						}
1299
-						if($key !== 'dn') {
1300
-							if($this->resemblesDN($key)) {
1301
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1302
-							} else if($key === 'objectguid' || $key === 'guid') {
1303
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1304
-							} else {
1305
-								$selection[$i][$key] = $item[$key];
1306
-							}
1307
-						} else {
1308
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1309
-						}
1310
-					}
1311
-
1312
-				}
1313
-				$i++;
1314
-			}
1315
-			$findings = $selection;
1316
-		}
1317
-		//we slice the findings, when
1318
-		//a) paged search unsuccessful, though attempted
1319
-		//b) no paged search, but limit set
1320
-		if((!$this->getPagedSearchResultState()
1321
-			&& $pagedSearchOK)
1322
-			|| (
1323
-				!$pagedSearchOK
1324
-				&& !is_null($limit)
1325
-			)
1326
-		) {
1327
-			$findings = array_slice($findings, (int)$offset, $limit);
1328
-		}
1329
-		return $findings;
1330
-	}
1331
-
1332
-	/**
1333
-	 * @param string $name
1334
-	 * @return string
1335
-	 * @throws \InvalidArgumentException
1336
-	 */
1337
-	public function sanitizeUsername($name) {
1338
-		$name = trim($name);
1339
-
1340
-		if($this->connection->ldapIgnoreNamingRules) {
1341
-			return $name;
1342
-		}
1343
-
1344
-		// Transliteration to ASCII
1345
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1346
-		if($transliterated !== false) {
1347
-			// depending on system config iconv can work or not
1348
-			$name = $transliterated;
1349
-		}
1350
-
1351
-		// Replacements
1352
-		$name = str_replace(' ', '_', $name);
1353
-
1354
-		// Every remaining disallowed characters will be removed
1355
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1356
-
1357
-		if($name === '') {
1358
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1359
-		}
1360
-
1361
-		return $name;
1362
-	}
1363
-
1364
-	/**
1365
-	* escapes (user provided) parts for LDAP filter
1366
-	* @param string $input, the provided value
1367
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1368
-	* @return string the escaped string
1369
-	*/
1370
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1371
-		$asterisk = '';
1372
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1373
-			$asterisk = '*';
1374
-			$input = mb_substr($input, 1, null, 'UTF-8');
1375
-		}
1376
-		$search  = array('*', '\\', '(', ')');
1377
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1378
-		return $asterisk . str_replace($search, $replace, $input);
1379
-	}
1380
-
1381
-	/**
1382
-	 * combines the input filters with AND
1383
-	 * @param string[] $filters the filters to connect
1384
-	 * @return string the combined filter
1385
-	 */
1386
-	public function combineFilterWithAnd($filters) {
1387
-		return $this->combineFilter($filters, '&');
1388
-	}
1389
-
1390
-	/**
1391
-	 * combines the input filters with OR
1392
-	 * @param string[] $filters the filters to connect
1393
-	 * @return string the combined filter
1394
-	 * Combines Filter arguments with OR
1395
-	 */
1396
-	public function combineFilterWithOr($filters) {
1397
-		return $this->combineFilter($filters, '|');
1398
-	}
1399
-
1400
-	/**
1401
-	 * combines the input filters with given operator
1402
-	 * @param string[] $filters the filters to connect
1403
-	 * @param string $operator either & or |
1404
-	 * @return string the combined filter
1405
-	 */
1406
-	private function combineFilter($filters, $operator) {
1407
-		$combinedFilter = '('.$operator;
1408
-		foreach($filters as $filter) {
1409
-			if ($filter !== '' && $filter[0] !== '(') {
1410
-				$filter = '('.$filter.')';
1411
-			}
1412
-			$combinedFilter.=$filter;
1413
-		}
1414
-		$combinedFilter.=')';
1415
-		return $combinedFilter;
1416
-	}
1417
-
1418
-	/**
1419
-	 * creates a filter part for to perform search for users
1420
-	 * @param string $search the search term
1421
-	 * @return string the final filter part to use in LDAP searches
1422
-	 */
1423
-	public function getFilterPartForUserSearch($search) {
1424
-		return $this->getFilterPartForSearch($search,
1425
-			$this->connection->ldapAttributesForUserSearch,
1426
-			$this->connection->ldapUserDisplayName);
1427
-	}
1428
-
1429
-	/**
1430
-	 * creates a filter part for to perform search for groups
1431
-	 * @param string $search the search term
1432
-	 * @return string the final filter part to use in LDAP searches
1433
-	 */
1434
-	public function getFilterPartForGroupSearch($search) {
1435
-		return $this->getFilterPartForSearch($search,
1436
-			$this->connection->ldapAttributesForGroupSearch,
1437
-			$this->connection->ldapGroupDisplayName);
1438
-	}
1439
-
1440
-	/**
1441
-	 * creates a filter part for searches by splitting up the given search
1442
-	 * string into single words
1443
-	 * @param string $search the search term
1444
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1445
-	 * otherwise it does not make sense :)
1446
-	 * @return string the final filter part to use in LDAP searches
1447
-	 * @throws \Exception
1448
-	 */
1449
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1450
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1451
-			throw new \Exception('searchAttributes must be an array with at least two string');
1452
-		}
1453
-		$searchWords = explode(' ', trim($search));
1454
-		$wordFilters = array();
1455
-		foreach($searchWords as $word) {
1456
-			$word = $this->prepareSearchTerm($word);
1457
-			//every word needs to appear at least once
1458
-			$wordMatchOneAttrFilters = array();
1459
-			foreach($searchAttributes as $attr) {
1460
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1461
-			}
1462
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1463
-		}
1464
-		return $this->combineFilterWithAnd($wordFilters);
1465
-	}
1466
-
1467
-	/**
1468
-	 * creates a filter part for searches
1469
-	 * @param string $search the search term
1470
-	 * @param string[]|null $searchAttributes
1471
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1472
-	 * did not define search attributes. Typically the display name attribute.
1473
-	 * @return string the final filter part to use in LDAP searches
1474
-	 */
1475
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1476
-		$filter = array();
1477
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1478
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1479
-			try {
1480
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1481
-			} catch(\Exception $e) {
1482
-				\OCP\Util::writeLog(
1483
-					'user_ldap',
1484
-					'Creating advanced filter for search failed, falling back to simple method.',
1485
-					ILogger::INFO
1486
-				);
1487
-			}
1488
-		}
1489
-
1490
-		$search = $this->prepareSearchTerm($search);
1491
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1492
-			if ($fallbackAttribute === '') {
1493
-				return '';
1494
-			}
1495
-			$filter[] = $fallbackAttribute . '=' . $search;
1496
-		} else {
1497
-			foreach($searchAttributes as $attribute) {
1498
-				$filter[] = $attribute . '=' . $search;
1499
-			}
1500
-		}
1501
-		if(count($filter) === 1) {
1502
-			return '('.$filter[0].')';
1503
-		}
1504
-		return $this->combineFilterWithOr($filter);
1505
-	}
1506
-
1507
-	/**
1508
-	 * returns the search term depending on whether we are allowed
1509
-	 * list users found by ldap with the current input appended by
1510
-	 * a *
1511
-	 * @return string
1512
-	 */
1513
-	private function prepareSearchTerm($term) {
1514
-		$config = \OC::$server->getConfig();
1515
-
1516
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1517
-
1518
-		$result = $term;
1519
-		if ($term === '') {
1520
-			$result = '*';
1521
-		} else if ($allowEnum !== 'no') {
1522
-			$result = $term . '*';
1523
-		}
1524
-		return $result;
1525
-	}
1526
-
1527
-	/**
1528
-	 * returns the filter used for counting users
1529
-	 * @return string
1530
-	 */
1531
-	public function getFilterForUserCount() {
1532
-		$filter = $this->combineFilterWithAnd(array(
1533
-			$this->connection->ldapUserFilter,
1534
-			$this->connection->ldapUserDisplayName . '=*'
1535
-		));
1536
-
1537
-		return $filter;
1538
-	}
1539
-
1540
-	/**
1541
-	 * @param string $name
1542
-	 * @param string $password
1543
-	 * @return bool
1544
-	 */
1545
-	public function areCredentialsValid($name, $password) {
1546
-		$name = $this->helper->DNasBaseParameter($name);
1547
-		$testConnection = clone $this->connection;
1548
-		$credentials = array(
1549
-			'ldapAgentName' => $name,
1550
-			'ldapAgentPassword' => $password
1551
-		);
1552
-		if(!$testConnection->setConfiguration($credentials)) {
1553
-			return false;
1554
-		}
1555
-		return $testConnection->bind();
1556
-	}
1557
-
1558
-	/**
1559
-	 * reverse lookup of a DN given a known UUID
1560
-	 *
1561
-	 * @param string $uuid
1562
-	 * @return string
1563
-	 * @throws \Exception
1564
-	 */
1565
-	public function getUserDnByUuid($uuid) {
1566
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1567
-		$filter       = $this->connection->ldapUserFilter;
1568
-		$base         = $this->connection->ldapBaseUsers;
1569
-
1570
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1571
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1572
-			// existing DN to be able to reliably detect it.
1573
-			$result = $this->search($filter, $base, ['dn'], 1);
1574
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1575
-				throw new \Exception('Cannot determine UUID attribute');
1576
-			}
1577
-			$dn = $result[0]['dn'][0];
1578
-			if(!$this->detectUuidAttribute($dn, true)) {
1579
-				throw new \Exception('Cannot determine UUID attribute');
1580
-			}
1581
-		} else {
1582
-			// The UUID attribute is either known or an override is given.
1583
-			// By calling this method we ensure that $this->connection->$uuidAttr
1584
-			// is definitely set
1585
-			if(!$this->detectUuidAttribute('', true)) {
1586
-				throw new \Exception('Cannot determine UUID attribute');
1587
-			}
1588
-		}
1589
-
1590
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1591
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1592
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1593
-		}
1594
-
1595
-		$filter = $uuidAttr . '=' . $uuid;
1596
-		$result = $this->searchUsers($filter, ['dn'], 2);
1597
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1598
-			// we put the count into account to make sure that this is
1599
-			// really unique
1600
-			return $result[0]['dn'][0];
1601
-		}
1602
-
1603
-		throw new \Exception('Cannot determine UUID attribute');
1604
-	}
1605
-
1606
-	/**
1607
-	 * auto-detects the directory's UUID attribute
1608
-	 *
1609
-	 * @param string $dn a known DN used to check against
1610
-	 * @param bool $isUser
1611
-	 * @param bool $force the detection should be run, even if it is not set to auto
1612
-	 * @param array|null $ldapRecord
1613
-	 * @return bool true on success, false otherwise
1614
-	 */
1615
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1616
-		if($isUser) {
1617
-			$uuidAttr     = 'ldapUuidUserAttribute';
1618
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1619
-		} else {
1620
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1621
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1622
-		}
1623
-
1624
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1625
-			return true;
1626
-		}
1627
-
1628
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1629
-			$this->connection->$uuidAttr = $uuidOverride;
1630
-			return true;
1631
-		}
1632
-
1633
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1634
-			if($ldapRecord !== null) {
1635
-				// we have the info from LDAP already, we don't need to talk to the server again
1636
-				if(isset($ldapRecord[$attribute])) {
1637
-					$this->connection->$uuidAttr = $attribute;
1638
-					return true;
1639
-				} else {
1640
-					continue;
1641
-				}
1642
-			}
1643
-
1644
-			$value = $this->readAttribute($dn, $attribute);
1645
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1646
-				\OCP\Util::writeLog(
1647
-					'user_ldap',
1648
-					'Setting '.$attribute.' as '.$uuidAttr,
1649
-					ILogger::DEBUG
1650
-				);
1651
-				$this->connection->$uuidAttr = $attribute;
1652
-				return true;
1653
-			}
1654
-		}
1655
-		\OCP\Util::writeLog(
1656
-			'user_ldap',
1657
-			'Could not autodetect the UUID attribute',
1658
-			ILogger::ERROR
1659
-		);
1660
-
1661
-		return false;
1662
-	}
1663
-
1664
-	/**
1665
-	 * @param string $dn
1666
-	 * @param bool $isUser
1667
-	 * @param null $ldapRecord
1668
-	 * @return bool|string
1669
-	 */
1670
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1671
-		if($isUser) {
1672
-			$uuidAttr     = 'ldapUuidUserAttribute';
1673
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1674
-		} else {
1675
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1676
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1677
-		}
1678
-
1679
-		$uuid = false;
1680
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1681
-			$attr = $this->connection->$uuidAttr;
1682
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1683
-			if( !is_array($uuid)
1684
-				&& $uuidOverride !== ''
1685
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1686
-			{
1687
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1688
-					? $ldapRecord[$this->connection->$uuidAttr]
1689
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1690
-			}
1691
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1692
-				$uuid = $uuid[0];
1693
-			}
1694
-		}
1695
-
1696
-		return $uuid;
1697
-	}
1698
-
1699
-	/**
1700
-	 * converts a binary ObjectGUID into a string representation
1701
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1702
-	 * @return string
1703
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1704
-	 */
1705
-	private function convertObjectGUID2Str($oguid) {
1706
-		$hex_guid = bin2hex($oguid);
1707
-		$hex_guid_to_guid_str = '';
1708
-		for($k = 1; $k <= 4; ++$k) {
1709
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1710
-		}
1711
-		$hex_guid_to_guid_str .= '-';
1712
-		for($k = 1; $k <= 2; ++$k) {
1713
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1714
-		}
1715
-		$hex_guid_to_guid_str .= '-';
1716
-		for($k = 1; $k <= 2; ++$k) {
1717
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1718
-		}
1719
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1720
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1721
-
1722
-		return strtoupper($hex_guid_to_guid_str);
1723
-	}
1724
-
1725
-	/**
1726
-	 * the first three blocks of the string-converted GUID happen to be in
1727
-	 * reverse order. In order to use it in a filter, this needs to be
1728
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1729
-	 * to every two hax figures.
1730
-	 *
1731
-	 * If an invalid string is passed, it will be returned without change.
1732
-	 *
1733
-	 * @param string $guid
1734
-	 * @return string
1735
-	 */
1736
-	public function formatGuid2ForFilterUser($guid) {
1737
-		if(!is_string($guid)) {
1738
-			throw new \InvalidArgumentException('String expected');
1739
-		}
1740
-		$blocks = explode('-', $guid);
1741
-		if(count($blocks) !== 5) {
1742
-			/*
1245
+        $findings = [];
1246
+        $savedoffset = $offset;
1247
+        do {
1248
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1249
+            if($search === false) {
1250
+                return [];
1251
+            }
1252
+            list($sr, $pagedSearchOK) = $search;
1253
+            $cr = $this->connection->getConnectionResource();
1254
+
1255
+            if($skipHandling) {
1256
+                //i.e. result do not need to be fetched, we just need the cookie
1257
+                //thus pass 1 or any other value as $iFoundItems because it is not
1258
+                //used
1259
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1260
+                                $offset, $pagedSearchOK,
1261
+                                $skipHandling);
1262
+                return array();
1263
+            }
1264
+
1265
+            $iFoundItems = 0;
1266
+            foreach($sr as $res) {
1267
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1268
+                $iFoundItems = max($iFoundItems, $findings['count']);
1269
+                unset($findings['count']);
1270
+            }
1271
+
1272
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1273
+                $limitPerPage, $offset, $pagedSearchOK,
1274
+                                        $skipHandling);
1275
+            $offset += $limitPerPage;
1276
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1277
+        // reseting offset
1278
+        $offset = $savedoffset;
1279
+
1280
+        // if we're here, probably no connection resource is returned.
1281
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1282
+        if(is_null($findings)) {
1283
+            return array();
1284
+        }
1285
+
1286
+        if(!is_null($attr)) {
1287
+            $selection = [];
1288
+            $i = 0;
1289
+            foreach($findings as $item) {
1290
+                if(!is_array($item)) {
1291
+                    continue;
1292
+                }
1293
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1294
+                foreach($attr as $key) {
1295
+                    if(isset($item[$key])) {
1296
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1297
+                            unset($item[$key]['count']);
1298
+                        }
1299
+                        if($key !== 'dn') {
1300
+                            if($this->resemblesDN($key)) {
1301
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1302
+                            } else if($key === 'objectguid' || $key === 'guid') {
1303
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1304
+                            } else {
1305
+                                $selection[$i][$key] = $item[$key];
1306
+                            }
1307
+                        } else {
1308
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1309
+                        }
1310
+                    }
1311
+
1312
+                }
1313
+                $i++;
1314
+            }
1315
+            $findings = $selection;
1316
+        }
1317
+        //we slice the findings, when
1318
+        //a) paged search unsuccessful, though attempted
1319
+        //b) no paged search, but limit set
1320
+        if((!$this->getPagedSearchResultState()
1321
+            && $pagedSearchOK)
1322
+            || (
1323
+                !$pagedSearchOK
1324
+                && !is_null($limit)
1325
+            )
1326
+        ) {
1327
+            $findings = array_slice($findings, (int)$offset, $limit);
1328
+        }
1329
+        return $findings;
1330
+    }
1331
+
1332
+    /**
1333
+     * @param string $name
1334
+     * @return string
1335
+     * @throws \InvalidArgumentException
1336
+     */
1337
+    public function sanitizeUsername($name) {
1338
+        $name = trim($name);
1339
+
1340
+        if($this->connection->ldapIgnoreNamingRules) {
1341
+            return $name;
1342
+        }
1343
+
1344
+        // Transliteration to ASCII
1345
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1346
+        if($transliterated !== false) {
1347
+            // depending on system config iconv can work or not
1348
+            $name = $transliterated;
1349
+        }
1350
+
1351
+        // Replacements
1352
+        $name = str_replace(' ', '_', $name);
1353
+
1354
+        // Every remaining disallowed characters will be removed
1355
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1356
+
1357
+        if($name === '') {
1358
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1359
+        }
1360
+
1361
+        return $name;
1362
+    }
1363
+
1364
+    /**
1365
+     * escapes (user provided) parts for LDAP filter
1366
+     * @param string $input, the provided value
1367
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1368
+     * @return string the escaped string
1369
+     */
1370
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1371
+        $asterisk = '';
1372
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1373
+            $asterisk = '*';
1374
+            $input = mb_substr($input, 1, null, 'UTF-8');
1375
+        }
1376
+        $search  = array('*', '\\', '(', ')');
1377
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1378
+        return $asterisk . str_replace($search, $replace, $input);
1379
+    }
1380
+
1381
+    /**
1382
+     * combines the input filters with AND
1383
+     * @param string[] $filters the filters to connect
1384
+     * @return string the combined filter
1385
+     */
1386
+    public function combineFilterWithAnd($filters) {
1387
+        return $this->combineFilter($filters, '&');
1388
+    }
1389
+
1390
+    /**
1391
+     * combines the input filters with OR
1392
+     * @param string[] $filters the filters to connect
1393
+     * @return string the combined filter
1394
+     * Combines Filter arguments with OR
1395
+     */
1396
+    public function combineFilterWithOr($filters) {
1397
+        return $this->combineFilter($filters, '|');
1398
+    }
1399
+
1400
+    /**
1401
+     * combines the input filters with given operator
1402
+     * @param string[] $filters the filters to connect
1403
+     * @param string $operator either & or |
1404
+     * @return string the combined filter
1405
+     */
1406
+    private function combineFilter($filters, $operator) {
1407
+        $combinedFilter = '('.$operator;
1408
+        foreach($filters as $filter) {
1409
+            if ($filter !== '' && $filter[0] !== '(') {
1410
+                $filter = '('.$filter.')';
1411
+            }
1412
+            $combinedFilter.=$filter;
1413
+        }
1414
+        $combinedFilter.=')';
1415
+        return $combinedFilter;
1416
+    }
1417
+
1418
+    /**
1419
+     * creates a filter part for to perform search for users
1420
+     * @param string $search the search term
1421
+     * @return string the final filter part to use in LDAP searches
1422
+     */
1423
+    public function getFilterPartForUserSearch($search) {
1424
+        return $this->getFilterPartForSearch($search,
1425
+            $this->connection->ldapAttributesForUserSearch,
1426
+            $this->connection->ldapUserDisplayName);
1427
+    }
1428
+
1429
+    /**
1430
+     * creates a filter part for to perform search for groups
1431
+     * @param string $search the search term
1432
+     * @return string the final filter part to use in LDAP searches
1433
+     */
1434
+    public function getFilterPartForGroupSearch($search) {
1435
+        return $this->getFilterPartForSearch($search,
1436
+            $this->connection->ldapAttributesForGroupSearch,
1437
+            $this->connection->ldapGroupDisplayName);
1438
+    }
1439
+
1440
+    /**
1441
+     * creates a filter part for searches by splitting up the given search
1442
+     * string into single words
1443
+     * @param string $search the search term
1444
+     * @param string[] $searchAttributes needs to have at least two attributes,
1445
+     * otherwise it does not make sense :)
1446
+     * @return string the final filter part to use in LDAP searches
1447
+     * @throws \Exception
1448
+     */
1449
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1450
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1451
+            throw new \Exception('searchAttributes must be an array with at least two string');
1452
+        }
1453
+        $searchWords = explode(' ', trim($search));
1454
+        $wordFilters = array();
1455
+        foreach($searchWords as $word) {
1456
+            $word = $this->prepareSearchTerm($word);
1457
+            //every word needs to appear at least once
1458
+            $wordMatchOneAttrFilters = array();
1459
+            foreach($searchAttributes as $attr) {
1460
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1461
+            }
1462
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1463
+        }
1464
+        return $this->combineFilterWithAnd($wordFilters);
1465
+    }
1466
+
1467
+    /**
1468
+     * creates a filter part for searches
1469
+     * @param string $search the search term
1470
+     * @param string[]|null $searchAttributes
1471
+     * @param string $fallbackAttribute a fallback attribute in case the user
1472
+     * did not define search attributes. Typically the display name attribute.
1473
+     * @return string the final filter part to use in LDAP searches
1474
+     */
1475
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1476
+        $filter = array();
1477
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1478
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1479
+            try {
1480
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1481
+            } catch(\Exception $e) {
1482
+                \OCP\Util::writeLog(
1483
+                    'user_ldap',
1484
+                    'Creating advanced filter for search failed, falling back to simple method.',
1485
+                    ILogger::INFO
1486
+                );
1487
+            }
1488
+        }
1489
+
1490
+        $search = $this->prepareSearchTerm($search);
1491
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1492
+            if ($fallbackAttribute === '') {
1493
+                return '';
1494
+            }
1495
+            $filter[] = $fallbackAttribute . '=' . $search;
1496
+        } else {
1497
+            foreach($searchAttributes as $attribute) {
1498
+                $filter[] = $attribute . '=' . $search;
1499
+            }
1500
+        }
1501
+        if(count($filter) === 1) {
1502
+            return '('.$filter[0].')';
1503
+        }
1504
+        return $this->combineFilterWithOr($filter);
1505
+    }
1506
+
1507
+    /**
1508
+     * returns the search term depending on whether we are allowed
1509
+     * list users found by ldap with the current input appended by
1510
+     * a *
1511
+     * @return string
1512
+     */
1513
+    private function prepareSearchTerm($term) {
1514
+        $config = \OC::$server->getConfig();
1515
+
1516
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1517
+
1518
+        $result = $term;
1519
+        if ($term === '') {
1520
+            $result = '*';
1521
+        } else if ($allowEnum !== 'no') {
1522
+            $result = $term . '*';
1523
+        }
1524
+        return $result;
1525
+    }
1526
+
1527
+    /**
1528
+     * returns the filter used for counting users
1529
+     * @return string
1530
+     */
1531
+    public function getFilterForUserCount() {
1532
+        $filter = $this->combineFilterWithAnd(array(
1533
+            $this->connection->ldapUserFilter,
1534
+            $this->connection->ldapUserDisplayName . '=*'
1535
+        ));
1536
+
1537
+        return $filter;
1538
+    }
1539
+
1540
+    /**
1541
+     * @param string $name
1542
+     * @param string $password
1543
+     * @return bool
1544
+     */
1545
+    public function areCredentialsValid($name, $password) {
1546
+        $name = $this->helper->DNasBaseParameter($name);
1547
+        $testConnection = clone $this->connection;
1548
+        $credentials = array(
1549
+            'ldapAgentName' => $name,
1550
+            'ldapAgentPassword' => $password
1551
+        );
1552
+        if(!$testConnection->setConfiguration($credentials)) {
1553
+            return false;
1554
+        }
1555
+        return $testConnection->bind();
1556
+    }
1557
+
1558
+    /**
1559
+     * reverse lookup of a DN given a known UUID
1560
+     *
1561
+     * @param string $uuid
1562
+     * @return string
1563
+     * @throws \Exception
1564
+     */
1565
+    public function getUserDnByUuid($uuid) {
1566
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1567
+        $filter       = $this->connection->ldapUserFilter;
1568
+        $base         = $this->connection->ldapBaseUsers;
1569
+
1570
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1571
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1572
+            // existing DN to be able to reliably detect it.
1573
+            $result = $this->search($filter, $base, ['dn'], 1);
1574
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1575
+                throw new \Exception('Cannot determine UUID attribute');
1576
+            }
1577
+            $dn = $result[0]['dn'][0];
1578
+            if(!$this->detectUuidAttribute($dn, true)) {
1579
+                throw new \Exception('Cannot determine UUID attribute');
1580
+            }
1581
+        } else {
1582
+            // The UUID attribute is either known or an override is given.
1583
+            // By calling this method we ensure that $this->connection->$uuidAttr
1584
+            // is definitely set
1585
+            if(!$this->detectUuidAttribute('', true)) {
1586
+                throw new \Exception('Cannot determine UUID attribute');
1587
+            }
1588
+        }
1589
+
1590
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1591
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1592
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1593
+        }
1594
+
1595
+        $filter = $uuidAttr . '=' . $uuid;
1596
+        $result = $this->searchUsers($filter, ['dn'], 2);
1597
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1598
+            // we put the count into account to make sure that this is
1599
+            // really unique
1600
+            return $result[0]['dn'][0];
1601
+        }
1602
+
1603
+        throw new \Exception('Cannot determine UUID attribute');
1604
+    }
1605
+
1606
+    /**
1607
+     * auto-detects the directory's UUID attribute
1608
+     *
1609
+     * @param string $dn a known DN used to check against
1610
+     * @param bool $isUser
1611
+     * @param bool $force the detection should be run, even if it is not set to auto
1612
+     * @param array|null $ldapRecord
1613
+     * @return bool true on success, false otherwise
1614
+     */
1615
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1616
+        if($isUser) {
1617
+            $uuidAttr     = 'ldapUuidUserAttribute';
1618
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1619
+        } else {
1620
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1621
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1622
+        }
1623
+
1624
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1625
+            return true;
1626
+        }
1627
+
1628
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1629
+            $this->connection->$uuidAttr = $uuidOverride;
1630
+            return true;
1631
+        }
1632
+
1633
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1634
+            if($ldapRecord !== null) {
1635
+                // we have the info from LDAP already, we don't need to talk to the server again
1636
+                if(isset($ldapRecord[$attribute])) {
1637
+                    $this->connection->$uuidAttr = $attribute;
1638
+                    return true;
1639
+                } else {
1640
+                    continue;
1641
+                }
1642
+            }
1643
+
1644
+            $value = $this->readAttribute($dn, $attribute);
1645
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1646
+                \OCP\Util::writeLog(
1647
+                    'user_ldap',
1648
+                    'Setting '.$attribute.' as '.$uuidAttr,
1649
+                    ILogger::DEBUG
1650
+                );
1651
+                $this->connection->$uuidAttr = $attribute;
1652
+                return true;
1653
+            }
1654
+        }
1655
+        \OCP\Util::writeLog(
1656
+            'user_ldap',
1657
+            'Could not autodetect the UUID attribute',
1658
+            ILogger::ERROR
1659
+        );
1660
+
1661
+        return false;
1662
+    }
1663
+
1664
+    /**
1665
+     * @param string $dn
1666
+     * @param bool $isUser
1667
+     * @param null $ldapRecord
1668
+     * @return bool|string
1669
+     */
1670
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1671
+        if($isUser) {
1672
+            $uuidAttr     = 'ldapUuidUserAttribute';
1673
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1674
+        } else {
1675
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1676
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1677
+        }
1678
+
1679
+        $uuid = false;
1680
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1681
+            $attr = $this->connection->$uuidAttr;
1682
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1683
+            if( !is_array($uuid)
1684
+                && $uuidOverride !== ''
1685
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1686
+            {
1687
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1688
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1689
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1690
+            }
1691
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1692
+                $uuid = $uuid[0];
1693
+            }
1694
+        }
1695
+
1696
+        return $uuid;
1697
+    }
1698
+
1699
+    /**
1700
+     * converts a binary ObjectGUID into a string representation
1701
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1702
+     * @return string
1703
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1704
+     */
1705
+    private function convertObjectGUID2Str($oguid) {
1706
+        $hex_guid = bin2hex($oguid);
1707
+        $hex_guid_to_guid_str = '';
1708
+        for($k = 1; $k <= 4; ++$k) {
1709
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1710
+        }
1711
+        $hex_guid_to_guid_str .= '-';
1712
+        for($k = 1; $k <= 2; ++$k) {
1713
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1714
+        }
1715
+        $hex_guid_to_guid_str .= '-';
1716
+        for($k = 1; $k <= 2; ++$k) {
1717
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1718
+        }
1719
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1720
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1721
+
1722
+        return strtoupper($hex_guid_to_guid_str);
1723
+    }
1724
+
1725
+    /**
1726
+     * the first three blocks of the string-converted GUID happen to be in
1727
+     * reverse order. In order to use it in a filter, this needs to be
1728
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1729
+     * to every two hax figures.
1730
+     *
1731
+     * If an invalid string is passed, it will be returned without change.
1732
+     *
1733
+     * @param string $guid
1734
+     * @return string
1735
+     */
1736
+    public function formatGuid2ForFilterUser($guid) {
1737
+        if(!is_string($guid)) {
1738
+            throw new \InvalidArgumentException('String expected');
1739
+        }
1740
+        $blocks = explode('-', $guid);
1741
+        if(count($blocks) !== 5) {
1742
+            /*
1743 1743
 			 * Why not throw an Exception instead? This method is a utility
1744 1744
 			 * called only when trying to figure out whether a "missing" known
1745 1745
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1750,266 +1750,266 @@  discard block
 block discarded – undo
1750 1750
 			 * an exception here would kill the experience for a valid, acting
1751 1751
 			 * user. Instead we write a log message.
1752 1752
 			 */
1753
-			\OC::$server->getLogger()->info(
1754
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1755
-				'({uuid}) probably does not match UUID configuration.',
1756
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1757
-			);
1758
-			return $guid;
1759
-		}
1760
-		for($i=0; $i < 3; $i++) {
1761
-			$pairs = str_split($blocks[$i], 2);
1762
-			$pairs = array_reverse($pairs);
1763
-			$blocks[$i] = implode('', $pairs);
1764
-		}
1765
-		for($i=0; $i < 5; $i++) {
1766
-			$pairs = str_split($blocks[$i], 2);
1767
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1768
-		}
1769
-		return implode('', $blocks);
1770
-	}
1771
-
1772
-	/**
1773
-	 * gets a SID of the domain of the given dn
1774
-	 * @param string $dn
1775
-	 * @return string|bool
1776
-	 */
1777
-	public function getSID($dn) {
1778
-		$domainDN = $this->getDomainDNFromDN($dn);
1779
-		$cacheKey = 'getSID-'.$domainDN;
1780
-		$sid = $this->connection->getFromCache($cacheKey);
1781
-		if(!is_null($sid)) {
1782
-			return $sid;
1783
-		}
1784
-
1785
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1786
-		if(!is_array($objectSid) || empty($objectSid)) {
1787
-			$this->connection->writeToCache($cacheKey, false);
1788
-			return false;
1789
-		}
1790
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1791
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1792
-
1793
-		return $domainObjectSid;
1794
-	}
1795
-
1796
-	/**
1797
-	 * converts a binary SID into a string representation
1798
-	 * @param string $sid
1799
-	 * @return string
1800
-	 */
1801
-	public function convertSID2Str($sid) {
1802
-		// The format of a SID binary string is as follows:
1803
-		// 1 byte for the revision level
1804
-		// 1 byte for the number n of variable sub-ids
1805
-		// 6 bytes for identifier authority value
1806
-		// n*4 bytes for n sub-ids
1807
-		//
1808
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1809
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1810
-		$revision = ord($sid[0]);
1811
-		$numberSubID = ord($sid[1]);
1812
-
1813
-		$subIdStart = 8; // 1 + 1 + 6
1814
-		$subIdLength = 4;
1815
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1816
-			// Incorrect number of bytes present.
1817
-			return '';
1818
-		}
1819
-
1820
-		// 6 bytes = 48 bits can be represented using floats without loss of
1821
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1822
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1823
-
1824
-		$subIDs = array();
1825
-		for ($i = 0; $i < $numberSubID; $i++) {
1826
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1827
-			$subIDs[] = sprintf('%u', $subID[1]);
1828
-		}
1829
-
1830
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1831
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1832
-	}
1833
-
1834
-	/**
1835
-	 * checks if the given DN is part of the given base DN(s)
1836
-	 * @param string $dn the DN
1837
-	 * @param string[] $bases array containing the allowed base DN or DNs
1838
-	 * @return bool
1839
-	 */
1840
-	public function isDNPartOfBase($dn, $bases) {
1841
-		$belongsToBase = false;
1842
-		$bases = $this->helper->sanitizeDN($bases);
1843
-
1844
-		foreach($bases as $base) {
1845
-			$belongsToBase = true;
1846
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1847
-				$belongsToBase = false;
1848
-			}
1849
-			if($belongsToBase) {
1850
-				break;
1851
-			}
1852
-		}
1853
-		return $belongsToBase;
1854
-	}
1855
-
1856
-	/**
1857
-	 * resets a running Paged Search operation
1858
-	 *
1859
-	 * @throws ServerNotAvailableException
1860
-	 */
1861
-	private function abandonPagedSearch() {
1862
-		$cr = $this->connection->getConnectionResource();
1863
-		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1864
-		$this->getPagedSearchResultState();
1865
-		$this->lastCookie = '';
1866
-		$this->cookies = [];
1867
-	}
1868
-
1869
-	/**
1870
-	 * get a cookie for the next LDAP paged search
1871
-	 * @param string $base a string with the base DN for the search
1872
-	 * @param string $filter the search filter to identify the correct search
1873
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1874
-	 * @param int $offset the offset for the new search to identify the correct search really good
1875
-	 * @return string containing the key or empty if none is cached
1876
-	 */
1877
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1878
-		if($offset === 0) {
1879
-			return '';
1880
-		}
1881
-		$offset -= $limit;
1882
-		//we work with cache here
1883
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1884
-		$cookie = '';
1885
-		if(isset($this->cookies[$cacheKey])) {
1886
-			$cookie = $this->cookies[$cacheKey];
1887
-			if(is_null($cookie)) {
1888
-				$cookie = '';
1889
-			}
1890
-		}
1891
-		return $cookie;
1892
-	}
1893
-
1894
-	/**
1895
-	 * checks whether an LDAP paged search operation has more pages that can be
1896
-	 * retrieved, typically when offset and limit are provided.
1897
-	 *
1898
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1899
-	 * be reset by other operations. Best, call it immediately after a search(),
1900
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1901
-	 * well. Don't rely on it with any fetchList-method.
1902
-	 * @return bool
1903
-	 */
1904
-	public function hasMoreResults() {
1905
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1906
-			// as in RFC 2696, when all results are returned, the cookie will
1907
-			// be empty.
1908
-			return false;
1909
-		}
1910
-
1911
-		return true;
1912
-	}
1913
-
1914
-	/**
1915
-	 * set a cookie for LDAP paged search run
1916
-	 * @param string $base a string with the base DN for the search
1917
-	 * @param string $filter the search filter to identify the correct search
1918
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1919
-	 * @param int $offset the offset for the run search to identify the correct search really good
1920
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1921
-	 * @return void
1922
-	 */
1923
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1924
-		// allow '0' for 389ds
1925
-		if(!empty($cookie) || $cookie === '0') {
1926
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1927
-			$this->cookies[$cacheKey] = $cookie;
1928
-			$this->lastCookie = $cookie;
1929
-		}
1930
-	}
1931
-
1932
-	/**
1933
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1934
-	 * @return boolean|null true on success, null or false otherwise
1935
-	 */
1936
-	public function getPagedSearchResultState() {
1937
-		$result = $this->pagedSearchedSuccessful;
1938
-		$this->pagedSearchedSuccessful = null;
1939
-		return $result;
1940
-	}
1941
-
1942
-	/**
1943
-	 * Prepares a paged search, if possible
1944
-	 * @param string $filter the LDAP filter for the search
1945
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1946
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1947
-	 * @param int $limit
1948
-	 * @param int $offset
1949
-	 * @return bool|true
1950
-	 */
1951
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1952
-		$pagedSearchOK = false;
1953
-		if ($limit !== 0) {
1954
-			$offset = (int)$offset; //can be null
1955
-			\OCP\Util::writeLog('user_ldap',
1956
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1957
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1958
-				ILogger::DEBUG);
1959
-			//get the cookie from the search for the previous search, required by LDAP
1960
-			foreach($bases as $base) {
1961
-
1962
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1963
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1964
-					// no cookie known from a potential previous search. We need
1965
-					// to start from 0 to come to the desired page. cookie value
1966
-					// of '0' is valid, because 389ds
1967
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1968
-					$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1969
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1970
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1971
-					// '0' is valid, because 389ds
1972
-					//TODO: remember this, probably does not change in the next request...
1973
-					if(empty($cookie) && $cookie !== '0') {
1974
-						$cookie = null;
1975
-					}
1976
-				}
1977
-				if(!is_null($cookie)) {
1978
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1979
-					$this->abandonPagedSearch();
1980
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1981
-						$this->connection->getConnectionResource(), $limit,
1982
-						false, $cookie);
1983
-					if(!$pagedSearchOK) {
1984
-						return false;
1985
-					}
1986
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
1987
-				} else {
1988
-					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
1989
-					\OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
1990
-				}
1991
-
1992
-			}
1993
-		/* ++ Fixing RHDS searches with pages with zero results ++
1753
+            \OC::$server->getLogger()->info(
1754
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1755
+                '({uuid}) probably does not match UUID configuration.',
1756
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1757
+            );
1758
+            return $guid;
1759
+        }
1760
+        for($i=0; $i < 3; $i++) {
1761
+            $pairs = str_split($blocks[$i], 2);
1762
+            $pairs = array_reverse($pairs);
1763
+            $blocks[$i] = implode('', $pairs);
1764
+        }
1765
+        for($i=0; $i < 5; $i++) {
1766
+            $pairs = str_split($blocks[$i], 2);
1767
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1768
+        }
1769
+        return implode('', $blocks);
1770
+    }
1771
+
1772
+    /**
1773
+     * gets a SID of the domain of the given dn
1774
+     * @param string $dn
1775
+     * @return string|bool
1776
+     */
1777
+    public function getSID($dn) {
1778
+        $domainDN = $this->getDomainDNFromDN($dn);
1779
+        $cacheKey = 'getSID-'.$domainDN;
1780
+        $sid = $this->connection->getFromCache($cacheKey);
1781
+        if(!is_null($sid)) {
1782
+            return $sid;
1783
+        }
1784
+
1785
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1786
+        if(!is_array($objectSid) || empty($objectSid)) {
1787
+            $this->connection->writeToCache($cacheKey, false);
1788
+            return false;
1789
+        }
1790
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1791
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1792
+
1793
+        return $domainObjectSid;
1794
+    }
1795
+
1796
+    /**
1797
+     * converts a binary SID into a string representation
1798
+     * @param string $sid
1799
+     * @return string
1800
+     */
1801
+    public function convertSID2Str($sid) {
1802
+        // The format of a SID binary string is as follows:
1803
+        // 1 byte for the revision level
1804
+        // 1 byte for the number n of variable sub-ids
1805
+        // 6 bytes for identifier authority value
1806
+        // n*4 bytes for n sub-ids
1807
+        //
1808
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1809
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1810
+        $revision = ord($sid[0]);
1811
+        $numberSubID = ord($sid[1]);
1812
+
1813
+        $subIdStart = 8; // 1 + 1 + 6
1814
+        $subIdLength = 4;
1815
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1816
+            // Incorrect number of bytes present.
1817
+            return '';
1818
+        }
1819
+
1820
+        // 6 bytes = 48 bits can be represented using floats without loss of
1821
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1822
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1823
+
1824
+        $subIDs = array();
1825
+        for ($i = 0; $i < $numberSubID; $i++) {
1826
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1827
+            $subIDs[] = sprintf('%u', $subID[1]);
1828
+        }
1829
+
1830
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1831
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1832
+    }
1833
+
1834
+    /**
1835
+     * checks if the given DN is part of the given base DN(s)
1836
+     * @param string $dn the DN
1837
+     * @param string[] $bases array containing the allowed base DN or DNs
1838
+     * @return bool
1839
+     */
1840
+    public function isDNPartOfBase($dn, $bases) {
1841
+        $belongsToBase = false;
1842
+        $bases = $this->helper->sanitizeDN($bases);
1843
+
1844
+        foreach($bases as $base) {
1845
+            $belongsToBase = true;
1846
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1847
+                $belongsToBase = false;
1848
+            }
1849
+            if($belongsToBase) {
1850
+                break;
1851
+            }
1852
+        }
1853
+        return $belongsToBase;
1854
+    }
1855
+
1856
+    /**
1857
+     * resets a running Paged Search operation
1858
+     *
1859
+     * @throws ServerNotAvailableException
1860
+     */
1861
+    private function abandonPagedSearch() {
1862
+        $cr = $this->connection->getConnectionResource();
1863
+        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1864
+        $this->getPagedSearchResultState();
1865
+        $this->lastCookie = '';
1866
+        $this->cookies = [];
1867
+    }
1868
+
1869
+    /**
1870
+     * get a cookie for the next LDAP paged search
1871
+     * @param string $base a string with the base DN for the search
1872
+     * @param string $filter the search filter to identify the correct search
1873
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1874
+     * @param int $offset the offset for the new search to identify the correct search really good
1875
+     * @return string containing the key or empty if none is cached
1876
+     */
1877
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1878
+        if($offset === 0) {
1879
+            return '';
1880
+        }
1881
+        $offset -= $limit;
1882
+        //we work with cache here
1883
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1884
+        $cookie = '';
1885
+        if(isset($this->cookies[$cacheKey])) {
1886
+            $cookie = $this->cookies[$cacheKey];
1887
+            if(is_null($cookie)) {
1888
+                $cookie = '';
1889
+            }
1890
+        }
1891
+        return $cookie;
1892
+    }
1893
+
1894
+    /**
1895
+     * checks whether an LDAP paged search operation has more pages that can be
1896
+     * retrieved, typically when offset and limit are provided.
1897
+     *
1898
+     * Be very careful to use it: the last cookie value, which is inspected, can
1899
+     * be reset by other operations. Best, call it immediately after a search(),
1900
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1901
+     * well. Don't rely on it with any fetchList-method.
1902
+     * @return bool
1903
+     */
1904
+    public function hasMoreResults() {
1905
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1906
+            // as in RFC 2696, when all results are returned, the cookie will
1907
+            // be empty.
1908
+            return false;
1909
+        }
1910
+
1911
+        return true;
1912
+    }
1913
+
1914
+    /**
1915
+     * set a cookie for LDAP paged search run
1916
+     * @param string $base a string with the base DN for the search
1917
+     * @param string $filter the search filter to identify the correct search
1918
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1919
+     * @param int $offset the offset for the run search to identify the correct search really good
1920
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1921
+     * @return void
1922
+     */
1923
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1924
+        // allow '0' for 389ds
1925
+        if(!empty($cookie) || $cookie === '0') {
1926
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1927
+            $this->cookies[$cacheKey] = $cookie;
1928
+            $this->lastCookie = $cookie;
1929
+        }
1930
+    }
1931
+
1932
+    /**
1933
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1934
+     * @return boolean|null true on success, null or false otherwise
1935
+     */
1936
+    public function getPagedSearchResultState() {
1937
+        $result = $this->pagedSearchedSuccessful;
1938
+        $this->pagedSearchedSuccessful = null;
1939
+        return $result;
1940
+    }
1941
+
1942
+    /**
1943
+     * Prepares a paged search, if possible
1944
+     * @param string $filter the LDAP filter for the search
1945
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1946
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1947
+     * @param int $limit
1948
+     * @param int $offset
1949
+     * @return bool|true
1950
+     */
1951
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1952
+        $pagedSearchOK = false;
1953
+        if ($limit !== 0) {
1954
+            $offset = (int)$offset; //can be null
1955
+            \OCP\Util::writeLog('user_ldap',
1956
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1957
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1958
+                ILogger::DEBUG);
1959
+            //get the cookie from the search for the previous search, required by LDAP
1960
+            foreach($bases as $base) {
1961
+
1962
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1963
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1964
+                    // no cookie known from a potential previous search. We need
1965
+                    // to start from 0 to come to the desired page. cookie value
1966
+                    // of '0' is valid, because 389ds
1967
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
1968
+                    $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1969
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1970
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1971
+                    // '0' is valid, because 389ds
1972
+                    //TODO: remember this, probably does not change in the next request...
1973
+                    if(empty($cookie) && $cookie !== '0') {
1974
+                        $cookie = null;
1975
+                    }
1976
+                }
1977
+                if(!is_null($cookie)) {
1978
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1979
+                    $this->abandonPagedSearch();
1980
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1981
+                        $this->connection->getConnectionResource(), $limit,
1982
+                        false, $cookie);
1983
+                    if(!$pagedSearchOK) {
1984
+                        return false;
1985
+                    }
1986
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
1987
+                } else {
1988
+                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
1989
+                    \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
1990
+                }
1991
+
1992
+            }
1993
+        /* ++ Fixing RHDS searches with pages with zero results ++
1994 1994
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1995 1995
 		 * due to pages with zero results.
1996 1996
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1997 1997
 		 * if we don't have a previous paged search.
1998 1998
 		 */
1999
-		} else if ($limit === 0 && !empty($this->lastCookie)) {
2000
-			// a search without limit was requested. However, if we do use
2001
-			// Paged Search once, we always must do it. This requires us to
2002
-			// initialize it with the configured page size.
2003
-			$this->abandonPagedSearch();
2004
-			// in case someone set it to 0 … use 500, otherwise no results will
2005
-			// be returned.
2006
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2007
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2008
-				$this->connection->getConnectionResource(),
2009
-				$pageSize, false, '');
2010
-		}
2011
-
2012
-		return $pagedSearchOK;
2013
-	}
1999
+        } else if ($limit === 0 && !empty($this->lastCookie)) {
2000
+            // a search without limit was requested. However, if we do use
2001
+            // Paged Search once, we always must do it. This requires us to
2002
+            // initialize it with the configured page size.
2003
+            $this->abandonPagedSearch();
2004
+            // in case someone set it to 0 … use 500, otherwise no results will
2005
+            // be returned.
2006
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2007
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2008
+                $this->connection->getConnectionResource(),
2009
+                $pageSize, false, '');
2010
+        }
2011
+
2012
+        return $pagedSearchOK;
2013
+    }
2014 2014
 
2015 2015
 }
Please login to merge, or discard this patch.
Spacing   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -130,7 +130,7 @@  discard block
 block discarded – undo
130 130
 	 * @return AbstractMapping
131 131
 	 */
132 132
 	public function getUserMapper() {
133
-		if(is_null($this->userMapper)) {
133
+		if (is_null($this->userMapper)) {
134 134
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
135 135
 		}
136 136
 		return $this->userMapper;
@@ -150,7 +150,7 @@  discard block
 block discarded – undo
150 150
 	 * @return AbstractMapping
151 151
 	 */
152 152
 	public function getGroupMapper() {
153
-		if(is_null($this->groupMapper)) {
153
+		if (is_null($this->groupMapper)) {
154 154
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
155 155
 		}
156 156
 		return $this->groupMapper;
@@ -183,14 +183,14 @@  discard block
 block discarded – undo
183 183
 	 * @throws ServerNotAvailableException
184 184
 	 */
185 185
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
186
-		if(!$this->checkConnection()) {
186
+		if (!$this->checkConnection()) {
187 187
 			\OCP\Util::writeLog('user_ldap',
188 188
 				'No LDAP Connector assigned, access impossible for readAttribute.',
189 189
 				ILogger::WARN);
190 190
 			return false;
191 191
 		}
192 192
 		$cr = $this->connection->getConnectionResource();
193
-		if(!$this->ldap->isResource($cr)) {
193
+		if (!$this->ldap->isResource($cr)) {
194 194
 			//LDAP not available
195 195
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
196 196
 			return false;
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 		$this->abandonPagedSearch();
201 201
 		// openLDAP requires that we init a new Paged Search. Not needed by AD,
202 202
 		// but does not hurt either.
203
-		$pagingSize = (int)$this->connection->ldapPagingSize;
203
+		$pagingSize = (int) $this->connection->ldapPagingSize;
204 204
 		// 0 won't result in replies, small numbers may leave out groups
205 205
 		// (cf. #12306), 500 is default for paging and should work everywhere.
206 206
 		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
@@ -213,7 +213,7 @@  discard block
 block discarded – undo
213 213
 		$isRangeRequest = false;
214 214
 		do {
215 215
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
216
-			if(is_bool($result)) {
216
+			if (is_bool($result)) {
217 217
 				// when an exists request was run and it was successful, an empty
218 218
 				// array must be returned
219 219
 				return $result ? [] : false;
@@ -230,22 +230,22 @@  discard block
 block discarded – undo
230 230
 			$result = $this->extractRangeData($result, $attr);
231 231
 			if (!empty($result)) {
232 232
 				$normalizedResult = $this->extractAttributeValuesFromResult(
233
-					[ $attr => $result['values'] ],
233
+					[$attr => $result['values']],
234 234
 					$attr
235 235
 				);
236 236
 				$values = array_merge($values, $normalizedResult);
237 237
 
238
-				if($result['rangeHigh'] === '*') {
238
+				if ($result['rangeHigh'] === '*') {
239 239
 					// when server replies with * as high range value, there are
240 240
 					// no more results left
241 241
 					return $values;
242 242
 				} else {
243
-					$low  = $result['rangeHigh'] + 1;
244
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
243
+					$low = $result['rangeHigh'] + 1;
244
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
245 245
 					$isRangeRequest = true;
246 246
 				}
247 247
 			}
248
-		} while($isRangeRequest);
248
+		} while ($isRangeRequest);
249 249
 
250 250
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
251 251
 		return false;
@@ -271,13 +271,13 @@  discard block
 block discarded – undo
271 271
 		if (!$this->ldap->isResource($rr)) {
272 272
 			if ($attribute !== '') {
273 273
 				//do not throw this message on userExists check, irritates
274
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
274
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, ILogger::DEBUG);
275 275
 			}
276 276
 			//in case an error occurs , e.g. object does not exist
277 277
 			return false;
278 278
 		}
279 279
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
280
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
280
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', ILogger::DEBUG);
281 281
 			return true;
282 282
 		}
283 283
 		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
@@ -302,12 +302,12 @@  discard block
 block discarded – undo
302 302
 	 */
303 303
 	public function extractAttributeValuesFromResult($result, $attribute) {
304 304
 		$values = [];
305
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
305
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
306 306
 			$lowercaseAttribute = strtolower($attribute);
307
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
308
-				if($this->resemblesDN($attribute)) {
307
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
308
+				if ($this->resemblesDN($attribute)) {
309 309
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
310
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
310
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
311 311
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
312 312
 				} else {
313 313
 					$values[] = $result[$attribute][$i];
@@ -329,10 +329,10 @@  discard block
 block discarded – undo
329 329
 	 */
330 330
 	public function extractRangeData($result, $attribute) {
331 331
 		$keys = array_keys($result);
332
-		foreach($keys as $key) {
333
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
332
+		foreach ($keys as $key) {
333
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
334 334
 				$queryData = explode(';', $key);
335
-				if(strpos($queryData[1], 'range=') === 0) {
335
+				if (strpos($queryData[1], 'range=') === 0) {
336 336
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
337 337
 					$data = [
338 338
 						'values' => $result[$key],
@@ -357,18 +357,18 @@  discard block
 block discarded – undo
357 357
 	 * @throws \Exception
358 358
 	 */
359 359
 	public function setPassword($userDN, $password) {
360
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
360
+		if ((int) $this->connection->turnOnPasswordChange !== 1) {
361 361
 			throw new \Exception('LDAP password changes are disabled.');
362 362
 		}
363 363
 		$cr = $this->connection->getConnectionResource();
364
-		if(!$this->ldap->isResource($cr)) {
364
+		if (!$this->ldap->isResource($cr)) {
365 365
 			//LDAP not available
366 366
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
367 367
 			return false;
368 368
 		}
369 369
 		try {
370 370
 			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
371
-		} catch(ConstraintViolationException $e) {
371
+		} catch (ConstraintViolationException $e) {
372 372
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
373 373
 		}
374 374
 	}
@@ -410,17 +410,17 @@  discard block
 block discarded – undo
410 410
 	 */
411 411
 	public function getDomainDNFromDN($dn) {
412 412
 		$allParts = $this->ldap->explodeDN($dn, 0);
413
-		if($allParts === false) {
413
+		if ($allParts === false) {
414 414
 			//not a valid DN
415 415
 			return '';
416 416
 		}
417 417
 		$domainParts = array();
418 418
 		$dcFound = false;
419
-		foreach($allParts as $part) {
420
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
419
+		foreach ($allParts as $part) {
420
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
421 421
 				$dcFound = true;
422 422
 			}
423
-			if($dcFound) {
423
+			if ($dcFound) {
424 424
 				$domainParts[] = $part;
425 425
 			}
426 426
 		}
@@ -446,7 +446,7 @@  discard block
 block discarded – undo
446 446
 
447 447
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
448 448
 		//server setups
449
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
449
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
450 450
 			return $fdn;
451 451
 		}
452 452
 
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 		//To avoid bypassing the base DN settings under certain circumstances
464 464
 		//with the group support, check whether the provided DN matches one of
465 465
 		//the given Bases
466
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
466
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
467 467
 			return false;
468 468
 		}
469 469
 
@@ -481,11 +481,11 @@  discard block
 block discarded – undo
481 481
 	 */
482 482
 	public function groupsMatchFilter($groupDNs) {
483 483
 		$validGroupDNs = [];
484
-		foreach($groupDNs as $dn) {
484
+		foreach ($groupDNs as $dn) {
485 485
 			$cacheKey = 'groupsMatchFilter-'.$dn;
486 486
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
487
-			if(!is_null($groupMatchFilter)) {
488
-				if($groupMatchFilter) {
487
+			if (!is_null($groupMatchFilter)) {
488
+				if ($groupMatchFilter) {
489 489
 					$validGroupDNs[] = $dn;
490 490
 				}
491 491
 				continue;
@@ -493,13 +493,13 @@  discard block
 block discarded – undo
493 493
 
494 494
 			// Check the base DN first. If this is not met already, we don't
495 495
 			// need to ask the server at all.
496
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
496
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
497 497
 				$this->connection->writeToCache($cacheKey, false);
498 498
 				continue;
499 499
 			}
500 500
 
501 501
 			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
502
-			if(is_array($result)) {
502
+			if (is_array($result)) {
503 503
 				$this->connection->writeToCache($cacheKey, true);
504 504
 				$validGroupDNs[] = $dn;
505 505
 			} else {
@@ -520,7 +520,7 @@  discard block
 block discarded – undo
520 520
 		//To avoid bypassing the base DN settings under certain circumstances
521 521
 		//with the group support, check whether the provided DN matches one of
522 522
 		//the given Bases
523
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
523
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
524 524
 			return false;
525 525
 		}
526 526
 
@@ -540,7 +540,7 @@  discard block
 block discarded – undo
540 540
 	 */
541 541
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
542 542
 		$newlyMapped = false;
543
-		if($isUser) {
543
+		if ($isUser) {
544 544
 			$mapper = $this->getUserMapper();
545 545
 			$nameAttribute = $this->connection->ldapUserDisplayName;
546 546
 			$filter = $this->connection->ldapUserFilter;
@@ -552,15 +552,15 @@  discard block
 block discarded – undo
552 552
 
553 553
 		//let's try to retrieve the Nextcloud name from the mappings table
554 554
 		$ncName = $mapper->getNameByDN($fdn);
555
-		if(is_string($ncName)) {
555
+		if (is_string($ncName)) {
556 556
 			return $ncName;
557 557
 		}
558 558
 
559 559
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
560 560
 		$uuid = $this->getUUID($fdn, $isUser, $record);
561
-		if(is_string($uuid)) {
561
+		if (is_string($uuid)) {
562 562
 			$ncName = $mapper->getNameByUUID($uuid);
563
-			if(is_string($ncName)) {
563
+			if (is_string($ncName)) {
564 564
 				$mapper->setDNbyUUID($fdn, $uuid);
565 565
 				return $ncName;
566 566
 			}
@@ -570,17 +570,17 @@  discard block
 block discarded – undo
570 570
 			return false;
571 571
 		}
572 572
 
573
-		if(is_null($ldapName)) {
573
+		if (is_null($ldapName)) {
574 574
 			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
575
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
575
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
576 576
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
577 577
 				return false;
578 578
 			}
579 579
 			$ldapName = $ldapName[0];
580 580
 		}
581 581
 
582
-		if($isUser) {
583
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
582
+		if ($isUser) {
583
+			$usernameAttribute = (string) $this->connection->ldapExpertUsernameAttr;
584 584
 			if ($usernameAttribute !== '') {
585 585
 				$username = $this->readAttribute($fdn, $usernameAttribute);
586 586
 				$username = $username[0];
@@ -610,11 +610,11 @@  discard block
 block discarded – undo
610 610
 		// outside of core user management will still cache the user as non-existing.
611 611
 		$originalTTL = $this->connection->ldapCacheTTL;
612 612
 		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
613
-		if(($isUser && $intName !== '' && !$this->ncUserManager->userExists($intName))
613
+		if (($isUser && $intName !== '' && !$this->ncUserManager->userExists($intName))
614 614
 			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
615
-			if($mapper->map($fdn, $intName, $uuid)) {
615
+			if ($mapper->map($fdn, $intName, $uuid)) {
616 616
 				$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
617
-				if($this->ncUserManager instanceof PublicEmitter && $isUser) {
617
+				if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
618 618
 					$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$intName]);
619 619
 				}
620 620
 				$newlyMapped = true;
@@ -624,8 +624,8 @@  discard block
 block discarded – undo
624 624
 		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
625 625
 
626 626
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
627
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
628
-			if($this->ncUserManager instanceof PublicEmitter && $isUser) {
627
+		if (is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
628
+			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
629 629
 				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$intName]);
630 630
 			}
631 631
 			$newlyMapped = true;
@@ -666,7 +666,7 @@  discard block
 block discarded – undo
666 666
 	 * @throws \Exception
667 667
 	 */
668 668
 	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
669
-		if($isUsers) {
669
+		if ($isUsers) {
670 670
 			$nameAttribute = $this->connection->ldapUserDisplayName;
671 671
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
672 672
 		} else {
@@ -674,9 +674,9 @@  discard block
 block discarded – undo
674 674
 		}
675 675
 		$nextcloudNames = [];
676 676
 
677
-		foreach($ldapObjects as $ldapObject) {
677
+		foreach ($ldapObjects as $ldapObject) {
678 678
 			$nameByLDAP = null;
679
-			if(    isset($ldapObject[$nameAttribute])
679
+			if (isset($ldapObject[$nameAttribute])
680 680
 				&& is_array($ldapObject[$nameAttribute])
681 681
 				&& isset($ldapObject[$nameAttribute][0])
682 682
 			) {
@@ -685,13 +685,13 @@  discard block
 block discarded – undo
685 685
 			}
686 686
 
687 687
 			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
688
-			if($ncName) {
688
+			if ($ncName) {
689 689
 				$nextcloudNames[] = $ncName;
690
-				if($isUsers) {
690
+				if ($isUsers) {
691 691
 					$this->updateUserState($ncName);
692 692
 					//cache the user names so it does not need to be retrieved
693 693
 					//again later (e.g. sharing dialogue).
694
-					if(is_null($nameByLDAP)) {
694
+					if (is_null($nameByLDAP)) {
695 695
 						continue;
696 696
 					}
697 697
 					$sndName = isset($ldapObject[$sndAttribute][0])
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
 	 */
712 712
 	public function updateUserState($ncname) {
713 713
 		$user = $this->userManager->get($ncname);
714
-		if($user instanceof OfflineUser) {
714
+		if ($user instanceof OfflineUser) {
715 715
 			$user->unmark();
716 716
 		}
717 717
 	}
@@ -742,7 +742,7 @@  discard block
 block discarded – undo
742 742
 	 */
743 743
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
744 744
 		$user = $this->userManager->get($ocName);
745
-		if($user === null) {
745
+		if ($user === null) {
746 746
 			return;
747 747
 		}
748 748
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -762,9 +762,9 @@  discard block
 block discarded – undo
762 762
 		$attempts = 0;
763 763
 		//while loop is just a precaution. If a name is not generated within
764 764
 		//20 attempts, something else is very wrong. Avoids infinite loop.
765
-		while($attempts < 20){
766
-			$altName = $name . '_' . rand(1000,9999);
767
-			if(!$this->ncUserManager->userExists($altName)) {
765
+		while ($attempts < 20) {
766
+			$altName = $name.'_'.rand(1000, 9999);
767
+			if (!$this->ncUserManager->userExists($altName)) {
768 768
 				return $altName;
769 769
 			}
770 770
 			$attempts++;
@@ -786,25 +786,25 @@  discard block
 block discarded – undo
786 786
 	 */
787 787
 	private function _createAltInternalOwnCloudNameForGroups($name) {
788 788
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
789
-		if(!$usedNames || count($usedNames) === 0) {
789
+		if (!$usedNames || count($usedNames) === 0) {
790 790
 			$lastNo = 1; //will become name_2
791 791
 		} else {
792 792
 			natsort($usedNames);
793 793
 			$lastName = array_pop($usedNames);
794
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
794
+			$lastNo = (int) substr($lastName, strrpos($lastName, '_') + 1);
795 795
 		}
796
-		$altName = $name.'_'. (string)($lastNo+1);
796
+		$altName = $name.'_'.(string) ($lastNo + 1);
797 797
 		unset($usedNames);
798 798
 
799 799
 		$attempts = 1;
800
-		while($attempts < 21){
800
+		while ($attempts < 21) {
801 801
 			// Check to be really sure it is unique
802 802
 			// while loop is just a precaution. If a name is not generated within
803 803
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
804
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
804
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
805 805
 				return $altName;
806 806
 			}
807
-			$altName = $name . '_' . ($lastNo + $attempts);
807
+			$altName = $name.'_'.($lastNo + $attempts);
808 808
 			$attempts++;
809 809
 		}
810 810
 		return false;
@@ -819,7 +819,7 @@  discard block
 block discarded – undo
819 819
 	private function createAltInternalOwnCloudName($name, $isUser) {
820 820
 		$originalTTL = $this->connection->ldapCacheTTL;
821 821
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
822
-		if($isUser) {
822
+		if ($isUser) {
823 823
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
824 824
 		} else {
825 825
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -867,13 +867,13 @@  discard block
 block discarded – undo
867 867
 	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
868 868
 		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
869 869
 		$recordsToUpdate = $ldapRecords;
870
-		if(!$forceApplyAttributes) {
870
+		if (!$forceApplyAttributes) {
871 871
 			$isBackgroundJobModeAjax = $this->config
872 872
 					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
873 873
 			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
874 874
 				$newlyMapped = false;
875 875
 				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
876
-				if(is_string($uid)) {
876
+				if (is_string($uid)) {
877 877
 					$this->cacheUserExists($uid);
878 878
 				}
879 879
 				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
@@ -891,15 +891,15 @@  discard block
 block discarded – undo
891 891
 	 * @param array $ldapRecords
892 892
 	 * @throws \Exception
893 893
 	 */
894
-	public function batchApplyUserAttributes(array $ldapRecords){
894
+	public function batchApplyUserAttributes(array $ldapRecords) {
895 895
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
896
-		foreach($ldapRecords as $userRecord) {
897
-			if(!isset($userRecord[$displayNameAttribute])) {
896
+		foreach ($ldapRecords as $userRecord) {
897
+			if (!isset($userRecord[$displayNameAttribute])) {
898 898
 				// displayName is obligatory
899 899
 				continue;
900 900
 			}
901
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
902
-			if($ocName === false) {
901
+			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
902
+			if ($ocName === false) {
903 903
 				continue;
904 904
 			}
905 905
 			$this->updateUserState($ocName);
@@ -932,8 +932,8 @@  discard block
 block discarded – undo
932 932
 	 * @return array
933 933
 	 */
934 934
 	private function fetchList($list, $manyAttributes) {
935
-		if(is_array($list)) {
936
-			if($manyAttributes) {
935
+		if (is_array($list)) {
936
+			if ($manyAttributes) {
937 937
 				return $list;
938 938
 			} else {
939 939
 				$list = array_reduce($list, function($carry, $item) {
@@ -1031,7 +1031,7 @@  discard block
 block discarded – undo
1031 1031
 		// php no longer supports call-time pass-by-reference
1032 1032
 		// thus cannot support controlPagedResultResponse as the third argument
1033 1033
 		// is a reference
1034
-		$doMethod = function () use ($command, &$arguments) {
1034
+		$doMethod = function() use ($command, &$arguments) {
1035 1035
 			if ($command == 'controlPagedResultResponse') {
1036 1036
 				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1037 1037
 			} else {
@@ -1049,7 +1049,7 @@  discard block
 block discarded – undo
1049 1049
 			$this->connection->resetConnectionResource();
1050 1050
 			$cr = $this->connection->getConnectionResource();
1051 1051
 
1052
-			if(!$this->ldap->isResource($cr)) {
1052
+			if (!$this->ldap->isResource($cr)) {
1053 1053
 				// Seems like we didn't find any resource.
1054 1054
 				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1055 1055
 				throw $e;
@@ -1074,13 +1074,13 @@  discard block
 block discarded – undo
1074 1074
 	 * @throws ServerNotAvailableException
1075 1075
 	 */
1076 1076
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1077
-		if(!is_null($attr) && !is_array($attr)) {
1077
+		if (!is_null($attr) && !is_array($attr)) {
1078 1078
 			$attr = array(mb_strtolower($attr, 'UTF-8'));
1079 1079
 		}
1080 1080
 
1081 1081
 		// See if we have a resource, in case not cancel with message
1082 1082
 		$cr = $this->connection->getConnectionResource();
1083
-		if(!$this->ldap->isResource($cr)) {
1083
+		if (!$this->ldap->isResource($cr)) {
1084 1084
 			// Seems like we didn't find any resource.
1085 1085
 			// Return an empty array just like before.
1086 1086
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
@@ -1088,13 +1088,13 @@  discard block
 block discarded – undo
1088 1088
 		}
1089 1089
 
1090 1090
 		//check whether paged search should be attempted
1091
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1091
+		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int) $limit, $offset);
1092 1092
 
1093 1093
 		$linkResources = array_pad(array(), count($base), $cr);
1094 1094
 		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1095 1095
 		// cannot use $cr anymore, might have changed in the previous call!
1096 1096
 		$error = $this->ldap->errno($this->connection->getConnectionResource());
1097
-		if(!is_array($sr) || $error !== 0) {
1097
+		if (!is_array($sr) || $error !== 0) {
1098 1098
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1099 1099
 			return false;
1100 1100
 		}
@@ -1117,29 +1117,29 @@  discard block
 block discarded – undo
1117 1117
 	 */
1118 1118
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1119 1119
 		$cookie = null;
1120
-		if($pagedSearchOK) {
1120
+		if ($pagedSearchOK) {
1121 1121
 			$cr = $this->connection->getConnectionResource();
1122
-			foreach($sr as $key => $res) {
1123
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1122
+			foreach ($sr as $key => $res) {
1123
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1124 1124
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1125 1125
 				}
1126 1126
 			}
1127 1127
 
1128 1128
 			//browsing through prior pages to get the cookie for the new one
1129
-			if($skipHandling) {
1129
+			if ($skipHandling) {
1130 1130
 				return false;
1131 1131
 			}
1132 1132
 			// if count is bigger, then the server does not support
1133 1133
 			// paged search. Instead, he did a normal search. We set a
1134 1134
 			// flag here, so the callee knows how to deal with it.
1135
-			if($iFoundItems <= $limit) {
1135
+			if ($iFoundItems <= $limit) {
1136 1136
 				$this->pagedSearchedSuccessful = true;
1137 1137
 			}
1138 1138
 		} else {
1139
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1139
+			if (!is_null($limit) && (int) $this->connection->ldapPagingSize !== 0) {
1140 1140
 				\OC::$server->getLogger()->debug(
1141 1141
 					'Paged search was not available',
1142
-					[ 'app' => 'user_ldap' ]
1142
+					['app' => 'user_ldap']
1143 1143
 				);
1144 1144
 			}
1145 1145
 		}
@@ -1168,8 +1168,8 @@  discard block
 block discarded – undo
1168 1168
 	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1169 1169
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1170 1170
 
1171
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1172
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1171
+		$limitPerPage = (int) $this->connection->ldapPagingSize;
1172
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1173 1173
 			$limitPerPage = $limit;
1174 1174
 		}
1175 1175
 
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
 
1180 1180
 		do {
1181 1181
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1182
-			if($search === false) {
1182
+			if ($search === false) {
1183 1183
 				return $counter > 0 ? $counter : false;
1184 1184
 			}
1185 1185
 			list($sr, $pagedSearchOK) = $search;
@@ -1198,7 +1198,7 @@  discard block
 block discarded – undo
1198 1198
 			 * Continue now depends on $hasMorePages value
1199 1199
 			 */
1200 1200
 			$continue = $pagedSearchOK && $hasMorePages;
1201
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1201
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1202 1202
 
1203 1203
 		return $counter;
1204 1204
 	}
@@ -1210,8 +1210,8 @@  discard block
 block discarded – undo
1210 1210
 	private function countEntriesInSearchResults($searchResults) {
1211 1211
 		$counter = 0;
1212 1212
 
1213
-		foreach($searchResults as $res) {
1214
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1213
+		foreach ($searchResults as $res) {
1214
+			$count = (int) $this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1215 1215
 			$counter += $count;
1216 1216
 		}
1217 1217
 
@@ -1231,8 +1231,8 @@  discard block
 block discarded – undo
1231 1231
 	 * @throws ServerNotAvailableException
1232 1232
 	 */
1233 1233
 	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1234
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1235
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1234
+		$limitPerPage = (int) $this->connection->ldapPagingSize;
1235
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1236 1236
 			$limitPerPage = $limit;
1237 1237
 		}
1238 1238
 
@@ -1246,13 +1246,13 @@  discard block
 block discarded – undo
1246 1246
 		$savedoffset = $offset;
1247 1247
 		do {
1248 1248
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1249
-			if($search === false) {
1249
+			if ($search === false) {
1250 1250
 				return [];
1251 1251
 			}
1252 1252
 			list($sr, $pagedSearchOK) = $search;
1253 1253
 			$cr = $this->connection->getConnectionResource();
1254 1254
 
1255
-			if($skipHandling) {
1255
+			if ($skipHandling) {
1256 1256
 				//i.e. result do not need to be fetched, we just need the cookie
1257 1257
 				//thus pass 1 or any other value as $iFoundItems because it is not
1258 1258
 				//used
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
 			}
1264 1264
 
1265 1265
 			$iFoundItems = 0;
1266
-			foreach($sr as $res) {
1266
+			foreach ($sr as $res) {
1267 1267
 				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1268 1268
 				$iFoundItems = max($iFoundItems, $findings['count']);
1269 1269
 				unset($findings['count']);
@@ -1279,27 +1279,27 @@  discard block
 block discarded – undo
1279 1279
 
1280 1280
 		// if we're here, probably no connection resource is returned.
1281 1281
 		// to make Nextcloud behave nicely, we simply give back an empty array.
1282
-		if(is_null($findings)) {
1282
+		if (is_null($findings)) {
1283 1283
 			return array();
1284 1284
 		}
1285 1285
 
1286
-		if(!is_null($attr)) {
1286
+		if (!is_null($attr)) {
1287 1287
 			$selection = [];
1288 1288
 			$i = 0;
1289
-			foreach($findings as $item) {
1290
-				if(!is_array($item)) {
1289
+			foreach ($findings as $item) {
1290
+				if (!is_array($item)) {
1291 1291
 					continue;
1292 1292
 				}
1293 1293
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1294
-				foreach($attr as $key) {
1295
-					if(isset($item[$key])) {
1296
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1294
+				foreach ($attr as $key) {
1295
+					if (isset($item[$key])) {
1296
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1297 1297
 							unset($item[$key]['count']);
1298 1298
 						}
1299
-						if($key !== 'dn') {
1300
-							if($this->resemblesDN($key)) {
1299
+						if ($key !== 'dn') {
1300
+							if ($this->resemblesDN($key)) {
1301 1301
 								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1302
-							} else if($key === 'objectguid' || $key === 'guid') {
1302
+							} else if ($key === 'objectguid' || $key === 'guid') {
1303 1303
 								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1304 1304
 							} else {
1305 1305
 								$selection[$i][$key] = $item[$key];
@@ -1317,14 +1317,14 @@  discard block
 block discarded – undo
1317 1317
 		//we slice the findings, when
1318 1318
 		//a) paged search unsuccessful, though attempted
1319 1319
 		//b) no paged search, but limit set
1320
-		if((!$this->getPagedSearchResultState()
1320
+		if ((!$this->getPagedSearchResultState()
1321 1321
 			&& $pagedSearchOK)
1322 1322
 			|| (
1323 1323
 				!$pagedSearchOK
1324 1324
 				&& !is_null($limit)
1325 1325
 			)
1326 1326
 		) {
1327
-			$findings = array_slice($findings, (int)$offset, $limit);
1327
+			$findings = array_slice($findings, (int) $offset, $limit);
1328 1328
 		}
1329 1329
 		return $findings;
1330 1330
 	}
@@ -1337,13 +1337,13 @@  discard block
 block discarded – undo
1337 1337
 	public function sanitizeUsername($name) {
1338 1338
 		$name = trim($name);
1339 1339
 
1340
-		if($this->connection->ldapIgnoreNamingRules) {
1340
+		if ($this->connection->ldapIgnoreNamingRules) {
1341 1341
 			return $name;
1342 1342
 		}
1343 1343
 
1344 1344
 		// Transliteration to ASCII
1345 1345
 		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1346
-		if($transliterated !== false) {
1346
+		if ($transliterated !== false) {
1347 1347
 			// depending on system config iconv can work or not
1348 1348
 			$name = $transliterated;
1349 1349
 		}
@@ -1354,7 +1354,7 @@  discard block
 block discarded – undo
1354 1354
 		// Every remaining disallowed characters will be removed
1355 1355
 		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1356 1356
 
1357
-		if($name === '') {
1357
+		if ($name === '') {
1358 1358
 			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1359 1359
 		}
1360 1360
 
@@ -1369,13 +1369,13 @@  discard block
 block discarded – undo
1369 1369
 	*/
1370 1370
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1371 1371
 		$asterisk = '';
1372
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1372
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1373 1373
 			$asterisk = '*';
1374 1374
 			$input = mb_substr($input, 1, null, 'UTF-8');
1375 1375
 		}
1376 1376
 		$search  = array('*', '\\', '(', ')');
1377 1377
 		$replace = array('\\*', '\\\\', '\\(', '\\)');
1378
-		return $asterisk . str_replace($search, $replace, $input);
1378
+		return $asterisk.str_replace($search, $replace, $input);
1379 1379
 	}
1380 1380
 
1381 1381
 	/**
@@ -1405,13 +1405,13 @@  discard block
 block discarded – undo
1405 1405
 	 */
1406 1406
 	private function combineFilter($filters, $operator) {
1407 1407
 		$combinedFilter = '('.$operator;
1408
-		foreach($filters as $filter) {
1408
+		foreach ($filters as $filter) {
1409 1409
 			if ($filter !== '' && $filter[0] !== '(') {
1410 1410
 				$filter = '('.$filter.')';
1411 1411
 			}
1412
-			$combinedFilter.=$filter;
1412
+			$combinedFilter .= $filter;
1413 1413
 		}
1414
-		$combinedFilter.=')';
1414
+		$combinedFilter .= ')';
1415 1415
 		return $combinedFilter;
1416 1416
 	}
1417 1417
 
@@ -1447,17 +1447,17 @@  discard block
 block discarded – undo
1447 1447
 	 * @throws \Exception
1448 1448
 	 */
1449 1449
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1450
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1450
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1451 1451
 			throw new \Exception('searchAttributes must be an array with at least two string');
1452 1452
 		}
1453 1453
 		$searchWords = explode(' ', trim($search));
1454 1454
 		$wordFilters = array();
1455
-		foreach($searchWords as $word) {
1455
+		foreach ($searchWords as $word) {
1456 1456
 			$word = $this->prepareSearchTerm($word);
1457 1457
 			//every word needs to appear at least once
1458 1458
 			$wordMatchOneAttrFilters = array();
1459
-			foreach($searchAttributes as $attr) {
1460
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1459
+			foreach ($searchAttributes as $attr) {
1460
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1461 1461
 			}
1462 1462
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1463 1463
 		}
@@ -1475,10 +1475,10 @@  discard block
 block discarded – undo
1475 1475
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1476 1476
 		$filter = array();
1477 1477
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1478
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1478
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1479 1479
 			try {
1480 1480
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1481
-			} catch(\Exception $e) {
1481
+			} catch (\Exception $e) {
1482 1482
 				\OCP\Util::writeLog(
1483 1483
 					'user_ldap',
1484 1484
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1488,17 +1488,17 @@  discard block
 block discarded – undo
1488 1488
 		}
1489 1489
 
1490 1490
 		$search = $this->prepareSearchTerm($search);
1491
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1491
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1492 1492
 			if ($fallbackAttribute === '') {
1493 1493
 				return '';
1494 1494
 			}
1495
-			$filter[] = $fallbackAttribute . '=' . $search;
1495
+			$filter[] = $fallbackAttribute.'='.$search;
1496 1496
 		} else {
1497
-			foreach($searchAttributes as $attribute) {
1498
-				$filter[] = $attribute . '=' . $search;
1497
+			foreach ($searchAttributes as $attribute) {
1498
+				$filter[] = $attribute.'='.$search;
1499 1499
 			}
1500 1500
 		}
1501
-		if(count($filter) === 1) {
1501
+		if (count($filter) === 1) {
1502 1502
 			return '('.$filter[0].')';
1503 1503
 		}
1504 1504
 		return $this->combineFilterWithOr($filter);
@@ -1519,7 +1519,7 @@  discard block
 block discarded – undo
1519 1519
 		if ($term === '') {
1520 1520
 			$result = '*';
1521 1521
 		} else if ($allowEnum !== 'no') {
1522
-			$result = $term . '*';
1522
+			$result = $term.'*';
1523 1523
 		}
1524 1524
 		return $result;
1525 1525
 	}
@@ -1531,7 +1531,7 @@  discard block
 block discarded – undo
1531 1531
 	public function getFilterForUserCount() {
1532 1532
 		$filter = $this->combineFilterWithAnd(array(
1533 1533
 			$this->connection->ldapUserFilter,
1534
-			$this->connection->ldapUserDisplayName . '=*'
1534
+			$this->connection->ldapUserDisplayName.'=*'
1535 1535
 		));
1536 1536
 
1537 1537
 		return $filter;
@@ -1549,7 +1549,7 @@  discard block
 block discarded – undo
1549 1549
 			'ldapAgentName' => $name,
1550 1550
 			'ldapAgentPassword' => $password
1551 1551
 		);
1552
-		if(!$testConnection->setConfiguration($credentials)) {
1552
+		if (!$testConnection->setConfiguration($credentials)) {
1553 1553
 			return false;
1554 1554
 		}
1555 1555
 		return $testConnection->bind();
@@ -1571,30 +1571,30 @@  discard block
 block discarded – undo
1571 1571
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1572 1572
 			// existing DN to be able to reliably detect it.
1573 1573
 			$result = $this->search($filter, $base, ['dn'], 1);
1574
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1574
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1575 1575
 				throw new \Exception('Cannot determine UUID attribute');
1576 1576
 			}
1577 1577
 			$dn = $result[0]['dn'][0];
1578
-			if(!$this->detectUuidAttribute($dn, true)) {
1578
+			if (!$this->detectUuidAttribute($dn, true)) {
1579 1579
 				throw new \Exception('Cannot determine UUID attribute');
1580 1580
 			}
1581 1581
 		} else {
1582 1582
 			// The UUID attribute is either known or an override is given.
1583 1583
 			// By calling this method we ensure that $this->connection->$uuidAttr
1584 1584
 			// is definitely set
1585
-			if(!$this->detectUuidAttribute('', true)) {
1585
+			if (!$this->detectUuidAttribute('', true)) {
1586 1586
 				throw new \Exception('Cannot determine UUID attribute');
1587 1587
 			}
1588 1588
 		}
1589 1589
 
1590 1590
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1591
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1591
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1592 1592
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1593 1593
 		}
1594 1594
 
1595
-		$filter = $uuidAttr . '=' . $uuid;
1595
+		$filter = $uuidAttr.'='.$uuid;
1596 1596
 		$result = $this->searchUsers($filter, ['dn'], 2);
1597
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1597
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1598 1598
 			// we put the count into account to make sure that this is
1599 1599
 			// really unique
1600 1600
 			return $result[0]['dn'][0];
@@ -1613,7 +1613,7 @@  discard block
 block discarded – undo
1613 1613
 	 * @return bool true on success, false otherwise
1614 1614
 	 */
1615 1615
 	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1616
-		if($isUser) {
1616
+		if ($isUser) {
1617 1617
 			$uuidAttr     = 'ldapUuidUserAttribute';
1618 1618
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1619 1619
 		} else {
@@ -1621,7 +1621,7 @@  discard block
 block discarded – undo
1621 1621
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1622 1622
 		}
1623 1623
 
1624
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1624
+		if (($this->connection->$uuidAttr !== 'auto') && !$force) {
1625 1625
 			return true;
1626 1626
 		}
1627 1627
 
@@ -1630,10 +1630,10 @@  discard block
 block discarded – undo
1630 1630
 			return true;
1631 1631
 		}
1632 1632
 
1633
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1634
-			if($ldapRecord !== null) {
1633
+		foreach (self::UUID_ATTRIBUTES as $attribute) {
1634
+			if ($ldapRecord !== null) {
1635 1635
 				// we have the info from LDAP already, we don't need to talk to the server again
1636
-				if(isset($ldapRecord[$attribute])) {
1636
+				if (isset($ldapRecord[$attribute])) {
1637 1637
 					$this->connection->$uuidAttr = $attribute;
1638 1638
 					return true;
1639 1639
 				} else {
@@ -1642,7 +1642,7 @@  discard block
 block discarded – undo
1642 1642
 			}
1643 1643
 
1644 1644
 			$value = $this->readAttribute($dn, $attribute);
1645
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1645
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1646 1646
 				\OCP\Util::writeLog(
1647 1647
 					'user_ldap',
1648 1648
 					'Setting '.$attribute.' as '.$uuidAttr,
@@ -1668,7 +1668,7 @@  discard block
 block discarded – undo
1668 1668
 	 * @return bool|string
1669 1669
 	 */
1670 1670
 	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1671
-		if($isUser) {
1671
+		if ($isUser) {
1672 1672
 			$uuidAttr     = 'ldapUuidUserAttribute';
1673 1673
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1674 1674
 		} else {
@@ -1677,10 +1677,10 @@  discard block
 block discarded – undo
1677 1677
 		}
1678 1678
 
1679 1679
 		$uuid = false;
1680
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1680
+		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1681 1681
 			$attr = $this->connection->$uuidAttr;
1682 1682
 			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1683
-			if( !is_array($uuid)
1683
+			if (!is_array($uuid)
1684 1684
 				&& $uuidOverride !== ''
1685 1685
 				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1686 1686
 			{
@@ -1688,7 +1688,7 @@  discard block
 block discarded – undo
1688 1688
 					? $ldapRecord[$this->connection->$uuidAttr]
1689 1689
 					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1690 1690
 			}
1691
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1691
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1692 1692
 				$uuid = $uuid[0];
1693 1693
 			}
1694 1694
 		}
@@ -1705,19 +1705,19 @@  discard block
 block discarded – undo
1705 1705
 	private function convertObjectGUID2Str($oguid) {
1706 1706
 		$hex_guid = bin2hex($oguid);
1707 1707
 		$hex_guid_to_guid_str = '';
1708
-		for($k = 1; $k <= 4; ++$k) {
1708
+		for ($k = 1; $k <= 4; ++$k) {
1709 1709
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1710 1710
 		}
1711 1711
 		$hex_guid_to_guid_str .= '-';
1712
-		for($k = 1; $k <= 2; ++$k) {
1712
+		for ($k = 1; $k <= 2; ++$k) {
1713 1713
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1714 1714
 		}
1715 1715
 		$hex_guid_to_guid_str .= '-';
1716
-		for($k = 1; $k <= 2; ++$k) {
1716
+		for ($k = 1; $k <= 2; ++$k) {
1717 1717
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1718 1718
 		}
1719
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1720
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1719
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1720
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1721 1721
 
1722 1722
 		return strtoupper($hex_guid_to_guid_str);
1723 1723
 	}
@@ -1734,11 +1734,11 @@  discard block
 block discarded – undo
1734 1734
 	 * @return string
1735 1735
 	 */
1736 1736
 	public function formatGuid2ForFilterUser($guid) {
1737
-		if(!is_string($guid)) {
1737
+		if (!is_string($guid)) {
1738 1738
 			throw new \InvalidArgumentException('String expected');
1739 1739
 		}
1740 1740
 		$blocks = explode('-', $guid);
1741
-		if(count($blocks) !== 5) {
1741
+		if (count($blocks) !== 5) {
1742 1742
 			/*
1743 1743
 			 * Why not throw an Exception instead? This method is a utility
1744 1744
 			 * called only when trying to figure out whether a "missing" known
@@ -1751,20 +1751,20 @@  discard block
 block discarded – undo
1751 1751
 			 * user. Instead we write a log message.
1752 1752
 			 */
1753 1753
 			\OC::$server->getLogger()->info(
1754
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1754
+				'Passed string does not resemble a valid GUID. Known UUID '.
1755 1755
 				'({uuid}) probably does not match UUID configuration.',
1756
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1756
+				['app' => 'user_ldap', 'uuid' => $guid]
1757 1757
 			);
1758 1758
 			return $guid;
1759 1759
 		}
1760
-		for($i=0; $i < 3; $i++) {
1760
+		for ($i = 0; $i < 3; $i++) {
1761 1761
 			$pairs = str_split($blocks[$i], 2);
1762 1762
 			$pairs = array_reverse($pairs);
1763 1763
 			$blocks[$i] = implode('', $pairs);
1764 1764
 		}
1765
-		for($i=0; $i < 5; $i++) {
1765
+		for ($i = 0; $i < 5; $i++) {
1766 1766
 			$pairs = str_split($blocks[$i], 2);
1767
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1767
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1768 1768
 		}
1769 1769
 		return implode('', $blocks);
1770 1770
 	}
@@ -1778,12 +1778,12 @@  discard block
 block discarded – undo
1778 1778
 		$domainDN = $this->getDomainDNFromDN($dn);
1779 1779
 		$cacheKey = 'getSID-'.$domainDN;
1780 1780
 		$sid = $this->connection->getFromCache($cacheKey);
1781
-		if(!is_null($sid)) {
1781
+		if (!is_null($sid)) {
1782 1782
 			return $sid;
1783 1783
 		}
1784 1784
 
1785 1785
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1786
-		if(!is_array($objectSid) || empty($objectSid)) {
1786
+		if (!is_array($objectSid) || empty($objectSid)) {
1787 1787
 			$this->connection->writeToCache($cacheKey, false);
1788 1788
 			return false;
1789 1789
 		}
@@ -1841,12 +1841,12 @@  discard block
 block discarded – undo
1841 1841
 		$belongsToBase = false;
1842 1842
 		$bases = $this->helper->sanitizeDN($bases);
1843 1843
 
1844
-		foreach($bases as $base) {
1844
+		foreach ($bases as $base) {
1845 1845
 			$belongsToBase = true;
1846
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1846
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1847 1847
 				$belongsToBase = false;
1848 1848
 			}
1849
-			if($belongsToBase) {
1849
+			if ($belongsToBase) {
1850 1850
 				break;
1851 1851
 			}
1852 1852
 		}
@@ -1875,16 +1875,16 @@  discard block
 block discarded – undo
1875 1875
 	 * @return string containing the key or empty if none is cached
1876 1876
 	 */
1877 1877
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1878
-		if($offset === 0) {
1878
+		if ($offset === 0) {
1879 1879
 			return '';
1880 1880
 		}
1881 1881
 		$offset -= $limit;
1882 1882
 		//we work with cache here
1883
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1883
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset;
1884 1884
 		$cookie = '';
1885
-		if(isset($this->cookies[$cacheKey])) {
1885
+		if (isset($this->cookies[$cacheKey])) {
1886 1886
 			$cookie = $this->cookies[$cacheKey];
1887
-			if(is_null($cookie)) {
1887
+			if (is_null($cookie)) {
1888 1888
 				$cookie = '';
1889 1889
 			}
1890 1890
 		}
@@ -1902,7 +1902,7 @@  discard block
 block discarded – undo
1902 1902
 	 * @return bool
1903 1903
 	 */
1904 1904
 	public function hasMoreResults() {
1905
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1905
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1906 1906
 			// as in RFC 2696, when all results are returned, the cookie will
1907 1907
 			// be empty.
1908 1908
 			return false;
@@ -1922,8 +1922,8 @@  discard block
 block discarded – undo
1922 1922
 	 */
1923 1923
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1924 1924
 		// allow '0' for 389ds
1925
-		if(!empty($cookie) || $cookie === '0') {
1926
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1925
+		if (!empty($cookie) || $cookie === '0') {
1926
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset;
1927 1927
 			$this->cookies[$cacheKey] = $cookie;
1928 1928
 			$this->lastCookie = $cookie;
1929 1929
 		}
@@ -1951,16 +1951,16 @@  discard block
 block discarded – undo
1951 1951
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1952 1952
 		$pagedSearchOK = false;
1953 1953
 		if ($limit !== 0) {
1954
-			$offset = (int)$offset; //can be null
1954
+			$offset = (int) $offset; //can be null
1955 1955
 			\OCP\Util::writeLog('user_ldap',
1956 1956
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1957
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1957
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
1958 1958
 				ILogger::DEBUG);
1959 1959
 			//get the cookie from the search for the previous search, required by LDAP
1960
-			foreach($bases as $base) {
1960
+			foreach ($bases as $base) {
1961 1961
 
1962 1962
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1963
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1963
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1964 1964
 					// no cookie known from a potential previous search. We need
1965 1965
 					// to start from 0 to come to the desired page. cookie value
1966 1966
 					// of '0' is valid, because 389ds
@@ -1970,17 +1970,17 @@  discard block
 block discarded – undo
1970 1970
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1971 1971
 					// '0' is valid, because 389ds
1972 1972
 					//TODO: remember this, probably does not change in the next request...
1973
-					if(empty($cookie) && $cookie !== '0') {
1973
+					if (empty($cookie) && $cookie !== '0') {
1974 1974
 						$cookie = null;
1975 1975
 					}
1976 1976
 				}
1977
-				if(!is_null($cookie)) {
1977
+				if (!is_null($cookie)) {
1978 1978
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1979 1979
 					$this->abandonPagedSearch();
1980 1980
 					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1981 1981
 						$this->connection->getConnectionResource(), $limit,
1982 1982
 						false, $cookie);
1983
-					if(!$pagedSearchOK) {
1983
+					if (!$pagedSearchOK) {
1984 1984
 						return false;
1985 1985
 					}
1986 1986
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
@@ -2003,7 +2003,7 @@  discard block
 block discarded – undo
2003 2003
 			$this->abandonPagedSearch();
2004 2004
 			// in case someone set it to 0 … use 500, otherwise no results will
2005 2005
 			// be returned.
2006
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2006
+			$pageSize = (int) $this->connection->ldapPagingSize > 0 ? (int) $this->connection->ldapPagingSize : 500;
2007 2007
 			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2008 2008
 				$this->connection->getConnectionResource(),
2009 2009
 				$pageSize, false, '');
Please login to merge, or discard this patch.
apps/user_ldap/lib/Connection.php 2 patches
Indentation   +615 added lines, -615 removed lines patch added patch discarded remove patch
@@ -62,620 +62,620 @@
 block discarded – undo
62 62
  * @property string ldapEmailAttribute
63 63
  */
64 64
 class Connection extends LDAPUtility {
65
-	private $ldapConnectionRes = null;
66
-	private $configPrefix;
67
-	private $configID;
68
-	private $configured = false;
69
-	//whether connection should be kept on __destruct
70
-	private $dontDestruct = false;
71
-
72
-	/**
73
-	 * @var bool runtime flag that indicates whether supported primary groups are available
74
-	 */
75
-	public $hasPrimaryGroups = true;
76
-
77
-	/**
78
-	 * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
79
-	 */
80
-	public $hasGidNumber = true;
81
-
82
-	//cache handler
83
-	protected $cache;
84
-
85
-	/** @var Configuration settings handler **/
86
-	protected $configuration;
87
-
88
-	protected $doNotValidate = false;
89
-
90
-	protected $ignoreValidation = false;
91
-
92
-	protected $bindResult = [];
93
-
94
-	/**
95
-	 * Constructor
96
-	 * @param ILDAPWrapper $ldap
97
-	 * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
98
-	 * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
99
-	 */
100
-	public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
101
-		parent::__construct($ldap);
102
-		$this->configPrefix = $configPrefix;
103
-		$this->configID = $configID;
104
-		$this->configuration = new Configuration($configPrefix,
105
-												 !is_null($configID));
106
-		$memcache = \OC::$server->getMemCacheFactory();
107
-		if($memcache->isAvailable()) {
108
-			$this->cache = $memcache->createDistributed();
109
-		}
110
-		$helper = new Helper(\OC::$server->getConfig());
111
-		$this->doNotValidate = !in_array($this->configPrefix,
112
-			$helper->getServerConfigurationPrefixes());
113
-	}
114
-
115
-	public function __destruct() {
116
-		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
117
-			@$this->ldap->unbind($this->ldapConnectionRes);
118
-			$this->bindResult = [];
119
-		}
120
-	}
121
-
122
-	/**
123
-	 * defines behaviour when the instance is cloned
124
-	 */
125
-	public function __clone() {
126
-		$this->configuration = new Configuration($this->configPrefix,
127
-												 !is_null($this->configID));
128
-		if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
129
-			$this->bindResult = [];
130
-		}
131
-		$this->ldapConnectionRes = null;
132
-		$this->dontDestruct = true;
133
-	}
134
-
135
-	/**
136
-	 * @param string $name
137
-	 * @return bool|mixed
138
-	 */
139
-	public function __get($name) {
140
-		if(!$this->configured) {
141
-			$this->readConfiguration();
142
-		}
143
-
144
-		return $this->configuration->$name;
145
-	}
146
-
147
-	/**
148
-	 * @param string $name
149
-	 * @param mixed $value
150
-	 */
151
-	public function __set($name, $value) {
152
-		$this->doNotValidate = false;
153
-		$before = $this->configuration->$name;
154
-		$this->configuration->$name = $value;
155
-		$after = $this->configuration->$name;
156
-		if($before !== $after) {
157
-			if ($this->configID !== '' && $this->configID !== null) {
158
-				$this->configuration->saveConfiguration();
159
-			}
160
-			$this->validateConfiguration();
161
-		}
162
-	}
163
-
164
-	/**
165
-	 * @param string $rule
166
-	 * @return array
167
-	 * @throws \RuntimeException
168
-	 */
169
-	public function resolveRule($rule) {
170
-		return $this->configuration->resolveRule($rule);
171
-	}
172
-
173
-	/**
174
-	 * sets whether the result of the configuration validation shall
175
-	 * be ignored when establishing the connection. Used by the Wizard
176
-	 * in early configuration state.
177
-	 * @param bool $state
178
-	 */
179
-	public function setIgnoreValidation($state) {
180
-		$this->ignoreValidation = (bool)$state;
181
-	}
182
-
183
-	/**
184
-	 * initializes the LDAP backend
185
-	 * @param bool $force read the config settings no matter what
186
-	 */
187
-	public function init($force = false) {
188
-		$this->readConfiguration($force);
189
-		$this->establishConnection();
190
-	}
191
-
192
-	/**
193
-	 * Returns the LDAP handler
194
-	 */
195
-	public function getConnectionResource() {
196
-		if(!$this->ldapConnectionRes) {
197
-			$this->init();
198
-		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
199
-			$this->ldapConnectionRes = null;
200
-			$this->establishConnection();
201
-		}
202
-		if(is_null($this->ldapConnectionRes)) {
203
-			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR);
204
-			throw new ServerNotAvailableException('Connection to LDAP server could not be established');
205
-		}
206
-		return $this->ldapConnectionRes;
207
-	}
208
-
209
-	/**
210
-	 * resets the connection resource
211
-	 */
212
-	public function resetConnectionResource() {
213
-		if(!is_null($this->ldapConnectionRes)) {
214
-			@$this->ldap->unbind($this->ldapConnectionRes);
215
-			$this->ldapConnectionRes = null;
216
-			$this->bindResult = [];
217
-		}
218
-	}
219
-
220
-	/**
221
-	 * @param string|null $key
222
-	 * @return string
223
-	 */
224
-	private function getCacheKey($key) {
225
-		$prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
226
-		if(is_null($key)) {
227
-			return $prefix;
228
-		}
229
-		return $prefix.hash('sha256', $key);
230
-	}
231
-
232
-	/**
233
-	 * @param string $key
234
-	 * @return mixed|null
235
-	 */
236
-	public function getFromCache($key) {
237
-		if(!$this->configured) {
238
-			$this->readConfiguration();
239
-		}
240
-		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
241
-			return null;
242
-		}
243
-		$key = $this->getCacheKey($key);
244
-
245
-		return json_decode(base64_decode($this->cache->get($key)), true);
246
-	}
247
-
248
-	/**
249
-	 * @param string $key
250
-	 * @param mixed $value
251
-	 *
252
-	 * @return string
253
-	 */
254
-	public function writeToCache($key, $value) {
255
-		if(!$this->configured) {
256
-			$this->readConfiguration();
257
-		}
258
-		if(is_null($this->cache)
259
-			|| !$this->configuration->ldapCacheTTL
260
-			|| !$this->configuration->ldapConfigurationActive) {
261
-			return null;
262
-		}
263
-		$key   = $this->getCacheKey($key);
264
-		$value = base64_encode(json_encode($value));
265
-		$this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
266
-	}
267
-
268
-	public function clearCache() {
269
-		if(!is_null($this->cache)) {
270
-			$this->cache->clear($this->getCacheKey(null));
271
-		}
272
-	}
273
-
274
-	/**
275
-	 * Caches the general LDAP configuration.
276
-	 * @param bool $force optional. true, if the re-read should be forced. defaults
277
-	 * to false.
278
-	 * @return null
279
-	 */
280
-	private function readConfiguration($force = false) {
281
-		if((!$this->configured || $force) && !is_null($this->configID)) {
282
-			$this->configuration->readConfiguration();
283
-			$this->configured = $this->validateConfiguration();
284
-		}
285
-	}
286
-
287
-	/**
288
-	 * set LDAP configuration with values delivered by an array, not read from configuration
289
-	 * @param array $config array that holds the config parameters in an associated array
290
-	 * @param array &$setParameters optional; array where the set fields will be given to
291
-	 * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
292
-	 */
293
-	public function setConfiguration($config, &$setParameters = null) {
294
-		if(is_null($setParameters)) {
295
-			$setParameters = array();
296
-		}
297
-		$this->doNotValidate = false;
298
-		$this->configuration->setConfiguration($config, $setParameters);
299
-		if(count($setParameters) > 0) {
300
-			$this->configured = $this->validateConfiguration();
301
-		}
302
-
303
-
304
-		return $this->configured;
305
-	}
306
-
307
-	/**
308
-	 * saves the current Configuration in the database and empties the
309
-	 * cache
310
-	 * @return null
311
-	 */
312
-	public function saveConfiguration() {
313
-		$this->configuration->saveConfiguration();
314
-		$this->clearCache();
315
-	}
316
-
317
-	/**
318
-	 * get the current LDAP configuration
319
-	 * @return array
320
-	 */
321
-	public function getConfiguration() {
322
-		$this->readConfiguration();
323
-		$config = $this->configuration->getConfiguration();
324
-		$cta = $this->configuration->getConfigTranslationArray();
325
-		$result = array();
326
-		foreach($cta as $dbkey => $configkey) {
327
-			switch($configkey) {
328
-				case 'homeFolderNamingRule':
329
-					if(strpos($config[$configkey], 'attr:') === 0) {
330
-						$result[$dbkey] = substr($config[$configkey], 5);
331
-					} else {
332
-						$result[$dbkey] = '';
333
-					}
334
-					break;
335
-				case 'ldapBase':
336
-				case 'ldapBaseUsers':
337
-				case 'ldapBaseGroups':
338
-				case 'ldapAttributesForUserSearch':
339
-				case 'ldapAttributesForGroupSearch':
340
-					if(is_array($config[$configkey])) {
341
-						$result[$dbkey] = implode("\n", $config[$configkey]);
342
-						break;
343
-					} //else follows default
344
-				default:
345
-					$result[$dbkey] = $config[$configkey];
346
-			}
347
-		}
348
-		return $result;
349
-	}
350
-
351
-	private function doSoftValidation() {
352
-		//if User or Group Base are not set, take over Base DN setting
353
-		foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
354
-			$val = $this->configuration->$keyBase;
355
-			if(empty($val)) {
356
-				$this->configuration->$keyBase = $this->configuration->ldapBase;
357
-			}
358
-		}
359
-
360
-		foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
361
-					  'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
362
-				as $expertSetting => $effectiveSetting) {
363
-			$uuidOverride = $this->configuration->$expertSetting;
364
-			if(!empty($uuidOverride)) {
365
-				$this->configuration->$effectiveSetting = $uuidOverride;
366
-			} else {
367
-				$uuidAttributes = Access::UUID_ATTRIBUTES;
368
-				array_unshift($uuidAttributes, 'auto');
369
-				if(!in_array($this->configuration->$effectiveSetting,
370
-							$uuidAttributes)
371
-					&& (!is_null($this->configID))) {
372
-					$this->configuration->$effectiveSetting = 'auto';
373
-					$this->configuration->saveConfiguration();
374
-					\OCP\Util::writeLog('user_ldap',
375
-										'Illegal value for the '.
376
-										$effectiveSetting.', '.'reset to '.
377
-										'autodetect.', ILogger::INFO);
378
-				}
379
-
380
-			}
381
-		}
382
-
383
-		$backupPort = (int)$this->configuration->ldapBackupPort;
384
-		if ($backupPort <= 0) {
385
-			$this->configuration->backupPort = $this->configuration->ldapPort;
386
-		}
387
-
388
-		//make sure empty search attributes are saved as simple, empty array
389
-		$saKeys = array('ldapAttributesForUserSearch',
390
-						'ldapAttributesForGroupSearch');
391
-		foreach($saKeys as $key) {
392
-			$val = $this->configuration->$key;
393
-			if(is_array($val) && count($val) === 1 && empty($val[0])) {
394
-				$this->configuration->$key = array();
395
-			}
396
-		}
397
-
398
-		if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
399
-			&& $this->configuration->ldapTLS) {
400
-			$this->configuration->ldapTLS = false;
401
-			\OCP\Util::writeLog(
402
-				'user_ldap',
403
-				'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
404
-				ILogger::INFO
405
-			);
406
-		}
407
-	}
408
-
409
-	/**
410
-	 * @return bool
411
-	 */
412
-	private function doCriticalValidation() {
413
-		$configurationOK = true;
414
-		$errorStr = 'Configuration Error (prefix '.
415
-			(string)$this->configPrefix .'): ';
416
-
417
-		//options that shall not be empty
418
-		$options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
419
-						 'ldapGroupDisplayName', 'ldapLoginFilter');
420
-		foreach($options as $key) {
421
-			$val = $this->configuration->$key;
422
-			if(empty($val)) {
423
-				switch($key) {
424
-					case 'ldapHost':
425
-						$subj = 'LDAP Host';
426
-						break;
427
-					case 'ldapPort':
428
-						$subj = 'LDAP Port';
429
-						break;
430
-					case 'ldapUserDisplayName':
431
-						$subj = 'LDAP User Display Name';
432
-						break;
433
-					case 'ldapGroupDisplayName':
434
-						$subj = 'LDAP Group Display Name';
435
-						break;
436
-					case 'ldapLoginFilter':
437
-						$subj = 'LDAP Login Filter';
438
-						break;
439
-					default:
440
-						$subj = $key;
441
-						break;
442
-				}
443
-				$configurationOK = false;
444
-				\OCP\Util::writeLog(
445
-					'user_ldap',
446
-					$errorStr.'No '.$subj.' given!',
447
-					ILogger::WARN
448
-				);
449
-			}
450
-		}
451
-
452
-		//combinations
453
-		$agent = $this->configuration->ldapAgentName;
454
-		$pwd = $this->configuration->ldapAgentPassword;
455
-		if (
456
-			($agent === ''  && $pwd !== '')
457
-			|| ($agent !== '' && $pwd === '')
458
-		) {
459
-			\OCP\Util::writeLog(
460
-				'user_ldap',
461
-				$errorStr.'either no password is given for the user ' .
462
-					'agent or a password is given, but not an LDAP agent.',
463
-				ILogger::WARN);
464
-			$configurationOK = false;
465
-		}
466
-
467
-		$base = $this->configuration->ldapBase;
468
-		$baseUsers = $this->configuration->ldapBaseUsers;
469
-		$baseGroups = $this->configuration->ldapBaseGroups;
470
-
471
-		if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
472
-			\OCP\Util::writeLog(
473
-				'user_ldap',
474
-				$errorStr.'Not a single Base DN given.',
475
-				ILogger::WARN
476
-			);
477
-			$configurationOK = false;
478
-		}
479
-
480
-		if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
481
-		   === false) {
482
-			\OCP\Util::writeLog(
483
-				'user_ldap',
484
-				$errorStr.'login filter does not contain %uid place holder.',
485
-				ILogger::WARN
486
-			);
487
-			$configurationOK = false;
488
-		}
489
-
490
-		return $configurationOK;
491
-	}
492
-
493
-	/**
494
-	 * Validates the user specified configuration
495
-	 * @return bool true if configuration seems OK, false otherwise
496
-	 */
497
-	private function validateConfiguration() {
498
-
499
-		if($this->doNotValidate) {
500
-			//don't do a validation if it is a new configuration with pure
501
-			//default values. Will be allowed on changes via __set or
502
-			//setConfiguration
503
-			return false;
504
-		}
505
-
506
-		// first step: "soft" checks: settings that are not really
507
-		// necessary, but advisable. If left empty, give an info message
508
-		$this->doSoftValidation();
509
-
510
-		//second step: critical checks. If left empty or filled wrong, mark as
511
-		//not configured and give a warning.
512
-		return $this->doCriticalValidation();
513
-	}
514
-
515
-
516
-	/**
517
-	 * Connects and Binds to LDAP
518
-	 *
519
-	 * @throws ServerNotAvailableException
520
-	 */
521
-	private function establishConnection() {
522
-		if(!$this->configuration->ldapConfigurationActive) {
523
-			return null;
524
-		}
525
-		static $phpLDAPinstalled = true;
526
-		if(!$phpLDAPinstalled) {
527
-			return false;
528
-		}
529
-		if(!$this->ignoreValidation && !$this->configured) {
530
-			\OCP\Util::writeLog(
531
-				'user_ldap',
532
-				'Configuration is invalid, cannot connect',
533
-				ILogger::WARN
534
-			);
535
-			return false;
536
-		}
537
-		if(!$this->ldapConnectionRes) {
538
-			if(!$this->ldap->areLDAPFunctionsAvailable()) {
539
-				$phpLDAPinstalled = false;
540
-				\OCP\Util::writeLog(
541
-					'user_ldap',
542
-					'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
543
-					ILogger::ERROR
544
-				);
545
-
546
-				return false;
547
-			}
548
-			if($this->configuration->turnOffCertCheck) {
549
-				if(putenv('LDAPTLS_REQCERT=never')) {
550
-					\OCP\Util::writeLog('user_ldap',
551
-						'Turned off SSL certificate validation successfully.',
552
-						ILogger::DEBUG);
553
-				} else {
554
-					\OCP\Util::writeLog(
555
-						'user_ldap',
556
-						'Could not turn off SSL certificate validation.',
557
-						ILogger::WARN
558
-					);
559
-				}
560
-			}
561
-
562
-			$isOverrideMainServer = ($this->configuration->ldapOverrideMainServer
563
-				|| $this->getFromCache('overrideMainServer'));
564
-			$isBackupHost = (trim($this->configuration->ldapBackupHost) !== "");
565
-			$bindStatus = false;
566
-			try {
567
-				if (!$isOverrideMainServer) {
568
-					$this->doConnect($this->configuration->ldapHost,
569
-						$this->configuration->ldapPort);
570
-					return $this->bind();
571
-				}
572
-			} catch (ServerNotAvailableException $e) {
573
-				if(!$isBackupHost) {
574
-					throw $e;
575
-				}
576
-			}
577
-
578
-			//if LDAP server is not reachable, try the Backup (Replica!) Server
579
-			if($isBackupHost || $isOverrideMainServer) {
580
-				$this->doConnect($this->configuration->ldapBackupHost,
581
-								 $this->configuration->ldapBackupPort);
582
-				$this->bindResult = [];
583
-				$bindStatus = $this->bind();
584
-				$error = $this->ldap->isResource($this->ldapConnectionRes) ?
585
-					$this->ldap->errno($this->ldapConnectionRes) : -1;
586
-				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
587
-					//when bind to backup server succeeded and failed to main server,
588
-					//skip contacting him until next cache refresh
589
-					$this->writeToCache('overrideMainServer', true);
590
-				}
591
-			}
592
-
593
-			return $bindStatus;
594
-		}
595
-		return null;
596
-	}
597
-
598
-	/**
599
-	 * @param string $host
600
-	 * @param string $port
601
-	 * @return bool
602
-	 * @throws \OC\ServerNotAvailableException
603
-	 */
604
-	private function doConnect($host, $port) {
605
-		if ($host === '') {
606
-			return false;
607
-		}
608
-
609
-		$this->ldapConnectionRes = $this->ldap->connect($host, $port);
610
-
611
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
612
-			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
613
-		}
614
-
615
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
616
-			throw new ServerNotAvailableException('Could not disable LDAP referrals.');
617
-		}
618
-
619
-		if($this->configuration->ldapTLS) {
620
-			if(!$this->ldap->startTls($this->ldapConnectionRes)) {
621
-				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
622
-			}
623
-		}
624
-
625
-		return true;
626
-	}
627
-
628
-	/**
629
-	 * Binds to LDAP
630
-	 */
631
-	public function bind() {
632
-		if(!$this->configuration->ldapConfigurationActive) {
633
-			return false;
634
-		}
635
-		$cr = $this->ldapConnectionRes;
636
-		if(!$this->ldap->isResource($cr)) {
637
-			$cr = $this->getConnectionResource();
638
-		}
639
-
640
-		if(
641
-			count($this->bindResult) !== 0
642
-			&& $this->bindResult['dn'] === $this->configuration->ldapAgentName
643
-			&& \OC::$server->getHasher()->verify(
644
-				$this->configPrefix . $this->configuration->ldapAgentPassword,
645
-				$this->bindResult['hash']
646
-			)
647
-		) {
648
-			// don't attempt to bind again with the same data as before
649
-			// bind might have been invoked via getConnectionResource(),
650
-			// but we need results specifically for e.g. user login
651
-			return $this->bindResult['result'];
652
-		}
653
-
654
-		$ldapLogin = @$this->ldap->bind($cr,
655
-										$this->configuration->ldapAgentName,
656
-										$this->configuration->ldapAgentPassword);
657
-
658
-		$this->bindResult = [
659
-			'dn' => $this->configuration->ldapAgentName,
660
-			'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword),
661
-			'result' => $ldapLogin,
662
-		];
663
-
664
-		if(!$ldapLogin) {
665
-			$errno = $this->ldap->errno($cr);
666
-
667
-			\OCP\Util::writeLog('user_ldap',
668
-				'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
669
-				ILogger::WARN);
670
-
671
-			// Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
672
-			if($errno !== 0x00 && $errno !== 0x31) {
673
-				$this->ldapConnectionRes = null;
674
-			}
675
-
676
-			return false;
677
-		}
678
-		return true;
679
-	}
65
+    private $ldapConnectionRes = null;
66
+    private $configPrefix;
67
+    private $configID;
68
+    private $configured = false;
69
+    //whether connection should be kept on __destruct
70
+    private $dontDestruct = false;
71
+
72
+    /**
73
+     * @var bool runtime flag that indicates whether supported primary groups are available
74
+     */
75
+    public $hasPrimaryGroups = true;
76
+
77
+    /**
78
+     * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
79
+     */
80
+    public $hasGidNumber = true;
81
+
82
+    //cache handler
83
+    protected $cache;
84
+
85
+    /** @var Configuration settings handler **/
86
+    protected $configuration;
87
+
88
+    protected $doNotValidate = false;
89
+
90
+    protected $ignoreValidation = false;
91
+
92
+    protected $bindResult = [];
93
+
94
+    /**
95
+     * Constructor
96
+     * @param ILDAPWrapper $ldap
97
+     * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
98
+     * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
99
+     */
100
+    public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
101
+        parent::__construct($ldap);
102
+        $this->configPrefix = $configPrefix;
103
+        $this->configID = $configID;
104
+        $this->configuration = new Configuration($configPrefix,
105
+                                                    !is_null($configID));
106
+        $memcache = \OC::$server->getMemCacheFactory();
107
+        if($memcache->isAvailable()) {
108
+            $this->cache = $memcache->createDistributed();
109
+        }
110
+        $helper = new Helper(\OC::$server->getConfig());
111
+        $this->doNotValidate = !in_array($this->configPrefix,
112
+            $helper->getServerConfigurationPrefixes());
113
+    }
114
+
115
+    public function __destruct() {
116
+        if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
117
+            @$this->ldap->unbind($this->ldapConnectionRes);
118
+            $this->bindResult = [];
119
+        }
120
+    }
121
+
122
+    /**
123
+     * defines behaviour when the instance is cloned
124
+     */
125
+    public function __clone() {
126
+        $this->configuration = new Configuration($this->configPrefix,
127
+                                                    !is_null($this->configID));
128
+        if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
129
+            $this->bindResult = [];
130
+        }
131
+        $this->ldapConnectionRes = null;
132
+        $this->dontDestruct = true;
133
+    }
134
+
135
+    /**
136
+     * @param string $name
137
+     * @return bool|mixed
138
+     */
139
+    public function __get($name) {
140
+        if(!$this->configured) {
141
+            $this->readConfiguration();
142
+        }
143
+
144
+        return $this->configuration->$name;
145
+    }
146
+
147
+    /**
148
+     * @param string $name
149
+     * @param mixed $value
150
+     */
151
+    public function __set($name, $value) {
152
+        $this->doNotValidate = false;
153
+        $before = $this->configuration->$name;
154
+        $this->configuration->$name = $value;
155
+        $after = $this->configuration->$name;
156
+        if($before !== $after) {
157
+            if ($this->configID !== '' && $this->configID !== null) {
158
+                $this->configuration->saveConfiguration();
159
+            }
160
+            $this->validateConfiguration();
161
+        }
162
+    }
163
+
164
+    /**
165
+     * @param string $rule
166
+     * @return array
167
+     * @throws \RuntimeException
168
+     */
169
+    public function resolveRule($rule) {
170
+        return $this->configuration->resolveRule($rule);
171
+    }
172
+
173
+    /**
174
+     * sets whether the result of the configuration validation shall
175
+     * be ignored when establishing the connection. Used by the Wizard
176
+     * in early configuration state.
177
+     * @param bool $state
178
+     */
179
+    public function setIgnoreValidation($state) {
180
+        $this->ignoreValidation = (bool)$state;
181
+    }
182
+
183
+    /**
184
+     * initializes the LDAP backend
185
+     * @param bool $force read the config settings no matter what
186
+     */
187
+    public function init($force = false) {
188
+        $this->readConfiguration($force);
189
+        $this->establishConnection();
190
+    }
191
+
192
+    /**
193
+     * Returns the LDAP handler
194
+     */
195
+    public function getConnectionResource() {
196
+        if(!$this->ldapConnectionRes) {
197
+            $this->init();
198
+        } else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
199
+            $this->ldapConnectionRes = null;
200
+            $this->establishConnection();
201
+        }
202
+        if(is_null($this->ldapConnectionRes)) {
203
+            \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR);
204
+            throw new ServerNotAvailableException('Connection to LDAP server could not be established');
205
+        }
206
+        return $this->ldapConnectionRes;
207
+    }
208
+
209
+    /**
210
+     * resets the connection resource
211
+     */
212
+    public function resetConnectionResource() {
213
+        if(!is_null($this->ldapConnectionRes)) {
214
+            @$this->ldap->unbind($this->ldapConnectionRes);
215
+            $this->ldapConnectionRes = null;
216
+            $this->bindResult = [];
217
+        }
218
+    }
219
+
220
+    /**
221
+     * @param string|null $key
222
+     * @return string
223
+     */
224
+    private function getCacheKey($key) {
225
+        $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
226
+        if(is_null($key)) {
227
+            return $prefix;
228
+        }
229
+        return $prefix.hash('sha256', $key);
230
+    }
231
+
232
+    /**
233
+     * @param string $key
234
+     * @return mixed|null
235
+     */
236
+    public function getFromCache($key) {
237
+        if(!$this->configured) {
238
+            $this->readConfiguration();
239
+        }
240
+        if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
241
+            return null;
242
+        }
243
+        $key = $this->getCacheKey($key);
244
+
245
+        return json_decode(base64_decode($this->cache->get($key)), true);
246
+    }
247
+
248
+    /**
249
+     * @param string $key
250
+     * @param mixed $value
251
+     *
252
+     * @return string
253
+     */
254
+    public function writeToCache($key, $value) {
255
+        if(!$this->configured) {
256
+            $this->readConfiguration();
257
+        }
258
+        if(is_null($this->cache)
259
+            || !$this->configuration->ldapCacheTTL
260
+            || !$this->configuration->ldapConfigurationActive) {
261
+            return null;
262
+        }
263
+        $key   = $this->getCacheKey($key);
264
+        $value = base64_encode(json_encode($value));
265
+        $this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
266
+    }
267
+
268
+    public function clearCache() {
269
+        if(!is_null($this->cache)) {
270
+            $this->cache->clear($this->getCacheKey(null));
271
+        }
272
+    }
273
+
274
+    /**
275
+     * Caches the general LDAP configuration.
276
+     * @param bool $force optional. true, if the re-read should be forced. defaults
277
+     * to false.
278
+     * @return null
279
+     */
280
+    private function readConfiguration($force = false) {
281
+        if((!$this->configured || $force) && !is_null($this->configID)) {
282
+            $this->configuration->readConfiguration();
283
+            $this->configured = $this->validateConfiguration();
284
+        }
285
+    }
286
+
287
+    /**
288
+     * set LDAP configuration with values delivered by an array, not read from configuration
289
+     * @param array $config array that holds the config parameters in an associated array
290
+     * @param array &$setParameters optional; array where the set fields will be given to
291
+     * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
292
+     */
293
+    public function setConfiguration($config, &$setParameters = null) {
294
+        if(is_null($setParameters)) {
295
+            $setParameters = array();
296
+        }
297
+        $this->doNotValidate = false;
298
+        $this->configuration->setConfiguration($config, $setParameters);
299
+        if(count($setParameters) > 0) {
300
+            $this->configured = $this->validateConfiguration();
301
+        }
302
+
303
+
304
+        return $this->configured;
305
+    }
306
+
307
+    /**
308
+     * saves the current Configuration in the database and empties the
309
+     * cache
310
+     * @return null
311
+     */
312
+    public function saveConfiguration() {
313
+        $this->configuration->saveConfiguration();
314
+        $this->clearCache();
315
+    }
316
+
317
+    /**
318
+     * get the current LDAP configuration
319
+     * @return array
320
+     */
321
+    public function getConfiguration() {
322
+        $this->readConfiguration();
323
+        $config = $this->configuration->getConfiguration();
324
+        $cta = $this->configuration->getConfigTranslationArray();
325
+        $result = array();
326
+        foreach($cta as $dbkey => $configkey) {
327
+            switch($configkey) {
328
+                case 'homeFolderNamingRule':
329
+                    if(strpos($config[$configkey], 'attr:') === 0) {
330
+                        $result[$dbkey] = substr($config[$configkey], 5);
331
+                    } else {
332
+                        $result[$dbkey] = '';
333
+                    }
334
+                    break;
335
+                case 'ldapBase':
336
+                case 'ldapBaseUsers':
337
+                case 'ldapBaseGroups':
338
+                case 'ldapAttributesForUserSearch':
339
+                case 'ldapAttributesForGroupSearch':
340
+                    if(is_array($config[$configkey])) {
341
+                        $result[$dbkey] = implode("\n", $config[$configkey]);
342
+                        break;
343
+                    } //else follows default
344
+                default:
345
+                    $result[$dbkey] = $config[$configkey];
346
+            }
347
+        }
348
+        return $result;
349
+    }
350
+
351
+    private function doSoftValidation() {
352
+        //if User or Group Base are not set, take over Base DN setting
353
+        foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
354
+            $val = $this->configuration->$keyBase;
355
+            if(empty($val)) {
356
+                $this->configuration->$keyBase = $this->configuration->ldapBase;
357
+            }
358
+        }
359
+
360
+        foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
361
+                        'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
362
+                as $expertSetting => $effectiveSetting) {
363
+            $uuidOverride = $this->configuration->$expertSetting;
364
+            if(!empty($uuidOverride)) {
365
+                $this->configuration->$effectiveSetting = $uuidOverride;
366
+            } else {
367
+                $uuidAttributes = Access::UUID_ATTRIBUTES;
368
+                array_unshift($uuidAttributes, 'auto');
369
+                if(!in_array($this->configuration->$effectiveSetting,
370
+                            $uuidAttributes)
371
+                    && (!is_null($this->configID))) {
372
+                    $this->configuration->$effectiveSetting = 'auto';
373
+                    $this->configuration->saveConfiguration();
374
+                    \OCP\Util::writeLog('user_ldap',
375
+                                        'Illegal value for the '.
376
+                                        $effectiveSetting.', '.'reset to '.
377
+                                        'autodetect.', ILogger::INFO);
378
+                }
379
+
380
+            }
381
+        }
382
+
383
+        $backupPort = (int)$this->configuration->ldapBackupPort;
384
+        if ($backupPort <= 0) {
385
+            $this->configuration->backupPort = $this->configuration->ldapPort;
386
+        }
387
+
388
+        //make sure empty search attributes are saved as simple, empty array
389
+        $saKeys = array('ldapAttributesForUserSearch',
390
+                        'ldapAttributesForGroupSearch');
391
+        foreach($saKeys as $key) {
392
+            $val = $this->configuration->$key;
393
+            if(is_array($val) && count($val) === 1 && empty($val[0])) {
394
+                $this->configuration->$key = array();
395
+            }
396
+        }
397
+
398
+        if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
399
+            && $this->configuration->ldapTLS) {
400
+            $this->configuration->ldapTLS = false;
401
+            \OCP\Util::writeLog(
402
+                'user_ldap',
403
+                'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
404
+                ILogger::INFO
405
+            );
406
+        }
407
+    }
408
+
409
+    /**
410
+     * @return bool
411
+     */
412
+    private function doCriticalValidation() {
413
+        $configurationOK = true;
414
+        $errorStr = 'Configuration Error (prefix '.
415
+            (string)$this->configPrefix .'): ';
416
+
417
+        //options that shall not be empty
418
+        $options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
419
+                            'ldapGroupDisplayName', 'ldapLoginFilter');
420
+        foreach($options as $key) {
421
+            $val = $this->configuration->$key;
422
+            if(empty($val)) {
423
+                switch($key) {
424
+                    case 'ldapHost':
425
+                        $subj = 'LDAP Host';
426
+                        break;
427
+                    case 'ldapPort':
428
+                        $subj = 'LDAP Port';
429
+                        break;
430
+                    case 'ldapUserDisplayName':
431
+                        $subj = 'LDAP User Display Name';
432
+                        break;
433
+                    case 'ldapGroupDisplayName':
434
+                        $subj = 'LDAP Group Display Name';
435
+                        break;
436
+                    case 'ldapLoginFilter':
437
+                        $subj = 'LDAP Login Filter';
438
+                        break;
439
+                    default:
440
+                        $subj = $key;
441
+                        break;
442
+                }
443
+                $configurationOK = false;
444
+                \OCP\Util::writeLog(
445
+                    'user_ldap',
446
+                    $errorStr.'No '.$subj.' given!',
447
+                    ILogger::WARN
448
+                );
449
+            }
450
+        }
451
+
452
+        //combinations
453
+        $agent = $this->configuration->ldapAgentName;
454
+        $pwd = $this->configuration->ldapAgentPassword;
455
+        if (
456
+            ($agent === ''  && $pwd !== '')
457
+            || ($agent !== '' && $pwd === '')
458
+        ) {
459
+            \OCP\Util::writeLog(
460
+                'user_ldap',
461
+                $errorStr.'either no password is given for the user ' .
462
+                    'agent or a password is given, but not an LDAP agent.',
463
+                ILogger::WARN);
464
+            $configurationOK = false;
465
+        }
466
+
467
+        $base = $this->configuration->ldapBase;
468
+        $baseUsers = $this->configuration->ldapBaseUsers;
469
+        $baseGroups = $this->configuration->ldapBaseGroups;
470
+
471
+        if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
472
+            \OCP\Util::writeLog(
473
+                'user_ldap',
474
+                $errorStr.'Not a single Base DN given.',
475
+                ILogger::WARN
476
+            );
477
+            $configurationOK = false;
478
+        }
479
+
480
+        if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
481
+            === false) {
482
+            \OCP\Util::writeLog(
483
+                'user_ldap',
484
+                $errorStr.'login filter does not contain %uid place holder.',
485
+                ILogger::WARN
486
+            );
487
+            $configurationOK = false;
488
+        }
489
+
490
+        return $configurationOK;
491
+    }
492
+
493
+    /**
494
+     * Validates the user specified configuration
495
+     * @return bool true if configuration seems OK, false otherwise
496
+     */
497
+    private function validateConfiguration() {
498
+
499
+        if($this->doNotValidate) {
500
+            //don't do a validation if it is a new configuration with pure
501
+            //default values. Will be allowed on changes via __set or
502
+            //setConfiguration
503
+            return false;
504
+        }
505
+
506
+        // first step: "soft" checks: settings that are not really
507
+        // necessary, but advisable. If left empty, give an info message
508
+        $this->doSoftValidation();
509
+
510
+        //second step: critical checks. If left empty or filled wrong, mark as
511
+        //not configured and give a warning.
512
+        return $this->doCriticalValidation();
513
+    }
514
+
515
+
516
+    /**
517
+     * Connects and Binds to LDAP
518
+     *
519
+     * @throws ServerNotAvailableException
520
+     */
521
+    private function establishConnection() {
522
+        if(!$this->configuration->ldapConfigurationActive) {
523
+            return null;
524
+        }
525
+        static $phpLDAPinstalled = true;
526
+        if(!$phpLDAPinstalled) {
527
+            return false;
528
+        }
529
+        if(!$this->ignoreValidation && !$this->configured) {
530
+            \OCP\Util::writeLog(
531
+                'user_ldap',
532
+                'Configuration is invalid, cannot connect',
533
+                ILogger::WARN
534
+            );
535
+            return false;
536
+        }
537
+        if(!$this->ldapConnectionRes) {
538
+            if(!$this->ldap->areLDAPFunctionsAvailable()) {
539
+                $phpLDAPinstalled = false;
540
+                \OCP\Util::writeLog(
541
+                    'user_ldap',
542
+                    'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
543
+                    ILogger::ERROR
544
+                );
545
+
546
+                return false;
547
+            }
548
+            if($this->configuration->turnOffCertCheck) {
549
+                if(putenv('LDAPTLS_REQCERT=never')) {
550
+                    \OCP\Util::writeLog('user_ldap',
551
+                        'Turned off SSL certificate validation successfully.',
552
+                        ILogger::DEBUG);
553
+                } else {
554
+                    \OCP\Util::writeLog(
555
+                        'user_ldap',
556
+                        'Could not turn off SSL certificate validation.',
557
+                        ILogger::WARN
558
+                    );
559
+                }
560
+            }
561
+
562
+            $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer
563
+                || $this->getFromCache('overrideMainServer'));
564
+            $isBackupHost = (trim($this->configuration->ldapBackupHost) !== "");
565
+            $bindStatus = false;
566
+            try {
567
+                if (!$isOverrideMainServer) {
568
+                    $this->doConnect($this->configuration->ldapHost,
569
+                        $this->configuration->ldapPort);
570
+                    return $this->bind();
571
+                }
572
+            } catch (ServerNotAvailableException $e) {
573
+                if(!$isBackupHost) {
574
+                    throw $e;
575
+                }
576
+            }
577
+
578
+            //if LDAP server is not reachable, try the Backup (Replica!) Server
579
+            if($isBackupHost || $isOverrideMainServer) {
580
+                $this->doConnect($this->configuration->ldapBackupHost,
581
+                                    $this->configuration->ldapBackupPort);
582
+                $this->bindResult = [];
583
+                $bindStatus = $this->bind();
584
+                $error = $this->ldap->isResource($this->ldapConnectionRes) ?
585
+                    $this->ldap->errno($this->ldapConnectionRes) : -1;
586
+                if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
587
+                    //when bind to backup server succeeded and failed to main server,
588
+                    //skip contacting him until next cache refresh
589
+                    $this->writeToCache('overrideMainServer', true);
590
+                }
591
+            }
592
+
593
+            return $bindStatus;
594
+        }
595
+        return null;
596
+    }
597
+
598
+    /**
599
+     * @param string $host
600
+     * @param string $port
601
+     * @return bool
602
+     * @throws \OC\ServerNotAvailableException
603
+     */
604
+    private function doConnect($host, $port) {
605
+        if ($host === '') {
606
+            return false;
607
+        }
608
+
609
+        $this->ldapConnectionRes = $this->ldap->connect($host, $port);
610
+
611
+        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
612
+            throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
613
+        }
614
+
615
+        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
616
+            throw new ServerNotAvailableException('Could not disable LDAP referrals.');
617
+        }
618
+
619
+        if($this->configuration->ldapTLS) {
620
+            if(!$this->ldap->startTls($this->ldapConnectionRes)) {
621
+                throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
622
+            }
623
+        }
624
+
625
+        return true;
626
+    }
627
+
628
+    /**
629
+     * Binds to LDAP
630
+     */
631
+    public function bind() {
632
+        if(!$this->configuration->ldapConfigurationActive) {
633
+            return false;
634
+        }
635
+        $cr = $this->ldapConnectionRes;
636
+        if(!$this->ldap->isResource($cr)) {
637
+            $cr = $this->getConnectionResource();
638
+        }
639
+
640
+        if(
641
+            count($this->bindResult) !== 0
642
+            && $this->bindResult['dn'] === $this->configuration->ldapAgentName
643
+            && \OC::$server->getHasher()->verify(
644
+                $this->configPrefix . $this->configuration->ldapAgentPassword,
645
+                $this->bindResult['hash']
646
+            )
647
+        ) {
648
+            // don't attempt to bind again with the same data as before
649
+            // bind might have been invoked via getConnectionResource(),
650
+            // but we need results specifically for e.g. user login
651
+            return $this->bindResult['result'];
652
+        }
653
+
654
+        $ldapLogin = @$this->ldap->bind($cr,
655
+                                        $this->configuration->ldapAgentName,
656
+                                        $this->configuration->ldapAgentPassword);
657
+
658
+        $this->bindResult = [
659
+            'dn' => $this->configuration->ldapAgentName,
660
+            'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword),
661
+            'result' => $ldapLogin,
662
+        ];
663
+
664
+        if(!$ldapLogin) {
665
+            $errno = $this->ldap->errno($cr);
666
+
667
+            \OCP\Util::writeLog('user_ldap',
668
+                'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
669
+                ILogger::WARN);
670
+
671
+            // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
672
+            if($errno !== 0x00 && $errno !== 0x31) {
673
+                $this->ldapConnectionRes = null;
674
+            }
675
+
676
+            return false;
677
+        }
678
+        return true;
679
+    }
680 680
 
681 681
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -104,7 +104,7 @@  discard block
 block discarded – undo
104 104
 		$this->configuration = new Configuration($configPrefix,
105 105
 												 !is_null($configID));
106 106
 		$memcache = \OC::$server->getMemCacheFactory();
107
-		if($memcache->isAvailable()) {
107
+		if ($memcache->isAvailable()) {
108 108
 			$this->cache = $memcache->createDistributed();
109 109
 		}
110 110
 		$helper = new Helper(\OC::$server->getConfig());
@@ -113,7 +113,7 @@  discard block
 block discarded – undo
113 113
 	}
114 114
 
115 115
 	public function __destruct() {
116
-		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
116
+		if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
117 117
 			@$this->ldap->unbind($this->ldapConnectionRes);
118 118
 			$this->bindResult = [];
119 119
 		}
@@ -125,7 +125,7 @@  discard block
 block discarded – undo
125 125
 	public function __clone() {
126 126
 		$this->configuration = new Configuration($this->configPrefix,
127 127
 												 !is_null($this->configID));
128
-		if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
128
+		if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
129 129
 			$this->bindResult = [];
130 130
 		}
131 131
 		$this->ldapConnectionRes = null;
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 	 * @return bool|mixed
138 138
 	 */
139 139
 	public function __get($name) {
140
-		if(!$this->configured) {
140
+		if (!$this->configured) {
141 141
 			$this->readConfiguration();
142 142
 		}
143 143
 
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 		$before = $this->configuration->$name;
154 154
 		$this->configuration->$name = $value;
155 155
 		$after = $this->configuration->$name;
156
-		if($before !== $after) {
156
+		if ($before !== $after) {
157 157
 			if ($this->configID !== '' && $this->configID !== null) {
158 158
 				$this->configuration->saveConfiguration();
159 159
 			}
@@ -177,7 +177,7 @@  discard block
 block discarded – undo
177 177
 	 * @param bool $state
178 178
 	 */
179 179
 	public function setIgnoreValidation($state) {
180
-		$this->ignoreValidation = (bool)$state;
180
+		$this->ignoreValidation = (bool) $state;
181 181
 	}
182 182
 
183 183
 	/**
@@ -193,14 +193,14 @@  discard block
 block discarded – undo
193 193
 	 * Returns the LDAP handler
194 194
 	 */
195 195
 	public function getConnectionResource() {
196
-		if(!$this->ldapConnectionRes) {
196
+		if (!$this->ldapConnectionRes) {
197 197
 			$this->init();
198
-		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
198
+		} else if (!$this->ldap->isResource($this->ldapConnectionRes)) {
199 199
 			$this->ldapConnectionRes = null;
200 200
 			$this->establishConnection();
201 201
 		}
202
-		if(is_null($this->ldapConnectionRes)) {
203
-			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR);
202
+		if (is_null($this->ldapConnectionRes)) {
203
+			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server '.$this->configuration->ldapHost, ILogger::ERROR);
204 204
 			throw new ServerNotAvailableException('Connection to LDAP server could not be established');
205 205
 		}
206 206
 		return $this->ldapConnectionRes;
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 	 * resets the connection resource
211 211
 	 */
212 212
 	public function resetConnectionResource() {
213
-		if(!is_null($this->ldapConnectionRes)) {
213
+		if (!is_null($this->ldapConnectionRes)) {
214 214
 			@$this->ldap->unbind($this->ldapConnectionRes);
215 215
 			$this->ldapConnectionRes = null;
216 216
 			$this->bindResult = [];
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	 */
224 224
 	private function getCacheKey($key) {
225 225
 		$prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
226
-		if(is_null($key)) {
226
+		if (is_null($key)) {
227 227
 			return $prefix;
228 228
 		}
229 229
 		return $prefix.hash('sha256', $key);
@@ -234,10 +234,10 @@  discard block
 block discarded – undo
234 234
 	 * @return mixed|null
235 235
 	 */
236 236
 	public function getFromCache($key) {
237
-		if(!$this->configured) {
237
+		if (!$this->configured) {
238 238
 			$this->readConfiguration();
239 239
 		}
240
-		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
240
+		if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
241 241
 			return null;
242 242
 		}
243 243
 		$key = $this->getCacheKey($key);
@@ -252,10 +252,10 @@  discard block
 block discarded – undo
252 252
 	 * @return string
253 253
 	 */
254 254
 	public function writeToCache($key, $value) {
255
-		if(!$this->configured) {
255
+		if (!$this->configured) {
256 256
 			$this->readConfiguration();
257 257
 		}
258
-		if(is_null($this->cache)
258
+		if (is_null($this->cache)
259 259
 			|| !$this->configuration->ldapCacheTTL
260 260
 			|| !$this->configuration->ldapConfigurationActive) {
261 261
 			return null;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	}
267 267
 
268 268
 	public function clearCache() {
269
-		if(!is_null($this->cache)) {
269
+		if (!is_null($this->cache)) {
270 270
 			$this->cache->clear($this->getCacheKey(null));
271 271
 		}
272 272
 	}
@@ -278,7 +278,7 @@  discard block
 block discarded – undo
278 278
 	 * @return null
279 279
 	 */
280 280
 	private function readConfiguration($force = false) {
281
-		if((!$this->configured || $force) && !is_null($this->configID)) {
281
+		if ((!$this->configured || $force) && !is_null($this->configID)) {
282 282
 			$this->configuration->readConfiguration();
283 283
 			$this->configured = $this->validateConfiguration();
284 284
 		}
@@ -291,12 +291,12 @@  discard block
 block discarded – undo
291 291
 	 * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
292 292
 	 */
293 293
 	public function setConfiguration($config, &$setParameters = null) {
294
-		if(is_null($setParameters)) {
294
+		if (is_null($setParameters)) {
295 295
 			$setParameters = array();
296 296
 		}
297 297
 		$this->doNotValidate = false;
298 298
 		$this->configuration->setConfiguration($config, $setParameters);
299
-		if(count($setParameters) > 0) {
299
+		if (count($setParameters) > 0) {
300 300
 			$this->configured = $this->validateConfiguration();
301 301
 		}
302 302
 
@@ -323,10 +323,10 @@  discard block
 block discarded – undo
323 323
 		$config = $this->configuration->getConfiguration();
324 324
 		$cta = $this->configuration->getConfigTranslationArray();
325 325
 		$result = array();
326
-		foreach($cta as $dbkey => $configkey) {
327
-			switch($configkey) {
326
+		foreach ($cta as $dbkey => $configkey) {
327
+			switch ($configkey) {
328 328
 				case 'homeFolderNamingRule':
329
-					if(strpos($config[$configkey], 'attr:') === 0) {
329
+					if (strpos($config[$configkey], 'attr:') === 0) {
330 330
 						$result[$dbkey] = substr($config[$configkey], 5);
331 331
 					} else {
332 332
 						$result[$dbkey] = '';
@@ -337,7 +337,7 @@  discard block
 block discarded – undo
337 337
 				case 'ldapBaseGroups':
338 338
 				case 'ldapAttributesForUserSearch':
339 339
 				case 'ldapAttributesForGroupSearch':
340
-					if(is_array($config[$configkey])) {
340
+					if (is_array($config[$configkey])) {
341 341
 						$result[$dbkey] = implode("\n", $config[$configkey]);
342 342
 						break;
343 343
 					} //else follows default
@@ -350,23 +350,23 @@  discard block
 block discarded – undo
350 350
 
351 351
 	private function doSoftValidation() {
352 352
 		//if User or Group Base are not set, take over Base DN setting
353
-		foreach(array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
353
+		foreach (array('ldapBaseUsers', 'ldapBaseGroups') as $keyBase) {
354 354
 			$val = $this->configuration->$keyBase;
355
-			if(empty($val)) {
355
+			if (empty($val)) {
356 356
 				$this->configuration->$keyBase = $this->configuration->ldapBase;
357 357
 			}
358 358
 		}
359 359
 
360
-		foreach(array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
360
+		foreach (array('ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
361 361
 					  'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute')
362 362
 				as $expertSetting => $effectiveSetting) {
363 363
 			$uuidOverride = $this->configuration->$expertSetting;
364
-			if(!empty($uuidOverride)) {
364
+			if (!empty($uuidOverride)) {
365 365
 				$this->configuration->$effectiveSetting = $uuidOverride;
366 366
 			} else {
367 367
 				$uuidAttributes = Access::UUID_ATTRIBUTES;
368 368
 				array_unshift($uuidAttributes, 'auto');
369
-				if(!in_array($this->configuration->$effectiveSetting,
369
+				if (!in_array($this->configuration->$effectiveSetting,
370 370
 							$uuidAttributes)
371 371
 					&& (!is_null($this->configID))) {
372 372
 					$this->configuration->$effectiveSetting = 'auto';
@@ -380,7 +380,7 @@  discard block
 block discarded – undo
380 380
 			}
381 381
 		}
382 382
 
383
-		$backupPort = (int)$this->configuration->ldapBackupPort;
383
+		$backupPort = (int) $this->configuration->ldapBackupPort;
384 384
 		if ($backupPort <= 0) {
385 385
 			$this->configuration->backupPort = $this->configuration->ldapPort;
386 386
 		}
@@ -388,14 +388,14 @@  discard block
 block discarded – undo
388 388
 		//make sure empty search attributes are saved as simple, empty array
389 389
 		$saKeys = array('ldapAttributesForUserSearch',
390 390
 						'ldapAttributesForGroupSearch');
391
-		foreach($saKeys as $key) {
391
+		foreach ($saKeys as $key) {
392 392
 			$val = $this->configuration->$key;
393
-			if(is_array($val) && count($val) === 1 && empty($val[0])) {
393
+			if (is_array($val) && count($val) === 1 && empty($val[0])) {
394 394
 				$this->configuration->$key = array();
395 395
 			}
396 396
 		}
397 397
 
398
-		if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
398
+		if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
399 399
 			&& $this->configuration->ldapTLS) {
400 400
 			$this->configuration->ldapTLS = false;
401 401
 			\OCP\Util::writeLog(
@@ -412,15 +412,15 @@  discard block
 block discarded – undo
412 412
 	private function doCriticalValidation() {
413 413
 		$configurationOK = true;
414 414
 		$errorStr = 'Configuration Error (prefix '.
415
-			(string)$this->configPrefix .'): ';
415
+			(string) $this->configPrefix.'): ';
416 416
 
417 417
 		//options that shall not be empty
418 418
 		$options = array('ldapHost', 'ldapPort', 'ldapUserDisplayName',
419 419
 						 'ldapGroupDisplayName', 'ldapLoginFilter');
420
-		foreach($options as $key) {
420
+		foreach ($options as $key) {
421 421
 			$val = $this->configuration->$key;
422
-			if(empty($val)) {
423
-				switch($key) {
422
+			if (empty($val)) {
423
+				switch ($key) {
424 424
 					case 'ldapHost':
425 425
 						$subj = 'LDAP Host';
426 426
 						break;
@@ -453,12 +453,12 @@  discard block
 block discarded – undo
453 453
 		$agent = $this->configuration->ldapAgentName;
454 454
 		$pwd = $this->configuration->ldapAgentPassword;
455 455
 		if (
456
-			($agent === ''  && $pwd !== '')
456
+			($agent === '' && $pwd !== '')
457 457
 			|| ($agent !== '' && $pwd === '')
458 458
 		) {
459 459
 			\OCP\Util::writeLog(
460 460
 				'user_ldap',
461
-				$errorStr.'either no password is given for the user ' .
461
+				$errorStr.'either no password is given for the user '.
462 462
 					'agent or a password is given, but not an LDAP agent.',
463 463
 				ILogger::WARN);
464 464
 			$configurationOK = false;
@@ -468,7 +468,7 @@  discard block
 block discarded – undo
468 468
 		$baseUsers = $this->configuration->ldapBaseUsers;
469 469
 		$baseGroups = $this->configuration->ldapBaseGroups;
470 470
 
471
-		if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
471
+		if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
472 472
 			\OCP\Util::writeLog(
473 473
 				'user_ldap',
474 474
 				$errorStr.'Not a single Base DN given.',
@@ -477,7 +477,7 @@  discard block
 block discarded – undo
477 477
 			$configurationOK = false;
478 478
 		}
479 479
 
480
-		if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
480
+		if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
481 481
 		   === false) {
482 482
 			\OCP\Util::writeLog(
483 483
 				'user_ldap',
@@ -496,7 +496,7 @@  discard block
 block discarded – undo
496 496
 	 */
497 497
 	private function validateConfiguration() {
498 498
 
499
-		if($this->doNotValidate) {
499
+		if ($this->doNotValidate) {
500 500
 			//don't do a validation if it is a new configuration with pure
501 501
 			//default values. Will be allowed on changes via __set or
502 502
 			//setConfiguration
@@ -519,14 +519,14 @@  discard block
 block discarded – undo
519 519
 	 * @throws ServerNotAvailableException
520 520
 	 */
521 521
 	private function establishConnection() {
522
-		if(!$this->configuration->ldapConfigurationActive) {
522
+		if (!$this->configuration->ldapConfigurationActive) {
523 523
 			return null;
524 524
 		}
525 525
 		static $phpLDAPinstalled = true;
526
-		if(!$phpLDAPinstalled) {
526
+		if (!$phpLDAPinstalled) {
527 527
 			return false;
528 528
 		}
529
-		if(!$this->ignoreValidation && !$this->configured) {
529
+		if (!$this->ignoreValidation && !$this->configured) {
530 530
 			\OCP\Util::writeLog(
531 531
 				'user_ldap',
532 532
 				'Configuration is invalid, cannot connect',
@@ -534,8 +534,8 @@  discard block
 block discarded – undo
534 534
 			);
535 535
 			return false;
536 536
 		}
537
-		if(!$this->ldapConnectionRes) {
538
-			if(!$this->ldap->areLDAPFunctionsAvailable()) {
537
+		if (!$this->ldapConnectionRes) {
538
+			if (!$this->ldap->areLDAPFunctionsAvailable()) {
539 539
 				$phpLDAPinstalled = false;
540 540
 				\OCP\Util::writeLog(
541 541
 					'user_ldap',
@@ -545,8 +545,8 @@  discard block
 block discarded – undo
545 545
 
546 546
 				return false;
547 547
 			}
548
-			if($this->configuration->turnOffCertCheck) {
549
-				if(putenv('LDAPTLS_REQCERT=never')) {
548
+			if ($this->configuration->turnOffCertCheck) {
549
+				if (putenv('LDAPTLS_REQCERT=never')) {
550 550
 					\OCP\Util::writeLog('user_ldap',
551 551
 						'Turned off SSL certificate validation successfully.',
552 552
 						ILogger::DEBUG);
@@ -570,20 +570,20 @@  discard block
 block discarded – undo
570 570
 					return $this->bind();
571 571
 				}
572 572
 			} catch (ServerNotAvailableException $e) {
573
-				if(!$isBackupHost) {
573
+				if (!$isBackupHost) {
574 574
 					throw $e;
575 575
 				}
576 576
 			}
577 577
 
578 578
 			//if LDAP server is not reachable, try the Backup (Replica!) Server
579
-			if($isBackupHost || $isOverrideMainServer) {
579
+			if ($isBackupHost || $isOverrideMainServer) {
580 580
 				$this->doConnect($this->configuration->ldapBackupHost,
581 581
 								 $this->configuration->ldapBackupPort);
582 582
 				$this->bindResult = [];
583 583
 				$bindStatus = $this->bind();
584 584
 				$error = $this->ldap->isResource($this->ldapConnectionRes) ?
585 585
 					$this->ldap->errno($this->ldapConnectionRes) : -1;
586
-				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
586
+				if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
587 587
 					//when bind to backup server succeeded and failed to main server,
588 588
 					//skip contacting him until next cache refresh
589 589
 					$this->writeToCache('overrideMainServer', true);
@@ -608,17 +608,17 @@  discard block
 block discarded – undo
608 608
 
609 609
 		$this->ldapConnectionRes = $this->ldap->connect($host, $port);
610 610
 
611
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
611
+		if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
612 612
 			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
613 613
 		}
614 614
 
615
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
615
+		if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
616 616
 			throw new ServerNotAvailableException('Could not disable LDAP referrals.');
617 617
 		}
618 618
 
619
-		if($this->configuration->ldapTLS) {
620
-			if(!$this->ldap->startTls($this->ldapConnectionRes)) {
621
-				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
619
+		if ($this->configuration->ldapTLS) {
620
+			if (!$this->ldap->startTls($this->ldapConnectionRes)) {
621
+				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host '.$host.'.');
622 622
 			}
623 623
 		}
624 624
 
@@ -629,19 +629,19 @@  discard block
 block discarded – undo
629 629
 	 * Binds to LDAP
630 630
 	 */
631 631
 	public function bind() {
632
-		if(!$this->configuration->ldapConfigurationActive) {
632
+		if (!$this->configuration->ldapConfigurationActive) {
633 633
 			return false;
634 634
 		}
635 635
 		$cr = $this->ldapConnectionRes;
636
-		if(!$this->ldap->isResource($cr)) {
636
+		if (!$this->ldap->isResource($cr)) {
637 637
 			$cr = $this->getConnectionResource();
638 638
 		}
639 639
 
640
-		if(
640
+		if (
641 641
 			count($this->bindResult) !== 0
642 642
 			&& $this->bindResult['dn'] === $this->configuration->ldapAgentName
643 643
 			&& \OC::$server->getHasher()->verify(
644
-				$this->configPrefix . $this->configuration->ldapAgentPassword,
644
+				$this->configPrefix.$this->configuration->ldapAgentPassword,
645 645
 				$this->bindResult['hash']
646 646
 			)
647 647
 		) {
@@ -657,19 +657,19 @@  discard block
 block discarded – undo
657 657
 
658 658
 		$this->bindResult = [
659 659
 			'dn' => $this->configuration->ldapAgentName,
660
-			'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword),
660
+			'hash' => \OC::$server->getHasher()->hash($this->configPrefix.$this->configuration->ldapAgentPassword),
661 661
 			'result' => $ldapLogin,
662 662
 		];
663 663
 
664
-		if(!$ldapLogin) {
664
+		if (!$ldapLogin) {
665 665
 			$errno = $this->ldap->errno($cr);
666 666
 
667 667
 			\OCP\Util::writeLog('user_ldap',
668
-				'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
668
+				'Bind failed: '.$errno.': '.$this->ldap->error($cr),
669 669
 				ILogger::WARN);
670 670
 
671 671
 			// Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
672
-			if($errno !== 0x00 && $errno !== 0x31) {
672
+			if ($errno !== 0x00 && $errno !== 0x31) {
673 673
 				$this->ldapConnectionRes = null;
674 674
 			}
675 675
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_LDAP.php 2 patches
Indentation   +1140 added lines, -1140 removed lines patch added patch discarded remove patch
@@ -46,1145 +46,1145 @@
 block discarded – undo
46 46
 use OCP\ILogger;
47 47
 
48 48
 class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLDAP {
49
-	protected $enabled = false;
50
-
51
-	/**
52
-	 * @var string[] $cachedGroupMembers array of users with gid as key
53
-	 */
54
-	protected $cachedGroupMembers;
55
-
56
-	/**
57
-	 * @var string[] $cachedGroupsByMember array of groups with uid as key
58
-	 */
59
-	protected $cachedGroupsByMember;
60
-
61
-	/** @var GroupPluginManager */
62
-	protected $groupPluginManager;
63
-
64
-	public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
65
-		parent::__construct($access);
66
-		$filter = $this->access->connection->ldapGroupFilter;
67
-		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
68
-		if(!empty($filter) && !empty($gassoc)) {
69
-			$this->enabled = true;
70
-		}
71
-
72
-		$this->cachedGroupMembers = new CappedMemoryCache();
73
-		$this->cachedGroupsByMember = new CappedMemoryCache();
74
-		$this->groupPluginManager = $groupPluginManager;
75
-	}
76
-
77
-	/**
78
-	 * is user in group?
79
-	 * @param string $uid uid of the user
80
-	 * @param string $gid gid of the group
81
-	 * @return bool
82
-	 *
83
-	 * Checks whether the user is member of a group or not.
84
-	 */
85
-	public function inGroup($uid, $gid) {
86
-		if(!$this->enabled) {
87
-			return false;
88
-		}
89
-		$cacheKey = 'inGroup'.$uid.':'.$gid;
90
-		$inGroup = $this->access->connection->getFromCache($cacheKey);
91
-		if(!is_null($inGroup)) {
92
-			return (bool)$inGroup;
93
-		}
94
-
95
-		$userDN = $this->access->username2dn($uid);
96
-
97
-		if(isset($this->cachedGroupMembers[$gid])) {
98
-			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
99
-			return $isInGroup;
100
-		}
101
-
102
-		$cacheKeyMembers = 'inGroup-members:'.$gid;
103
-		$members = $this->access->connection->getFromCache($cacheKeyMembers);
104
-		if(!is_null($members)) {
105
-			$this->cachedGroupMembers[$gid] = $members;
106
-			$isInGroup = in_array($userDN, $members);
107
-			$this->access->connection->writeToCache($cacheKey, $isInGroup);
108
-			return $isInGroup;
109
-		}
110
-
111
-		$groupDN = $this->access->groupname2dn($gid);
112
-		// just in case
113
-		if(!$groupDN || !$userDN) {
114
-			$this->access->connection->writeToCache($cacheKey, false);
115
-			return false;
116
-		}
117
-
118
-		//check primary group first
119
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
120
-			$this->access->connection->writeToCache($cacheKey, true);
121
-			return true;
122
-		}
123
-
124
-		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
125
-		$members = $this->_groupMembers($groupDN);
126
-		$members = array_keys($members); // uids are returned as keys
127
-		if(!is_array($members) || count($members) === 0) {
128
-			$this->access->connection->writeToCache($cacheKey, false);
129
-			return false;
130
-		}
131
-
132
-		//extra work if we don't get back user DNs
133
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
134
-			$dns = array();
135
-			$filterParts = array();
136
-			$bytes = 0;
137
-			foreach($members as $mid) {
138
-				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
139
-				$filterParts[] = $filter;
140
-				$bytes += strlen($filter);
141
-				if($bytes >= 9000000) {
142
-					// AD has a default input buffer of 10 MB, we do not want
143
-					// to take even the chance to exceed it
144
-					$filter = $this->access->combineFilterWithOr($filterParts);
145
-					$bytes = 0;
146
-					$filterParts = array();
147
-					$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
148
-					$dns = array_merge($dns, $users);
149
-				}
150
-			}
151
-			if(count($filterParts) > 0) {
152
-				$filter = $this->access->combineFilterWithOr($filterParts);
153
-				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
154
-				$dns = array_merge($dns, $users);
155
-			}
156
-			$members = $dns;
157
-		}
158
-
159
-		$isInGroup = in_array($userDN, $members);
160
-		$this->access->connection->writeToCache($cacheKey, $isInGroup);
161
-		$this->access->connection->writeToCache($cacheKeyMembers, $members);
162
-		$this->cachedGroupMembers[$gid] = $members;
163
-
164
-		return $isInGroup;
165
-	}
166
-
167
-	/**
168
-	 * @param string $dnGroup
169
-	 * @return array
170
-	 *
171
-	 * For a group that has user membership defined by an LDAP search url attribute returns the users
172
-	 * that match the search url otherwise returns an empty array.
173
-	 */
174
-	public function getDynamicGroupMembers($dnGroup) {
175
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
176
-
177
-		if (empty($dynamicGroupMemberURL)) {
178
-			return array();
179
-		}
180
-
181
-		$dynamicMembers = array();
182
-		$memberURLs = $this->access->readAttribute(
183
-			$dnGroup,
184
-			$dynamicGroupMemberURL,
185
-			$this->access->connection->ldapGroupFilter
186
-		);
187
-		if ($memberURLs !== false) {
188
-			// this group has the 'memberURL' attribute so this is a dynamic group
189
-			// example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
190
-			// example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
191
-			$pos = strpos($memberURLs[0], '(');
192
-			if ($pos !== false) {
193
-				$memberUrlFilter = substr($memberURLs[0], $pos);
194
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
195
-				$dynamicMembers = array();
196
-				foreach($foundMembers as $value) {
197
-					$dynamicMembers[$value['dn'][0]] = 1;
198
-				}
199
-			} else {
200
-				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
201
-					'of group ' . $dnGroup, ILogger::DEBUG);
202
-			}
203
-		}
204
-		return $dynamicMembers;
205
-	}
206
-
207
-	/**
208
-	 * @param string $dnGroup
209
-	 * @param array|null &$seen
210
-	 * @return array|mixed|null
211
-	 * @throws \OC\ServerNotAvailableException
212
-	 */
213
-	private function _groupMembers($dnGroup, &$seen = null) {
214
-		if ($seen === null) {
215
-			$seen = array();
216
-		}
217
-		$allMembers = array();
218
-		if (array_key_exists($dnGroup, $seen)) {
219
-			// avoid loops
220
-			return array();
221
-		}
222
-		// used extensively in cron job, caching makes sense for nested groups
223
-		$cacheKey = '_groupMembers'.$dnGroup;
224
-		$groupMembers = $this->access->connection->getFromCache($cacheKey);
225
-		if($groupMembers !== null) {
226
-			return $groupMembers;
227
-		}
228
-		$seen[$dnGroup] = 1;
229
-		$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr,
230
-												$this->access->connection->ldapGroupFilter);
231
-		if (is_array($members)) {
232
-			foreach ($members as $member) {
233
-				$allMembers[$member] = 1;
234
-				$nestedGroups = $this->access->connection->ldapNestedGroups;
235
-				if (!empty($nestedGroups)) {
236
-					$subMembers = $this->_groupMembers($member, $seen);
237
-					if ($subMembers) {
238
-						$allMembers += $subMembers;
239
-					}
240
-				}
241
-			}
242
-		}
243
-
244
-		$allMembers += $this->getDynamicGroupMembers($dnGroup);
245
-
246
-		$this->access->connection->writeToCache($cacheKey, $allMembers);
247
-		return $allMembers;
248
-	}
249
-
250
-	/**
251
-	 * @param string $DN
252
-	 * @param array|null &$seen
253
-	 * @return array
254
-	 */
255
-	private function _getGroupDNsFromMemberOf($DN, &$seen = null) {
256
-		if ($seen === null) {
257
-			$seen = array();
258
-		}
259
-		if (array_key_exists($DN, $seen)) {
260
-			// avoid loops
261
-			return array();
262
-		}
263
-		$seen[$DN] = 1;
264
-		$groups = $this->access->readAttribute($DN, 'memberOf');
265
-		if (!is_array($groups)) {
266
-			return array();
267
-		}
268
-		$groups = $this->access->groupsMatchFilter($groups);
269
-		$allGroups =  $groups;
270
-		$nestedGroups = $this->access->connection->ldapNestedGroups;
271
-		if ((int)$nestedGroups === 1) {
272
-			foreach ($groups as $group) {
273
-				$subGroups = $this->_getGroupDNsFromMemberOf($group, $seen);
274
-				$allGroups = array_merge($allGroups, $subGroups);
275
-			}
276
-		}
277
-		return $allGroups;
278
-	}
279
-
280
-	/**
281
-	 * translates a gidNumber into an ownCloud internal name
282
-	 * @param string $gid as given by gidNumber on POSIX LDAP
283
-	 * @param string $dn a DN that belongs to the same domain as the group
284
-	 * @return string|bool
285
-	 */
286
-	public function gidNumber2Name($gid, $dn) {
287
-		$cacheKey = 'gidNumberToName' . $gid;
288
-		$groupName = $this->access->connection->getFromCache($cacheKey);
289
-		if(!is_null($groupName) && isset($groupName)) {
290
-			return $groupName;
291
-		}
292
-
293
-		//we need to get the DN from LDAP
294
-		$filter = $this->access->combineFilterWithAnd([
295
-			$this->access->connection->ldapGroupFilter,
296
-			'objectClass=posixGroup',
297
-			$this->access->connection->ldapGidNumber . '=' . $gid
298
-		]);
299
-		$result = $this->access->searchGroups($filter, array('dn'), 1);
300
-		if(empty($result)) {
301
-			return false;
302
-		}
303
-		$dn = $result[0]['dn'][0];
304
-
305
-		//and now the group name
306
-		//NOTE once we have separate ownCloud group IDs and group names we can
307
-		//directly read the display name attribute instead of the DN
308
-		$name = $this->access->dn2groupname($dn);
309
-
310
-		$this->access->connection->writeToCache($cacheKey, $name);
311
-
312
-		return $name;
313
-	}
314
-
315
-	/**
316
-	 * returns the entry's gidNumber
317
-	 * @param string $dn
318
-	 * @param string $attribute
319
-	 * @return string|bool
320
-	 */
321
-	private function getEntryGidNumber($dn, $attribute) {
322
-		$value = $this->access->readAttribute($dn, $attribute);
323
-		if(is_array($value) && !empty($value)) {
324
-			return $value[0];
325
-		}
326
-		return false;
327
-	}
328
-
329
-	/**
330
-	 * returns the group's primary ID
331
-	 * @param string $dn
332
-	 * @return string|bool
333
-	 */
334
-	public function getGroupGidNumber($dn) {
335
-		return $this->getEntryGidNumber($dn, 'gidNumber');
336
-	}
337
-
338
-	/**
339
-	 * returns the user's gidNumber
340
-	 * @param string $dn
341
-	 * @return string|bool
342
-	 */
343
-	public function getUserGidNumber($dn) {
344
-		$gidNumber = false;
345
-		if($this->access->connection->hasGidNumber) {
346
-			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
347
-			if($gidNumber === false) {
348
-				$this->access->connection->hasGidNumber = false;
349
-			}
350
-		}
351
-		return $gidNumber;
352
-	}
353
-
354
-	/**
355
-	 * returns a filter for a "users has specific gid" search or count operation
356
-	 *
357
-	 * @param string $groupDN
358
-	 * @param string $search
359
-	 * @return string
360
-	 * @throws \Exception
361
-	 */
362
-	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
363
-		$groupID = $this->getGroupGidNumber($groupDN);
364
-		if($groupID === false) {
365
-			throw new \Exception('Not a valid group');
366
-		}
367
-
368
-		$filterParts = [];
369
-		$filterParts[] = $this->access->getFilterForUserCount();
370
-		if ($search !== '') {
371
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
372
-		}
373
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
374
-
375
-		return $this->access->combineFilterWithAnd($filterParts);
376
-	}
377
-
378
-	/**
379
-	 * returns a list of users that have the given group as gid number
380
-	 *
381
-	 * @param string $groupDN
382
-	 * @param string $search
383
-	 * @param int $limit
384
-	 * @param int $offset
385
-	 * @return string[]
386
-	 */
387
-	public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
388
-		try {
389
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
390
-			$users = $this->access->fetchListOfUsers(
391
-				$filter,
392
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
393
-				$limit,
394
-				$offset
395
-			);
396
-			return $this->access->nextcloudUserNames($users);
397
-		} catch (\Exception $e) {
398
-			return [];
399
-		}
400
-	}
401
-
402
-	/**
403
-	 * returns the number of users that have the given group as gid number
404
-	 *
405
-	 * @param string $groupDN
406
-	 * @param string $search
407
-	 * @param int $limit
408
-	 * @param int $offset
409
-	 * @return int
410
-	 */
411
-	public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
412
-		try {
413
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
414
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
415
-			return (int)$users;
416
-		} catch (\Exception $e) {
417
-			return 0;
418
-		}
419
-	}
420
-
421
-	/**
422
-	 * gets the gidNumber of a user
423
-	 * @param string $dn
424
-	 * @return string
425
-	 */
426
-	public function getUserGroupByGid($dn) {
427
-		$groupID = $this->getUserGidNumber($dn);
428
-		if($groupID !== false) {
429
-			$groupName = $this->gidNumber2Name($groupID, $dn);
430
-			if($groupName !== false) {
431
-				return $groupName;
432
-			}
433
-		}
434
-
435
-		return false;
436
-	}
437
-
438
-	/**
439
-	 * translates a primary group ID into an Nextcloud internal name
440
-	 * @param string $gid as given by primaryGroupID on AD
441
-	 * @param string $dn a DN that belongs to the same domain as the group
442
-	 * @return string|bool
443
-	 */
444
-	public function primaryGroupID2Name($gid, $dn) {
445
-		$cacheKey = 'primaryGroupIDtoName';
446
-		$groupNames = $this->access->connection->getFromCache($cacheKey);
447
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
448
-			return $groupNames[$gid];
449
-		}
450
-
451
-		$domainObjectSid = $this->access->getSID($dn);
452
-		if($domainObjectSid === false) {
453
-			return false;
454
-		}
455
-
456
-		//we need to get the DN from LDAP
457
-		$filter = $this->access->combineFilterWithAnd(array(
458
-			$this->access->connection->ldapGroupFilter,
459
-			'objectsid=' . $domainObjectSid . '-' . $gid
460
-		));
461
-		$result = $this->access->searchGroups($filter, array('dn'), 1);
462
-		if(empty($result)) {
463
-			return false;
464
-		}
465
-		$dn = $result[0]['dn'][0];
466
-
467
-		//and now the group name
468
-		//NOTE once we have separate Nextcloud group IDs and group names we can
469
-		//directly read the display name attribute instead of the DN
470
-		$name = $this->access->dn2groupname($dn);
471
-
472
-		$this->access->connection->writeToCache($cacheKey, $name);
473
-
474
-		return $name;
475
-	}
476
-
477
-	/**
478
-	 * returns the entry's primary group ID
479
-	 * @param string $dn
480
-	 * @param string $attribute
481
-	 * @return string|bool
482
-	 */
483
-	private function getEntryGroupID($dn, $attribute) {
484
-		$value = $this->access->readAttribute($dn, $attribute);
485
-		if(is_array($value) && !empty($value)) {
486
-			return $value[0];
487
-		}
488
-		return false;
489
-	}
490
-
491
-	/**
492
-	 * returns the group's primary ID
493
-	 * @param string $dn
494
-	 * @return string|bool
495
-	 */
496
-	public function getGroupPrimaryGroupID($dn) {
497
-		return $this->getEntryGroupID($dn, 'primaryGroupToken');
498
-	}
499
-
500
-	/**
501
-	 * returns the user's primary group ID
502
-	 * @param string $dn
503
-	 * @return string|bool
504
-	 */
505
-	public function getUserPrimaryGroupIDs($dn) {
506
-		$primaryGroupID = false;
507
-		if($this->access->connection->hasPrimaryGroups) {
508
-			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
509
-			if($primaryGroupID === false) {
510
-				$this->access->connection->hasPrimaryGroups = false;
511
-			}
512
-		}
513
-		return $primaryGroupID;
514
-	}
515
-
516
-	/**
517
-	 * returns a filter for a "users in primary group" search or count operation
518
-	 *
519
-	 * @param string $groupDN
520
-	 * @param string $search
521
-	 * @return string
522
-	 * @throws \Exception
523
-	 */
524
-	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
525
-		$groupID = $this->getGroupPrimaryGroupID($groupDN);
526
-		if($groupID === false) {
527
-			throw new \Exception('Not a valid group');
528
-		}
529
-
530
-		$filterParts = [];
531
-		$filterParts[] = $this->access->getFilterForUserCount();
532
-		if ($search !== '') {
533
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
534
-		}
535
-		$filterParts[] = 'primaryGroupID=' . $groupID;
536
-
537
-		return $this->access->combineFilterWithAnd($filterParts);
538
-	}
539
-
540
-	/**
541
-	 * returns a list of users that have the given group as primary group
542
-	 *
543
-	 * @param string $groupDN
544
-	 * @param string $search
545
-	 * @param int $limit
546
-	 * @param int $offset
547
-	 * @return string[]
548
-	 */
549
-	public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
550
-		try {
551
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
552
-			$users = $this->access->fetchListOfUsers(
553
-				$filter,
554
-				array($this->access->connection->ldapUserDisplayName, 'dn'),
555
-				$limit,
556
-				$offset
557
-			);
558
-			return $this->access->nextcloudUserNames($users);
559
-		} catch (\Exception $e) {
560
-			return array();
561
-		}
562
-	}
563
-
564
-	/**
565
-	 * returns the number of users that have the given group as primary group
566
-	 *
567
-	 * @param string $groupDN
568
-	 * @param string $search
569
-	 * @param int $limit
570
-	 * @param int $offset
571
-	 * @return int
572
-	 */
573
-	public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
574
-		try {
575
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
576
-			$users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
577
-			return (int)$users;
578
-		} catch (\Exception $e) {
579
-			return 0;
580
-		}
581
-	}
582
-
583
-	/**
584
-	 * gets the primary group of a user
585
-	 * @param string $dn
586
-	 * @return string
587
-	 */
588
-	public function getUserPrimaryGroup($dn) {
589
-		$groupID = $this->getUserPrimaryGroupIDs($dn);
590
-		if($groupID !== false) {
591
-			$groupName = $this->primaryGroupID2Name($groupID, $dn);
592
-			if($groupName !== false) {
593
-				return $groupName;
594
-			}
595
-		}
596
-
597
-		return false;
598
-	}
599
-
600
-	/**
601
-	 * Get all groups a user belongs to
602
-	 * @param string $uid Name of the user
603
-	 * @return array with group names
604
-	 *
605
-	 * This function fetches all groups a user belongs to. It does not check
606
-	 * if the user exists at all.
607
-	 *
608
-	 * This function includes groups based on dynamic group membership.
609
-	 */
610
-	public function getUserGroups($uid) {
611
-		if(!$this->enabled) {
612
-			return array();
613
-		}
614
-		$cacheKey = 'getUserGroups'.$uid;
615
-		$userGroups = $this->access->connection->getFromCache($cacheKey);
616
-		if(!is_null($userGroups)) {
617
-			return $userGroups;
618
-		}
619
-		$userDN = $this->access->username2dn($uid);
620
-		if(!$userDN) {
621
-			$this->access->connection->writeToCache($cacheKey, array());
622
-			return array();
623
-		}
624
-
625
-		$groups = [];
626
-		$primaryGroup = $this->getUserPrimaryGroup($userDN);
627
-		$gidGroupName = $this->getUserGroupByGid($userDN);
628
-
629
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
630
-
631
-		if (!empty($dynamicGroupMemberURL)) {
632
-			// look through dynamic groups to add them to the result array if needed
633
-			$groupsToMatch = $this->access->fetchListOfGroups(
634
-				$this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
635
-			foreach($groupsToMatch as $dynamicGroup) {
636
-				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
637
-					continue;
638
-				}
639
-				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
640
-				if ($pos !== false) {
641
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
642
-					// apply filter via ldap search to see if this user is in this
643
-					// dynamic group
644
-					$userMatch = $this->access->readAttribute(
645
-						$userDN,
646
-						$this->access->connection->ldapUserDisplayName,
647
-						$memberUrlFilter
648
-					);
649
-					if ($userMatch !== false) {
650
-						// match found so this user is in this group
651
-						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
652
-						if(is_string($groupName)) {
653
-							// be sure to never return false if the dn could not be
654
-							// resolved to a name, for whatever reason.
655
-							$groups[] = $groupName;
656
-						}
657
-					}
658
-				} else {
659
-					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
660
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
661
-				}
662
-			}
663
-		}
664
-
665
-		// if possible, read out membership via memberOf. It's far faster than
666
-		// performing a search, which still is a fallback later.
667
-		// memberof doesn't support memberuid, so skip it here.
668
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
669
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
670
-		    && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
671
-		    ) {
672
-			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
673
-			if (is_array($groupDNs)) {
674
-				foreach ($groupDNs as $dn) {
675
-					$groupName = $this->access->dn2groupname($dn);
676
-					if(is_string($groupName)) {
677
-						// be sure to never return false if the dn could not be
678
-						// resolved to a name, for whatever reason.
679
-						$groups[] = $groupName;
680
-					}
681
-				}
682
-			}
683
-
684
-			if($primaryGroup !== false) {
685
-				$groups[] = $primaryGroup;
686
-			}
687
-			if($gidGroupName !== false) {
688
-				$groups[] = $gidGroupName;
689
-			}
690
-			$this->access->connection->writeToCache($cacheKey, $groups);
691
-			return $groups;
692
-		}
693
-
694
-		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
695
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
696
-			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
697
-		) {
698
-			$uid = $userDN;
699
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
700
-			$result = $this->access->readAttribute($userDN, 'uid');
701
-			if ($result === false) {
702
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
703
-					$this->access->connection->ldapHost, ILogger::DEBUG);
704
-			}
705
-			$uid = $result[0];
706
-		} else {
707
-			// just in case
708
-			$uid = $userDN;
709
-		}
710
-
711
-		if(isset($this->cachedGroupsByMember[$uid])) {
712
-			$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
713
-		} else {
714
-			$groupsByMember = array_values($this->getGroupsByMember($uid));
715
-			$groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
716
-			$this->cachedGroupsByMember[$uid] = $groupsByMember;
717
-			$groups = array_merge($groups, $groupsByMember);
718
-		}
719
-
720
-		if($primaryGroup !== false) {
721
-			$groups[] = $primaryGroup;
722
-		}
723
-		if($gidGroupName !== false) {
724
-			$groups[] = $gidGroupName;
725
-		}
726
-
727
-		$groups = array_unique($groups, SORT_LOCALE_STRING);
728
-		$this->access->connection->writeToCache($cacheKey, $groups);
729
-
730
-		return $groups;
731
-	}
732
-
733
-	/**
734
-	 * @param string $dn
735
-	 * @param array|null &$seen
736
-	 * @return array
737
-	 */
738
-	private function getGroupsByMember($dn, &$seen = null) {
739
-		if ($seen === null) {
740
-			$seen = array();
741
-		}
742
-		$allGroups = array();
743
-		if (array_key_exists($dn, $seen)) {
744
-			// avoid loops
745
-			return array();
746
-		}
747
-		$seen[$dn] = true;
748
-		$filter = $this->access->combineFilterWithAnd(array(
749
-			$this->access->connection->ldapGroupFilter,
750
-			$this->access->connection->ldapGroupMemberAssocAttr.'='.$dn
751
-		));
752
-		$groups = $this->access->fetchListOfGroups($filter,
753
-			array($this->access->connection->ldapGroupDisplayName, 'dn'));
754
-		if (is_array($groups)) {
755
-			foreach ($groups as $groupobj) {
756
-				$groupDN = $groupobj['dn'][0];
757
-				$allGroups[$groupDN] = $groupobj;
758
-				$nestedGroups = $this->access->connection->ldapNestedGroups;
759
-				if (!empty($nestedGroups)) {
760
-					$supergroups = $this->getGroupsByMember($groupDN, $seen);
761
-					if (is_array($supergroups) && (count($supergroups)>0)) {
762
-						$allGroups = array_merge($allGroups, $supergroups);
763
-					}
764
-				}
765
-			}
766
-		}
767
-		return $allGroups;
768
-	}
769
-
770
-	/**
771
-	 * get a list of all users in a group
772
-	 *
773
-	 * @param string $gid
774
-	 * @param string $search
775
-	 * @param int $limit
776
-	 * @param int $offset
777
-	 * @return array with user ids
778
-	 */
779
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
780
-		if(!$this->enabled) {
781
-			return array();
782
-		}
783
-		if(!$this->groupExists($gid)) {
784
-			return array();
785
-		}
786
-		$search = $this->access->escapeFilterPart($search, true);
787
-		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
788
-		// check for cache of the exact query
789
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
790
-		if(!is_null($groupUsers)) {
791
-			return $groupUsers;
792
-		}
793
-
794
-		// check for cache of the query without limit and offset
795
-		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
796
-		if(!is_null($groupUsers)) {
797
-			$groupUsers = array_slice($groupUsers, $offset, $limit);
798
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
799
-			return $groupUsers;
800
-		}
801
-
802
-		if($limit === -1) {
803
-			$limit = null;
804
-		}
805
-		$groupDN = $this->access->groupname2dn($gid);
806
-		if(!$groupDN) {
807
-			// group couldn't be found, return empty resultset
808
-			$this->access->connection->writeToCache($cacheKey, array());
809
-			return array();
810
-		}
811
-
812
-		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
813
-		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
814
-		$members = array_keys($this->_groupMembers($groupDN));
815
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
816
-			//in case users could not be retrieved, return empty result set
817
-			$this->access->connection->writeToCache($cacheKey, []);
818
-			return [];
819
-		}
820
-
821
-		$groupUsers = array();
822
-		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
823
-		$attrs = $this->access->userManager->getAttributes(true);
824
-		foreach($members as $member) {
825
-			if($isMemberUid) {
826
-				//we got uids, need to get their DNs to 'translate' them to user names
827
-				$filter = $this->access->combineFilterWithAnd(array(
828
-					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
829
-					$this->access->getFilterPartForUserSearch($search)
830
-				));
831
-				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
832
-				if(count($ldap_users) < 1) {
833
-					continue;
834
-				}
835
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
836
-			} else {
837
-				//we got DNs, check if we need to filter by search or we can give back all of them
838
-				if ($search !== '') {
839
-					if(!$this->access->readAttribute($member,
840
-						$this->access->connection->ldapUserDisplayName,
841
-						$this->access->getFilterPartForUserSearch($search))) {
842
-						continue;
843
-					}
844
-				}
845
-				// dn2username will also check if the users belong to the allowed base
846
-				if($ocname = $this->access->dn2username($member)) {
847
-					$groupUsers[] = $ocname;
848
-				}
849
-			}
850
-		}
851
-
852
-		$groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
853
-		natsort($groupUsers);
854
-		$this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
855
-		$groupUsers = array_slice($groupUsers, $offset, $limit);
856
-
857
-		$this->access->connection->writeToCache($cacheKey, $groupUsers);
858
-
859
-		return $groupUsers;
860
-	}
861
-
862
-	/**
863
-	 * returns the number of users in a group, who match the search term
864
-	 * @param string $gid the internal group name
865
-	 * @param string $search optional, a search string
866
-	 * @return int|bool
867
-	 */
868
-	public function countUsersInGroup($gid, $search = '') {
869
-		if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
870
-			return $this->groupPluginManager->countUsersInGroup($gid, $search);
871
-		}
872
-
873
-		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
874
-		if(!$this->enabled || !$this->groupExists($gid)) {
875
-			return false;
876
-		}
877
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
878
-		if(!is_null($groupUsers)) {
879
-			return $groupUsers;
880
-		}
881
-
882
-		$groupDN = $this->access->groupname2dn($gid);
883
-		if(!$groupDN) {
884
-			// group couldn't be found, return empty result set
885
-			$this->access->connection->writeToCache($cacheKey, false);
886
-			return false;
887
-		}
888
-
889
-		$members = array_keys($this->_groupMembers($groupDN));
890
-		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
891
-		if(!$members && $primaryUserCount === 0) {
892
-			//in case users could not be retrieved, return empty result set
893
-			$this->access->connection->writeToCache($cacheKey, false);
894
-			return false;
895
-		}
896
-
897
-		if ($search === '') {
898
-			$groupUsers = count($members) + $primaryUserCount;
899
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
900
-			return $groupUsers;
901
-		}
902
-		$search = $this->access->escapeFilterPart($search, true);
903
-		$isMemberUid =
904
-			(strtolower($this->access->connection->ldapGroupMemberAssocAttr)
905
-			=== 'memberuid');
906
-
907
-		//we need to apply the search filter
908
-		//alternatives that need to be checked:
909
-		//a) get all users by search filter and array_intersect them
910
-		//b) a, but only when less than 1k 10k ?k users like it is
911
-		//c) put all DNs|uids in a LDAP filter, combine with the search string
912
-		//   and let it count.
913
-		//For now this is not important, because the only use of this method
914
-		//does not supply a search string
915
-		$groupUsers = array();
916
-		foreach($members as $member) {
917
-			if($isMemberUid) {
918
-				//we got uids, need to get their DNs to 'translate' them to user names
919
-				$filter = $this->access->combineFilterWithAnd(array(
920
-					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
921
-					$this->access->getFilterPartForUserSearch($search)
922
-				));
923
-				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
924
-				if(count($ldap_users) < 1) {
925
-					continue;
926
-				}
927
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
928
-			} else {
929
-				//we need to apply the search filter now
930
-				if(!$this->access->readAttribute($member,
931
-					$this->access->connection->ldapUserDisplayName,
932
-					$this->access->getFilterPartForUserSearch($search))) {
933
-					continue;
934
-				}
935
-				// dn2username will also check if the users belong to the allowed base
936
-				if($ocname = $this->access->dn2username($member)) {
937
-					$groupUsers[] = $ocname;
938
-				}
939
-			}
940
-		}
941
-
942
-		//and get users that have the group as primary
943
-		$primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
944
-
945
-		return count($groupUsers) + $primaryUsers;
946
-	}
947
-
948
-	/**
949
-	 * get a list of all groups
950
-	 *
951
-	 * @param string $search
952
-	 * @param $limit
953
-	 * @param int $offset
954
-	 * @return array with group names
955
-	 *
956
-	 * Returns a list with all groups (used by getGroups)
957
-	 */
958
-	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
959
-		if(!$this->enabled) {
960
-			return array();
961
-		}
962
-		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
963
-
964
-		//Check cache before driving unnecessary searches
965
-		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
966
-		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
967
-		if(!is_null($ldap_groups)) {
968
-			return $ldap_groups;
969
-		}
970
-
971
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
972
-		// error. With a limit of 0, we get 0 results. So we pass null.
973
-		if($limit <= 0) {
974
-			$limit = null;
975
-		}
976
-		$filter = $this->access->combineFilterWithAnd(array(
977
-			$this->access->connection->ldapGroupFilter,
978
-			$this->access->getFilterPartForGroupSearch($search)
979
-		));
980
-		\OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
981
-		$ldap_groups = $this->access->fetchListOfGroups($filter,
982
-				array($this->access->connection->ldapGroupDisplayName, 'dn'),
983
-				$limit,
984
-				$offset);
985
-		$ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
986
-
987
-		$this->access->connection->writeToCache($cacheKey, $ldap_groups);
988
-		return $ldap_groups;
989
-	}
990
-
991
-	/**
992
-	 * get a list of all groups using a paged search
993
-	 *
994
-	 * @param string $search
995
-	 * @param int $limit
996
-	 * @param int $offset
997
-	 * @return array with group names
998
-	 *
999
-	 * Returns a list with all groups
1000
-	 * Uses a paged search if available to override a
1001
-	 * server side search limit.
1002
-	 * (active directory has a limit of 1000 by default)
1003
-	 */
1004
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
1005
-		if(!$this->enabled) {
1006
-			return array();
1007
-		}
1008
-		$search = $this->access->escapeFilterPart($search, true);
1009
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1010
-		if ($pagingSize <= 0) {
1011
-			return $this->getGroupsChunk($search, $limit, $offset);
1012
-		}
1013
-		$maxGroups = 100000; // limit max results (just for safety reasons)
1014
-		if ($limit > -1) {
1015
-		   $overallLimit = min($limit + $offset, $maxGroups);
1016
-		} else {
1017
-		   $overallLimit = $maxGroups;
1018
-		}
1019
-		$chunkOffset = $offset;
1020
-		$allGroups = array();
1021
-		while ($chunkOffset < $overallLimit) {
1022
-			$chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1023
-			$ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1024
-			$nread = count($ldapGroups);
1025
-			\OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1026
-			if ($nread) {
1027
-				$allGroups = array_merge($allGroups, $ldapGroups);
1028
-				$chunkOffset += $nread;
1029
-			}
1030
-			if ($nread < $chunkLimit) {
1031
-				break;
1032
-			}
1033
-		}
1034
-		return $allGroups;
1035
-	}
1036
-
1037
-	/**
1038
-	 * @param string $group
1039
-	 * @return bool
1040
-	 */
1041
-	public function groupMatchesFilter($group) {
1042
-		return (strripos($group, $this->groupSearch) !== false);
1043
-	}
1044
-
1045
-	/**
1046
-	 * check if a group exists
1047
-	 * @param string $gid
1048
-	 * @return bool
1049
-	 */
1050
-	public function groupExists($gid) {
1051
-		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1052
-		if(!is_null($groupExists)) {
1053
-			return (bool)$groupExists;
1054
-		}
1055
-
1056
-		//getting dn, if false the group does not exist. If dn, it may be mapped
1057
-		//only, requires more checking.
1058
-		$dn = $this->access->groupname2dn($gid);
1059
-		if(!$dn) {
1060
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1061
-			return false;
1062
-		}
1063
-
1064
-		//if group really still exists, we will be able to read its objectclass
1065
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1066
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1067
-			return false;
1068
-		}
1069
-
1070
-		$this->access->connection->writeToCache('groupExists'.$gid, true);
1071
-		return true;
1072
-	}
1073
-
1074
-	/**
1075
-	* Check if backend implements actions
1076
-	* @param int $actions bitwise-or'ed actions
1077
-	* @return boolean
1078
-	*
1079
-	* Returns the supported actions as int to be
1080
-	* compared with GroupInterface::CREATE_GROUP etc.
1081
-	*/
1082
-	public function implementsActions($actions) {
1083
-		return (bool)((GroupInterface::COUNT_USERS |
1084
-				$this->groupPluginManager->getImplementedActions()) & $actions);
1085
-	}
1086
-
1087
-	/**
1088
-	 * Return access for LDAP interaction.
1089
-	 * @return Access instance of Access for LDAP interaction
1090
-	 */
1091
-	public function getLDAPAccess($gid) {
1092
-		return $this->access;
1093
-	}
1094
-
1095
-	/**
1096
-	 * create a group
1097
-	 * @param string $gid
1098
-	 * @return bool
1099
-	 * @throws \Exception
1100
-	 */
1101
-	public function createGroup($gid) {
1102
-		if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1103
-			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1104
-				//updates group mapping
1105
-				$this->access->dn2ocname($dn, $gid, false);
1106
-				$this->access->connection->writeToCache("groupExists".$gid, true);
1107
-			}
1108
-			return $dn != null;
1109
-		}
1110
-		throw new \Exception('Could not create group in LDAP backend.');
1111
-	}
1112
-
1113
-	/**
1114
-	 * delete a group
1115
-	 * @param string $gid gid of the group to delete
1116
-	 * @return bool
1117
-	 * @throws \Exception
1118
-	 */
1119
-	public function deleteGroup($gid) {
1120
-		if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1121
-			if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1122
-				#delete group in nextcloud internal db
1123
-				$this->access->getGroupMapper()->unmap($gid);
1124
-				$this->access->connection->writeToCache("groupExists".$gid, false);
1125
-			}
1126
-			return $ret;
1127
-		}
1128
-		throw new \Exception('Could not delete group in LDAP backend.');
1129
-	}
1130
-
1131
-	/**
1132
-	 * Add a user to a group
1133
-	 * @param string $uid Name of the user to add to group
1134
-	 * @param string $gid Name of the group in which add the user
1135
-	 * @return bool
1136
-	 * @throws \Exception
1137
-	 */
1138
-	public function addToGroup($uid, $gid) {
1139
-		if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1140
-			if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1141
-				$this->access->connection->clearCache();
1142
-			}
1143
-			return $ret;
1144
-		}
1145
-		throw new \Exception('Could not add user to group in LDAP backend.');
1146
-	}
1147
-
1148
-	/**
1149
-	 * Removes a user from a group
1150
-	 * @param string $uid Name of the user to remove from group
1151
-	 * @param string $gid Name of the group from which remove the user
1152
-	 * @return bool
1153
-	 * @throws \Exception
1154
-	 */
1155
-	public function removeFromGroup($uid, $gid) {
1156
-		if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1157
-			if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1158
-				$this->access->connection->clearCache();
1159
-			}
1160
-			return $ret;
1161
-		}
1162
-		throw new \Exception('Could not remove user from group in LDAP backend.');
1163
-	}
1164
-
1165
-	/**
1166
-	 * Gets group details
1167
-	 * @param string $gid Name of the group
1168
-	 * @return array | false
1169
-	 * @throws \Exception
1170
-	 */
1171
-	public function getGroupDetails($gid) {
1172
-		if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1173
-			return $this->groupPluginManager->getGroupDetails($gid);
1174
-		}
1175
-		throw new \Exception('Could not get group details in LDAP backend.');
1176
-	}
1177
-
1178
-	/**
1179
-	 * Return LDAP connection resource from a cloned connection.
1180
-	 * The cloned connection needs to be closed manually.
1181
-	 * of the current access.
1182
-	 * @param string $gid
1183
-	 * @return resource of the LDAP connection
1184
-	 */
1185
-	public function getNewLDAPConnection($gid) {
1186
-		$connection = clone $this->access->getConnection();
1187
-		return $connection->getConnectionResource();
1188
-	}
49
+    protected $enabled = false;
50
+
51
+    /**
52
+     * @var string[] $cachedGroupMembers array of users with gid as key
53
+     */
54
+    protected $cachedGroupMembers;
55
+
56
+    /**
57
+     * @var string[] $cachedGroupsByMember array of groups with uid as key
58
+     */
59
+    protected $cachedGroupsByMember;
60
+
61
+    /** @var GroupPluginManager */
62
+    protected $groupPluginManager;
63
+
64
+    public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
65
+        parent::__construct($access);
66
+        $filter = $this->access->connection->ldapGroupFilter;
67
+        $gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
68
+        if(!empty($filter) && !empty($gassoc)) {
69
+            $this->enabled = true;
70
+        }
71
+
72
+        $this->cachedGroupMembers = new CappedMemoryCache();
73
+        $this->cachedGroupsByMember = new CappedMemoryCache();
74
+        $this->groupPluginManager = $groupPluginManager;
75
+    }
76
+
77
+    /**
78
+     * is user in group?
79
+     * @param string $uid uid of the user
80
+     * @param string $gid gid of the group
81
+     * @return bool
82
+     *
83
+     * Checks whether the user is member of a group or not.
84
+     */
85
+    public function inGroup($uid, $gid) {
86
+        if(!$this->enabled) {
87
+            return false;
88
+        }
89
+        $cacheKey = 'inGroup'.$uid.':'.$gid;
90
+        $inGroup = $this->access->connection->getFromCache($cacheKey);
91
+        if(!is_null($inGroup)) {
92
+            return (bool)$inGroup;
93
+        }
94
+
95
+        $userDN = $this->access->username2dn($uid);
96
+
97
+        if(isset($this->cachedGroupMembers[$gid])) {
98
+            $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
99
+            return $isInGroup;
100
+        }
101
+
102
+        $cacheKeyMembers = 'inGroup-members:'.$gid;
103
+        $members = $this->access->connection->getFromCache($cacheKeyMembers);
104
+        if(!is_null($members)) {
105
+            $this->cachedGroupMembers[$gid] = $members;
106
+            $isInGroup = in_array($userDN, $members);
107
+            $this->access->connection->writeToCache($cacheKey, $isInGroup);
108
+            return $isInGroup;
109
+        }
110
+
111
+        $groupDN = $this->access->groupname2dn($gid);
112
+        // just in case
113
+        if(!$groupDN || !$userDN) {
114
+            $this->access->connection->writeToCache($cacheKey, false);
115
+            return false;
116
+        }
117
+
118
+        //check primary group first
119
+        if($gid === $this->getUserPrimaryGroup($userDN)) {
120
+            $this->access->connection->writeToCache($cacheKey, true);
121
+            return true;
122
+        }
123
+
124
+        //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
125
+        $members = $this->_groupMembers($groupDN);
126
+        $members = array_keys($members); // uids are returned as keys
127
+        if(!is_array($members) || count($members) === 0) {
128
+            $this->access->connection->writeToCache($cacheKey, false);
129
+            return false;
130
+        }
131
+
132
+        //extra work if we don't get back user DNs
133
+        if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
134
+            $dns = array();
135
+            $filterParts = array();
136
+            $bytes = 0;
137
+            foreach($members as $mid) {
138
+                $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
139
+                $filterParts[] = $filter;
140
+                $bytes += strlen($filter);
141
+                if($bytes >= 9000000) {
142
+                    // AD has a default input buffer of 10 MB, we do not want
143
+                    // to take even the chance to exceed it
144
+                    $filter = $this->access->combineFilterWithOr($filterParts);
145
+                    $bytes = 0;
146
+                    $filterParts = array();
147
+                    $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
148
+                    $dns = array_merge($dns, $users);
149
+                }
150
+            }
151
+            if(count($filterParts) > 0) {
152
+                $filter = $this->access->combineFilterWithOr($filterParts);
153
+                $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
154
+                $dns = array_merge($dns, $users);
155
+            }
156
+            $members = $dns;
157
+        }
158
+
159
+        $isInGroup = in_array($userDN, $members);
160
+        $this->access->connection->writeToCache($cacheKey, $isInGroup);
161
+        $this->access->connection->writeToCache($cacheKeyMembers, $members);
162
+        $this->cachedGroupMembers[$gid] = $members;
163
+
164
+        return $isInGroup;
165
+    }
166
+
167
+    /**
168
+     * @param string $dnGroup
169
+     * @return array
170
+     *
171
+     * For a group that has user membership defined by an LDAP search url attribute returns the users
172
+     * that match the search url otherwise returns an empty array.
173
+     */
174
+    public function getDynamicGroupMembers($dnGroup) {
175
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
176
+
177
+        if (empty($dynamicGroupMemberURL)) {
178
+            return array();
179
+        }
180
+
181
+        $dynamicMembers = array();
182
+        $memberURLs = $this->access->readAttribute(
183
+            $dnGroup,
184
+            $dynamicGroupMemberURL,
185
+            $this->access->connection->ldapGroupFilter
186
+        );
187
+        if ($memberURLs !== false) {
188
+            // this group has the 'memberURL' attribute so this is a dynamic group
189
+            // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
190
+            // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
191
+            $pos = strpos($memberURLs[0], '(');
192
+            if ($pos !== false) {
193
+                $memberUrlFilter = substr($memberURLs[0], $pos);
194
+                $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
195
+                $dynamicMembers = array();
196
+                foreach($foundMembers as $value) {
197
+                    $dynamicMembers[$value['dn'][0]] = 1;
198
+                }
199
+            } else {
200
+                \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
201
+                    'of group ' . $dnGroup, ILogger::DEBUG);
202
+            }
203
+        }
204
+        return $dynamicMembers;
205
+    }
206
+
207
+    /**
208
+     * @param string $dnGroup
209
+     * @param array|null &$seen
210
+     * @return array|mixed|null
211
+     * @throws \OC\ServerNotAvailableException
212
+     */
213
+    private function _groupMembers($dnGroup, &$seen = null) {
214
+        if ($seen === null) {
215
+            $seen = array();
216
+        }
217
+        $allMembers = array();
218
+        if (array_key_exists($dnGroup, $seen)) {
219
+            // avoid loops
220
+            return array();
221
+        }
222
+        // used extensively in cron job, caching makes sense for nested groups
223
+        $cacheKey = '_groupMembers'.$dnGroup;
224
+        $groupMembers = $this->access->connection->getFromCache($cacheKey);
225
+        if($groupMembers !== null) {
226
+            return $groupMembers;
227
+        }
228
+        $seen[$dnGroup] = 1;
229
+        $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr,
230
+                                                $this->access->connection->ldapGroupFilter);
231
+        if (is_array($members)) {
232
+            foreach ($members as $member) {
233
+                $allMembers[$member] = 1;
234
+                $nestedGroups = $this->access->connection->ldapNestedGroups;
235
+                if (!empty($nestedGroups)) {
236
+                    $subMembers = $this->_groupMembers($member, $seen);
237
+                    if ($subMembers) {
238
+                        $allMembers += $subMembers;
239
+                    }
240
+                }
241
+            }
242
+        }
243
+
244
+        $allMembers += $this->getDynamicGroupMembers($dnGroup);
245
+
246
+        $this->access->connection->writeToCache($cacheKey, $allMembers);
247
+        return $allMembers;
248
+    }
249
+
250
+    /**
251
+     * @param string $DN
252
+     * @param array|null &$seen
253
+     * @return array
254
+     */
255
+    private function _getGroupDNsFromMemberOf($DN, &$seen = null) {
256
+        if ($seen === null) {
257
+            $seen = array();
258
+        }
259
+        if (array_key_exists($DN, $seen)) {
260
+            // avoid loops
261
+            return array();
262
+        }
263
+        $seen[$DN] = 1;
264
+        $groups = $this->access->readAttribute($DN, 'memberOf');
265
+        if (!is_array($groups)) {
266
+            return array();
267
+        }
268
+        $groups = $this->access->groupsMatchFilter($groups);
269
+        $allGroups =  $groups;
270
+        $nestedGroups = $this->access->connection->ldapNestedGroups;
271
+        if ((int)$nestedGroups === 1) {
272
+            foreach ($groups as $group) {
273
+                $subGroups = $this->_getGroupDNsFromMemberOf($group, $seen);
274
+                $allGroups = array_merge($allGroups, $subGroups);
275
+            }
276
+        }
277
+        return $allGroups;
278
+    }
279
+
280
+    /**
281
+     * translates a gidNumber into an ownCloud internal name
282
+     * @param string $gid as given by gidNumber on POSIX LDAP
283
+     * @param string $dn a DN that belongs to the same domain as the group
284
+     * @return string|bool
285
+     */
286
+    public function gidNumber2Name($gid, $dn) {
287
+        $cacheKey = 'gidNumberToName' . $gid;
288
+        $groupName = $this->access->connection->getFromCache($cacheKey);
289
+        if(!is_null($groupName) && isset($groupName)) {
290
+            return $groupName;
291
+        }
292
+
293
+        //we need to get the DN from LDAP
294
+        $filter = $this->access->combineFilterWithAnd([
295
+            $this->access->connection->ldapGroupFilter,
296
+            'objectClass=posixGroup',
297
+            $this->access->connection->ldapGidNumber . '=' . $gid
298
+        ]);
299
+        $result = $this->access->searchGroups($filter, array('dn'), 1);
300
+        if(empty($result)) {
301
+            return false;
302
+        }
303
+        $dn = $result[0]['dn'][0];
304
+
305
+        //and now the group name
306
+        //NOTE once we have separate ownCloud group IDs and group names we can
307
+        //directly read the display name attribute instead of the DN
308
+        $name = $this->access->dn2groupname($dn);
309
+
310
+        $this->access->connection->writeToCache($cacheKey, $name);
311
+
312
+        return $name;
313
+    }
314
+
315
+    /**
316
+     * returns the entry's gidNumber
317
+     * @param string $dn
318
+     * @param string $attribute
319
+     * @return string|bool
320
+     */
321
+    private function getEntryGidNumber($dn, $attribute) {
322
+        $value = $this->access->readAttribute($dn, $attribute);
323
+        if(is_array($value) && !empty($value)) {
324
+            return $value[0];
325
+        }
326
+        return false;
327
+    }
328
+
329
+    /**
330
+     * returns the group's primary ID
331
+     * @param string $dn
332
+     * @return string|bool
333
+     */
334
+    public function getGroupGidNumber($dn) {
335
+        return $this->getEntryGidNumber($dn, 'gidNumber');
336
+    }
337
+
338
+    /**
339
+     * returns the user's gidNumber
340
+     * @param string $dn
341
+     * @return string|bool
342
+     */
343
+    public function getUserGidNumber($dn) {
344
+        $gidNumber = false;
345
+        if($this->access->connection->hasGidNumber) {
346
+            $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
347
+            if($gidNumber === false) {
348
+                $this->access->connection->hasGidNumber = false;
349
+            }
350
+        }
351
+        return $gidNumber;
352
+    }
353
+
354
+    /**
355
+     * returns a filter for a "users has specific gid" search or count operation
356
+     *
357
+     * @param string $groupDN
358
+     * @param string $search
359
+     * @return string
360
+     * @throws \Exception
361
+     */
362
+    private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
363
+        $groupID = $this->getGroupGidNumber($groupDN);
364
+        if($groupID === false) {
365
+            throw new \Exception('Not a valid group');
366
+        }
367
+
368
+        $filterParts = [];
369
+        $filterParts[] = $this->access->getFilterForUserCount();
370
+        if ($search !== '') {
371
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
372
+        }
373
+        $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
374
+
375
+        return $this->access->combineFilterWithAnd($filterParts);
376
+    }
377
+
378
+    /**
379
+     * returns a list of users that have the given group as gid number
380
+     *
381
+     * @param string $groupDN
382
+     * @param string $search
383
+     * @param int $limit
384
+     * @param int $offset
385
+     * @return string[]
386
+     */
387
+    public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
388
+        try {
389
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
390
+            $users = $this->access->fetchListOfUsers(
391
+                $filter,
392
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
393
+                $limit,
394
+                $offset
395
+            );
396
+            return $this->access->nextcloudUserNames($users);
397
+        } catch (\Exception $e) {
398
+            return [];
399
+        }
400
+    }
401
+
402
+    /**
403
+     * returns the number of users that have the given group as gid number
404
+     *
405
+     * @param string $groupDN
406
+     * @param string $search
407
+     * @param int $limit
408
+     * @param int $offset
409
+     * @return int
410
+     */
411
+    public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
412
+        try {
413
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
414
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
415
+            return (int)$users;
416
+        } catch (\Exception $e) {
417
+            return 0;
418
+        }
419
+    }
420
+
421
+    /**
422
+     * gets the gidNumber of a user
423
+     * @param string $dn
424
+     * @return string
425
+     */
426
+    public function getUserGroupByGid($dn) {
427
+        $groupID = $this->getUserGidNumber($dn);
428
+        if($groupID !== false) {
429
+            $groupName = $this->gidNumber2Name($groupID, $dn);
430
+            if($groupName !== false) {
431
+                return $groupName;
432
+            }
433
+        }
434
+
435
+        return false;
436
+    }
437
+
438
+    /**
439
+     * translates a primary group ID into an Nextcloud internal name
440
+     * @param string $gid as given by primaryGroupID on AD
441
+     * @param string $dn a DN that belongs to the same domain as the group
442
+     * @return string|bool
443
+     */
444
+    public function primaryGroupID2Name($gid, $dn) {
445
+        $cacheKey = 'primaryGroupIDtoName';
446
+        $groupNames = $this->access->connection->getFromCache($cacheKey);
447
+        if(!is_null($groupNames) && isset($groupNames[$gid])) {
448
+            return $groupNames[$gid];
449
+        }
450
+
451
+        $domainObjectSid = $this->access->getSID($dn);
452
+        if($domainObjectSid === false) {
453
+            return false;
454
+        }
455
+
456
+        //we need to get the DN from LDAP
457
+        $filter = $this->access->combineFilterWithAnd(array(
458
+            $this->access->connection->ldapGroupFilter,
459
+            'objectsid=' . $domainObjectSid . '-' . $gid
460
+        ));
461
+        $result = $this->access->searchGroups($filter, array('dn'), 1);
462
+        if(empty($result)) {
463
+            return false;
464
+        }
465
+        $dn = $result[0]['dn'][0];
466
+
467
+        //and now the group name
468
+        //NOTE once we have separate Nextcloud group IDs and group names we can
469
+        //directly read the display name attribute instead of the DN
470
+        $name = $this->access->dn2groupname($dn);
471
+
472
+        $this->access->connection->writeToCache($cacheKey, $name);
473
+
474
+        return $name;
475
+    }
476
+
477
+    /**
478
+     * returns the entry's primary group ID
479
+     * @param string $dn
480
+     * @param string $attribute
481
+     * @return string|bool
482
+     */
483
+    private function getEntryGroupID($dn, $attribute) {
484
+        $value = $this->access->readAttribute($dn, $attribute);
485
+        if(is_array($value) && !empty($value)) {
486
+            return $value[0];
487
+        }
488
+        return false;
489
+    }
490
+
491
+    /**
492
+     * returns the group's primary ID
493
+     * @param string $dn
494
+     * @return string|bool
495
+     */
496
+    public function getGroupPrimaryGroupID($dn) {
497
+        return $this->getEntryGroupID($dn, 'primaryGroupToken');
498
+    }
499
+
500
+    /**
501
+     * returns the user's primary group ID
502
+     * @param string $dn
503
+     * @return string|bool
504
+     */
505
+    public function getUserPrimaryGroupIDs($dn) {
506
+        $primaryGroupID = false;
507
+        if($this->access->connection->hasPrimaryGroups) {
508
+            $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
509
+            if($primaryGroupID === false) {
510
+                $this->access->connection->hasPrimaryGroups = false;
511
+            }
512
+        }
513
+        return $primaryGroupID;
514
+    }
515
+
516
+    /**
517
+     * returns a filter for a "users in primary group" search or count operation
518
+     *
519
+     * @param string $groupDN
520
+     * @param string $search
521
+     * @return string
522
+     * @throws \Exception
523
+     */
524
+    private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
525
+        $groupID = $this->getGroupPrimaryGroupID($groupDN);
526
+        if($groupID === false) {
527
+            throw new \Exception('Not a valid group');
528
+        }
529
+
530
+        $filterParts = [];
531
+        $filterParts[] = $this->access->getFilterForUserCount();
532
+        if ($search !== '') {
533
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
534
+        }
535
+        $filterParts[] = 'primaryGroupID=' . $groupID;
536
+
537
+        return $this->access->combineFilterWithAnd($filterParts);
538
+    }
539
+
540
+    /**
541
+     * returns a list of users that have the given group as primary group
542
+     *
543
+     * @param string $groupDN
544
+     * @param string $search
545
+     * @param int $limit
546
+     * @param int $offset
547
+     * @return string[]
548
+     */
549
+    public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
550
+        try {
551
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
552
+            $users = $this->access->fetchListOfUsers(
553
+                $filter,
554
+                array($this->access->connection->ldapUserDisplayName, 'dn'),
555
+                $limit,
556
+                $offset
557
+            );
558
+            return $this->access->nextcloudUserNames($users);
559
+        } catch (\Exception $e) {
560
+            return array();
561
+        }
562
+    }
563
+
564
+    /**
565
+     * returns the number of users that have the given group as primary group
566
+     *
567
+     * @param string $groupDN
568
+     * @param string $search
569
+     * @param int $limit
570
+     * @param int $offset
571
+     * @return int
572
+     */
573
+    public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
574
+        try {
575
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
576
+            $users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
577
+            return (int)$users;
578
+        } catch (\Exception $e) {
579
+            return 0;
580
+        }
581
+    }
582
+
583
+    /**
584
+     * gets the primary group of a user
585
+     * @param string $dn
586
+     * @return string
587
+     */
588
+    public function getUserPrimaryGroup($dn) {
589
+        $groupID = $this->getUserPrimaryGroupIDs($dn);
590
+        if($groupID !== false) {
591
+            $groupName = $this->primaryGroupID2Name($groupID, $dn);
592
+            if($groupName !== false) {
593
+                return $groupName;
594
+            }
595
+        }
596
+
597
+        return false;
598
+    }
599
+
600
+    /**
601
+     * Get all groups a user belongs to
602
+     * @param string $uid Name of the user
603
+     * @return array with group names
604
+     *
605
+     * This function fetches all groups a user belongs to. It does not check
606
+     * if the user exists at all.
607
+     *
608
+     * This function includes groups based on dynamic group membership.
609
+     */
610
+    public function getUserGroups($uid) {
611
+        if(!$this->enabled) {
612
+            return array();
613
+        }
614
+        $cacheKey = 'getUserGroups'.$uid;
615
+        $userGroups = $this->access->connection->getFromCache($cacheKey);
616
+        if(!is_null($userGroups)) {
617
+            return $userGroups;
618
+        }
619
+        $userDN = $this->access->username2dn($uid);
620
+        if(!$userDN) {
621
+            $this->access->connection->writeToCache($cacheKey, array());
622
+            return array();
623
+        }
624
+
625
+        $groups = [];
626
+        $primaryGroup = $this->getUserPrimaryGroup($userDN);
627
+        $gidGroupName = $this->getUserGroupByGid($userDN);
628
+
629
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
630
+
631
+        if (!empty($dynamicGroupMemberURL)) {
632
+            // look through dynamic groups to add them to the result array if needed
633
+            $groupsToMatch = $this->access->fetchListOfGroups(
634
+                $this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
635
+            foreach($groupsToMatch as $dynamicGroup) {
636
+                if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
637
+                    continue;
638
+                }
639
+                $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
640
+                if ($pos !== false) {
641
+                    $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
642
+                    // apply filter via ldap search to see if this user is in this
643
+                    // dynamic group
644
+                    $userMatch = $this->access->readAttribute(
645
+                        $userDN,
646
+                        $this->access->connection->ldapUserDisplayName,
647
+                        $memberUrlFilter
648
+                    );
649
+                    if ($userMatch !== false) {
650
+                        // match found so this user is in this group
651
+                        $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
652
+                        if(is_string($groupName)) {
653
+                            // be sure to never return false if the dn could not be
654
+                            // resolved to a name, for whatever reason.
655
+                            $groups[] = $groupName;
656
+                        }
657
+                    }
658
+                } else {
659
+                    \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
660
+                        'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
661
+                }
662
+            }
663
+        }
664
+
665
+        // if possible, read out membership via memberOf. It's far faster than
666
+        // performing a search, which still is a fallback later.
667
+        // memberof doesn't support memberuid, so skip it here.
668
+        if((int)$this->access->connection->hasMemberOfFilterSupport === 1
669
+            && (int)$this->access->connection->useMemberOfToDetectMembership === 1
670
+            && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
671
+            ) {
672
+            $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
673
+            if (is_array($groupDNs)) {
674
+                foreach ($groupDNs as $dn) {
675
+                    $groupName = $this->access->dn2groupname($dn);
676
+                    if(is_string($groupName)) {
677
+                        // be sure to never return false if the dn could not be
678
+                        // resolved to a name, for whatever reason.
679
+                        $groups[] = $groupName;
680
+                    }
681
+                }
682
+            }
683
+
684
+            if($primaryGroup !== false) {
685
+                $groups[] = $primaryGroup;
686
+            }
687
+            if($gidGroupName !== false) {
688
+                $groups[] = $gidGroupName;
689
+            }
690
+            $this->access->connection->writeToCache($cacheKey, $groups);
691
+            return $groups;
692
+        }
693
+
694
+        //uniqueMember takes DN, memberuid the uid, so we need to distinguish
695
+        if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
696
+            || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
697
+        ) {
698
+            $uid = $userDN;
699
+        } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
700
+            $result = $this->access->readAttribute($userDN, 'uid');
701
+            if ($result === false) {
702
+                \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
703
+                    $this->access->connection->ldapHost, ILogger::DEBUG);
704
+            }
705
+            $uid = $result[0];
706
+        } else {
707
+            // just in case
708
+            $uid = $userDN;
709
+        }
710
+
711
+        if(isset($this->cachedGroupsByMember[$uid])) {
712
+            $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
713
+        } else {
714
+            $groupsByMember = array_values($this->getGroupsByMember($uid));
715
+            $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
716
+            $this->cachedGroupsByMember[$uid] = $groupsByMember;
717
+            $groups = array_merge($groups, $groupsByMember);
718
+        }
719
+
720
+        if($primaryGroup !== false) {
721
+            $groups[] = $primaryGroup;
722
+        }
723
+        if($gidGroupName !== false) {
724
+            $groups[] = $gidGroupName;
725
+        }
726
+
727
+        $groups = array_unique($groups, SORT_LOCALE_STRING);
728
+        $this->access->connection->writeToCache($cacheKey, $groups);
729
+
730
+        return $groups;
731
+    }
732
+
733
+    /**
734
+     * @param string $dn
735
+     * @param array|null &$seen
736
+     * @return array
737
+     */
738
+    private function getGroupsByMember($dn, &$seen = null) {
739
+        if ($seen === null) {
740
+            $seen = array();
741
+        }
742
+        $allGroups = array();
743
+        if (array_key_exists($dn, $seen)) {
744
+            // avoid loops
745
+            return array();
746
+        }
747
+        $seen[$dn] = true;
748
+        $filter = $this->access->combineFilterWithAnd(array(
749
+            $this->access->connection->ldapGroupFilter,
750
+            $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn
751
+        ));
752
+        $groups = $this->access->fetchListOfGroups($filter,
753
+            array($this->access->connection->ldapGroupDisplayName, 'dn'));
754
+        if (is_array($groups)) {
755
+            foreach ($groups as $groupobj) {
756
+                $groupDN = $groupobj['dn'][0];
757
+                $allGroups[$groupDN] = $groupobj;
758
+                $nestedGroups = $this->access->connection->ldapNestedGroups;
759
+                if (!empty($nestedGroups)) {
760
+                    $supergroups = $this->getGroupsByMember($groupDN, $seen);
761
+                    if (is_array($supergroups) && (count($supergroups)>0)) {
762
+                        $allGroups = array_merge($allGroups, $supergroups);
763
+                    }
764
+                }
765
+            }
766
+        }
767
+        return $allGroups;
768
+    }
769
+
770
+    /**
771
+     * get a list of all users in a group
772
+     *
773
+     * @param string $gid
774
+     * @param string $search
775
+     * @param int $limit
776
+     * @param int $offset
777
+     * @return array with user ids
778
+     */
779
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
780
+        if(!$this->enabled) {
781
+            return array();
782
+        }
783
+        if(!$this->groupExists($gid)) {
784
+            return array();
785
+        }
786
+        $search = $this->access->escapeFilterPart($search, true);
787
+        $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
788
+        // check for cache of the exact query
789
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
790
+        if(!is_null($groupUsers)) {
791
+            return $groupUsers;
792
+        }
793
+
794
+        // check for cache of the query without limit and offset
795
+        $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
796
+        if(!is_null($groupUsers)) {
797
+            $groupUsers = array_slice($groupUsers, $offset, $limit);
798
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
799
+            return $groupUsers;
800
+        }
801
+
802
+        if($limit === -1) {
803
+            $limit = null;
804
+        }
805
+        $groupDN = $this->access->groupname2dn($gid);
806
+        if(!$groupDN) {
807
+            // group couldn't be found, return empty resultset
808
+            $this->access->connection->writeToCache($cacheKey, array());
809
+            return array();
810
+        }
811
+
812
+        $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
813
+        $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
814
+        $members = array_keys($this->_groupMembers($groupDN));
815
+        if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
816
+            //in case users could not be retrieved, return empty result set
817
+            $this->access->connection->writeToCache($cacheKey, []);
818
+            return [];
819
+        }
820
+
821
+        $groupUsers = array();
822
+        $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
823
+        $attrs = $this->access->userManager->getAttributes(true);
824
+        foreach($members as $member) {
825
+            if($isMemberUid) {
826
+                //we got uids, need to get their DNs to 'translate' them to user names
827
+                $filter = $this->access->combineFilterWithAnd(array(
828
+                    str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
829
+                    $this->access->getFilterPartForUserSearch($search)
830
+                ));
831
+                $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
832
+                if(count($ldap_users) < 1) {
833
+                    continue;
834
+                }
835
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
836
+            } else {
837
+                //we got DNs, check if we need to filter by search or we can give back all of them
838
+                if ($search !== '') {
839
+                    if(!$this->access->readAttribute($member,
840
+                        $this->access->connection->ldapUserDisplayName,
841
+                        $this->access->getFilterPartForUserSearch($search))) {
842
+                        continue;
843
+                    }
844
+                }
845
+                // dn2username will also check if the users belong to the allowed base
846
+                if($ocname = $this->access->dn2username($member)) {
847
+                    $groupUsers[] = $ocname;
848
+                }
849
+            }
850
+        }
851
+
852
+        $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
853
+        natsort($groupUsers);
854
+        $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
855
+        $groupUsers = array_slice($groupUsers, $offset, $limit);
856
+
857
+        $this->access->connection->writeToCache($cacheKey, $groupUsers);
858
+
859
+        return $groupUsers;
860
+    }
861
+
862
+    /**
863
+     * returns the number of users in a group, who match the search term
864
+     * @param string $gid the internal group name
865
+     * @param string $search optional, a search string
866
+     * @return int|bool
867
+     */
868
+    public function countUsersInGroup($gid, $search = '') {
869
+        if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
870
+            return $this->groupPluginManager->countUsersInGroup($gid, $search);
871
+        }
872
+
873
+        $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
874
+        if(!$this->enabled || !$this->groupExists($gid)) {
875
+            return false;
876
+        }
877
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
878
+        if(!is_null($groupUsers)) {
879
+            return $groupUsers;
880
+        }
881
+
882
+        $groupDN = $this->access->groupname2dn($gid);
883
+        if(!$groupDN) {
884
+            // group couldn't be found, return empty result set
885
+            $this->access->connection->writeToCache($cacheKey, false);
886
+            return false;
887
+        }
888
+
889
+        $members = array_keys($this->_groupMembers($groupDN));
890
+        $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
891
+        if(!$members && $primaryUserCount === 0) {
892
+            //in case users could not be retrieved, return empty result set
893
+            $this->access->connection->writeToCache($cacheKey, false);
894
+            return false;
895
+        }
896
+
897
+        if ($search === '') {
898
+            $groupUsers = count($members) + $primaryUserCount;
899
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
900
+            return $groupUsers;
901
+        }
902
+        $search = $this->access->escapeFilterPart($search, true);
903
+        $isMemberUid =
904
+            (strtolower($this->access->connection->ldapGroupMemberAssocAttr)
905
+            === 'memberuid');
906
+
907
+        //we need to apply the search filter
908
+        //alternatives that need to be checked:
909
+        //a) get all users by search filter and array_intersect them
910
+        //b) a, but only when less than 1k 10k ?k users like it is
911
+        //c) put all DNs|uids in a LDAP filter, combine with the search string
912
+        //   and let it count.
913
+        //For now this is not important, because the only use of this method
914
+        //does not supply a search string
915
+        $groupUsers = array();
916
+        foreach($members as $member) {
917
+            if($isMemberUid) {
918
+                //we got uids, need to get their DNs to 'translate' them to user names
919
+                $filter = $this->access->combineFilterWithAnd(array(
920
+                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
921
+                    $this->access->getFilterPartForUserSearch($search)
922
+                ));
923
+                $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
924
+                if(count($ldap_users) < 1) {
925
+                    continue;
926
+                }
927
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]);
928
+            } else {
929
+                //we need to apply the search filter now
930
+                if(!$this->access->readAttribute($member,
931
+                    $this->access->connection->ldapUserDisplayName,
932
+                    $this->access->getFilterPartForUserSearch($search))) {
933
+                    continue;
934
+                }
935
+                // dn2username will also check if the users belong to the allowed base
936
+                if($ocname = $this->access->dn2username($member)) {
937
+                    $groupUsers[] = $ocname;
938
+                }
939
+            }
940
+        }
941
+
942
+        //and get users that have the group as primary
943
+        $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
944
+
945
+        return count($groupUsers) + $primaryUsers;
946
+    }
947
+
948
+    /**
949
+     * get a list of all groups
950
+     *
951
+     * @param string $search
952
+     * @param $limit
953
+     * @param int $offset
954
+     * @return array with group names
955
+     *
956
+     * Returns a list with all groups (used by getGroups)
957
+     */
958
+    protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
959
+        if(!$this->enabled) {
960
+            return array();
961
+        }
962
+        $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
963
+
964
+        //Check cache before driving unnecessary searches
965
+        \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
966
+        $ldap_groups = $this->access->connection->getFromCache($cacheKey);
967
+        if(!is_null($ldap_groups)) {
968
+            return $ldap_groups;
969
+        }
970
+
971
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
972
+        // error. With a limit of 0, we get 0 results. So we pass null.
973
+        if($limit <= 0) {
974
+            $limit = null;
975
+        }
976
+        $filter = $this->access->combineFilterWithAnd(array(
977
+            $this->access->connection->ldapGroupFilter,
978
+            $this->access->getFilterPartForGroupSearch($search)
979
+        ));
980
+        \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
981
+        $ldap_groups = $this->access->fetchListOfGroups($filter,
982
+                array($this->access->connection->ldapGroupDisplayName, 'dn'),
983
+                $limit,
984
+                $offset);
985
+        $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
986
+
987
+        $this->access->connection->writeToCache($cacheKey, $ldap_groups);
988
+        return $ldap_groups;
989
+    }
990
+
991
+    /**
992
+     * get a list of all groups using a paged search
993
+     *
994
+     * @param string $search
995
+     * @param int $limit
996
+     * @param int $offset
997
+     * @return array with group names
998
+     *
999
+     * Returns a list with all groups
1000
+     * Uses a paged search if available to override a
1001
+     * server side search limit.
1002
+     * (active directory has a limit of 1000 by default)
1003
+     */
1004
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
1005
+        if(!$this->enabled) {
1006
+            return array();
1007
+        }
1008
+        $search = $this->access->escapeFilterPart($search, true);
1009
+        $pagingSize = (int)$this->access->connection->ldapPagingSize;
1010
+        if ($pagingSize <= 0) {
1011
+            return $this->getGroupsChunk($search, $limit, $offset);
1012
+        }
1013
+        $maxGroups = 100000; // limit max results (just for safety reasons)
1014
+        if ($limit > -1) {
1015
+            $overallLimit = min($limit + $offset, $maxGroups);
1016
+        } else {
1017
+            $overallLimit = $maxGroups;
1018
+        }
1019
+        $chunkOffset = $offset;
1020
+        $allGroups = array();
1021
+        while ($chunkOffset < $overallLimit) {
1022
+            $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1023
+            $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1024
+            $nread = count($ldapGroups);
1025
+            \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1026
+            if ($nread) {
1027
+                $allGroups = array_merge($allGroups, $ldapGroups);
1028
+                $chunkOffset += $nread;
1029
+            }
1030
+            if ($nread < $chunkLimit) {
1031
+                break;
1032
+            }
1033
+        }
1034
+        return $allGroups;
1035
+    }
1036
+
1037
+    /**
1038
+     * @param string $group
1039
+     * @return bool
1040
+     */
1041
+    public function groupMatchesFilter($group) {
1042
+        return (strripos($group, $this->groupSearch) !== false);
1043
+    }
1044
+
1045
+    /**
1046
+     * check if a group exists
1047
+     * @param string $gid
1048
+     * @return bool
1049
+     */
1050
+    public function groupExists($gid) {
1051
+        $groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1052
+        if(!is_null($groupExists)) {
1053
+            return (bool)$groupExists;
1054
+        }
1055
+
1056
+        //getting dn, if false the group does not exist. If dn, it may be mapped
1057
+        //only, requires more checking.
1058
+        $dn = $this->access->groupname2dn($gid);
1059
+        if(!$dn) {
1060
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1061
+            return false;
1062
+        }
1063
+
1064
+        //if group really still exists, we will be able to read its objectclass
1065
+        if(!is_array($this->access->readAttribute($dn, ''))) {
1066
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1067
+            return false;
1068
+        }
1069
+
1070
+        $this->access->connection->writeToCache('groupExists'.$gid, true);
1071
+        return true;
1072
+    }
1073
+
1074
+    /**
1075
+     * Check if backend implements actions
1076
+     * @param int $actions bitwise-or'ed actions
1077
+     * @return boolean
1078
+     *
1079
+     * Returns the supported actions as int to be
1080
+     * compared with GroupInterface::CREATE_GROUP etc.
1081
+     */
1082
+    public function implementsActions($actions) {
1083
+        return (bool)((GroupInterface::COUNT_USERS |
1084
+                $this->groupPluginManager->getImplementedActions()) & $actions);
1085
+    }
1086
+
1087
+    /**
1088
+     * Return access for LDAP interaction.
1089
+     * @return Access instance of Access for LDAP interaction
1090
+     */
1091
+    public function getLDAPAccess($gid) {
1092
+        return $this->access;
1093
+    }
1094
+
1095
+    /**
1096
+     * create a group
1097
+     * @param string $gid
1098
+     * @return bool
1099
+     * @throws \Exception
1100
+     */
1101
+    public function createGroup($gid) {
1102
+        if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1103
+            if ($dn = $this->groupPluginManager->createGroup($gid)) {
1104
+                //updates group mapping
1105
+                $this->access->dn2ocname($dn, $gid, false);
1106
+                $this->access->connection->writeToCache("groupExists".$gid, true);
1107
+            }
1108
+            return $dn != null;
1109
+        }
1110
+        throw new \Exception('Could not create group in LDAP backend.');
1111
+    }
1112
+
1113
+    /**
1114
+     * delete a group
1115
+     * @param string $gid gid of the group to delete
1116
+     * @return bool
1117
+     * @throws \Exception
1118
+     */
1119
+    public function deleteGroup($gid) {
1120
+        if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1121
+            if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1122
+                #delete group in nextcloud internal db
1123
+                $this->access->getGroupMapper()->unmap($gid);
1124
+                $this->access->connection->writeToCache("groupExists".$gid, false);
1125
+            }
1126
+            return $ret;
1127
+        }
1128
+        throw new \Exception('Could not delete group in LDAP backend.');
1129
+    }
1130
+
1131
+    /**
1132
+     * Add a user to a group
1133
+     * @param string $uid Name of the user to add to group
1134
+     * @param string $gid Name of the group in which add the user
1135
+     * @return bool
1136
+     * @throws \Exception
1137
+     */
1138
+    public function addToGroup($uid, $gid) {
1139
+        if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1140
+            if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1141
+                $this->access->connection->clearCache();
1142
+            }
1143
+            return $ret;
1144
+        }
1145
+        throw new \Exception('Could not add user to group in LDAP backend.');
1146
+    }
1147
+
1148
+    /**
1149
+     * Removes a user from a group
1150
+     * @param string $uid Name of the user to remove from group
1151
+     * @param string $gid Name of the group from which remove the user
1152
+     * @return bool
1153
+     * @throws \Exception
1154
+     */
1155
+    public function removeFromGroup($uid, $gid) {
1156
+        if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1157
+            if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1158
+                $this->access->connection->clearCache();
1159
+            }
1160
+            return $ret;
1161
+        }
1162
+        throw new \Exception('Could not remove user from group in LDAP backend.');
1163
+    }
1164
+
1165
+    /**
1166
+     * Gets group details
1167
+     * @param string $gid Name of the group
1168
+     * @return array | false
1169
+     * @throws \Exception
1170
+     */
1171
+    public function getGroupDetails($gid) {
1172
+        if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1173
+            return $this->groupPluginManager->getGroupDetails($gid);
1174
+        }
1175
+        throw new \Exception('Could not get group details in LDAP backend.');
1176
+    }
1177
+
1178
+    /**
1179
+     * Return LDAP connection resource from a cloned connection.
1180
+     * The cloned connection needs to be closed manually.
1181
+     * of the current access.
1182
+     * @param string $gid
1183
+     * @return resource of the LDAP connection
1184
+     */
1185
+    public function getNewLDAPConnection($gid) {
1186
+        $connection = clone $this->access->getConnection();
1187
+        return $connection->getConnectionResource();
1188
+    }
1189 1189
 
1190 1190
 }
Please login to merge, or discard this patch.
Spacing   +94 added lines, -94 removed lines patch added patch discarded remove patch
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 		parent::__construct($access);
66 66
 		$filter = $this->access->connection->ldapGroupFilter;
67 67
 		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
68
-		if(!empty($filter) && !empty($gassoc)) {
68
+		if (!empty($filter) && !empty($gassoc)) {
69 69
 			$this->enabled = true;
70 70
 		}
71 71
 
@@ -83,25 +83,25 @@  discard block
 block discarded – undo
83 83
 	 * Checks whether the user is member of a group or not.
84 84
 	 */
85 85
 	public function inGroup($uid, $gid) {
86
-		if(!$this->enabled) {
86
+		if (!$this->enabled) {
87 87
 			return false;
88 88
 		}
89 89
 		$cacheKey = 'inGroup'.$uid.':'.$gid;
90 90
 		$inGroup = $this->access->connection->getFromCache($cacheKey);
91
-		if(!is_null($inGroup)) {
92
-			return (bool)$inGroup;
91
+		if (!is_null($inGroup)) {
92
+			return (bool) $inGroup;
93 93
 		}
94 94
 
95 95
 		$userDN = $this->access->username2dn($uid);
96 96
 
97
-		if(isset($this->cachedGroupMembers[$gid])) {
97
+		if (isset($this->cachedGroupMembers[$gid])) {
98 98
 			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
99 99
 			return $isInGroup;
100 100
 		}
101 101
 
102 102
 		$cacheKeyMembers = 'inGroup-members:'.$gid;
103 103
 		$members = $this->access->connection->getFromCache($cacheKeyMembers);
104
-		if(!is_null($members)) {
104
+		if (!is_null($members)) {
105 105
 			$this->cachedGroupMembers[$gid] = $members;
106 106
 			$isInGroup = in_array($userDN, $members);
107 107
 			$this->access->connection->writeToCache($cacheKey, $isInGroup);
@@ -110,13 +110,13 @@  discard block
 block discarded – undo
110 110
 
111 111
 		$groupDN = $this->access->groupname2dn($gid);
112 112
 		// just in case
113
-		if(!$groupDN || !$userDN) {
113
+		if (!$groupDN || !$userDN) {
114 114
 			$this->access->connection->writeToCache($cacheKey, false);
115 115
 			return false;
116 116
 		}
117 117
 
118 118
 		//check primary group first
119
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
119
+		if ($gid === $this->getUserPrimaryGroup($userDN)) {
120 120
 			$this->access->connection->writeToCache($cacheKey, true);
121 121
 			return true;
122 122
 		}
@@ -124,21 +124,21 @@  discard block
 block discarded – undo
124 124
 		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
125 125
 		$members = $this->_groupMembers($groupDN);
126 126
 		$members = array_keys($members); // uids are returned as keys
127
-		if(!is_array($members) || count($members) === 0) {
127
+		if (!is_array($members) || count($members) === 0) {
128 128
 			$this->access->connection->writeToCache($cacheKey, false);
129 129
 			return false;
130 130
 		}
131 131
 
132 132
 		//extra work if we don't get back user DNs
133
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
133
+		if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
134 134
 			$dns = array();
135 135
 			$filterParts = array();
136 136
 			$bytes = 0;
137
-			foreach($members as $mid) {
137
+			foreach ($members as $mid) {
138 138
 				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
139 139
 				$filterParts[] = $filter;
140 140
 				$bytes += strlen($filter);
141
-				if($bytes >= 9000000) {
141
+				if ($bytes >= 9000000) {
142 142
 					// AD has a default input buffer of 10 MB, we do not want
143 143
 					// to take even the chance to exceed it
144 144
 					$filter = $this->access->combineFilterWithOr($filterParts);
@@ -148,7 +148,7 @@  discard block
 block discarded – undo
148 148
 					$dns = array_merge($dns, $users);
149 149
 				}
150 150
 			}
151
-			if(count($filterParts) > 0) {
151
+			if (count($filterParts) > 0) {
152 152
 				$filter = $this->access->combineFilterWithOr($filterParts);
153 153
 				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
154 154
 				$dns = array_merge($dns, $users);
@@ -191,14 +191,14 @@  discard block
 block discarded – undo
191 191
 			$pos = strpos($memberURLs[0], '(');
192 192
 			if ($pos !== false) {
193 193
 				$memberUrlFilter = substr($memberURLs[0], $pos);
194
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
194
+				$foundMembers = $this->access->searchUsers($memberUrlFilter, 'dn');
195 195
 				$dynamicMembers = array();
196
-				foreach($foundMembers as $value) {
196
+				foreach ($foundMembers as $value) {
197 197
 					$dynamicMembers[$value['dn'][0]] = 1;
198 198
 				}
199 199
 			} else {
200 200
 				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
201
-					'of group ' . $dnGroup, ILogger::DEBUG);
201
+					'of group '.$dnGroup, ILogger::DEBUG);
202 202
 			}
203 203
 		}
204 204
 		return $dynamicMembers;
@@ -222,7 +222,7 @@  discard block
 block discarded – undo
222 222
 		// used extensively in cron job, caching makes sense for nested groups
223 223
 		$cacheKey = '_groupMembers'.$dnGroup;
224 224
 		$groupMembers = $this->access->connection->getFromCache($cacheKey);
225
-		if($groupMembers !== null) {
225
+		if ($groupMembers !== null) {
226 226
 			return $groupMembers;
227 227
 		}
228 228
 		$seen[$dnGroup] = 1;
@@ -266,9 +266,9 @@  discard block
 block discarded – undo
266 266
 			return array();
267 267
 		}
268 268
 		$groups = $this->access->groupsMatchFilter($groups);
269
-		$allGroups =  $groups;
269
+		$allGroups = $groups;
270 270
 		$nestedGroups = $this->access->connection->ldapNestedGroups;
271
-		if ((int)$nestedGroups === 1) {
271
+		if ((int) $nestedGroups === 1) {
272 272
 			foreach ($groups as $group) {
273 273
 				$subGroups = $this->_getGroupDNsFromMemberOf($group, $seen);
274 274
 				$allGroups = array_merge($allGroups, $subGroups);
@@ -284,9 +284,9 @@  discard block
 block discarded – undo
284 284
 	 * @return string|bool
285 285
 	 */
286 286
 	public function gidNumber2Name($gid, $dn) {
287
-		$cacheKey = 'gidNumberToName' . $gid;
287
+		$cacheKey = 'gidNumberToName'.$gid;
288 288
 		$groupName = $this->access->connection->getFromCache($cacheKey);
289
-		if(!is_null($groupName) && isset($groupName)) {
289
+		if (!is_null($groupName) && isset($groupName)) {
290 290
 			return $groupName;
291 291
 		}
292 292
 
@@ -294,10 +294,10 @@  discard block
 block discarded – undo
294 294
 		$filter = $this->access->combineFilterWithAnd([
295 295
 			$this->access->connection->ldapGroupFilter,
296 296
 			'objectClass=posixGroup',
297
-			$this->access->connection->ldapGidNumber . '=' . $gid
297
+			$this->access->connection->ldapGidNumber.'='.$gid
298 298
 		]);
299 299
 		$result = $this->access->searchGroups($filter, array('dn'), 1);
300
-		if(empty($result)) {
300
+		if (empty($result)) {
301 301
 			return false;
302 302
 		}
303 303
 		$dn = $result[0]['dn'][0];
@@ -320,7 +320,7 @@  discard block
 block discarded – undo
320 320
 	 */
321 321
 	private function getEntryGidNumber($dn, $attribute) {
322 322
 		$value = $this->access->readAttribute($dn, $attribute);
323
-		if(is_array($value) && !empty($value)) {
323
+		if (is_array($value) && !empty($value)) {
324 324
 			return $value[0];
325 325
 		}
326 326
 		return false;
@@ -342,9 +342,9 @@  discard block
 block discarded – undo
342 342
 	 */
343 343
 	public function getUserGidNumber($dn) {
344 344
 		$gidNumber = false;
345
-		if($this->access->connection->hasGidNumber) {
345
+		if ($this->access->connection->hasGidNumber) {
346 346
 			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
347
-			if($gidNumber === false) {
347
+			if ($gidNumber === false) {
348 348
 				$this->access->connection->hasGidNumber = false;
349 349
 			}
350 350
 		}
@@ -361,7 +361,7 @@  discard block
 block discarded – undo
361 361
 	 */
362 362
 	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
363 363
 		$groupID = $this->getGroupGidNumber($groupDN);
364
-		if($groupID === false) {
364
+		if ($groupID === false) {
365 365
 			throw new \Exception('Not a valid group');
366 366
 		}
367 367
 
@@ -370,7 +370,7 @@  discard block
 block discarded – undo
370 370
 		if ($search !== '') {
371 371
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
372 372
 		}
373
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
373
+		$filterParts[] = $this->access->connection->ldapGidNumber.'='.$groupID;
374 374
 
375 375
 		return $this->access->combineFilterWithAnd($filterParts);
376 376
 	}
@@ -412,7 +412,7 @@  discard block
 block discarded – undo
412 412
 		try {
413 413
 			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
414 414
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
415
-			return (int)$users;
415
+			return (int) $users;
416 416
 		} catch (\Exception $e) {
417 417
 			return 0;
418 418
 		}
@@ -425,9 +425,9 @@  discard block
 block discarded – undo
425 425
 	 */
426 426
 	public function getUserGroupByGid($dn) {
427 427
 		$groupID = $this->getUserGidNumber($dn);
428
-		if($groupID !== false) {
428
+		if ($groupID !== false) {
429 429
 			$groupName = $this->gidNumber2Name($groupID, $dn);
430
-			if($groupName !== false) {
430
+			if ($groupName !== false) {
431 431
 				return $groupName;
432 432
 			}
433 433
 		}
@@ -444,22 +444,22 @@  discard block
 block discarded – undo
444 444
 	public function primaryGroupID2Name($gid, $dn) {
445 445
 		$cacheKey = 'primaryGroupIDtoName';
446 446
 		$groupNames = $this->access->connection->getFromCache($cacheKey);
447
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
447
+		if (!is_null($groupNames) && isset($groupNames[$gid])) {
448 448
 			return $groupNames[$gid];
449 449
 		}
450 450
 
451 451
 		$domainObjectSid = $this->access->getSID($dn);
452
-		if($domainObjectSid === false) {
452
+		if ($domainObjectSid === false) {
453 453
 			return false;
454 454
 		}
455 455
 
456 456
 		//we need to get the DN from LDAP
457 457
 		$filter = $this->access->combineFilterWithAnd(array(
458 458
 			$this->access->connection->ldapGroupFilter,
459
-			'objectsid=' . $domainObjectSid . '-' . $gid
459
+			'objectsid='.$domainObjectSid.'-'.$gid
460 460
 		));
461 461
 		$result = $this->access->searchGroups($filter, array('dn'), 1);
462
-		if(empty($result)) {
462
+		if (empty($result)) {
463 463
 			return false;
464 464
 		}
465 465
 		$dn = $result[0]['dn'][0];
@@ -482,7 +482,7 @@  discard block
 block discarded – undo
482 482
 	 */
483 483
 	private function getEntryGroupID($dn, $attribute) {
484 484
 		$value = $this->access->readAttribute($dn, $attribute);
485
-		if(is_array($value) && !empty($value)) {
485
+		if (is_array($value) && !empty($value)) {
486 486
 			return $value[0];
487 487
 		}
488 488
 		return false;
@@ -504,9 +504,9 @@  discard block
 block discarded – undo
504 504
 	 */
505 505
 	public function getUserPrimaryGroupIDs($dn) {
506 506
 		$primaryGroupID = false;
507
-		if($this->access->connection->hasPrimaryGroups) {
507
+		if ($this->access->connection->hasPrimaryGroups) {
508 508
 			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
509
-			if($primaryGroupID === false) {
509
+			if ($primaryGroupID === false) {
510 510
 				$this->access->connection->hasPrimaryGroups = false;
511 511
 			}
512 512
 		}
@@ -523,7 +523,7 @@  discard block
 block discarded – undo
523 523
 	 */
524 524
 	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
525 525
 		$groupID = $this->getGroupPrimaryGroupID($groupDN);
526
-		if($groupID === false) {
526
+		if ($groupID === false) {
527 527
 			throw new \Exception('Not a valid group');
528 528
 		}
529 529
 
@@ -532,7 +532,7 @@  discard block
 block discarded – undo
532 532
 		if ($search !== '') {
533 533
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
534 534
 		}
535
-		$filterParts[] = 'primaryGroupID=' . $groupID;
535
+		$filterParts[] = 'primaryGroupID='.$groupID;
536 536
 
537 537
 		return $this->access->combineFilterWithAnd($filterParts);
538 538
 	}
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
 		try {
575 575
 			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
576 576
 			$users = $this->access->countUsers($filter, array('dn'), $limit, $offset);
577
-			return (int)$users;
577
+			return (int) $users;
578 578
 		} catch (\Exception $e) {
579 579
 			return 0;
580 580
 		}
@@ -587,9 +587,9 @@  discard block
 block discarded – undo
587 587
 	 */
588 588
 	public function getUserPrimaryGroup($dn) {
589 589
 		$groupID = $this->getUserPrimaryGroupIDs($dn);
590
-		if($groupID !== false) {
590
+		if ($groupID !== false) {
591 591
 			$groupName = $this->primaryGroupID2Name($groupID, $dn);
592
-			if($groupName !== false) {
592
+			if ($groupName !== false) {
593 593
 				return $groupName;
594 594
 			}
595 595
 		}
@@ -608,16 +608,16 @@  discard block
 block discarded – undo
608 608
 	 * This function includes groups based on dynamic group membership.
609 609
 	 */
610 610
 	public function getUserGroups($uid) {
611
-		if(!$this->enabled) {
611
+		if (!$this->enabled) {
612 612
 			return array();
613 613
 		}
614 614
 		$cacheKey = 'getUserGroups'.$uid;
615 615
 		$userGroups = $this->access->connection->getFromCache($cacheKey);
616
-		if(!is_null($userGroups)) {
616
+		if (!is_null($userGroups)) {
617 617
 			return $userGroups;
618 618
 		}
619 619
 		$userDN = $this->access->username2dn($uid);
620
-		if(!$userDN) {
620
+		if (!$userDN) {
621 621
 			$this->access->connection->writeToCache($cacheKey, array());
622 622
 			return array();
623 623
 		}
@@ -631,14 +631,14 @@  discard block
 block discarded – undo
631 631
 		if (!empty($dynamicGroupMemberURL)) {
632 632
 			// look through dynamic groups to add them to the result array if needed
633 633
 			$groupsToMatch = $this->access->fetchListOfGroups(
634
-				$this->access->connection->ldapGroupFilter,array('dn',$dynamicGroupMemberURL));
635
-			foreach($groupsToMatch as $dynamicGroup) {
634
+				$this->access->connection->ldapGroupFilter, array('dn', $dynamicGroupMemberURL));
635
+			foreach ($groupsToMatch as $dynamicGroup) {
636 636
 				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
637 637
 					continue;
638 638
 				}
639 639
 				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
640 640
 				if ($pos !== false) {
641
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
641
+					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
642 642
 					// apply filter via ldap search to see if this user is in this
643 643
 					// dynamic group
644 644
 					$userMatch = $this->access->readAttribute(
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 					if ($userMatch !== false) {
650 650
 						// match found so this user is in this group
651 651
 						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
652
-						if(is_string($groupName)) {
652
+						if (is_string($groupName)) {
653 653
 							// be sure to never return false if the dn could not be
654 654
 							// resolved to a name, for whatever reason.
655 655
 							$groups[] = $groupName;
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
 					}
658 658
 				} else {
659 659
 					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
660
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
660
+						'of group '.print_r($dynamicGroup, true), ILogger::DEBUG);
661 661
 				}
662 662
 			}
663 663
 		}
@@ -665,15 +665,15 @@  discard block
 block discarded – undo
665 665
 		// if possible, read out membership via memberOf. It's far faster than
666 666
 		// performing a search, which still is a fallback later.
667 667
 		// memberof doesn't support memberuid, so skip it here.
668
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
669
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
668
+		if ((int) $this->access->connection->hasMemberOfFilterSupport === 1
669
+			&& (int) $this->access->connection->useMemberOfToDetectMembership === 1
670 670
 		    && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
671 671
 		    ) {
672 672
 			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
673 673
 			if (is_array($groupDNs)) {
674 674
 				foreach ($groupDNs as $dn) {
675 675
 					$groupName = $this->access->dn2groupname($dn);
676
-					if(is_string($groupName)) {
676
+					if (is_string($groupName)) {
677 677
 						// be sure to never return false if the dn could not be
678 678
 						// resolved to a name, for whatever reason.
679 679
 						$groups[] = $groupName;
@@ -681,10 +681,10 @@  discard block
 block discarded – undo
681 681
 				}
682 682
 			}
683 683
 
684
-			if($primaryGroup !== false) {
684
+			if ($primaryGroup !== false) {
685 685
 				$groups[] = $primaryGroup;
686 686
 			}
687
-			if($gidGroupName !== false) {
687
+			if ($gidGroupName !== false) {
688 688
 				$groups[] = $gidGroupName;
689 689
 			}
690 690
 			$this->access->connection->writeToCache($cacheKey, $groups);
@@ -692,14 +692,14 @@  discard block
 block discarded – undo
692 692
 		}
693 693
 
694 694
 		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
695
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
695
+		if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
696 696
 			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
697 697
 		) {
698 698
 			$uid = $userDN;
699
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
699
+		} else if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
700 700
 			$result = $this->access->readAttribute($userDN, 'uid');
701 701
 			if ($result === false) {
702
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
702
+				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN '.$userDN.' on '.
703 703
 					$this->access->connection->ldapHost, ILogger::DEBUG);
704 704
 			}
705 705
 			$uid = $result[0];
@@ -708,7 +708,7 @@  discard block
 block discarded – undo
708 708
 			$uid = $userDN;
709 709
 		}
710 710
 
711
-		if(isset($this->cachedGroupsByMember[$uid])) {
711
+		if (isset($this->cachedGroupsByMember[$uid])) {
712 712
 			$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
713 713
 		} else {
714 714
 			$groupsByMember = array_values($this->getGroupsByMember($uid));
@@ -717,10 +717,10 @@  discard block
 block discarded – undo
717 717
 			$groups = array_merge($groups, $groupsByMember);
718 718
 		}
719 719
 
720
-		if($primaryGroup !== false) {
720
+		if ($primaryGroup !== false) {
721 721
 			$groups[] = $primaryGroup;
722 722
 		}
723
-		if($gidGroupName !== false) {
723
+		if ($gidGroupName !== false) {
724 724
 			$groups[] = $gidGroupName;
725 725
 		}
726 726
 
@@ -758,7 +758,7 @@  discard block
 block discarded – undo
758 758
 				$nestedGroups = $this->access->connection->ldapNestedGroups;
759 759
 				if (!empty($nestedGroups)) {
760 760
 					$supergroups = $this->getGroupsByMember($groupDN, $seen);
761
-					if (is_array($supergroups) && (count($supergroups)>0)) {
761
+					if (is_array($supergroups) && (count($supergroups) > 0)) {
762 762
 						$allGroups = array_merge($allGroups, $supergroups);
763 763
 					}
764 764
 				}
@@ -777,33 +777,33 @@  discard block
 block discarded – undo
777 777
 	 * @return array with user ids
778 778
 	 */
779 779
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
780
-		if(!$this->enabled) {
780
+		if (!$this->enabled) {
781 781
 			return array();
782 782
 		}
783
-		if(!$this->groupExists($gid)) {
783
+		if (!$this->groupExists($gid)) {
784 784
 			return array();
785 785
 		}
786 786
 		$search = $this->access->escapeFilterPart($search, true);
787 787
 		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
788 788
 		// check for cache of the exact query
789 789
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
790
-		if(!is_null($groupUsers)) {
790
+		if (!is_null($groupUsers)) {
791 791
 			return $groupUsers;
792 792
 		}
793 793
 
794 794
 		// check for cache of the query without limit and offset
795 795
 		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
796
-		if(!is_null($groupUsers)) {
796
+		if (!is_null($groupUsers)) {
797 797
 			$groupUsers = array_slice($groupUsers, $offset, $limit);
798 798
 			$this->access->connection->writeToCache($cacheKey, $groupUsers);
799 799
 			return $groupUsers;
800 800
 		}
801 801
 
802
-		if($limit === -1) {
802
+		if ($limit === -1) {
803 803
 			$limit = null;
804 804
 		}
805 805
 		$groupDN = $this->access->groupname2dn($gid);
806
-		if(!$groupDN) {
806
+		if (!$groupDN) {
807 807
 			// group couldn't be found, return empty resultset
808 808
 			$this->access->connection->writeToCache($cacheKey, array());
809 809
 			return array();
@@ -812,7 +812,7 @@  discard block
 block discarded – undo
812 812
 		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
813 813
 		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
814 814
 		$members = array_keys($this->_groupMembers($groupDN));
815
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
815
+		if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
816 816
 			//in case users could not be retrieved, return empty result set
817 817
 			$this->access->connection->writeToCache($cacheKey, []);
818 818
 			return [];
@@ -821,29 +821,29 @@  discard block
 block discarded – undo
821 821
 		$groupUsers = array();
822 822
 		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
823 823
 		$attrs = $this->access->userManager->getAttributes(true);
824
-		foreach($members as $member) {
825
-			if($isMemberUid) {
824
+		foreach ($members as $member) {
825
+			if ($isMemberUid) {
826 826
 				//we got uids, need to get their DNs to 'translate' them to user names
827 827
 				$filter = $this->access->combineFilterWithAnd(array(
828 828
 					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
829 829
 					$this->access->getFilterPartForUserSearch($search)
830 830
 				));
831 831
 				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
832
-				if(count($ldap_users) < 1) {
832
+				if (count($ldap_users) < 1) {
833 833
 					continue;
834 834
 				}
835 835
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
836 836
 			} else {
837 837
 				//we got DNs, check if we need to filter by search or we can give back all of them
838 838
 				if ($search !== '') {
839
-					if(!$this->access->readAttribute($member,
839
+					if (!$this->access->readAttribute($member,
840 840
 						$this->access->connection->ldapUserDisplayName,
841 841
 						$this->access->getFilterPartForUserSearch($search))) {
842 842
 						continue;
843 843
 					}
844 844
 				}
845 845
 				// dn2username will also check if the users belong to the allowed base
846
-				if($ocname = $this->access->dn2username($member)) {
846
+				if ($ocname = $this->access->dn2username($member)) {
847 847
 					$groupUsers[] = $ocname;
848 848
 				}
849 849
 			}
@@ -871,16 +871,16 @@  discard block
 block discarded – undo
871 871
 		}
872 872
 
873 873
 		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
874
-		if(!$this->enabled || !$this->groupExists($gid)) {
874
+		if (!$this->enabled || !$this->groupExists($gid)) {
875 875
 			return false;
876 876
 		}
877 877
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
878
-		if(!is_null($groupUsers)) {
878
+		if (!is_null($groupUsers)) {
879 879
 			return $groupUsers;
880 880
 		}
881 881
 
882 882
 		$groupDN = $this->access->groupname2dn($gid);
883
-		if(!$groupDN) {
883
+		if (!$groupDN) {
884 884
 			// group couldn't be found, return empty result set
885 885
 			$this->access->connection->writeToCache($cacheKey, false);
886 886
 			return false;
@@ -888,7 +888,7 @@  discard block
 block discarded – undo
888 888
 
889 889
 		$members = array_keys($this->_groupMembers($groupDN));
890 890
 		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
891
-		if(!$members && $primaryUserCount === 0) {
891
+		if (!$members && $primaryUserCount === 0) {
892 892
 			//in case users could not be retrieved, return empty result set
893 893
 			$this->access->connection->writeToCache($cacheKey, false);
894 894
 			return false;
@@ -913,27 +913,27 @@  discard block
 block discarded – undo
913 913
 		//For now this is not important, because the only use of this method
914 914
 		//does not supply a search string
915 915
 		$groupUsers = array();
916
-		foreach($members as $member) {
917
-			if($isMemberUid) {
916
+		foreach ($members as $member) {
917
+			if ($isMemberUid) {
918 918
 				//we got uids, need to get their DNs to 'translate' them to user names
919 919
 				$filter = $this->access->combineFilterWithAnd(array(
920 920
 					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
921 921
 					$this->access->getFilterPartForUserSearch($search)
922 922
 				));
923 923
 				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
924
-				if(count($ldap_users) < 1) {
924
+				if (count($ldap_users) < 1) {
925 925
 					continue;
926 926
 				}
927 927
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
928 928
 			} else {
929 929
 				//we need to apply the search filter now
930
-				if(!$this->access->readAttribute($member,
930
+				if (!$this->access->readAttribute($member,
931 931
 					$this->access->connection->ldapUserDisplayName,
932 932
 					$this->access->getFilterPartForUserSearch($search))) {
933 933
 					continue;
934 934
 				}
935 935
 				// dn2username will also check if the users belong to the allowed base
936
-				if($ocname = $this->access->dn2username($member)) {
936
+				if ($ocname = $this->access->dn2username($member)) {
937 937
 					$groupUsers[] = $ocname;
938 938
 				}
939 939
 			}
@@ -956,7 +956,7 @@  discard block
 block discarded – undo
956 956
 	 * Returns a list with all groups (used by getGroups)
957 957
 	 */
958 958
 	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
959
-		if(!$this->enabled) {
959
+		if (!$this->enabled) {
960 960
 			return array();
961 961
 		}
962 962
 		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
@@ -964,13 +964,13 @@  discard block
 block discarded – undo
964 964
 		//Check cache before driving unnecessary searches
965 965
 		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
966 966
 		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
967
-		if(!is_null($ldap_groups)) {
967
+		if (!is_null($ldap_groups)) {
968 968
 			return $ldap_groups;
969 969
 		}
970 970
 
971 971
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
972 972
 		// error. With a limit of 0, we get 0 results. So we pass null.
973
-		if($limit <= 0) {
973
+		if ($limit <= 0) {
974 974
 			$limit = null;
975 975
 		}
976 976
 		$filter = $this->access->combineFilterWithAnd(array(
@@ -1002,11 +1002,11 @@  discard block
 block discarded – undo
1002 1002
 	 * (active directory has a limit of 1000 by default)
1003 1003
 	 */
1004 1004
 	public function getGroups($search = '', $limit = -1, $offset = 0) {
1005
-		if(!$this->enabled) {
1005
+		if (!$this->enabled) {
1006 1006
 			return array();
1007 1007
 		}
1008 1008
 		$search = $this->access->escapeFilterPart($search, true);
1009
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1009
+		$pagingSize = (int) $this->access->connection->ldapPagingSize;
1010 1010
 		if ($pagingSize <= 0) {
1011 1011
 			return $this->getGroupsChunk($search, $limit, $offset);
1012 1012
 		}
@@ -1049,20 +1049,20 @@  discard block
 block discarded – undo
1049 1049
 	 */
1050 1050
 	public function groupExists($gid) {
1051 1051
 		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1052
-		if(!is_null($groupExists)) {
1053
-			return (bool)$groupExists;
1052
+		if (!is_null($groupExists)) {
1053
+			return (bool) $groupExists;
1054 1054
 		}
1055 1055
 
1056 1056
 		//getting dn, if false the group does not exist. If dn, it may be mapped
1057 1057
 		//only, requires more checking.
1058 1058
 		$dn = $this->access->groupname2dn($gid);
1059
-		if(!$dn) {
1059
+		if (!$dn) {
1060 1060
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1061 1061
 			return false;
1062 1062
 		}
1063 1063
 
1064 1064
 		//if group really still exists, we will be able to read its objectclass
1065
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1065
+		if (!is_array($this->access->readAttribute($dn, ''))) {
1066 1066
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1067 1067
 			return false;
1068 1068
 		}
@@ -1080,7 +1080,7 @@  discard block
 block discarded – undo
1080 1080
 	* compared with GroupInterface::CREATE_GROUP etc.
1081 1081
 	*/
1082 1082
 	public function implementsActions($actions) {
1083
-		return (bool)((GroupInterface::COUNT_USERS |
1083
+		return (bool) ((GroupInterface::COUNT_USERS |
1084 1084
 				$this->groupPluginManager->getImplementedActions()) & $actions);
1085 1085
 	}
1086 1086
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/LDAP.php 1 patch
Indentation   +330 added lines, -330 removed lines patch added patch discarded remove patch
@@ -33,334 +33,334 @@
 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
-	 */
193
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
194
-		return $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
195
-	}
196
-
197
-	/**
198
-	 * @param LDAP $link
199
-	 * @param string $userDN
200
-	 * @param string $password
201
-	 * @return bool
202
-	 */
203
-	public function modReplace($link, $userDN, $password) {
204
-		return $this->invokeLDAPMethod('mod_replace', $link, $userDN, array('userPassword' => $password));
205
-	}
206
-
207
-	/**
208
-	 * @param LDAP $link
209
-	 * @param string $option
210
-	 * @param int $value
211
-	 * @return bool|mixed
212
-	 */
213
-	public function setOption($link, $option, $value) {
214
-		return $this->invokeLDAPMethod('set_option', $link, $option, $value);
215
-	}
216
-
217
-	/**
218
-	 * @param LDAP $link
219
-	 * @return mixed|true
220
-	 */
221
-	public function startTls($link) {
222
-		return $this->invokeLDAPMethod('start_tls', $link);
223
-	}
224
-
225
-	/**
226
-	 * @param resource $link
227
-	 * @return bool|mixed
228
-	 */
229
-	public function unbind($link) {
230
-		return $this->invokeLDAPMethod('unbind', $link);
231
-	}
232
-
233
-	/**
234
-	 * Checks whether the server supports LDAP
235
-	 * @return boolean if it the case, false otherwise
236
-	 * */
237
-	public function areLDAPFunctionsAvailable() {
238
-		return function_exists('ldap_connect');
239
-	}
240
-
241
-	/**
242
-	 * Checks whether the submitted parameter is a resource
243
-	 * @param Resource $resource the resource variable to check
244
-	 * @return bool true if it is a resource, false otherwise
245
-	 */
246
-	public function isResource($resource) {
247
-		return is_resource($resource);
248
-	}
249
-
250
-	/**
251
-	 * Checks whether the return value from LDAP is wrong or not.
252
-	 *
253
-	 * When using ldap_search we provide an array, in case multiple bases are
254
-	 * configured. Thus, we need to check the array elements.
255
-	 *
256
-	 * @param $result
257
-	 * @return bool
258
-	 */
259
-	protected function isResultFalse($result) {
260
-		if($result === false) {
261
-			return true;
262
-		}
263
-
264
-		if($this->curFunc === 'ldap_search' && is_array($result)) {
265
-			foreach ($result as $singleResult) {
266
-				if($singleResult === false) {
267
-					return true;
268
-				}
269
-			}
270
-		}
271
-
272
-		return false;
273
-	}
274
-
275
-	/**
276
-	 * @return mixed
277
-	 */
278
-	protected function invokeLDAPMethod() {
279
-		$arguments = func_get_args();
280
-		$func = 'ldap_' . array_shift($arguments);
281
-		if(function_exists($func)) {
282
-			$this->preFunctionCall($func, $arguments);
283
-			$result = call_user_func_array($func, $arguments);
284
-			if ($this->isResultFalse($result)) {
285
-				$this->postFunctionCall();
286
-			}
287
-			return $result;
288
-		}
289
-		return null;
290
-	}
291
-
292
-	/**
293
-	 * @param string $functionName
294
-	 * @param array $args
295
-	 */
296
-	private function preFunctionCall($functionName, $args) {
297
-		$this->curFunc = $functionName;
298
-		$this->curArgs = $args;
299
-	}
300
-
301
-	/**
302
-	 * Analyzes the returned LDAP error and acts accordingly if not 0
303
-	 *
304
-	 * @param resource $resource the LDAP Connection resource
305
-	 * @throws ConstraintViolationException
306
-	 * @throws ServerNotAvailableException
307
-	 * @throws \Exception
308
-	 */
309
-	private function processLDAPError($resource) {
310
-		$errorCode = ldap_errno($resource);
311
-		if($errorCode === 0) {
312
-			return;
313
-		}
314
-		$errorMsg  = ldap_error($resource);
315
-
316
-		if($this->curFunc === 'ldap_get_entries'
317
-			&& $errorCode === -4) {
318
-		} else if ($errorCode === 32) {
319
-			//for now
320
-		} else if ($errorCode === 10) {
321
-			//referrals, we switch them off, but then there is AD :)
322
-		} else if ($errorCode === -1) {
323
-			throw new ServerNotAvailableException('Lost connection to LDAP server.');
324
-		} else if ($errorCode === 52) {
325
-			throw new ServerNotAvailableException('LDAP server is shutting down.');
326
-		} else if ($errorCode === 48) {
327
-			throw new \Exception('LDAP authentication method rejected', $errorCode);
328
-		} else if ($errorCode === 1) {
329
-			throw new \Exception('LDAP Operations error', $errorCode);
330
-		} else if ($errorCode === 19) {
331
-			ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
332
-			throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
333
-		} else {
334
-			\OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
335
-				'app' => 'user_ldap',
336
-				'message' => $errorMsg,
337
-				'code' => $errorCode,
338
-				'func' => $this->curFunc,
339
-			]);
340
-		}
341
-	}
342
-
343
-	/**
344
-	 * Called after an ldap method is run to act on LDAP error if necessary
345
-	 */
346
-	private function postFunctionCall() {
347
-		if($this->isResource($this->curArgs[0])) {
348
-			$resource = $this->curArgs[0];
349
-		} else if(
350
-			   $this->curFunc === 'ldap_search'
351
-			&& is_array($this->curArgs[0])
352
-			&& $this->isResource($this->curArgs[0][0])
353
-		) {
354
-			// we use always the same LDAP connection resource, is enough to
355
-			// take the first one.
356
-			$resource = $this->curArgs[0][0];
357
-		} else {
358
-			return;
359
-		}
360
-
361
-		$this->processLDAPError($resource);
362
-
363
-		$this->curFunc = '';
364
-		$this->curArgs = [];
365
-	}
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
+     */
193
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
194
+        return $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
195
+    }
196
+
197
+    /**
198
+     * @param LDAP $link
199
+     * @param string $userDN
200
+     * @param string $password
201
+     * @return bool
202
+     */
203
+    public function modReplace($link, $userDN, $password) {
204
+        return $this->invokeLDAPMethod('mod_replace', $link, $userDN, array('userPassword' => $password));
205
+    }
206
+
207
+    /**
208
+     * @param LDAP $link
209
+     * @param string $option
210
+     * @param int $value
211
+     * @return bool|mixed
212
+     */
213
+    public function setOption($link, $option, $value) {
214
+        return $this->invokeLDAPMethod('set_option', $link, $option, $value);
215
+    }
216
+
217
+    /**
218
+     * @param LDAP $link
219
+     * @return mixed|true
220
+     */
221
+    public function startTls($link) {
222
+        return $this->invokeLDAPMethod('start_tls', $link);
223
+    }
224
+
225
+    /**
226
+     * @param resource $link
227
+     * @return bool|mixed
228
+     */
229
+    public function unbind($link) {
230
+        return $this->invokeLDAPMethod('unbind', $link);
231
+    }
232
+
233
+    /**
234
+     * Checks whether the server supports LDAP
235
+     * @return boolean if it the case, false otherwise
236
+     * */
237
+    public function areLDAPFunctionsAvailable() {
238
+        return function_exists('ldap_connect');
239
+    }
240
+
241
+    /**
242
+     * Checks whether the submitted parameter is a resource
243
+     * @param Resource $resource the resource variable to check
244
+     * @return bool true if it is a resource, false otherwise
245
+     */
246
+    public function isResource($resource) {
247
+        return is_resource($resource);
248
+    }
249
+
250
+    /**
251
+     * Checks whether the return value from LDAP is wrong or not.
252
+     *
253
+     * When using ldap_search we provide an array, in case multiple bases are
254
+     * configured. Thus, we need to check the array elements.
255
+     *
256
+     * @param $result
257
+     * @return bool
258
+     */
259
+    protected function isResultFalse($result) {
260
+        if($result === false) {
261
+            return true;
262
+        }
263
+
264
+        if($this->curFunc === 'ldap_search' && is_array($result)) {
265
+            foreach ($result as $singleResult) {
266
+                if($singleResult === false) {
267
+                    return true;
268
+                }
269
+            }
270
+        }
271
+
272
+        return false;
273
+    }
274
+
275
+    /**
276
+     * @return mixed
277
+     */
278
+    protected function invokeLDAPMethod() {
279
+        $arguments = func_get_args();
280
+        $func = 'ldap_' . array_shift($arguments);
281
+        if(function_exists($func)) {
282
+            $this->preFunctionCall($func, $arguments);
283
+            $result = call_user_func_array($func, $arguments);
284
+            if ($this->isResultFalse($result)) {
285
+                $this->postFunctionCall();
286
+            }
287
+            return $result;
288
+        }
289
+        return null;
290
+    }
291
+
292
+    /**
293
+     * @param string $functionName
294
+     * @param array $args
295
+     */
296
+    private function preFunctionCall($functionName, $args) {
297
+        $this->curFunc = $functionName;
298
+        $this->curArgs = $args;
299
+    }
300
+
301
+    /**
302
+     * Analyzes the returned LDAP error and acts accordingly if not 0
303
+     *
304
+     * @param resource $resource the LDAP Connection resource
305
+     * @throws ConstraintViolationException
306
+     * @throws ServerNotAvailableException
307
+     * @throws \Exception
308
+     */
309
+    private function processLDAPError($resource) {
310
+        $errorCode = ldap_errno($resource);
311
+        if($errorCode === 0) {
312
+            return;
313
+        }
314
+        $errorMsg  = ldap_error($resource);
315
+
316
+        if($this->curFunc === 'ldap_get_entries'
317
+            && $errorCode === -4) {
318
+        } else if ($errorCode === 32) {
319
+            //for now
320
+        } else if ($errorCode === 10) {
321
+            //referrals, we switch them off, but then there is AD :)
322
+        } else if ($errorCode === -1) {
323
+            throw new ServerNotAvailableException('Lost connection to LDAP server.');
324
+        } else if ($errorCode === 52) {
325
+            throw new ServerNotAvailableException('LDAP server is shutting down.');
326
+        } else if ($errorCode === 48) {
327
+            throw new \Exception('LDAP authentication method rejected', $errorCode);
328
+        } else if ($errorCode === 1) {
329
+            throw new \Exception('LDAP Operations error', $errorCode);
330
+        } else if ($errorCode === 19) {
331
+            ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
332
+            throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
333
+        } else {
334
+            \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
335
+                'app' => 'user_ldap',
336
+                'message' => $errorMsg,
337
+                'code' => $errorCode,
338
+                'func' => $this->curFunc,
339
+            ]);
340
+        }
341
+    }
342
+
343
+    /**
344
+     * Called after an ldap method is run to act on LDAP error if necessary
345
+     */
346
+    private function postFunctionCall() {
347
+        if($this->isResource($this->curArgs[0])) {
348
+            $resource = $this->curArgs[0];
349
+        } else if(
350
+                $this->curFunc === 'ldap_search'
351
+            && is_array($this->curArgs[0])
352
+            && $this->isResource($this->curArgs[0][0])
353
+        ) {
354
+            // we use always the same LDAP connection resource, is enough to
355
+            // take the first one.
356
+            $resource = $this->curArgs[0][0];
357
+        } else {
358
+            return;
359
+        }
360
+
361
+        $this->processLDAPError($resource);
362
+
363
+        $this->curFunc = '';
364
+        $this->curArgs = [];
365
+    }
366 366
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Controller/ConfigAPIController.php 1 patch
Indentation   +259 added lines, -259 removed lines patch added patch discarded remove patch
@@ -39,280 +39,280 @@
 block discarded – undo
39 39
 
40 40
 class ConfigAPIController extends OCSController {
41 41
 
42
-	/** @var Helper */
43
-	private $ldapHelper;
42
+    /** @var Helper */
43
+    private $ldapHelper;
44 44
 
45
-	/** @var ILogger */
46
-	private $logger;
45
+    /** @var ILogger */
46
+    private $logger;
47 47
 
48
-	public function __construct(
49
-		$appName,
50
-		IRequest $request,
51
-		CapabilitiesManager $capabilitiesManager,
52
-		IUserSession $userSession,
53
-		IUserManager $userManager,
54
-		Manager $keyManager,
55
-		Helper $ldapHelper,
56
-		ILogger $logger
57
-	) {
58
-		parent::__construct(
59
-			$appName,
60
-			$request,
61
-			$capabilitiesManager,
62
-			$userSession,
63
-			$userManager,
64
-			$keyManager
65
-		);
48
+    public function __construct(
49
+        $appName,
50
+        IRequest $request,
51
+        CapabilitiesManager $capabilitiesManager,
52
+        IUserSession $userSession,
53
+        IUserManager $userManager,
54
+        Manager $keyManager,
55
+        Helper $ldapHelper,
56
+        ILogger $logger
57
+    ) {
58
+        parent::__construct(
59
+            $appName,
60
+            $request,
61
+            $capabilitiesManager,
62
+            $userSession,
63
+            $userManager,
64
+            $keyManager
65
+        );
66 66
 
67 67
 
68
-		$this->ldapHelper = $ldapHelper;
69
-		$this->logger = $logger;
70
-	}
68
+        $this->ldapHelper = $ldapHelper;
69
+        $this->logger = $logger;
70
+    }
71 71
 
72
-	/**
73
-	 * creates a new (empty) configuration and returns the resulting prefix
74
-	 *
75
-	 * Example: curl -X POST -H "OCS-APIREQUEST: true"  -u $admin:$password \
76
-	 *   https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config
77
-	 *
78
-	 * results in:
79
-	 *
80
-	 * <?xml version="1.0"?>
81
-	 * <ocs>
82
-	 *   <meta>
83
-	 *     <status>ok</status>
84
-	 *     <statuscode>200</statuscode>
85
-	 *     <message>OK</message>
86
-	 *   </meta>
87
-	 *   <data>
88
-	 *     <configID>s40</configID>
89
-	 *   </data>
90
-	 * </ocs>
91
-	 *
92
-	 * Failing example: if an exception is thrown (e.g. Database connection lost)
93
-	 * the detailed error will be logged. The output will then look like:
94
-	 *
95
-	 * <?xml version="1.0"?>
96
-	 * <ocs>
97
-	 *   <meta>
98
-	 *     <status>failure</status>
99
-	 *     <statuscode>999</statuscode>
100
-	 *     <message>An issue occurred when creating the new config.</message>
101
-	 *   </meta>
102
-	 *   <data/>
103
-	 * </ocs>
104
-	 *
105
-	 * For JSON output provide the format=json parameter
106
-	 *
107
-	 * @return DataResponse
108
-	 * @throws OCSException
109
-	 */
110
-	public function create() {
111
-		try {
112
-			$configPrefix = $this->ldapHelper->getNextServerConfigurationPrefix();
113
-			$configHolder = new Configuration($configPrefix);
114
-			$configHolder->saveConfiguration();
115
-		} catch (\Exception $e) {
116
-			$this->logger->logException($e);
117
-			throw new OCSException('An issue occurred when creating the new config.');
118
-		}
119
-		return new DataResponse(['configID' => $configPrefix]);
120
-	}
72
+    /**
73
+     * creates a new (empty) configuration and returns the resulting prefix
74
+     *
75
+     * Example: curl -X POST -H "OCS-APIREQUEST: true"  -u $admin:$password \
76
+     *   https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config
77
+     *
78
+     * results in:
79
+     *
80
+     * <?xml version="1.0"?>
81
+     * <ocs>
82
+     *   <meta>
83
+     *     <status>ok</status>
84
+     *     <statuscode>200</statuscode>
85
+     *     <message>OK</message>
86
+     *   </meta>
87
+     *   <data>
88
+     *     <configID>s40</configID>
89
+     *   </data>
90
+     * </ocs>
91
+     *
92
+     * Failing example: if an exception is thrown (e.g. Database connection lost)
93
+     * the detailed error will be logged. The output will then look like:
94
+     *
95
+     * <?xml version="1.0"?>
96
+     * <ocs>
97
+     *   <meta>
98
+     *     <status>failure</status>
99
+     *     <statuscode>999</statuscode>
100
+     *     <message>An issue occurred when creating the new config.</message>
101
+     *   </meta>
102
+     *   <data/>
103
+     * </ocs>
104
+     *
105
+     * For JSON output provide the format=json parameter
106
+     *
107
+     * @return DataResponse
108
+     * @throws OCSException
109
+     */
110
+    public function create() {
111
+        try {
112
+            $configPrefix = $this->ldapHelper->getNextServerConfigurationPrefix();
113
+            $configHolder = new Configuration($configPrefix);
114
+            $configHolder->saveConfiguration();
115
+        } catch (\Exception $e) {
116
+            $this->logger->logException($e);
117
+            throw new OCSException('An issue occurred when creating the new config.');
118
+        }
119
+        return new DataResponse(['configID' => $configPrefix]);
120
+    }
121 121
 
122
-	/**
123
-	 * Deletes a LDAP configuration, if present.
124
-	 *
125
-	 * Example:
126
-	 *   curl -X DELETE -H "OCS-APIREQUEST: true" -u $admin:$password \
127
-	 *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
128
-	 *
129
-	 * <?xml version="1.0"?>
130
-	 * <ocs>
131
-	 *   <meta>
132
-	 *     <status>ok</status>
133
-	 *     <statuscode>200</statuscode>
134
-	 *     <message>OK</message>
135
-	 *   </meta>
136
-	 *   <data/>
137
-	 * </ocs>
138
-	 *
139
-	 * @param string $configID
140
-	 * @return DataResponse
141
-	 * @throws OCSBadRequestException
142
-	 * @throws OCSException
143
-	 */
144
-	public function delete($configID) {
145
-		try {
146
-			$this->ensureConfigIDExists($configID);
147
-			if(!$this->ldapHelper->deleteServerConfiguration($configID)) {
148
-				throw new OCSException('Could not delete configuration');
149
-			}
150
-		} catch(OCSException $e) {
151
-			throw $e;
152
-		} catch(\Exception $e) {
153
-			$this->logger->logException($e);
154
-			throw new OCSException('An issue occurred when deleting the config.');
155
-		}
122
+    /**
123
+     * Deletes a LDAP configuration, if present.
124
+     *
125
+     * Example:
126
+     *   curl -X DELETE -H "OCS-APIREQUEST: true" -u $admin:$password \
127
+     *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
128
+     *
129
+     * <?xml version="1.0"?>
130
+     * <ocs>
131
+     *   <meta>
132
+     *     <status>ok</status>
133
+     *     <statuscode>200</statuscode>
134
+     *     <message>OK</message>
135
+     *   </meta>
136
+     *   <data/>
137
+     * </ocs>
138
+     *
139
+     * @param string $configID
140
+     * @return DataResponse
141
+     * @throws OCSBadRequestException
142
+     * @throws OCSException
143
+     */
144
+    public function delete($configID) {
145
+        try {
146
+            $this->ensureConfigIDExists($configID);
147
+            if(!$this->ldapHelper->deleteServerConfiguration($configID)) {
148
+                throw new OCSException('Could not delete configuration');
149
+            }
150
+        } catch(OCSException $e) {
151
+            throw $e;
152
+        } catch(\Exception $e) {
153
+            $this->logger->logException($e);
154
+            throw new OCSException('An issue occurred when deleting the config.');
155
+        }
156 156
 
157
-		return new DataResponse();
158
-	}
157
+        return new DataResponse();
158
+    }
159 159
 
160
-	/**
161
-	 * modifies a configuration
162
-	 *
163
-	 * Example:
164
-	 *   curl -X PUT -d "configData[ldapHost]=ldaps://my.ldap.server&configData[ldapPort]=636" \
165
-	 *    -H "OCS-APIREQUEST: true" -u $admin:$password \
166
-	 *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
167
-	 *
168
-	 * <?xml version="1.0"?>
169
-	 * <ocs>
170
-	 *   <meta>
171
-	 *     <status>ok</status>
172
-	 *     <statuscode>200</statuscode>
173
-	 *     <message>OK</message>
174
-	 *   </meta>
175
-	 *   <data/>
176
-	 * </ocs>
177
-	 *
178
-	 * @param string $configID
179
-	 * @param array $configData
180
-	 * @return DataResponse
181
-	 * @throws OCSException
182
-	 */
183
-	public function modify($configID, $configData) {
184
-		try {
185
-			$this->ensureConfigIDExists($configID);
160
+    /**
161
+     * modifies a configuration
162
+     *
163
+     * Example:
164
+     *   curl -X PUT -d "configData[ldapHost]=ldaps://my.ldap.server&configData[ldapPort]=636" \
165
+     *    -H "OCS-APIREQUEST: true" -u $admin:$password \
166
+     *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
167
+     *
168
+     * <?xml version="1.0"?>
169
+     * <ocs>
170
+     *   <meta>
171
+     *     <status>ok</status>
172
+     *     <statuscode>200</statuscode>
173
+     *     <message>OK</message>
174
+     *   </meta>
175
+     *   <data/>
176
+     * </ocs>
177
+     *
178
+     * @param string $configID
179
+     * @param array $configData
180
+     * @return DataResponse
181
+     * @throws OCSException
182
+     */
183
+    public function modify($configID, $configData) {
184
+        try {
185
+            $this->ensureConfigIDExists($configID);
186 186
 
187
-			if(!is_array($configData)) {
188
-				throw new OCSBadRequestException('configData is not properly set');
189
-			}
187
+            if(!is_array($configData)) {
188
+                throw new OCSBadRequestException('configData is not properly set');
189
+            }
190 190
 
191
-			$configuration = new Configuration($configID);
192
-			$configKeys = $configuration->getConfigTranslationArray();
191
+            $configuration = new Configuration($configID);
192
+            $configKeys = $configuration->getConfigTranslationArray();
193 193
 
194
-			foreach ($configKeys as $i => $key) {
195
-				if(isset($configData[$key])) {
196
-					$configuration->$key = $configData[$key];
197
-				}
198
-			}
194
+            foreach ($configKeys as $i => $key) {
195
+                if(isset($configData[$key])) {
196
+                    $configuration->$key = $configData[$key];
197
+                }
198
+            }
199 199
 
200
-			$configuration->saveConfiguration();
201
-		} catch(OCSException $e) {
202
-			throw $e;
203
-		} catch (\Exception $e) {
204
-			$this->logger->logException($e);
205
-			throw new OCSException('An issue occurred when modifying the config.');
206
-		}
200
+            $configuration->saveConfiguration();
201
+        } catch(OCSException $e) {
202
+            throw $e;
203
+        } catch (\Exception $e) {
204
+            $this->logger->logException($e);
205
+            throw new OCSException('An issue occurred when modifying the config.');
206
+        }
207 207
 
208
-		return new DataResponse();
209
-	}
208
+        return new DataResponse();
209
+    }
210 210
 
211
-	/**
212
-	 * retrieves a configuration
213
-	 *
214
-	 * <?xml version="1.0"?>
215
-	 * <ocs>
216
-	 *   <meta>
217
-	 *     <status>ok</status>
218
-	 *     <statuscode>200</statuscode>
219
-	 *     <message>OK</message>
220
-	 *   </meta>
221
-	 *   <data>
222
-	 *     <ldapHost>ldaps://my.ldap.server</ldapHost>
223
-	 *     <ldapPort>7770</ldapPort>
224
-	 *     <ldapBackupHost></ldapBackupHost>
225
-	 *     <ldapBackupPort></ldapBackupPort>
226
-	 *     <ldapBase>ou=small,dc=my,dc=ldap,dc=server</ldapBase>
227
-	 *     <ldapBaseUsers>ou=users,ou=small,dc=my,dc=ldap,dc=server</ldapBaseUsers>
228
-	 *     <ldapBaseGroups>ou=small,dc=my,dc=ldap,dc=server</ldapBaseGroups>
229
-	 *     <ldapAgentName>cn=root,dc=my,dc=ldap,dc=server</ldapAgentName>
230
-	 *     <ldapAgentPassword>clearTextWithShowPassword=1</ldapAgentPassword>
231
-	 *     <ldapTLS>1</ldapTLS>
232
-	 *     <turnOffCertCheck>0</turnOffCertCheck>
233
-	 *     <ldapIgnoreNamingRules/>
234
-	 *     <ldapUserDisplayName>displayname</ldapUserDisplayName>
235
-	 *     <ldapUserDisplayName2>uid</ldapUserDisplayName2>
236
-	 *     <ldapUserFilterObjectclass>inetOrgPerson</ldapUserFilterObjectclass>
237
-	 *     <ldapUserFilterGroups></ldapUserFilterGroups>
238
-	 *     <ldapUserFilter>(&amp;(objectclass=nextcloudUser)(nextcloudEnabled=TRUE))</ldapUserFilter>
239
-	 *     <ldapUserFilterMode>1</ldapUserFilterMode>
240
-	 *     <ldapGroupFilter>(&amp;(|(objectclass=nextcloudGroup)))</ldapGroupFilter>
241
-	 *     <ldapGroupFilterMode>0</ldapGroupFilterMode>
242
-	 *     <ldapGroupFilterObjectclass>nextcloudGroup</ldapGroupFilterObjectclass>
243
-	 *     <ldapGroupFilterGroups></ldapGroupFilterGroups>
244
-	 *     <ldapGroupDisplayName>cn</ldapGroupDisplayName>
245
-	 *     <ldapGroupMemberAssocAttr>memberUid</ldapGroupMemberAssocAttr>
246
-	 *     <ldapLoginFilter>(&amp;(|(objectclass=inetOrgPerson))(uid=%uid))</ldapLoginFilter>
247
-	 *     <ldapLoginFilterMode>0</ldapLoginFilterMode>
248
-	 *     <ldapLoginFilterEmail>0</ldapLoginFilterEmail>
249
-	 *     <ldapLoginFilterUsername>1</ldapLoginFilterUsername>
250
-	 *     <ldapLoginFilterAttributes></ldapLoginFilterAttributes>
251
-	 *     <ldapQuotaAttribute></ldapQuotaAttribute>
252
-	 *     <ldapQuotaDefault></ldapQuotaDefault>
253
-	 *     <ldapEmailAttribute>mail</ldapEmailAttribute>
254
-	 *     <ldapCacheTTL>20</ldapCacheTTL>
255
-	 *     <ldapUuidUserAttribute>auto</ldapUuidUserAttribute>
256
-	 *     <ldapUuidGroupAttribute>auto</ldapUuidGroupAttribute>
257
-	 *     <ldapOverrideMainServer></ldapOverrideMainServer>
258
-	 *     <ldapConfigurationActive>1</ldapConfigurationActive>
259
-	 *     <ldapAttributesForUserSearch>uid;sn;givenname</ldapAttributesForUserSearch>
260
-	 *     <ldapAttributesForGroupSearch></ldapAttributesForGroupSearch>
261
-	 *     <ldapExperiencedAdmin>0</ldapExperiencedAdmin>
262
-	 *     <homeFolderNamingRule></homeFolderNamingRule>
263
-	 *     <hasMemberOfFilterSupport></hasMemberOfFilterSupport>
264
-	 *     <useMemberOfToDetectMembership>1</useMemberOfToDetectMembership>
265
-	 *     <ldapExpertUsernameAttr>uid</ldapExpertUsernameAttr>
266
-	 *     <ldapExpertUUIDUserAttr>uid</ldapExpertUUIDUserAttr>
267
-	 *     <ldapExpertUUIDGroupAttr></ldapExpertUUIDGroupAttr>
268
-	 *     <lastJpegPhotoLookup>0</lastJpegPhotoLookup>
269
-	 *     <ldapNestedGroups>0</ldapNestedGroups>
270
-	 *     <ldapPagingSize>500</ldapPagingSize>
271
-	 *     <turnOnPasswordChange>1</turnOnPasswordChange>
272
-	 *     <ldapDynamicGroupMemberURL></ldapDynamicGroupMemberURL>
273
-	 *   </data>
274
-	 * </ocs>
275
-	 *
276
-	 * @param string $configID
277
-	 * @param bool|string $showPassword
278
-	 * @return DataResponse
279
-	 * @throws OCSException
280
-	 */
281
-	public function show($configID, $showPassword = false) {
282
-		try {
283
-			$this->ensureConfigIDExists($configID);
211
+    /**
212
+     * retrieves a configuration
213
+     *
214
+     * <?xml version="1.0"?>
215
+     * <ocs>
216
+     *   <meta>
217
+     *     <status>ok</status>
218
+     *     <statuscode>200</statuscode>
219
+     *     <message>OK</message>
220
+     *   </meta>
221
+     *   <data>
222
+     *     <ldapHost>ldaps://my.ldap.server</ldapHost>
223
+     *     <ldapPort>7770</ldapPort>
224
+     *     <ldapBackupHost></ldapBackupHost>
225
+     *     <ldapBackupPort></ldapBackupPort>
226
+     *     <ldapBase>ou=small,dc=my,dc=ldap,dc=server</ldapBase>
227
+     *     <ldapBaseUsers>ou=users,ou=small,dc=my,dc=ldap,dc=server</ldapBaseUsers>
228
+     *     <ldapBaseGroups>ou=small,dc=my,dc=ldap,dc=server</ldapBaseGroups>
229
+     *     <ldapAgentName>cn=root,dc=my,dc=ldap,dc=server</ldapAgentName>
230
+     *     <ldapAgentPassword>clearTextWithShowPassword=1</ldapAgentPassword>
231
+     *     <ldapTLS>1</ldapTLS>
232
+     *     <turnOffCertCheck>0</turnOffCertCheck>
233
+     *     <ldapIgnoreNamingRules/>
234
+     *     <ldapUserDisplayName>displayname</ldapUserDisplayName>
235
+     *     <ldapUserDisplayName2>uid</ldapUserDisplayName2>
236
+     *     <ldapUserFilterObjectclass>inetOrgPerson</ldapUserFilterObjectclass>
237
+     *     <ldapUserFilterGroups></ldapUserFilterGroups>
238
+     *     <ldapUserFilter>(&amp;(objectclass=nextcloudUser)(nextcloudEnabled=TRUE))</ldapUserFilter>
239
+     *     <ldapUserFilterMode>1</ldapUserFilterMode>
240
+     *     <ldapGroupFilter>(&amp;(|(objectclass=nextcloudGroup)))</ldapGroupFilter>
241
+     *     <ldapGroupFilterMode>0</ldapGroupFilterMode>
242
+     *     <ldapGroupFilterObjectclass>nextcloudGroup</ldapGroupFilterObjectclass>
243
+     *     <ldapGroupFilterGroups></ldapGroupFilterGroups>
244
+     *     <ldapGroupDisplayName>cn</ldapGroupDisplayName>
245
+     *     <ldapGroupMemberAssocAttr>memberUid</ldapGroupMemberAssocAttr>
246
+     *     <ldapLoginFilter>(&amp;(|(objectclass=inetOrgPerson))(uid=%uid))</ldapLoginFilter>
247
+     *     <ldapLoginFilterMode>0</ldapLoginFilterMode>
248
+     *     <ldapLoginFilterEmail>0</ldapLoginFilterEmail>
249
+     *     <ldapLoginFilterUsername>1</ldapLoginFilterUsername>
250
+     *     <ldapLoginFilterAttributes></ldapLoginFilterAttributes>
251
+     *     <ldapQuotaAttribute></ldapQuotaAttribute>
252
+     *     <ldapQuotaDefault></ldapQuotaDefault>
253
+     *     <ldapEmailAttribute>mail</ldapEmailAttribute>
254
+     *     <ldapCacheTTL>20</ldapCacheTTL>
255
+     *     <ldapUuidUserAttribute>auto</ldapUuidUserAttribute>
256
+     *     <ldapUuidGroupAttribute>auto</ldapUuidGroupAttribute>
257
+     *     <ldapOverrideMainServer></ldapOverrideMainServer>
258
+     *     <ldapConfigurationActive>1</ldapConfigurationActive>
259
+     *     <ldapAttributesForUserSearch>uid;sn;givenname</ldapAttributesForUserSearch>
260
+     *     <ldapAttributesForGroupSearch></ldapAttributesForGroupSearch>
261
+     *     <ldapExperiencedAdmin>0</ldapExperiencedAdmin>
262
+     *     <homeFolderNamingRule></homeFolderNamingRule>
263
+     *     <hasMemberOfFilterSupport></hasMemberOfFilterSupport>
264
+     *     <useMemberOfToDetectMembership>1</useMemberOfToDetectMembership>
265
+     *     <ldapExpertUsernameAttr>uid</ldapExpertUsernameAttr>
266
+     *     <ldapExpertUUIDUserAttr>uid</ldapExpertUUIDUserAttr>
267
+     *     <ldapExpertUUIDGroupAttr></ldapExpertUUIDGroupAttr>
268
+     *     <lastJpegPhotoLookup>0</lastJpegPhotoLookup>
269
+     *     <ldapNestedGroups>0</ldapNestedGroups>
270
+     *     <ldapPagingSize>500</ldapPagingSize>
271
+     *     <turnOnPasswordChange>1</turnOnPasswordChange>
272
+     *     <ldapDynamicGroupMemberURL></ldapDynamicGroupMemberURL>
273
+     *   </data>
274
+     * </ocs>
275
+     *
276
+     * @param string $configID
277
+     * @param bool|string $showPassword
278
+     * @return DataResponse
279
+     * @throws OCSException
280
+     */
281
+    public function show($configID, $showPassword = false) {
282
+        try {
283
+            $this->ensureConfigIDExists($configID);
284 284
 
285
-			$config = new Configuration($configID);
286
-			$data = $config->getConfiguration();
287
-			if(!(int)$showPassword) {
288
-				$data['ldapAgentPassword'] = '***';
289
-			}
290
-			foreach ($data as $key => $value) {
291
-				if(is_array($value)) {
292
-					$value = implode(';', $value);
293
-					$data[$key] = $value;
294
-				}
295
-			}
296
-		} catch(OCSException $e) {
297
-			throw $e;
298
-		} catch (\Exception $e) {
299
-			$this->logger->logException($e);
300
-			throw new OCSException('An issue occurred when modifying the config.');
301
-		}
285
+            $config = new Configuration($configID);
286
+            $data = $config->getConfiguration();
287
+            if(!(int)$showPassword) {
288
+                $data['ldapAgentPassword'] = '***';
289
+            }
290
+            foreach ($data as $key => $value) {
291
+                if(is_array($value)) {
292
+                    $value = implode(';', $value);
293
+                    $data[$key] = $value;
294
+                }
295
+            }
296
+        } catch(OCSException $e) {
297
+            throw $e;
298
+        } catch (\Exception $e) {
299
+            $this->logger->logException($e);
300
+            throw new OCSException('An issue occurred when modifying the config.');
301
+        }
302 302
 
303
-		return new DataResponse($data);
304
-	}
303
+        return new DataResponse($data);
304
+    }
305 305
 
306
-	/**
307
-	 * if the given config ID is not available, an exception is thrown
308
-	 *
309
-	 * @param string $configID
310
-	 * @throws OCSNotFoundException
311
-	 */
312
-	private function ensureConfigIDExists($configID) {
313
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes();
314
-		if(!in_array($configID, $prefixes, true)) {
315
-			throw new OCSNotFoundException('Config ID not found');
316
-		}
317
-	}
306
+    /**
307
+     * if the given config ID is not available, an exception is thrown
308
+     *
309
+     * @param string $configID
310
+     * @throws OCSNotFoundException
311
+     */
312
+    private function ensureConfigIDExists($configID) {
313
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes();
314
+        if(!in_array($configID, $prefixes, true)) {
315
+            throw new OCSNotFoundException('Config ID not found');
316
+        }
317
+    }
318 318
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/ILDAPWrapper.php 1 patch
Indentation   +181 added lines, -181 removed lines patch added patch discarded remove patch
@@ -31,186 +31,186 @@
 block discarded – undo
31 31
 
32 32
 interface ILDAPWrapper {
33 33
 
34
-	//LDAP functions in use
35
-
36
-	/**
37
-	 * Bind to LDAP directory
38
-	 * @param resource $link LDAP link resource
39
-	 * @param string $dn an RDN to log in with
40
-	 * @param string $password the password
41
-	 * @return bool true on success, false otherwise
42
-	 *
43
-	 * with $dn and $password as null a anonymous bind is attempted.
44
-	 */
45
-	public function bind($link, $dn, $password);
46
-
47
-	/**
48
-	 * connect to an LDAP server
49
-	 * @param string $host The host to connect to
50
-	 * @param string $port The port to connect to
51
-	 * @return mixed a link resource on success, otherwise false
52
-	 */
53
-	public function connect($host, $port);
54
-
55
-	/**
56
-	 * Send LDAP pagination control
57
-	 * @param resource $link LDAP link resource
58
-	 * @param int $pageSize number of results per page
59
-	 * @param bool $isCritical Indicates whether the pagination is critical of not.
60
-	 * @param string $cookie structure sent by LDAP server
61
-	 * @return bool true on success, false otherwise
62
-	 */
63
-	public function controlPagedResult($link, $pageSize, $isCritical, $cookie);
64
-
65
-	/**
66
-	 * Retrieve the LDAP pagination cookie
67
-	 * @param resource $link LDAP link resource
68
-	 * @param resource $result LDAP result resource
69
-	 * @param string $cookie structure sent by LDAP server
70
-	 * @return bool true on success, false otherwise
71
-	 *
72
-	 * Corresponds to ldap_control_paged_result_response
73
-	 */
74
-	public function controlPagedResultResponse($link, $result, &$cookie);
75
-
76
-	/**
77
-	 * Count the number of entries in a search
78
-	 * @param resource $link LDAP link resource
79
-	 * @param resource $result LDAP result resource
80
-	 * @return int|false number of results on success, false otherwise
81
-	 */
82
-	public function countEntries($link, $result);
83
-
84
-	/**
85
-	 * Return the LDAP error number of the last LDAP command
86
-	 * @param resource $link LDAP link resource
87
-	 * @return int error code
88
-	 */
89
-	public function errno($link);
90
-
91
-	/**
92
-	 * Return the LDAP error message of the last LDAP command
93
-	 * @param resource $link LDAP link resource
94
-	 * @return string error message
95
-	 */
96
-	public function error($link);
97
-
98
-	/**
99
-	 * Splits DN into its component parts
100
-	 * @param string $dn
101
-	 * @param int @withAttrib
102
-	 * @return array|false
103
-	 * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
104
-	 */
105
-	public function explodeDN($dn, $withAttrib);
106
-
107
-	/**
108
-	 * Return first result id
109
-	 * @param resource $link LDAP link resource
110
-	 * @param resource $result LDAP result resource
111
-	 * @return Resource an LDAP search result resource
112
-	 * */
113
-	public function firstEntry($link, $result);
114
-
115
-	/**
116
-	 * Get attributes from a search result entry
117
-	 * @param resource $link LDAP link resource
118
-	 * @param resource $result LDAP result resource
119
-	 * @return array containing the results, false on error
120
-	 * */
121
-	public function getAttributes($link, $result);
122
-
123
-	/**
124
-	 * Get the DN of a result entry
125
-	 * @param resource $link LDAP link resource
126
-	 * @param resource $result LDAP result resource
127
-	 * @return string containing the DN, false on error
128
-	 */
129
-	public function getDN($link, $result);
130
-
131
-	/**
132
-	 * Get all result entries
133
-	 * @param resource $link LDAP link resource
134
-	 * @param resource $result LDAP result resource
135
-	 * @return array containing the results, false on error
136
-	 */
137
-	public function getEntries($link, $result);
138
-
139
-	/**
140
-	 * Return next result id
141
-	 * @param resource $link LDAP link resource
142
-	 * @param resource $result LDAP entry result resource
143
-	 * @return resource an LDAP search result resource
144
-	 * */
145
-	public function nextEntry($link, $result);
146
-
147
-	/**
148
-	 * Read an entry
149
-	 * @param resource $link LDAP link resource
150
-	 * @param array $baseDN The DN of the entry to read from
151
-	 * @param string $filter An LDAP filter
152
-	 * @param array $attr array of the attributes to read
153
-	 * @return resource an LDAP search result resource
154
-	 */
155
-	public function read($link, $baseDN, $filter, $attr);
156
-
157
-	/**
158
-	 * Search LDAP tree
159
-	 * @param resource $link LDAP link resource
160
-	 * @param string $baseDN The DN of the entry to read from
161
-	 * @param string $filter An LDAP filter
162
-	 * @param array $attr array of the attributes to read
163
-	 * @param int $attrsOnly optional, 1 if only attribute types shall be returned
164
-	 * @param int $limit optional, limits the result entries
165
-	 * @return resource|false an LDAP search result resource, false on error
166
-	 */
167
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0);
168
-
169
-	/**
170
-	 * Replace the value of a userPassword by $password
171
-	 * @param resource $link LDAP link resource
172
-	 * @param string $userDN the DN of the user whose password is to be replaced
173
-	 * @param string $password the new value for the userPassword
174
-	 * @return bool true on success, false otherwise
175
-	 */
176
-	public function modReplace($link, $userDN, $password);
177
-
178
-	/**
179
-	 * Sets the value of the specified option to be $value
180
-	 * @param resource $link LDAP link resource
181
-	 * @param string $option a defined LDAP Server option
182
-	 * @param int $value the new value for the option
183
-	 * @return bool true on success, false otherwise
184
-	 */
185
-	public function setOption($link, $option, $value);
186
-
187
-	/**
188
-	 * establish Start TLS
189
-	 * @param resource $link LDAP link resource
190
-	 * @return bool true on success, false otherwise
191
-	 */
192
-	public function startTls($link);
193
-
194
-	/**
195
-	 * Unbind from LDAP directory
196
-	 * @param resource $link LDAP link resource
197
-	 * @return bool true on success, false otherwise
198
-	 */
199
-	public function unbind($link);
200
-
201
-	//additional required methods in Nextcloud
202
-
203
-	/**
204
-	 * Checks whether the server supports LDAP
205
-	 * @return bool true if it the case, false otherwise
206
-	 * */
207
-	public function areLDAPFunctionsAvailable();
208
-
209
-	/**
210
-	 * Checks whether the submitted parameter is a resource
211
-	 * @param resource $resource the resource variable to check
212
-	 * @return bool true if it is a resource, false otherwise
213
-	 */
214
-	public function isResource($resource);
34
+    //LDAP functions in use
35
+
36
+    /**
37
+     * Bind to LDAP directory
38
+     * @param resource $link LDAP link resource
39
+     * @param string $dn an RDN to log in with
40
+     * @param string $password the password
41
+     * @return bool true on success, false otherwise
42
+     *
43
+     * with $dn and $password as null a anonymous bind is attempted.
44
+     */
45
+    public function bind($link, $dn, $password);
46
+
47
+    /**
48
+     * connect to an LDAP server
49
+     * @param string $host The host to connect to
50
+     * @param string $port The port to connect to
51
+     * @return mixed a link resource on success, otherwise false
52
+     */
53
+    public function connect($host, $port);
54
+
55
+    /**
56
+     * Send LDAP pagination control
57
+     * @param resource $link LDAP link resource
58
+     * @param int $pageSize number of results per page
59
+     * @param bool $isCritical Indicates whether the pagination is critical of not.
60
+     * @param string $cookie structure sent by LDAP server
61
+     * @return bool true on success, false otherwise
62
+     */
63
+    public function controlPagedResult($link, $pageSize, $isCritical, $cookie);
64
+
65
+    /**
66
+     * Retrieve the LDAP pagination cookie
67
+     * @param resource $link LDAP link resource
68
+     * @param resource $result LDAP result resource
69
+     * @param string $cookie structure sent by LDAP server
70
+     * @return bool true on success, false otherwise
71
+     *
72
+     * Corresponds to ldap_control_paged_result_response
73
+     */
74
+    public function controlPagedResultResponse($link, $result, &$cookie);
75
+
76
+    /**
77
+     * Count the number of entries in a search
78
+     * @param resource $link LDAP link resource
79
+     * @param resource $result LDAP result resource
80
+     * @return int|false number of results on success, false otherwise
81
+     */
82
+    public function countEntries($link, $result);
83
+
84
+    /**
85
+     * Return the LDAP error number of the last LDAP command
86
+     * @param resource $link LDAP link resource
87
+     * @return int error code
88
+     */
89
+    public function errno($link);
90
+
91
+    /**
92
+     * Return the LDAP error message of the last LDAP command
93
+     * @param resource $link LDAP link resource
94
+     * @return string error message
95
+     */
96
+    public function error($link);
97
+
98
+    /**
99
+     * Splits DN into its component parts
100
+     * @param string $dn
101
+     * @param int @withAttrib
102
+     * @return array|false
103
+     * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
104
+     */
105
+    public function explodeDN($dn, $withAttrib);
106
+
107
+    /**
108
+     * Return first result id
109
+     * @param resource $link LDAP link resource
110
+     * @param resource $result LDAP result resource
111
+     * @return Resource an LDAP search result resource
112
+     * */
113
+    public function firstEntry($link, $result);
114
+
115
+    /**
116
+     * Get attributes from a search result entry
117
+     * @param resource $link LDAP link resource
118
+     * @param resource $result LDAP result resource
119
+     * @return array containing the results, false on error
120
+     * */
121
+    public function getAttributes($link, $result);
122
+
123
+    /**
124
+     * Get the DN of a result entry
125
+     * @param resource $link LDAP link resource
126
+     * @param resource $result LDAP result resource
127
+     * @return string containing the DN, false on error
128
+     */
129
+    public function getDN($link, $result);
130
+
131
+    /**
132
+     * Get all result entries
133
+     * @param resource $link LDAP link resource
134
+     * @param resource $result LDAP result resource
135
+     * @return array containing the results, false on error
136
+     */
137
+    public function getEntries($link, $result);
138
+
139
+    /**
140
+     * Return next result id
141
+     * @param resource $link LDAP link resource
142
+     * @param resource $result LDAP entry result resource
143
+     * @return resource an LDAP search result resource
144
+     * */
145
+    public function nextEntry($link, $result);
146
+
147
+    /**
148
+     * Read an entry
149
+     * @param resource $link LDAP link resource
150
+     * @param array $baseDN The DN of the entry to read from
151
+     * @param string $filter An LDAP filter
152
+     * @param array $attr array of the attributes to read
153
+     * @return resource an LDAP search result resource
154
+     */
155
+    public function read($link, $baseDN, $filter, $attr);
156
+
157
+    /**
158
+     * Search LDAP tree
159
+     * @param resource $link LDAP link resource
160
+     * @param string $baseDN The DN of the entry to read from
161
+     * @param string $filter An LDAP filter
162
+     * @param array $attr array of the attributes to read
163
+     * @param int $attrsOnly optional, 1 if only attribute types shall be returned
164
+     * @param int $limit optional, limits the result entries
165
+     * @return resource|false an LDAP search result resource, false on error
166
+     */
167
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0);
168
+
169
+    /**
170
+     * Replace the value of a userPassword by $password
171
+     * @param resource $link LDAP link resource
172
+     * @param string $userDN the DN of the user whose password is to be replaced
173
+     * @param string $password the new value for the userPassword
174
+     * @return bool true on success, false otherwise
175
+     */
176
+    public function modReplace($link, $userDN, $password);
177
+
178
+    /**
179
+     * Sets the value of the specified option to be $value
180
+     * @param resource $link LDAP link resource
181
+     * @param string $option a defined LDAP Server option
182
+     * @param int $value the new value for the option
183
+     * @return bool true on success, false otherwise
184
+     */
185
+    public function setOption($link, $option, $value);
186
+
187
+    /**
188
+     * establish Start TLS
189
+     * @param resource $link LDAP link resource
190
+     * @return bool true on success, false otherwise
191
+     */
192
+    public function startTls($link);
193
+
194
+    /**
195
+     * Unbind from LDAP directory
196
+     * @param resource $link LDAP link resource
197
+     * @return bool true on success, false otherwise
198
+     */
199
+    public function unbind($link);
200
+
201
+    //additional required methods in Nextcloud
202
+
203
+    /**
204
+     * Checks whether the server supports LDAP
205
+     * @return bool true if it the case, false otherwise
206
+     * */
207
+    public function areLDAPFunctionsAvailable();
208
+
209
+    /**
210
+     * Checks whether the submitted parameter is a resource
211
+     * @param resource $resource the resource variable to check
212
+     * @return bool true if it is a resource, false otherwise
213
+     */
214
+    public function isResource($resource);
215 215
 
216 216
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Configuration.php 1 patch
Indentation   +507 added lines, -507 removed lines patch added patch discarded remove patch
@@ -38,540 +38,540 @@
 block discarded – undo
38 38
  * @property string ldapUserAvatarRule
39 39
  */
40 40
 class Configuration {
41
-	const AVATAR_PREFIX_DEFAULT = 'default';
42
-	const AVATAR_PREFIX_NONE = 'none';
43
-	const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
41
+    const AVATAR_PREFIX_DEFAULT = 'default';
42
+    const AVATAR_PREFIX_NONE = 'none';
43
+    const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
44 44
 
45
-	protected $configPrefix = null;
46
-	protected $configRead = false;
47
-	/**
48
-	 * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
49
-	 *               the config ID is registered
50
-	 */
51
-	protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
45
+    protected $configPrefix = null;
46
+    protected $configRead = false;
47
+    /**
48
+     * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
49
+     *               the config ID is registered
50
+     */
51
+    protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
52 52
 
53
-	//settings
54
-	protected $config = array(
55
-		'ldapHost' => null,
56
-		'ldapPort' => null,
57
-		'ldapBackupHost' => null,
58
-		'ldapBackupPort' => null,
59
-		'ldapBase' => null,
60
-		'ldapBaseUsers' => null,
61
-		'ldapBaseGroups' => null,
62
-		'ldapAgentName' => null,
63
-		'ldapAgentPassword' => null,
64
-		'ldapTLS' => null,
65
-		'turnOffCertCheck' => null,
66
-		'ldapIgnoreNamingRules' => null,
67
-		'ldapUserDisplayName' => null,
68
-		'ldapUserDisplayName2' => null,
69
-		'ldapUserAvatarRule' => null,
70
-		'ldapGidNumber' => null,
71
-		'ldapUserFilterObjectclass' => null,
72
-		'ldapUserFilterGroups' => null,
73
-		'ldapUserFilter' => null,
74
-		'ldapUserFilterMode' => null,
75
-		'ldapGroupFilter' => null,
76
-		'ldapGroupFilterMode' => null,
77
-		'ldapGroupFilterObjectclass' => null,
78
-		'ldapGroupFilterGroups' => null,
79
-		'ldapGroupDisplayName' => null,
80
-		'ldapGroupMemberAssocAttr' => null,
81
-		'ldapLoginFilter' => null,
82
-		'ldapLoginFilterMode' => null,
83
-		'ldapLoginFilterEmail' => null,
84
-		'ldapLoginFilterUsername' => null,
85
-		'ldapLoginFilterAttributes' => null,
86
-		'ldapQuotaAttribute' => null,
87
-		'ldapQuotaDefault' => null,
88
-		'ldapEmailAttribute' => null,
89
-		'ldapCacheTTL' => null,
90
-		'ldapUuidUserAttribute' => 'auto',
91
-		'ldapUuidGroupAttribute' => 'auto',
92
-		'ldapOverrideMainServer' => false,
93
-		'ldapConfigurationActive' => false,
94
-		'ldapAttributesForUserSearch' => null,
95
-		'ldapAttributesForGroupSearch' => null,
96
-		'ldapExperiencedAdmin' => false,
97
-		'homeFolderNamingRule' => null,
98
-		'hasMemberOfFilterSupport' => false,
99
-		'useMemberOfToDetectMembership' => true,
100
-		'ldapExpertUsernameAttr' => null,
101
-		'ldapExpertUUIDUserAttr' => null,
102
-		'ldapExpertUUIDGroupAttr' => null,
103
-		'lastJpegPhotoLookup' => null,
104
-		'ldapNestedGroups' => false,
105
-		'ldapPagingSize' => null,
106
-		'turnOnPasswordChange' => false,
107
-		'ldapDynamicGroupMemberURL' => null,
108
-		'ldapDefaultPPolicyDN' => null,
109
-	);
53
+    //settings
54
+    protected $config = array(
55
+        'ldapHost' => null,
56
+        'ldapPort' => null,
57
+        'ldapBackupHost' => null,
58
+        'ldapBackupPort' => null,
59
+        'ldapBase' => null,
60
+        'ldapBaseUsers' => null,
61
+        'ldapBaseGroups' => null,
62
+        'ldapAgentName' => null,
63
+        'ldapAgentPassword' => null,
64
+        'ldapTLS' => null,
65
+        'turnOffCertCheck' => null,
66
+        'ldapIgnoreNamingRules' => null,
67
+        'ldapUserDisplayName' => null,
68
+        'ldapUserDisplayName2' => null,
69
+        'ldapUserAvatarRule' => null,
70
+        'ldapGidNumber' => null,
71
+        'ldapUserFilterObjectclass' => null,
72
+        'ldapUserFilterGroups' => null,
73
+        'ldapUserFilter' => null,
74
+        'ldapUserFilterMode' => null,
75
+        'ldapGroupFilter' => null,
76
+        'ldapGroupFilterMode' => null,
77
+        'ldapGroupFilterObjectclass' => null,
78
+        'ldapGroupFilterGroups' => null,
79
+        'ldapGroupDisplayName' => null,
80
+        'ldapGroupMemberAssocAttr' => null,
81
+        'ldapLoginFilter' => null,
82
+        'ldapLoginFilterMode' => null,
83
+        'ldapLoginFilterEmail' => null,
84
+        'ldapLoginFilterUsername' => null,
85
+        'ldapLoginFilterAttributes' => null,
86
+        'ldapQuotaAttribute' => null,
87
+        'ldapQuotaDefault' => null,
88
+        'ldapEmailAttribute' => null,
89
+        'ldapCacheTTL' => null,
90
+        'ldapUuidUserAttribute' => 'auto',
91
+        'ldapUuidGroupAttribute' => 'auto',
92
+        'ldapOverrideMainServer' => false,
93
+        'ldapConfigurationActive' => false,
94
+        'ldapAttributesForUserSearch' => null,
95
+        'ldapAttributesForGroupSearch' => null,
96
+        'ldapExperiencedAdmin' => false,
97
+        'homeFolderNamingRule' => null,
98
+        'hasMemberOfFilterSupport' => false,
99
+        'useMemberOfToDetectMembership' => true,
100
+        'ldapExpertUsernameAttr' => null,
101
+        'ldapExpertUUIDUserAttr' => null,
102
+        'ldapExpertUUIDGroupAttr' => null,
103
+        'lastJpegPhotoLookup' => null,
104
+        'ldapNestedGroups' => false,
105
+        'ldapPagingSize' => null,
106
+        'turnOnPasswordChange' => false,
107
+        'ldapDynamicGroupMemberURL' => null,
108
+        'ldapDefaultPPolicyDN' => null,
109
+    );
110 110
 
111
-	/**
112
-	 * @param string $configPrefix
113
-	 * @param bool $autoRead
114
-	 */
115
-	public function __construct($configPrefix, $autoRead = true) {
116
-		$this->configPrefix = $configPrefix;
117
-		if($autoRead) {
118
-			$this->readConfiguration();
119
-		}
120
-	}
111
+    /**
112
+     * @param string $configPrefix
113
+     * @param bool $autoRead
114
+     */
115
+    public function __construct($configPrefix, $autoRead = true) {
116
+        $this->configPrefix = $configPrefix;
117
+        if($autoRead) {
118
+            $this->readConfiguration();
119
+        }
120
+    }
121 121
 
122
-	/**
123
-	 * @param string $name
124
-	 * @return mixed|null
125
-	 */
126
-	public function __get($name) {
127
-		if(isset($this->config[$name])) {
128
-			return $this->config[$name];
129
-		}
130
-		return null;
131
-	}
122
+    /**
123
+     * @param string $name
124
+     * @return mixed|null
125
+     */
126
+    public function __get($name) {
127
+        if(isset($this->config[$name])) {
128
+            return $this->config[$name];
129
+        }
130
+        return null;
131
+    }
132 132
 
133
-	/**
134
-	 * @param string $name
135
-	 * @param mixed $value
136
-	 */
137
-	public function __set($name, $value) {
138
-		$this->setConfiguration(array($name => $value));
139
-	}
133
+    /**
134
+     * @param string $name
135
+     * @param mixed $value
136
+     */
137
+    public function __set($name, $value) {
138
+        $this->setConfiguration(array($name => $value));
139
+    }
140 140
 
141
-	/**
142
-	 * @return array
143
-	 */
144
-	public function getConfiguration() {
145
-		return $this->config;
146
-	}
141
+    /**
142
+     * @return array
143
+     */
144
+    public function getConfiguration() {
145
+        return $this->config;
146
+    }
147 147
 
148
-	/**
149
-	 * set LDAP configuration with values delivered by an array, not read
150
-	 * from configuration. It does not save the configuration! To do so, you
151
-	 * must call saveConfiguration afterwards.
152
-	 * @param array $config array that holds the config parameters in an associated
153
-	 * array
154
-	 * @param array &$applied optional; array where the set fields will be given to
155
-	 * @return false|null
156
-	 */
157
-	public function setConfiguration($config, &$applied = null) {
158
-		if(!is_array($config)) {
159
-			return false;
160
-		}
148
+    /**
149
+     * set LDAP configuration with values delivered by an array, not read
150
+     * from configuration. It does not save the configuration! To do so, you
151
+     * must call saveConfiguration afterwards.
152
+     * @param array $config array that holds the config parameters in an associated
153
+     * array
154
+     * @param array &$applied optional; array where the set fields will be given to
155
+     * @return false|null
156
+     */
157
+    public function setConfiguration($config, &$applied = null) {
158
+        if(!is_array($config)) {
159
+            return false;
160
+        }
161 161
 
162
-		$cta = $this->getConfigTranslationArray();
163
-		foreach($config as $inputKey => $val) {
164
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
165
-				$key = $cta[$inputKey];
166
-			} elseif(array_key_exists($inputKey, $this->config)) {
167
-				$key = $inputKey;
168
-			} else {
169
-				continue;
170
-			}
162
+        $cta = $this->getConfigTranslationArray();
163
+        foreach($config as $inputKey => $val) {
164
+            if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
165
+                $key = $cta[$inputKey];
166
+            } elseif(array_key_exists($inputKey, $this->config)) {
167
+                $key = $inputKey;
168
+            } else {
169
+                continue;
170
+            }
171 171
 
172
-			$setMethod = 'setValue';
173
-			switch($key) {
174
-				case 'ldapAgentPassword':
175
-					$setMethod = 'setRawValue';
176
-					break;
177
-				case 'homeFolderNamingRule':
178
-					$trimmedVal = trim($val);
179
-					if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
180
-						$val = 'attr:'.$trimmedVal;
181
-					}
182
-					break;
183
-				case 'ldapBase':
184
-				case 'ldapBaseUsers':
185
-				case 'ldapBaseGroups':
186
-				case 'ldapAttributesForUserSearch':
187
-				case 'ldapAttributesForGroupSearch':
188
-				case 'ldapUserFilterObjectclass':
189
-				case 'ldapUserFilterGroups':
190
-				case 'ldapGroupFilterObjectclass':
191
-				case 'ldapGroupFilterGroups':
192
-				case 'ldapLoginFilterAttributes':
193
-					$setMethod = 'setMultiLine';
194
-					break;
195
-			}
196
-			$this->$setMethod($key, $val);
197
-			if(is_array($applied)) {
198
-				$applied[] = $inputKey;
199
-				// storing key as index avoids duplication, and as value for simplicity
200
-			}
201
-			$this->unsavedChanges[$key] = $key;
202
-		}
203
-		return null;
204
-	}
172
+            $setMethod = 'setValue';
173
+            switch($key) {
174
+                case 'ldapAgentPassword':
175
+                    $setMethod = 'setRawValue';
176
+                    break;
177
+                case 'homeFolderNamingRule':
178
+                    $trimmedVal = trim($val);
179
+                    if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
180
+                        $val = 'attr:'.$trimmedVal;
181
+                    }
182
+                    break;
183
+                case 'ldapBase':
184
+                case 'ldapBaseUsers':
185
+                case 'ldapBaseGroups':
186
+                case 'ldapAttributesForUserSearch':
187
+                case 'ldapAttributesForGroupSearch':
188
+                case 'ldapUserFilterObjectclass':
189
+                case 'ldapUserFilterGroups':
190
+                case 'ldapGroupFilterObjectclass':
191
+                case 'ldapGroupFilterGroups':
192
+                case 'ldapLoginFilterAttributes':
193
+                    $setMethod = 'setMultiLine';
194
+                    break;
195
+            }
196
+            $this->$setMethod($key, $val);
197
+            if(is_array($applied)) {
198
+                $applied[] = $inputKey;
199
+                // storing key as index avoids duplication, and as value for simplicity
200
+            }
201
+            $this->unsavedChanges[$key] = $key;
202
+        }
203
+        return null;
204
+    }
205 205
 
206
-	public function readConfiguration() {
207
-		if(!$this->configRead && !is_null($this->configPrefix)) {
208
-			$cta = array_flip($this->getConfigTranslationArray());
209
-			foreach($this->config as $key => $val) {
210
-				if(!isset($cta[$key])) {
211
-					//some are determined
212
-					continue;
213
-				}
214
-				$dbKey = $cta[$key];
215
-				switch($key) {
216
-					case 'ldapBase':
217
-					case 'ldapBaseUsers':
218
-					case 'ldapBaseGroups':
219
-					case 'ldapAttributesForUserSearch':
220
-					case 'ldapAttributesForGroupSearch':
221
-					case 'ldapUserFilterObjectclass':
222
-					case 'ldapUserFilterGroups':
223
-					case 'ldapGroupFilterObjectclass':
224
-					case 'ldapGroupFilterGroups':
225
-					case 'ldapLoginFilterAttributes':
226
-						$readMethod = 'getMultiLine';
227
-						break;
228
-					case 'ldapIgnoreNamingRules':
229
-						$readMethod = 'getSystemValue';
230
-						$dbKey = $key;
231
-						break;
232
-					case 'ldapAgentPassword':
233
-						$readMethod = 'getPwd';
234
-						break;
235
-					case 'ldapUserDisplayName2':
236
-					case 'ldapGroupDisplayName':
237
-						$readMethod = 'getLcValue';
238
-						break;
239
-					case 'ldapUserDisplayName':
240
-					default:
241
-						// user display name does not lower case because
242
-						// we rely on an upper case N as indicator whether to
243
-						// auto-detect it or not. FIXME
244
-						$readMethod = 'getValue';
245
-						break;
246
-				}
247
-				$this->config[$key] = $this->$readMethod($dbKey);
248
-			}
249
-			$this->configRead = true;
250
-		}
251
-	}
206
+    public function readConfiguration() {
207
+        if(!$this->configRead && !is_null($this->configPrefix)) {
208
+            $cta = array_flip($this->getConfigTranslationArray());
209
+            foreach($this->config as $key => $val) {
210
+                if(!isset($cta[$key])) {
211
+                    //some are determined
212
+                    continue;
213
+                }
214
+                $dbKey = $cta[$key];
215
+                switch($key) {
216
+                    case 'ldapBase':
217
+                    case 'ldapBaseUsers':
218
+                    case 'ldapBaseGroups':
219
+                    case 'ldapAttributesForUserSearch':
220
+                    case 'ldapAttributesForGroupSearch':
221
+                    case 'ldapUserFilterObjectclass':
222
+                    case 'ldapUserFilterGroups':
223
+                    case 'ldapGroupFilterObjectclass':
224
+                    case 'ldapGroupFilterGroups':
225
+                    case 'ldapLoginFilterAttributes':
226
+                        $readMethod = 'getMultiLine';
227
+                        break;
228
+                    case 'ldapIgnoreNamingRules':
229
+                        $readMethod = 'getSystemValue';
230
+                        $dbKey = $key;
231
+                        break;
232
+                    case 'ldapAgentPassword':
233
+                        $readMethod = 'getPwd';
234
+                        break;
235
+                    case 'ldapUserDisplayName2':
236
+                    case 'ldapGroupDisplayName':
237
+                        $readMethod = 'getLcValue';
238
+                        break;
239
+                    case 'ldapUserDisplayName':
240
+                    default:
241
+                        // user display name does not lower case because
242
+                        // we rely on an upper case N as indicator whether to
243
+                        // auto-detect it or not. FIXME
244
+                        $readMethod = 'getValue';
245
+                        break;
246
+                }
247
+                $this->config[$key] = $this->$readMethod($dbKey);
248
+            }
249
+            $this->configRead = true;
250
+        }
251
+    }
252 252
 
253
-	/**
254
-	 * saves the current config changes in the database
255
-	 */
256
-	public function saveConfiguration() {
257
-		$cta = array_flip($this->getConfigTranslationArray());
258
-		foreach($this->unsavedChanges as $key) {
259
-			$value = $this->config[$key];
260
-			switch ($key) {
261
-				case 'ldapAgentPassword':
262
-					$value = base64_encode($value);
263
-					break;
264
-				case 'ldapBase':
265
-				case 'ldapBaseUsers':
266
-				case 'ldapBaseGroups':
267
-				case 'ldapAttributesForUserSearch':
268
-				case 'ldapAttributesForGroupSearch':
269
-				case 'ldapUserFilterObjectclass':
270
-				case 'ldapUserFilterGroups':
271
-				case 'ldapGroupFilterObjectclass':
272
-				case 'ldapGroupFilterGroups':
273
-				case 'ldapLoginFilterAttributes':
274
-					if(is_array($value)) {
275
-						$value = implode("\n", $value);
276
-					}
277
-					break;
278
-				//following options are not stored but detected, skip them
279
-				case 'ldapIgnoreNamingRules':
280
-				case 'ldapUuidUserAttribute':
281
-				case 'ldapUuidGroupAttribute':
282
-					continue 2;
283
-			}
284
-			if(is_null($value)) {
285
-				$value = '';
286
-			}
287
-			$this->saveValue($cta[$key], $value);
288
-		}
289
-		$this->saveValue('_lastChange', time());
290
-		$this->unsavedChanges = [];
291
-	}
253
+    /**
254
+     * saves the current config changes in the database
255
+     */
256
+    public function saveConfiguration() {
257
+        $cta = array_flip($this->getConfigTranslationArray());
258
+        foreach($this->unsavedChanges as $key) {
259
+            $value = $this->config[$key];
260
+            switch ($key) {
261
+                case 'ldapAgentPassword':
262
+                    $value = base64_encode($value);
263
+                    break;
264
+                case 'ldapBase':
265
+                case 'ldapBaseUsers':
266
+                case 'ldapBaseGroups':
267
+                case 'ldapAttributesForUserSearch':
268
+                case 'ldapAttributesForGroupSearch':
269
+                case 'ldapUserFilterObjectclass':
270
+                case 'ldapUserFilterGroups':
271
+                case 'ldapGroupFilterObjectclass':
272
+                case 'ldapGroupFilterGroups':
273
+                case 'ldapLoginFilterAttributes':
274
+                    if(is_array($value)) {
275
+                        $value = implode("\n", $value);
276
+                    }
277
+                    break;
278
+                //following options are not stored but detected, skip them
279
+                case 'ldapIgnoreNamingRules':
280
+                case 'ldapUuidUserAttribute':
281
+                case 'ldapUuidGroupAttribute':
282
+                    continue 2;
283
+            }
284
+            if(is_null($value)) {
285
+                $value = '';
286
+            }
287
+            $this->saveValue($cta[$key], $value);
288
+        }
289
+        $this->saveValue('_lastChange', time());
290
+        $this->unsavedChanges = [];
291
+    }
292 292
 
293
-	/**
294
-	 * @param string $varName
295
-	 * @return array|string
296
-	 */
297
-	protected function getMultiLine($varName) {
298
-		$value = $this->getValue($varName);
299
-		if(empty($value)) {
300
-			$value = '';
301
-		} else {
302
-			$value = preg_split('/\r\n|\r|\n/', $value);
303
-		}
293
+    /**
294
+     * @param string $varName
295
+     * @return array|string
296
+     */
297
+    protected function getMultiLine($varName) {
298
+        $value = $this->getValue($varName);
299
+        if(empty($value)) {
300
+            $value = '';
301
+        } else {
302
+            $value = preg_split('/\r\n|\r|\n/', $value);
303
+        }
304 304
 
305
-		return $value;
306
-	}
305
+        return $value;
306
+    }
307 307
 
308
-	/**
309
-	 * Sets multi-line values as arrays
310
-	 * 
311
-	 * @param string $varName name of config-key
312
-	 * @param array|string $value to set
313
-	 */
314
-	protected function setMultiLine($varName, $value) {
315
-		if(empty($value)) {
316
-			$value = '';
317
-		} else if (!is_array($value)) {
318
-			$value = preg_split('/\r\n|\r|\n|;/', $value);
319
-			if($value === false) {
320
-				$value = '';
321
-			}
322
-		}
308
+    /**
309
+     * Sets multi-line values as arrays
310
+     * 
311
+     * @param string $varName name of config-key
312
+     * @param array|string $value to set
313
+     */
314
+    protected function setMultiLine($varName, $value) {
315
+        if(empty($value)) {
316
+            $value = '';
317
+        } else if (!is_array($value)) {
318
+            $value = preg_split('/\r\n|\r|\n|;/', $value);
319
+            if($value === false) {
320
+                $value = '';
321
+            }
322
+        }
323 323
 
324
-		if(!is_array($value)) {
325
-			$finalValue = trim($value);
326
-		} else {
327
-			$finalValue = [];
328
-			foreach($value as $key => $val) {
329
-				if(is_string($val)) {
330
-					$val = trim($val);
331
-					if ($val !== '') {
332
-						//accidental line breaks are not wanted and can cause
333
-						// odd behaviour. Thus, away with them.
334
-						$finalValue[] = $val;
335
-					}
336
-				} else {
337
-					$finalValue[] = $val;
338
-				}
339
-			}
340
-		}
324
+        if(!is_array($value)) {
325
+            $finalValue = trim($value);
326
+        } else {
327
+            $finalValue = [];
328
+            foreach($value as $key => $val) {
329
+                if(is_string($val)) {
330
+                    $val = trim($val);
331
+                    if ($val !== '') {
332
+                        //accidental line breaks are not wanted and can cause
333
+                        // odd behaviour. Thus, away with them.
334
+                        $finalValue[] = $val;
335
+                    }
336
+                } else {
337
+                    $finalValue[] = $val;
338
+                }
339
+            }
340
+        }
341 341
 
342
-		$this->setRawValue($varName, $finalValue);
343
-	}
342
+        $this->setRawValue($varName, $finalValue);
343
+    }
344 344
 
345
-	/**
346
-	 * @param string $varName
347
-	 * @return string
348
-	 */
349
-	protected function getPwd($varName) {
350
-		return base64_decode($this->getValue($varName));
351
-	}
345
+    /**
346
+     * @param string $varName
347
+     * @return string
348
+     */
349
+    protected function getPwd($varName) {
350
+        return base64_decode($this->getValue($varName));
351
+    }
352 352
 
353
-	/**
354
-	 * @param string $varName
355
-	 * @return string
356
-	 */
357
-	protected function getLcValue($varName) {
358
-		return mb_strtolower($this->getValue($varName), 'UTF-8');
359
-	}
353
+    /**
354
+     * @param string $varName
355
+     * @return string
356
+     */
357
+    protected function getLcValue($varName) {
358
+        return mb_strtolower($this->getValue($varName), 'UTF-8');
359
+    }
360 360
 
361
-	/**
362
-	 * @param string $varName
363
-	 * @return string
364
-	 */
365
-	protected function getSystemValue($varName) {
366
-		//FIXME: if another system value is added, softcode the default value
367
-		return \OC::$server->getConfig()->getSystemValue($varName, false);
368
-	}
361
+    /**
362
+     * @param string $varName
363
+     * @return string
364
+     */
365
+    protected function getSystemValue($varName) {
366
+        //FIXME: if another system value is added, softcode the default value
367
+        return \OC::$server->getConfig()->getSystemValue($varName, false);
368
+    }
369 369
 
370
-	/**
371
-	 * @param string $varName
372
-	 * @return string
373
-	 */
374
-	protected function getValue($varName) {
375
-		static $defaults;
376
-		if(is_null($defaults)) {
377
-			$defaults = $this->getDefaults();
378
-		}
379
-		return \OC::$server->getConfig()->getAppValue('user_ldap',
380
-										$this->configPrefix.$varName,
381
-										$defaults[$varName]);
382
-	}
370
+    /**
371
+     * @param string $varName
372
+     * @return string
373
+     */
374
+    protected function getValue($varName) {
375
+        static $defaults;
376
+        if(is_null($defaults)) {
377
+            $defaults = $this->getDefaults();
378
+        }
379
+        return \OC::$server->getConfig()->getAppValue('user_ldap',
380
+                                        $this->configPrefix.$varName,
381
+                                        $defaults[$varName]);
382
+    }
383 383
 
384
-	/**
385
-	 * Sets a scalar value.
386
-	 * 
387
-	 * @param string $varName name of config key
388
-	 * @param mixed $value to set
389
-	 */
390
-	protected function setValue($varName, $value) {
391
-		if(is_string($value)) {
392
-			$value = trim($value);
393
-		}
394
-		$this->config[$varName] = $value;
395
-	}
384
+    /**
385
+     * Sets a scalar value.
386
+     * 
387
+     * @param string $varName name of config key
388
+     * @param mixed $value to set
389
+     */
390
+    protected function setValue($varName, $value) {
391
+        if(is_string($value)) {
392
+            $value = trim($value);
393
+        }
394
+        $this->config[$varName] = $value;
395
+    }
396 396
 
397
-	/**
398
-	 * Sets a scalar value without trimming.
399
-	 *
400
-	 * @param string $varName name of config key
401
-	 * @param mixed $value to set
402
-	 */
403
-	protected function setRawValue($varName, $value) {
404
-		$this->config[$varName] = $value;
405
-	}
397
+    /**
398
+     * Sets a scalar value without trimming.
399
+     *
400
+     * @param string $varName name of config key
401
+     * @param mixed $value to set
402
+     */
403
+    protected function setRawValue($varName, $value) {
404
+        $this->config[$varName] = $value;
405
+    }
406 406
 
407
-	/**
408
-	 * @param string $varName
409
-	 * @param string $value
410
-	 * @return bool
411
-	 */
412
-	protected function saveValue($varName, $value) {
413
-		\OC::$server->getConfig()->setAppValue(
414
-			'user_ldap',
415
-			$this->configPrefix.$varName,
416
-			$value
417
-		);
418
-		return true;
419
-	}
407
+    /**
408
+     * @param string $varName
409
+     * @param string $value
410
+     * @return bool
411
+     */
412
+    protected function saveValue($varName, $value) {
413
+        \OC::$server->getConfig()->setAppValue(
414
+            'user_ldap',
415
+            $this->configPrefix.$varName,
416
+            $value
417
+        );
418
+        return true;
419
+    }
420 420
 
421
-	/**
422
-	 * @return array an associative array with the default values. Keys are correspond
423
-	 * to config-value entries in the database table
424
-	 */
425
-	public function getDefaults() {
426
-		return array(
427
-			'ldap_host'                         => '',
428
-			'ldap_port'                         => '',
429
-			'ldap_backup_host'                  => '',
430
-			'ldap_backup_port'                  => '',
431
-			'ldap_override_main_server'         => '',
432
-			'ldap_dn'                           => '',
433
-			'ldap_agent_password'               => '',
434
-			'ldap_base'                         => '',
435
-			'ldap_base_users'                   => '',
436
-			'ldap_base_groups'                  => '',
437
-			'ldap_userlist_filter'              => '',
438
-			'ldap_user_filter_mode'             => 0,
439
-			'ldap_userfilter_objectclass'       => '',
440
-			'ldap_userfilter_groups'            => '',
441
-			'ldap_login_filter'                 => '',
442
-			'ldap_login_filter_mode'            => 0,
443
-			'ldap_loginfilter_email'            => 0,
444
-			'ldap_loginfilter_username'         => 1,
445
-			'ldap_loginfilter_attributes'       => '',
446
-			'ldap_group_filter'                 => '',
447
-			'ldap_group_filter_mode'            => 0,
448
-			'ldap_groupfilter_objectclass'      => '',
449
-			'ldap_groupfilter_groups'           => '',
450
-			'ldap_gid_number'                   => 'gidNumber',
451
-			'ldap_display_name'                 => 'displayName',
452
-			'ldap_user_display_name_2'			=> '',
453
-			'ldap_group_display_name'           => 'cn',
454
-			'ldap_tls'                          => 0,
455
-			'ldap_quota_def'                    => '',
456
-			'ldap_quota_attr'                   => '',
457
-			'ldap_email_attr'                   => '',
458
-			'ldap_group_member_assoc_attribute' => 'uniqueMember',
459
-			'ldap_cache_ttl'                    => 600,
460
-			'ldap_uuid_user_attribute'          => 'auto',
461
-			'ldap_uuid_group_attribute'         => 'auto',
462
-			'home_folder_naming_rule'           => '',
463
-			'ldap_turn_off_cert_check'          => 0,
464
-			'ldap_configuration_active'         => 0,
465
-			'ldap_attributes_for_user_search'   => '',
466
-			'ldap_attributes_for_group_search'  => '',
467
-			'ldap_expert_username_attr'         => '',
468
-			'ldap_expert_uuid_user_attr'        => '',
469
-			'ldap_expert_uuid_group_attr'       => '',
470
-			'has_memberof_filter_support'       => 0,
471
-			'use_memberof_to_detect_membership' => 1,
472
-			'last_jpegPhoto_lookup'             => 0,
473
-			'ldap_nested_groups'                => 0,
474
-			'ldap_paging_size'                  => 500,
475
-			'ldap_turn_on_pwd_change'           => 0,
476
-			'ldap_experienced_admin'            => 0,
477
-			'ldap_dynamic_group_member_url'     => '',
478
-			'ldap_default_ppolicy_dn'           => '',
479
-			'ldap_user_avatar_rule'             => 'default',
480
-		);
481
-	}
421
+    /**
422
+     * @return array an associative array with the default values. Keys are correspond
423
+     * to config-value entries in the database table
424
+     */
425
+    public function getDefaults() {
426
+        return array(
427
+            'ldap_host'                         => '',
428
+            'ldap_port'                         => '',
429
+            'ldap_backup_host'                  => '',
430
+            'ldap_backup_port'                  => '',
431
+            'ldap_override_main_server'         => '',
432
+            'ldap_dn'                           => '',
433
+            'ldap_agent_password'               => '',
434
+            'ldap_base'                         => '',
435
+            'ldap_base_users'                   => '',
436
+            'ldap_base_groups'                  => '',
437
+            'ldap_userlist_filter'              => '',
438
+            'ldap_user_filter_mode'             => 0,
439
+            'ldap_userfilter_objectclass'       => '',
440
+            'ldap_userfilter_groups'            => '',
441
+            'ldap_login_filter'                 => '',
442
+            'ldap_login_filter_mode'            => 0,
443
+            'ldap_loginfilter_email'            => 0,
444
+            'ldap_loginfilter_username'         => 1,
445
+            'ldap_loginfilter_attributes'       => '',
446
+            'ldap_group_filter'                 => '',
447
+            'ldap_group_filter_mode'            => 0,
448
+            'ldap_groupfilter_objectclass'      => '',
449
+            'ldap_groupfilter_groups'           => '',
450
+            'ldap_gid_number'                   => 'gidNumber',
451
+            'ldap_display_name'                 => 'displayName',
452
+            'ldap_user_display_name_2'			=> '',
453
+            'ldap_group_display_name'           => 'cn',
454
+            'ldap_tls'                          => 0,
455
+            'ldap_quota_def'                    => '',
456
+            'ldap_quota_attr'                   => '',
457
+            'ldap_email_attr'                   => '',
458
+            'ldap_group_member_assoc_attribute' => 'uniqueMember',
459
+            'ldap_cache_ttl'                    => 600,
460
+            'ldap_uuid_user_attribute'          => 'auto',
461
+            'ldap_uuid_group_attribute'         => 'auto',
462
+            'home_folder_naming_rule'           => '',
463
+            'ldap_turn_off_cert_check'          => 0,
464
+            'ldap_configuration_active'         => 0,
465
+            'ldap_attributes_for_user_search'   => '',
466
+            'ldap_attributes_for_group_search'  => '',
467
+            'ldap_expert_username_attr'         => '',
468
+            'ldap_expert_uuid_user_attr'        => '',
469
+            'ldap_expert_uuid_group_attr'       => '',
470
+            'has_memberof_filter_support'       => 0,
471
+            'use_memberof_to_detect_membership' => 1,
472
+            'last_jpegPhoto_lookup'             => 0,
473
+            'ldap_nested_groups'                => 0,
474
+            'ldap_paging_size'                  => 500,
475
+            'ldap_turn_on_pwd_change'           => 0,
476
+            'ldap_experienced_admin'            => 0,
477
+            'ldap_dynamic_group_member_url'     => '',
478
+            'ldap_default_ppolicy_dn'           => '',
479
+            'ldap_user_avatar_rule'             => 'default',
480
+        );
481
+    }
482 482
 
483
-	/**
484
-	 * @return array that maps internal variable names to database fields
485
-	 */
486
-	public function getConfigTranslationArray() {
487
-		//TODO: merge them into one representation
488
-		static $array = array(
489
-			'ldap_host'                         => 'ldapHost',
490
-			'ldap_port'                         => 'ldapPort',
491
-			'ldap_backup_host'                  => 'ldapBackupHost',
492
-			'ldap_backup_port'                  => 'ldapBackupPort',
493
-			'ldap_override_main_server'         => 'ldapOverrideMainServer',
494
-			'ldap_dn'                           => 'ldapAgentName',
495
-			'ldap_agent_password'               => 'ldapAgentPassword',
496
-			'ldap_base'                         => 'ldapBase',
497
-			'ldap_base_users'                   => 'ldapBaseUsers',
498
-			'ldap_base_groups'                  => 'ldapBaseGroups',
499
-			'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
500
-			'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
501
-			'ldap_userlist_filter'              => 'ldapUserFilter',
502
-			'ldap_user_filter_mode'             => 'ldapUserFilterMode',
503
-			'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
504
-			'ldap_login_filter'                 => 'ldapLoginFilter',
505
-			'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
506
-			'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
507
-			'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
508
-			'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
509
-			'ldap_group_filter'                 => 'ldapGroupFilter',
510
-			'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
511
-			'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
512
-			'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
513
-			'ldap_gid_number'                   => 'ldapGidNumber',
514
-			'ldap_display_name'                 => 'ldapUserDisplayName',
515
-			'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
516
-			'ldap_group_display_name'           => 'ldapGroupDisplayName',
517
-			'ldap_tls'                          => 'ldapTLS',
518
-			'ldap_quota_def'                    => 'ldapQuotaDefault',
519
-			'ldap_quota_attr'                   => 'ldapQuotaAttribute',
520
-			'ldap_email_attr'                   => 'ldapEmailAttribute',
521
-			'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
522
-			'ldap_cache_ttl'                    => 'ldapCacheTTL',
523
-			'home_folder_naming_rule'           => 'homeFolderNamingRule',
524
-			'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
525
-			'ldap_configuration_active'         => 'ldapConfigurationActive',
526
-			'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
527
-			'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
528
-			'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
529
-			'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
530
-			'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
531
-			'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
532
-			'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
533
-			'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
534
-			'ldap_nested_groups'                => 'ldapNestedGroups',
535
-			'ldap_paging_size'                  => 'ldapPagingSize',
536
-			'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
537
-			'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
538
-			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
539
-			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
540
-			'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
541
-		);
542
-		return $array;
543
-	}
483
+    /**
484
+     * @return array that maps internal variable names to database fields
485
+     */
486
+    public function getConfigTranslationArray() {
487
+        //TODO: merge them into one representation
488
+        static $array = array(
489
+            'ldap_host'                         => 'ldapHost',
490
+            'ldap_port'                         => 'ldapPort',
491
+            'ldap_backup_host'                  => 'ldapBackupHost',
492
+            'ldap_backup_port'                  => 'ldapBackupPort',
493
+            'ldap_override_main_server'         => 'ldapOverrideMainServer',
494
+            'ldap_dn'                           => 'ldapAgentName',
495
+            'ldap_agent_password'               => 'ldapAgentPassword',
496
+            'ldap_base'                         => 'ldapBase',
497
+            'ldap_base_users'                   => 'ldapBaseUsers',
498
+            'ldap_base_groups'                  => 'ldapBaseGroups',
499
+            'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
500
+            'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
501
+            'ldap_userlist_filter'              => 'ldapUserFilter',
502
+            'ldap_user_filter_mode'             => 'ldapUserFilterMode',
503
+            'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
504
+            'ldap_login_filter'                 => 'ldapLoginFilter',
505
+            'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
506
+            'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
507
+            'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
508
+            'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
509
+            'ldap_group_filter'                 => 'ldapGroupFilter',
510
+            'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
511
+            'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
512
+            'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
513
+            'ldap_gid_number'                   => 'ldapGidNumber',
514
+            'ldap_display_name'                 => 'ldapUserDisplayName',
515
+            'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
516
+            'ldap_group_display_name'           => 'ldapGroupDisplayName',
517
+            'ldap_tls'                          => 'ldapTLS',
518
+            'ldap_quota_def'                    => 'ldapQuotaDefault',
519
+            'ldap_quota_attr'                   => 'ldapQuotaAttribute',
520
+            'ldap_email_attr'                   => 'ldapEmailAttribute',
521
+            'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
522
+            'ldap_cache_ttl'                    => 'ldapCacheTTL',
523
+            'home_folder_naming_rule'           => 'homeFolderNamingRule',
524
+            'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
525
+            'ldap_configuration_active'         => 'ldapConfigurationActive',
526
+            'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
527
+            'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
528
+            'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
529
+            'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
530
+            'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
531
+            'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
532
+            'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
533
+            'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
534
+            'ldap_nested_groups'                => 'ldapNestedGroups',
535
+            'ldap_paging_size'                  => 'ldapPagingSize',
536
+            'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
537
+            'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
538
+            'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
539
+            'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
540
+            'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
541
+        );
542
+        return $array;
543
+    }
544 544
 
545
-	/**
546
-	 * @param string $rule
547
-	 * @return array
548
-	 * @throws \RuntimeException
549
-	 */
550
-	public function resolveRule($rule) {
551
-		if($rule === 'avatar') {
552
-			return $this->getAvatarAttributes();
553
-		}
554
-		throw new \RuntimeException('Invalid rule');
555
-	}
545
+    /**
546
+     * @param string $rule
547
+     * @return array
548
+     * @throws \RuntimeException
549
+     */
550
+    public function resolveRule($rule) {
551
+        if($rule === 'avatar') {
552
+            return $this->getAvatarAttributes();
553
+        }
554
+        throw new \RuntimeException('Invalid rule');
555
+    }
556 556
 
557
-	public function getAvatarAttributes() {
558
-		$value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
559
-		$defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
557
+    public function getAvatarAttributes() {
558
+        $value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
559
+        $defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
560 560
 
561
-		if($value === self::AVATAR_PREFIX_NONE) {
562
-			return [];
563
-		}
564
-		if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
565
-			$attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
566
-			if($attribute === '') {
567
-				return $defaultAttributes;
568
-			}
569
-			return [strtolower($attribute)];
570
-		}
571
-		if($value !== self::AVATAR_PREFIX_DEFAULT) {
572
-			\OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
573
-		}
574
-		return $defaultAttributes;
575
-	}
561
+        if($value === self::AVATAR_PREFIX_NONE) {
562
+            return [];
563
+        }
564
+        if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
565
+            $attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
566
+            if($attribute === '') {
567
+                return $defaultAttributes;
568
+            }
569
+            return [strtolower($attribute)];
570
+        }
571
+        if($value !== self::AVATAR_PREFIX_DEFAULT) {
572
+            \OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
573
+        }
574
+        return $defaultAttributes;
575
+    }
576 576
 
577 577
 }
Please login to merge, or discard this patch.