Passed
Push — master ( f0dd71...c56a27 )
by Christoph
11:49 queued 12s
created
apps/user_ldap/lib/LDAP.php 2 patches
Indentation   +357 added lines, -357 removed lines patch added patch discarded remove patch
@@ -35,361 +35,361 @@
 block discarded – undo
35 35
 use OCA\User_LDAP\Exceptions\ConstraintViolationException;
36 36
 
37 37
 class LDAP implements ILDAPWrapper {
38
-	protected $curFunc = '';
39
-	protected $curArgs = [];
40
-
41
-	/**
42
-	 * @param resource $link
43
-	 * @param string $dn
44
-	 * @param string $password
45
-	 * @return bool|mixed
46
-	 */
47
-	public function bind($link, $dn, $password) {
48
-		return $this->invokeLDAPMethod('bind', $link, $dn, $password);
49
-	}
50
-
51
-	/**
52
-	 * @param string $host
53
-	 * @param string $port
54
-	 * @return mixed
55
-	 */
56
-	public function connect($host, $port) {
57
-		if(strpos($host, '://') === false) {
58
-			$host = 'ldap://' . $host;
59
-		}
60
-		if(strpos($host, ':', strpos($host, '://') + 1) === false) {
61
-			//ldap_connect ignores port parameter when URLs are passed
62
-			$host .= ':' . $port;
63
-		}
64
-		return $this->invokeLDAPMethod('connect', $host);
65
-	}
66
-
67
-	/**
68
-	 * @param resource $link
69
-	 * @param resource $result
70
-	 * @param string $cookie
71
-	 * @return bool|LDAP
72
-	 */
73
-	public function controlPagedResultResponse($link, $result, &$cookie) {
74
-		$this->preFunctionCall('ldap_control_paged_result_response',
75
-			[$link, $result, $cookie]);
76
-		$result = ldap_control_paged_result_response($link, $result, $cookie);
77
-		$this->postFunctionCall();
78
-
79
-		return $result;
80
-	}
81
-
82
-	/**
83
-	 * @param LDAP $link
84
-	 * @param int $pageSize
85
-	 * @param bool $isCritical
86
-	 * @param string $cookie
87
-	 * @return mixed|true
88
-	 */
89
-	public function controlPagedResult($link, $pageSize, $isCritical, $cookie) {
90
-		return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize,
91
-										$isCritical, $cookie);
92
-	}
93
-
94
-	/**
95
-	 * @param LDAP $link
96
-	 * @param LDAP $result
97
-	 * @return mixed
98
-	 */
99
-	public function countEntries($link, $result) {
100
-		return $this->invokeLDAPMethod('count_entries', $link, $result);
101
-	}
102
-
103
-	/**
104
-	 * @param LDAP $link
105
-	 * @return integer
106
-	 */
107
-	public function errno($link) {
108
-		return $this->invokeLDAPMethod('errno', $link);
109
-	}
110
-
111
-	/**
112
-	 * @param LDAP $link
113
-	 * @return string
114
-	 */
115
-	public function error($link) {
116
-		return $this->invokeLDAPMethod('error', $link);
117
-	}
118
-
119
-	/**
120
-	 * Splits DN into its component parts
121
-	 * @param string $dn
122
-	 * @param int @withAttrib
123
-	 * @return array|false
124
-	 * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
125
-	 */
126
-	public function explodeDN($dn, $withAttrib) {
127
-		return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
128
-	}
129
-
130
-	/**
131
-	 * @param LDAP $link
132
-	 * @param LDAP $result
133
-	 * @return mixed
134
-	 */
135
-	public function firstEntry($link, $result) {
136
-		return $this->invokeLDAPMethod('first_entry', $link, $result);
137
-	}
138
-
139
-	/**
140
-	 * @param LDAP $link
141
-	 * @param LDAP $result
142
-	 * @return array|mixed
143
-	 */
144
-	public function getAttributes($link, $result) {
145
-		return $this->invokeLDAPMethod('get_attributes', $link, $result);
146
-	}
147
-
148
-	/**
149
-	 * @param LDAP $link
150
-	 * @param LDAP $result
151
-	 * @return mixed|string
152
-	 */
153
-	public function getDN($link, $result) {
154
-		return $this->invokeLDAPMethod('get_dn', $link, $result);
155
-	}
156
-
157
-	/**
158
-	 * @param LDAP $link
159
-	 * @param LDAP $result
160
-	 * @return array|mixed
161
-	 */
162
-	public function getEntries($link, $result) {
163
-		return $this->invokeLDAPMethod('get_entries', $link, $result);
164
-	}
165
-
166
-	/**
167
-	 * @param LDAP $link
168
-	 * @param resource $result
169
-	 * @return mixed
170
-	 */
171
-	public function nextEntry($link, $result) {
172
-		return $this->invokeLDAPMethod('next_entry', $link, $result);
173
-	}
174
-
175
-	/**
176
-	 * @param LDAP $link
177
-	 * @param string $baseDN
178
-	 * @param string $filter
179
-	 * @param array $attr
180
-	 * @return mixed
181
-	 */
182
-	public function read($link, $baseDN, $filter, $attr) {
183
-		return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr);
184
-	}
185
-
186
-	/**
187
-	 * @param LDAP $link
188
-	 * @param string $baseDN
189
-	 * @param string $filter
190
-	 * @param array $attr
191
-	 * @param int $attrsOnly
192
-	 * @param int $limit
193
-	 * @return mixed
194
-	 * @throws \Exception
195
-	 */
196
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
197
-		$oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
198
-			if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
199
-				return true;
200
-			}
201
-			$oldHandler($no, $message, $file, $line);
202
-			return true;
203
-		});
204
-		try {
205
-			$result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
206
-			restore_error_handler();
207
-			return $result;
208
-		} catch (\Exception $e) {
209
-			restore_error_handler();
210
-			throw $e;
211
-		}
212
-	}
213
-
214
-	/**
215
-	 * @param LDAP $link
216
-	 * @param string $userDN
217
-	 * @param string $password
218
-	 * @return bool
219
-	 */
220
-	public function modReplace($link, $userDN, $password) {
221
-		return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
222
-	}
223
-
224
-	/**
225
-	 * @param LDAP $link
226
-	 * @param string $userDN
227
-	 * @param string $oldPassword
228
-	 * @param string $password
229
-	 * @return bool
230
-	 */
231
-	public function exopPasswd($link, $userDN, $oldPassword, $password) {
232
-		return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
233
-	}
234
-
235
-	/**
236
-	 * @param LDAP $link
237
-	 * @param string $option
238
-	 * @param int $value
239
-	 * @return bool|mixed
240
-	 */
241
-	public function setOption($link, $option, $value) {
242
-		return $this->invokeLDAPMethod('set_option', $link, $option, $value);
243
-	}
244
-
245
-	/**
246
-	 * @param LDAP $link
247
-	 * @return mixed|true
248
-	 */
249
-	public function startTls($link) {
250
-		return $this->invokeLDAPMethod('start_tls', $link);
251
-	}
252
-
253
-	/**
254
-	 * @param resource $link
255
-	 * @return bool|mixed
256
-	 */
257
-	public function unbind($link) {
258
-		return $this->invokeLDAPMethod('unbind', $link);
259
-	}
260
-
261
-	/**
262
-	 * Checks whether the server supports LDAP
263
-	 * @return boolean if it the case, false otherwise
264
-	 * */
265
-	public function areLDAPFunctionsAvailable() {
266
-		return function_exists('ldap_connect');
267
-	}
268
-
269
-	/**
270
-	 * Checks whether the submitted parameter is a resource
271
-	 * @param Resource $resource the resource variable to check
272
-	 * @return bool true if it is a resource, false otherwise
273
-	 */
274
-	public function isResource($resource) {
275
-		return is_resource($resource);
276
-	}
277
-
278
-	/**
279
-	 * Checks whether the return value from LDAP is wrong or not.
280
-	 *
281
-	 * When using ldap_search we provide an array, in case multiple bases are
282
-	 * configured. Thus, we need to check the array elements.
283
-	 *
284
-	 * @param $result
285
-	 * @return bool
286
-	 */
287
-	protected function isResultFalse($result) {
288
-		if($result === false) {
289
-			return true;
290
-		}
291
-
292
-		if($this->curFunc === 'ldap_search' && is_array($result)) {
293
-			foreach ($result as $singleResult) {
294
-				if($singleResult === false) {
295
-					return true;
296
-				}
297
-			}
298
-		}
299
-
300
-		return false;
301
-	}
302
-
303
-	/**
304
-	 * @return mixed
305
-	 */
306
-	protected function invokeLDAPMethod() {
307
-		$arguments = func_get_args();
308
-		$func = 'ldap_' . array_shift($arguments);
309
-		if(function_exists($func)) {
310
-			$this->preFunctionCall($func, $arguments);
311
-			$result = call_user_func_array($func, $arguments);
312
-			if ($this->isResultFalse($result)) {
313
-				$this->postFunctionCall();
314
-			}
315
-			return $result;
316
-		}
317
-		return null;
318
-	}
319
-
320
-	/**
321
-	 * @param string $functionName
322
-	 * @param array $args
323
-	 */
324
-	private function preFunctionCall($functionName, $args) {
325
-		$this->curFunc = $functionName;
326
-		$this->curArgs = $args;
327
-	}
328
-
329
-	/**
330
-	 * Analyzes the returned LDAP error and acts accordingly if not 0
331
-	 *
332
-	 * @param resource $resource the LDAP Connection resource
333
-	 * @throws ConstraintViolationException
334
-	 * @throws ServerNotAvailableException
335
-	 * @throws \Exception
336
-	 */
337
-	private function processLDAPError($resource) {
338
-		$errorCode = ldap_errno($resource);
339
-		if($errorCode === 0) {
340
-			return;
341
-		}
342
-		$errorMsg  = ldap_error($resource);
343
-
344
-		if($this->curFunc === 'ldap_get_entries'
345
-			&& $errorCode === -4) {
346
-		} else if ($errorCode === 32) {
347
-			//for now
348
-		} else if ($errorCode === 10) {
349
-			//referrals, we switch them off, but then there is AD :)
350
-		} else if ($errorCode === -1) {
351
-			throw new ServerNotAvailableException('Lost connection to LDAP server.');
352
-		} else if ($errorCode === 52) {
353
-			throw new ServerNotAvailableException('LDAP server is shutting down.');
354
-		} else if ($errorCode === 48) {
355
-			throw new \Exception('LDAP authentication method rejected', $errorCode);
356
-		} else if ($errorCode === 1) {
357
-			throw new \Exception('LDAP Operations error', $errorCode);
358
-		} else if ($errorCode === 19) {
359
-			ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
360
-			throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
361
-		} else {
362
-			\OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
363
-				'app' => 'user_ldap',
364
-				'message' => $errorMsg,
365
-				'code' => $errorCode,
366
-				'func' => $this->curFunc,
367
-			]);
368
-		}
369
-	}
370
-
371
-	/**
372
-	 * Called after an ldap method is run to act on LDAP error if necessary
373
-	 * @throw \Exception
374
-	 */
375
-	private function postFunctionCall() {
376
-		if($this->isResource($this->curArgs[0])) {
377
-			$resource = $this->curArgs[0];
378
-		} else if(
379
-			   $this->curFunc === 'ldap_search'
380
-			&& is_array($this->curArgs[0])
381
-			&& $this->isResource($this->curArgs[0][0])
382
-		) {
383
-			// we use always the same LDAP connection resource, is enough to
384
-			// take the first one.
385
-			$resource = $this->curArgs[0][0];
386
-		} else {
387
-			return;
388
-		}
389
-
390
-		$this->processLDAPError($resource);
391
-
392
-		$this->curFunc = '';
393
-		$this->curArgs = [];
394
-	}
38
+    protected $curFunc = '';
39
+    protected $curArgs = [];
40
+
41
+    /**
42
+     * @param resource $link
43
+     * @param string $dn
44
+     * @param string $password
45
+     * @return bool|mixed
46
+     */
47
+    public function bind($link, $dn, $password) {
48
+        return $this->invokeLDAPMethod('bind', $link, $dn, $password);
49
+    }
50
+
51
+    /**
52
+     * @param string $host
53
+     * @param string $port
54
+     * @return mixed
55
+     */
56
+    public function connect($host, $port) {
57
+        if(strpos($host, '://') === false) {
58
+            $host = 'ldap://' . $host;
59
+        }
60
+        if(strpos($host, ':', strpos($host, '://') + 1) === false) {
61
+            //ldap_connect ignores port parameter when URLs are passed
62
+            $host .= ':' . $port;
63
+        }
64
+        return $this->invokeLDAPMethod('connect', $host);
65
+    }
66
+
67
+    /**
68
+     * @param resource $link
69
+     * @param resource $result
70
+     * @param string $cookie
71
+     * @return bool|LDAP
72
+     */
73
+    public function controlPagedResultResponse($link, $result, &$cookie) {
74
+        $this->preFunctionCall('ldap_control_paged_result_response',
75
+            [$link, $result, $cookie]);
76
+        $result = ldap_control_paged_result_response($link, $result, $cookie);
77
+        $this->postFunctionCall();
78
+
79
+        return $result;
80
+    }
81
+
82
+    /**
83
+     * @param LDAP $link
84
+     * @param int $pageSize
85
+     * @param bool $isCritical
86
+     * @param string $cookie
87
+     * @return mixed|true
88
+     */
89
+    public function controlPagedResult($link, $pageSize, $isCritical, $cookie) {
90
+        return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize,
91
+                                        $isCritical, $cookie);
92
+    }
93
+
94
+    /**
95
+     * @param LDAP $link
96
+     * @param LDAP $result
97
+     * @return mixed
98
+     */
99
+    public function countEntries($link, $result) {
100
+        return $this->invokeLDAPMethod('count_entries', $link, $result);
101
+    }
102
+
103
+    /**
104
+     * @param LDAP $link
105
+     * @return integer
106
+     */
107
+    public function errno($link) {
108
+        return $this->invokeLDAPMethod('errno', $link);
109
+    }
110
+
111
+    /**
112
+     * @param LDAP $link
113
+     * @return string
114
+     */
115
+    public function error($link) {
116
+        return $this->invokeLDAPMethod('error', $link);
117
+    }
118
+
119
+    /**
120
+     * Splits DN into its component parts
121
+     * @param string $dn
122
+     * @param int @withAttrib
123
+     * @return array|false
124
+     * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
125
+     */
126
+    public function explodeDN($dn, $withAttrib) {
127
+        return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
128
+    }
129
+
130
+    /**
131
+     * @param LDAP $link
132
+     * @param LDAP $result
133
+     * @return mixed
134
+     */
135
+    public function firstEntry($link, $result) {
136
+        return $this->invokeLDAPMethod('first_entry', $link, $result);
137
+    }
138
+
139
+    /**
140
+     * @param LDAP $link
141
+     * @param LDAP $result
142
+     * @return array|mixed
143
+     */
144
+    public function getAttributes($link, $result) {
145
+        return $this->invokeLDAPMethod('get_attributes', $link, $result);
146
+    }
147
+
148
+    /**
149
+     * @param LDAP $link
150
+     * @param LDAP $result
151
+     * @return mixed|string
152
+     */
153
+    public function getDN($link, $result) {
154
+        return $this->invokeLDAPMethod('get_dn', $link, $result);
155
+    }
156
+
157
+    /**
158
+     * @param LDAP $link
159
+     * @param LDAP $result
160
+     * @return array|mixed
161
+     */
162
+    public function getEntries($link, $result) {
163
+        return $this->invokeLDAPMethod('get_entries', $link, $result);
164
+    }
165
+
166
+    /**
167
+     * @param LDAP $link
168
+     * @param resource $result
169
+     * @return mixed
170
+     */
171
+    public function nextEntry($link, $result) {
172
+        return $this->invokeLDAPMethod('next_entry', $link, $result);
173
+    }
174
+
175
+    /**
176
+     * @param LDAP $link
177
+     * @param string $baseDN
178
+     * @param string $filter
179
+     * @param array $attr
180
+     * @return mixed
181
+     */
182
+    public function read($link, $baseDN, $filter, $attr) {
183
+        return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr);
184
+    }
185
+
186
+    /**
187
+     * @param LDAP $link
188
+     * @param string $baseDN
189
+     * @param string $filter
190
+     * @param array $attr
191
+     * @param int $attrsOnly
192
+     * @param int $limit
193
+     * @return mixed
194
+     * @throws \Exception
195
+     */
196
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
197
+        $oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
198
+            if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
199
+                return true;
200
+            }
201
+            $oldHandler($no, $message, $file, $line);
202
+            return true;
203
+        });
204
+        try {
205
+            $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
206
+            restore_error_handler();
207
+            return $result;
208
+        } catch (\Exception $e) {
209
+            restore_error_handler();
210
+            throw $e;
211
+        }
212
+    }
213
+
214
+    /**
215
+     * @param LDAP $link
216
+     * @param string $userDN
217
+     * @param string $password
218
+     * @return bool
219
+     */
220
+    public function modReplace($link, $userDN, $password) {
221
+        return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
222
+    }
223
+
224
+    /**
225
+     * @param LDAP $link
226
+     * @param string $userDN
227
+     * @param string $oldPassword
228
+     * @param string $password
229
+     * @return bool
230
+     */
231
+    public function exopPasswd($link, $userDN, $oldPassword, $password) {
232
+        return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
233
+    }
234
+
235
+    /**
236
+     * @param LDAP $link
237
+     * @param string $option
238
+     * @param int $value
239
+     * @return bool|mixed
240
+     */
241
+    public function setOption($link, $option, $value) {
242
+        return $this->invokeLDAPMethod('set_option', $link, $option, $value);
243
+    }
244
+
245
+    /**
246
+     * @param LDAP $link
247
+     * @return mixed|true
248
+     */
249
+    public function startTls($link) {
250
+        return $this->invokeLDAPMethod('start_tls', $link);
251
+    }
252
+
253
+    /**
254
+     * @param resource $link
255
+     * @return bool|mixed
256
+     */
257
+    public function unbind($link) {
258
+        return $this->invokeLDAPMethod('unbind', $link);
259
+    }
260
+
261
+    /**
262
+     * Checks whether the server supports LDAP
263
+     * @return boolean if it the case, false otherwise
264
+     * */
265
+    public function areLDAPFunctionsAvailable() {
266
+        return function_exists('ldap_connect');
267
+    }
268
+
269
+    /**
270
+     * Checks whether the submitted parameter is a resource
271
+     * @param Resource $resource the resource variable to check
272
+     * @return bool true if it is a resource, false otherwise
273
+     */
274
+    public function isResource($resource) {
275
+        return is_resource($resource);
276
+    }
277
+
278
+    /**
279
+     * Checks whether the return value from LDAP is wrong or not.
280
+     *
281
+     * When using ldap_search we provide an array, in case multiple bases are
282
+     * configured. Thus, we need to check the array elements.
283
+     *
284
+     * @param $result
285
+     * @return bool
286
+     */
287
+    protected function isResultFalse($result) {
288
+        if($result === false) {
289
+            return true;
290
+        }
291
+
292
+        if($this->curFunc === 'ldap_search' && is_array($result)) {
293
+            foreach ($result as $singleResult) {
294
+                if($singleResult === false) {
295
+                    return true;
296
+                }
297
+            }
298
+        }
299
+
300
+        return false;
301
+    }
302
+
303
+    /**
304
+     * @return mixed
305
+     */
306
+    protected function invokeLDAPMethod() {
307
+        $arguments = func_get_args();
308
+        $func = 'ldap_' . array_shift($arguments);
309
+        if(function_exists($func)) {
310
+            $this->preFunctionCall($func, $arguments);
311
+            $result = call_user_func_array($func, $arguments);
312
+            if ($this->isResultFalse($result)) {
313
+                $this->postFunctionCall();
314
+            }
315
+            return $result;
316
+        }
317
+        return null;
318
+    }
319
+
320
+    /**
321
+     * @param string $functionName
322
+     * @param array $args
323
+     */
324
+    private function preFunctionCall($functionName, $args) {
325
+        $this->curFunc = $functionName;
326
+        $this->curArgs = $args;
327
+    }
328
+
329
+    /**
330
+     * Analyzes the returned LDAP error and acts accordingly if not 0
331
+     *
332
+     * @param resource $resource the LDAP Connection resource
333
+     * @throws ConstraintViolationException
334
+     * @throws ServerNotAvailableException
335
+     * @throws \Exception
336
+     */
337
+    private function processLDAPError($resource) {
338
+        $errorCode = ldap_errno($resource);
339
+        if($errorCode === 0) {
340
+            return;
341
+        }
342
+        $errorMsg  = ldap_error($resource);
343
+
344
+        if($this->curFunc === 'ldap_get_entries'
345
+            && $errorCode === -4) {
346
+        } else if ($errorCode === 32) {
347
+            //for now
348
+        } else if ($errorCode === 10) {
349
+            //referrals, we switch them off, but then there is AD :)
350
+        } else if ($errorCode === -1) {
351
+            throw new ServerNotAvailableException('Lost connection to LDAP server.');
352
+        } else if ($errorCode === 52) {
353
+            throw new ServerNotAvailableException('LDAP server is shutting down.');
354
+        } else if ($errorCode === 48) {
355
+            throw new \Exception('LDAP authentication method rejected', $errorCode);
356
+        } else if ($errorCode === 1) {
357
+            throw new \Exception('LDAP Operations error', $errorCode);
358
+        } else if ($errorCode === 19) {
359
+            ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
360
+            throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
361
+        } else {
362
+            \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
363
+                'app' => 'user_ldap',
364
+                'message' => $errorMsg,
365
+                'code' => $errorCode,
366
+                'func' => $this->curFunc,
367
+            ]);
368
+        }
369
+    }
370
+
371
+    /**
372
+     * Called after an ldap method is run to act on LDAP error if necessary
373
+     * @throw \Exception
374
+     */
375
+    private function postFunctionCall() {
376
+        if($this->isResource($this->curArgs[0])) {
377
+            $resource = $this->curArgs[0];
378
+        } else if(
379
+                $this->curFunc === 'ldap_search'
380
+            && is_array($this->curArgs[0])
381
+            && $this->isResource($this->curArgs[0][0])
382
+        ) {
383
+            // we use always the same LDAP connection resource, is enough to
384
+            // take the first one.
385
+            $resource = $this->curArgs[0][0];
386
+        } else {
387
+            return;
388
+        }
389
+
390
+        $this->processLDAPError($resource);
391
+
392
+        $this->curFunc = '';
393
+        $this->curArgs = [];
394
+    }
395 395
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -54,12 +54,12 @@  discard block
 block discarded – undo
54 54
 	 * @return mixed
55 55
 	 */
56 56
 	public function connect($host, $port) {
57
-		if(strpos($host, '://') === false) {
58
-			$host = 'ldap://' . $host;
57
+		if (strpos($host, '://') === false) {
58
+			$host = 'ldap://'.$host;
59 59
 		}
60
-		if(strpos($host, ':', strpos($host, '://') + 1) === false) {
60
+		if (strpos($host, ':', strpos($host, '://') + 1) === false) {
61 61
 			//ldap_connect ignores port parameter when URLs are passed
62
-			$host .= ':' . $port;
62
+			$host .= ':'.$port;
63 63
 		}
64 64
 		return $this->invokeLDAPMethod('connect', $host);
65 65
 	}
@@ -194,8 +194,8 @@  discard block
 block discarded – undo
194 194
 	 * @throws \Exception
195 195
 	 */
196 196
 	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
197
-		$oldHandler = set_error_handler(function ($no, $message, $file, $line) use (&$oldHandler) {
198
-			if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
197
+		$oldHandler = set_error_handler(function($no, $message, $file, $line) use (&$oldHandler) {
198
+			if (strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
199 199
 				return true;
200 200
 			}
201 201
 			$oldHandler($no, $message, $file, $line);
@@ -285,13 +285,13 @@  discard block
 block discarded – undo
285 285
 	 * @return bool
286 286
 	 */
287 287
 	protected function isResultFalse($result) {
288
-		if($result === false) {
288
+		if ($result === false) {
289 289
 			return true;
290 290
 		}
291 291
 
292
-		if($this->curFunc === 'ldap_search' && is_array($result)) {
292
+		if ($this->curFunc === 'ldap_search' && is_array($result)) {
293 293
 			foreach ($result as $singleResult) {
294
-				if($singleResult === false) {
294
+				if ($singleResult === false) {
295 295
 					return true;
296 296
 				}
297 297
 			}
@@ -305,8 +305,8 @@  discard block
 block discarded – undo
305 305
 	 */
306 306
 	protected function invokeLDAPMethod() {
307 307
 		$arguments = func_get_args();
308
-		$func = 'ldap_' . array_shift($arguments);
309
-		if(function_exists($func)) {
308
+		$func = 'ldap_'.array_shift($arguments);
309
+		if (function_exists($func)) {
310 310
 			$this->preFunctionCall($func, $arguments);
311 311
 			$result = call_user_func_array($func, $arguments);
312 312
 			if ($this->isResultFalse($result)) {
@@ -336,12 +336,12 @@  discard block
 block discarded – undo
336 336
 	 */
337 337
 	private function processLDAPError($resource) {
338 338
 		$errorCode = ldap_errno($resource);
339
-		if($errorCode === 0) {
339
+		if ($errorCode === 0) {
340 340
 			return;
341 341
 		}
342
-		$errorMsg  = ldap_error($resource);
342
+		$errorMsg = ldap_error($resource);
343 343
 
344
-		if($this->curFunc === 'ldap_get_entries'
344
+		if ($this->curFunc === 'ldap_get_entries'
345 345
 			&& $errorCode === -4) {
346 346
 		} else if ($errorCode === 32) {
347 347
 			//for now
@@ -357,7 +357,7 @@  discard block
 block discarded – undo
357 357
 			throw new \Exception('LDAP Operations error', $errorCode);
358 358
 		} else if ($errorCode === 19) {
359 359
 			ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
360
-			throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
360
+			throw new ConstraintViolationException(!empty($extended_error) ? $extended_error : $errorMsg, $errorCode);
361 361
 		} else {
362 362
 			\OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
363 363
 				'app' => 'user_ldap',
@@ -373,9 +373,9 @@  discard block
 block discarded – undo
373 373
 	 * @throw \Exception
374 374
 	 */
375 375
 	private function postFunctionCall() {
376
-		if($this->isResource($this->curArgs[0])) {
376
+		if ($this->isResource($this->curArgs[0])) {
377 377
 			$resource = $this->curArgs[0];
378
-		} else if(
378
+		} else if (
379 379
 			   $this->curFunc === 'ldap_search'
380 380
 			&& is_array($this->curArgs[0])
381 381
 			&& $this->isResource($this->curArgs[0][0])
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/Manager.php 2 patches
Indentation   +200 added lines, -200 removed lines patch added patch discarded remove patch
@@ -46,232 +46,232 @@
 block discarded – undo
46 46
  * cache
47 47
  */
48 48
 class Manager {
49
-	/** @var Access */
50
-	protected $access;
49
+    /** @var Access */
50
+    protected $access;
51 51
 
52
-	/** @var IConfig */
53
-	protected $ocConfig;
52
+    /** @var IConfig */
53
+    protected $ocConfig;
54 54
 
55
-	/** @var IDBConnection */
56
-	protected $db;
55
+    /** @var IDBConnection */
56
+    protected $db;
57 57
 
58
-	/** @var IUserManager */
59
-	protected $userManager;
58
+    /** @var IUserManager */
59
+    protected $userManager;
60 60
 
61
-	/** @var INotificationManager */
62
-	protected $notificationManager;
61
+    /** @var INotificationManager */
62
+    protected $notificationManager;
63 63
 
64
-	/** @var FilesystemHelper */
65
-	protected $ocFilesystem;
64
+    /** @var FilesystemHelper */
65
+    protected $ocFilesystem;
66 66
 
67
-	/** @var LogWrapper */
68
-	protected $ocLog;
67
+    /** @var LogWrapper */
68
+    protected $ocLog;
69 69
 
70
-	/** @var Image */
71
-	protected $image;
70
+    /** @var Image */
71
+    protected $image;
72 72
 
73
-	/** @param \OCP\IAvatarManager */
74
-	protected $avatarManager;
73
+    /** @param \OCP\IAvatarManager */
74
+    protected $avatarManager;
75 75
 
76
-	/**
77
-	 * @var CappedMemoryCache $usersByDN
78
-	 */
79
-	protected $usersByDN;
80
-	/**
81
-	 * @var CappedMemoryCache $usersByUid
82
-	 */
83
-	protected $usersByUid;
76
+    /**
77
+     * @var CappedMemoryCache $usersByDN
78
+     */
79
+    protected $usersByDN;
80
+    /**
81
+     * @var CappedMemoryCache $usersByUid
82
+     */
83
+    protected $usersByUid;
84 84
 
85
-	/**
86
-	 * @param IConfig $ocConfig
87
-	 * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
88
-	 * gives access to necessary functions from the OC filesystem
89
-	 * @param  \OCA\User_LDAP\LogWrapper $ocLog
90
-	 * @param IAvatarManager $avatarManager
91
-	 * @param Image $image an empty image instance
92
-	 * @param IDBConnection $db
93
-	 * @throws \Exception when the methods mentioned above do not exist
94
-	 */
95
-	public function __construct(IConfig $ocConfig,
96
-								FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
97
-								IAvatarManager $avatarManager, Image $image,
98
-								IDBConnection $db, IUserManager $userManager,
99
-								INotificationManager $notificationManager) {
85
+    /**
86
+     * @param IConfig $ocConfig
87
+     * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
88
+     * gives access to necessary functions from the OC filesystem
89
+     * @param  \OCA\User_LDAP\LogWrapper $ocLog
90
+     * @param IAvatarManager $avatarManager
91
+     * @param Image $image an empty image instance
92
+     * @param IDBConnection $db
93
+     * @throws \Exception when the methods mentioned above do not exist
94
+     */
95
+    public function __construct(IConfig $ocConfig,
96
+                                FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
97
+                                IAvatarManager $avatarManager, Image $image,
98
+                                IDBConnection $db, IUserManager $userManager,
99
+                                INotificationManager $notificationManager) {
100 100
 
101
-		$this->ocConfig            = $ocConfig;
102
-		$this->ocFilesystem        = $ocFilesystem;
103
-		$this->ocLog               = $ocLog;
104
-		$this->avatarManager       = $avatarManager;
105
-		$this->image               = $image;
106
-		$this->db                  = $db;
107
-		$this->userManager         = $userManager;
108
-		$this->notificationManager = $notificationManager;
109
-		$this->usersByDN           = new CappedMemoryCache();
110
-		$this->usersByUid          = new CappedMemoryCache();
111
-	}
101
+        $this->ocConfig            = $ocConfig;
102
+        $this->ocFilesystem        = $ocFilesystem;
103
+        $this->ocLog               = $ocLog;
104
+        $this->avatarManager       = $avatarManager;
105
+        $this->image               = $image;
106
+        $this->db                  = $db;
107
+        $this->userManager         = $userManager;
108
+        $this->notificationManager = $notificationManager;
109
+        $this->usersByDN           = new CappedMemoryCache();
110
+        $this->usersByUid          = new CappedMemoryCache();
111
+    }
112 112
 
113
-	/**
114
-	 * Binds manager to an instance of Access.
115
-	 * It needs to be assigned first before the manager can be used.
116
-	 * @param Access
117
-	 */
118
-	public function setLdapAccess(Access $access) {
119
-		$this->access = $access;
120
-	}
113
+    /**
114
+     * Binds manager to an instance of Access.
115
+     * It needs to be assigned first before the manager can be used.
116
+     * @param Access
117
+     */
118
+    public function setLdapAccess(Access $access) {
119
+        $this->access = $access;
120
+    }
121 121
 
122
-	/**
123
-	 * @brief creates an instance of User and caches (just runtime) it in the
124
-	 * property array
125
-	 * @param string $dn the DN of the user
126
-	 * @param string $uid the internal (owncloud) username
127
-	 * @return \OCA\User_LDAP\User\User
128
-	 */
129
-	private function createAndCache($dn, $uid) {
130
-		$this->checkAccess();
131
-		$user = new User($uid, $dn, $this->access, $this->ocConfig,
132
-			$this->ocFilesystem, clone $this->image, $this->ocLog,
133
-			$this->avatarManager, $this->userManager, 
134
-			$this->notificationManager);
135
-		$this->usersByDN[$dn]   = $user;
136
-		$this->usersByUid[$uid] = $user;
137
-		return $user;
138
-	}
122
+    /**
123
+     * @brief creates an instance of User and caches (just runtime) it in the
124
+     * property array
125
+     * @param string $dn the DN of the user
126
+     * @param string $uid the internal (owncloud) username
127
+     * @return \OCA\User_LDAP\User\User
128
+     */
129
+    private function createAndCache($dn, $uid) {
130
+        $this->checkAccess();
131
+        $user = new User($uid, $dn, $this->access, $this->ocConfig,
132
+            $this->ocFilesystem, clone $this->image, $this->ocLog,
133
+            $this->avatarManager, $this->userManager, 
134
+            $this->notificationManager);
135
+        $this->usersByDN[$dn]   = $user;
136
+        $this->usersByUid[$uid] = $user;
137
+        return $user;
138
+    }
139 139
 
140
-	/**
141
-	 * removes a user entry from the cache
142
-	 * @param $uid
143
-	 */
144
-	public function invalidate($uid) {
145
-		if(!isset($this->usersByUid[$uid])) {
146
-			return;
147
-		}
148
-		$dn = $this->usersByUid[$uid]->getDN();
149
-		unset($this->usersByUid[$uid]);
150
-		unset($this->usersByDN[$dn]);
151
-	}
140
+    /**
141
+     * removes a user entry from the cache
142
+     * @param $uid
143
+     */
144
+    public function invalidate($uid) {
145
+        if(!isset($this->usersByUid[$uid])) {
146
+            return;
147
+        }
148
+        $dn = $this->usersByUid[$uid]->getDN();
149
+        unset($this->usersByUid[$uid]);
150
+        unset($this->usersByDN[$dn]);
151
+    }
152 152
 
153
-	/**
154
-	 * @brief checks whether the Access instance has been set
155
-	 * @throws \Exception if Access has not been set
156
-	 * @return null
157
-	 */
158
-	private function checkAccess() {
159
-		if(is_null($this->access)) {
160
-			throw new \Exception('LDAP Access instance must be set first');
161
-		}
162
-	}
153
+    /**
154
+     * @brief checks whether the Access instance has been set
155
+     * @throws \Exception if Access has not been set
156
+     * @return null
157
+     */
158
+    private function checkAccess() {
159
+        if(is_null($this->access)) {
160
+            throw new \Exception('LDAP Access instance must be set first');
161
+        }
162
+    }
163 163
 
164
-	/**
165
-	 * returns a list of attributes that will be processed further, e.g. quota,
166
-	 * email, displayname, or others.
167
-	 *
168
-	 * @param bool $minimal - optional, set to true to skip attributes with big
169
-	 * payload
170
-	 * @return string[]
171
-	 */
172
-	public function getAttributes($minimal = false) {
173
-		$baseAttributes = array_merge(Access::UUID_ATTRIBUTES, ['dn', 'uid', 'samaccountname', 'memberof']);
174
-		$attributes = [
175
-			$this->access->getConnection()->ldapExpertUUIDUserAttr,
176
-			$this->access->getConnection()->ldapQuotaAttribute,
177
-			$this->access->getConnection()->ldapEmailAttribute,
178
-			$this->access->getConnection()->ldapUserDisplayName,
179
-			$this->access->getConnection()->ldapUserDisplayName2,
180
-			$this->access->getConnection()->ldapExtStorageHomeAttribute,
181
-		];
164
+    /**
165
+     * returns a list of attributes that will be processed further, e.g. quota,
166
+     * email, displayname, or others.
167
+     *
168
+     * @param bool $minimal - optional, set to true to skip attributes with big
169
+     * payload
170
+     * @return string[]
171
+     */
172
+    public function getAttributes($minimal = false) {
173
+        $baseAttributes = array_merge(Access::UUID_ATTRIBUTES, ['dn', 'uid', 'samaccountname', 'memberof']);
174
+        $attributes = [
175
+            $this->access->getConnection()->ldapExpertUUIDUserAttr,
176
+            $this->access->getConnection()->ldapQuotaAttribute,
177
+            $this->access->getConnection()->ldapEmailAttribute,
178
+            $this->access->getConnection()->ldapUserDisplayName,
179
+            $this->access->getConnection()->ldapUserDisplayName2,
180
+            $this->access->getConnection()->ldapExtStorageHomeAttribute,
181
+        ];
182 182
 
183
-		$homeRule = $this->access->getConnection()->homeFolderNamingRule;
184
-		if(strpos($homeRule, 'attr:') === 0) {
185
-			$attributes[] = substr($homeRule, strlen('attr:'));
186
-		}
183
+        $homeRule = $this->access->getConnection()->homeFolderNamingRule;
184
+        if(strpos($homeRule, 'attr:') === 0) {
185
+            $attributes[] = substr($homeRule, strlen('attr:'));
186
+        }
187 187
 
188
-		if(!$minimal) {
189
-			// attributes that are not really important but may come with big
190
-			// payload.
191
-			$attributes = array_merge(
192
-				$attributes,
193
-				$this->access->getConnection()->resolveRule('avatar')
194
-			);
195
-		}
188
+        if(!$minimal) {
189
+            // attributes that are not really important but may come with big
190
+            // payload.
191
+            $attributes = array_merge(
192
+                $attributes,
193
+                $this->access->getConnection()->resolveRule('avatar')
194
+            );
195
+        }
196 196
 
197
-		$attributes = array_reduce($attributes,
198
-			function ($list, $attribute) {
199
-				$attribute = strtolower(trim((string)$attribute));
200
-				if(!empty($attribute) && !in_array($attribute, $list)) {
201
-					$list[] = $attribute;
202
-				}
197
+        $attributes = array_reduce($attributes,
198
+            function ($list, $attribute) {
199
+                $attribute = strtolower(trim((string)$attribute));
200
+                if(!empty($attribute) && !in_array($attribute, $list)) {
201
+                    $list[] = $attribute;
202
+                }
203 203
 
204
-				return $list;
205
-			},
206
-			$baseAttributes // hard-coded, lower-case, non-empty attributes
207
-		);
204
+                return $list;
205
+            },
206
+            $baseAttributes // hard-coded, lower-case, non-empty attributes
207
+        );
208 208
 
209
-		return $attributes;
210
-	}
209
+        return $attributes;
210
+    }
211 211
 
212
-	/**
213
-	 * Checks whether the specified user is marked as deleted
214
-	 * @param string $id the Nextcloud user name
215
-	 * @return bool
216
-	 */
217
-	public function isDeletedUser($id) {
218
-		$isDeleted = $this->ocConfig->getUserValue(
219
-			$id, 'user_ldap', 'isDeleted', 0);
220
-		return (int)$isDeleted === 1;
221
-	}
212
+    /**
213
+     * Checks whether the specified user is marked as deleted
214
+     * @param string $id the Nextcloud user name
215
+     * @return bool
216
+     */
217
+    public function isDeletedUser($id) {
218
+        $isDeleted = $this->ocConfig->getUserValue(
219
+            $id, 'user_ldap', 'isDeleted', 0);
220
+        return (int)$isDeleted === 1;
221
+    }
222 222
 
223
-	/**
224
-	 * creates and returns an instance of OfflineUser for the specified user
225
-	 * @param string $id
226
-	 * @return \OCA\User_LDAP\User\OfflineUser
227
-	 */
228
-	public function getDeletedUser($id) {
229
-		return new OfflineUser(
230
-			$id,
231
-			$this->ocConfig,
232
-			$this->db,
233
-			$this->access->getUserMapper());
234
-	}
223
+    /**
224
+     * creates and returns an instance of OfflineUser for the specified user
225
+     * @param string $id
226
+     * @return \OCA\User_LDAP\User\OfflineUser
227
+     */
228
+    public function getDeletedUser($id) {
229
+        return new OfflineUser(
230
+            $id,
231
+            $this->ocConfig,
232
+            $this->db,
233
+            $this->access->getUserMapper());
234
+    }
235 235
 
236
-	/**
237
-	 * @brief returns a User object by it's Nextcloud username
238
-	 * @param string $id the DN or username of the user
239
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
240
-	 */
241
-	protected function createInstancyByUserName($id) {
242
-		//most likely a uid. Check whether it is a deleted user
243
-		if($this->isDeletedUser($id)) {
244
-			return $this->getDeletedUser($id);
245
-		}
246
-		$dn = $this->access->username2dn($id);
247
-		if($dn !== false) {
248
-			return $this->createAndCache($dn, $id);
249
-		}
250
-		return null;
251
-	}
236
+    /**
237
+     * @brief returns a User object by it's Nextcloud username
238
+     * @param string $id the DN or username of the user
239
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
240
+     */
241
+    protected function createInstancyByUserName($id) {
242
+        //most likely a uid. Check whether it is a deleted user
243
+        if($this->isDeletedUser($id)) {
244
+            return $this->getDeletedUser($id);
245
+        }
246
+        $dn = $this->access->username2dn($id);
247
+        if($dn !== false) {
248
+            return $this->createAndCache($dn, $id);
249
+        }
250
+        return null;
251
+    }
252 252
 
253
-	/**
254
-	 * @brief returns a User object by it's DN or Nextcloud username
255
-	 * @param string $id the DN or username of the user
256
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
257
-	 * @throws \Exception when connection could not be established
258
-	 */
259
-	public function get($id) {
260
-		$this->checkAccess();
261
-		if(isset($this->usersByDN[$id])) {
262
-			return $this->usersByDN[$id];
263
-		} else if(isset($this->usersByUid[$id])) {
264
-			return $this->usersByUid[$id];
265
-		}
253
+    /**
254
+     * @brief returns a User object by it's DN or Nextcloud username
255
+     * @param string $id the DN or username of the user
256
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
257
+     * @throws \Exception when connection could not be established
258
+     */
259
+    public function get($id) {
260
+        $this->checkAccess();
261
+        if(isset($this->usersByDN[$id])) {
262
+            return $this->usersByDN[$id];
263
+        } else if(isset($this->usersByUid[$id])) {
264
+            return $this->usersByUid[$id];
265
+        }
266 266
 
267
-		if($this->access->stringResemblesDN($id) ) {
268
-			$uid = $this->access->dn2username($id);
269
-			if($uid !== false) {
270
-				return $this->createAndCache($id, $uid);
271
-			}
272
-		}
267
+        if($this->access->stringResemblesDN($id) ) {
268
+            $uid = $this->access->dn2username($id);
269
+            if($uid !== false) {
270
+                return $this->createAndCache($id, $uid);
271
+            }
272
+        }
273 273
 
274
-		return $this->createInstancyByUserName($id);
275
-	}
274
+        return $this->createInstancyByUserName($id);
275
+    }
276 276
 
277 277
 }
Please login to merge, or discard this patch.
Spacing   +14 added lines, -14 removed lines patch added patch discarded remove patch
@@ -142,7 +142,7 @@  discard block
 block discarded – undo
142 142
 	 * @param $uid
143 143
 	 */
144 144
 	public function invalidate($uid) {
145
-		if(!isset($this->usersByUid[$uid])) {
145
+		if (!isset($this->usersByUid[$uid])) {
146 146
 			return;
147 147
 		}
148 148
 		$dn = $this->usersByUid[$uid]->getDN();
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 	 * @return null
157 157
 	 */
158 158
 	private function checkAccess() {
159
-		if(is_null($this->access)) {
159
+		if (is_null($this->access)) {
160 160
 			throw new \Exception('LDAP Access instance must be set first');
161 161
 		}
162 162
 	}
@@ -181,11 +181,11 @@  discard block
 block discarded – undo
181 181
 		];
182 182
 
183 183
 		$homeRule = $this->access->getConnection()->homeFolderNamingRule;
184
-		if(strpos($homeRule, 'attr:') === 0) {
184
+		if (strpos($homeRule, 'attr:') === 0) {
185 185
 			$attributes[] = substr($homeRule, strlen('attr:'));
186 186
 		}
187 187
 
188
-		if(!$minimal) {
188
+		if (!$minimal) {
189 189
 			// attributes that are not really important but may come with big
190 190
 			// payload.
191 191
 			$attributes = array_merge(
@@ -195,9 +195,9 @@  discard block
 block discarded – undo
195 195
 		}
196 196
 
197 197
 		$attributes = array_reduce($attributes,
198
-			function ($list, $attribute) {
199
-				$attribute = strtolower(trim((string)$attribute));
200
-				if(!empty($attribute) && !in_array($attribute, $list)) {
198
+			function($list, $attribute) {
199
+				$attribute = strtolower(trim((string) $attribute));
200
+				if (!empty($attribute) && !in_array($attribute, $list)) {
201 201
 					$list[] = $attribute;
202 202
 				}
203 203
 
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 	public function isDeletedUser($id) {
218 218
 		$isDeleted = $this->ocConfig->getUserValue(
219 219
 			$id, 'user_ldap', 'isDeleted', 0);
220
-		return (int)$isDeleted === 1;
220
+		return (int) $isDeleted === 1;
221 221
 	}
222 222
 
223 223
 	/**
@@ -240,11 +240,11 @@  discard block
 block discarded – undo
240 240
 	 */
241 241
 	protected function createInstancyByUserName($id) {
242 242
 		//most likely a uid. Check whether it is a deleted user
243
-		if($this->isDeletedUser($id)) {
243
+		if ($this->isDeletedUser($id)) {
244 244
 			return $this->getDeletedUser($id);
245 245
 		}
246 246
 		$dn = $this->access->username2dn($id);
247
-		if($dn !== false) {
247
+		if ($dn !== false) {
248 248
 			return $this->createAndCache($dn, $id);
249 249
 		}
250 250
 		return null;
@@ -258,15 +258,15 @@  discard block
 block discarded – undo
258 258
 	 */
259 259
 	public function get($id) {
260 260
 		$this->checkAccess();
261
-		if(isset($this->usersByDN[$id])) {
261
+		if (isset($this->usersByDN[$id])) {
262 262
 			return $this->usersByDN[$id];
263
-		} else if(isset($this->usersByUid[$id])) {
263
+		} else if (isset($this->usersByUid[$id])) {
264 264
 			return $this->usersByUid[$id];
265 265
 		}
266 266
 
267
-		if($this->access->stringResemblesDN($id) ) {
267
+		if ($this->access->stringResemblesDN($id)) {
268 268
 			$uid = $this->access->dn2username($id);
269
-			if($uid !== false) {
269
+			if ($uid !== false) {
270 270
 				return $this->createAndCache($id, $uid);
271 271
 			}
272 272
 		}
Please login to merge, or discard this patch.
apps/user_ldap/lib/AppInfo/Application.php 2 patches
Indentation   +35 added lines, -35 removed lines patch added patch discarded remove patch
@@ -35,44 +35,44 @@
 block discarded – undo
35 35
 use OCP\IL10N;
36 36
 
37 37
 class Application extends App {
38
-	public function __construct() {
39
-		parent::__construct('user_ldap');
40
-		$container = $this->getContainer();
38
+    public function __construct() {
39
+        parent::__construct('user_ldap');
40
+        $container = $this->getContainer();
41 41
 
42
-		/**
43
-		 * Controller
44
-		 */
45
-		$container->registerService('RenewPasswordController', function (IAppContainer $c) {
46
-			/** @var \OC\Server $server */
47
-			$server = $c->query('ServerContainer');
42
+        /**
43
+         * Controller
44
+         */
45
+        $container->registerService('RenewPasswordController', function (IAppContainer $c) {
46
+            /** @var \OC\Server $server */
47
+            $server = $c->query('ServerContainer');
48 48
 
49
-			return new RenewPasswordController(
50
-				$c->getAppName(),
51
-				$server->getRequest(),
52
-				$c->query('UserManager'),
53
-				$server->getConfig(),
54
-				$c->query(IL10N::class),
55
-				$c->query('Session'),
56
-				$server->getURLGenerator()
57
-			);
58
-		});
49
+            return new RenewPasswordController(
50
+                $c->getAppName(),
51
+                $server->getRequest(),
52
+                $c->query('UserManager'),
53
+                $server->getConfig(),
54
+                $c->query(IL10N::class),
55
+                $c->query('Session'),
56
+                $server->getURLGenerator()
57
+            );
58
+        });
59 59
 
60
-		$container->registerService(ILDAPWrapper::class, function () {
61
-			return new LDAP();
62
-		});
63
-	}
60
+        $container->registerService(ILDAPWrapper::class, function () {
61
+            return new LDAP();
62
+        });
63
+    }
64 64
 
65
-	public function registerBackendDependents() {
66
-		$container = $this->getContainer();
65
+    public function registerBackendDependents() {
66
+        $container = $this->getContainer();
67 67
 
68
-		$container->getServer()->getEventDispatcher()->addListener(
69
-			'OCA\\Files_External::loadAdditionalBackends',
70
-			function () use ($container) {
71
-				$storagesBackendService = $container->query(BackendService::class);
72
-				$storagesBackendService->registerConfigHandler('home', function () use ($container) {
73
-					return $container->query(ExtStorageConfigHandler::class);
74
-				});
75
-			}
76
-		);
77
-	}
68
+        $container->getServer()->getEventDispatcher()->addListener(
69
+            'OCA\\Files_External::loadAdditionalBackends',
70
+            function () use ($container) {
71
+                $storagesBackendService = $container->query(BackendService::class);
72
+                $storagesBackendService->registerConfigHandler('home', function () use ($container) {
73
+                    return $container->query(ExtStorageConfigHandler::class);
74
+                });
75
+            }
76
+        );
77
+    }
78 78
 }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -42,7 +42,7 @@  discard block
 block discarded – undo
42 42
 		/**
43 43
 		 * Controller
44 44
 		 */
45
-		$container->registerService('RenewPasswordController', function (IAppContainer $c) {
45
+		$container->registerService('RenewPasswordController', function(IAppContainer $c) {
46 46
 			/** @var \OC\Server $server */
47 47
 			$server = $c->query('ServerContainer');
48 48
 
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
 			);
58 58
 		});
59 59
 
60
-		$container->registerService(ILDAPWrapper::class, function () {
60
+		$container->registerService(ILDAPWrapper::class, function() {
61 61
 			return new LDAP();
62 62
 		});
63 63
 	}
@@ -67,9 +67,9 @@  discard block
 block discarded – undo
67 67
 
68 68
 		$container->getServer()->getEventDispatcher()->addListener(
69 69
 			'OCA\\Files_External::loadAdditionalBackends',
70
-			function () use ($container) {
70
+			function() use ($container) {
71 71
 				$storagesBackendService = $container->query(BackendService::class);
72
-				$storagesBackendService->registerConfigHandler('home', function () use ($container) {
72
+				$storagesBackendService->registerConfigHandler('home', function() use ($container) {
73 73
 					return $container->query(ExtStorageConfigHandler::class);
74 74
 				});
75 75
 			}
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 2 patches
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -46,183 +46,183 @@
 block discarded – undo
46 46
 use OCP\ILogger;
47 47
 
48 48
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
49
-	static private $groupsFromDB;
50
-
51
-	static private $groupBE;
52
-
53
-	public function __construct() {
54
-		$this->interval = self::getRefreshInterval();
55
-	}
56
-
57
-	/**
58
-	 * @param mixed $argument
59
-	 */
60
-	public function run($argument) {
61
-		self::updateGroups();
62
-	}
63
-
64
-	static public function updateGroups() {
65
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
66
-
67
-		$knownGroups = array_keys(self::getKnownGroups());
68
-		$actualGroups = self::getGroupBE()->getGroups();
69
-
70
-		if(empty($actualGroups) && empty($knownGroups)) {
71
-			\OCP\Util::writeLog('user_ldap',
72
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
73
-				ILogger::INFO);
74
-			return;
75
-		}
76
-
77
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
78
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
79
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
80
-
81
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
82
-	}
83
-
84
-	/**
85
-	 * @return int
86
-	 */
87
-	static private function getRefreshInterval() {
88
-		//defaults to every hour
89
-		return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
90
-	}
91
-
92
-	/**
93
-	 * @param string[] $groups
94
-	 */
95
-	static private function handleKnownGroups($groups) {
96
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
97
-		$query = \OC_DB::prepare('
49
+    static private $groupsFromDB;
50
+
51
+    static private $groupBE;
52
+
53
+    public function __construct() {
54
+        $this->interval = self::getRefreshInterval();
55
+    }
56
+
57
+    /**
58
+     * @param mixed $argument
59
+     */
60
+    public function run($argument) {
61
+        self::updateGroups();
62
+    }
63
+
64
+    static public function updateGroups() {
65
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
66
+
67
+        $knownGroups = array_keys(self::getKnownGroups());
68
+        $actualGroups = self::getGroupBE()->getGroups();
69
+
70
+        if(empty($actualGroups) && empty($knownGroups)) {
71
+            \OCP\Util::writeLog('user_ldap',
72
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
73
+                ILogger::INFO);
74
+            return;
75
+        }
76
+
77
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
78
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
79
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
80
+
81
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
82
+    }
83
+
84
+    /**
85
+     * @return int
86
+     */
87
+    static private function getRefreshInterval() {
88
+        //defaults to every hour
89
+        return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
90
+    }
91
+
92
+    /**
93
+     * @param string[] $groups
94
+     */
95
+    static private function handleKnownGroups($groups) {
96
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
97
+        $query = \OC_DB::prepare('
98 98
 			UPDATE `*PREFIX*ldap_group_members`
99 99
 			SET `owncloudusers` = ?
100 100
 			WHERE `owncloudname` = ?
101 101
 		');
102
-		foreach($groups as $group) {
103
-			//we assume, that self::$groupsFromDB has been retrieved already
104
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
105
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
106
-			$hasChanged = false;
107
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
108
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
109
-				\OCP\Util::writeLog('user_ldap',
110
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
111
-					ILogger::INFO);
112
-				$hasChanged = true;
113
-			}
114
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
115
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
116
-				\OCP\Util::writeLog('user_ldap',
117
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
118
-					ILogger::INFO);
119
-				$hasChanged = true;
120
-			}
121
-			if($hasChanged) {
122
-				$query->execute([serialize($actualUsers), $group]);
123
-			}
124
-		}
125
-		\OCP\Util::writeLog('user_ldap',
126
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
127
-			ILogger::DEBUG);
128
-	}
129
-
130
-	/**
131
-	 * @param string[] $createdGroups
132
-	 */
133
-	static private function handleCreatedGroups($createdGroups) {
134
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
135
-		$query = \OC_DB::prepare('
102
+        foreach($groups as $group) {
103
+            //we assume, that self::$groupsFromDB has been retrieved already
104
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
105
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
106
+            $hasChanged = false;
107
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
108
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
109
+                \OCP\Util::writeLog('user_ldap',
110
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
111
+                    ILogger::INFO);
112
+                $hasChanged = true;
113
+            }
114
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
115
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
116
+                \OCP\Util::writeLog('user_ldap',
117
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
118
+                    ILogger::INFO);
119
+                $hasChanged = true;
120
+            }
121
+            if($hasChanged) {
122
+                $query->execute([serialize($actualUsers), $group]);
123
+            }
124
+        }
125
+        \OCP\Util::writeLog('user_ldap',
126
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
127
+            ILogger::DEBUG);
128
+    }
129
+
130
+    /**
131
+     * @param string[] $createdGroups
132
+     */
133
+    static private function handleCreatedGroups($createdGroups) {
134
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
135
+        $query = \OC_DB::prepare('
136 136
 			INSERT
137 137
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
138 138
 			VALUES (?, ?)
139 139
 		');
140
-		foreach($createdGroups as $createdGroup) {
141
-			\OCP\Util::writeLog('user_ldap',
142
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
143
-				ILogger::INFO);
144
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
145
-			$query->execute([$createdGroup, $users]);
146
-		}
147
-		\OCP\Util::writeLog('user_ldap',
148
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
149
-			ILogger::DEBUG);
150
-	}
151
-
152
-	/**
153
-	 * @param string[] $removedGroups
154
-	 */
155
-	static private function handleRemovedGroups($removedGroups) {
156
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
157
-		$query = \OC_DB::prepare('
140
+        foreach($createdGroups as $createdGroup) {
141
+            \OCP\Util::writeLog('user_ldap',
142
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
143
+                ILogger::INFO);
144
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
145
+            $query->execute([$createdGroup, $users]);
146
+        }
147
+        \OCP\Util::writeLog('user_ldap',
148
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
149
+            ILogger::DEBUG);
150
+    }
151
+
152
+    /**
153
+     * @param string[] $removedGroups
154
+     */
155
+    static private function handleRemovedGroups($removedGroups) {
156
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
157
+        $query = \OC_DB::prepare('
158 158
 			DELETE
159 159
 			FROM `*PREFIX*ldap_group_members`
160 160
 			WHERE `owncloudname` = ?
161 161
 		');
162
-		foreach($removedGroups as $removedGroup) {
163
-			\OCP\Util::writeLog('user_ldap',
164
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
165
-				ILogger::INFO);
166
-			$query->execute([$removedGroup]);
167
-		}
168
-		\OCP\Util::writeLog('user_ldap',
169
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
170
-			ILogger::DEBUG);
171
-	}
172
-
173
-	/**
174
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
175
-	 */
176
-	static private function getGroupBE() {
177
-		if(!is_null(self::$groupBE)) {
178
-			return self::$groupBE;
179
-		}
180
-		$helper = new Helper(\OC::$server->getConfig());
181
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
182
-		$ldapWrapper = new LDAP();
183
-		if(count($configPrefixes) === 1) {
184
-			//avoid the proxy when there is only one LDAP server configured
185
-			$dbc = \OC::$server->getDatabaseConnection();
186
-			$userManager = new Manager(
187
-				\OC::$server->getConfig(),
188
-				new FilesystemHelper(),
189
-				new LogWrapper(),
190
-				\OC::$server->getAvatarManager(),
191
-				new \OCP\Image(),
192
-				$dbc,
193
-				\OC::$server->getUserManager(),
194
-				\OC::$server->getNotificationManager());
195
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
196
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
197
-			$groupMapper = new GroupMapping($dbc);
198
-			$userMapper  = new UserMapping($dbc);
199
-			$ldapAccess->setGroupMapper($groupMapper);
200
-			$ldapAccess->setUserMapper($userMapper);
201
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
202
-		} else {
203
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
204
-		}
205
-
206
-		return self::$groupBE;
207
-	}
208
-
209
-	/**
210
-	 * @return array
211
-	 */
212
-	static private function getKnownGroups() {
213
-		if(is_array(self::$groupsFromDB)) {
214
-			return self::$groupsFromDB;
215
-		}
216
-		$query = \OC_DB::prepare('
162
+        foreach($removedGroups as $removedGroup) {
163
+            \OCP\Util::writeLog('user_ldap',
164
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
165
+                ILogger::INFO);
166
+            $query->execute([$removedGroup]);
167
+        }
168
+        \OCP\Util::writeLog('user_ldap',
169
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
170
+            ILogger::DEBUG);
171
+    }
172
+
173
+    /**
174
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
175
+     */
176
+    static private function getGroupBE() {
177
+        if(!is_null(self::$groupBE)) {
178
+            return self::$groupBE;
179
+        }
180
+        $helper = new Helper(\OC::$server->getConfig());
181
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
182
+        $ldapWrapper = new LDAP();
183
+        if(count($configPrefixes) === 1) {
184
+            //avoid the proxy when there is only one LDAP server configured
185
+            $dbc = \OC::$server->getDatabaseConnection();
186
+            $userManager = new Manager(
187
+                \OC::$server->getConfig(),
188
+                new FilesystemHelper(),
189
+                new LogWrapper(),
190
+                \OC::$server->getAvatarManager(),
191
+                new \OCP\Image(),
192
+                $dbc,
193
+                \OC::$server->getUserManager(),
194
+                \OC::$server->getNotificationManager());
195
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
196
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
197
+            $groupMapper = new GroupMapping($dbc);
198
+            $userMapper  = new UserMapping($dbc);
199
+            $ldapAccess->setGroupMapper($groupMapper);
200
+            $ldapAccess->setUserMapper($userMapper);
201
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
202
+        } else {
203
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
204
+        }
205
+
206
+        return self::$groupBE;
207
+    }
208
+
209
+    /**
210
+     * @return array
211
+     */
212
+    static private function getKnownGroups() {
213
+        if(is_array(self::$groupsFromDB)) {
214
+            return self::$groupsFromDB;
215
+        }
216
+        $query = \OC_DB::prepare('
217 217
 			SELECT `owncloudname`, `owncloudusers`
218 218
 			FROM `*PREFIX*ldap_group_members`
219 219
 		');
220
-		$result = $query->execute()->fetchAll();
221
-		self::$groupsFromDB = [];
222
-		foreach($result as $dataset) {
223
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
224
-		}
225
-
226
-		return self::$groupsFromDB;
227
-	}
220
+        $result = $query->execute()->fetchAll();
221
+        self::$groupsFromDB = [];
222
+        foreach($result as $dataset) {
223
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
224
+        }
225
+
226
+        return self::$groupsFromDB;
227
+    }
228 228
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -67,7 +67,7 @@  discard block
 block discarded – undo
67 67
 		$knownGroups = array_keys(self::getKnownGroups());
68 68
 		$actualGroups = self::getGroupBE()->getGroups();
69 69
 
70
-		if(empty($actualGroups) && empty($knownGroups)) {
70
+		if (empty($actualGroups) && empty($knownGroups)) {
71 71
 			\OCP\Util::writeLog('user_ldap',
72 72
 				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
73 73
 				ILogger::INFO);
@@ -99,26 +99,26 @@  discard block
 block discarded – undo
99 99
 			SET `owncloudusers` = ?
100 100
 			WHERE `owncloudname` = ?
101 101
 		');
102
-		foreach($groups as $group) {
102
+		foreach ($groups as $group) {
103 103
 			//we assume, that self::$groupsFromDB has been retrieved already
104 104
 			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
105 105
 			$actualUsers = self::getGroupBE()->usersInGroup($group);
106 106
 			$hasChanged = false;
107
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
+			foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
108 108
 				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
109 109
 				\OCP\Util::writeLog('user_ldap',
110 110
 				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
111 111
 					ILogger::INFO);
112 112
 				$hasChanged = true;
113 113
 			}
114
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
+			foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
115 115
 				\OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
116 116
 				\OCP\Util::writeLog('user_ldap',
117 117
 				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
118 118
 					ILogger::INFO);
119 119
 				$hasChanged = true;
120 120
 			}
121
-			if($hasChanged) {
121
+			if ($hasChanged) {
122 122
 				$query->execute([serialize($actualUsers), $group]);
123 123
 			}
124 124
 		}
@@ -137,7 +137,7 @@  discard block
 block discarded – undo
137 137
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
138 138
 			VALUES (?, ?)
139 139
 		');
140
-		foreach($createdGroups as $createdGroup) {
140
+		foreach ($createdGroups as $createdGroup) {
141 141
 			\OCP\Util::writeLog('user_ldap',
142 142
 				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
143 143
 				ILogger::INFO);
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 			FROM `*PREFIX*ldap_group_members`
160 160
 			WHERE `owncloudname` = ?
161 161
 		');
162
-		foreach($removedGroups as $removedGroup) {
162
+		foreach ($removedGroups as $removedGroup) {
163 163
 			\OCP\Util::writeLog('user_ldap',
164 164
 				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
165 165
 				ILogger::INFO);
@@ -174,13 +174,13 @@  discard block
 block discarded – undo
174 174
 	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
175 175
 	 */
176 176
 	static private function getGroupBE() {
177
-		if(!is_null(self::$groupBE)) {
177
+		if (!is_null(self::$groupBE)) {
178 178
 			return self::$groupBE;
179 179
 		}
180 180
 		$helper = new Helper(\OC::$server->getConfig());
181 181
 		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
182 182
 		$ldapWrapper = new LDAP();
183
-		if(count($configPrefixes) === 1) {
183
+		if (count($configPrefixes) === 1) {
184 184
 			//avoid the proxy when there is only one LDAP server configured
185 185
 			$dbc = \OC::$server->getDatabaseConnection();
186 186
 			$userManager = new Manager(
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 	 * @return array
211 211
 	 */
212 212
 	static private function getKnownGroups() {
213
-		if(is_array(self::$groupsFromDB)) {
213
+		if (is_array(self::$groupsFromDB)) {
214 214
 			return self::$groupsFromDB;
215 215
 		}
216 216
 		$query = \OC_DB::prepare('
@@ -219,7 +219,7 @@  discard block
 block discarded – undo
219 219
 		');
220 220
 		$result = $query->execute()->fetchAll();
221 221
 		self::$groupsFromDB = [];
222
-		foreach($result as $dataset) {
222
+		foreach ($result as $dataset) {
223 223
 			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
224 224
 		}
225 225
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/Sync.php 2 patches
Indentation   +338 added lines, -338 removed lines patch added patch discarded remove patch
@@ -43,343 +43,343 @@
 block discarded – undo
43 43
 use OCP\Notification\IManager;
44 44
 
45 45
 class Sync extends TimedJob {
46
-	const MAX_INTERVAL = 12 * 60 * 60; // 12h
47
-	const MIN_INTERVAL = 30 * 60; // 30min
48
-	/** @var  Helper */
49
-	protected $ldapHelper;
50
-	/** @var  LDAP */
51
-	protected $ldap;
52
-	/** @var  Manager */
53
-	protected $userManager;
54
-	/** @var UserMapping */
55
-	protected $mapper;
56
-	/** @var  IConfig */
57
-	protected $config;
58
-	/** @var  IAvatarManager */
59
-	protected $avatarManager;
60
-	/** @var  IDBConnection */
61
-	protected $dbc;
62
-	/** @var  IUserManager */
63
-	protected $ncUserManager;
64
-	/** @var  IManager */
65
-	protected $notificationManager;
66
-	/** @var ConnectionFactory */
67
-	protected $connectionFactory;
68
-	/** @var AccessFactory */
69
-	protected $accessFactory;
70
-
71
-	public function __construct() {
72
-		$this->setInterval(
73
-			\OC::$server->getConfig()->getAppValue(
74
-				'user_ldap',
75
-				'background_sync_interval',
76
-				self::MIN_INTERVAL
77
-			)
78
-		);
79
-	}
80
-
81
-	/**
82
-	 * updates the interval
83
-	 *
84
-	 * the idea is to adjust the interval depending on the amount of known users
85
-	 * and the attempt to update each user one day. At most it would run every
86
-	 * 30 minutes, and at least every 12 hours.
87
-	 */
88
-	public function updateInterval() {
89
-		$minPagingSize = $this->getMinPagingSize();
90
-		$mappedUsers = $this->mapper->count();
91
-
92
-		$runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
93
-			: $mappedUsers / $minPagingSize;
94
-		$interval = floor(24 * 60 * 60 / $runsPerDay);
95
-		$interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
96
-
97
-		$this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
98
-	}
99
-
100
-	/**
101
-	 * returns the smallest configured paging size
102
-	 * @return int
103
-	 */
104
-	protected function getMinPagingSize() {
105
-		$configKeys = $this->config->getAppKeys('user_ldap');
106
-		$configKeys = array_filter($configKeys, function ($key) {
107
-			return strpos($key, 'ldap_paging_size') !== false;
108
-		});
109
-		$minPagingSize = null;
110
-		foreach ($configKeys as $configKey) {
111
-			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
112
-			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
113
-		}
114
-		return (int)$minPagingSize;
115
-	}
116
-
117
-	/**
118
-	 * @param array $argument
119
-	 */
120
-	public function run($argument) {
121
-		$this->setArgument($argument);
122
-
123
-		$isBackgroundJobModeAjax = $this->config
124
-				->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
125
-		if($isBackgroundJobModeAjax) {
126
-			return;
127
-		}
128
-
129
-		$cycleData = $this->getCycle();
130
-		if($cycleData === null) {
131
-			$cycleData = $this->determineNextCycle();
132
-			if($cycleData === null) {
133
-				$this->updateInterval();
134
-				return;
135
-			}
136
-		}
137
-
138
-		if(!$this->qualifiesToRun($cycleData)) {
139
-			$this->updateInterval();
140
-			return;
141
-		}
142
-
143
-		try {
144
-			$expectMoreResults = $this->runCycle($cycleData);
145
-			if ($expectMoreResults) {
146
-				$this->increaseOffset($cycleData);
147
-			} else {
148
-				$this->determineNextCycle($cycleData);
149
-			}
150
-			$this->updateInterval();
151
-		} catch (ServerNotAvailableException $e) {
152
-			$this->determineNextCycle($cycleData);
153
-		}
154
-	}
155
-
156
-	/**
157
-	 * @param array $cycleData
158
-	 * @return bool whether more results are expected from the same configuration
159
-	 */
160
-	public function runCycle($cycleData) {
161
-		$connection = $this->connectionFactory->get($cycleData['prefix']);
162
-		$access = $this->accessFactory->get($connection);
163
-		$access->setUserMapper($this->mapper);
164
-
165
-		$filter = $access->combineFilterWithAnd([
166
-			$access->connection->ldapUserFilter,
167
-			$access->connection->ldapUserDisplayName . '=*',
168
-			$access->getFilterPartForUserSearch('')
169
-		]);
170
-		$results = $access->fetchListOfUsers(
171
-			$filter,
172
-			$access->userManager->getAttributes(),
173
-			$connection->ldapPagingSize,
174
-			$cycleData['offset'],
175
-			true
176
-		);
177
-
178
-		if((int)$connection->ldapPagingSize === 0) {
179
-			return false;
180
-		}
181
-		return count($results) >= (int)$connection->ldapPagingSize;
182
-	}
183
-
184
-	/**
185
-	 * returns the info about the current cycle that should be run, if any,
186
-	 * otherwise null
187
-	 *
188
-	 * @return array|null
189
-	 */
190
-	public function getCycle() {
191
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
192
-		if(count($prefixes) === 0) {
193
-			return null;
194
-		}
195
-
196
-		$cycleData = [
197
-			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
198
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
199
-		];
200
-
201
-		if(
202
-			$cycleData['prefix'] !== null
203
-			&& in_array($cycleData['prefix'], $prefixes)
204
-		) {
205
-			return $cycleData;
206
-		}
207
-
208
-		return null;
209
-	}
210
-
211
-	/**
212
-	 * Save the provided cycle information in the DB
213
-	 *
214
-	 * @param array $cycleData
215
-	 */
216
-	public function setCycle(array $cycleData) {
217
-		$this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
218
-		$this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
219
-	}
220
-
221
-	/**
222
-	 * returns data about the next cycle that should run, if any, otherwise
223
-	 * null. It also always goes for the next LDAP configuration!
224
-	 *
225
-	 * @param array|null $cycleData the old cycle
226
-	 * @return array|null
227
-	 */
228
-	public function determineNextCycle(array $cycleData = null) {
229
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
230
-		if(count($prefixes) === 0) {
231
-			return null;
232
-		}
233
-
234
-		// get the next prefix in line and remember it
235
-		$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
236
-		$prefix = $this->getNextPrefix($oldPrefix);
237
-		if($prefix === null) {
238
-			return null;
239
-		}
240
-		$cycleData['prefix'] = $prefix;
241
-		$cycleData['offset'] = 0;
242
-		$this->setCycle(['prefix' => $prefix, 'offset' => 0]);
243
-
244
-		return $cycleData;
245
-	}
246
-
247
-	/**
248
-	 * Checks whether the provided cycle should be run. Currently only the
249
-	 * last configuration change goes into account (at least one hour).
250
-	 *
251
-	 * @param $cycleData
252
-	 * @return bool
253
-	 */
254
-	public function qualifiesToRun($cycleData) {
255
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
256
-		if((time() - $lastChange) > 60 * 30) {
257
-			return true;
258
-		}
259
-		return false;
260
-	}
261
-
262
-	/**
263
-	 * increases the offset of the current cycle for the next run
264
-	 *
265
-	 * @param $cycleData
266
-	 */
267
-	protected function increaseOffset($cycleData) {
268
-		$ldapConfig = new Configuration($cycleData['prefix']);
269
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
270
-		$this->setCycle($cycleData);
271
-	}
272
-
273
-	/**
274
-	 * determines the next configuration prefix based on the last one (if any)
275
-	 *
276
-	 * @param string|null $lastPrefix
277
-	 * @return string|null
278
-	 */
279
-	protected function getNextPrefix($lastPrefix) {
280
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
281
-		$noOfPrefixes = count($prefixes);
282
-		if($noOfPrefixes === 0) {
283
-			return null;
284
-		}
285
-		$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
286
-		if($i === false) {
287
-			$i = -1;
288
-		} else {
289
-			$i++;
290
-		}
291
-
292
-		if(!isset($prefixes[$i])) {
293
-			$i = 0;
294
-		}
295
-		return $prefixes[$i];
296
-	}
297
-
298
-	/**
299
-	 * "fixes" DI
300
-	 *
301
-	 * @param array $argument
302
-	 */
303
-	public function setArgument($argument) {
304
-		if(isset($argument['config'])) {
305
-			$this->config = $argument['config'];
306
-		} else {
307
-			$this->config = \OC::$server->getConfig();
308
-		}
309
-
310
-		if(isset($argument['helper'])) {
311
-			$this->ldapHelper = $argument['helper'];
312
-		} else {
313
-			$this->ldapHelper = new Helper($this->config);
314
-		}
315
-
316
-		if(isset($argument['ldapWrapper'])) {
317
-			$this->ldap = $argument['ldapWrapper'];
318
-		} else {
319
-			$this->ldap = new LDAP();
320
-		}
321
-
322
-		if(isset($argument['avatarManager'])) {
323
-			$this->avatarManager = $argument['avatarManager'];
324
-		} else {
325
-			$this->avatarManager = \OC::$server->getAvatarManager();
326
-		}
327
-
328
-		if(isset($argument['dbc'])) {
329
-			$this->dbc = $argument['dbc'];
330
-		} else {
331
-			$this->dbc = \OC::$server->getDatabaseConnection();
332
-		}
333
-
334
-		if(isset($argument['ncUserManager'])) {
335
-			$this->ncUserManager = $argument['ncUserManager'];
336
-		} else {
337
-			$this->ncUserManager = \OC::$server->getUserManager();
338
-		}
339
-
340
-		if(isset($argument['notificationManager'])) {
341
-			$this->notificationManager = $argument['notificationManager'];
342
-		} else {
343
-			$this->notificationManager = \OC::$server->getNotificationManager();
344
-		}
345
-
346
-		if(isset($argument['userManager'])) {
347
-			$this->userManager = $argument['userManager'];
348
-		} else {
349
-			$this->userManager = new Manager(
350
-				$this->config,
351
-				new FilesystemHelper(),
352
-				new LogWrapper(),
353
-				$this->avatarManager,
354
-				new Image(),
355
-				$this->dbc,
356
-				$this->ncUserManager,
357
-				$this->notificationManager
358
-			);
359
-		}
360
-
361
-		if(isset($argument['mapper'])) {
362
-			$this->mapper = $argument['mapper'];
363
-		} else {
364
-			$this->mapper = new UserMapping($this->dbc);
365
-		}
46
+    const MAX_INTERVAL = 12 * 60 * 60; // 12h
47
+    const MIN_INTERVAL = 30 * 60; // 30min
48
+    /** @var  Helper */
49
+    protected $ldapHelper;
50
+    /** @var  LDAP */
51
+    protected $ldap;
52
+    /** @var  Manager */
53
+    protected $userManager;
54
+    /** @var UserMapping */
55
+    protected $mapper;
56
+    /** @var  IConfig */
57
+    protected $config;
58
+    /** @var  IAvatarManager */
59
+    protected $avatarManager;
60
+    /** @var  IDBConnection */
61
+    protected $dbc;
62
+    /** @var  IUserManager */
63
+    protected $ncUserManager;
64
+    /** @var  IManager */
65
+    protected $notificationManager;
66
+    /** @var ConnectionFactory */
67
+    protected $connectionFactory;
68
+    /** @var AccessFactory */
69
+    protected $accessFactory;
70
+
71
+    public function __construct() {
72
+        $this->setInterval(
73
+            \OC::$server->getConfig()->getAppValue(
74
+                'user_ldap',
75
+                'background_sync_interval',
76
+                self::MIN_INTERVAL
77
+            )
78
+        );
79
+    }
80
+
81
+    /**
82
+     * updates the interval
83
+     *
84
+     * the idea is to adjust the interval depending on the amount of known users
85
+     * and the attempt to update each user one day. At most it would run every
86
+     * 30 minutes, and at least every 12 hours.
87
+     */
88
+    public function updateInterval() {
89
+        $minPagingSize = $this->getMinPagingSize();
90
+        $mappedUsers = $this->mapper->count();
91
+
92
+        $runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
93
+            : $mappedUsers / $minPagingSize;
94
+        $interval = floor(24 * 60 * 60 / $runsPerDay);
95
+        $interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
96
+
97
+        $this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
98
+    }
99
+
100
+    /**
101
+     * returns the smallest configured paging size
102
+     * @return int
103
+     */
104
+    protected function getMinPagingSize() {
105
+        $configKeys = $this->config->getAppKeys('user_ldap');
106
+        $configKeys = array_filter($configKeys, function ($key) {
107
+            return strpos($key, 'ldap_paging_size') !== false;
108
+        });
109
+        $minPagingSize = null;
110
+        foreach ($configKeys as $configKey) {
111
+            $pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
112
+            $minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
113
+        }
114
+        return (int)$minPagingSize;
115
+    }
116
+
117
+    /**
118
+     * @param array $argument
119
+     */
120
+    public function run($argument) {
121
+        $this->setArgument($argument);
122
+
123
+        $isBackgroundJobModeAjax = $this->config
124
+                ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
125
+        if($isBackgroundJobModeAjax) {
126
+            return;
127
+        }
128
+
129
+        $cycleData = $this->getCycle();
130
+        if($cycleData === null) {
131
+            $cycleData = $this->determineNextCycle();
132
+            if($cycleData === null) {
133
+                $this->updateInterval();
134
+                return;
135
+            }
136
+        }
137
+
138
+        if(!$this->qualifiesToRun($cycleData)) {
139
+            $this->updateInterval();
140
+            return;
141
+        }
142
+
143
+        try {
144
+            $expectMoreResults = $this->runCycle($cycleData);
145
+            if ($expectMoreResults) {
146
+                $this->increaseOffset($cycleData);
147
+            } else {
148
+                $this->determineNextCycle($cycleData);
149
+            }
150
+            $this->updateInterval();
151
+        } catch (ServerNotAvailableException $e) {
152
+            $this->determineNextCycle($cycleData);
153
+        }
154
+    }
155
+
156
+    /**
157
+     * @param array $cycleData
158
+     * @return bool whether more results are expected from the same configuration
159
+     */
160
+    public function runCycle($cycleData) {
161
+        $connection = $this->connectionFactory->get($cycleData['prefix']);
162
+        $access = $this->accessFactory->get($connection);
163
+        $access->setUserMapper($this->mapper);
164
+
165
+        $filter = $access->combineFilterWithAnd([
166
+            $access->connection->ldapUserFilter,
167
+            $access->connection->ldapUserDisplayName . '=*',
168
+            $access->getFilterPartForUserSearch('')
169
+        ]);
170
+        $results = $access->fetchListOfUsers(
171
+            $filter,
172
+            $access->userManager->getAttributes(),
173
+            $connection->ldapPagingSize,
174
+            $cycleData['offset'],
175
+            true
176
+        );
177
+
178
+        if((int)$connection->ldapPagingSize === 0) {
179
+            return false;
180
+        }
181
+        return count($results) >= (int)$connection->ldapPagingSize;
182
+    }
183
+
184
+    /**
185
+     * returns the info about the current cycle that should be run, if any,
186
+     * otherwise null
187
+     *
188
+     * @return array|null
189
+     */
190
+    public function getCycle() {
191
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
192
+        if(count($prefixes) === 0) {
193
+            return null;
194
+        }
195
+
196
+        $cycleData = [
197
+            'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
198
+            'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
199
+        ];
200
+
201
+        if(
202
+            $cycleData['prefix'] !== null
203
+            && in_array($cycleData['prefix'], $prefixes)
204
+        ) {
205
+            return $cycleData;
206
+        }
207
+
208
+        return null;
209
+    }
210
+
211
+    /**
212
+     * Save the provided cycle information in the DB
213
+     *
214
+     * @param array $cycleData
215
+     */
216
+    public function setCycle(array $cycleData) {
217
+        $this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
218
+        $this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
219
+    }
220
+
221
+    /**
222
+     * returns data about the next cycle that should run, if any, otherwise
223
+     * null. It also always goes for the next LDAP configuration!
224
+     *
225
+     * @param array|null $cycleData the old cycle
226
+     * @return array|null
227
+     */
228
+    public function determineNextCycle(array $cycleData = null) {
229
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
230
+        if(count($prefixes) === 0) {
231
+            return null;
232
+        }
233
+
234
+        // get the next prefix in line and remember it
235
+        $oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
236
+        $prefix = $this->getNextPrefix($oldPrefix);
237
+        if($prefix === null) {
238
+            return null;
239
+        }
240
+        $cycleData['prefix'] = $prefix;
241
+        $cycleData['offset'] = 0;
242
+        $this->setCycle(['prefix' => $prefix, 'offset' => 0]);
243
+
244
+        return $cycleData;
245
+    }
246
+
247
+    /**
248
+     * Checks whether the provided cycle should be run. Currently only the
249
+     * last configuration change goes into account (at least one hour).
250
+     *
251
+     * @param $cycleData
252
+     * @return bool
253
+     */
254
+    public function qualifiesToRun($cycleData) {
255
+        $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
256
+        if((time() - $lastChange) > 60 * 30) {
257
+            return true;
258
+        }
259
+        return false;
260
+    }
261
+
262
+    /**
263
+     * increases the offset of the current cycle for the next run
264
+     *
265
+     * @param $cycleData
266
+     */
267
+    protected function increaseOffset($cycleData) {
268
+        $ldapConfig = new Configuration($cycleData['prefix']);
269
+        $cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
270
+        $this->setCycle($cycleData);
271
+    }
272
+
273
+    /**
274
+     * determines the next configuration prefix based on the last one (if any)
275
+     *
276
+     * @param string|null $lastPrefix
277
+     * @return string|null
278
+     */
279
+    protected function getNextPrefix($lastPrefix) {
280
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
281
+        $noOfPrefixes = count($prefixes);
282
+        if($noOfPrefixes === 0) {
283
+            return null;
284
+        }
285
+        $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
286
+        if($i === false) {
287
+            $i = -1;
288
+        } else {
289
+            $i++;
290
+        }
291
+
292
+        if(!isset($prefixes[$i])) {
293
+            $i = 0;
294
+        }
295
+        return $prefixes[$i];
296
+    }
297
+
298
+    /**
299
+     * "fixes" DI
300
+     *
301
+     * @param array $argument
302
+     */
303
+    public function setArgument($argument) {
304
+        if(isset($argument['config'])) {
305
+            $this->config = $argument['config'];
306
+        } else {
307
+            $this->config = \OC::$server->getConfig();
308
+        }
309
+
310
+        if(isset($argument['helper'])) {
311
+            $this->ldapHelper = $argument['helper'];
312
+        } else {
313
+            $this->ldapHelper = new Helper($this->config);
314
+        }
315
+
316
+        if(isset($argument['ldapWrapper'])) {
317
+            $this->ldap = $argument['ldapWrapper'];
318
+        } else {
319
+            $this->ldap = new LDAP();
320
+        }
321
+
322
+        if(isset($argument['avatarManager'])) {
323
+            $this->avatarManager = $argument['avatarManager'];
324
+        } else {
325
+            $this->avatarManager = \OC::$server->getAvatarManager();
326
+        }
327
+
328
+        if(isset($argument['dbc'])) {
329
+            $this->dbc = $argument['dbc'];
330
+        } else {
331
+            $this->dbc = \OC::$server->getDatabaseConnection();
332
+        }
333
+
334
+        if(isset($argument['ncUserManager'])) {
335
+            $this->ncUserManager = $argument['ncUserManager'];
336
+        } else {
337
+            $this->ncUserManager = \OC::$server->getUserManager();
338
+        }
339
+
340
+        if(isset($argument['notificationManager'])) {
341
+            $this->notificationManager = $argument['notificationManager'];
342
+        } else {
343
+            $this->notificationManager = \OC::$server->getNotificationManager();
344
+        }
345
+
346
+        if(isset($argument['userManager'])) {
347
+            $this->userManager = $argument['userManager'];
348
+        } else {
349
+            $this->userManager = new Manager(
350
+                $this->config,
351
+                new FilesystemHelper(),
352
+                new LogWrapper(),
353
+                $this->avatarManager,
354
+                new Image(),
355
+                $this->dbc,
356
+                $this->ncUserManager,
357
+                $this->notificationManager
358
+            );
359
+        }
360
+
361
+        if(isset($argument['mapper'])) {
362
+            $this->mapper = $argument['mapper'];
363
+        } else {
364
+            $this->mapper = new UserMapping($this->dbc);
365
+        }
366 366
 		
367
-		if(isset($argument['connectionFactory'])) {
368
-			$this->connectionFactory = $argument['connectionFactory'];
369
-		} else {
370
-			$this->connectionFactory = new ConnectionFactory($this->ldap);
371
-		}
372
-
373
-		if(isset($argument['accessFactory'])) {
374
-			$this->accessFactory = $argument['accessFactory'];
375
-		} else {
376
-			$this->accessFactory = new AccessFactory(
377
-				$this->ldap,
378
-				$this->userManager,
379
-				$this->ldapHelper,
380
-				$this->config,
381
-				$this->ncUserManager
382
-			);
383
-		}
384
-	}
367
+        if(isset($argument['connectionFactory'])) {
368
+            $this->connectionFactory = $argument['connectionFactory'];
369
+        } else {
370
+            $this->connectionFactory = new ConnectionFactory($this->ldap);
371
+        }
372
+
373
+        if(isset($argument['accessFactory'])) {
374
+            $this->accessFactory = $argument['accessFactory'];
375
+        } else {
376
+            $this->accessFactory = new AccessFactory(
377
+                $this->ldap,
378
+                $this->userManager,
379
+                $this->ldapHelper,
380
+                $this->config,
381
+                $this->ncUserManager
382
+            );
383
+        }
384
+    }
385 385
 }
Please login to merge, or discard this patch.
Spacing   +31 added lines, -31 removed lines patch added patch discarded remove patch
@@ -103,7 +103,7 @@  discard block
 block discarded – undo
103 103
 	 */
104 104
 	protected function getMinPagingSize() {
105 105
 		$configKeys = $this->config->getAppKeys('user_ldap');
106
-		$configKeys = array_filter($configKeys, function ($key) {
106
+		$configKeys = array_filter($configKeys, function($key) {
107 107
 			return strpos($key, 'ldap_paging_size') !== false;
108 108
 		});
109 109
 		$minPagingSize = null;
@@ -111,7 +111,7 @@  discard block
 block discarded – undo
111 111
 			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
112 112
 			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
113 113
 		}
114
-		return (int)$minPagingSize;
114
+		return (int) $minPagingSize;
115 115
 	}
116 116
 
117 117
 	/**
@@ -122,20 +122,20 @@  discard block
 block discarded – undo
122 122
 
123 123
 		$isBackgroundJobModeAjax = $this->config
124 124
 				->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
125
-		if($isBackgroundJobModeAjax) {
125
+		if ($isBackgroundJobModeAjax) {
126 126
 			return;
127 127
 		}
128 128
 
129 129
 		$cycleData = $this->getCycle();
130
-		if($cycleData === null) {
130
+		if ($cycleData === null) {
131 131
 			$cycleData = $this->determineNextCycle();
132
-			if($cycleData === null) {
132
+			if ($cycleData === null) {
133 133
 				$this->updateInterval();
134 134
 				return;
135 135
 			}
136 136
 		}
137 137
 
138
-		if(!$this->qualifiesToRun($cycleData)) {
138
+		if (!$this->qualifiesToRun($cycleData)) {
139 139
 			$this->updateInterval();
140 140
 			return;
141 141
 		}
@@ -164,7 +164,7 @@  discard block
 block discarded – undo
164 164
 
165 165
 		$filter = $access->combineFilterWithAnd([
166 166
 			$access->connection->ldapUserFilter,
167
-			$access->connection->ldapUserDisplayName . '=*',
167
+			$access->connection->ldapUserDisplayName.'=*',
168 168
 			$access->getFilterPartForUserSearch('')
169 169
 		]);
170 170
 		$results = $access->fetchListOfUsers(
@@ -175,10 +175,10 @@  discard block
 block discarded – undo
175 175
 			true
176 176
 		);
177 177
 
178
-		if((int)$connection->ldapPagingSize === 0) {
178
+		if ((int) $connection->ldapPagingSize === 0) {
179 179
 			return false;
180 180
 		}
181
-		return count($results) >= (int)$connection->ldapPagingSize;
181
+		return count($results) >= (int) $connection->ldapPagingSize;
182 182
 	}
183 183
 
184 184
 	/**
@@ -189,16 +189,16 @@  discard block
 block discarded – undo
189 189
 	 */
190 190
 	public function getCycle() {
191 191
 		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
192
-		if(count($prefixes) === 0) {
192
+		if (count($prefixes) === 0) {
193 193
 			return null;
194 194
 		}
195 195
 
196 196
 		$cycleData = [
197 197
 			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
198
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
198
+			'offset' => (int) $this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
199 199
 		];
200 200
 
201
-		if(
201
+		if (
202 202
 			$cycleData['prefix'] !== null
203 203
 			&& in_array($cycleData['prefix'], $prefixes)
204 204
 		) {
@@ -227,14 +227,14 @@  discard block
 block discarded – undo
227 227
 	 */
228 228
 	public function determineNextCycle(array $cycleData = null) {
229 229
 		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
230
-		if(count($prefixes) === 0) {
230
+		if (count($prefixes) === 0) {
231 231
 			return null;
232 232
 		}
233 233
 
234 234
 		// get the next prefix in line and remember it
235 235
 		$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
236 236
 		$prefix = $this->getNextPrefix($oldPrefix);
237
-		if($prefix === null) {
237
+		if ($prefix === null) {
238 238
 			return null;
239 239
 		}
240 240
 		$cycleData['prefix'] = $prefix;
@@ -252,8 +252,8 @@  discard block
 block discarded – undo
252 252
 	 * @return bool
253 253
 	 */
254 254
 	public function qualifiesToRun($cycleData) {
255
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
256
-		if((time() - $lastChange) > 60 * 30) {
255
+		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'].'_lastChange', 0);
256
+		if ((time() - $lastChange) > 60 * 30) {
257 257
 			return true;
258 258
 		}
259 259
 		return false;
@@ -266,7 +266,7 @@  discard block
 block discarded – undo
266 266
 	 */
267 267
 	protected function increaseOffset($cycleData) {
268 268
 		$ldapConfig = new Configuration($cycleData['prefix']);
269
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
269
+		$cycleData['offset'] += (int) $ldapConfig->ldapPagingSize;
270 270
 		$this->setCycle($cycleData);
271 271
 	}
272 272
 
@@ -279,17 +279,17 @@  discard block
 block discarded – undo
279 279
 	protected function getNextPrefix($lastPrefix) {
280 280
 		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
281 281
 		$noOfPrefixes = count($prefixes);
282
-		if($noOfPrefixes === 0) {
282
+		if ($noOfPrefixes === 0) {
283 283
 			return null;
284 284
 		}
285 285
 		$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
286
-		if($i === false) {
286
+		if ($i === false) {
287 287
 			$i = -1;
288 288
 		} else {
289 289
 			$i++;
290 290
 		}
291 291
 
292
-		if(!isset($prefixes[$i])) {
292
+		if (!isset($prefixes[$i])) {
293 293
 			$i = 0;
294 294
 		}
295 295
 		return $prefixes[$i];
@@ -301,49 +301,49 @@  discard block
 block discarded – undo
301 301
 	 * @param array $argument
302 302
 	 */
303 303
 	public function setArgument($argument) {
304
-		if(isset($argument['config'])) {
304
+		if (isset($argument['config'])) {
305 305
 			$this->config = $argument['config'];
306 306
 		} else {
307 307
 			$this->config = \OC::$server->getConfig();
308 308
 		}
309 309
 
310
-		if(isset($argument['helper'])) {
310
+		if (isset($argument['helper'])) {
311 311
 			$this->ldapHelper = $argument['helper'];
312 312
 		} else {
313 313
 			$this->ldapHelper = new Helper($this->config);
314 314
 		}
315 315
 
316
-		if(isset($argument['ldapWrapper'])) {
316
+		if (isset($argument['ldapWrapper'])) {
317 317
 			$this->ldap = $argument['ldapWrapper'];
318 318
 		} else {
319 319
 			$this->ldap = new LDAP();
320 320
 		}
321 321
 
322
-		if(isset($argument['avatarManager'])) {
322
+		if (isset($argument['avatarManager'])) {
323 323
 			$this->avatarManager = $argument['avatarManager'];
324 324
 		} else {
325 325
 			$this->avatarManager = \OC::$server->getAvatarManager();
326 326
 		}
327 327
 
328
-		if(isset($argument['dbc'])) {
328
+		if (isset($argument['dbc'])) {
329 329
 			$this->dbc = $argument['dbc'];
330 330
 		} else {
331 331
 			$this->dbc = \OC::$server->getDatabaseConnection();
332 332
 		}
333 333
 
334
-		if(isset($argument['ncUserManager'])) {
334
+		if (isset($argument['ncUserManager'])) {
335 335
 			$this->ncUserManager = $argument['ncUserManager'];
336 336
 		} else {
337 337
 			$this->ncUserManager = \OC::$server->getUserManager();
338 338
 		}
339 339
 
340
-		if(isset($argument['notificationManager'])) {
340
+		if (isset($argument['notificationManager'])) {
341 341
 			$this->notificationManager = $argument['notificationManager'];
342 342
 		} else {
343 343
 			$this->notificationManager = \OC::$server->getNotificationManager();
344 344
 		}
345 345
 
346
-		if(isset($argument['userManager'])) {
346
+		if (isset($argument['userManager'])) {
347 347
 			$this->userManager = $argument['userManager'];
348 348
 		} else {
349 349
 			$this->userManager = new Manager(
@@ -358,19 +358,19 @@  discard block
 block discarded – undo
358 358
 			);
359 359
 		}
360 360
 
361
-		if(isset($argument['mapper'])) {
361
+		if (isset($argument['mapper'])) {
362 362
 			$this->mapper = $argument['mapper'];
363 363
 		} else {
364 364
 			$this->mapper = new UserMapping($this->dbc);
365 365
 		}
366 366
 		
367
-		if(isset($argument['connectionFactory'])) {
367
+		if (isset($argument['connectionFactory'])) {
368 368
 			$this->connectionFactory = $argument['connectionFactory'];
369 369
 		} else {
370 370
 			$this->connectionFactory = new ConnectionFactory($this->ldap);
371 371
 		}
372 372
 
373
-		if(isset($argument['accessFactory'])) {
373
+		if (isset($argument['accessFactory'])) {
374 374
 			$this->accessFactory = $argument['accessFactory'];
375 375
 		} else {
376 376
 			$this->accessFactory = new AccessFactory(
Please login to merge, or discard this patch.
apps/user_ldap/lib/Wizard.php 2 patches
Indentation   +1314 added lines, -1314 removed lines patch added patch discarded remove patch
@@ -42,1320 +42,1320 @@
 block discarded – undo
42 42
 use OCP\ILogger;
43 43
 
44 44
 class Wizard extends LDAPUtility {
45
-	/** @var \OCP\IL10N */
46
-	static protected $l;
47
-	protected $access;
48
-	protected $cr;
49
-	protected $configuration;
50
-	protected $result;
51
-	protected $resultCache = [];
52
-
53
-	const LRESULT_PROCESSED_OK = 2;
54
-	const LRESULT_PROCESSED_INVALID = 3;
55
-	const LRESULT_PROCESSED_SKIP = 4;
56
-
57
-	const LFILTER_LOGIN      = 2;
58
-	const LFILTER_USER_LIST  = 3;
59
-	const LFILTER_GROUP_LIST = 4;
60
-
61
-	const LFILTER_MODE_ASSISTED = 2;
62
-	const LFILTER_MODE_RAW = 1;
63
-
64
-	const LDAP_NW_TIMEOUT = 4;
65
-
66
-	/**
67
-	 * Constructor
68
-	 * @param Configuration $configuration an instance of Configuration
69
-	 * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
70
-	 * @param Access $access
71
-	 */
72
-	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73
-		parent::__construct($ldap);
74
-		$this->configuration = $configuration;
75
-		if(is_null(Wizard::$l)) {
76
-			Wizard::$l = \OC::$server->getL10N('user_ldap');
77
-		}
78
-		$this->access = $access;
79
-		$this->result = new WizardResult();
80
-	}
81
-
82
-	public function __destruct() {
83
-		if($this->result->hasChanges()) {
84
-			$this->configuration->saveConfiguration();
85
-		}
86
-	}
87
-
88
-	/**
89
-	 * counts entries in the LDAP directory
90
-	 *
91
-	 * @param string $filter the LDAP search filter
92
-	 * @param string $type a string being either 'users' or 'groups';
93
-	 * @return int
94
-	 * @throws \Exception
95
-	 */
96
-	public function countEntries(string $filter, string $type): int {
97
-		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
-		if($type === 'users') {
99
-			$reqs[] = 'ldapUserFilter';
100
-		}
101
-		if(!$this->checkRequirements($reqs)) {
102
-			throw new \Exception('Requirements not met', 400);
103
-		}
104
-
105
-		$attr = ['dn']; // default
106
-		$limit = 1001;
107
-		if($type === 'groups') {
108
-			$result =  $this->access->countGroups($filter, $attr, $limit);
109
-		} else if($type === 'users') {
110
-			$result = $this->access->countUsers($filter, $attr, $limit);
111
-		} else if ($type === 'objects') {
112
-			$result = $this->access->countObjects($limit);
113
-		} else {
114
-			throw new \Exception('Internal error: Invalid object type', 500);
115
-		}
116
-
117
-		return (int)$result;
118
-	}
119
-
120
-	/**
121
-	 * formats the return value of a count operation to the string to be
122
-	 * inserted.
123
-	 *
124
-	 * @param int $count
125
-	 * @return string
126
-	 */
127
-	private function formatCountResult(int $count): string {
128
-		if($count > 1000) {
129
-			return '> 1000';
130
-		}
131
-		return (string)$count;
132
-	}
133
-
134
-	public function countGroups() {
135
-		$filter = $this->configuration->ldapGroupFilter;
136
-
137
-		if(empty($filter)) {
138
-			$output = self::$l->n('%s group found', '%s groups found', 0, [0]);
139
-			$this->result->addChange('ldap_group_count', $output);
140
-			return $this->result;
141
-		}
142
-
143
-		try {
144
-			$groupsTotal = $this->countEntries($filter, 'groups');
145
-		} catch (\Exception $e) {
146
-			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
148
-				throw $e;
149
-			}
150
-			return false;
151
-		}
152
-		$output = self::$l->n(
153
-			'%s group found',
154
-			'%s groups found',
155
-			$groupsTotal,
156
-			[$this->formatCountResult($groupsTotal)]
157
-		);
158
-		$this->result->addChange('ldap_group_count', $output);
159
-		return $this->result;
160
-	}
161
-
162
-	/**
163
-	 * @return WizardResult
164
-	 * @throws \Exception
165
-	 */
166
-	public function countUsers() {
167
-		$filter = $this->access->getFilterForUserCount();
168
-
169
-		$usersTotal = $this->countEntries($filter, 'users');
170
-		$output = self::$l->n(
171
-			'%s user found',
172
-			'%s users found',
173
-			$usersTotal,
174
-			[$this->formatCountResult($usersTotal)]
175
-		);
176
-		$this->result->addChange('ldap_user_count', $output);
177
-		return $this->result;
178
-	}
179
-
180
-	/**
181
-	 * counts any objects in the currently set base dn
182
-	 *
183
-	 * @return WizardResult
184
-	 * @throws \Exception
185
-	 */
186
-	public function countInBaseDN() {
187
-		// we don't need to provide a filter in this case
188
-		$total = $this->countEntries('', 'objects');
189
-		if($total === false) {
190
-			throw new \Exception('invalid results received');
191
-		}
192
-		$this->result->addChange('ldap_test_base', $total);
193
-		return $this->result;
194
-	}
195
-
196
-	/**
197
-	 * counts users with a specified attribute
198
-	 * @param string $attr
199
-	 * @param bool $existsCheck
200
-	 * @return int|bool
201
-	 */
202
-	public function countUsersWithAttribute($attr, $existsCheck = false) {
203
-		if(!$this->checkRequirements(['ldapHost',
204
-			'ldapPort',
205
-			'ldapBase',
206
-			'ldapUserFilter',
207
-		])) {
208
-			return  false;
209
-		}
210
-
211
-		$filter = $this->access->combineFilterWithAnd([
212
-			$this->configuration->ldapUserFilter,
213
-			$attr . '=*'
214
-		]);
215
-
216
-		$limit = ($existsCheck === false) ? null : 1;
217
-
218
-		return $this->access->countUsers($filter, ['dn'], $limit);
219
-	}
220
-
221
-	/**
222
-	 * detects the display name attribute. If a setting is already present that
223
-	 * returns at least one hit, the detection will be canceled.
224
-	 * @return WizardResult|bool
225
-	 * @throws \Exception
226
-	 */
227
-	public function detectUserDisplayNameAttribute() {
228
-		if(!$this->checkRequirements(['ldapHost',
229
-			'ldapPort',
230
-			'ldapBase',
231
-			'ldapUserFilter',
232
-		])) {
233
-			return  false;
234
-		}
235
-
236
-		$attr = $this->configuration->ldapUserDisplayName;
237
-		if ($attr !== '' && $attr !== 'displayName') {
238
-			// most likely not the default value with upper case N,
239
-			// verify it still produces a result
240
-			$count = (int)$this->countUsersWithAttribute($attr, true);
241
-			if($count > 0) {
242
-				//no change, but we sent it back to make sure the user interface
243
-				//is still correct, even if the ajax call was cancelled meanwhile
244
-				$this->result->addChange('ldap_display_name', $attr);
245
-				return $this->result;
246
-			}
247
-		}
248
-
249
-		// first attribute that has at least one result wins
250
-		$displayNameAttrs = ['displayname', 'cn'];
251
-		foreach ($displayNameAttrs as $attr) {
252
-			$count = (int)$this->countUsersWithAttribute($attr, true);
253
-
254
-			if($count > 0) {
255
-				$this->applyFind('ldap_display_name', $attr);
256
-				return $this->result;
257
-			}
258
-		}
259
-
260
-		throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
261
-	}
262
-
263
-	/**
264
-	 * detects the most often used email attribute for users applying to the
265
-	 * user list filter. If a setting is already present that returns at least
266
-	 * one hit, the detection will be canceled.
267
-	 * @return WizardResult|bool
268
-	 */
269
-	public function detectEmailAttribute() {
270
-		if(!$this->checkRequirements(['ldapHost',
271
-			'ldapPort',
272
-			'ldapBase',
273
-			'ldapUserFilter',
274
-		])) {
275
-			return  false;
276
-		}
277
-
278
-		$attr = $this->configuration->ldapEmailAttribute;
279
-		if ($attr !== '') {
280
-			$count = (int)$this->countUsersWithAttribute($attr, true);
281
-			if($count > 0) {
282
-				return false;
283
-			}
284
-			$writeLog = true;
285
-		} else {
286
-			$writeLog = false;
287
-		}
288
-
289
-		$emailAttributes = ['mail', 'mailPrimaryAddress'];
290
-		$winner = '';
291
-		$maxUsers = 0;
292
-		foreach($emailAttributes as $attr) {
293
-			$count = $this->countUsersWithAttribute($attr);
294
-			if($count > $maxUsers) {
295
-				$maxUsers = $count;
296
-				$winner = $attr;
297
-			}
298
-		}
299
-
300
-		if($winner !== '') {
301
-			$this->applyFind('ldap_email_attr', $winner);
302
-			if($writeLog) {
303
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
-					'automatically been reset, because the original value ' .
305
-					'did not return any results.', ILogger::INFO);
306
-			}
307
-		}
308
-
309
-		return $this->result;
310
-	}
311
-
312
-	/**
313
-	 * @return WizardResult
314
-	 * @throws \Exception
315
-	 */
316
-	public function determineAttributes() {
317
-		if(!$this->checkRequirements(['ldapHost',
318
-			'ldapPort',
319
-			'ldapBase',
320
-			'ldapUserFilter',
321
-		])) {
322
-			return  false;
323
-		}
324
-
325
-		$attributes = $this->getUserAttributes();
326
-
327
-		natcasesort($attributes);
328
-		$attributes = array_values($attributes);
329
-
330
-		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331
-
332
-		$selected = $this->configuration->ldapLoginFilterAttributes;
333
-		if(is_array($selected) && !empty($selected)) {
334
-			$this->result->addChange('ldap_loginfilter_attributes', $selected);
335
-		}
336
-
337
-		return $this->result;
338
-	}
339
-
340
-	/**
341
-	 * detects the available LDAP attributes
342
-	 * @return array|false The instance's WizardResult instance
343
-	 * @throws \Exception
344
-	 */
345
-	private function getUserAttributes() {
346
-		if(!$this->checkRequirements(['ldapHost',
347
-			'ldapPort',
348
-			'ldapBase',
349
-			'ldapUserFilter',
350
-		])) {
351
-			return  false;
352
-		}
353
-		$cr = $this->getConnection();
354
-		if(!$cr) {
355
-			throw new \Exception('Could not connect to LDAP');
356
-		}
357
-
358
-		$base = $this->configuration->ldapBase[0];
359
-		$filter = $this->configuration->ldapUserFilter;
360
-		$rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
361
-		if(!$this->ldap->isResource($rr)) {
362
-			return false;
363
-		}
364
-		$er = $this->ldap->firstEntry($cr, $rr);
365
-		$attributes = $this->ldap->getAttributes($cr, $er);
366
-		$pureAttributes = [];
367
-		for($i = 0; $i < $attributes['count']; $i++) {
368
-			$pureAttributes[] = $attributes[$i];
369
-		}
370
-
371
-		return $pureAttributes;
372
-	}
373
-
374
-	/**
375
-	 * detects the available LDAP groups
376
-	 * @return WizardResult|false the instance's WizardResult instance
377
-	 */
378
-	public function determineGroupsForGroups() {
379
-		return $this->determineGroups('ldap_groupfilter_groups',
380
-									  'ldapGroupFilterGroups',
381
-									  false);
382
-	}
383
-
384
-	/**
385
-	 * detects the available LDAP groups
386
-	 * @return WizardResult|false the instance's WizardResult instance
387
-	 */
388
-	public function determineGroupsForUsers() {
389
-		return $this->determineGroups('ldap_userfilter_groups',
390
-									  'ldapUserFilterGroups');
391
-	}
392
-
393
-	/**
394
-	 * detects the available LDAP groups
395
-	 * @param string $dbKey
396
-	 * @param string $confKey
397
-	 * @param bool $testMemberOf
398
-	 * @return WizardResult|false the instance's WizardResult instance
399
-	 * @throws \Exception
400
-	 */
401
-	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
-		if(!$this->checkRequirements(['ldapHost',
403
-			'ldapPort',
404
-			'ldapBase',
405
-		])) {
406
-			return  false;
407
-		}
408
-		$cr = $this->getConnection();
409
-		if(!$cr) {
410
-			throw new \Exception('Could not connect to LDAP');
411
-		}
412
-
413
-		$this->fetchGroups($dbKey, $confKey);
414
-
415
-		if($testMemberOf) {
416
-			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417
-			$this->result->markChange();
418
-			if(!$this->configuration->hasMemberOfFilterSupport) {
419
-				throw new \Exception('memberOf is not supported by the server');
420
-			}
421
-		}
422
-
423
-		return $this->result;
424
-	}
425
-
426
-	/**
427
-	 * fetches all groups from LDAP and adds them to the result object
428
-	 *
429
-	 * @param string $dbKey
430
-	 * @param string $confKey
431
-	 * @return array $groupEntries
432
-	 * @throws \Exception
433
-	 */
434
-	public function fetchGroups($dbKey, $confKey) {
435
-		$obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
436
-
437
-		$filterParts = [];
438
-		foreach($obclasses as $obclass) {
439
-			$filterParts[] = 'objectclass='.$obclass;
440
-		}
441
-		//we filter for everything
442
-		//- that looks like a group and
443
-		//- has the group display name set
444
-		$filter = $this->access->combineFilterWithOr($filterParts);
445
-		$filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']);
446
-
447
-		$groupNames = [];
448
-		$groupEntries = [];
449
-		$limit = 400;
450
-		$offset = 0;
451
-		do {
452
-			// we need to request dn additionally here, otherwise memberOf
453
-			// detection will fail later
454
-			$result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
455
-			foreach($result as $item) {
456
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457
-					// just in case - no issue known
458
-					continue;
459
-				}
460
-				$groupNames[] = $item['cn'][0];
461
-				$groupEntries[] = $item;
462
-			}
463
-			$offset += $limit;
464
-		} while ($this->access->hasMoreResults());
465
-
466
-		if(count($groupNames) > 0) {
467
-			natsort($groupNames);
468
-			$this->result->addOptions($dbKey, array_values($groupNames));
469
-		} else {
470
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
471
-		}
472
-
473
-		$setFeatures = $this->configuration->$confKey;
474
-		if(is_array($setFeatures) && !empty($setFeatures)) {
475
-			//something is already configured? pre-select it.
476
-			$this->result->addChange($dbKey, $setFeatures);
477
-		}
478
-		return $groupEntries;
479
-	}
480
-
481
-	public function determineGroupMemberAssoc() {
482
-		if(!$this->checkRequirements(['ldapHost',
483
-			'ldapPort',
484
-			'ldapGroupFilter',
485
-		])) {
486
-			return  false;
487
-		}
488
-		$attribute = $this->detectGroupMemberAssoc();
489
-		if($attribute === false) {
490
-			return false;
491
-		}
492
-		$this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
493
-		$this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
494
-
495
-		return $this->result;
496
-	}
497
-
498
-	/**
499
-	 * Detects the available object classes
500
-	 * @return WizardResult|false the instance's WizardResult instance
501
-	 * @throws \Exception
502
-	 */
503
-	public function determineGroupObjectClasses() {
504
-		if(!$this->checkRequirements(['ldapHost',
505
-			'ldapPort',
506
-			'ldapBase',
507
-		])) {
508
-			return  false;
509
-		}
510
-		$cr = $this->getConnection();
511
-		if(!$cr) {
512
-			throw new \Exception('Could not connect to LDAP');
513
-		}
514
-
515
-		$obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*'];
516
-		$this->determineFeature($obclasses,
517
-								'objectclass',
518
-								'ldap_groupfilter_objectclass',
519
-								'ldapGroupFilterObjectclass',
520
-								false);
521
-
522
-		return $this->result;
523
-	}
524
-
525
-	/**
526
-	 * detects the available object classes
527
-	 * @return WizardResult
528
-	 * @throws \Exception
529
-	 */
530
-	public function determineUserObjectClasses() {
531
-		if(!$this->checkRequirements(['ldapHost',
532
-			'ldapPort',
533
-			'ldapBase',
534
-		])) {
535
-			return  false;
536
-		}
537
-		$cr = $this->getConnection();
538
-		if(!$cr) {
539
-			throw new \Exception('Could not connect to LDAP');
540
-		}
541
-
542
-		$obclasses = ['inetOrgPerson', 'person', 'organizationalPerson',
543
-			'user', 'posixAccount', '*'];
544
-		$filter = $this->configuration->ldapUserFilter;
545
-		//if filter is empty, it is probably the first time the wizard is called
546
-		//then, apply suggestions.
547
-		$this->determineFeature($obclasses,
548
-								'objectclass',
549
-								'ldap_userfilter_objectclass',
550
-								'ldapUserFilterObjectclass',
551
-								empty($filter));
552
-
553
-		return $this->result;
554
-	}
555
-
556
-	/**
557
-	 * @return WizardResult|false
558
-	 * @throws \Exception
559
-	 */
560
-	public function getGroupFilter() {
561
-		if(!$this->checkRequirements(['ldapHost',
562
-			'ldapPort',
563
-			'ldapBase',
564
-		])) {
565
-			return false;
566
-		}
567
-		//make sure the use display name is set
568
-		$displayName = $this->configuration->ldapGroupDisplayName;
569
-		if ($displayName === '') {
570
-			$d = $this->configuration->getDefaults();
571
-			$this->applyFind('ldap_group_display_name',
572
-							 $d['ldap_group_display_name']);
573
-		}
574
-		$filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
575
-
576
-		$this->applyFind('ldap_group_filter', $filter);
577
-		return $this->result;
578
-	}
579
-
580
-	/**
581
-	 * @return WizardResult|false
582
-	 * @throws \Exception
583
-	 */
584
-	public function getUserListFilter() {
585
-		if(!$this->checkRequirements(['ldapHost',
586
-			'ldapPort',
587
-			'ldapBase',
588
-		])) {
589
-			return false;
590
-		}
591
-		//make sure the use display name is set
592
-		$displayName = $this->configuration->ldapUserDisplayName;
593
-		if ($displayName === '') {
594
-			$d = $this->configuration->getDefaults();
595
-			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
596
-		}
597
-		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
-		if(!$filter) {
599
-			throw new \Exception('Cannot create filter');
600
-		}
601
-
602
-		$this->applyFind('ldap_userlist_filter', $filter);
603
-		return $this->result;
604
-	}
605
-
606
-	/**
607
-	 * @return bool|WizardResult
608
-	 * @throws \Exception
609
-	 */
610
-	public function getUserLoginFilter() {
611
-		if(!$this->checkRequirements(['ldapHost',
612
-			'ldapPort',
613
-			'ldapBase',
614
-			'ldapUserFilter',
615
-		])) {
616
-			return false;
617
-		}
618
-
619
-		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
-		if(!$filter) {
621
-			throw new \Exception('Cannot create filter');
622
-		}
623
-
624
-		$this->applyFind('ldap_login_filter', $filter);
625
-		return $this->result;
626
-	}
627
-
628
-	/**
629
-	 * @return bool|WizardResult
630
-	 * @param string $loginName
631
-	 * @throws \Exception
632
-	 */
633
-	public function testLoginName($loginName) {
634
-		if(!$this->checkRequirements(['ldapHost',
635
-			'ldapPort',
636
-			'ldapBase',
637
-			'ldapLoginFilter',
638
-		])) {
639
-			return false;
640
-		}
641
-
642
-		$cr = $this->access->connection->getConnectionResource();
643
-		if(!$this->ldap->isResource($cr)) {
644
-			throw new \Exception('connection error');
645
-		}
646
-
647
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648
-			=== false) {
649
-			throw new \Exception('missing placeholder');
650
-		}
651
-
652
-		$users = $this->access->countUsersByLoginName($loginName);
653
-		if($this->ldap->errno($cr) !== 0) {
654
-			throw new \Exception($this->ldap->error($cr));
655
-		}
656
-		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
657
-		$this->result->addChange('ldap_test_loginname', $users);
658
-		$this->result->addChange('ldap_test_effective_filter', $filter);
659
-		return $this->result;
660
-	}
661
-
662
-	/**
663
-	 * Tries to determine the port, requires given Host, User DN and Password
664
-	 * @return WizardResult|false WizardResult on success, false otherwise
665
-	 * @throws \Exception
666
-	 */
667
-	public function guessPortAndTLS() {
668
-		if(!$this->checkRequirements(['ldapHost',
669
-		])) {
670
-			return false;
671
-		}
672
-		$this->checkHost();
673
-		$portSettings = $this->getPortSettingsToTry();
674
-
675
-		if(!is_array($portSettings)) {
676
-			throw new \Exception(print_r($portSettings, true));
677
-		}
678
-
679
-		//proceed from the best configuration and return on first success
680
-		foreach($portSettings as $setting) {
681
-			$p = $setting['port'];
682
-			$t = $setting['tls'];
683
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
684
-			//connectAndBind may throw Exception, it needs to be catched by the
685
-			//callee of this method
686
-
687
-			try {
688
-				$settingsFound = $this->connectAndBind($p, $t);
689
-			} catch (\Exception $e) {
690
-				// any reply other than -1 (= cannot connect) is already okay,
691
-				// because then we found the server
692
-				// unavailable startTLS returns -11
693
-				if($e->getCode() > 0) {
694
-					$settingsFound = true;
695
-				} else {
696
-					throw $e;
697
-				}
698
-			}
699
-
700
-			if ($settingsFound === true) {
701
-				$config = [
702
-					'ldapPort' => $p,
703
-					'ldapTLS' => (int)$t
704
-				];
705
-				$this->configuration->setConfiguration($config);
706
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
707
-				$this->result->addChange('ldap_port', $p);
708
-				return $this->result;
709
-			}
710
-		}
711
-
712
-		//custom port, undetected (we do not brute force)
713
-		return false;
714
-	}
715
-
716
-	/**
717
-	 * tries to determine a base dn from User DN or LDAP Host
718
-	 * @return WizardResult|false WizardResult on success, false otherwise
719
-	 */
720
-	public function guessBaseDN() {
721
-		if(!$this->checkRequirements(['ldapHost',
722
-			'ldapPort',
723
-		])) {
724
-			return false;
725
-		}
726
-
727
-		//check whether a DN is given in the agent name (99.9% of all cases)
728
-		$base = null;
729
-		$i = stripos($this->configuration->ldapAgentName, 'dc=');
730
-		if($i !== false) {
731
-			$base = substr($this->configuration->ldapAgentName, $i);
732
-			if($this->testBaseDN($base)) {
733
-				$this->applyFind('ldap_base', $base);
734
-				return $this->result;
735
-			}
736
-		}
737
-
738
-		//this did not help :(
739
-		//Let's see whether we can parse the Host URL and convert the domain to
740
-		//a base DN
741
-		$helper = new Helper(\OC::$server->getConfig());
742
-		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
-		if(!$domain) {
744
-			return false;
745
-		}
746
-
747
-		$dparts = explode('.', $domain);
748
-		while(count($dparts) > 0) {
749
-			$base2 = 'dc=' . implode(',dc=', $dparts);
750
-			if ($base !== $base2 && $this->testBaseDN($base2)) {
751
-				$this->applyFind('ldap_base', $base2);
752
-				return $this->result;
753
-			}
754
-			array_shift($dparts);
755
-		}
756
-
757
-		return false;
758
-	}
759
-
760
-	/**
761
-	 * sets the found value for the configuration key in the WizardResult
762
-	 * as well as in the Configuration instance
763
-	 * @param string $key the configuration key
764
-	 * @param string $value the (detected) value
765
-	 *
766
-	 */
767
-	private function applyFind($key, $value) {
768
-		$this->result->addChange($key, $value);
769
-		$this->configuration->setConfiguration([$key => $value]);
770
-	}
771
-
772
-	/**
773
-	 * Checks, whether a port was entered in the Host configuration
774
-	 * field. In this case the port will be stripped off, but also stored as
775
-	 * setting.
776
-	 */
777
-	private function checkHost() {
778
-		$host = $this->configuration->ldapHost;
779
-		$hostInfo = parse_url($host);
780
-
781
-		//removes Port from Host
782
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
783
-			$port = $hostInfo['port'];
784
-			$host = str_replace(':'.$port, '', $host);
785
-			$this->applyFind('ldap_host', $host);
786
-			$this->applyFind('ldap_port', $port);
787
-		}
788
-	}
789
-
790
-	/**
791
-	 * tries to detect the group member association attribute which is
792
-	 * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
793
-	 * @return string|false, string with the attribute name, false on error
794
-	 * @throws \Exception
795
-	 */
796
-	private function detectGroupMemberAssoc() {
797
-		$possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber'];
798
-		$filter = $this->configuration->ldapGroupFilter;
799
-		if(empty($filter)) {
800
-			return false;
801
-		}
802
-		$cr = $this->getConnection();
803
-		if(!$cr) {
804
-			throw new \Exception('Could not connect to LDAP');
805
-		}
806
-		$base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
807
-		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
-		if(!$this->ldap->isResource($rr)) {
809
-			return false;
810
-		}
811
-		$er = $this->ldap->firstEntry($cr, $rr);
812
-		while(is_resource($er)) {
813
-			$this->ldap->getDN($cr, $er);
814
-			$attrs = $this->ldap->getAttributes($cr, $er);
815
-			$result = [];
816
-			$possibleAttrsCount = count($possibleAttrs);
817
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
818
-				if(isset($attrs[$possibleAttrs[$i]])) {
819
-					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820
-				}
821
-			}
822
-			if(!empty($result)) {
823
-				natsort($result);
824
-				return key($result);
825
-			}
826
-
827
-			$er = $this->ldap->nextEntry($cr, $er);
828
-		}
829
-
830
-		return false;
831
-	}
832
-
833
-	/**
834
-	 * Checks whether for a given BaseDN results will be returned
835
-	 * @param string $base the BaseDN to test
836
-	 * @return bool true on success, false otherwise
837
-	 * @throws \Exception
838
-	 */
839
-	private function testBaseDN($base) {
840
-		$cr = $this->getConnection();
841
-		if(!$cr) {
842
-			throw new \Exception('Could not connect to LDAP');
843
-		}
844
-
845
-		//base is there, let's validate it. If we search for anything, we should
846
-		//get a result set > 0 on a proper base
847
-		$rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
848
-		if(!$this->ldap->isResource($rr)) {
849
-			$errorNo  = $this->ldap->errno($cr);
850
-			$errorMsg = $this->ldap->error($cr);
851
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
852
-							' Error '.$errorNo.': '.$errorMsg, ILogger::INFO);
853
-			return false;
854
-		}
855
-		$entries = $this->ldap->countEntries($cr, $rr);
856
-		return ($entries !== false) && ($entries > 0);
857
-	}
858
-
859
-	/**
860
-	 * Checks whether the server supports memberOf in LDAP Filter.
861
-	 * Note: at least in OpenLDAP, availability of memberOf is dependent on
862
-	 * a configured objectClass. I.e. not necessarily for all available groups
863
-	 * memberOf does work.
864
-	 *
865
-	 * @return bool true if it does, false otherwise
866
-	 * @throws \Exception
867
-	 */
868
-	private function testMemberOf() {
869
-		$cr = $this->getConnection();
870
-		if(!$cr) {
871
-			throw new \Exception('Could not connect to LDAP');
872
-		}
873
-		$result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
874
-		if(is_int($result) &&  $result > 0) {
875
-			return true;
876
-		}
877
-		return false;
878
-	}
879
-
880
-	/**
881
-	 * creates an LDAP Filter from given configuration
882
-	 * @param integer $filterType int, for which use case the filter shall be created
883
-	 * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
884
-	 * self::LFILTER_GROUP_LIST
885
-	 * @return string|false string with the filter on success, false otherwise
886
-	 * @throws \Exception
887
-	 */
888
-	private function composeLdapFilter($filterType) {
889
-		$filter = '';
890
-		$parts = 0;
891
-		switch ($filterType) {
892
-			case self::LFILTER_USER_LIST:
893
-				$objcs = $this->configuration->ldapUserFilterObjectclass;
894
-				//glue objectclasses
895
-				if(is_array($objcs) && count($objcs) > 0) {
896
-					$filter .= '(|';
897
-					foreach($objcs as $objc) {
898
-						$filter .= '(objectclass=' . $objc . ')';
899
-					}
900
-					$filter .= ')';
901
-					$parts++;
902
-				}
903
-				//glue group memberships
904
-				if($this->configuration->hasMemberOfFilterSupport) {
905
-					$cns = $this->configuration->ldapUserFilterGroups;
906
-					if(is_array($cns) && count($cns) > 0) {
907
-						$filter .= '(|';
908
-						$cr = $this->getConnection();
909
-						if(!$cr) {
910
-							throw new \Exception('Could not connect to LDAP');
911
-						}
912
-						$base = $this->configuration->ldapBase[0];
913
-						foreach($cns as $cn) {
914
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']);
915
-							if(!$this->ldap->isResource($rr)) {
916
-								continue;
917
-							}
918
-							$er = $this->ldap->firstEntry($cr, $rr);
919
-							$attrs = $this->ldap->getAttributes($cr, $er);
920
-							$dn = $this->ldap->getDN($cr, $er);
921
-							if ($dn === false || $dn === '') {
922
-								continue;
923
-							}
924
-							$filterPart = '(memberof=' . $dn . ')';
925
-							if(isset($attrs['primaryGroupToken'])) {
926
-								$pgt = $attrs['primaryGroupToken'][0];
927
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
929
-							}
930
-							$filter .= $filterPart;
931
-						}
932
-						$filter .= ')';
933
-					}
934
-					$parts++;
935
-				}
936
-				//wrap parts in AND condition
937
-				if($parts > 1) {
938
-					$filter = '(&' . $filter . ')';
939
-				}
940
-				if ($filter === '') {
941
-					$filter = '(objectclass=*)';
942
-				}
943
-				break;
944
-
945
-			case self::LFILTER_GROUP_LIST:
946
-				$objcs = $this->configuration->ldapGroupFilterObjectclass;
947
-				//glue objectclasses
948
-				if(is_array($objcs) && count($objcs) > 0) {
949
-					$filter .= '(|';
950
-					foreach($objcs as $objc) {
951
-						$filter .= '(objectclass=' . $objc . ')';
952
-					}
953
-					$filter .= ')';
954
-					$parts++;
955
-				}
956
-				//glue group memberships
957
-				$cns = $this->configuration->ldapGroupFilterGroups;
958
-				if(is_array($cns) && count($cns) > 0) {
959
-					$filter .= '(|';
960
-					foreach($cns as $cn) {
961
-						$filter .= '(cn=' . $cn . ')';
962
-					}
963
-					$filter .= ')';
964
-				}
965
-				$parts++;
966
-				//wrap parts in AND condition
967
-				if($parts > 1) {
968
-					$filter = '(&' . $filter . ')';
969
-				}
970
-				break;
971
-
972
-			case self::LFILTER_LOGIN:
973
-				$ulf = $this->configuration->ldapUserFilter;
974
-				$loginpart = '=%uid';
975
-				$filterUsername = '';
976
-				$userAttributes = $this->getUserAttributes();
977
-				$userAttributes = array_change_key_case(array_flip($userAttributes));
978
-				$parts = 0;
979
-
980
-				if($this->configuration->ldapLoginFilterUsername === '1') {
981
-					$attr = '';
982
-					if(isset($userAttributes['uid'])) {
983
-						$attr = 'uid';
984
-					} else if(isset($userAttributes['samaccountname'])) {
985
-						$attr = 'samaccountname';
986
-					} else if(isset($userAttributes['cn'])) {
987
-						//fallback
988
-						$attr = 'cn';
989
-					}
990
-					if ($attr !== '') {
991
-						$filterUsername = '(' . $attr . $loginpart . ')';
992
-						$parts++;
993
-					}
994
-				}
995
-
996
-				$filterEmail = '';
997
-				if($this->configuration->ldapLoginFilterEmail === '1') {
998
-					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999
-					$parts++;
1000
-				}
1001
-
1002
-				$filterAttributes = '';
1003
-				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005
-					$filterAttributes = '(|';
1006
-					foreach($attrsToFilter as $attribute) {
1007
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1008
-					}
1009
-					$filterAttributes .= ')';
1010
-					$parts++;
1011
-				}
1012
-
1013
-				$filterLogin = '';
1014
-				if($parts > 1) {
1015
-					$filterLogin = '(|';
1016
-				}
1017
-				$filterLogin .= $filterUsername;
1018
-				$filterLogin .= $filterEmail;
1019
-				$filterLogin .= $filterAttributes;
1020
-				if($parts > 1) {
1021
-					$filterLogin .= ')';
1022
-				}
1023
-
1024
-				$filter = '(&'.$ulf.$filterLogin.')';
1025
-				break;
1026
-		}
1027
-
1028
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG);
1029
-
1030
-		return $filter;
1031
-	}
1032
-
1033
-	/**
1034
-	 * Connects and Binds to an LDAP Server
1035
-	 *
1036
-	 * @param int $port the port to connect with
1037
-	 * @param bool $tls whether startTLS is to be used
1038
-	 * @return bool
1039
-	 * @throws \Exception
1040
-	 */
1041
-	private function connectAndBind($port, $tls) {
1042
-		//connect, does not really trigger any server communication
1043
-		$host = $this->configuration->ldapHost;
1044
-		$hostInfo = parse_url($host);
1045
-		if(!$hostInfo) {
1046
-			throw new \Exception(self::$l->t('Invalid Host'));
1047
-		}
1048
-		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049
-		$cr = $this->ldap->connect($host, $port);
1050
-		if(!is_resource($cr)) {
1051
-			throw new \Exception(self::$l->t('Invalid Host'));
1052
-		}
1053
-
1054
-		//set LDAP options
1055
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1056
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1057
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058
-
1059
-		try {
1060
-			if($tls) {
1061
-				$isTlsWorking = @$this->ldap->startTls($cr);
1062
-				if(!$isTlsWorking) {
1063
-					return false;
1064
-				}
1065
-			}
1066
-
1067
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG);
1068
-			//interesting part: do the bind!
1069
-			$login = $this->ldap->bind($cr,
1070
-				$this->configuration->ldapAgentName,
1071
-				$this->configuration->ldapAgentPassword
1072
-			);
1073
-			$errNo = $this->ldap->errno($cr);
1074
-			$error = ldap_error($cr);
1075
-			$this->ldap->unbind($cr);
1076
-		} catch(ServerNotAvailableException $e) {
1077
-			return false;
1078
-		}
1079
-
1080
-		if($login === true) {
1081
-			$this->ldap->unbind($cr);
1082
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1083
-			return true;
1084
-		}
1085
-
1086
-		if($errNo === -1) {
1087
-			//host, port or TLS wrong
1088
-			return false;
1089
-		}
1090
-		throw new \Exception($error, $errNo);
1091
-	}
1092
-
1093
-	/**
1094
-	 * checks whether a valid combination of agent and password has been
1095
-	 * provided (either two values or nothing for anonymous connect)
1096
-	 * @return bool, true if everything is fine, false otherwise
1097
-	 */
1098
-	private function checkAgentRequirements() {
1099
-		$agent = $this->configuration->ldapAgentName;
1100
-		$pwd = $this->configuration->ldapAgentPassword;
1101
-
1102
-		return
1103
-			($agent !== '' && $pwd !== '')
1104
-			||  ($agent === '' && $pwd === '')
1105
-		;
1106
-	}
1107
-
1108
-	/**
1109
-	 * @param array $reqs
1110
-	 * @return bool
1111
-	 */
1112
-	private function checkRequirements($reqs) {
1113
-		$this->checkAgentRequirements();
1114
-		foreach($reqs as $option) {
1115
-			$value = $this->configuration->$option;
1116
-			if(empty($value)) {
1117
-				return false;
1118
-			}
1119
-		}
1120
-		return true;
1121
-	}
1122
-
1123
-	/**
1124
-	 * does a cumulativeSearch on LDAP to get different values of a
1125
-	 * specified attribute
1126
-	 * @param string[] $filters array, the filters that shall be used in the search
1127
-	 * @param string $attr the attribute of which a list of values shall be returned
1128
-	 * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1129
-	 * The lower, the faster
1130
-	 * @param string $maxF string. if not null, this variable will have the filter that
1131
-	 * yields most result entries
1132
-	 * @return array|false an array with the values on success, false otherwise
1133
-	 */
1134
-	public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1135
-		$dnRead = [];
1136
-		$foundItems = [];
1137
-		$maxEntries = 0;
1138
-		if(!is_array($this->configuration->ldapBase)
1139
-		   || !isset($this->configuration->ldapBase[0])) {
1140
-			return false;
1141
-		}
1142
-		$base = $this->configuration->ldapBase[0];
1143
-		$cr = $this->getConnection();
1144
-		if(!$this->ldap->isResource($cr)) {
1145
-			return false;
1146
-		}
1147
-		$lastFilter = null;
1148
-		if(isset($filters[count($filters)-1])) {
1149
-			$lastFilter = $filters[count($filters)-1];
1150
-		}
1151
-		foreach($filters as $filter) {
1152
-			if($lastFilter === $filter && count($foundItems) > 0) {
1153
-				//skip when the filter is a wildcard and results were found
1154
-				continue;
1155
-			}
1156
-			// 20k limit for performance and reason
1157
-			$rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
1158
-			if(!$this->ldap->isResource($rr)) {
1159
-				continue;
1160
-			}
1161
-			$entries = $this->ldap->countEntries($cr, $rr);
1162
-			$getEntryFunc = 'firstEntry';
1163
-			if(($entries !== false) && ($entries > 0)) {
1164
-				if(!is_null($maxF) && $entries > $maxEntries) {
1165
-					$maxEntries = $entries;
1166
-					$maxF = $filter;
1167
-				}
1168
-				$dnReadCount = 0;
1169
-				do {
1170
-					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1171
-					$getEntryFunc = 'nextEntry';
1172
-					if(!$this->ldap->isResource($entry)) {
1173
-						continue 2;
1174
-					}
1175
-					$rr = $entry; //will be expected by nextEntry next round
1176
-					$attributes = $this->ldap->getAttributes($cr, $entry);
1177
-					$dn = $this->ldap->getDN($cr, $entry);
1178
-					if($dn === false || in_array($dn, $dnRead)) {
1179
-						continue;
1180
-					}
1181
-					$newItems = [];
1182
-					$state = $this->getAttributeValuesFromEntry($attributes,
1183
-																$attr,
1184
-																$newItems);
1185
-					$dnReadCount++;
1186
-					$foundItems = array_merge($foundItems, $newItems);
1187
-					$this->resultCache[$dn][$attr] = $newItems;
1188
-					$dnRead[] = $dn;
1189
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1190
-						|| $this->ldap->isResource($entry))
1191
-						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192
-			}
1193
-		}
1194
-
1195
-		return array_unique($foundItems);
1196
-	}
1197
-
1198
-	/**
1199
-	 * determines if and which $attr are available on the LDAP server
1200
-	 * @param string[] $objectclasses the objectclasses to use as search filter
1201
-	 * @param string $attr the attribute to look for
1202
-	 * @param string $dbkey the dbkey of the setting the feature is connected to
1203
-	 * @param string $confkey the confkey counterpart for the $dbkey as used in the
1204
-	 * Configuration class
1205
-	 * @param bool $po whether the objectClass with most result entries
1206
-	 * shall be pre-selected via the result
1207
-	 * @return array|false list of found items.
1208
-	 * @throws \Exception
1209
-	 */
1210
-	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211
-		$cr = $this->getConnection();
1212
-		if(!$cr) {
1213
-			throw new \Exception('Could not connect to LDAP');
1214
-		}
1215
-		$p = 'objectclass=';
1216
-		foreach($objectclasses as $key => $value) {
1217
-			$objectclasses[$key] = $p.$value;
1218
-		}
1219
-		$maxEntryObjC = '';
1220
-
1221
-		//how deep to dig?
1222
-		//When looking for objectclasses, testing few entries is sufficient,
1223
-		$dig = 3;
1224
-
1225
-		$availableFeatures =
1226
-			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227
-											   $dig, $maxEntryObjC);
1228
-		if(is_array($availableFeatures)
1229
-		   && count($availableFeatures) > 0) {
1230
-			natcasesort($availableFeatures);
1231
-			//natcasesort keeps indices, but we must get rid of them for proper
1232
-			//sorting in the web UI. Therefore: array_values
1233
-			$this->result->addOptions($dbkey, array_values($availableFeatures));
1234
-		} else {
1235
-			throw new \Exception(self::$l->t('Could not find the desired feature'));
1236
-		}
1237
-
1238
-		$setFeatures = $this->configuration->$confkey;
1239
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1240
-			//something is already configured? pre-select it.
1241
-			$this->result->addChange($dbkey, $setFeatures);
1242
-		} else if ($po && $maxEntryObjC !== '') {
1243
-			//pre-select objectclass with most result entries
1244
-			$maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1245
-			$this->applyFind($dbkey, $maxEntryObjC);
1246
-			$this->result->addChange($dbkey, $maxEntryObjC);
1247
-		}
1248
-
1249
-		return $availableFeatures;
1250
-	}
1251
-
1252
-	/**
1253
-	 * appends a list of values fr
1254
-	 * @param resource $result the return value from ldap_get_attributes
1255
-	 * @param string $attribute the attribute values to look for
1256
-	 * @param array &$known new values will be appended here
1257
-	 * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1258
-	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259
-	 */
1260
-	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
-		if(!is_array($result)
1262
-		   || !isset($result['count'])
1263
-		   || !$result['count'] > 0) {
1264
-			return self::LRESULT_PROCESSED_INVALID;
1265
-		}
1266
-
1267
-		// strtolower on all keys for proper comparison
1268
-		$result = \OCP\Util::mb_array_change_key_case($result);
1269
-		$attribute = strtolower($attribute);
1270
-		if(isset($result[$attribute])) {
1271
-			foreach($result[$attribute] as $key => $val) {
1272
-				if($key === 'count') {
1273
-					continue;
1274
-				}
1275
-				if(!in_array($val, $known)) {
1276
-					$known[] = $val;
1277
-				}
1278
-			}
1279
-			return self::LRESULT_PROCESSED_OK;
1280
-		} else {
1281
-			return self::LRESULT_PROCESSED_SKIP;
1282
-		}
1283
-	}
1284
-
1285
-	/**
1286
-	 * @return bool|mixed
1287
-	 */
1288
-	private function getConnection() {
1289
-		if(!is_null($this->cr)) {
1290
-			return $this->cr;
1291
-		}
1292
-
1293
-		$cr = $this->ldap->connect(
1294
-			$this->configuration->ldapHost,
1295
-			$this->configuration->ldapPort
1296
-		);
1297
-
1298
-		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299
-		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300
-		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
-		if($this->configuration->ldapTLS === 1) {
1302
-			$this->ldap->startTls($cr);
1303
-		}
1304
-
1305
-		$lo = @$this->ldap->bind($cr,
1306
-								 $this->configuration->ldapAgentName,
1307
-								 $this->configuration->ldapAgentPassword);
1308
-		if($lo === true) {
1309
-			$this->$cr = $cr;
1310
-			return $cr;
1311
-		}
1312
-
1313
-		return false;
1314
-	}
1315
-
1316
-	/**
1317
-	 * @return array
1318
-	 */
1319
-	private function getDefaultLdapPortSettings() {
1320
-		static $settings = [
1321
-			['port' => 7636, 'tls' => false],
1322
-			['port' =>  636, 'tls' => false],
1323
-			['port' => 7389, 'tls' => true],
1324
-			['port' =>  389, 'tls' => true],
1325
-			['port' => 7389, 'tls' => false],
1326
-			['port' =>  389, 'tls' => false],
1327
-		];
1328
-		return $settings;
1329
-	}
1330
-
1331
-	/**
1332
-	 * @return array
1333
-	 */
1334
-	private function getPortSettingsToTry() {
1335
-		//389 ← LDAP / Unencrypted or StartTLS
1336
-		//636 ← LDAPS / SSL
1337
-		//7xxx ← UCS. need to be checked first, because both ports may be open
1338
-		$host = $this->configuration->ldapHost;
1339
-		$port = (int)$this->configuration->ldapPort;
1340
-		$portSettings = [];
1341
-
1342
-		//In case the port is already provided, we will check this first
1343
-		if($port > 0) {
1344
-			$hostInfo = parse_url($host);
1345
-			if(!(is_array($hostInfo)
1346
-				&& isset($hostInfo['scheme'])
1347
-				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348
-				$portSettings[] = ['port' => $port, 'tls' => true];
1349
-			}
1350
-			$portSettings[] =['port' => $port, 'tls' => false];
1351
-		}
1352
-
1353
-		//default ports
1354
-		$portSettings = array_merge($portSettings,
1355
-									$this->getDefaultLdapPortSettings());
1356
-
1357
-		return $portSettings;
1358
-	}
45
+    /** @var \OCP\IL10N */
46
+    static protected $l;
47
+    protected $access;
48
+    protected $cr;
49
+    protected $configuration;
50
+    protected $result;
51
+    protected $resultCache = [];
52
+
53
+    const LRESULT_PROCESSED_OK = 2;
54
+    const LRESULT_PROCESSED_INVALID = 3;
55
+    const LRESULT_PROCESSED_SKIP = 4;
56
+
57
+    const LFILTER_LOGIN      = 2;
58
+    const LFILTER_USER_LIST  = 3;
59
+    const LFILTER_GROUP_LIST = 4;
60
+
61
+    const LFILTER_MODE_ASSISTED = 2;
62
+    const LFILTER_MODE_RAW = 1;
63
+
64
+    const LDAP_NW_TIMEOUT = 4;
65
+
66
+    /**
67
+     * Constructor
68
+     * @param Configuration $configuration an instance of Configuration
69
+     * @param ILDAPWrapper $ldap an instance of ILDAPWrapper
70
+     * @param Access $access
71
+     */
72
+    public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73
+        parent::__construct($ldap);
74
+        $this->configuration = $configuration;
75
+        if(is_null(Wizard::$l)) {
76
+            Wizard::$l = \OC::$server->getL10N('user_ldap');
77
+        }
78
+        $this->access = $access;
79
+        $this->result = new WizardResult();
80
+    }
81
+
82
+    public function __destruct() {
83
+        if($this->result->hasChanges()) {
84
+            $this->configuration->saveConfiguration();
85
+        }
86
+    }
87
+
88
+    /**
89
+     * counts entries in the LDAP directory
90
+     *
91
+     * @param string $filter the LDAP search filter
92
+     * @param string $type a string being either 'users' or 'groups';
93
+     * @return int
94
+     * @throws \Exception
95
+     */
96
+    public function countEntries(string $filter, string $type): int {
97
+        $reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
+        if($type === 'users') {
99
+            $reqs[] = 'ldapUserFilter';
100
+        }
101
+        if(!$this->checkRequirements($reqs)) {
102
+            throw new \Exception('Requirements not met', 400);
103
+        }
104
+
105
+        $attr = ['dn']; // default
106
+        $limit = 1001;
107
+        if($type === 'groups') {
108
+            $result =  $this->access->countGroups($filter, $attr, $limit);
109
+        } else if($type === 'users') {
110
+            $result = $this->access->countUsers($filter, $attr, $limit);
111
+        } else if ($type === 'objects') {
112
+            $result = $this->access->countObjects($limit);
113
+        } else {
114
+            throw new \Exception('Internal error: Invalid object type', 500);
115
+        }
116
+
117
+        return (int)$result;
118
+    }
119
+
120
+    /**
121
+     * formats the return value of a count operation to the string to be
122
+     * inserted.
123
+     *
124
+     * @param int $count
125
+     * @return string
126
+     */
127
+    private function formatCountResult(int $count): string {
128
+        if($count > 1000) {
129
+            return '> 1000';
130
+        }
131
+        return (string)$count;
132
+    }
133
+
134
+    public function countGroups() {
135
+        $filter = $this->configuration->ldapGroupFilter;
136
+
137
+        if(empty($filter)) {
138
+            $output = self::$l->n('%s group found', '%s groups found', 0, [0]);
139
+            $this->result->addChange('ldap_group_count', $output);
140
+            return $this->result;
141
+        }
142
+
143
+        try {
144
+            $groupsTotal = $this->countEntries($filter, 'groups');
145
+        } catch (\Exception $e) {
146
+            //400 can be ignored, 500 is forwarded
147
+            if($e->getCode() === 500) {
148
+                throw $e;
149
+            }
150
+            return false;
151
+        }
152
+        $output = self::$l->n(
153
+            '%s group found',
154
+            '%s groups found',
155
+            $groupsTotal,
156
+            [$this->formatCountResult($groupsTotal)]
157
+        );
158
+        $this->result->addChange('ldap_group_count', $output);
159
+        return $this->result;
160
+    }
161
+
162
+    /**
163
+     * @return WizardResult
164
+     * @throws \Exception
165
+     */
166
+    public function countUsers() {
167
+        $filter = $this->access->getFilterForUserCount();
168
+
169
+        $usersTotal = $this->countEntries($filter, 'users');
170
+        $output = self::$l->n(
171
+            '%s user found',
172
+            '%s users found',
173
+            $usersTotal,
174
+            [$this->formatCountResult($usersTotal)]
175
+        );
176
+        $this->result->addChange('ldap_user_count', $output);
177
+        return $this->result;
178
+    }
179
+
180
+    /**
181
+     * counts any objects in the currently set base dn
182
+     *
183
+     * @return WizardResult
184
+     * @throws \Exception
185
+     */
186
+    public function countInBaseDN() {
187
+        // we don't need to provide a filter in this case
188
+        $total = $this->countEntries('', 'objects');
189
+        if($total === false) {
190
+            throw new \Exception('invalid results received');
191
+        }
192
+        $this->result->addChange('ldap_test_base', $total);
193
+        return $this->result;
194
+    }
195
+
196
+    /**
197
+     * counts users with a specified attribute
198
+     * @param string $attr
199
+     * @param bool $existsCheck
200
+     * @return int|bool
201
+     */
202
+    public function countUsersWithAttribute($attr, $existsCheck = false) {
203
+        if(!$this->checkRequirements(['ldapHost',
204
+            'ldapPort',
205
+            'ldapBase',
206
+            'ldapUserFilter',
207
+        ])) {
208
+            return  false;
209
+        }
210
+
211
+        $filter = $this->access->combineFilterWithAnd([
212
+            $this->configuration->ldapUserFilter,
213
+            $attr . '=*'
214
+        ]);
215
+
216
+        $limit = ($existsCheck === false) ? null : 1;
217
+
218
+        return $this->access->countUsers($filter, ['dn'], $limit);
219
+    }
220
+
221
+    /**
222
+     * detects the display name attribute. If a setting is already present that
223
+     * returns at least one hit, the detection will be canceled.
224
+     * @return WizardResult|bool
225
+     * @throws \Exception
226
+     */
227
+    public function detectUserDisplayNameAttribute() {
228
+        if(!$this->checkRequirements(['ldapHost',
229
+            'ldapPort',
230
+            'ldapBase',
231
+            'ldapUserFilter',
232
+        ])) {
233
+            return  false;
234
+        }
235
+
236
+        $attr = $this->configuration->ldapUserDisplayName;
237
+        if ($attr !== '' && $attr !== 'displayName') {
238
+            // most likely not the default value with upper case N,
239
+            // verify it still produces a result
240
+            $count = (int)$this->countUsersWithAttribute($attr, true);
241
+            if($count > 0) {
242
+                //no change, but we sent it back to make sure the user interface
243
+                //is still correct, even if the ajax call was cancelled meanwhile
244
+                $this->result->addChange('ldap_display_name', $attr);
245
+                return $this->result;
246
+            }
247
+        }
248
+
249
+        // first attribute that has at least one result wins
250
+        $displayNameAttrs = ['displayname', 'cn'];
251
+        foreach ($displayNameAttrs as $attr) {
252
+            $count = (int)$this->countUsersWithAttribute($attr, true);
253
+
254
+            if($count > 0) {
255
+                $this->applyFind('ldap_display_name', $attr);
256
+                return $this->result;
257
+            }
258
+        }
259
+
260
+        throw new \Exception(self::$l->t('Could not detect user display name attribute. Please specify it yourself in advanced LDAP settings.'));
261
+    }
262
+
263
+    /**
264
+     * detects the most often used email attribute for users applying to the
265
+     * user list filter. If a setting is already present that returns at least
266
+     * one hit, the detection will be canceled.
267
+     * @return WizardResult|bool
268
+     */
269
+    public function detectEmailAttribute() {
270
+        if(!$this->checkRequirements(['ldapHost',
271
+            'ldapPort',
272
+            'ldapBase',
273
+            'ldapUserFilter',
274
+        ])) {
275
+            return  false;
276
+        }
277
+
278
+        $attr = $this->configuration->ldapEmailAttribute;
279
+        if ($attr !== '') {
280
+            $count = (int)$this->countUsersWithAttribute($attr, true);
281
+            if($count > 0) {
282
+                return false;
283
+            }
284
+            $writeLog = true;
285
+        } else {
286
+            $writeLog = false;
287
+        }
288
+
289
+        $emailAttributes = ['mail', 'mailPrimaryAddress'];
290
+        $winner = '';
291
+        $maxUsers = 0;
292
+        foreach($emailAttributes as $attr) {
293
+            $count = $this->countUsersWithAttribute($attr);
294
+            if($count > $maxUsers) {
295
+                $maxUsers = $count;
296
+                $winner = $attr;
297
+            }
298
+        }
299
+
300
+        if($winner !== '') {
301
+            $this->applyFind('ldap_email_attr', $winner);
302
+            if($writeLog) {
303
+                \OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
+                    'automatically been reset, because the original value ' .
305
+                    'did not return any results.', ILogger::INFO);
306
+            }
307
+        }
308
+
309
+        return $this->result;
310
+    }
311
+
312
+    /**
313
+     * @return WizardResult
314
+     * @throws \Exception
315
+     */
316
+    public function determineAttributes() {
317
+        if(!$this->checkRequirements(['ldapHost',
318
+            'ldapPort',
319
+            'ldapBase',
320
+            'ldapUserFilter',
321
+        ])) {
322
+            return  false;
323
+        }
324
+
325
+        $attributes = $this->getUserAttributes();
326
+
327
+        natcasesort($attributes);
328
+        $attributes = array_values($attributes);
329
+
330
+        $this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331
+
332
+        $selected = $this->configuration->ldapLoginFilterAttributes;
333
+        if(is_array($selected) && !empty($selected)) {
334
+            $this->result->addChange('ldap_loginfilter_attributes', $selected);
335
+        }
336
+
337
+        return $this->result;
338
+    }
339
+
340
+    /**
341
+     * detects the available LDAP attributes
342
+     * @return array|false The instance's WizardResult instance
343
+     * @throws \Exception
344
+     */
345
+    private function getUserAttributes() {
346
+        if(!$this->checkRequirements(['ldapHost',
347
+            'ldapPort',
348
+            'ldapBase',
349
+            'ldapUserFilter',
350
+        ])) {
351
+            return  false;
352
+        }
353
+        $cr = $this->getConnection();
354
+        if(!$cr) {
355
+            throw new \Exception('Could not connect to LDAP');
356
+        }
357
+
358
+        $base = $this->configuration->ldapBase[0];
359
+        $filter = $this->configuration->ldapUserFilter;
360
+        $rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
361
+        if(!$this->ldap->isResource($rr)) {
362
+            return false;
363
+        }
364
+        $er = $this->ldap->firstEntry($cr, $rr);
365
+        $attributes = $this->ldap->getAttributes($cr, $er);
366
+        $pureAttributes = [];
367
+        for($i = 0; $i < $attributes['count']; $i++) {
368
+            $pureAttributes[] = $attributes[$i];
369
+        }
370
+
371
+        return $pureAttributes;
372
+    }
373
+
374
+    /**
375
+     * detects the available LDAP groups
376
+     * @return WizardResult|false the instance's WizardResult instance
377
+     */
378
+    public function determineGroupsForGroups() {
379
+        return $this->determineGroups('ldap_groupfilter_groups',
380
+                                        'ldapGroupFilterGroups',
381
+                                        false);
382
+    }
383
+
384
+    /**
385
+     * detects the available LDAP groups
386
+     * @return WizardResult|false the instance's WizardResult instance
387
+     */
388
+    public function determineGroupsForUsers() {
389
+        return $this->determineGroups('ldap_userfilter_groups',
390
+                                        'ldapUserFilterGroups');
391
+    }
392
+
393
+    /**
394
+     * detects the available LDAP groups
395
+     * @param string $dbKey
396
+     * @param string $confKey
397
+     * @param bool $testMemberOf
398
+     * @return WizardResult|false the instance's WizardResult instance
399
+     * @throws \Exception
400
+     */
401
+    private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
+        if(!$this->checkRequirements(['ldapHost',
403
+            'ldapPort',
404
+            'ldapBase',
405
+        ])) {
406
+            return  false;
407
+        }
408
+        $cr = $this->getConnection();
409
+        if(!$cr) {
410
+            throw new \Exception('Could not connect to LDAP');
411
+        }
412
+
413
+        $this->fetchGroups($dbKey, $confKey);
414
+
415
+        if($testMemberOf) {
416
+            $this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417
+            $this->result->markChange();
418
+            if(!$this->configuration->hasMemberOfFilterSupport) {
419
+                throw new \Exception('memberOf is not supported by the server');
420
+            }
421
+        }
422
+
423
+        return $this->result;
424
+    }
425
+
426
+    /**
427
+     * fetches all groups from LDAP and adds them to the result object
428
+     *
429
+     * @param string $dbKey
430
+     * @param string $confKey
431
+     * @return array $groupEntries
432
+     * @throws \Exception
433
+     */
434
+    public function fetchGroups($dbKey, $confKey) {
435
+        $obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
436
+
437
+        $filterParts = [];
438
+        foreach($obclasses as $obclass) {
439
+            $filterParts[] = 'objectclass='.$obclass;
440
+        }
441
+        //we filter for everything
442
+        //- that looks like a group and
443
+        //- has the group display name set
444
+        $filter = $this->access->combineFilterWithOr($filterParts);
445
+        $filter = $this->access->combineFilterWithAnd([$filter, 'cn=*']);
446
+
447
+        $groupNames = [];
448
+        $groupEntries = [];
449
+        $limit = 400;
450
+        $offset = 0;
451
+        do {
452
+            // we need to request dn additionally here, otherwise memberOf
453
+            // detection will fail later
454
+            $result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
455
+            foreach($result as $item) {
456
+                if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457
+                    // just in case - no issue known
458
+                    continue;
459
+                }
460
+                $groupNames[] = $item['cn'][0];
461
+                $groupEntries[] = $item;
462
+            }
463
+            $offset += $limit;
464
+        } while ($this->access->hasMoreResults());
465
+
466
+        if(count($groupNames) > 0) {
467
+            natsort($groupNames);
468
+            $this->result->addOptions($dbKey, array_values($groupNames));
469
+        } else {
470
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
471
+        }
472
+
473
+        $setFeatures = $this->configuration->$confKey;
474
+        if(is_array($setFeatures) && !empty($setFeatures)) {
475
+            //something is already configured? pre-select it.
476
+            $this->result->addChange($dbKey, $setFeatures);
477
+        }
478
+        return $groupEntries;
479
+    }
480
+
481
+    public function determineGroupMemberAssoc() {
482
+        if(!$this->checkRequirements(['ldapHost',
483
+            'ldapPort',
484
+            'ldapGroupFilter',
485
+        ])) {
486
+            return  false;
487
+        }
488
+        $attribute = $this->detectGroupMemberAssoc();
489
+        if($attribute === false) {
490
+            return false;
491
+        }
492
+        $this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
493
+        $this->result->addChange('ldap_group_member_assoc_attribute', $attribute);
494
+
495
+        return $this->result;
496
+    }
497
+
498
+    /**
499
+     * Detects the available object classes
500
+     * @return WizardResult|false the instance's WizardResult instance
501
+     * @throws \Exception
502
+     */
503
+    public function determineGroupObjectClasses() {
504
+        if(!$this->checkRequirements(['ldapHost',
505
+            'ldapPort',
506
+            'ldapBase',
507
+        ])) {
508
+            return  false;
509
+        }
510
+        $cr = $this->getConnection();
511
+        if(!$cr) {
512
+            throw new \Exception('Could not connect to LDAP');
513
+        }
514
+
515
+        $obclasses = ['groupOfNames', 'groupOfUniqueNames', 'group', 'posixGroup', '*'];
516
+        $this->determineFeature($obclasses,
517
+                                'objectclass',
518
+                                'ldap_groupfilter_objectclass',
519
+                                'ldapGroupFilterObjectclass',
520
+                                false);
521
+
522
+        return $this->result;
523
+    }
524
+
525
+    /**
526
+     * detects the available object classes
527
+     * @return WizardResult
528
+     * @throws \Exception
529
+     */
530
+    public function determineUserObjectClasses() {
531
+        if(!$this->checkRequirements(['ldapHost',
532
+            'ldapPort',
533
+            'ldapBase',
534
+        ])) {
535
+            return  false;
536
+        }
537
+        $cr = $this->getConnection();
538
+        if(!$cr) {
539
+            throw new \Exception('Could not connect to LDAP');
540
+        }
541
+
542
+        $obclasses = ['inetOrgPerson', 'person', 'organizationalPerson',
543
+            'user', 'posixAccount', '*'];
544
+        $filter = $this->configuration->ldapUserFilter;
545
+        //if filter is empty, it is probably the first time the wizard is called
546
+        //then, apply suggestions.
547
+        $this->determineFeature($obclasses,
548
+                                'objectclass',
549
+                                'ldap_userfilter_objectclass',
550
+                                'ldapUserFilterObjectclass',
551
+                                empty($filter));
552
+
553
+        return $this->result;
554
+    }
555
+
556
+    /**
557
+     * @return WizardResult|false
558
+     * @throws \Exception
559
+     */
560
+    public function getGroupFilter() {
561
+        if(!$this->checkRequirements(['ldapHost',
562
+            'ldapPort',
563
+            'ldapBase',
564
+        ])) {
565
+            return false;
566
+        }
567
+        //make sure the use display name is set
568
+        $displayName = $this->configuration->ldapGroupDisplayName;
569
+        if ($displayName === '') {
570
+            $d = $this->configuration->getDefaults();
571
+            $this->applyFind('ldap_group_display_name',
572
+                                $d['ldap_group_display_name']);
573
+        }
574
+        $filter = $this->composeLdapFilter(self::LFILTER_GROUP_LIST);
575
+
576
+        $this->applyFind('ldap_group_filter', $filter);
577
+        return $this->result;
578
+    }
579
+
580
+    /**
581
+     * @return WizardResult|false
582
+     * @throws \Exception
583
+     */
584
+    public function getUserListFilter() {
585
+        if(!$this->checkRequirements(['ldapHost',
586
+            'ldapPort',
587
+            'ldapBase',
588
+        ])) {
589
+            return false;
590
+        }
591
+        //make sure the use display name is set
592
+        $displayName = $this->configuration->ldapUserDisplayName;
593
+        if ($displayName === '') {
594
+            $d = $this->configuration->getDefaults();
595
+            $this->applyFind('ldap_display_name', $d['ldap_display_name']);
596
+        }
597
+        $filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
+        if(!$filter) {
599
+            throw new \Exception('Cannot create filter');
600
+        }
601
+
602
+        $this->applyFind('ldap_userlist_filter', $filter);
603
+        return $this->result;
604
+    }
605
+
606
+    /**
607
+     * @return bool|WizardResult
608
+     * @throws \Exception
609
+     */
610
+    public function getUserLoginFilter() {
611
+        if(!$this->checkRequirements(['ldapHost',
612
+            'ldapPort',
613
+            'ldapBase',
614
+            'ldapUserFilter',
615
+        ])) {
616
+            return false;
617
+        }
618
+
619
+        $filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
+        if(!$filter) {
621
+            throw new \Exception('Cannot create filter');
622
+        }
623
+
624
+        $this->applyFind('ldap_login_filter', $filter);
625
+        return $this->result;
626
+    }
627
+
628
+    /**
629
+     * @return bool|WizardResult
630
+     * @param string $loginName
631
+     * @throws \Exception
632
+     */
633
+    public function testLoginName($loginName) {
634
+        if(!$this->checkRequirements(['ldapHost',
635
+            'ldapPort',
636
+            'ldapBase',
637
+            'ldapLoginFilter',
638
+        ])) {
639
+            return false;
640
+        }
641
+
642
+        $cr = $this->access->connection->getConnectionResource();
643
+        if(!$this->ldap->isResource($cr)) {
644
+            throw new \Exception('connection error');
645
+        }
646
+
647
+        if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648
+            === false) {
649
+            throw new \Exception('missing placeholder');
650
+        }
651
+
652
+        $users = $this->access->countUsersByLoginName($loginName);
653
+        if($this->ldap->errno($cr) !== 0) {
654
+            throw new \Exception($this->ldap->error($cr));
655
+        }
656
+        $filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
657
+        $this->result->addChange('ldap_test_loginname', $users);
658
+        $this->result->addChange('ldap_test_effective_filter', $filter);
659
+        return $this->result;
660
+    }
661
+
662
+    /**
663
+     * Tries to determine the port, requires given Host, User DN and Password
664
+     * @return WizardResult|false WizardResult on success, false otherwise
665
+     * @throws \Exception
666
+     */
667
+    public function guessPortAndTLS() {
668
+        if(!$this->checkRequirements(['ldapHost',
669
+        ])) {
670
+            return false;
671
+        }
672
+        $this->checkHost();
673
+        $portSettings = $this->getPortSettingsToTry();
674
+
675
+        if(!is_array($portSettings)) {
676
+            throw new \Exception(print_r($portSettings, true));
677
+        }
678
+
679
+        //proceed from the best configuration and return on first success
680
+        foreach($portSettings as $setting) {
681
+            $p = $setting['port'];
682
+            $t = $setting['tls'];
683
+            \OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
684
+            //connectAndBind may throw Exception, it needs to be catched by the
685
+            //callee of this method
686
+
687
+            try {
688
+                $settingsFound = $this->connectAndBind($p, $t);
689
+            } catch (\Exception $e) {
690
+                // any reply other than -1 (= cannot connect) is already okay,
691
+                // because then we found the server
692
+                // unavailable startTLS returns -11
693
+                if($e->getCode() > 0) {
694
+                    $settingsFound = true;
695
+                } else {
696
+                    throw $e;
697
+                }
698
+            }
699
+
700
+            if ($settingsFound === true) {
701
+                $config = [
702
+                    'ldapPort' => $p,
703
+                    'ldapTLS' => (int)$t
704
+                ];
705
+                $this->configuration->setConfiguration($config);
706
+                \OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
707
+                $this->result->addChange('ldap_port', $p);
708
+                return $this->result;
709
+            }
710
+        }
711
+
712
+        //custom port, undetected (we do not brute force)
713
+        return false;
714
+    }
715
+
716
+    /**
717
+     * tries to determine a base dn from User DN or LDAP Host
718
+     * @return WizardResult|false WizardResult on success, false otherwise
719
+     */
720
+    public function guessBaseDN() {
721
+        if(!$this->checkRequirements(['ldapHost',
722
+            'ldapPort',
723
+        ])) {
724
+            return false;
725
+        }
726
+
727
+        //check whether a DN is given in the agent name (99.9% of all cases)
728
+        $base = null;
729
+        $i = stripos($this->configuration->ldapAgentName, 'dc=');
730
+        if($i !== false) {
731
+            $base = substr($this->configuration->ldapAgentName, $i);
732
+            if($this->testBaseDN($base)) {
733
+                $this->applyFind('ldap_base', $base);
734
+                return $this->result;
735
+            }
736
+        }
737
+
738
+        //this did not help :(
739
+        //Let's see whether we can parse the Host URL and convert the domain to
740
+        //a base DN
741
+        $helper = new Helper(\OC::$server->getConfig());
742
+        $domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
+        if(!$domain) {
744
+            return false;
745
+        }
746
+
747
+        $dparts = explode('.', $domain);
748
+        while(count($dparts) > 0) {
749
+            $base2 = 'dc=' . implode(',dc=', $dparts);
750
+            if ($base !== $base2 && $this->testBaseDN($base2)) {
751
+                $this->applyFind('ldap_base', $base2);
752
+                return $this->result;
753
+            }
754
+            array_shift($dparts);
755
+        }
756
+
757
+        return false;
758
+    }
759
+
760
+    /**
761
+     * sets the found value for the configuration key in the WizardResult
762
+     * as well as in the Configuration instance
763
+     * @param string $key the configuration key
764
+     * @param string $value the (detected) value
765
+     *
766
+     */
767
+    private function applyFind($key, $value) {
768
+        $this->result->addChange($key, $value);
769
+        $this->configuration->setConfiguration([$key => $value]);
770
+    }
771
+
772
+    /**
773
+     * Checks, whether a port was entered in the Host configuration
774
+     * field. In this case the port will be stripped off, but also stored as
775
+     * setting.
776
+     */
777
+    private function checkHost() {
778
+        $host = $this->configuration->ldapHost;
779
+        $hostInfo = parse_url($host);
780
+
781
+        //removes Port from Host
782
+        if(is_array($hostInfo) && isset($hostInfo['port'])) {
783
+            $port = $hostInfo['port'];
784
+            $host = str_replace(':'.$port, '', $host);
785
+            $this->applyFind('ldap_host', $host);
786
+            $this->applyFind('ldap_port', $port);
787
+        }
788
+    }
789
+
790
+    /**
791
+     * tries to detect the group member association attribute which is
792
+     * one of 'uniqueMember', 'memberUid', 'member', 'gidNumber'
793
+     * @return string|false, string with the attribute name, false on error
794
+     * @throws \Exception
795
+     */
796
+    private function detectGroupMemberAssoc() {
797
+        $possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber'];
798
+        $filter = $this->configuration->ldapGroupFilter;
799
+        if(empty($filter)) {
800
+            return false;
801
+        }
802
+        $cr = $this->getConnection();
803
+        if(!$cr) {
804
+            throw new \Exception('Could not connect to LDAP');
805
+        }
806
+        $base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
807
+        $rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
+        if(!$this->ldap->isResource($rr)) {
809
+            return false;
810
+        }
811
+        $er = $this->ldap->firstEntry($cr, $rr);
812
+        while(is_resource($er)) {
813
+            $this->ldap->getDN($cr, $er);
814
+            $attrs = $this->ldap->getAttributes($cr, $er);
815
+            $result = [];
816
+            $possibleAttrsCount = count($possibleAttrs);
817
+            for($i = 0; $i < $possibleAttrsCount; $i++) {
818
+                if(isset($attrs[$possibleAttrs[$i]])) {
819
+                    $result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820
+                }
821
+            }
822
+            if(!empty($result)) {
823
+                natsort($result);
824
+                return key($result);
825
+            }
826
+
827
+            $er = $this->ldap->nextEntry($cr, $er);
828
+        }
829
+
830
+        return false;
831
+    }
832
+
833
+    /**
834
+     * Checks whether for a given BaseDN results will be returned
835
+     * @param string $base the BaseDN to test
836
+     * @return bool true on success, false otherwise
837
+     * @throws \Exception
838
+     */
839
+    private function testBaseDN($base) {
840
+        $cr = $this->getConnection();
841
+        if(!$cr) {
842
+            throw new \Exception('Could not connect to LDAP');
843
+        }
844
+
845
+        //base is there, let's validate it. If we search for anything, we should
846
+        //get a result set > 0 on a proper base
847
+        $rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
848
+        if(!$this->ldap->isResource($rr)) {
849
+            $errorNo  = $this->ldap->errno($cr);
850
+            $errorMsg = $this->ldap->error($cr);
851
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
852
+                            ' Error '.$errorNo.': '.$errorMsg, ILogger::INFO);
853
+            return false;
854
+        }
855
+        $entries = $this->ldap->countEntries($cr, $rr);
856
+        return ($entries !== false) && ($entries > 0);
857
+    }
858
+
859
+    /**
860
+     * Checks whether the server supports memberOf in LDAP Filter.
861
+     * Note: at least in OpenLDAP, availability of memberOf is dependent on
862
+     * a configured objectClass. I.e. not necessarily for all available groups
863
+     * memberOf does work.
864
+     *
865
+     * @return bool true if it does, false otherwise
866
+     * @throws \Exception
867
+     */
868
+    private function testMemberOf() {
869
+        $cr = $this->getConnection();
870
+        if(!$cr) {
871
+            throw new \Exception('Could not connect to LDAP');
872
+        }
873
+        $result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
874
+        if(is_int($result) &&  $result > 0) {
875
+            return true;
876
+        }
877
+        return false;
878
+    }
879
+
880
+    /**
881
+     * creates an LDAP Filter from given configuration
882
+     * @param integer $filterType int, for which use case the filter shall be created
883
+     * can be any of self::LFILTER_USER_LIST, self::LFILTER_LOGIN or
884
+     * self::LFILTER_GROUP_LIST
885
+     * @return string|false string with the filter on success, false otherwise
886
+     * @throws \Exception
887
+     */
888
+    private function composeLdapFilter($filterType) {
889
+        $filter = '';
890
+        $parts = 0;
891
+        switch ($filterType) {
892
+            case self::LFILTER_USER_LIST:
893
+                $objcs = $this->configuration->ldapUserFilterObjectclass;
894
+                //glue objectclasses
895
+                if(is_array($objcs) && count($objcs) > 0) {
896
+                    $filter .= '(|';
897
+                    foreach($objcs as $objc) {
898
+                        $filter .= '(objectclass=' . $objc . ')';
899
+                    }
900
+                    $filter .= ')';
901
+                    $parts++;
902
+                }
903
+                //glue group memberships
904
+                if($this->configuration->hasMemberOfFilterSupport) {
905
+                    $cns = $this->configuration->ldapUserFilterGroups;
906
+                    if(is_array($cns) && count($cns) > 0) {
907
+                        $filter .= '(|';
908
+                        $cr = $this->getConnection();
909
+                        if(!$cr) {
910
+                            throw new \Exception('Could not connect to LDAP');
911
+                        }
912
+                        $base = $this->configuration->ldapBase[0];
913
+                        foreach($cns as $cn) {
914
+                            $rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']);
915
+                            if(!$this->ldap->isResource($rr)) {
916
+                                continue;
917
+                            }
918
+                            $er = $this->ldap->firstEntry($cr, $rr);
919
+                            $attrs = $this->ldap->getAttributes($cr, $er);
920
+                            $dn = $this->ldap->getDN($cr, $er);
921
+                            if ($dn === false || $dn === '') {
922
+                                continue;
923
+                            }
924
+                            $filterPart = '(memberof=' . $dn . ')';
925
+                            if(isset($attrs['primaryGroupToken'])) {
926
+                                $pgt = $attrs['primaryGroupToken'][0];
927
+                                $primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
+                                $filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
929
+                            }
930
+                            $filter .= $filterPart;
931
+                        }
932
+                        $filter .= ')';
933
+                    }
934
+                    $parts++;
935
+                }
936
+                //wrap parts in AND condition
937
+                if($parts > 1) {
938
+                    $filter = '(&' . $filter . ')';
939
+                }
940
+                if ($filter === '') {
941
+                    $filter = '(objectclass=*)';
942
+                }
943
+                break;
944
+
945
+            case self::LFILTER_GROUP_LIST:
946
+                $objcs = $this->configuration->ldapGroupFilterObjectclass;
947
+                //glue objectclasses
948
+                if(is_array($objcs) && count($objcs) > 0) {
949
+                    $filter .= '(|';
950
+                    foreach($objcs as $objc) {
951
+                        $filter .= '(objectclass=' . $objc . ')';
952
+                    }
953
+                    $filter .= ')';
954
+                    $parts++;
955
+                }
956
+                //glue group memberships
957
+                $cns = $this->configuration->ldapGroupFilterGroups;
958
+                if(is_array($cns) && count($cns) > 0) {
959
+                    $filter .= '(|';
960
+                    foreach($cns as $cn) {
961
+                        $filter .= '(cn=' . $cn . ')';
962
+                    }
963
+                    $filter .= ')';
964
+                }
965
+                $parts++;
966
+                //wrap parts in AND condition
967
+                if($parts > 1) {
968
+                    $filter = '(&' . $filter . ')';
969
+                }
970
+                break;
971
+
972
+            case self::LFILTER_LOGIN:
973
+                $ulf = $this->configuration->ldapUserFilter;
974
+                $loginpart = '=%uid';
975
+                $filterUsername = '';
976
+                $userAttributes = $this->getUserAttributes();
977
+                $userAttributes = array_change_key_case(array_flip($userAttributes));
978
+                $parts = 0;
979
+
980
+                if($this->configuration->ldapLoginFilterUsername === '1') {
981
+                    $attr = '';
982
+                    if(isset($userAttributes['uid'])) {
983
+                        $attr = 'uid';
984
+                    } else if(isset($userAttributes['samaccountname'])) {
985
+                        $attr = 'samaccountname';
986
+                    } else if(isset($userAttributes['cn'])) {
987
+                        //fallback
988
+                        $attr = 'cn';
989
+                    }
990
+                    if ($attr !== '') {
991
+                        $filterUsername = '(' . $attr . $loginpart . ')';
992
+                        $parts++;
993
+                    }
994
+                }
995
+
996
+                $filterEmail = '';
997
+                if($this->configuration->ldapLoginFilterEmail === '1') {
998
+                    $filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999
+                    $parts++;
1000
+                }
1001
+
1002
+                $filterAttributes = '';
1003
+                $attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
+                if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005
+                    $filterAttributes = '(|';
1006
+                    foreach($attrsToFilter as $attribute) {
1007
+                        $filterAttributes .= '(' . $attribute . $loginpart . ')';
1008
+                    }
1009
+                    $filterAttributes .= ')';
1010
+                    $parts++;
1011
+                }
1012
+
1013
+                $filterLogin = '';
1014
+                if($parts > 1) {
1015
+                    $filterLogin = '(|';
1016
+                }
1017
+                $filterLogin .= $filterUsername;
1018
+                $filterLogin .= $filterEmail;
1019
+                $filterLogin .= $filterAttributes;
1020
+                if($parts > 1) {
1021
+                    $filterLogin .= ')';
1022
+                }
1023
+
1024
+                $filter = '(&'.$ulf.$filterLogin.')';
1025
+                break;
1026
+        }
1027
+
1028
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Final filter '.$filter, ILogger::DEBUG);
1029
+
1030
+        return $filter;
1031
+    }
1032
+
1033
+    /**
1034
+     * Connects and Binds to an LDAP Server
1035
+     *
1036
+     * @param int $port the port to connect with
1037
+     * @param bool $tls whether startTLS is to be used
1038
+     * @return bool
1039
+     * @throws \Exception
1040
+     */
1041
+    private function connectAndBind($port, $tls) {
1042
+        //connect, does not really trigger any server communication
1043
+        $host = $this->configuration->ldapHost;
1044
+        $hostInfo = parse_url($host);
1045
+        if(!$hostInfo) {
1046
+            throw new \Exception(self::$l->t('Invalid Host'));
1047
+        }
1048
+        \OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049
+        $cr = $this->ldap->connect($host, $port);
1050
+        if(!is_resource($cr)) {
1051
+            throw new \Exception(self::$l->t('Invalid Host'));
1052
+        }
1053
+
1054
+        //set LDAP options
1055
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1056
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1057
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058
+
1059
+        try {
1060
+            if($tls) {
1061
+                $isTlsWorking = @$this->ldap->startTls($cr);
1062
+                if(!$isTlsWorking) {
1063
+                    return false;
1064
+                }
1065
+            }
1066
+
1067
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Attemping to Bind ', ILogger::DEBUG);
1068
+            //interesting part: do the bind!
1069
+            $login = $this->ldap->bind($cr,
1070
+                $this->configuration->ldapAgentName,
1071
+                $this->configuration->ldapAgentPassword
1072
+            );
1073
+            $errNo = $this->ldap->errno($cr);
1074
+            $error = ldap_error($cr);
1075
+            $this->ldap->unbind($cr);
1076
+        } catch(ServerNotAvailableException $e) {
1077
+            return false;
1078
+        }
1079
+
1080
+        if($login === true) {
1081
+            $this->ldap->unbind($cr);
1082
+            \OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1083
+            return true;
1084
+        }
1085
+
1086
+        if($errNo === -1) {
1087
+            //host, port or TLS wrong
1088
+            return false;
1089
+        }
1090
+        throw new \Exception($error, $errNo);
1091
+    }
1092
+
1093
+    /**
1094
+     * checks whether a valid combination of agent and password has been
1095
+     * provided (either two values or nothing for anonymous connect)
1096
+     * @return bool, true if everything is fine, false otherwise
1097
+     */
1098
+    private function checkAgentRequirements() {
1099
+        $agent = $this->configuration->ldapAgentName;
1100
+        $pwd = $this->configuration->ldapAgentPassword;
1101
+
1102
+        return
1103
+            ($agent !== '' && $pwd !== '')
1104
+            ||  ($agent === '' && $pwd === '')
1105
+        ;
1106
+    }
1107
+
1108
+    /**
1109
+     * @param array $reqs
1110
+     * @return bool
1111
+     */
1112
+    private function checkRequirements($reqs) {
1113
+        $this->checkAgentRequirements();
1114
+        foreach($reqs as $option) {
1115
+            $value = $this->configuration->$option;
1116
+            if(empty($value)) {
1117
+                return false;
1118
+            }
1119
+        }
1120
+        return true;
1121
+    }
1122
+
1123
+    /**
1124
+     * does a cumulativeSearch on LDAP to get different values of a
1125
+     * specified attribute
1126
+     * @param string[] $filters array, the filters that shall be used in the search
1127
+     * @param string $attr the attribute of which a list of values shall be returned
1128
+     * @param int $dnReadLimit the amount of how many DNs should be analyzed.
1129
+     * The lower, the faster
1130
+     * @param string $maxF string. if not null, this variable will have the filter that
1131
+     * yields most result entries
1132
+     * @return array|false an array with the values on success, false otherwise
1133
+     */
1134
+    public function cumulativeSearchOnAttribute($filters, $attr, $dnReadLimit = 3, &$maxF = null) {
1135
+        $dnRead = [];
1136
+        $foundItems = [];
1137
+        $maxEntries = 0;
1138
+        if(!is_array($this->configuration->ldapBase)
1139
+           || !isset($this->configuration->ldapBase[0])) {
1140
+            return false;
1141
+        }
1142
+        $base = $this->configuration->ldapBase[0];
1143
+        $cr = $this->getConnection();
1144
+        if(!$this->ldap->isResource($cr)) {
1145
+            return false;
1146
+        }
1147
+        $lastFilter = null;
1148
+        if(isset($filters[count($filters)-1])) {
1149
+            $lastFilter = $filters[count($filters)-1];
1150
+        }
1151
+        foreach($filters as $filter) {
1152
+            if($lastFilter === $filter && count($foundItems) > 0) {
1153
+                //skip when the filter is a wildcard and results were found
1154
+                continue;
1155
+            }
1156
+            // 20k limit for performance and reason
1157
+            $rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
1158
+            if(!$this->ldap->isResource($rr)) {
1159
+                continue;
1160
+            }
1161
+            $entries = $this->ldap->countEntries($cr, $rr);
1162
+            $getEntryFunc = 'firstEntry';
1163
+            if(($entries !== false) && ($entries > 0)) {
1164
+                if(!is_null($maxF) && $entries > $maxEntries) {
1165
+                    $maxEntries = $entries;
1166
+                    $maxF = $filter;
1167
+                }
1168
+                $dnReadCount = 0;
1169
+                do {
1170
+                    $entry = $this->ldap->$getEntryFunc($cr, $rr);
1171
+                    $getEntryFunc = 'nextEntry';
1172
+                    if(!$this->ldap->isResource($entry)) {
1173
+                        continue 2;
1174
+                    }
1175
+                    $rr = $entry; //will be expected by nextEntry next round
1176
+                    $attributes = $this->ldap->getAttributes($cr, $entry);
1177
+                    $dn = $this->ldap->getDN($cr, $entry);
1178
+                    if($dn === false || in_array($dn, $dnRead)) {
1179
+                        continue;
1180
+                    }
1181
+                    $newItems = [];
1182
+                    $state = $this->getAttributeValuesFromEntry($attributes,
1183
+                                                                $attr,
1184
+                                                                $newItems);
1185
+                    $dnReadCount++;
1186
+                    $foundItems = array_merge($foundItems, $newItems);
1187
+                    $this->resultCache[$dn][$attr] = $newItems;
1188
+                    $dnRead[] = $dn;
1189
+                } while(($state === self::LRESULT_PROCESSED_SKIP
1190
+                        || $this->ldap->isResource($entry))
1191
+                        && ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192
+            }
1193
+        }
1194
+
1195
+        return array_unique($foundItems);
1196
+    }
1197
+
1198
+    /**
1199
+     * determines if and which $attr are available on the LDAP server
1200
+     * @param string[] $objectclasses the objectclasses to use as search filter
1201
+     * @param string $attr the attribute to look for
1202
+     * @param string $dbkey the dbkey of the setting the feature is connected to
1203
+     * @param string $confkey the confkey counterpart for the $dbkey as used in the
1204
+     * Configuration class
1205
+     * @param bool $po whether the objectClass with most result entries
1206
+     * shall be pre-selected via the result
1207
+     * @return array|false list of found items.
1208
+     * @throws \Exception
1209
+     */
1210
+    private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211
+        $cr = $this->getConnection();
1212
+        if(!$cr) {
1213
+            throw new \Exception('Could not connect to LDAP');
1214
+        }
1215
+        $p = 'objectclass=';
1216
+        foreach($objectclasses as $key => $value) {
1217
+            $objectclasses[$key] = $p.$value;
1218
+        }
1219
+        $maxEntryObjC = '';
1220
+
1221
+        //how deep to dig?
1222
+        //When looking for objectclasses, testing few entries is sufficient,
1223
+        $dig = 3;
1224
+
1225
+        $availableFeatures =
1226
+            $this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227
+                                                $dig, $maxEntryObjC);
1228
+        if(is_array($availableFeatures)
1229
+           && count($availableFeatures) > 0) {
1230
+            natcasesort($availableFeatures);
1231
+            //natcasesort keeps indices, but we must get rid of them for proper
1232
+            //sorting in the web UI. Therefore: array_values
1233
+            $this->result->addOptions($dbkey, array_values($availableFeatures));
1234
+        } else {
1235
+            throw new \Exception(self::$l->t('Could not find the desired feature'));
1236
+        }
1237
+
1238
+        $setFeatures = $this->configuration->$confkey;
1239
+        if(is_array($setFeatures) && !empty($setFeatures)) {
1240
+            //something is already configured? pre-select it.
1241
+            $this->result->addChange($dbkey, $setFeatures);
1242
+        } else if ($po && $maxEntryObjC !== '') {
1243
+            //pre-select objectclass with most result entries
1244
+            $maxEntryObjC = str_replace($p, '', $maxEntryObjC);
1245
+            $this->applyFind($dbkey, $maxEntryObjC);
1246
+            $this->result->addChange($dbkey, $maxEntryObjC);
1247
+        }
1248
+
1249
+        return $availableFeatures;
1250
+    }
1251
+
1252
+    /**
1253
+     * appends a list of values fr
1254
+     * @param resource $result the return value from ldap_get_attributes
1255
+     * @param string $attribute the attribute values to look for
1256
+     * @param array &$known new values will be appended here
1257
+     * @return int, state on of the class constants LRESULT_PROCESSED_OK,
1258
+     * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259
+     */
1260
+    private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
+        if(!is_array($result)
1262
+           || !isset($result['count'])
1263
+           || !$result['count'] > 0) {
1264
+            return self::LRESULT_PROCESSED_INVALID;
1265
+        }
1266
+
1267
+        // strtolower on all keys for proper comparison
1268
+        $result = \OCP\Util::mb_array_change_key_case($result);
1269
+        $attribute = strtolower($attribute);
1270
+        if(isset($result[$attribute])) {
1271
+            foreach($result[$attribute] as $key => $val) {
1272
+                if($key === 'count') {
1273
+                    continue;
1274
+                }
1275
+                if(!in_array($val, $known)) {
1276
+                    $known[] = $val;
1277
+                }
1278
+            }
1279
+            return self::LRESULT_PROCESSED_OK;
1280
+        } else {
1281
+            return self::LRESULT_PROCESSED_SKIP;
1282
+        }
1283
+    }
1284
+
1285
+    /**
1286
+     * @return bool|mixed
1287
+     */
1288
+    private function getConnection() {
1289
+        if(!is_null($this->cr)) {
1290
+            return $this->cr;
1291
+        }
1292
+
1293
+        $cr = $this->ldap->connect(
1294
+            $this->configuration->ldapHost,
1295
+            $this->configuration->ldapPort
1296
+        );
1297
+
1298
+        $this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299
+        $this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300
+        $this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
+        if($this->configuration->ldapTLS === 1) {
1302
+            $this->ldap->startTls($cr);
1303
+        }
1304
+
1305
+        $lo = @$this->ldap->bind($cr,
1306
+                                    $this->configuration->ldapAgentName,
1307
+                                    $this->configuration->ldapAgentPassword);
1308
+        if($lo === true) {
1309
+            $this->$cr = $cr;
1310
+            return $cr;
1311
+        }
1312
+
1313
+        return false;
1314
+    }
1315
+
1316
+    /**
1317
+     * @return array
1318
+     */
1319
+    private function getDefaultLdapPortSettings() {
1320
+        static $settings = [
1321
+            ['port' => 7636, 'tls' => false],
1322
+            ['port' =>  636, 'tls' => false],
1323
+            ['port' => 7389, 'tls' => true],
1324
+            ['port' =>  389, 'tls' => true],
1325
+            ['port' => 7389, 'tls' => false],
1326
+            ['port' =>  389, 'tls' => false],
1327
+        ];
1328
+        return $settings;
1329
+    }
1330
+
1331
+    /**
1332
+     * @return array
1333
+     */
1334
+    private function getPortSettingsToTry() {
1335
+        //389 ← LDAP / Unencrypted or StartTLS
1336
+        //636 ← LDAPS / SSL
1337
+        //7xxx ← UCS. need to be checked first, because both ports may be open
1338
+        $host = $this->configuration->ldapHost;
1339
+        $port = (int)$this->configuration->ldapPort;
1340
+        $portSettings = [];
1341
+
1342
+        //In case the port is already provided, we will check this first
1343
+        if($port > 0) {
1344
+            $hostInfo = parse_url($host);
1345
+            if(!(is_array($hostInfo)
1346
+                && isset($hostInfo['scheme'])
1347
+                && stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348
+                $portSettings[] = ['port' => $port, 'tls' => true];
1349
+            }
1350
+            $portSettings[] =['port' => $port, 'tls' => false];
1351
+        }
1352
+
1353
+        //default ports
1354
+        $portSettings = array_merge($portSettings,
1355
+                                    $this->getDefaultLdapPortSettings());
1356
+
1357
+        return $portSettings;
1358
+    }
1359 1359
 
1360 1360
 
1361 1361
 }
Please login to merge, or discard this patch.
Spacing   +156 added lines, -156 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 	public function __construct(Configuration $configuration, ILDAPWrapper $ldap, Access $access) {
73 73
 		parent::__construct($ldap);
74 74
 		$this->configuration = $configuration;
75
-		if(is_null(Wizard::$l)) {
75
+		if (is_null(Wizard::$l)) {
76 76
 			Wizard::$l = \OC::$server->getL10N('user_ldap');
77 77
 		}
78 78
 		$this->access = $access;
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
 	}
81 81
 
82 82
 	public function __destruct() {
83
-		if($this->result->hasChanges()) {
83
+		if ($this->result->hasChanges()) {
84 84
 			$this->configuration->saveConfiguration();
85 85
 		}
86 86
 	}
@@ -95,18 +95,18 @@  discard block
 block discarded – undo
95 95
 	 */
96 96
 	public function countEntries(string $filter, string $type): int {
97 97
 		$reqs = ['ldapHost', 'ldapPort', 'ldapBase'];
98
-		if($type === 'users') {
98
+		if ($type === 'users') {
99 99
 			$reqs[] = 'ldapUserFilter';
100 100
 		}
101
-		if(!$this->checkRequirements($reqs)) {
101
+		if (!$this->checkRequirements($reqs)) {
102 102
 			throw new \Exception('Requirements not met', 400);
103 103
 		}
104 104
 
105 105
 		$attr = ['dn']; // default
106 106
 		$limit = 1001;
107
-		if($type === 'groups') {
108
-			$result =  $this->access->countGroups($filter, $attr, $limit);
109
-		} else if($type === 'users') {
107
+		if ($type === 'groups') {
108
+			$result = $this->access->countGroups($filter, $attr, $limit);
109
+		} else if ($type === 'users') {
110 110
 			$result = $this->access->countUsers($filter, $attr, $limit);
111 111
 		} else if ($type === 'objects') {
112 112
 			$result = $this->access->countObjects($limit);
@@ -114,7 +114,7 @@  discard block
 block discarded – undo
114 114
 			throw new \Exception('Internal error: Invalid object type', 500);
115 115
 		}
116 116
 
117
-		return (int)$result;
117
+		return (int) $result;
118 118
 	}
119 119
 
120 120
 	/**
@@ -125,16 +125,16 @@  discard block
 block discarded – undo
125 125
 	 * @return string
126 126
 	 */
127 127
 	private function formatCountResult(int $count): string {
128
-		if($count > 1000) {
128
+		if ($count > 1000) {
129 129
 			return '> 1000';
130 130
 		}
131
-		return (string)$count;
131
+		return (string) $count;
132 132
 	}
133 133
 
134 134
 	public function countGroups() {
135 135
 		$filter = $this->configuration->ldapGroupFilter;
136 136
 
137
-		if(empty($filter)) {
137
+		if (empty($filter)) {
138 138
 			$output = self::$l->n('%s group found', '%s groups found', 0, [0]);
139 139
 			$this->result->addChange('ldap_group_count', $output);
140 140
 			return $this->result;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 			$groupsTotal = $this->countEntries($filter, 'groups');
145 145
 		} catch (\Exception $e) {
146 146
 			//400 can be ignored, 500 is forwarded
147
-			if($e->getCode() === 500) {
147
+			if ($e->getCode() === 500) {
148 148
 				throw $e;
149 149
 			}
150 150
 			return false;
@@ -186,7 +186,7 @@  discard block
 block discarded – undo
186 186
 	public function countInBaseDN() {
187 187
 		// we don't need to provide a filter in this case
188 188
 		$total = $this->countEntries('', 'objects');
189
-		if($total === false) {
189
+		if ($total === false) {
190 190
 			throw new \Exception('invalid results received');
191 191
 		}
192 192
 		$this->result->addChange('ldap_test_base', $total);
@@ -200,7 +200,7 @@  discard block
 block discarded – undo
200 200
 	 * @return int|bool
201 201
 	 */
202 202
 	public function countUsersWithAttribute($attr, $existsCheck = false) {
203
-		if(!$this->checkRequirements(['ldapHost',
203
+		if (!$this->checkRequirements(['ldapHost',
204 204
 			'ldapPort',
205 205
 			'ldapBase',
206 206
 			'ldapUserFilter',
@@ -210,7 +210,7 @@  discard block
 block discarded – undo
210 210
 
211 211
 		$filter = $this->access->combineFilterWithAnd([
212 212
 			$this->configuration->ldapUserFilter,
213
-			$attr . '=*'
213
+			$attr.'=*'
214 214
 		]);
215 215
 
216 216
 		$limit = ($existsCheck === false) ? null : 1;
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 	 * @throws \Exception
226 226
 	 */
227 227
 	public function detectUserDisplayNameAttribute() {
228
-		if(!$this->checkRequirements(['ldapHost',
228
+		if (!$this->checkRequirements(['ldapHost',
229 229
 			'ldapPort',
230 230
 			'ldapBase',
231 231
 			'ldapUserFilter',
@@ -237,8 +237,8 @@  discard block
 block discarded – undo
237 237
 		if ($attr !== '' && $attr !== 'displayName') {
238 238
 			// most likely not the default value with upper case N,
239 239
 			// verify it still produces a result
240
-			$count = (int)$this->countUsersWithAttribute($attr, true);
241
-			if($count > 0) {
240
+			$count = (int) $this->countUsersWithAttribute($attr, true);
241
+			if ($count > 0) {
242 242
 				//no change, but we sent it back to make sure the user interface
243 243
 				//is still correct, even if the ajax call was cancelled meanwhile
244 244
 				$this->result->addChange('ldap_display_name', $attr);
@@ -249,9 +249,9 @@  discard block
 block discarded – undo
249 249
 		// first attribute that has at least one result wins
250 250
 		$displayNameAttrs = ['displayname', 'cn'];
251 251
 		foreach ($displayNameAttrs as $attr) {
252
-			$count = (int)$this->countUsersWithAttribute($attr, true);
252
+			$count = (int) $this->countUsersWithAttribute($attr, true);
253 253
 
254
-			if($count > 0) {
254
+			if ($count > 0) {
255 255
 				$this->applyFind('ldap_display_name', $attr);
256 256
 				return $this->result;
257 257
 			}
@@ -267,7 +267,7 @@  discard block
 block discarded – undo
267 267
 	 * @return WizardResult|bool
268 268
 	 */
269 269
 	public function detectEmailAttribute() {
270
-		if(!$this->checkRequirements(['ldapHost',
270
+		if (!$this->checkRequirements(['ldapHost',
271 271
 			'ldapPort',
272 272
 			'ldapBase',
273 273
 			'ldapUserFilter',
@@ -277,8 +277,8 @@  discard block
 block discarded – undo
277 277
 
278 278
 		$attr = $this->configuration->ldapEmailAttribute;
279 279
 		if ($attr !== '') {
280
-			$count = (int)$this->countUsersWithAttribute($attr, true);
281
-			if($count > 0) {
280
+			$count = (int) $this->countUsersWithAttribute($attr, true);
281
+			if ($count > 0) {
282 282
 				return false;
283 283
 			}
284 284
 			$writeLog = true;
@@ -289,19 +289,19 @@  discard block
 block discarded – undo
289 289
 		$emailAttributes = ['mail', 'mailPrimaryAddress'];
290 290
 		$winner = '';
291 291
 		$maxUsers = 0;
292
-		foreach($emailAttributes as $attr) {
292
+		foreach ($emailAttributes as $attr) {
293 293
 			$count = $this->countUsersWithAttribute($attr);
294
-			if($count > $maxUsers) {
294
+			if ($count > $maxUsers) {
295 295
 				$maxUsers = $count;
296 296
 				$winner = $attr;
297 297
 			}
298 298
 		}
299 299
 
300
-		if($winner !== '') {
300
+		if ($winner !== '') {
301 301
 			$this->applyFind('ldap_email_attr', $winner);
302
-			if($writeLog) {
303
-				\OCP\Util::writeLog('user_ldap', 'The mail attribute has ' .
304
-					'automatically been reset, because the original value ' .
302
+			if ($writeLog) {
303
+				\OCP\Util::writeLog('user_ldap', 'The mail attribute has '.
304
+					'automatically been reset, because the original value '.
305 305
 					'did not return any results.', ILogger::INFO);
306 306
 			}
307 307
 		}
@@ -314,7 +314,7 @@  discard block
 block discarded – undo
314 314
 	 * @throws \Exception
315 315
 	 */
316 316
 	public function determineAttributes() {
317
-		if(!$this->checkRequirements(['ldapHost',
317
+		if (!$this->checkRequirements(['ldapHost',
318 318
 			'ldapPort',
319 319
 			'ldapBase',
320 320
 			'ldapUserFilter',
@@ -330,7 +330,7 @@  discard block
 block discarded – undo
330 330
 		$this->result->addOptions('ldap_loginfilter_attributes', $attributes);
331 331
 
332 332
 		$selected = $this->configuration->ldapLoginFilterAttributes;
333
-		if(is_array($selected) && !empty($selected)) {
333
+		if (is_array($selected) && !empty($selected)) {
334 334
 			$this->result->addChange('ldap_loginfilter_attributes', $selected);
335 335
 		}
336 336
 
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 	 * @throws \Exception
344 344
 	 */
345 345
 	private function getUserAttributes() {
346
-		if(!$this->checkRequirements(['ldapHost',
346
+		if (!$this->checkRequirements(['ldapHost',
347 347
 			'ldapPort',
348 348
 			'ldapBase',
349 349
 			'ldapUserFilter',
@@ -351,20 +351,20 @@  discard block
 block discarded – undo
351 351
 			return  false;
352 352
 		}
353 353
 		$cr = $this->getConnection();
354
-		if(!$cr) {
354
+		if (!$cr) {
355 355
 			throw new \Exception('Could not connect to LDAP');
356 356
 		}
357 357
 
358 358
 		$base = $this->configuration->ldapBase[0];
359 359
 		$filter = $this->configuration->ldapUserFilter;
360 360
 		$rr = $this->ldap->search($cr, $base, $filter, [], 1, 1);
361
-		if(!$this->ldap->isResource($rr)) {
361
+		if (!$this->ldap->isResource($rr)) {
362 362
 			return false;
363 363
 		}
364 364
 		$er = $this->ldap->firstEntry($cr, $rr);
365 365
 		$attributes = $this->ldap->getAttributes($cr, $er);
366 366
 		$pureAttributes = [];
367
-		for($i = 0; $i < $attributes['count']; $i++) {
367
+		for ($i = 0; $i < $attributes['count']; $i++) {
368 368
 			$pureAttributes[] = $attributes[$i];
369 369
 		}
370 370
 
@@ -399,23 +399,23 @@  discard block
 block discarded – undo
399 399
 	 * @throws \Exception
400 400
 	 */
401 401
 	private function determineGroups($dbKey, $confKey, $testMemberOf = true) {
402
-		if(!$this->checkRequirements(['ldapHost',
402
+		if (!$this->checkRequirements(['ldapHost',
403 403
 			'ldapPort',
404 404
 			'ldapBase',
405 405
 		])) {
406 406
 			return  false;
407 407
 		}
408 408
 		$cr = $this->getConnection();
409
-		if(!$cr) {
409
+		if (!$cr) {
410 410
 			throw new \Exception('Could not connect to LDAP');
411 411
 		}
412 412
 
413 413
 		$this->fetchGroups($dbKey, $confKey);
414 414
 
415
-		if($testMemberOf) {
415
+		if ($testMemberOf) {
416 416
 			$this->configuration->hasMemberOfFilterSupport = $this->testMemberOf();
417 417
 			$this->result->markChange();
418
-			if(!$this->configuration->hasMemberOfFilterSupport) {
418
+			if (!$this->configuration->hasMemberOfFilterSupport) {
419 419
 				throw new \Exception('memberOf is not supported by the server');
420 420
 			}
421 421
 		}
@@ -435,7 +435,7 @@  discard block
 block discarded – undo
435 435
 		$obclasses = ['posixGroup', 'group', 'zimbraDistributionList', 'groupOfNames', 'groupOfUniqueNames'];
436 436
 
437 437
 		$filterParts = [];
438
-		foreach($obclasses as $obclass) {
438
+		foreach ($obclasses as $obclass) {
439 439
 			$filterParts[] = 'objectclass='.$obclass;
440 440
 		}
441 441
 		//we filter for everything
@@ -452,8 +452,8 @@  discard block
 block discarded – undo
452 452
 			// we need to request dn additionally here, otherwise memberOf
453 453
 			// detection will fail later
454 454
 			$result = $this->access->searchGroups($filter, ['cn', 'dn'], $limit, $offset);
455
-			foreach($result as $item) {
456
-				if(!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
455
+			foreach ($result as $item) {
456
+				if (!isset($item['cn']) && !is_array($item['cn']) && !isset($item['cn'][0])) {
457 457
 					// just in case - no issue known
458 458
 					continue;
459 459
 				}
@@ -463,7 +463,7 @@  discard block
 block discarded – undo
463 463
 			$offset += $limit;
464 464
 		} while ($this->access->hasMoreResults());
465 465
 
466
-		if(count($groupNames) > 0) {
466
+		if (count($groupNames) > 0) {
467 467
 			natsort($groupNames);
468 468
 			$this->result->addOptions($dbKey, array_values($groupNames));
469 469
 		} else {
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 		}
472 472
 
473 473
 		$setFeatures = $this->configuration->$confKey;
474
-		if(is_array($setFeatures) && !empty($setFeatures)) {
474
+		if (is_array($setFeatures) && !empty($setFeatures)) {
475 475
 			//something is already configured? pre-select it.
476 476
 			$this->result->addChange($dbKey, $setFeatures);
477 477
 		}
@@ -479,14 +479,14 @@  discard block
 block discarded – undo
479 479
 	}
480 480
 
481 481
 	public function determineGroupMemberAssoc() {
482
-		if(!$this->checkRequirements(['ldapHost',
482
+		if (!$this->checkRequirements(['ldapHost',
483 483
 			'ldapPort',
484 484
 			'ldapGroupFilter',
485 485
 		])) {
486 486
 			return  false;
487 487
 		}
488 488
 		$attribute = $this->detectGroupMemberAssoc();
489
-		if($attribute === false) {
489
+		if ($attribute === false) {
490 490
 			return false;
491 491
 		}
492 492
 		$this->configuration->setConfiguration(['ldapGroupMemberAssocAttr' => $attribute]);
@@ -501,14 +501,14 @@  discard block
 block discarded – undo
501 501
 	 * @throws \Exception
502 502
 	 */
503 503
 	public function determineGroupObjectClasses() {
504
-		if(!$this->checkRequirements(['ldapHost',
504
+		if (!$this->checkRequirements(['ldapHost',
505 505
 			'ldapPort',
506 506
 			'ldapBase',
507 507
 		])) {
508 508
 			return  false;
509 509
 		}
510 510
 		$cr = $this->getConnection();
511
-		if(!$cr) {
511
+		if (!$cr) {
512 512
 			throw new \Exception('Could not connect to LDAP');
513 513
 		}
514 514
 
@@ -528,14 +528,14 @@  discard block
 block discarded – undo
528 528
 	 * @throws \Exception
529 529
 	 */
530 530
 	public function determineUserObjectClasses() {
531
-		if(!$this->checkRequirements(['ldapHost',
531
+		if (!$this->checkRequirements(['ldapHost',
532 532
 			'ldapPort',
533 533
 			'ldapBase',
534 534
 		])) {
535 535
 			return  false;
536 536
 		}
537 537
 		$cr = $this->getConnection();
538
-		if(!$cr) {
538
+		if (!$cr) {
539 539
 			throw new \Exception('Could not connect to LDAP');
540 540
 		}
541 541
 
@@ -558,7 +558,7 @@  discard block
 block discarded – undo
558 558
 	 * @throws \Exception
559 559
 	 */
560 560
 	public function getGroupFilter() {
561
-		if(!$this->checkRequirements(['ldapHost',
561
+		if (!$this->checkRequirements(['ldapHost',
562 562
 			'ldapPort',
563 563
 			'ldapBase',
564 564
 		])) {
@@ -582,7 +582,7 @@  discard block
 block discarded – undo
582 582
 	 * @throws \Exception
583 583
 	 */
584 584
 	public function getUserListFilter() {
585
-		if(!$this->checkRequirements(['ldapHost',
585
+		if (!$this->checkRequirements(['ldapHost',
586 586
 			'ldapPort',
587 587
 			'ldapBase',
588 588
 		])) {
@@ -595,7 +595,7 @@  discard block
 block discarded – undo
595 595
 			$this->applyFind('ldap_display_name', $d['ldap_display_name']);
596 596
 		}
597 597
 		$filter = $this->composeLdapFilter(self::LFILTER_USER_LIST);
598
-		if(!$filter) {
598
+		if (!$filter) {
599 599
 			throw new \Exception('Cannot create filter');
600 600
 		}
601 601
 
@@ -608,7 +608,7 @@  discard block
 block discarded – undo
608 608
 	 * @throws \Exception
609 609
 	 */
610 610
 	public function getUserLoginFilter() {
611
-		if(!$this->checkRequirements(['ldapHost',
611
+		if (!$this->checkRequirements(['ldapHost',
612 612
 			'ldapPort',
613 613
 			'ldapBase',
614 614
 			'ldapUserFilter',
@@ -617,7 +617,7 @@  discard block
 block discarded – undo
617 617
 		}
618 618
 
619 619
 		$filter = $this->composeLdapFilter(self::LFILTER_LOGIN);
620
-		if(!$filter) {
620
+		if (!$filter) {
621 621
 			throw new \Exception('Cannot create filter');
622 622
 		}
623 623
 
@@ -631,7 +631,7 @@  discard block
 block discarded – undo
631 631
 	 * @throws \Exception
632 632
 	 */
633 633
 	public function testLoginName($loginName) {
634
-		if(!$this->checkRequirements(['ldapHost',
634
+		if (!$this->checkRequirements(['ldapHost',
635 635
 			'ldapPort',
636 636
 			'ldapBase',
637 637
 			'ldapLoginFilter',
@@ -640,17 +640,17 @@  discard block
 block discarded – undo
640 640
 		}
641 641
 
642 642
 		$cr = $this->access->connection->getConnectionResource();
643
-		if(!$this->ldap->isResource($cr)) {
643
+		if (!$this->ldap->isResource($cr)) {
644 644
 			throw new \Exception('connection error');
645 645
 		}
646 646
 
647
-		if(mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
647
+		if (mb_strpos($this->access->connection->ldapLoginFilter, '%uid', 0, 'UTF-8')
648 648
 			=== false) {
649 649
 			throw new \Exception('missing placeholder');
650 650
 		}
651 651
 
652 652
 		$users = $this->access->countUsersByLoginName($loginName);
653
-		if($this->ldap->errno($cr) !== 0) {
653
+		if ($this->ldap->errno($cr) !== 0) {
654 654
 			throw new \Exception($this->ldap->error($cr));
655 655
 		}
656 656
 		$filter = str_replace('%uid', $loginName, $this->access->connection->ldapLoginFilter);
@@ -665,22 +665,22 @@  discard block
 block discarded – undo
665 665
 	 * @throws \Exception
666 666
 	 */
667 667
 	public function guessPortAndTLS() {
668
-		if(!$this->checkRequirements(['ldapHost',
668
+		if (!$this->checkRequirements(['ldapHost',
669 669
 		])) {
670 670
 			return false;
671 671
 		}
672 672
 		$this->checkHost();
673 673
 		$portSettings = $this->getPortSettingsToTry();
674 674
 
675
-		if(!is_array($portSettings)) {
675
+		if (!is_array($portSettings)) {
676 676
 			throw new \Exception(print_r($portSettings, true));
677 677
 		}
678 678
 
679 679
 		//proceed from the best configuration and return on first success
680
-		foreach($portSettings as $setting) {
680
+		foreach ($portSettings as $setting) {
681 681
 			$p = $setting['port'];
682 682
 			$t = $setting['tls'];
683
-			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '. $p . ', TLS '. $t, ILogger::DEBUG);
683
+			\OCP\Util::writeLog('user_ldap', 'Wiz: trying port '.$p.', TLS '.$t, ILogger::DEBUG);
684 684
 			//connectAndBind may throw Exception, it needs to be catched by the
685 685
 			//callee of this method
686 686
 
@@ -690,7 +690,7 @@  discard block
 block discarded – undo
690 690
 				// any reply other than -1 (= cannot connect) is already okay,
691 691
 				// because then we found the server
692 692
 				// unavailable startTLS returns -11
693
-				if($e->getCode() > 0) {
693
+				if ($e->getCode() > 0) {
694 694
 					$settingsFound = true;
695 695
 				} else {
696 696
 					throw $e;
@@ -700,10 +700,10 @@  discard block
 block discarded – undo
700 700
 			if ($settingsFound === true) {
701 701
 				$config = [
702 702
 					'ldapPort' => $p,
703
-					'ldapTLS' => (int)$t
703
+					'ldapTLS' => (int) $t
704 704
 				];
705 705
 				$this->configuration->setConfiguration($config);
706
-				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port ' . $p, ILogger::DEBUG);
706
+				\OCP\Util::writeLog('user_ldap', 'Wiz: detected Port '.$p, ILogger::DEBUG);
707 707
 				$this->result->addChange('ldap_port', $p);
708 708
 				return $this->result;
709 709
 			}
@@ -718,7 +718,7 @@  discard block
 block discarded – undo
718 718
 	 * @return WizardResult|false WizardResult on success, false otherwise
719 719
 	 */
720 720
 	public function guessBaseDN() {
721
-		if(!$this->checkRequirements(['ldapHost',
721
+		if (!$this->checkRequirements(['ldapHost',
722 722
 			'ldapPort',
723 723
 		])) {
724 724
 			return false;
@@ -727,9 +727,9 @@  discard block
 block discarded – undo
727 727
 		//check whether a DN is given in the agent name (99.9% of all cases)
728 728
 		$base = null;
729 729
 		$i = stripos($this->configuration->ldapAgentName, 'dc=');
730
-		if($i !== false) {
730
+		if ($i !== false) {
731 731
 			$base = substr($this->configuration->ldapAgentName, $i);
732
-			if($this->testBaseDN($base)) {
732
+			if ($this->testBaseDN($base)) {
733 733
 				$this->applyFind('ldap_base', $base);
734 734
 				return $this->result;
735 735
 			}
@@ -740,13 +740,13 @@  discard block
 block discarded – undo
740 740
 		//a base DN
741 741
 		$helper = new Helper(\OC::$server->getConfig());
742 742
 		$domain = $helper->getDomainFromURL($this->configuration->ldapHost);
743
-		if(!$domain) {
743
+		if (!$domain) {
744 744
 			return false;
745 745
 		}
746 746
 
747 747
 		$dparts = explode('.', $domain);
748
-		while(count($dparts) > 0) {
749
-			$base2 = 'dc=' . implode(',dc=', $dparts);
748
+		while (count($dparts) > 0) {
749
+			$base2 = 'dc='.implode(',dc=', $dparts);
750 750
 			if ($base !== $base2 && $this->testBaseDN($base2)) {
751 751
 				$this->applyFind('ldap_base', $base2);
752 752
 				return $this->result;
@@ -779,7 +779,7 @@  discard block
 block discarded – undo
779 779
 		$hostInfo = parse_url($host);
780 780
 
781 781
 		//removes Port from Host
782
-		if(is_array($hostInfo) && isset($hostInfo['port'])) {
782
+		if (is_array($hostInfo) && isset($hostInfo['port'])) {
783 783
 			$port = $hostInfo['port'];
784 784
 			$host = str_replace(':'.$port, '', $host);
785 785
 			$this->applyFind('ldap_host', $host);
@@ -796,30 +796,30 @@  discard block
 block discarded – undo
796 796
 	private function detectGroupMemberAssoc() {
797 797
 		$possibleAttrs = ['uniqueMember', 'memberUid', 'member', 'gidNumber'];
798 798
 		$filter = $this->configuration->ldapGroupFilter;
799
-		if(empty($filter)) {
799
+		if (empty($filter)) {
800 800
 			return false;
801 801
 		}
802 802
 		$cr = $this->getConnection();
803
-		if(!$cr) {
803
+		if (!$cr) {
804 804
 			throw new \Exception('Could not connect to LDAP');
805 805
 		}
806 806
 		$base = $this->configuration->ldapBaseGroups[0] ?: $this->configuration->ldapBase[0];
807 807
 		$rr = $this->ldap->search($cr, $base, $filter, $possibleAttrs, 0, 1000);
808
-		if(!$this->ldap->isResource($rr)) {
808
+		if (!$this->ldap->isResource($rr)) {
809 809
 			return false;
810 810
 		}
811 811
 		$er = $this->ldap->firstEntry($cr, $rr);
812
-		while(is_resource($er)) {
812
+		while (is_resource($er)) {
813 813
 			$this->ldap->getDN($cr, $er);
814 814
 			$attrs = $this->ldap->getAttributes($cr, $er);
815 815
 			$result = [];
816 816
 			$possibleAttrsCount = count($possibleAttrs);
817
-			for($i = 0; $i < $possibleAttrsCount; $i++) {
818
-				if(isset($attrs[$possibleAttrs[$i]])) {
817
+			for ($i = 0; $i < $possibleAttrsCount; $i++) {
818
+				if (isset($attrs[$possibleAttrs[$i]])) {
819 819
 					$result[$possibleAttrs[$i]] = $attrs[$possibleAttrs[$i]]['count'];
820 820
 				}
821 821
 			}
822
-			if(!empty($result)) {
822
+			if (!empty($result)) {
823 823
 				natsort($result);
824 824
 				return key($result);
825 825
 			}
@@ -838,14 +838,14 @@  discard block
 block discarded – undo
838 838
 	 */
839 839
 	private function testBaseDN($base) {
840 840
 		$cr = $this->getConnection();
841
-		if(!$cr) {
841
+		if (!$cr) {
842 842
 			throw new \Exception('Could not connect to LDAP');
843 843
 		}
844 844
 
845 845
 		//base is there, let's validate it. If we search for anything, we should
846 846
 		//get a result set > 0 on a proper base
847 847
 		$rr = $this->ldap->search($cr, $base, 'objectClass=*', ['dn'], 0, 1);
848
-		if(!$this->ldap->isResource($rr)) {
848
+		if (!$this->ldap->isResource($rr)) {
849 849
 			$errorNo  = $this->ldap->errno($cr);
850 850
 			$errorMsg = $this->ldap->error($cr);
851 851
 			\OCP\Util::writeLog('user_ldap', 'Wiz: Could not search base '.$base.
@@ -867,11 +867,11 @@  discard block
 block discarded – undo
867 867
 	 */
868 868
 	private function testMemberOf() {
869 869
 		$cr = $this->getConnection();
870
-		if(!$cr) {
870
+		if (!$cr) {
871 871
 			throw new \Exception('Could not connect to LDAP');
872 872
 		}
873 873
 		$result = $this->access->countUsers('memberOf=*', ['memberOf'], 1);
874
-		if(is_int($result) &&  $result > 0) {
874
+		if (is_int($result) && $result > 0) {
875 875
 			return true;
876 876
 		}
877 877
 		return false;
@@ -892,27 +892,27 @@  discard block
 block discarded – undo
892 892
 			case self::LFILTER_USER_LIST:
893 893
 				$objcs = $this->configuration->ldapUserFilterObjectclass;
894 894
 				//glue objectclasses
895
-				if(is_array($objcs) && count($objcs) > 0) {
895
+				if (is_array($objcs) && count($objcs) > 0) {
896 896
 					$filter .= '(|';
897
-					foreach($objcs as $objc) {
898
-						$filter .= '(objectclass=' . $objc . ')';
897
+					foreach ($objcs as $objc) {
898
+						$filter .= '(objectclass='.$objc.')';
899 899
 					}
900 900
 					$filter .= ')';
901 901
 					$parts++;
902 902
 				}
903 903
 				//glue group memberships
904
-				if($this->configuration->hasMemberOfFilterSupport) {
904
+				if ($this->configuration->hasMemberOfFilterSupport) {
905 905
 					$cns = $this->configuration->ldapUserFilterGroups;
906
-					if(is_array($cns) && count($cns) > 0) {
906
+					if (is_array($cns) && count($cns) > 0) {
907 907
 						$filter .= '(|';
908 908
 						$cr = $this->getConnection();
909
-						if(!$cr) {
909
+						if (!$cr) {
910 910
 							throw new \Exception('Could not connect to LDAP');
911 911
 						}
912 912
 						$base = $this->configuration->ldapBase[0];
913
-						foreach($cns as $cn) {
914
-							$rr = $this->ldap->search($cr, $base, 'cn=' . $cn, ['dn', 'primaryGroupToken']);
915
-							if(!$this->ldap->isResource($rr)) {
913
+						foreach ($cns as $cn) {
914
+							$rr = $this->ldap->search($cr, $base, 'cn='.$cn, ['dn', 'primaryGroupToken']);
915
+							if (!$this->ldap->isResource($rr)) {
916 916
 								continue;
917 917
 							}
918 918
 							$er = $this->ldap->firstEntry($cr, $rr);
@@ -921,11 +921,11 @@  discard block
 block discarded – undo
921 921
 							if ($dn === false || $dn === '') {
922 922
 								continue;
923 923
 							}
924
-							$filterPart = '(memberof=' . $dn . ')';
925
-							if(isset($attrs['primaryGroupToken'])) {
924
+							$filterPart = '(memberof='.$dn.')';
925
+							if (isset($attrs['primaryGroupToken'])) {
926 926
 								$pgt = $attrs['primaryGroupToken'][0];
927
-								$primaryFilterPart = '(primaryGroupID=' . $pgt .')';
928
-								$filterPart = '(|' . $filterPart . $primaryFilterPart . ')';
927
+								$primaryFilterPart = '(primaryGroupID='.$pgt.')';
928
+								$filterPart = '(|'.$filterPart.$primaryFilterPart.')';
929 929
 							}
930 930
 							$filter .= $filterPart;
931 931
 						}
@@ -934,8 +934,8 @@  discard block
 block discarded – undo
934 934
 					$parts++;
935 935
 				}
936 936
 				//wrap parts in AND condition
937
-				if($parts > 1) {
938
-					$filter = '(&' . $filter . ')';
937
+				if ($parts > 1) {
938
+					$filter = '(&'.$filter.')';
939 939
 				}
940 940
 				if ($filter === '') {
941 941
 					$filter = '(objectclass=*)';
@@ -945,27 +945,27 @@  discard block
 block discarded – undo
945 945
 			case self::LFILTER_GROUP_LIST:
946 946
 				$objcs = $this->configuration->ldapGroupFilterObjectclass;
947 947
 				//glue objectclasses
948
-				if(is_array($objcs) && count($objcs) > 0) {
948
+				if (is_array($objcs) && count($objcs) > 0) {
949 949
 					$filter .= '(|';
950
-					foreach($objcs as $objc) {
951
-						$filter .= '(objectclass=' . $objc . ')';
950
+					foreach ($objcs as $objc) {
951
+						$filter .= '(objectclass='.$objc.')';
952 952
 					}
953 953
 					$filter .= ')';
954 954
 					$parts++;
955 955
 				}
956 956
 				//glue group memberships
957 957
 				$cns = $this->configuration->ldapGroupFilterGroups;
958
-				if(is_array($cns) && count($cns) > 0) {
958
+				if (is_array($cns) && count($cns) > 0) {
959 959
 					$filter .= '(|';
960
-					foreach($cns as $cn) {
961
-						$filter .= '(cn=' . $cn . ')';
960
+					foreach ($cns as $cn) {
961
+						$filter .= '(cn='.$cn.')';
962 962
 					}
963 963
 					$filter .= ')';
964 964
 				}
965 965
 				$parts++;
966 966
 				//wrap parts in AND condition
967
-				if($parts > 1) {
968
-					$filter = '(&' . $filter . ')';
967
+				if ($parts > 1) {
968
+					$filter = '(&'.$filter.')';
969 969
 				}
970 970
 				break;
971 971
 
@@ -977,47 +977,47 @@  discard block
 block discarded – undo
977 977
 				$userAttributes = array_change_key_case(array_flip($userAttributes));
978 978
 				$parts = 0;
979 979
 
980
-				if($this->configuration->ldapLoginFilterUsername === '1') {
980
+				if ($this->configuration->ldapLoginFilterUsername === '1') {
981 981
 					$attr = '';
982
-					if(isset($userAttributes['uid'])) {
982
+					if (isset($userAttributes['uid'])) {
983 983
 						$attr = 'uid';
984
-					} else if(isset($userAttributes['samaccountname'])) {
984
+					} else if (isset($userAttributes['samaccountname'])) {
985 985
 						$attr = 'samaccountname';
986
-					} else if(isset($userAttributes['cn'])) {
986
+					} else if (isset($userAttributes['cn'])) {
987 987
 						//fallback
988 988
 						$attr = 'cn';
989 989
 					}
990 990
 					if ($attr !== '') {
991
-						$filterUsername = '(' . $attr . $loginpart . ')';
991
+						$filterUsername = '('.$attr.$loginpart.')';
992 992
 						$parts++;
993 993
 					}
994 994
 				}
995 995
 
996 996
 				$filterEmail = '';
997
-				if($this->configuration->ldapLoginFilterEmail === '1') {
997
+				if ($this->configuration->ldapLoginFilterEmail === '1') {
998 998
 					$filterEmail = '(|(mailPrimaryAddress=%uid)(mail=%uid))';
999 999
 					$parts++;
1000 1000
 				}
1001 1001
 
1002 1002
 				$filterAttributes = '';
1003 1003
 				$attrsToFilter = $this->configuration->ldapLoginFilterAttributes;
1004
-				if(is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1004
+				if (is_array($attrsToFilter) && count($attrsToFilter) > 0) {
1005 1005
 					$filterAttributes = '(|';
1006
-					foreach($attrsToFilter as $attribute) {
1007
-						$filterAttributes .= '(' . $attribute . $loginpart . ')';
1006
+					foreach ($attrsToFilter as $attribute) {
1007
+						$filterAttributes .= '('.$attribute.$loginpart.')';
1008 1008
 					}
1009 1009
 					$filterAttributes .= ')';
1010 1010
 					$parts++;
1011 1011
 				}
1012 1012
 
1013 1013
 				$filterLogin = '';
1014
-				if($parts > 1) {
1014
+				if ($parts > 1) {
1015 1015
 					$filterLogin = '(|';
1016 1016
 				}
1017 1017
 				$filterLogin .= $filterUsername;
1018 1018
 				$filterLogin .= $filterEmail;
1019 1019
 				$filterLogin .= $filterAttributes;
1020
-				if($parts > 1) {
1020
+				if ($parts > 1) {
1021 1021
 					$filterLogin .= ')';
1022 1022
 				}
1023 1023
 
@@ -1042,12 +1042,12 @@  discard block
 block discarded – undo
1042 1042
 		//connect, does not really trigger any server communication
1043 1043
 		$host = $this->configuration->ldapHost;
1044 1044
 		$hostInfo = parse_url($host);
1045
-		if(!$hostInfo) {
1045
+		if (!$hostInfo) {
1046 1046
 			throw new \Exception(self::$l->t('Invalid Host'));
1047 1047
 		}
1048 1048
 		\OCP\Util::writeLog('user_ldap', 'Wiz: Attempting to connect ', ILogger::DEBUG);
1049 1049
 		$cr = $this->ldap->connect($host, $port);
1050
-		if(!is_resource($cr)) {
1050
+		if (!is_resource($cr)) {
1051 1051
 			throw new \Exception(self::$l->t('Invalid Host'));
1052 1052
 		}
1053 1053
 
@@ -1057,9 +1057,9 @@  discard block
 block discarded – undo
1057 1057
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1058 1058
 
1059 1059
 		try {
1060
-			if($tls) {
1060
+			if ($tls) {
1061 1061
 				$isTlsWorking = @$this->ldap->startTls($cr);
1062
-				if(!$isTlsWorking) {
1062
+				if (!$isTlsWorking) {
1063 1063
 					return false;
1064 1064
 				}
1065 1065
 			}
@@ -1073,17 +1073,17 @@  discard block
 block discarded – undo
1073 1073
 			$errNo = $this->ldap->errno($cr);
1074 1074
 			$error = ldap_error($cr);
1075 1075
 			$this->ldap->unbind($cr);
1076
-		} catch(ServerNotAvailableException $e) {
1076
+		} catch (ServerNotAvailableException $e) {
1077 1077
 			return false;
1078 1078
 		}
1079 1079
 
1080
-		if($login === true) {
1080
+		if ($login === true) {
1081 1081
 			$this->ldap->unbind($cr);
1082
-			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '. $port . ' TLS ' . (int)$tls, ILogger::DEBUG);
1082
+			\OCP\Util::writeLog('user_ldap', 'Wiz: Bind successful to Port '.$port.' TLS '.(int) $tls, ILogger::DEBUG);
1083 1083
 			return true;
1084 1084
 		}
1085 1085
 
1086
-		if($errNo === -1) {
1086
+		if ($errNo === -1) {
1087 1087
 			//host, port or TLS wrong
1088 1088
 			return false;
1089 1089
 		}
@@ -1111,9 +1111,9 @@  discard block
 block discarded – undo
1111 1111
 	 */
1112 1112
 	private function checkRequirements($reqs) {
1113 1113
 		$this->checkAgentRequirements();
1114
-		foreach($reqs as $option) {
1114
+		foreach ($reqs as $option) {
1115 1115
 			$value = $this->configuration->$option;
1116
-			if(empty($value)) {
1116
+			if (empty($value)) {
1117 1117
 				return false;
1118 1118
 			}
1119 1119
 		}
@@ -1135,33 +1135,33 @@  discard block
 block discarded – undo
1135 1135
 		$dnRead = [];
1136 1136
 		$foundItems = [];
1137 1137
 		$maxEntries = 0;
1138
-		if(!is_array($this->configuration->ldapBase)
1138
+		if (!is_array($this->configuration->ldapBase)
1139 1139
 		   || !isset($this->configuration->ldapBase[0])) {
1140 1140
 			return false;
1141 1141
 		}
1142 1142
 		$base = $this->configuration->ldapBase[0];
1143 1143
 		$cr = $this->getConnection();
1144
-		if(!$this->ldap->isResource($cr)) {
1144
+		if (!$this->ldap->isResource($cr)) {
1145 1145
 			return false;
1146 1146
 		}
1147 1147
 		$lastFilter = null;
1148
-		if(isset($filters[count($filters)-1])) {
1149
-			$lastFilter = $filters[count($filters)-1];
1148
+		if (isset($filters[count($filters) - 1])) {
1149
+			$lastFilter = $filters[count($filters) - 1];
1150 1150
 		}
1151
-		foreach($filters as $filter) {
1152
-			if($lastFilter === $filter && count($foundItems) > 0) {
1151
+		foreach ($filters as $filter) {
1152
+			if ($lastFilter === $filter && count($foundItems) > 0) {
1153 1153
 				//skip when the filter is a wildcard and results were found
1154 1154
 				continue;
1155 1155
 			}
1156 1156
 			// 20k limit for performance and reason
1157 1157
 			$rr = $this->ldap->search($cr, $base, $filter, [$attr], 0, 20000);
1158
-			if(!$this->ldap->isResource($rr)) {
1158
+			if (!$this->ldap->isResource($rr)) {
1159 1159
 				continue;
1160 1160
 			}
1161 1161
 			$entries = $this->ldap->countEntries($cr, $rr);
1162 1162
 			$getEntryFunc = 'firstEntry';
1163
-			if(($entries !== false) && ($entries > 0)) {
1164
-				if(!is_null($maxF) && $entries > $maxEntries) {
1163
+			if (($entries !== false) && ($entries > 0)) {
1164
+				if (!is_null($maxF) && $entries > $maxEntries) {
1165 1165
 					$maxEntries = $entries;
1166 1166
 					$maxF = $filter;
1167 1167
 				}
@@ -1169,13 +1169,13 @@  discard block
 block discarded – undo
1169 1169
 				do {
1170 1170
 					$entry = $this->ldap->$getEntryFunc($cr, $rr);
1171 1171
 					$getEntryFunc = 'nextEntry';
1172
-					if(!$this->ldap->isResource($entry)) {
1172
+					if (!$this->ldap->isResource($entry)) {
1173 1173
 						continue 2;
1174 1174
 					}
1175 1175
 					$rr = $entry; //will be expected by nextEntry next round
1176 1176
 					$attributes = $this->ldap->getAttributes($cr, $entry);
1177 1177
 					$dn = $this->ldap->getDN($cr, $entry);
1178
-					if($dn === false || in_array($dn, $dnRead)) {
1178
+					if ($dn === false || in_array($dn, $dnRead)) {
1179 1179
 						continue;
1180 1180
 					}
1181 1181
 					$newItems = [];
@@ -1186,7 +1186,7 @@  discard block
 block discarded – undo
1186 1186
 					$foundItems = array_merge($foundItems, $newItems);
1187 1187
 					$this->resultCache[$dn][$attr] = $newItems;
1188 1188
 					$dnRead[] = $dn;
1189
-				} while(($state === self::LRESULT_PROCESSED_SKIP
1189
+				} while (($state === self::LRESULT_PROCESSED_SKIP
1190 1190
 						|| $this->ldap->isResource($entry))
1191 1191
 						&& ($dnReadLimit === 0 || $dnReadCount < $dnReadLimit));
1192 1192
 			}
@@ -1209,11 +1209,11 @@  discard block
 block discarded – undo
1209 1209
 	 */
1210 1210
 	private function determineFeature($objectclasses, $attr, $dbkey, $confkey, $po = false) {
1211 1211
 		$cr = $this->getConnection();
1212
-		if(!$cr) {
1212
+		if (!$cr) {
1213 1213
 			throw new \Exception('Could not connect to LDAP');
1214 1214
 		}
1215 1215
 		$p = 'objectclass=';
1216
-		foreach($objectclasses as $key => $value) {
1216
+		foreach ($objectclasses as $key => $value) {
1217 1217
 			$objectclasses[$key] = $p.$value;
1218 1218
 		}
1219 1219
 		$maxEntryObjC = '';
@@ -1225,7 +1225,7 @@  discard block
 block discarded – undo
1225 1225
 		$availableFeatures =
1226 1226
 			$this->cumulativeSearchOnAttribute($objectclasses, $attr,
1227 1227
 											   $dig, $maxEntryObjC);
1228
-		if(is_array($availableFeatures)
1228
+		if (is_array($availableFeatures)
1229 1229
 		   && count($availableFeatures) > 0) {
1230 1230
 			natcasesort($availableFeatures);
1231 1231
 			//natcasesort keeps indices, but we must get rid of them for proper
@@ -1236,7 +1236,7 @@  discard block
 block discarded – undo
1236 1236
 		}
1237 1237
 
1238 1238
 		$setFeatures = $this->configuration->$confkey;
1239
-		if(is_array($setFeatures) && !empty($setFeatures)) {
1239
+		if (is_array($setFeatures) && !empty($setFeatures)) {
1240 1240
 			//something is already configured? pre-select it.
1241 1241
 			$this->result->addChange($dbkey, $setFeatures);
1242 1242
 		} else if ($po && $maxEntryObjC !== '') {
@@ -1258,7 +1258,7 @@  discard block
 block discarded – undo
1258 1258
 	 * LRESULT_PROCESSED_INVALID or LRESULT_PROCESSED_SKIP
1259 1259
 	 */
1260 1260
 	private function getAttributeValuesFromEntry($result, $attribute, &$known) {
1261
-		if(!is_array($result)
1261
+		if (!is_array($result)
1262 1262
 		   || !isset($result['count'])
1263 1263
 		   || !$result['count'] > 0) {
1264 1264
 			return self::LRESULT_PROCESSED_INVALID;
@@ -1267,12 +1267,12 @@  discard block
 block discarded – undo
1267 1267
 		// strtolower on all keys for proper comparison
1268 1268
 		$result = \OCP\Util::mb_array_change_key_case($result);
1269 1269
 		$attribute = strtolower($attribute);
1270
-		if(isset($result[$attribute])) {
1271
-			foreach($result[$attribute] as $key => $val) {
1272
-				if($key === 'count') {
1270
+		if (isset($result[$attribute])) {
1271
+			foreach ($result[$attribute] as $key => $val) {
1272
+				if ($key === 'count') {
1273 1273
 					continue;
1274 1274
 				}
1275
-				if(!in_array($val, $known)) {
1275
+				if (!in_array($val, $known)) {
1276 1276
 					$known[] = $val;
1277 1277
 				}
1278 1278
 			}
@@ -1286,7 +1286,7 @@  discard block
 block discarded – undo
1286 1286
 	 * @return bool|mixed
1287 1287
 	 */
1288 1288
 	private function getConnection() {
1289
-		if(!is_null($this->cr)) {
1289
+		if (!is_null($this->cr)) {
1290 1290
 			return $this->cr;
1291 1291
 		}
1292 1292
 
@@ -1298,14 +1298,14 @@  discard block
 block discarded – undo
1298 1298
 		$this->ldap->setOption($cr, LDAP_OPT_PROTOCOL_VERSION, 3);
1299 1299
 		$this->ldap->setOption($cr, LDAP_OPT_REFERRALS, 0);
1300 1300
 		$this->ldap->setOption($cr, LDAP_OPT_NETWORK_TIMEOUT, self::LDAP_NW_TIMEOUT);
1301
-		if($this->configuration->ldapTLS === 1) {
1301
+		if ($this->configuration->ldapTLS === 1) {
1302 1302
 			$this->ldap->startTls($cr);
1303 1303
 		}
1304 1304
 
1305 1305
 		$lo = @$this->ldap->bind($cr,
1306 1306
 								 $this->configuration->ldapAgentName,
1307 1307
 								 $this->configuration->ldapAgentPassword);
1308
-		if($lo === true) {
1308
+		if ($lo === true) {
1309 1309
 			$this->$cr = $cr;
1310 1310
 			return $cr;
1311 1311
 		}
@@ -1336,18 +1336,18 @@  discard block
 block discarded – undo
1336 1336
 		//636 ← LDAPS / SSL
1337 1337
 		//7xxx ← UCS. need to be checked first, because both ports may be open
1338 1338
 		$host = $this->configuration->ldapHost;
1339
-		$port = (int)$this->configuration->ldapPort;
1339
+		$port = (int) $this->configuration->ldapPort;
1340 1340
 		$portSettings = [];
1341 1341
 
1342 1342
 		//In case the port is already provided, we will check this first
1343
-		if($port > 0) {
1343
+		if ($port > 0) {
1344 1344
 			$hostInfo = parse_url($host);
1345
-			if(!(is_array($hostInfo)
1345
+			if (!(is_array($hostInfo)
1346 1346
 				&& isset($hostInfo['scheme'])
1347 1347
 				&& stripos($hostInfo['scheme'], 'ldaps') !== false)) {
1348 1348
 				$portSettings[] = ['port' => $port, 'tls' => true];
1349 1349
 			}
1350
-			$portSettings[] =['port' => $port, 'tls' => false];
1350
+			$portSettings[] = ['port' => $port, 'tls' => false];
1351 1351
 		}
1352 1352
 
1353 1353
 		//default ports
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_LDAP.php 2 patches
Indentation   +579 added lines, -579 removed lines patch added patch discarded remove patch
@@ -53,587 +53,587 @@
 block discarded – undo
53 53
 use OCP\Util;
54 54
 
55 55
 class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
56
-	/** @var \OCP\IConfig */
57
-	protected $ocConfig;
58
-
59
-	/** @var INotificationManager */
60
-	protected $notificationManager;
61
-
62
-	/** @var UserPluginManager */
63
-	protected $userPluginManager;
64
-
65
-	/**
66
-	 * @param Access $access
67
-	 * @param \OCP\IConfig $ocConfig
68
-	 * @param \OCP\Notification\IManager $notificationManager
69
-	 * @param IUserSession $userSession
70
-	 */
71
-	public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
72
-		parent::__construct($access);
73
-		$this->ocConfig = $ocConfig;
74
-		$this->notificationManager = $notificationManager;
75
-		$this->userPluginManager = $userPluginManager;
76
-	}
77
-
78
-	/**
79
-	 * checks whether the user is allowed to change his avatar in Nextcloud
80
-	 *
81
-	 * @param string $uid the Nextcloud user name
82
-	 * @return boolean either the user can or cannot
83
-	 * @throws \Exception
84
-	 */
85
-	public function canChangeAvatar($uid) {
86
-		if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
87
-			return $this->userPluginManager->canChangeAvatar($uid);
88
-		}
89
-
90
-		if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
91
-			return true;
92
-		}
93
-
94
-		$user = $this->access->userManager->get($uid);
95
-		if(!$user instanceof User) {
96
-			return false;
97
-		}
98
-		$imageData = $user->getAvatarImage();
99
-		if($imageData === false) {
100
-			return true;
101
-		}
102
-		return !$user->updateAvatar(true);
103
-	}
104
-
105
-	/**
106
-	 * Return the username for the given login name, if available
107
-	 *
108
-	 * @param string $loginName
109
-	 * @return string|false
110
-	 * @throws \Exception
111
-	 */
112
-	public function loginName2UserName($loginName) {
113
-		$cacheKey = 'loginName2UserName-' . $loginName;
114
-		$username = $this->access->connection->getFromCache($cacheKey);
115
-
116
-		if ($username !== null) {
117
-			return $username;
118
-		}
119
-
120
-		try {
121
-			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
122
-			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
123
-			if ($user === null || $user instanceof OfflineUser) {
124
-				// this path is not really possible, however get() is documented
125
-				// to return User, OfflineUser or null so we are very defensive here.
126
-				$this->access->connection->writeToCache($cacheKey, false);
127
-				return false;
128
-			}
129
-			$username = $user->getUsername();
130
-			$this->access->connection->writeToCache($cacheKey, $username);
131
-			return $username;
132
-		} catch (NotOnLDAP $e) {
133
-			$this->access->connection->writeToCache($cacheKey, false);
134
-			return false;
135
-		}
136
-	}
56
+    /** @var \OCP\IConfig */
57
+    protected $ocConfig;
58
+
59
+    /** @var INotificationManager */
60
+    protected $notificationManager;
61
+
62
+    /** @var UserPluginManager */
63
+    protected $userPluginManager;
64
+
65
+    /**
66
+     * @param Access $access
67
+     * @param \OCP\IConfig $ocConfig
68
+     * @param \OCP\Notification\IManager $notificationManager
69
+     * @param IUserSession $userSession
70
+     */
71
+    public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
72
+        parent::__construct($access);
73
+        $this->ocConfig = $ocConfig;
74
+        $this->notificationManager = $notificationManager;
75
+        $this->userPluginManager = $userPluginManager;
76
+    }
77
+
78
+    /**
79
+     * checks whether the user is allowed to change his avatar in Nextcloud
80
+     *
81
+     * @param string $uid the Nextcloud user name
82
+     * @return boolean either the user can or cannot
83
+     * @throws \Exception
84
+     */
85
+    public function canChangeAvatar($uid) {
86
+        if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
87
+            return $this->userPluginManager->canChangeAvatar($uid);
88
+        }
89
+
90
+        if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
91
+            return true;
92
+        }
93
+
94
+        $user = $this->access->userManager->get($uid);
95
+        if(!$user instanceof User) {
96
+            return false;
97
+        }
98
+        $imageData = $user->getAvatarImage();
99
+        if($imageData === false) {
100
+            return true;
101
+        }
102
+        return !$user->updateAvatar(true);
103
+    }
104
+
105
+    /**
106
+     * Return the username for the given login name, if available
107
+     *
108
+     * @param string $loginName
109
+     * @return string|false
110
+     * @throws \Exception
111
+     */
112
+    public function loginName2UserName($loginName) {
113
+        $cacheKey = 'loginName2UserName-' . $loginName;
114
+        $username = $this->access->connection->getFromCache($cacheKey);
115
+
116
+        if ($username !== null) {
117
+            return $username;
118
+        }
119
+
120
+        try {
121
+            $ldapRecord = $this->getLDAPUserByLoginName($loginName);
122
+            $user = $this->access->userManager->get($ldapRecord['dn'][0]);
123
+            if ($user === null || $user instanceof OfflineUser) {
124
+                // this path is not really possible, however get() is documented
125
+                // to return User, OfflineUser or null so we are very defensive here.
126
+                $this->access->connection->writeToCache($cacheKey, false);
127
+                return false;
128
+            }
129
+            $username = $user->getUsername();
130
+            $this->access->connection->writeToCache($cacheKey, $username);
131
+            return $username;
132
+        } catch (NotOnLDAP $e) {
133
+            $this->access->connection->writeToCache($cacheKey, false);
134
+            return false;
135
+        }
136
+    }
137 137
 	
138
-	/**
139
-	 * returns the username for the given LDAP DN, if available
140
-	 *
141
-	 * @param string $dn
142
-	 * @return string|false with the username
143
-	 */
144
-	public function dn2UserName($dn) {
145
-		return $this->access->dn2username($dn);
146
-	}
147
-
148
-	/**
149
-	 * returns an LDAP record based on a given login name
150
-	 *
151
-	 * @param string $loginName
152
-	 * @return array
153
-	 * @throws NotOnLDAP
154
-	 */
155
-	public function getLDAPUserByLoginName($loginName) {
156
-		//find out dn of the user name
157
-		$attrs = $this->access->userManager->getAttributes();
158
-		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
159
-		if(count($users) < 1) {
160
-			throw new NotOnLDAP('No user available for the given login name on ' .
161
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
162
-		}
163
-		return $users[0];
164
-	}
165
-
166
-	/**
167
-	 * Check if the password is correct without logging in the user
168
-	 *
169
-	 * @param string $uid The username
170
-	 * @param string $password The password
171
-	 * @return false|string
172
-	 */
173
-	public function checkPassword($uid, $password) {
174
-		try {
175
-			$ldapRecord = $this->getLDAPUserByLoginName($uid);
176
-		} catch(NotOnLDAP $e) {
177
-			\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
178
-			return false;
179
-		}
180
-		$dn = $ldapRecord['dn'][0];
181
-		$user = $this->access->userManager->get($dn);
182
-
183
-		if(!$user instanceof User) {
184
-			Util::writeLog('user_ldap',
185
-				'LDAP Login: Could not get user object for DN ' . $dn .
186
-				'. Maybe the LDAP entry has no set display name attribute?',
187
-				ILogger::WARN);
188
-			return false;
189
-		}
190
-		if($user->getUsername() !== false) {
191
-			//are the credentials OK?
192
-			if(!$this->access->areCredentialsValid($dn, $password)) {
193
-				return false;
194
-			}
195
-
196
-			$this->access->cacheUserExists($user->getUsername());
197
-			$user->processAttributes($ldapRecord);
198
-			$user->markLogin();
199
-
200
-			return $user->getUsername();
201
-		}
202
-
203
-		return false;
204
-	}
205
-
206
-	/**
207
-	 * Set password
208
-	 * @param string $uid The username
209
-	 * @param string $password The new password
210
-	 * @return bool
211
-	 */
212
-	public function setPassword($uid, $password) {
213
-		if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
214
-			return $this->userPluginManager->setPassword($uid, $password);
215
-		}
216
-
217
-		$user = $this->access->userManager->get($uid);
218
-
219
-		if(!$user instanceof User) {
220
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
221
-				'. Maybe the LDAP entry has no set display name attribute?');
222
-		}
223
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
224
-			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
225
-			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
226
-			if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
227
-				//remove last password expiry warning if any
228
-				$notification = $this->notificationManager->createNotification();
229
-				$notification->setApp('user_ldap')
230
-					->setUser($uid)
231
-					->setObject('pwd_exp_warn', $uid)
232
-				;
233
-				$this->notificationManager->markProcessed($notification);
234
-			}
235
-			return true;
236
-		}
237
-
238
-		return false;
239
-	}
240
-
241
-	/**
242
-	 * Get a list of all users
243
-	 *
244
-	 * @param string $search
245
-	 * @param integer $limit
246
-	 * @param integer $offset
247
-	 * @return string[] an array of all uids
248
-	 */
249
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
250
-		$search = $this->access->escapeFilterPart($search, true);
251
-		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
252
-
253
-		//check if users are cached, if so return
254
-		$ldap_users = $this->access->connection->getFromCache($cachekey);
255
-		if(!is_null($ldap_users)) {
256
-			return $ldap_users;
257
-		}
258
-
259
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
260
-		// error. With a limit of 0, we get 0 results. So we pass null.
261
-		if($limit <= 0) {
262
-			$limit = null;
263
-		}
264
-		$filter = $this->access->combineFilterWithAnd([
265
-			$this->access->connection->ldapUserFilter,
266
-			$this->access->connection->ldapUserDisplayName . '=*',
267
-			$this->access->getFilterPartForUserSearch($search)
268
-		]);
269
-
270
-		Util::writeLog('user_ldap',
271
-			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
272
-			ILogger::DEBUG);
273
-		//do the search and translate results to Nextcloud names
274
-		$ldap_users = $this->access->fetchListOfUsers(
275
-			$filter,
276
-			$this->access->userManager->getAttributes(true),
277
-			$limit, $offset);
278
-		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
279
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
280
-
281
-		$this->access->connection->writeToCache($cachekey, $ldap_users);
282
-		return $ldap_users;
283
-	}
284
-
285
-	/**
286
-	 * checks whether a user is still available on LDAP
287
-	 *
288
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
289
-	 * name or an instance of that user
290
-	 * @return bool
291
-	 * @throws \Exception
292
-	 * @throws \OC\ServerNotAvailableException
293
-	 */
294
-	public function userExistsOnLDAP($user) {
295
-		if(is_string($user)) {
296
-			$user = $this->access->userManager->get($user);
297
-		}
298
-		if(is_null($user)) {
299
-			return false;
300
-		}
301
-		$uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
302
-		$cacheKey = 'userExistsOnLDAP' . $uid;
303
-		$userExists = $this->access->connection->getFromCache($cacheKey);
304
-		if(!is_null($userExists)) {
305
-			return (bool)$userExists;
306
-		}
307
-
308
-		$dn = $user->getDN();
309
-		//check if user really still exists by reading its entry
310
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
311
-			try {
312
-				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
313
-				if (!$uuid) {
314
-					$this->access->connection->writeToCache($cacheKey, false);
315
-					return false;
316
-				}
317
-				$newDn = $this->access->getUserDnByUuid($uuid);
318
-				//check if renamed user is still valid by reapplying the ldap filter
319
-				if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
320
-					$this->access->connection->writeToCache($cacheKey, false);
321
-					return false;
322
-				}
323
-				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
324
-				$this->access->connection->writeToCache($cacheKey, true);
325
-				return true;
326
-			} catch (ServerNotAvailableException $e) {
327
-				throw $e;
328
-			} catch (\Exception $e) {
329
-				$this->access->connection->writeToCache($cacheKey, false);
330
-				return false;
331
-			}
332
-		}
333
-
334
-		if($user instanceof OfflineUser) {
335
-			$user->unmark();
336
-		}
337
-
338
-		$this->access->connection->writeToCache($cacheKey, true);
339
-		return true;
340
-	}
341
-
342
-	/**
343
-	 * check if a user exists
344
-	 * @param string $uid the username
345
-	 * @return boolean
346
-	 * @throws \Exception when connection could not be established
347
-	 */
348
-	public function userExists($uid) {
349
-		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
-		if(!is_null($userExists)) {
351
-			return (bool)$userExists;
352
-		}
353
-		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354
-		$user = $this->access->userManager->get($uid);
355
-
356
-		if(is_null($user)) {
357
-			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358
-				$this->access->connection->ldapHost, ILogger::DEBUG);
359
-			$this->access->connection->writeToCache('userExists'.$uid, false);
360
-			return false;
361
-		}
362
-
363
-		$this->access->connection->writeToCache('userExists'.$uid, true);
364
-		return true;
365
-	}
366
-
367
-	/**
368
-	 * returns whether a user was deleted in LDAP
369
-	 *
370
-	 * @param string $uid The username of the user to delete
371
-	 * @return bool
372
-	 */
373
-	public function deleteUser($uid) {
374
-		if ($this->userPluginManager->canDeleteUser()) {
375
-			$status = $this->userPluginManager->deleteUser($uid);
376
-			if($status === false) {
377
-				return false;
378
-			}
379
-		}
380
-
381
-		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
382
-		if((int)$marked === 0) {
383
-			\OC::$server->getLogger()->notice(
384
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
385
-				['app' => 'user_ldap']);
386
-			return false;
387
-		}
388
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
389
-			['app' => 'user_ldap']);
390
-
391
-		$this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
392
-		$this->access->userManager->invalidate($uid);
393
-		return true;
394
-	}
395
-
396
-	/**
397
-	 * get the user's home directory
398
-	 *
399
-	 * @param string $uid the username
400
-	 * @return bool|string
401
-	 * @throws NoUserException
402
-	 * @throws \Exception
403
-	 */
404
-	public function getHome($uid) {
405
-		// user Exists check required as it is not done in user proxy!
406
-		if(!$this->userExists($uid)) {
407
-			return false;
408
-		}
409
-
410
-		if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
411
-			return $this->userPluginManager->getHome($uid);
412
-		}
413
-
414
-		$cacheKey = 'getHome'.$uid;
415
-		$path = $this->access->connection->getFromCache($cacheKey);
416
-		if(!is_null($path)) {
417
-			return $path;
418
-		}
419
-
420
-		// early return path if it is a deleted user
421
-		$user = $this->access->userManager->get($uid);
422
-		if($user instanceof User || $user instanceof OfflineUser) {
423
-			$path = $user->getHomePath() ?: false;
424
-		} else {
425
-			throw new NoUserException($uid . ' is not a valid user anymore');
426
-		}
427
-
428
-		$this->access->cacheUserHome($uid, $path);
429
-		return $path;
430
-	}
431
-
432
-	/**
433
-	 * get display name of the user
434
-	 * @param string $uid user ID of the user
435
-	 * @return string|false display name
436
-	 */
437
-	public function getDisplayName($uid) {
438
-		if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
439
-			return $this->userPluginManager->getDisplayName($uid);
440
-		}
441
-
442
-		if(!$this->userExists($uid)) {
443
-			return false;
444
-		}
445
-
446
-		$cacheKey = 'getDisplayName'.$uid;
447
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
448
-			return $displayName;
449
-		}
450
-
451
-		//Check whether the display name is configured to have a 2nd feature
452
-		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
453
-		$displayName2 = '';
454
-		if ($additionalAttribute !== '') {
455
-			$displayName2 = $this->access->readAttribute(
456
-				$this->access->username2dn($uid),
457
-				$additionalAttribute);
458
-		}
459
-
460
-		$displayName = $this->access->readAttribute(
461
-			$this->access->username2dn($uid),
462
-			$this->access->connection->ldapUserDisplayName);
463
-
464
-		if($displayName && (count($displayName) > 0)) {
465
-			$displayName = $displayName[0];
466
-
467
-			if (is_array($displayName2)){
468
-				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
469
-			}
470
-
471
-			$user = $this->access->userManager->get($uid);
472
-			if ($user instanceof User) {
473
-				$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
474
-				$this->access->connection->writeToCache($cacheKey, $displayName);
475
-			}
476
-			if ($user instanceof OfflineUser) {
477
-				/** @var OfflineUser $user*/
478
-				$displayName = $user->getDisplayName();
479
-			}
480
-			return $displayName;
481
-		}
482
-
483
-		return null;
484
-	}
485
-
486
-	/**
487
-	 * set display name of the user
488
-	 * @param string $uid user ID of the user
489
-	 * @param string $displayName new display name of the user
490
-	 * @return string|false display name
491
-	 */
492
-	public function setDisplayName($uid, $displayName) {
493
-		if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
494
-			$this->userPluginManager->setDisplayName($uid, $displayName);
495
-			$this->access->cacheUserDisplayName($uid, $displayName);
496
-			return $displayName;
497
-		}
498
-		return false;
499
-	}
500
-
501
-	/**
502
-	 * Get a list of all display names
503
-	 *
504
-	 * @param string $search
505
-	 * @param string|null $limit
506
-	 * @param string|null $offset
507
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
508
-	 */
509
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
510
-		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
511
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
512
-			return $displayNames;
513
-		}
514
-
515
-		$displayNames = [];
516
-		$users = $this->getUsers($search, $limit, $offset);
517
-		foreach ($users as $user) {
518
-			$displayNames[$user] = $this->getDisplayName($user);
519
-		}
520
-		$this->access->connection->writeToCache($cacheKey, $displayNames);
521
-		return $displayNames;
522
-	}
523
-
524
-	/**
525
-	 * Check if backend implements actions
526
-	 * @param int $actions bitwise-or'ed actions
527
-	 * @return boolean
528
-	 *
529
-	 * Returns the supported actions as int to be
530
-	 * compared with \OC\User\Backend::CREATE_USER etc.
531
-	 */
532
-	public function implementsActions($actions) {
533
-		return (bool)((Backend::CHECK_PASSWORD
534
-			| Backend::GET_HOME
535
-			| Backend::GET_DISPLAYNAME
536
-			| (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
537
-			| Backend::COUNT_USERS
538
-			| (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
539
-			| $this->userPluginManager->getImplementedActions())
540
-			& $actions);
541
-	}
542
-
543
-	/**
544
-	 * @return bool
545
-	 */
546
-	public function hasUserListings() {
547
-		return true;
548
-	}
549
-
550
-	/**
551
-	 * counts the users in LDAP
552
-	 *
553
-	 * @return int|bool
554
-	 */
555
-	public function countUsers() {
556
-		if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
557
-			return $this->userPluginManager->countUsers();
558
-		}
559
-
560
-		$filter = $this->access->getFilterForUserCount();
561
-		$cacheKey = 'countUsers-'.$filter;
562
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
563
-			return $entries;
564
-		}
565
-		$entries = $this->access->countUsers($filter);
566
-		$this->access->connection->writeToCache($cacheKey, $entries);
567
-		return $entries;
568
-	}
569
-
570
-	/**
571
-	 * Backend name to be shown in user management
572
-	 * @return string the name of the backend to be shown
573
-	 */
574
-	public function getBackendName() {
575
-		return 'LDAP';
576
-	}
138
+    /**
139
+     * returns the username for the given LDAP DN, if available
140
+     *
141
+     * @param string $dn
142
+     * @return string|false with the username
143
+     */
144
+    public function dn2UserName($dn) {
145
+        return $this->access->dn2username($dn);
146
+    }
147
+
148
+    /**
149
+     * returns an LDAP record based on a given login name
150
+     *
151
+     * @param string $loginName
152
+     * @return array
153
+     * @throws NotOnLDAP
154
+     */
155
+    public function getLDAPUserByLoginName($loginName) {
156
+        //find out dn of the user name
157
+        $attrs = $this->access->userManager->getAttributes();
158
+        $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
159
+        if(count($users) < 1) {
160
+            throw new NotOnLDAP('No user available for the given login name on ' .
161
+                $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
162
+        }
163
+        return $users[0];
164
+    }
165
+
166
+    /**
167
+     * Check if the password is correct without logging in the user
168
+     *
169
+     * @param string $uid The username
170
+     * @param string $password The password
171
+     * @return false|string
172
+     */
173
+    public function checkPassword($uid, $password) {
174
+        try {
175
+            $ldapRecord = $this->getLDAPUserByLoginName($uid);
176
+        } catch(NotOnLDAP $e) {
177
+            \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
178
+            return false;
179
+        }
180
+        $dn = $ldapRecord['dn'][0];
181
+        $user = $this->access->userManager->get($dn);
182
+
183
+        if(!$user instanceof User) {
184
+            Util::writeLog('user_ldap',
185
+                'LDAP Login: Could not get user object for DN ' . $dn .
186
+                '. Maybe the LDAP entry has no set display name attribute?',
187
+                ILogger::WARN);
188
+            return false;
189
+        }
190
+        if($user->getUsername() !== false) {
191
+            //are the credentials OK?
192
+            if(!$this->access->areCredentialsValid($dn, $password)) {
193
+                return false;
194
+            }
195
+
196
+            $this->access->cacheUserExists($user->getUsername());
197
+            $user->processAttributes($ldapRecord);
198
+            $user->markLogin();
199
+
200
+            return $user->getUsername();
201
+        }
202
+
203
+        return false;
204
+    }
205
+
206
+    /**
207
+     * Set password
208
+     * @param string $uid The username
209
+     * @param string $password The new password
210
+     * @return bool
211
+     */
212
+    public function setPassword($uid, $password) {
213
+        if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
214
+            return $this->userPluginManager->setPassword($uid, $password);
215
+        }
216
+
217
+        $user = $this->access->userManager->get($uid);
218
+
219
+        if(!$user instanceof User) {
220
+            throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
221
+                '. Maybe the LDAP entry has no set display name attribute?');
222
+        }
223
+        if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
224
+            $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
225
+            $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
226
+            if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
227
+                //remove last password expiry warning if any
228
+                $notification = $this->notificationManager->createNotification();
229
+                $notification->setApp('user_ldap')
230
+                    ->setUser($uid)
231
+                    ->setObject('pwd_exp_warn', $uid)
232
+                ;
233
+                $this->notificationManager->markProcessed($notification);
234
+            }
235
+            return true;
236
+        }
237
+
238
+        return false;
239
+    }
240
+
241
+    /**
242
+     * Get a list of all users
243
+     *
244
+     * @param string $search
245
+     * @param integer $limit
246
+     * @param integer $offset
247
+     * @return string[] an array of all uids
248
+     */
249
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
250
+        $search = $this->access->escapeFilterPart($search, true);
251
+        $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
252
+
253
+        //check if users are cached, if so return
254
+        $ldap_users = $this->access->connection->getFromCache($cachekey);
255
+        if(!is_null($ldap_users)) {
256
+            return $ldap_users;
257
+        }
258
+
259
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
260
+        // error. With a limit of 0, we get 0 results. So we pass null.
261
+        if($limit <= 0) {
262
+            $limit = null;
263
+        }
264
+        $filter = $this->access->combineFilterWithAnd([
265
+            $this->access->connection->ldapUserFilter,
266
+            $this->access->connection->ldapUserDisplayName . '=*',
267
+            $this->access->getFilterPartForUserSearch($search)
268
+        ]);
269
+
270
+        Util::writeLog('user_ldap',
271
+            'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
272
+            ILogger::DEBUG);
273
+        //do the search and translate results to Nextcloud names
274
+        $ldap_users = $this->access->fetchListOfUsers(
275
+            $filter,
276
+            $this->access->userManager->getAttributes(true),
277
+            $limit, $offset);
278
+        $ldap_users = $this->access->nextcloudUserNames($ldap_users);
279
+        Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
280
+
281
+        $this->access->connection->writeToCache($cachekey, $ldap_users);
282
+        return $ldap_users;
283
+    }
284
+
285
+    /**
286
+     * checks whether a user is still available on LDAP
287
+     *
288
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
289
+     * name or an instance of that user
290
+     * @return bool
291
+     * @throws \Exception
292
+     * @throws \OC\ServerNotAvailableException
293
+     */
294
+    public function userExistsOnLDAP($user) {
295
+        if(is_string($user)) {
296
+            $user = $this->access->userManager->get($user);
297
+        }
298
+        if(is_null($user)) {
299
+            return false;
300
+        }
301
+        $uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
302
+        $cacheKey = 'userExistsOnLDAP' . $uid;
303
+        $userExists = $this->access->connection->getFromCache($cacheKey);
304
+        if(!is_null($userExists)) {
305
+            return (bool)$userExists;
306
+        }
307
+
308
+        $dn = $user->getDN();
309
+        //check if user really still exists by reading its entry
310
+        if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
311
+            try {
312
+                $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
313
+                if (!$uuid) {
314
+                    $this->access->connection->writeToCache($cacheKey, false);
315
+                    return false;
316
+                }
317
+                $newDn = $this->access->getUserDnByUuid($uuid);
318
+                //check if renamed user is still valid by reapplying the ldap filter
319
+                if ($newDn === $dn || !is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
320
+                    $this->access->connection->writeToCache($cacheKey, false);
321
+                    return false;
322
+                }
323
+                $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
324
+                $this->access->connection->writeToCache($cacheKey, true);
325
+                return true;
326
+            } catch (ServerNotAvailableException $e) {
327
+                throw $e;
328
+            } catch (\Exception $e) {
329
+                $this->access->connection->writeToCache($cacheKey, false);
330
+                return false;
331
+            }
332
+        }
333
+
334
+        if($user instanceof OfflineUser) {
335
+            $user->unmark();
336
+        }
337
+
338
+        $this->access->connection->writeToCache($cacheKey, true);
339
+        return true;
340
+    }
341
+
342
+    /**
343
+     * check if a user exists
344
+     * @param string $uid the username
345
+     * @return boolean
346
+     * @throws \Exception when connection could not be established
347
+     */
348
+    public function userExists($uid) {
349
+        $userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
+        if(!is_null($userExists)) {
351
+            return (bool)$userExists;
352
+        }
353
+        //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354
+        $user = $this->access->userManager->get($uid);
355
+
356
+        if(is_null($user)) {
357
+            Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358
+                $this->access->connection->ldapHost, ILogger::DEBUG);
359
+            $this->access->connection->writeToCache('userExists'.$uid, false);
360
+            return false;
361
+        }
362
+
363
+        $this->access->connection->writeToCache('userExists'.$uid, true);
364
+        return true;
365
+    }
366
+
367
+    /**
368
+     * returns whether a user was deleted in LDAP
369
+     *
370
+     * @param string $uid The username of the user to delete
371
+     * @return bool
372
+     */
373
+    public function deleteUser($uid) {
374
+        if ($this->userPluginManager->canDeleteUser()) {
375
+            $status = $this->userPluginManager->deleteUser($uid);
376
+            if($status === false) {
377
+                return false;
378
+            }
379
+        }
380
+
381
+        $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
382
+        if((int)$marked === 0) {
383
+            \OC::$server->getLogger()->notice(
384
+                'User '.$uid . ' is not marked as deleted, not cleaning up.',
385
+                ['app' => 'user_ldap']);
386
+            return false;
387
+        }
388
+        \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
389
+            ['app' => 'user_ldap']);
390
+
391
+        $this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
392
+        $this->access->userManager->invalidate($uid);
393
+        return true;
394
+    }
395
+
396
+    /**
397
+     * get the user's home directory
398
+     *
399
+     * @param string $uid the username
400
+     * @return bool|string
401
+     * @throws NoUserException
402
+     * @throws \Exception
403
+     */
404
+    public function getHome($uid) {
405
+        // user Exists check required as it is not done in user proxy!
406
+        if(!$this->userExists($uid)) {
407
+            return false;
408
+        }
409
+
410
+        if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
411
+            return $this->userPluginManager->getHome($uid);
412
+        }
413
+
414
+        $cacheKey = 'getHome'.$uid;
415
+        $path = $this->access->connection->getFromCache($cacheKey);
416
+        if(!is_null($path)) {
417
+            return $path;
418
+        }
419
+
420
+        // early return path if it is a deleted user
421
+        $user = $this->access->userManager->get($uid);
422
+        if($user instanceof User || $user instanceof OfflineUser) {
423
+            $path = $user->getHomePath() ?: false;
424
+        } else {
425
+            throw new NoUserException($uid . ' is not a valid user anymore');
426
+        }
427
+
428
+        $this->access->cacheUserHome($uid, $path);
429
+        return $path;
430
+    }
431
+
432
+    /**
433
+     * get display name of the user
434
+     * @param string $uid user ID of the user
435
+     * @return string|false display name
436
+     */
437
+    public function getDisplayName($uid) {
438
+        if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
439
+            return $this->userPluginManager->getDisplayName($uid);
440
+        }
441
+
442
+        if(!$this->userExists($uid)) {
443
+            return false;
444
+        }
445
+
446
+        $cacheKey = 'getDisplayName'.$uid;
447
+        if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
448
+            return $displayName;
449
+        }
450
+
451
+        //Check whether the display name is configured to have a 2nd feature
452
+        $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
453
+        $displayName2 = '';
454
+        if ($additionalAttribute !== '') {
455
+            $displayName2 = $this->access->readAttribute(
456
+                $this->access->username2dn($uid),
457
+                $additionalAttribute);
458
+        }
459
+
460
+        $displayName = $this->access->readAttribute(
461
+            $this->access->username2dn($uid),
462
+            $this->access->connection->ldapUserDisplayName);
463
+
464
+        if($displayName && (count($displayName) > 0)) {
465
+            $displayName = $displayName[0];
466
+
467
+            if (is_array($displayName2)){
468
+                $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
469
+            }
470
+
471
+            $user = $this->access->userManager->get($uid);
472
+            if ($user instanceof User) {
473
+                $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
474
+                $this->access->connection->writeToCache($cacheKey, $displayName);
475
+            }
476
+            if ($user instanceof OfflineUser) {
477
+                /** @var OfflineUser $user*/
478
+                $displayName = $user->getDisplayName();
479
+            }
480
+            return $displayName;
481
+        }
482
+
483
+        return null;
484
+    }
485
+
486
+    /**
487
+     * set display name of the user
488
+     * @param string $uid user ID of the user
489
+     * @param string $displayName new display name of the user
490
+     * @return string|false display name
491
+     */
492
+    public function setDisplayName($uid, $displayName) {
493
+        if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
494
+            $this->userPluginManager->setDisplayName($uid, $displayName);
495
+            $this->access->cacheUserDisplayName($uid, $displayName);
496
+            return $displayName;
497
+        }
498
+        return false;
499
+    }
500
+
501
+    /**
502
+     * Get a list of all display names
503
+     *
504
+     * @param string $search
505
+     * @param string|null $limit
506
+     * @param string|null $offset
507
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
508
+     */
509
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
510
+        $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
511
+        if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
512
+            return $displayNames;
513
+        }
514
+
515
+        $displayNames = [];
516
+        $users = $this->getUsers($search, $limit, $offset);
517
+        foreach ($users as $user) {
518
+            $displayNames[$user] = $this->getDisplayName($user);
519
+        }
520
+        $this->access->connection->writeToCache($cacheKey, $displayNames);
521
+        return $displayNames;
522
+    }
523
+
524
+    /**
525
+     * Check if backend implements actions
526
+     * @param int $actions bitwise-or'ed actions
527
+     * @return boolean
528
+     *
529
+     * Returns the supported actions as int to be
530
+     * compared with \OC\User\Backend::CREATE_USER etc.
531
+     */
532
+    public function implementsActions($actions) {
533
+        return (bool)((Backend::CHECK_PASSWORD
534
+            | Backend::GET_HOME
535
+            | Backend::GET_DISPLAYNAME
536
+            | (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
537
+            | Backend::COUNT_USERS
538
+            | (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
539
+            | $this->userPluginManager->getImplementedActions())
540
+            & $actions);
541
+    }
542
+
543
+    /**
544
+     * @return bool
545
+     */
546
+    public function hasUserListings() {
547
+        return true;
548
+    }
549
+
550
+    /**
551
+     * counts the users in LDAP
552
+     *
553
+     * @return int|bool
554
+     */
555
+    public function countUsers() {
556
+        if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
557
+            return $this->userPluginManager->countUsers();
558
+        }
559
+
560
+        $filter = $this->access->getFilterForUserCount();
561
+        $cacheKey = 'countUsers-'.$filter;
562
+        if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
563
+            return $entries;
564
+        }
565
+        $entries = $this->access->countUsers($filter);
566
+        $this->access->connection->writeToCache($cacheKey, $entries);
567
+        return $entries;
568
+    }
569
+
570
+    /**
571
+     * Backend name to be shown in user management
572
+     * @return string the name of the backend to be shown
573
+     */
574
+    public function getBackendName() {
575
+        return 'LDAP';
576
+    }
577 577
 	
578
-	/**
579
-	 * Return access for LDAP interaction.
580
-	 * @param string $uid
581
-	 * @return Access instance of Access for LDAP interaction
582
-	 */
583
-	public function getLDAPAccess($uid) {
584
-		return $this->access;
585
-	}
578
+    /**
579
+     * Return access for LDAP interaction.
580
+     * @param string $uid
581
+     * @return Access instance of Access for LDAP interaction
582
+     */
583
+    public function getLDAPAccess($uid) {
584
+        return $this->access;
585
+    }
586 586
 	
587
-	/**
588
-	 * Return LDAP connection resource from a cloned connection.
589
-	 * The cloned connection needs to be closed manually.
590
-	 * of the current access.
591
-	 * @param string $uid
592
-	 * @return resource of the LDAP connection
593
-	 */
594
-	public function getNewLDAPConnection($uid) {
595
-		$connection = clone $this->access->getConnection();
596
-		return $connection->getConnectionResource();
597
-	}
598
-
599
-	/**
600
-	 * create new user
601
-	 * @param string $username username of the new user
602
-	 * @param string $password password of the new user
603
-	 * @throws \UnexpectedValueException
604
-	 * @return bool
605
-	 */
606
-	public function createUser($username, $password) {
607
-		if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
608
-			if ($dn = $this->userPluginManager->createUser($username, $password)) {
609
-				if (is_string($dn)) {
610
-					// the NC user creation work flow requires a know user id up front
611
-					$uuid = $this->access->getUUID($dn, true);
612
-					if(is_string($uuid)) {
613
-						$this->access->mapAndAnnounceIfApplicable(
614
-							$this->access->getUserMapper(),
615
-							$dn,
616
-							$username,
617
-							$uuid,
618
-							true
619
-						);
620
-						$this->access->cacheUserExists($username);
621
-					} else {
622
-						\OC::$server->getLogger()->warning(
623
-							'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
624
-							[
625
-								'app' => 'user_ldap',
626
-								'userid' => $username,
627
-							]
628
-						);
629
-					}
630
-				} else {
631
-					throw new \UnexpectedValueException("LDAP Plugin: Method createUser changed to return the user DN instead of boolean.");
632
-				}
633
-			}
634
-			return (bool) $dn;
635
-		}
636
-		return false;
637
-	}
587
+    /**
588
+     * Return LDAP connection resource from a cloned connection.
589
+     * The cloned connection needs to be closed manually.
590
+     * of the current access.
591
+     * @param string $uid
592
+     * @return resource of the LDAP connection
593
+     */
594
+    public function getNewLDAPConnection($uid) {
595
+        $connection = clone $this->access->getConnection();
596
+        return $connection->getConnectionResource();
597
+    }
598
+
599
+    /**
600
+     * create new user
601
+     * @param string $username username of the new user
602
+     * @param string $password password of the new user
603
+     * @throws \UnexpectedValueException
604
+     * @return bool
605
+     */
606
+    public function createUser($username, $password) {
607
+        if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
608
+            if ($dn = $this->userPluginManager->createUser($username, $password)) {
609
+                if (is_string($dn)) {
610
+                    // the NC user creation work flow requires a know user id up front
611
+                    $uuid = $this->access->getUUID($dn, true);
612
+                    if(is_string($uuid)) {
613
+                        $this->access->mapAndAnnounceIfApplicable(
614
+                            $this->access->getUserMapper(),
615
+                            $dn,
616
+                            $username,
617
+                            $uuid,
618
+                            true
619
+                        );
620
+                        $this->access->cacheUserExists($username);
621
+                    } else {
622
+                        \OC::$server->getLogger()->warning(
623
+                            'Failed to map created LDAP user with userid {userid}, because UUID could not be determined',
624
+                            [
625
+                                'app' => 'user_ldap',
626
+                                'userid' => $username,
627
+                            ]
628
+                        );
629
+                    }
630
+                } else {
631
+                    throw new \UnexpectedValueException("LDAP Plugin: Method createUser changed to return the user DN instead of boolean.");
632
+                }
633
+            }
634
+            return (bool) $dn;
635
+        }
636
+        return false;
637
+    }
638 638
 
639 639
 }
Please login to merge, or discard this patch.
Spacing   +47 added lines, -47 removed lines patch added patch discarded remove patch
@@ -87,16 +87,16 @@  discard block
 block discarded – undo
87 87
 			return $this->userPluginManager->canChangeAvatar($uid);
88 88
 		}
89 89
 
90
-		if(!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
90
+		if (!$this->implementsActions(Backend::PROVIDE_AVATAR)) {
91 91
 			return true;
92 92
 		}
93 93
 
94 94
 		$user = $this->access->userManager->get($uid);
95
-		if(!$user instanceof User) {
95
+		if (!$user instanceof User) {
96 96
 			return false;
97 97
 		}
98 98
 		$imageData = $user->getAvatarImage();
99
-		if($imageData === false) {
99
+		if ($imageData === false) {
100 100
 			return true;
101 101
 		}
102 102
 		return !$user->updateAvatar(true);
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 	 * @throws \Exception
111 111
 	 */
112 112
 	public function loginName2UserName($loginName) {
113
-		$cacheKey = 'loginName2UserName-' . $loginName;
113
+		$cacheKey = 'loginName2UserName-'.$loginName;
114 114
 		$username = $this->access->connection->getFromCache($cacheKey);
115 115
 
116 116
 		if ($username !== null) {
@@ -156,9 +156,9 @@  discard block
 block discarded – undo
156 156
 		//find out dn of the user name
157 157
 		$attrs = $this->access->userManager->getAttributes();
158 158
 		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
159
-		if(count($users) < 1) {
160
-			throw new NotOnLDAP('No user available for the given login name on ' .
161
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
159
+		if (count($users) < 1) {
160
+			throw new NotOnLDAP('No user available for the given login name on '.
161
+				$this->access->connection->ldapHost.':'.$this->access->connection->ldapPort);
162 162
 		}
163 163
 		return $users[0];
164 164
 	}
@@ -173,23 +173,23 @@  discard block
 block discarded – undo
173 173
 	public function checkPassword($uid, $password) {
174 174
 		try {
175 175
 			$ldapRecord = $this->getLDAPUserByLoginName($uid);
176
-		} catch(NotOnLDAP $e) {
176
+		} catch (NotOnLDAP $e) {
177 177
 			\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap', 'level' => ILogger::DEBUG]);
178 178
 			return false;
179 179
 		}
180 180
 		$dn = $ldapRecord['dn'][0];
181 181
 		$user = $this->access->userManager->get($dn);
182 182
 
183
-		if(!$user instanceof User) {
183
+		if (!$user instanceof User) {
184 184
 			Util::writeLog('user_ldap',
185
-				'LDAP Login: Could not get user object for DN ' . $dn .
185
+				'LDAP Login: Could not get user object for DN '.$dn.
186 186
 				'. Maybe the LDAP entry has no set display name attribute?',
187 187
 				ILogger::WARN);
188 188
 			return false;
189 189
 		}
190
-		if($user->getUsername() !== false) {
190
+		if ($user->getUsername() !== false) {
191 191
 			//are the credentials OK?
192
-			if(!$this->access->areCredentialsValid($dn, $password)) {
192
+			if (!$this->access->areCredentialsValid($dn, $password)) {
193 193
 				return false;
194 194
 			}
195 195
 
@@ -216,14 +216,14 @@  discard block
 block discarded – undo
216 216
 
217 217
 		$user = $this->access->userManager->get($uid);
218 218
 
219
-		if(!$user instanceof User) {
220
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
219
+		if (!$user instanceof User) {
220
+			throw new \Exception('LDAP setPassword: Could not get user object for uid '.$uid.
221 221
 				'. Maybe the LDAP entry has no set display name attribute?');
222 222
 		}
223
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
223
+		if ($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
224 224
 			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
225 225
 			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
226
-			if (!empty($ldapDefaultPPolicyDN) && ((int)$turnOnPasswordChange === 1)) {
226
+			if (!empty($ldapDefaultPPolicyDN) && ((int) $turnOnPasswordChange === 1)) {
227 227
 				//remove last password expiry warning if any
228 228
 				$notification = $this->notificationManager->createNotification();
229 229
 				$notification->setApp('user_ldap')
@@ -252,18 +252,18 @@  discard block
 block discarded – undo
252 252
 
253 253
 		//check if users are cached, if so return
254 254
 		$ldap_users = $this->access->connection->getFromCache($cachekey);
255
-		if(!is_null($ldap_users)) {
255
+		if (!is_null($ldap_users)) {
256 256
 			return $ldap_users;
257 257
 		}
258 258
 
259 259
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
260 260
 		// error. With a limit of 0, we get 0 results. So we pass null.
261
-		if($limit <= 0) {
261
+		if ($limit <= 0) {
262 262
 			$limit = null;
263 263
 		}
264 264
 		$filter = $this->access->combineFilterWithAnd([
265 265
 			$this->access->connection->ldapUserFilter,
266
-			$this->access->connection->ldapUserDisplayName . '=*',
266
+			$this->access->connection->ldapUserDisplayName.'=*',
267 267
 			$this->access->getFilterPartForUserSearch($search)
268 268
 		]);
269 269
 
@@ -276,7 +276,7 @@  discard block
 block discarded – undo
276 276
 			$this->access->userManager->getAttributes(true),
277 277
 			$limit, $offset);
278 278
 		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
279
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', ILogger::DEBUG);
279
+		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users).' Users found', ILogger::DEBUG);
280 280
 
281 281
 		$this->access->connection->writeToCache($cachekey, $ldap_users);
282 282
 		return $ldap_users;
@@ -292,22 +292,22 @@  discard block
 block discarded – undo
292 292
 	 * @throws \OC\ServerNotAvailableException
293 293
 	 */
294 294
 	public function userExistsOnLDAP($user) {
295
-		if(is_string($user)) {
295
+		if (is_string($user)) {
296 296
 			$user = $this->access->userManager->get($user);
297 297
 		}
298
-		if(is_null($user)) {
298
+		if (is_null($user)) {
299 299
 			return false;
300 300
 		}
301 301
 		$uid = $user instanceof User ? $user->getUsername() : $user->getOCName();
302
-		$cacheKey = 'userExistsOnLDAP' . $uid;
302
+		$cacheKey = 'userExistsOnLDAP'.$uid;
303 303
 		$userExists = $this->access->connection->getFromCache($cacheKey);
304
-		if(!is_null($userExists)) {
305
-			return (bool)$userExists;
304
+		if (!is_null($userExists)) {
305
+			return (bool) $userExists;
306 306
 		}
307 307
 
308 308
 		$dn = $user->getDN();
309 309
 		//check if user really still exists by reading its entry
310
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
310
+		if (!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
311 311
 			try {
312 312
 				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
313 313
 				if (!$uuid) {
@@ -331,7 +331,7 @@  discard block
 block discarded – undo
331 331
 			}
332 332
 		}
333 333
 
334
-		if($user instanceof OfflineUser) {
334
+		if ($user instanceof OfflineUser) {
335 335
 			$user->unmark();
336 336
 		}
337 337
 
@@ -347,13 +347,13 @@  discard block
 block discarded – undo
347 347
 	 */
348 348
 	public function userExists($uid) {
349 349
 		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
-		if(!is_null($userExists)) {
351
-			return (bool)$userExists;
350
+		if (!is_null($userExists)) {
351
+			return (bool) $userExists;
352 352
 		}
353 353
 		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354 354
 		$user = $this->access->userManager->get($uid);
355 355
 
356
-		if(is_null($user)) {
356
+		if (is_null($user)) {
357 357
 			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358 358
 				$this->access->connection->ldapHost, ILogger::DEBUG);
359 359
 			$this->access->connection->writeToCache('userExists'.$uid, false);
@@ -373,19 +373,19 @@  discard block
 block discarded – undo
373 373
 	public function deleteUser($uid) {
374 374
 		if ($this->userPluginManager->canDeleteUser()) {
375 375
 			$status = $this->userPluginManager->deleteUser($uid);
376
-			if($status === false) {
376
+			if ($status === false) {
377 377
 				return false;
378 378
 			}
379 379
 		}
380 380
 
381 381
 		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
382
-		if((int)$marked === 0) {
382
+		if ((int) $marked === 0) {
383 383
 			\OC::$server->getLogger()->notice(
384
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
384
+				'User '.$uid.' is not marked as deleted, not cleaning up.',
385 385
 				['app' => 'user_ldap']);
386 386
 			return false;
387 387
 		}
388
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
388
+		\OC::$server->getLogger()->info('Cleaning up after user '.$uid,
389 389
 			['app' => 'user_ldap']);
390 390
 
391 391
 		$this->access->getUserMapper()->unmap($uid); // we don't emit unassign signals here, since it is implicit to delete signals fired from core
@@ -403,7 +403,7 @@  discard block
 block discarded – undo
403 403
 	 */
404 404
 	public function getHome($uid) {
405 405
 		// user Exists check required as it is not done in user proxy!
406
-		if(!$this->userExists($uid)) {
406
+		if (!$this->userExists($uid)) {
407 407
 			return false;
408 408
 		}
409 409
 
@@ -413,16 +413,16 @@  discard block
 block discarded – undo
413 413
 
414 414
 		$cacheKey = 'getHome'.$uid;
415 415
 		$path = $this->access->connection->getFromCache($cacheKey);
416
-		if(!is_null($path)) {
416
+		if (!is_null($path)) {
417 417
 			return $path;
418 418
 		}
419 419
 
420 420
 		// early return path if it is a deleted user
421 421
 		$user = $this->access->userManager->get($uid);
422
-		if($user instanceof User || $user instanceof OfflineUser) {
422
+		if ($user instanceof User || $user instanceof OfflineUser) {
423 423
 			$path = $user->getHomePath() ?: false;
424 424
 		} else {
425
-			throw new NoUserException($uid . ' is not a valid user anymore');
425
+			throw new NoUserException($uid.' is not a valid user anymore');
426 426
 		}
427 427
 
428 428
 		$this->access->cacheUserHome($uid, $path);
@@ -439,12 +439,12 @@  discard block
 block discarded – undo
439 439
 			return $this->userPluginManager->getDisplayName($uid);
440 440
 		}
441 441
 
442
-		if(!$this->userExists($uid)) {
442
+		if (!$this->userExists($uid)) {
443 443
 			return false;
444 444
 		}
445 445
 
446 446
 		$cacheKey = 'getDisplayName'.$uid;
447
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
447
+		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
448 448
 			return $displayName;
449 449
 		}
450 450
 
@@ -461,10 +461,10 @@  discard block
 block discarded – undo
461 461
 			$this->access->username2dn($uid),
462 462
 			$this->access->connection->ldapUserDisplayName);
463 463
 
464
-		if($displayName && (count($displayName) > 0)) {
464
+		if ($displayName && (count($displayName) > 0)) {
465 465
 			$displayName = $displayName[0];
466 466
 
467
-			if (is_array($displayName2)){
467
+			if (is_array($displayName2)) {
468 468
 				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
469 469
 			}
470 470
 
@@ -508,7 +508,7 @@  discard block
 block discarded – undo
508 508
 	 */
509 509
 	public function getDisplayNames($search = '', $limit = null, $offset = null) {
510 510
 		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
511
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
511
+		if (!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
512 512
 			return $displayNames;
513 513
 		}
514 514
 
@@ -530,12 +530,12 @@  discard block
 block discarded – undo
530 530
 	 * compared with \OC\User\Backend::CREATE_USER etc.
531 531
 	 */
532 532
 	public function implementsActions($actions) {
533
-		return (bool)((Backend::CHECK_PASSWORD
533
+		return (bool) ((Backend::CHECK_PASSWORD
534 534
 			| Backend::GET_HOME
535 535
 			| Backend::GET_DISPLAYNAME
536 536
 			| (($this->access->connection->ldapUserAvatarRule !== 'none') ? Backend::PROVIDE_AVATAR : 0)
537 537
 			| Backend::COUNT_USERS
538
-			| (((int)$this->access->connection->turnOnPasswordChange === 1)? Backend::SET_PASSWORD :0)
538
+			| (((int) $this->access->connection->turnOnPasswordChange === 1) ? Backend::SET_PASSWORD : 0)
539 539
 			| $this->userPluginManager->getImplementedActions())
540 540
 			& $actions);
541 541
 	}
@@ -559,7 +559,7 @@  discard block
 block discarded – undo
559 559
 
560 560
 		$filter = $this->access->getFilterForUserCount();
561 561
 		$cacheKey = 'countUsers-'.$filter;
562
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
562
+		if (!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
563 563
 			return $entries;
564 564
 		}
565 565
 		$entries = $this->access->countUsers($filter);
@@ -609,7 +609,7 @@  discard block
 block discarded – undo
609 609
 				if (is_string($dn)) {
610 610
 					// the NC user creation work flow requires a know user id up front
611 611
 					$uuid = $this->access->getUUID($dn, true);
612
-					if(is_string($uuid)) {
612
+					if (is_string($uuid)) {
613 613
 						$this->access->mapAndAnnounceIfApplicable(
614 614
 							$this->access->getUserMapper(),
615 615
 							$dn,
Please login to merge, or discard this patch.
apps/user_ldap/lib/Access.php 2 patches
Indentation   +2028 added lines, -2028 removed lines patch added patch discarded remove patch
@@ -64,1779 +64,1779 @@  discard block
 block discarded – undo
64 64
  * @package OCA\User_LDAP
65 65
  */
66 66
 class Access extends LDAPUtility {
67
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
68
-
69
-	/** @var \OCA\User_LDAP\Connection */
70
-	public $connection;
71
-	/** @var Manager */
72
-	public $userManager;
73
-	//never ever check this var directly, always use getPagedSearchResultState
74
-	protected $pagedSearchedSuccessful;
75
-
76
-	/**
77
-	 * @var string[] $cookies an array of returned Paged Result cookies
78
-	 */
79
-	protected $cookies = [];
80
-
81
-	/**
82
-	 * @var string $lastCookie the last cookie returned from a Paged Results
83
-	 * operation, defaults to an empty string
84
-	 */
85
-	protected $lastCookie = '';
86
-
87
-	/**
88
-	 * @var AbstractMapping $userMapper
89
-	 */
90
-	protected $userMapper;
91
-
92
-	/**
93
-	 * @var AbstractMapping $userMapper
94
-	 */
95
-	protected $groupMapper;
96
-
97
-	/**
98
-	 * @var \OCA\User_LDAP\Helper
99
-	 */
100
-	private $helper;
101
-	/** @var IConfig */
102
-	private $config;
103
-	/** @var IUserManager */
104
-	private $ncUserManager;
105
-
106
-	public function __construct(
107
-		Connection $connection,
108
-		ILDAPWrapper $ldap,
109
-		Manager $userManager,
110
-		Helper $helper,
111
-		IConfig $config,
112
-		IUserManager $ncUserManager
113
-	) {
114
-		parent::__construct($ldap);
115
-		$this->connection = $connection;
116
-		$this->userManager = $userManager;
117
-		$this->userManager->setLdapAccess($this);
118
-		$this->helper = $helper;
119
-		$this->config = $config;
120
-		$this->ncUserManager = $ncUserManager;
121
-	}
122
-
123
-	/**
124
-	 * sets the User Mapper
125
-	 * @param AbstractMapping $mapper
126
-	 */
127
-	public function setUserMapper(AbstractMapping $mapper) {
128
-		$this->userMapper = $mapper;
129
-	}
130
-
131
-	/**
132
-	 * returns the User Mapper
133
-	 * @throws \Exception
134
-	 * @return AbstractMapping
135
-	 */
136
-	public function getUserMapper() {
137
-		if(is_null($this->userMapper)) {
138
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
139
-		}
140
-		return $this->userMapper;
141
-	}
142
-
143
-	/**
144
-	 * sets the Group Mapper
145
-	 * @param AbstractMapping $mapper
146
-	 */
147
-	public function setGroupMapper(AbstractMapping $mapper) {
148
-		$this->groupMapper = $mapper;
149
-	}
150
-
151
-	/**
152
-	 * returns the Group Mapper
153
-	 * @throws \Exception
154
-	 * @return AbstractMapping
155
-	 */
156
-	public function getGroupMapper() {
157
-		if(is_null($this->groupMapper)) {
158
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
159
-		}
160
-		return $this->groupMapper;
161
-	}
162
-
163
-	/**
164
-	 * @return bool
165
-	 */
166
-	private function checkConnection() {
167
-		return ($this->connection instanceof Connection);
168
-	}
169
-
170
-	/**
171
-	 * returns the Connection instance
172
-	 * @return \OCA\User_LDAP\Connection
173
-	 */
174
-	public function getConnection() {
175
-		return $this->connection;
176
-	}
177
-
178
-	/**
179
-	 * reads a given attribute for an LDAP record identified by a DN
180
-	 *
181
-	 * @param string $dn the record in question
182
-	 * @param string $attr the attribute that shall be retrieved
183
-	 *        if empty, just check the record's existence
184
-	 * @param string $filter
185
-	 * @return array|false an array of values on success or an empty
186
-	 *          array if $attr is empty, false otherwise
187
-	 * @throws ServerNotAvailableException
188
-	 */
189
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
190
-		if(!$this->checkConnection()) {
191
-			\OCP\Util::writeLog('user_ldap',
192
-				'No LDAP Connector assigned, access impossible for readAttribute.',
193
-				ILogger::WARN);
194
-			return false;
195
-		}
196
-		$cr = $this->connection->getConnectionResource();
197
-		if(!$this->ldap->isResource($cr)) {
198
-			//LDAP not available
199
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
200
-			return false;
201
-		}
202
-		//Cancel possibly running Paged Results operation, otherwise we run in
203
-		//LDAP protocol errors
204
-		$this->abandonPagedSearch();
205
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
206
-		// but does not hurt either.
207
-		$pagingSize = (int)$this->connection->ldapPagingSize;
208
-		// 0 won't result in replies, small numbers may leave out groups
209
-		// (cf. #12306), 500 is default for paging and should work everywhere.
210
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
211
-		$attr = mb_strtolower($attr, 'UTF-8');
212
-		// the actual read attribute later may contain parameters on a ranged
213
-		// request, e.g. member;range=99-199. Depends on server reply.
214
-		$attrToRead = $attr;
215
-
216
-		$values = [];
217
-		$isRangeRequest = false;
218
-		do {
219
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
220
-			if(is_bool($result)) {
221
-				// when an exists request was run and it was successful, an empty
222
-				// array must be returned
223
-				return $result ? [] : false;
224
-			}
225
-
226
-			if (!$isRangeRequest) {
227
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
228
-				if (!empty($values)) {
229
-					return $values;
230
-				}
231
-			}
232
-
233
-			$isRangeRequest = false;
234
-			$result = $this->extractRangeData($result, $attr);
235
-			if (!empty($result)) {
236
-				$normalizedResult = $this->extractAttributeValuesFromResult(
237
-					[ $attr => $result['values'] ],
238
-					$attr
239
-				);
240
-				$values = array_merge($values, $normalizedResult);
241
-
242
-				if($result['rangeHigh'] === '*') {
243
-					// when server replies with * as high range value, there are
244
-					// no more results left
245
-					return $values;
246
-				} else {
247
-					$low  = $result['rangeHigh'] + 1;
248
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
249
-					$isRangeRequest = true;
250
-				}
251
-			}
252
-		} while($isRangeRequest);
253
-
254
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
255
-		return false;
256
-	}
257
-
258
-	/**
259
-	 * Runs an read operation against LDAP
260
-	 *
261
-	 * @param resource $cr the LDAP connection
262
-	 * @param string $dn
263
-	 * @param string $attribute
264
-	 * @param string $filter
265
-	 * @param int $maxResults
266
-	 * @return array|bool false if there was any error, true if an exists check
267
-	 *                    was performed and the requested DN found, array with the
268
-	 *                    returned data on a successful usual operation
269
-	 * @throws ServerNotAvailableException
270
-	 */
271
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
272
-		$this->initPagedSearch($filter, [$dn], [$attribute], $maxResults, 0);
273
-		$dn = $this->helper->DNasBaseParameter($dn);
274
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
275
-		if (!$this->ldap->isResource($rr)) {
276
-			if ($attribute !== '') {
277
-				//do not throw this message on userExists check, irritates
278
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
279
-			}
280
-			//in case an error occurs , e.g. object does not exist
281
-			return false;
282
-		}
283
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
284
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
285
-			return true;
286
-		}
287
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
288
-		if (!$this->ldap->isResource($er)) {
289
-			//did not match the filter, return false
290
-			return false;
291
-		}
292
-		//LDAP attributes are not case sensitive
293
-		$result = \OCP\Util::mb_array_change_key_case(
294
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
295
-
296
-		return $result;
297
-	}
298
-
299
-	/**
300
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
301
-	 * data if present.
302
-	 *
303
-	 * @param array $result from ILDAPWrapper::getAttributes()
304
-	 * @param string $attribute the attribute name that was read
305
-	 * @return string[]
306
-	 */
307
-	public function extractAttributeValuesFromResult($result, $attribute) {
308
-		$values = [];
309
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
310
-			$lowercaseAttribute = strtolower($attribute);
311
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
312
-				if($this->resemblesDN($attribute)) {
313
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
314
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
315
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
316
-				} else {
317
-					$values[] = $result[$attribute][$i];
318
-				}
319
-			}
320
-		}
321
-		return $values;
322
-	}
323
-
324
-	/**
325
-	 * Attempts to find ranged data in a getAttribute results and extracts the
326
-	 * returned values as well as information on the range and full attribute
327
-	 * name for further processing.
328
-	 *
329
-	 * @param array $result from ILDAPWrapper::getAttributes()
330
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
331
-	 * @return array If a range was detected with keys 'values', 'attributeName',
332
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
333
-	 */
334
-	public function extractRangeData($result, $attribute) {
335
-		$keys = array_keys($result);
336
-		foreach($keys as $key) {
337
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
338
-				$queryData = explode(';', $key);
339
-				if(strpos($queryData[1], 'range=') === 0) {
340
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
341
-					$data = [
342
-						'values' => $result[$key],
343
-						'attributeName' => $queryData[0],
344
-						'attributeFull' => $key,
345
-						'rangeHigh' => $high,
346
-					];
347
-					return $data;
348
-				}
349
-			}
350
-		}
351
-		return [];
352
-	}
353
-
354
-	/**
355
-	 * Set password for an LDAP user identified by a DN
356
-	 *
357
-	 * @param string $userDN the user in question
358
-	 * @param string $password the new password
359
-	 * @return bool
360
-	 * @throws HintException
361
-	 * @throws \Exception
362
-	 */
363
-	public function setPassword($userDN, $password) {
364
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
365
-			throw new \Exception('LDAP password changes are disabled.');
366
-		}
367
-		$cr = $this->connection->getConnectionResource();
368
-		if(!$this->ldap->isResource($cr)) {
369
-			//LDAP not available
370
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
371
-			return false;
372
-		}
373
-		try {
374
-			// try PASSWD extended operation first
375
-			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
376
-						@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
377
-		} catch(ConstraintViolationException $e) {
378
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
379
-		}
380
-	}
381
-
382
-	/**
383
-	 * checks whether the given attributes value is probably a DN
384
-	 * @param string $attr the attribute in question
385
-	 * @return boolean if so true, otherwise false
386
-	 */
387
-	private function resemblesDN($attr) {
388
-		$resemblingAttributes = [
389
-			'dn',
390
-			'uniquemember',
391
-			'member',
392
-			// memberOf is an "operational" attribute, without a definition in any RFC
393
-			'memberof'
394
-		];
395
-		return in_array($attr, $resemblingAttributes);
396
-	}
397
-
398
-	/**
399
-	 * checks whether the given string is probably a DN
400
-	 * @param string $string
401
-	 * @return boolean
402
-	 */
403
-	public function stringResemblesDN($string) {
404
-		$r = $this->ldap->explodeDN($string, 0);
405
-		// if exploding a DN succeeds and does not end up in
406
-		// an empty array except for $r[count] being 0.
407
-		return (is_array($r) && count($r) > 1);
408
-	}
409
-
410
-	/**
411
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
412
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
413
-	 * becomes dc=foobar,dc=server,dc=org
414
-	 * @param string $dn
415
-	 * @return string
416
-	 */
417
-	public function getDomainDNFromDN($dn) {
418
-		$allParts = $this->ldap->explodeDN($dn, 0);
419
-		if($allParts === false) {
420
-			//not a valid DN
421
-			return '';
422
-		}
423
-		$domainParts = [];
424
-		$dcFound = false;
425
-		foreach($allParts as $part) {
426
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
427
-				$dcFound = true;
428
-			}
429
-			if($dcFound) {
430
-				$domainParts[] = $part;
431
-			}
432
-		}
433
-		return implode(',', $domainParts);
434
-	}
435
-
436
-	/**
437
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
438
-	 * @param string $name the Nextcloud name in question
439
-	 * @return string|false LDAP DN on success, otherwise false
440
-	 */
441
-	public function groupname2dn($name) {
442
-		return $this->groupMapper->getDNByName($name);
443
-	}
444
-
445
-	/**
446
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
447
-	 * @param string $name the Nextcloud name in question
448
-	 * @return string|false with the LDAP DN on success, otherwise false
449
-	 */
450
-	public function username2dn($name) {
451
-		$fdn = $this->userMapper->getDNByName($name);
452
-
453
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
454
-		//server setups
455
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
456
-			return $fdn;
457
-		}
458
-
459
-		return false;
460
-	}
461
-
462
-	/**
463
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
464
-	 *
465
-	 * @param string $fdn the dn of the group object
466
-	 * @param string $ldapName optional, the display name of the object
467
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
468
-	 * @throws \Exception
469
-	 */
470
-	public function dn2groupname($fdn, $ldapName = null) {
471
-		//To avoid bypassing the base DN settings under certain circumstances
472
-		//with the group support, check whether the provided DN matches one of
473
-		//the given Bases
474
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
475
-			return false;
476
-		}
477
-
478
-		return $this->dn2ocname($fdn, $ldapName, false);
479
-	}
480
-
481
-	/**
482
-	 * accepts an array of group DNs and tests whether they match the user
483
-	 * filter by doing read operations against the group entries. Returns an
484
-	 * array of DNs that match the filter.
485
-	 *
486
-	 * @param string[] $groupDNs
487
-	 * @return string[]
488
-	 * @throws ServerNotAvailableException
489
-	 */
490
-	public function groupsMatchFilter($groupDNs) {
491
-		$validGroupDNs = [];
492
-		foreach($groupDNs as $dn) {
493
-			$cacheKey = 'groupsMatchFilter-'.$dn;
494
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
495
-			if(!is_null($groupMatchFilter)) {
496
-				if($groupMatchFilter) {
497
-					$validGroupDNs[] = $dn;
498
-				}
499
-				continue;
500
-			}
501
-
502
-			// Check the base DN first. If this is not met already, we don't
503
-			// need to ask the server at all.
504
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
505
-				$this->connection->writeToCache($cacheKey, false);
506
-				continue;
507
-			}
508
-
509
-			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
510
-			if(is_array($result)) {
511
-				$this->connection->writeToCache($cacheKey, true);
512
-				$validGroupDNs[] = $dn;
513
-			} else {
514
-				$this->connection->writeToCache($cacheKey, false);
515
-			}
516
-
517
-		}
518
-		return $validGroupDNs;
519
-	}
520
-
521
-	/**
522
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
523
-	 *
524
-	 * @param string $dn the dn of the user object
525
-	 * @param string $ldapName optional, the display name of the object
526
-	 * @return string|false with with the name to use in Nextcloud
527
-	 * @throws \Exception
528
-	 */
529
-	public function dn2username($fdn, $ldapName = null) {
530
-		//To avoid bypassing the base DN settings under certain circumstances
531
-		//with the group support, check whether the provided DN matches one of
532
-		//the given Bases
533
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
534
-			return false;
535
-		}
536
-
537
-		return $this->dn2ocname($fdn, $ldapName, true);
538
-	}
539
-
540
-	/**
541
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
542
-	 *
543
-	 * @param string $fdn the dn of the user object
544
-	 * @param string|null $ldapName optional, the display name of the object
545
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
546
-	 * @param bool|null $newlyMapped
547
-	 * @param array|null $record
548
-	 * @return false|string with with the name to use in Nextcloud
549
-	 * @throws \Exception
550
-	 */
551
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
552
-		$newlyMapped = false;
553
-		if($isUser) {
554
-			$mapper = $this->getUserMapper();
555
-			$nameAttribute = $this->connection->ldapUserDisplayName;
556
-			$filter = $this->connection->ldapUserFilter;
557
-		} else {
558
-			$mapper = $this->getGroupMapper();
559
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
560
-			$filter = $this->connection->ldapGroupFilter;
561
-		}
562
-
563
-		//let's try to retrieve the Nextcloud name from the mappings table
564
-		$ncName = $mapper->getNameByDN($fdn);
565
-		if(is_string($ncName)) {
566
-			return $ncName;
567
-		}
568
-
569
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
570
-		$uuid = $this->getUUID($fdn, $isUser, $record);
571
-		if(is_string($uuid)) {
572
-			$ncName = $mapper->getNameByUUID($uuid);
573
-			if(is_string($ncName)) {
574
-				$mapper->setDNbyUUID($fdn, $uuid);
575
-				return $ncName;
576
-			}
577
-		} else {
578
-			//If the UUID can't be detected something is foul.
579
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
580
-			return false;
581
-		}
582
-
583
-		if(is_null($ldapName)) {
584
-			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
585
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
586
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
587
-				return false;
588
-			}
589
-			$ldapName = $ldapName[0];
590
-		}
591
-
592
-		if($isUser) {
593
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
594
-			if ($usernameAttribute !== '') {
595
-				$username = $this->readAttribute($fdn, $usernameAttribute);
596
-				$username = $username[0];
597
-			} else {
598
-				$username = $uuid;
599
-			}
600
-			try {
601
-				$intName = $this->sanitizeUsername($username);
602
-			} catch (\InvalidArgumentException $e) {
603
-				\OC::$server->getLogger()->logException($e, [
604
-					'app' => 'user_ldap',
605
-					'level' => ILogger::WARN,
606
-				]);
607
-				// we don't attempt to set a username here. We can go for
608
-				// for an alternative 4 digit random number as we would append
609
-				// otherwise, however it's likely not enough space in bigger
610
-				// setups, and most importantly: this is not intended.
611
-				return false;
612
-			}
613
-		} else {
614
-			$intName = $ldapName;
615
-		}
616
-
617
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
618
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
619
-		//NOTE: mind, disabling cache affects only this instance! Using it
620
-		// outside of core user management will still cache the user as non-existing.
621
-		$originalTTL = $this->connection->ldapCacheTTL;
622
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
623
-		if( $intName !== ''
624
-			&& (($isUser && !$this->ncUserManager->userExists($intName))
625
-				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
626
-			)
627
-		) {
628
-			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
629
-			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
630
-			if($newlyMapped) {
631
-				return $intName;
632
-			}
633
-		}
634
-
635
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
636
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
637
-		if (is_string($altName)) {
638
-			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
639
-				$newlyMapped = true;
640
-				return $altName;
641
-			}
642
-		}
643
-
644
-		//if everything else did not help..
645
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
646
-		return false;
647
-	}
648
-
649
-	public function mapAndAnnounceIfApplicable(
650
-		AbstractMapping $mapper,
651
-		string $fdn,
652
-		string $name,
653
-		string $uuid,
654
-		bool $isUser
655
-	) :bool {
656
-		if($mapper->map($fdn, $name, $uuid)) {
657
-			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
658
-				$this->cacheUserExists($name);
659
-				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
660
-			} elseif (!$isUser) {
661
-				$this->cacheGroupExists($name);
662
-			}
663
-			return true;
664
-		}
665
-		return false;
666
-	}
667
-
668
-	/**
669
-	 * gives back the user names as they are used ownClod internally
670
-	 *
671
-	 * @param array $ldapUsers as returned by fetchList()
672
-	 * @return array an array with the user names to use in Nextcloud
673
-	 *
674
-	 * gives back the user names as they are used ownClod internally
675
-	 * @throws \Exception
676
-	 */
677
-	public function nextcloudUserNames($ldapUsers) {
678
-		return $this->ldap2NextcloudNames($ldapUsers, true);
679
-	}
680
-
681
-	/**
682
-	 * gives back the group names as they are used ownClod internally
683
-	 *
684
-	 * @param array $ldapGroups as returned by fetchList()
685
-	 * @return array an array with the group names to use in Nextcloud
686
-	 *
687
-	 * gives back the group names as they are used ownClod internally
688
-	 * @throws \Exception
689
-	 */
690
-	public function nextcloudGroupNames($ldapGroups) {
691
-		return $this->ldap2NextcloudNames($ldapGroups, false);
692
-	}
693
-
694
-	/**
695
-	 * @param array $ldapObjects as returned by fetchList()
696
-	 * @param bool $isUsers
697
-	 * @return array
698
-	 * @throws \Exception
699
-	 */
700
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
701
-		if($isUsers) {
702
-			$nameAttribute = $this->connection->ldapUserDisplayName;
703
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
704
-		} else {
705
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
706
-		}
707
-		$nextcloudNames = [];
708
-
709
-		foreach($ldapObjects as $ldapObject) {
710
-			$nameByLDAP = null;
711
-			if(    isset($ldapObject[$nameAttribute])
712
-				&& is_array($ldapObject[$nameAttribute])
713
-				&& isset($ldapObject[$nameAttribute][0])
714
-			) {
715
-				// might be set, but not necessarily. if so, we use it.
716
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
717
-			}
718
-
719
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
720
-			if($ncName) {
721
-				$nextcloudNames[] = $ncName;
722
-				if($isUsers) {
723
-					$this->updateUserState($ncName);
724
-					//cache the user names so it does not need to be retrieved
725
-					//again later (e.g. sharing dialogue).
726
-					if(is_null($nameByLDAP)) {
727
-						continue;
728
-					}
729
-					$sndName = isset($ldapObject[$sndAttribute][0])
730
-						? $ldapObject[$sndAttribute][0] : '';
731
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
732
-				} else if($nameByLDAP !== null) {
733
-					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
734
-				}
735
-			}
736
-		}
737
-		return $nextcloudNames;
738
-	}
739
-
740
-	/**
741
-	 * removes the deleted-flag of a user if it was set
742
-	 *
743
-	 * @param string $ncname
744
-	 * @throws \Exception
745
-	 */
746
-	public function updateUserState($ncname) {
747
-		$user = $this->userManager->get($ncname);
748
-		if($user instanceof OfflineUser) {
749
-			$user->unmark();
750
-		}
751
-	}
752
-
753
-	/**
754
-	 * caches the user display name
755
-	 * @param string $ocName the internal Nextcloud username
756
-	 * @param string|false $home the home directory path
757
-	 */
758
-	public function cacheUserHome($ocName, $home) {
759
-		$cacheKey = 'getHome'.$ocName;
760
-		$this->connection->writeToCache($cacheKey, $home);
761
-	}
762
-
763
-	/**
764
-	 * caches a user as existing
765
-	 * @param string $ocName the internal Nextcloud username
766
-	 */
767
-	public function cacheUserExists($ocName) {
768
-		$this->connection->writeToCache('userExists'.$ocName, true);
769
-	}
770
-
771
-	/**
772
-	 * caches a group as existing
773
-	 */
774
-	public function cacheGroupExists(string $gid): void {
775
-		$this->connection->writeToCache('groupExists'.$gid, true);
776
-	}
777
-
778
-	/**
779
-	 * caches the user display name
780
-	 *
781
-	 * @param string $ocName the internal Nextcloud username
782
-	 * @param string $displayName the display name
783
-	 * @param string $displayName2 the second display name
784
-	 * @throws \Exception
785
-	 */
786
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
787
-		$user = $this->userManager->get($ocName);
788
-		if($user === null) {
789
-			return;
790
-		}
791
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
792
-		$cacheKeyTrunk = 'getDisplayName';
793
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
794
-	}
795
-
796
-	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
797
-		$cacheKey = 'group_getDisplayName' . $ncName;
798
-		$this->connection->writeToCache($cacheKey, $displayName);
799
-	}
800
-
801
-	/**
802
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
803
-	 * @param string $name the display name of the object
804
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
805
-	 *
806
-	 * Instead of using this method directly, call
807
-	 * createAltInternalOwnCloudName($name, true)
808
-	 */
809
-	private function _createAltInternalOwnCloudNameForUsers($name) {
810
-		$attempts = 0;
811
-		//while loop is just a precaution. If a name is not generated within
812
-		//20 attempts, something else is very wrong. Avoids infinite loop.
813
-		while($attempts < 20){
814
-			$altName = $name . '_' . rand(1000,9999);
815
-			if(!$this->ncUserManager->userExists($altName)) {
816
-				return $altName;
817
-			}
818
-			$attempts++;
819
-		}
820
-		return false;
821
-	}
822
-
823
-	/**
824
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
825
-	 * @param string $name the display name of the object
826
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
827
-	 *
828
-	 * Instead of using this method directly, call
829
-	 * createAltInternalOwnCloudName($name, false)
830
-	 *
831
-	 * Group names are also used as display names, so we do a sequential
832
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
833
-	 * "Developers"
834
-	 */
835
-	private function _createAltInternalOwnCloudNameForGroups($name) {
836
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
837
-		if(!$usedNames || count($usedNames) === 0) {
838
-			$lastNo = 1; //will become name_2
839
-		} else {
840
-			natsort($usedNames);
841
-			$lastName = array_pop($usedNames);
842
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
843
-		}
844
-		$altName = $name.'_'. (string)($lastNo+1);
845
-		unset($usedNames);
846
-
847
-		$attempts = 1;
848
-		while($attempts < 21){
849
-			// Check to be really sure it is unique
850
-			// while loop is just a precaution. If a name is not generated within
851
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
852
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
853
-				return $altName;
854
-			}
855
-			$altName = $name . '_' . ($lastNo + $attempts);
856
-			$attempts++;
857
-		}
858
-		return false;
859
-	}
860
-
861
-	/**
862
-	 * creates a unique name for internal Nextcloud use.
863
-	 * @param string $name the display name of the object
864
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
865
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
866
-	 */
867
-	private function createAltInternalOwnCloudName($name, $isUser) {
868
-		$originalTTL = $this->connection->ldapCacheTTL;
869
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
870
-		if($isUser) {
871
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
872
-		} else {
873
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
874
-		}
875
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
876
-
877
-		return $altName;
878
-	}
879
-
880
-	/**
881
-	 * fetches a list of users according to a provided loginName and utilizing
882
-	 * the login filter.
883
-	 *
884
-	 * @param string $loginName
885
-	 * @param array $attributes optional, list of attributes to read
886
-	 * @return array
887
-	 */
888
-	public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
889
-		$loginName = $this->escapeFilterPart($loginName);
890
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
891
-		return $this->fetchListOfUsers($filter, $attributes);
892
-	}
893
-
894
-	/**
895
-	 * counts the number of users according to a provided loginName and
896
-	 * utilizing the login filter.
897
-	 *
898
-	 * @param string $loginName
899
-	 * @return int
900
-	 */
901
-	public function countUsersByLoginName($loginName) {
902
-		$loginName = $this->escapeFilterPart($loginName);
903
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
904
-		return $this->countUsers($filter);
905
-	}
906
-
907
-	/**
908
-	 * @param string $filter
909
-	 * @param string|string[] $attr
910
-	 * @param int $limit
911
-	 * @param int $offset
912
-	 * @param bool $forceApplyAttributes
913
-	 * @return array
914
-	 * @throws \Exception
915
-	 */
916
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
917
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
918
-		$recordsToUpdate = $ldapRecords;
919
-		if(!$forceApplyAttributes) {
920
-			$isBackgroundJobModeAjax = $this->config
921
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
922
-			$recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) {
923
-				$newlyMapped = false;
924
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
925
-				if(is_string($uid)) {
926
-					$this->cacheUserExists($uid);
927
-				}
928
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
929
-			});
930
-		}
931
-		$this->batchApplyUserAttributes($recordsToUpdate);
932
-		return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
933
-	}
934
-
935
-	/**
936
-	 * provided with an array of LDAP user records the method will fetch the
937
-	 * user object and requests it to process the freshly fetched attributes and
938
-	 * and their values
939
-	 *
940
-	 * @param array $ldapRecords
941
-	 * @throws \Exception
942
-	 */
943
-	public function batchApplyUserAttributes(array $ldapRecords) {
944
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
945
-		foreach($ldapRecords as $userRecord) {
946
-			if(!isset($userRecord[$displayNameAttribute])) {
947
-				// displayName is obligatory
948
-				continue;
949
-			}
950
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
951
-			if($ocName === false) {
952
-				continue;
953
-			}
954
-			$this->updateUserState($ocName);
955
-			$user = $this->userManager->get($ocName);
956
-			if ($user !== null) {
957
-				$user->processAttributes($userRecord);
958
-			} else {
959
-				\OC::$server->getLogger()->debug(
960
-					"The ldap user manager returned null for $ocName",
961
-					['app'=>'user_ldap']
962
-				);
963
-			}
964
-		}
965
-	}
966
-
967
-	/**
968
-	 * @param string $filter
969
-	 * @param string|string[] $attr
970
-	 * @param int $limit
971
-	 * @param int $offset
972
-	 * @return array
973
-	 */
974
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
975
-		$groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
976
-		array_walk($groupRecords, function ($record) {
977
-			$newlyMapped = false;
978
-			$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
979
-			if(!$newlyMapped && is_string($gid)) {
980
-				$this->cacheGroupExists($gid);
981
-			}
982
-		});
983
-		return $this->fetchList($groupRecords, $this->manyAttributes($attr));
984
-	}
985
-
986
-	/**
987
-	 * @param array $list
988
-	 * @param bool $manyAttributes
989
-	 * @return array
990
-	 */
991
-	private function fetchList($list, $manyAttributes) {
992
-		if(is_array($list)) {
993
-			if($manyAttributes) {
994
-				return $list;
995
-			} else {
996
-				$list = array_reduce($list, function ($carry, $item) {
997
-					$attribute = array_keys($item)[0];
998
-					$carry[] = $item[$attribute][0];
999
-					return $carry;
1000
-				}, []);
1001
-				return array_unique($list, SORT_LOCALE_STRING);
1002
-			}
1003
-		}
1004
-
1005
-		//error cause actually, maybe throw an exception in future.
1006
-		return [];
1007
-	}
1008
-
1009
-	/**
1010
-	 * executes an LDAP search, optimized for Users
1011
-	 *
1012
-	 * @param string $filter the LDAP filter for the search
1013
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1014
-	 * @param integer $limit
1015
-	 * @param integer $offset
1016
-	 * @return array with the search result
1017
-	 *
1018
-	 * Executes an LDAP search
1019
-	 * @throws ServerNotAvailableException
1020
-	 */
1021
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1022
-		$result = [];
1023
-		foreach($this->connection->ldapBaseUsers as $base) {
1024
-			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1025
-		}
1026
-		return $result;
1027
-	}
1028
-
1029
-	/**
1030
-	 * @param string $filter
1031
-	 * @param string|string[] $attr
1032
-	 * @param int $limit
1033
-	 * @param int $offset
1034
-	 * @return false|int
1035
-	 * @throws ServerNotAvailableException
1036
-	 */
1037
-	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1038
-		$result = false;
1039
-		foreach($this->connection->ldapBaseUsers as $base) {
1040
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1041
-			$result = is_int($count) ? (int)$result + $count : $result;
1042
-		}
1043
-		return $result;
1044
-	}
1045
-
1046
-	/**
1047
-	 * executes an LDAP search, optimized for Groups
1048
-	 *
1049
-	 * @param string $filter the LDAP filter for the search
1050
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1051
-	 * @param integer $limit
1052
-	 * @param integer $offset
1053
-	 * @return array with the search result
1054
-	 *
1055
-	 * Executes an LDAP search
1056
-	 * @throws ServerNotAvailableException
1057
-	 */
1058
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1059
-		$result = [];
1060
-		foreach($this->connection->ldapBaseGroups as $base) {
1061
-			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1062
-		}
1063
-		return $result;
1064
-	}
1065
-
1066
-	/**
1067
-	 * returns the number of available groups
1068
-	 *
1069
-	 * @param string $filter the LDAP search filter
1070
-	 * @param string[] $attr optional
1071
-	 * @param int|null $limit
1072
-	 * @param int|null $offset
1073
-	 * @return int|bool
1074
-	 * @throws ServerNotAvailableException
1075
-	 */
1076
-	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1077
-		$result = false;
1078
-		foreach($this->connection->ldapBaseGroups as $base) {
1079
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1080
-			$result = is_int($count) ? (int)$result + $count : $result;
1081
-		}
1082
-		return $result;
1083
-	}
1084
-
1085
-	/**
1086
-	 * returns the number of available objects on the base DN
1087
-	 *
1088
-	 * @param int|null $limit
1089
-	 * @param int|null $offset
1090
-	 * @return int|bool
1091
-	 * @throws ServerNotAvailableException
1092
-	 */
1093
-	public function countObjects($limit = null, $offset = null) {
1094
-		$result = false;
1095
-		foreach($this->connection->ldapBase as $base) {
1096
-			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1097
-			$result = is_int($count) ? (int)$result + $count : $result;
1098
-		}
1099
-		return $result;
1100
-	}
1101
-
1102
-	/**
1103
-	 * Returns the LDAP handler
1104
-	 * @throws \OC\ServerNotAvailableException
1105
-	 */
1106
-
1107
-	/**
1108
-	 * @return mixed
1109
-	 * @throws \OC\ServerNotAvailableException
1110
-	 */
1111
-	private function invokeLDAPMethod() {
1112
-		$arguments = func_get_args();
1113
-		$command = array_shift($arguments);
1114
-		$cr = array_shift($arguments);
1115
-		if (!method_exists($this->ldap, $command)) {
1116
-			return null;
1117
-		}
1118
-		array_unshift($arguments, $cr);
1119
-		// php no longer supports call-time pass-by-reference
1120
-		// thus cannot support controlPagedResultResponse as the third argument
1121
-		// is a reference
1122
-		$doMethod = function () use ($command, &$arguments) {
1123
-			if ($command == 'controlPagedResultResponse') {
1124
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1125
-			} else {
1126
-				return call_user_func_array([$this->ldap, $command], $arguments);
1127
-			}
1128
-		};
1129
-		try {
1130
-			$ret = $doMethod();
1131
-		} catch (ServerNotAvailableException $e) {
1132
-			/* Server connection lost, attempt to reestablish it
67
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
68
+
69
+    /** @var \OCA\User_LDAP\Connection */
70
+    public $connection;
71
+    /** @var Manager */
72
+    public $userManager;
73
+    //never ever check this var directly, always use getPagedSearchResultState
74
+    protected $pagedSearchedSuccessful;
75
+
76
+    /**
77
+     * @var string[] $cookies an array of returned Paged Result cookies
78
+     */
79
+    protected $cookies = [];
80
+
81
+    /**
82
+     * @var string $lastCookie the last cookie returned from a Paged Results
83
+     * operation, defaults to an empty string
84
+     */
85
+    protected $lastCookie = '';
86
+
87
+    /**
88
+     * @var AbstractMapping $userMapper
89
+     */
90
+    protected $userMapper;
91
+
92
+    /**
93
+     * @var AbstractMapping $userMapper
94
+     */
95
+    protected $groupMapper;
96
+
97
+    /**
98
+     * @var \OCA\User_LDAP\Helper
99
+     */
100
+    private $helper;
101
+    /** @var IConfig */
102
+    private $config;
103
+    /** @var IUserManager */
104
+    private $ncUserManager;
105
+
106
+    public function __construct(
107
+        Connection $connection,
108
+        ILDAPWrapper $ldap,
109
+        Manager $userManager,
110
+        Helper $helper,
111
+        IConfig $config,
112
+        IUserManager $ncUserManager
113
+    ) {
114
+        parent::__construct($ldap);
115
+        $this->connection = $connection;
116
+        $this->userManager = $userManager;
117
+        $this->userManager->setLdapAccess($this);
118
+        $this->helper = $helper;
119
+        $this->config = $config;
120
+        $this->ncUserManager = $ncUserManager;
121
+    }
122
+
123
+    /**
124
+     * sets the User Mapper
125
+     * @param AbstractMapping $mapper
126
+     */
127
+    public function setUserMapper(AbstractMapping $mapper) {
128
+        $this->userMapper = $mapper;
129
+    }
130
+
131
+    /**
132
+     * returns the User Mapper
133
+     * @throws \Exception
134
+     * @return AbstractMapping
135
+     */
136
+    public function getUserMapper() {
137
+        if(is_null($this->userMapper)) {
138
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
139
+        }
140
+        return $this->userMapper;
141
+    }
142
+
143
+    /**
144
+     * sets the Group Mapper
145
+     * @param AbstractMapping $mapper
146
+     */
147
+    public function setGroupMapper(AbstractMapping $mapper) {
148
+        $this->groupMapper = $mapper;
149
+    }
150
+
151
+    /**
152
+     * returns the Group Mapper
153
+     * @throws \Exception
154
+     * @return AbstractMapping
155
+     */
156
+    public function getGroupMapper() {
157
+        if(is_null($this->groupMapper)) {
158
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
159
+        }
160
+        return $this->groupMapper;
161
+    }
162
+
163
+    /**
164
+     * @return bool
165
+     */
166
+    private function checkConnection() {
167
+        return ($this->connection instanceof Connection);
168
+    }
169
+
170
+    /**
171
+     * returns the Connection instance
172
+     * @return \OCA\User_LDAP\Connection
173
+     */
174
+    public function getConnection() {
175
+        return $this->connection;
176
+    }
177
+
178
+    /**
179
+     * reads a given attribute for an LDAP record identified by a DN
180
+     *
181
+     * @param string $dn the record in question
182
+     * @param string $attr the attribute that shall be retrieved
183
+     *        if empty, just check the record's existence
184
+     * @param string $filter
185
+     * @return array|false an array of values on success or an empty
186
+     *          array if $attr is empty, false otherwise
187
+     * @throws ServerNotAvailableException
188
+     */
189
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
190
+        if(!$this->checkConnection()) {
191
+            \OCP\Util::writeLog('user_ldap',
192
+                'No LDAP Connector assigned, access impossible for readAttribute.',
193
+                ILogger::WARN);
194
+            return false;
195
+        }
196
+        $cr = $this->connection->getConnectionResource();
197
+        if(!$this->ldap->isResource($cr)) {
198
+            //LDAP not available
199
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
200
+            return false;
201
+        }
202
+        //Cancel possibly running Paged Results operation, otherwise we run in
203
+        //LDAP protocol errors
204
+        $this->abandonPagedSearch();
205
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
206
+        // but does not hurt either.
207
+        $pagingSize = (int)$this->connection->ldapPagingSize;
208
+        // 0 won't result in replies, small numbers may leave out groups
209
+        // (cf. #12306), 500 is default for paging and should work everywhere.
210
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
211
+        $attr = mb_strtolower($attr, 'UTF-8');
212
+        // the actual read attribute later may contain parameters on a ranged
213
+        // request, e.g. member;range=99-199. Depends on server reply.
214
+        $attrToRead = $attr;
215
+
216
+        $values = [];
217
+        $isRangeRequest = false;
218
+        do {
219
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
220
+            if(is_bool($result)) {
221
+                // when an exists request was run and it was successful, an empty
222
+                // array must be returned
223
+                return $result ? [] : false;
224
+            }
225
+
226
+            if (!$isRangeRequest) {
227
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
228
+                if (!empty($values)) {
229
+                    return $values;
230
+                }
231
+            }
232
+
233
+            $isRangeRequest = false;
234
+            $result = $this->extractRangeData($result, $attr);
235
+            if (!empty($result)) {
236
+                $normalizedResult = $this->extractAttributeValuesFromResult(
237
+                    [ $attr => $result['values'] ],
238
+                    $attr
239
+                );
240
+                $values = array_merge($values, $normalizedResult);
241
+
242
+                if($result['rangeHigh'] === '*') {
243
+                    // when server replies with * as high range value, there are
244
+                    // no more results left
245
+                    return $values;
246
+                } else {
247
+                    $low  = $result['rangeHigh'] + 1;
248
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
249
+                    $isRangeRequest = true;
250
+                }
251
+            }
252
+        } while($isRangeRequest);
253
+
254
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
255
+        return false;
256
+    }
257
+
258
+    /**
259
+     * Runs an read operation against LDAP
260
+     *
261
+     * @param resource $cr the LDAP connection
262
+     * @param string $dn
263
+     * @param string $attribute
264
+     * @param string $filter
265
+     * @param int $maxResults
266
+     * @return array|bool false if there was any error, true if an exists check
267
+     *                    was performed and the requested DN found, array with the
268
+     *                    returned data on a successful usual operation
269
+     * @throws ServerNotAvailableException
270
+     */
271
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
272
+        $this->initPagedSearch($filter, [$dn], [$attribute], $maxResults, 0);
273
+        $dn = $this->helper->DNasBaseParameter($dn);
274
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
275
+        if (!$this->ldap->isResource($rr)) {
276
+            if ($attribute !== '') {
277
+                //do not throw this message on userExists check, irritates
278
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
279
+            }
280
+            //in case an error occurs , e.g. object does not exist
281
+            return false;
282
+        }
283
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
284
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
285
+            return true;
286
+        }
287
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
288
+        if (!$this->ldap->isResource($er)) {
289
+            //did not match the filter, return false
290
+            return false;
291
+        }
292
+        //LDAP attributes are not case sensitive
293
+        $result = \OCP\Util::mb_array_change_key_case(
294
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
295
+
296
+        return $result;
297
+    }
298
+
299
+    /**
300
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
301
+     * data if present.
302
+     *
303
+     * @param array $result from ILDAPWrapper::getAttributes()
304
+     * @param string $attribute the attribute name that was read
305
+     * @return string[]
306
+     */
307
+    public function extractAttributeValuesFromResult($result, $attribute) {
308
+        $values = [];
309
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
310
+            $lowercaseAttribute = strtolower($attribute);
311
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
312
+                if($this->resemblesDN($attribute)) {
313
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
314
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
315
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
316
+                } else {
317
+                    $values[] = $result[$attribute][$i];
318
+                }
319
+            }
320
+        }
321
+        return $values;
322
+    }
323
+
324
+    /**
325
+     * Attempts to find ranged data in a getAttribute results and extracts the
326
+     * returned values as well as information on the range and full attribute
327
+     * name for further processing.
328
+     *
329
+     * @param array $result from ILDAPWrapper::getAttributes()
330
+     * @param string $attribute the attribute name that was read. Without ";range=…"
331
+     * @return array If a range was detected with keys 'values', 'attributeName',
332
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
333
+     */
334
+    public function extractRangeData($result, $attribute) {
335
+        $keys = array_keys($result);
336
+        foreach($keys as $key) {
337
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
338
+                $queryData = explode(';', $key);
339
+                if(strpos($queryData[1], 'range=') === 0) {
340
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
341
+                    $data = [
342
+                        'values' => $result[$key],
343
+                        'attributeName' => $queryData[0],
344
+                        'attributeFull' => $key,
345
+                        'rangeHigh' => $high,
346
+                    ];
347
+                    return $data;
348
+                }
349
+            }
350
+        }
351
+        return [];
352
+    }
353
+
354
+    /**
355
+     * Set password for an LDAP user identified by a DN
356
+     *
357
+     * @param string $userDN the user in question
358
+     * @param string $password the new password
359
+     * @return bool
360
+     * @throws HintException
361
+     * @throws \Exception
362
+     */
363
+    public function setPassword($userDN, $password) {
364
+        if((int)$this->connection->turnOnPasswordChange !== 1) {
365
+            throw new \Exception('LDAP password changes are disabled.');
366
+        }
367
+        $cr = $this->connection->getConnectionResource();
368
+        if(!$this->ldap->isResource($cr)) {
369
+            //LDAP not available
370
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
371
+            return false;
372
+        }
373
+        try {
374
+            // try PASSWD extended operation first
375
+            return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
376
+                        @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
377
+        } catch(ConstraintViolationException $e) {
378
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
379
+        }
380
+    }
381
+
382
+    /**
383
+     * checks whether the given attributes value is probably a DN
384
+     * @param string $attr the attribute in question
385
+     * @return boolean if so true, otherwise false
386
+     */
387
+    private function resemblesDN($attr) {
388
+        $resemblingAttributes = [
389
+            'dn',
390
+            'uniquemember',
391
+            'member',
392
+            // memberOf is an "operational" attribute, without a definition in any RFC
393
+            'memberof'
394
+        ];
395
+        return in_array($attr, $resemblingAttributes);
396
+    }
397
+
398
+    /**
399
+     * checks whether the given string is probably a DN
400
+     * @param string $string
401
+     * @return boolean
402
+     */
403
+    public function stringResemblesDN($string) {
404
+        $r = $this->ldap->explodeDN($string, 0);
405
+        // if exploding a DN succeeds and does not end up in
406
+        // an empty array except for $r[count] being 0.
407
+        return (is_array($r) && count($r) > 1);
408
+    }
409
+
410
+    /**
411
+     * returns a DN-string that is cleaned from not domain parts, e.g.
412
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
413
+     * becomes dc=foobar,dc=server,dc=org
414
+     * @param string $dn
415
+     * @return string
416
+     */
417
+    public function getDomainDNFromDN($dn) {
418
+        $allParts = $this->ldap->explodeDN($dn, 0);
419
+        if($allParts === false) {
420
+            //not a valid DN
421
+            return '';
422
+        }
423
+        $domainParts = [];
424
+        $dcFound = false;
425
+        foreach($allParts as $part) {
426
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
427
+                $dcFound = true;
428
+            }
429
+            if($dcFound) {
430
+                $domainParts[] = $part;
431
+            }
432
+        }
433
+        return implode(',', $domainParts);
434
+    }
435
+
436
+    /**
437
+     * returns the LDAP DN for the given internal Nextcloud name of the group
438
+     * @param string $name the Nextcloud name in question
439
+     * @return string|false LDAP DN on success, otherwise false
440
+     */
441
+    public function groupname2dn($name) {
442
+        return $this->groupMapper->getDNByName($name);
443
+    }
444
+
445
+    /**
446
+     * returns the LDAP DN for the given internal Nextcloud name of the user
447
+     * @param string $name the Nextcloud name in question
448
+     * @return string|false with the LDAP DN on success, otherwise false
449
+     */
450
+    public function username2dn($name) {
451
+        $fdn = $this->userMapper->getDNByName($name);
452
+
453
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
454
+        //server setups
455
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
456
+            return $fdn;
457
+        }
458
+
459
+        return false;
460
+    }
461
+
462
+    /**
463
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
464
+     *
465
+     * @param string $fdn the dn of the group object
466
+     * @param string $ldapName optional, the display name of the object
467
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
468
+     * @throws \Exception
469
+     */
470
+    public function dn2groupname($fdn, $ldapName = null) {
471
+        //To avoid bypassing the base DN settings under certain circumstances
472
+        //with the group support, check whether the provided DN matches one of
473
+        //the given Bases
474
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
475
+            return false;
476
+        }
477
+
478
+        return $this->dn2ocname($fdn, $ldapName, false);
479
+    }
480
+
481
+    /**
482
+     * accepts an array of group DNs and tests whether they match the user
483
+     * filter by doing read operations against the group entries. Returns an
484
+     * array of DNs that match the filter.
485
+     *
486
+     * @param string[] $groupDNs
487
+     * @return string[]
488
+     * @throws ServerNotAvailableException
489
+     */
490
+    public function groupsMatchFilter($groupDNs) {
491
+        $validGroupDNs = [];
492
+        foreach($groupDNs as $dn) {
493
+            $cacheKey = 'groupsMatchFilter-'.$dn;
494
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
495
+            if(!is_null($groupMatchFilter)) {
496
+                if($groupMatchFilter) {
497
+                    $validGroupDNs[] = $dn;
498
+                }
499
+                continue;
500
+            }
501
+
502
+            // Check the base DN first. If this is not met already, we don't
503
+            // need to ask the server at all.
504
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
505
+                $this->connection->writeToCache($cacheKey, false);
506
+                continue;
507
+            }
508
+
509
+            $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
510
+            if(is_array($result)) {
511
+                $this->connection->writeToCache($cacheKey, true);
512
+                $validGroupDNs[] = $dn;
513
+            } else {
514
+                $this->connection->writeToCache($cacheKey, false);
515
+            }
516
+
517
+        }
518
+        return $validGroupDNs;
519
+    }
520
+
521
+    /**
522
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
523
+     *
524
+     * @param string $dn the dn of the user object
525
+     * @param string $ldapName optional, the display name of the object
526
+     * @return string|false with with the name to use in Nextcloud
527
+     * @throws \Exception
528
+     */
529
+    public function dn2username($fdn, $ldapName = null) {
530
+        //To avoid bypassing the base DN settings under certain circumstances
531
+        //with the group support, check whether the provided DN matches one of
532
+        //the given Bases
533
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
534
+            return false;
535
+        }
536
+
537
+        return $this->dn2ocname($fdn, $ldapName, true);
538
+    }
539
+
540
+    /**
541
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
542
+     *
543
+     * @param string $fdn the dn of the user object
544
+     * @param string|null $ldapName optional, the display name of the object
545
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
546
+     * @param bool|null $newlyMapped
547
+     * @param array|null $record
548
+     * @return false|string with with the name to use in Nextcloud
549
+     * @throws \Exception
550
+     */
551
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
552
+        $newlyMapped = false;
553
+        if($isUser) {
554
+            $mapper = $this->getUserMapper();
555
+            $nameAttribute = $this->connection->ldapUserDisplayName;
556
+            $filter = $this->connection->ldapUserFilter;
557
+        } else {
558
+            $mapper = $this->getGroupMapper();
559
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
560
+            $filter = $this->connection->ldapGroupFilter;
561
+        }
562
+
563
+        //let's try to retrieve the Nextcloud name from the mappings table
564
+        $ncName = $mapper->getNameByDN($fdn);
565
+        if(is_string($ncName)) {
566
+            return $ncName;
567
+        }
568
+
569
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
570
+        $uuid = $this->getUUID($fdn, $isUser, $record);
571
+        if(is_string($uuid)) {
572
+            $ncName = $mapper->getNameByUUID($uuid);
573
+            if(is_string($ncName)) {
574
+                $mapper->setDNbyUUID($fdn, $uuid);
575
+                return $ncName;
576
+            }
577
+        } else {
578
+            //If the UUID can't be detected something is foul.
579
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
580
+            return false;
581
+        }
582
+
583
+        if(is_null($ldapName)) {
584
+            $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
585
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
586
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
587
+                return false;
588
+            }
589
+            $ldapName = $ldapName[0];
590
+        }
591
+
592
+        if($isUser) {
593
+            $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
594
+            if ($usernameAttribute !== '') {
595
+                $username = $this->readAttribute($fdn, $usernameAttribute);
596
+                $username = $username[0];
597
+            } else {
598
+                $username = $uuid;
599
+            }
600
+            try {
601
+                $intName = $this->sanitizeUsername($username);
602
+            } catch (\InvalidArgumentException $e) {
603
+                \OC::$server->getLogger()->logException($e, [
604
+                    'app' => 'user_ldap',
605
+                    'level' => ILogger::WARN,
606
+                ]);
607
+                // we don't attempt to set a username here. We can go for
608
+                // for an alternative 4 digit random number as we would append
609
+                // otherwise, however it's likely not enough space in bigger
610
+                // setups, and most importantly: this is not intended.
611
+                return false;
612
+            }
613
+        } else {
614
+            $intName = $ldapName;
615
+        }
616
+
617
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
618
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
619
+        //NOTE: mind, disabling cache affects only this instance! Using it
620
+        // outside of core user management will still cache the user as non-existing.
621
+        $originalTTL = $this->connection->ldapCacheTTL;
622
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
623
+        if( $intName !== ''
624
+            && (($isUser && !$this->ncUserManager->userExists($intName))
625
+                || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
626
+            )
627
+        ) {
628
+            $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
629
+            $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
630
+            if($newlyMapped) {
631
+                return $intName;
632
+            }
633
+        }
634
+
635
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
636
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
637
+        if (is_string($altName)) {
638
+            if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
639
+                $newlyMapped = true;
640
+                return $altName;
641
+            }
642
+        }
643
+
644
+        //if everything else did not help..
645
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
646
+        return false;
647
+    }
648
+
649
+    public function mapAndAnnounceIfApplicable(
650
+        AbstractMapping $mapper,
651
+        string $fdn,
652
+        string $name,
653
+        string $uuid,
654
+        bool $isUser
655
+    ) :bool {
656
+        if($mapper->map($fdn, $name, $uuid)) {
657
+            if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
658
+                $this->cacheUserExists($name);
659
+                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
660
+            } elseif (!$isUser) {
661
+                $this->cacheGroupExists($name);
662
+            }
663
+            return true;
664
+        }
665
+        return false;
666
+    }
667
+
668
+    /**
669
+     * gives back the user names as they are used ownClod internally
670
+     *
671
+     * @param array $ldapUsers as returned by fetchList()
672
+     * @return array an array with the user names to use in Nextcloud
673
+     *
674
+     * gives back the user names as they are used ownClod internally
675
+     * @throws \Exception
676
+     */
677
+    public function nextcloudUserNames($ldapUsers) {
678
+        return $this->ldap2NextcloudNames($ldapUsers, true);
679
+    }
680
+
681
+    /**
682
+     * gives back the group names as they are used ownClod internally
683
+     *
684
+     * @param array $ldapGroups as returned by fetchList()
685
+     * @return array an array with the group names to use in Nextcloud
686
+     *
687
+     * gives back the group names as they are used ownClod internally
688
+     * @throws \Exception
689
+     */
690
+    public function nextcloudGroupNames($ldapGroups) {
691
+        return $this->ldap2NextcloudNames($ldapGroups, false);
692
+    }
693
+
694
+    /**
695
+     * @param array $ldapObjects as returned by fetchList()
696
+     * @param bool $isUsers
697
+     * @return array
698
+     * @throws \Exception
699
+     */
700
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
701
+        if($isUsers) {
702
+            $nameAttribute = $this->connection->ldapUserDisplayName;
703
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
704
+        } else {
705
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
706
+        }
707
+        $nextcloudNames = [];
708
+
709
+        foreach($ldapObjects as $ldapObject) {
710
+            $nameByLDAP = null;
711
+            if(    isset($ldapObject[$nameAttribute])
712
+                && is_array($ldapObject[$nameAttribute])
713
+                && isset($ldapObject[$nameAttribute][0])
714
+            ) {
715
+                // might be set, but not necessarily. if so, we use it.
716
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
717
+            }
718
+
719
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
720
+            if($ncName) {
721
+                $nextcloudNames[] = $ncName;
722
+                if($isUsers) {
723
+                    $this->updateUserState($ncName);
724
+                    //cache the user names so it does not need to be retrieved
725
+                    //again later (e.g. sharing dialogue).
726
+                    if(is_null($nameByLDAP)) {
727
+                        continue;
728
+                    }
729
+                    $sndName = isset($ldapObject[$sndAttribute][0])
730
+                        ? $ldapObject[$sndAttribute][0] : '';
731
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
732
+                } else if($nameByLDAP !== null) {
733
+                    $this->cacheGroupDisplayName($ncName, $nameByLDAP);
734
+                }
735
+            }
736
+        }
737
+        return $nextcloudNames;
738
+    }
739
+
740
+    /**
741
+     * removes the deleted-flag of a user if it was set
742
+     *
743
+     * @param string $ncname
744
+     * @throws \Exception
745
+     */
746
+    public function updateUserState($ncname) {
747
+        $user = $this->userManager->get($ncname);
748
+        if($user instanceof OfflineUser) {
749
+            $user->unmark();
750
+        }
751
+    }
752
+
753
+    /**
754
+     * caches the user display name
755
+     * @param string $ocName the internal Nextcloud username
756
+     * @param string|false $home the home directory path
757
+     */
758
+    public function cacheUserHome($ocName, $home) {
759
+        $cacheKey = 'getHome'.$ocName;
760
+        $this->connection->writeToCache($cacheKey, $home);
761
+    }
762
+
763
+    /**
764
+     * caches a user as existing
765
+     * @param string $ocName the internal Nextcloud username
766
+     */
767
+    public function cacheUserExists($ocName) {
768
+        $this->connection->writeToCache('userExists'.$ocName, true);
769
+    }
770
+
771
+    /**
772
+     * caches a group as existing
773
+     */
774
+    public function cacheGroupExists(string $gid): void {
775
+        $this->connection->writeToCache('groupExists'.$gid, true);
776
+    }
777
+
778
+    /**
779
+     * caches the user display name
780
+     *
781
+     * @param string $ocName the internal Nextcloud username
782
+     * @param string $displayName the display name
783
+     * @param string $displayName2 the second display name
784
+     * @throws \Exception
785
+     */
786
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
787
+        $user = $this->userManager->get($ocName);
788
+        if($user === null) {
789
+            return;
790
+        }
791
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
792
+        $cacheKeyTrunk = 'getDisplayName';
793
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
794
+    }
795
+
796
+    public function cacheGroupDisplayName(string $ncName, string $displayName): void {
797
+        $cacheKey = 'group_getDisplayName' . $ncName;
798
+        $this->connection->writeToCache($cacheKey, $displayName);
799
+    }
800
+
801
+    /**
802
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
803
+     * @param string $name the display name of the object
804
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
805
+     *
806
+     * Instead of using this method directly, call
807
+     * createAltInternalOwnCloudName($name, true)
808
+     */
809
+    private function _createAltInternalOwnCloudNameForUsers($name) {
810
+        $attempts = 0;
811
+        //while loop is just a precaution. If a name is not generated within
812
+        //20 attempts, something else is very wrong. Avoids infinite loop.
813
+        while($attempts < 20){
814
+            $altName = $name . '_' . rand(1000,9999);
815
+            if(!$this->ncUserManager->userExists($altName)) {
816
+                return $altName;
817
+            }
818
+            $attempts++;
819
+        }
820
+        return false;
821
+    }
822
+
823
+    /**
824
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
825
+     * @param string $name the display name of the object
826
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
827
+     *
828
+     * Instead of using this method directly, call
829
+     * createAltInternalOwnCloudName($name, false)
830
+     *
831
+     * Group names are also used as display names, so we do a sequential
832
+     * numbering, e.g. Developers_42 when there are 41 other groups called
833
+     * "Developers"
834
+     */
835
+    private function _createAltInternalOwnCloudNameForGroups($name) {
836
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
837
+        if(!$usedNames || count($usedNames) === 0) {
838
+            $lastNo = 1; //will become name_2
839
+        } else {
840
+            natsort($usedNames);
841
+            $lastName = array_pop($usedNames);
842
+            $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
843
+        }
844
+        $altName = $name.'_'. (string)($lastNo+1);
845
+        unset($usedNames);
846
+
847
+        $attempts = 1;
848
+        while($attempts < 21){
849
+            // Check to be really sure it is unique
850
+            // while loop is just a precaution. If a name is not generated within
851
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
852
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
853
+                return $altName;
854
+            }
855
+            $altName = $name . '_' . ($lastNo + $attempts);
856
+            $attempts++;
857
+        }
858
+        return false;
859
+    }
860
+
861
+    /**
862
+     * creates a unique name for internal Nextcloud use.
863
+     * @param string $name the display name of the object
864
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
865
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
866
+     */
867
+    private function createAltInternalOwnCloudName($name, $isUser) {
868
+        $originalTTL = $this->connection->ldapCacheTTL;
869
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
870
+        if($isUser) {
871
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
872
+        } else {
873
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
874
+        }
875
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
876
+
877
+        return $altName;
878
+    }
879
+
880
+    /**
881
+     * fetches a list of users according to a provided loginName and utilizing
882
+     * the login filter.
883
+     *
884
+     * @param string $loginName
885
+     * @param array $attributes optional, list of attributes to read
886
+     * @return array
887
+     */
888
+    public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
889
+        $loginName = $this->escapeFilterPart($loginName);
890
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
891
+        return $this->fetchListOfUsers($filter, $attributes);
892
+    }
893
+
894
+    /**
895
+     * counts the number of users according to a provided loginName and
896
+     * utilizing the login filter.
897
+     *
898
+     * @param string $loginName
899
+     * @return int
900
+     */
901
+    public function countUsersByLoginName($loginName) {
902
+        $loginName = $this->escapeFilterPart($loginName);
903
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
904
+        return $this->countUsers($filter);
905
+    }
906
+
907
+    /**
908
+     * @param string $filter
909
+     * @param string|string[] $attr
910
+     * @param int $limit
911
+     * @param int $offset
912
+     * @param bool $forceApplyAttributes
913
+     * @return array
914
+     * @throws \Exception
915
+     */
916
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
917
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
918
+        $recordsToUpdate = $ldapRecords;
919
+        if(!$forceApplyAttributes) {
920
+            $isBackgroundJobModeAjax = $this->config
921
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
922
+            $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) {
923
+                $newlyMapped = false;
924
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
925
+                if(is_string($uid)) {
926
+                    $this->cacheUserExists($uid);
927
+                }
928
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
929
+            });
930
+        }
931
+        $this->batchApplyUserAttributes($recordsToUpdate);
932
+        return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
933
+    }
934
+
935
+    /**
936
+     * provided with an array of LDAP user records the method will fetch the
937
+     * user object and requests it to process the freshly fetched attributes and
938
+     * and their values
939
+     *
940
+     * @param array $ldapRecords
941
+     * @throws \Exception
942
+     */
943
+    public function batchApplyUserAttributes(array $ldapRecords) {
944
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
945
+        foreach($ldapRecords as $userRecord) {
946
+            if(!isset($userRecord[$displayNameAttribute])) {
947
+                // displayName is obligatory
948
+                continue;
949
+            }
950
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
951
+            if($ocName === false) {
952
+                continue;
953
+            }
954
+            $this->updateUserState($ocName);
955
+            $user = $this->userManager->get($ocName);
956
+            if ($user !== null) {
957
+                $user->processAttributes($userRecord);
958
+            } else {
959
+                \OC::$server->getLogger()->debug(
960
+                    "The ldap user manager returned null for $ocName",
961
+                    ['app'=>'user_ldap']
962
+                );
963
+            }
964
+        }
965
+    }
966
+
967
+    /**
968
+     * @param string $filter
969
+     * @param string|string[] $attr
970
+     * @param int $limit
971
+     * @param int $offset
972
+     * @return array
973
+     */
974
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
975
+        $groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
976
+        array_walk($groupRecords, function ($record) {
977
+            $newlyMapped = false;
978
+            $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
979
+            if(!$newlyMapped && is_string($gid)) {
980
+                $this->cacheGroupExists($gid);
981
+            }
982
+        });
983
+        return $this->fetchList($groupRecords, $this->manyAttributes($attr));
984
+    }
985
+
986
+    /**
987
+     * @param array $list
988
+     * @param bool $manyAttributes
989
+     * @return array
990
+     */
991
+    private function fetchList($list, $manyAttributes) {
992
+        if(is_array($list)) {
993
+            if($manyAttributes) {
994
+                return $list;
995
+            } else {
996
+                $list = array_reduce($list, function ($carry, $item) {
997
+                    $attribute = array_keys($item)[0];
998
+                    $carry[] = $item[$attribute][0];
999
+                    return $carry;
1000
+                }, []);
1001
+                return array_unique($list, SORT_LOCALE_STRING);
1002
+            }
1003
+        }
1004
+
1005
+        //error cause actually, maybe throw an exception in future.
1006
+        return [];
1007
+    }
1008
+
1009
+    /**
1010
+     * executes an LDAP search, optimized for Users
1011
+     *
1012
+     * @param string $filter the LDAP filter for the search
1013
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1014
+     * @param integer $limit
1015
+     * @param integer $offset
1016
+     * @return array with the search result
1017
+     *
1018
+     * Executes an LDAP search
1019
+     * @throws ServerNotAvailableException
1020
+     */
1021
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1022
+        $result = [];
1023
+        foreach($this->connection->ldapBaseUsers as $base) {
1024
+            $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1025
+        }
1026
+        return $result;
1027
+    }
1028
+
1029
+    /**
1030
+     * @param string $filter
1031
+     * @param string|string[] $attr
1032
+     * @param int $limit
1033
+     * @param int $offset
1034
+     * @return false|int
1035
+     * @throws ServerNotAvailableException
1036
+     */
1037
+    public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1038
+        $result = false;
1039
+        foreach($this->connection->ldapBaseUsers as $base) {
1040
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1041
+            $result = is_int($count) ? (int)$result + $count : $result;
1042
+        }
1043
+        return $result;
1044
+    }
1045
+
1046
+    /**
1047
+     * executes an LDAP search, optimized for Groups
1048
+     *
1049
+     * @param string $filter the LDAP filter for the search
1050
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1051
+     * @param integer $limit
1052
+     * @param integer $offset
1053
+     * @return array with the search result
1054
+     *
1055
+     * Executes an LDAP search
1056
+     * @throws ServerNotAvailableException
1057
+     */
1058
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1059
+        $result = [];
1060
+        foreach($this->connection->ldapBaseGroups as $base) {
1061
+            $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1062
+        }
1063
+        return $result;
1064
+    }
1065
+
1066
+    /**
1067
+     * returns the number of available groups
1068
+     *
1069
+     * @param string $filter the LDAP search filter
1070
+     * @param string[] $attr optional
1071
+     * @param int|null $limit
1072
+     * @param int|null $offset
1073
+     * @return int|bool
1074
+     * @throws ServerNotAvailableException
1075
+     */
1076
+    public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1077
+        $result = false;
1078
+        foreach($this->connection->ldapBaseGroups as $base) {
1079
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1080
+            $result = is_int($count) ? (int)$result + $count : $result;
1081
+        }
1082
+        return $result;
1083
+    }
1084
+
1085
+    /**
1086
+     * returns the number of available objects on the base DN
1087
+     *
1088
+     * @param int|null $limit
1089
+     * @param int|null $offset
1090
+     * @return int|bool
1091
+     * @throws ServerNotAvailableException
1092
+     */
1093
+    public function countObjects($limit = null, $offset = null) {
1094
+        $result = false;
1095
+        foreach($this->connection->ldapBase as $base) {
1096
+            $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1097
+            $result = is_int($count) ? (int)$result + $count : $result;
1098
+        }
1099
+        return $result;
1100
+    }
1101
+
1102
+    /**
1103
+     * Returns the LDAP handler
1104
+     * @throws \OC\ServerNotAvailableException
1105
+     */
1106
+
1107
+    /**
1108
+     * @return mixed
1109
+     * @throws \OC\ServerNotAvailableException
1110
+     */
1111
+    private function invokeLDAPMethod() {
1112
+        $arguments = func_get_args();
1113
+        $command = array_shift($arguments);
1114
+        $cr = array_shift($arguments);
1115
+        if (!method_exists($this->ldap, $command)) {
1116
+            return null;
1117
+        }
1118
+        array_unshift($arguments, $cr);
1119
+        // php no longer supports call-time pass-by-reference
1120
+        // thus cannot support controlPagedResultResponse as the third argument
1121
+        // is a reference
1122
+        $doMethod = function () use ($command, &$arguments) {
1123
+            if ($command == 'controlPagedResultResponse') {
1124
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1125
+            } else {
1126
+                return call_user_func_array([$this->ldap, $command], $arguments);
1127
+            }
1128
+        };
1129
+        try {
1130
+            $ret = $doMethod();
1131
+        } catch (ServerNotAvailableException $e) {
1132
+            /* Server connection lost, attempt to reestablish it
1133 1133
 			 * Maybe implement exponential backoff?
1134 1134
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1135 1135
 			 */
1136
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1137
-			$this->connection->resetConnectionResource();
1138
-			$cr = $this->connection->getConnectionResource();
1139
-
1140
-			if(!$this->ldap->isResource($cr)) {
1141
-				// Seems like we didn't find any resource.
1142
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1143
-				throw $e;
1144
-			}
1145
-
1146
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1147
-			$ret = $doMethod();
1148
-		}
1149
-		return $ret;
1150
-	}
1151
-
1152
-	/**
1153
-	 * retrieved. Results will according to the order in the array.
1154
-	 *
1155
-	 * @param $filter
1156
-	 * @param $base
1157
-	 * @param string[]|string|null $attr
1158
-	 * @param int $limit optional, maximum results to be counted
1159
-	 * @param int $offset optional, a starting point
1160
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1161
-	 * second | false if not successful
1162
-	 * @throws ServerNotAvailableException
1163
-	 */
1164
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1165
-		if(!is_null($attr) && !is_array($attr)) {
1166
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1167
-		}
1168
-
1169
-		// See if we have a resource, in case not cancel with message
1170
-		$cr = $this->connection->getConnectionResource();
1171
-		if(!$this->ldap->isResource($cr)) {
1172
-			// Seems like we didn't find any resource.
1173
-			// Return an empty array just like before.
1174
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1175
-			return false;
1176
-		}
1177
-
1178
-		//check whether paged search should be attempted
1179
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1180
-
1181
-		$linkResources = array_pad([], count($base), $cr);
1182
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1183
-		// cannot use $cr anymore, might have changed in the previous call!
1184
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1185
-		if(!is_array($sr) || $error !== 0) {
1186
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1187
-			return false;
1188
-		}
1189
-
1190
-		return [$sr, $pagedSearchOK];
1191
-	}
1192
-
1193
-	/**
1194
-	 * processes an LDAP paged search operation
1195
-	 *
1196
-	 * @param array $sr the array containing the LDAP search resources
1197
-	 * @param string $filter the LDAP filter for the search
1198
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1199
-	 * @param int $iFoundItems number of results in the single search operation
1200
-	 * @param int $limit maximum results to be counted
1201
-	 * @param int $offset a starting point
1202
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1203
-	 * @param bool $skipHandling required for paged search when cookies to
1204
-	 * prior results need to be gained
1205
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1206
-	 * @throws ServerNotAvailableException
1207
-	 */
1208
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1209
-		$cookie = null;
1210
-		if($pagedSearchOK) {
1211
-			$cr = $this->connection->getConnectionResource();
1212
-			foreach($sr as $key => $res) {
1213
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1214
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1215
-				}
1216
-			}
1217
-
1218
-			//browsing through prior pages to get the cookie for the new one
1219
-			if($skipHandling) {
1220
-				return false;
1221
-			}
1222
-			// if count is bigger, then the server does not support
1223
-			// paged search. Instead, he did a normal search. We set a
1224
-			// flag here, so the callee knows how to deal with it.
1225
-			if($iFoundItems <= $limit) {
1226
-				$this->pagedSearchedSuccessful = true;
1227
-			}
1228
-		} else {
1229
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1230
-				\OC::$server->getLogger()->debug(
1231
-					'Paged search was not available',
1232
-					[ 'app' => 'user_ldap' ]
1233
-				);
1234
-			}
1235
-		}
1236
-		/* ++ Fixing RHDS searches with pages with zero results ++
1136
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1137
+            $this->connection->resetConnectionResource();
1138
+            $cr = $this->connection->getConnectionResource();
1139
+
1140
+            if(!$this->ldap->isResource($cr)) {
1141
+                // Seems like we didn't find any resource.
1142
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1143
+                throw $e;
1144
+            }
1145
+
1146
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1147
+            $ret = $doMethod();
1148
+        }
1149
+        return $ret;
1150
+    }
1151
+
1152
+    /**
1153
+     * retrieved. Results will according to the order in the array.
1154
+     *
1155
+     * @param $filter
1156
+     * @param $base
1157
+     * @param string[]|string|null $attr
1158
+     * @param int $limit optional, maximum results to be counted
1159
+     * @param int $offset optional, a starting point
1160
+     * @return array|false array with the search result as first value and pagedSearchOK as
1161
+     * second | false if not successful
1162
+     * @throws ServerNotAvailableException
1163
+     */
1164
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1165
+        if(!is_null($attr) && !is_array($attr)) {
1166
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1167
+        }
1168
+
1169
+        // See if we have a resource, in case not cancel with message
1170
+        $cr = $this->connection->getConnectionResource();
1171
+        if(!$this->ldap->isResource($cr)) {
1172
+            // Seems like we didn't find any resource.
1173
+            // Return an empty array just like before.
1174
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1175
+            return false;
1176
+        }
1177
+
1178
+        //check whether paged search should be attempted
1179
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1180
+
1181
+        $linkResources = array_pad([], count($base), $cr);
1182
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1183
+        // cannot use $cr anymore, might have changed in the previous call!
1184
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1185
+        if(!is_array($sr) || $error !== 0) {
1186
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1187
+            return false;
1188
+        }
1189
+
1190
+        return [$sr, $pagedSearchOK];
1191
+    }
1192
+
1193
+    /**
1194
+     * processes an LDAP paged search operation
1195
+     *
1196
+     * @param array $sr the array containing the LDAP search resources
1197
+     * @param string $filter the LDAP filter for the search
1198
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1199
+     * @param int $iFoundItems number of results in the single search operation
1200
+     * @param int $limit maximum results to be counted
1201
+     * @param int $offset a starting point
1202
+     * @param bool $pagedSearchOK whether a paged search has been executed
1203
+     * @param bool $skipHandling required for paged search when cookies to
1204
+     * prior results need to be gained
1205
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1206
+     * @throws ServerNotAvailableException
1207
+     */
1208
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1209
+        $cookie = null;
1210
+        if($pagedSearchOK) {
1211
+            $cr = $this->connection->getConnectionResource();
1212
+            foreach($sr as $key => $res) {
1213
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1214
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1215
+                }
1216
+            }
1217
+
1218
+            //browsing through prior pages to get the cookie for the new one
1219
+            if($skipHandling) {
1220
+                return false;
1221
+            }
1222
+            // if count is bigger, then the server does not support
1223
+            // paged search. Instead, he did a normal search. We set a
1224
+            // flag here, so the callee knows how to deal with it.
1225
+            if($iFoundItems <= $limit) {
1226
+                $this->pagedSearchedSuccessful = true;
1227
+            }
1228
+        } else {
1229
+            if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1230
+                \OC::$server->getLogger()->debug(
1231
+                    'Paged search was not available',
1232
+                    [ 'app' => 'user_ldap' ]
1233
+                );
1234
+            }
1235
+        }
1236
+        /* ++ Fixing RHDS searches with pages with zero results ++
1237 1237
 		 * Return cookie status. If we don't have more pages, with RHDS
1238 1238
 		 * cookie is null, with openldap cookie is an empty string and
1239 1239
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1240 1240
 		 */
1241
-		return !empty($cookie) || $cookie === '0';
1242
-	}
1243
-
1244
-	/**
1245
-	 * executes an LDAP search, but counts the results only
1246
-	 *
1247
-	 * @param string $filter the LDAP filter for the search
1248
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1249
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1250
-	 * retrieved. Results will according to the order in the array.
1251
-	 * @param int $limit optional, maximum results to be counted
1252
-	 * @param int $offset optional, a starting point
1253
-	 * @param bool $skipHandling indicates whether the pages search operation is
1254
-	 * completed
1255
-	 * @return int|false Integer or false if the search could not be initialized
1256
-	 * @throws ServerNotAvailableException
1257
-	 */
1258
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1259
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1260
-
1261
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1262
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1263
-			$limitPerPage = $limit;
1264
-		}
1265
-
1266
-		$counter = 0;
1267
-		$count = null;
1268
-		$this->connection->getConnectionResource();
1269
-
1270
-		do {
1271
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1272
-			if($search === false) {
1273
-				return $counter > 0 ? $counter : false;
1274
-			}
1275
-			list($sr, $pagedSearchOK) = $search;
1276
-
1277
-			/* ++ Fixing RHDS searches with pages with zero results ++
1241
+        return !empty($cookie) || $cookie === '0';
1242
+    }
1243
+
1244
+    /**
1245
+     * executes an LDAP search, but counts the results only
1246
+     *
1247
+     * @param string $filter the LDAP filter for the search
1248
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1249
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1250
+     * retrieved. Results will according to the order in the array.
1251
+     * @param int $limit optional, maximum results to be counted
1252
+     * @param int $offset optional, a starting point
1253
+     * @param bool $skipHandling indicates whether the pages search operation is
1254
+     * completed
1255
+     * @return int|false Integer or false if the search could not be initialized
1256
+     * @throws ServerNotAvailableException
1257
+     */
1258
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1259
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1260
+
1261
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1262
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1263
+            $limitPerPage = $limit;
1264
+        }
1265
+
1266
+        $counter = 0;
1267
+        $count = null;
1268
+        $this->connection->getConnectionResource();
1269
+
1270
+        do {
1271
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1272
+            if($search === false) {
1273
+                return $counter > 0 ? $counter : false;
1274
+            }
1275
+            list($sr, $pagedSearchOK) = $search;
1276
+
1277
+            /* ++ Fixing RHDS searches with pages with zero results ++
1278 1278
 			 * countEntriesInSearchResults() method signature changed
1279 1279
 			 * by removing $limit and &$hasHitLimit parameters
1280 1280
 			 */
1281
-			$count = $this->countEntriesInSearchResults($sr);
1282
-			$counter += $count;
1281
+            $count = $this->countEntriesInSearchResults($sr);
1282
+            $counter += $count;
1283 1283
 
1284
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1285
-										$offset, $pagedSearchOK, $skipHandling);
1286
-			$offset += $limitPerPage;
1287
-			/* ++ Fixing RHDS searches with pages with zero results ++
1284
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1285
+                                        $offset, $pagedSearchOK, $skipHandling);
1286
+            $offset += $limitPerPage;
1287
+            /* ++ Fixing RHDS searches with pages with zero results ++
1288 1288
 			 * Continue now depends on $hasMorePages value
1289 1289
 			 */
1290
-			$continue = $pagedSearchOK && $hasMorePages;
1291
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1292
-
1293
-		return $counter;
1294
-	}
1295
-
1296
-	/**
1297
-	 * @param array $searchResults
1298
-	 * @return int
1299
-	 * @throws ServerNotAvailableException
1300
-	 */
1301
-	private function countEntriesInSearchResults($searchResults) {
1302
-		$counter = 0;
1303
-
1304
-		foreach($searchResults as $res) {
1305
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1306
-			$counter += $count;
1307
-		}
1308
-
1309
-		return $counter;
1310
-	}
1311
-
1312
-	/**
1313
-	 * Executes an LDAP search
1314
-	 *
1315
-	 * @param string $filter the LDAP filter for the search
1316
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1317
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1318
-	 * @param int $limit
1319
-	 * @param int $offset
1320
-	 * @param bool $skipHandling
1321
-	 * @return array with the search result
1322
-	 * @throws ServerNotAvailableException
1323
-	 */
1324
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1325
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1326
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1327
-			$limitPerPage = $limit;
1328
-		}
1329
-
1330
-		/* ++ Fixing RHDS searches with pages with zero results ++
1290
+            $continue = $pagedSearchOK && $hasMorePages;
1291
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1292
+
1293
+        return $counter;
1294
+    }
1295
+
1296
+    /**
1297
+     * @param array $searchResults
1298
+     * @return int
1299
+     * @throws ServerNotAvailableException
1300
+     */
1301
+    private function countEntriesInSearchResults($searchResults) {
1302
+        $counter = 0;
1303
+
1304
+        foreach($searchResults as $res) {
1305
+            $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1306
+            $counter += $count;
1307
+        }
1308
+
1309
+        return $counter;
1310
+    }
1311
+
1312
+    /**
1313
+     * Executes an LDAP search
1314
+     *
1315
+     * @param string $filter the LDAP filter for the search
1316
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1317
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1318
+     * @param int $limit
1319
+     * @param int $offset
1320
+     * @param bool $skipHandling
1321
+     * @return array with the search result
1322
+     * @throws ServerNotAvailableException
1323
+     */
1324
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1325
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1326
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1327
+            $limitPerPage = $limit;
1328
+        }
1329
+
1330
+        /* ++ Fixing RHDS searches with pages with zero results ++
1331 1331
 		 * As we can have pages with zero results and/or pages with less
1332 1332
 		 * than $limit results but with a still valid server 'cookie',
1333 1333
 		 * loops through until we get $continue equals true and
1334 1334
 		 * $findings['count'] < $limit
1335 1335
 		 */
1336
-		$findings = [];
1337
-		$savedoffset = $offset;
1338
-		do {
1339
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1340
-			if($search === false) {
1341
-				return [];
1342
-			}
1343
-			list($sr, $pagedSearchOK) = $search;
1344
-			$cr = $this->connection->getConnectionResource();
1345
-
1346
-			if($skipHandling) {
1347
-				//i.e. result do not need to be fetched, we just need the cookie
1348
-				//thus pass 1 or any other value as $iFoundItems because it is not
1349
-				//used
1350
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1351
-								$offset, $pagedSearchOK,
1352
-								$skipHandling);
1353
-				return [];
1354
-			}
1355
-
1356
-			$iFoundItems = 0;
1357
-			foreach($sr as $res) {
1358
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1359
-				$iFoundItems = max($iFoundItems, $findings['count']);
1360
-				unset($findings['count']);
1361
-			}
1362
-
1363
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1364
-				$limitPerPage, $offset, $pagedSearchOK,
1365
-										$skipHandling);
1366
-			$offset += $limitPerPage;
1367
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1368
-		// reseting offset
1369
-		$offset = $savedoffset;
1370
-
1371
-		// if we're here, probably no connection resource is returned.
1372
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1373
-		if(is_null($findings)) {
1374
-			return [];
1375
-		}
1376
-
1377
-		if(!is_null($attr)) {
1378
-			$selection = [];
1379
-			$i = 0;
1380
-			foreach($findings as $item) {
1381
-				if(!is_array($item)) {
1382
-					continue;
1383
-				}
1384
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1385
-				foreach($attr as $key) {
1386
-					if(isset($item[$key])) {
1387
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1388
-							unset($item[$key]['count']);
1389
-						}
1390
-						if($key !== 'dn') {
1391
-							if($this->resemblesDN($key)) {
1392
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1393
-							} else if($key === 'objectguid' || $key === 'guid') {
1394
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1395
-							} else {
1396
-								$selection[$i][$key] = $item[$key];
1397
-							}
1398
-						} else {
1399
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1400
-						}
1401
-					}
1402
-
1403
-				}
1404
-				$i++;
1405
-			}
1406
-			$findings = $selection;
1407
-		}
1408
-		//we slice the findings, when
1409
-		//a) paged search unsuccessful, though attempted
1410
-		//b) no paged search, but limit set
1411
-		if((!$this->getPagedSearchResultState()
1412
-			&& $pagedSearchOK)
1413
-			|| (
1414
-				!$pagedSearchOK
1415
-				&& !is_null($limit)
1416
-			)
1417
-		) {
1418
-			$findings = array_slice($findings, (int)$offset, $limit);
1419
-		}
1420
-		return $findings;
1421
-	}
1422
-
1423
-	/**
1424
-	 * @param string $name
1425
-	 * @return string
1426
-	 * @throws \InvalidArgumentException
1427
-	 */
1428
-	public function sanitizeUsername($name) {
1429
-		$name = trim($name);
1430
-
1431
-		if($this->connection->ldapIgnoreNamingRules) {
1432
-			return $name;
1433
-		}
1434
-
1435
-		// Transliteration to ASCII
1436
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1437
-		if($transliterated !== false) {
1438
-			// depending on system config iconv can work or not
1439
-			$name = $transliterated;
1440
-		}
1441
-
1442
-		// Replacements
1443
-		$name = str_replace(' ', '_', $name);
1444
-
1445
-		// Every remaining disallowed characters will be removed
1446
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1447
-
1448
-		if($name === '') {
1449
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1450
-		}
1451
-
1452
-		return $name;
1453
-	}
1454
-
1455
-	/**
1456
-	 * escapes (user provided) parts for LDAP filter
1457
-	 * @param string $input, the provided value
1458
-	 * @param bool $allowAsterisk whether in * at the beginning should be preserved
1459
-	 * @return string the escaped string
1460
-	 */
1461
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1462
-		$asterisk = '';
1463
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1464
-			$asterisk = '*';
1465
-			$input = mb_substr($input, 1, null, 'UTF-8');
1466
-		}
1467
-		$search  = ['*', '\\', '(', ')'];
1468
-		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1469
-		return $asterisk . str_replace($search, $replace, $input);
1470
-	}
1471
-
1472
-	/**
1473
-	 * combines the input filters with AND
1474
-	 * @param string[] $filters the filters to connect
1475
-	 * @return string the combined filter
1476
-	 */
1477
-	public function combineFilterWithAnd($filters) {
1478
-		return $this->combineFilter($filters, '&');
1479
-	}
1480
-
1481
-	/**
1482
-	 * combines the input filters with OR
1483
-	 * @param string[] $filters the filters to connect
1484
-	 * @return string the combined filter
1485
-	 * Combines Filter arguments with OR
1486
-	 */
1487
-	public function combineFilterWithOr($filters) {
1488
-		return $this->combineFilter($filters, '|');
1489
-	}
1490
-
1491
-	/**
1492
-	 * combines the input filters with given operator
1493
-	 * @param string[] $filters the filters to connect
1494
-	 * @param string $operator either & or |
1495
-	 * @return string the combined filter
1496
-	 */
1497
-	private function combineFilter($filters, $operator) {
1498
-		$combinedFilter = '('.$operator;
1499
-		foreach($filters as $filter) {
1500
-			if ($filter !== '' && $filter[0] !== '(') {
1501
-				$filter = '('.$filter.')';
1502
-			}
1503
-			$combinedFilter.=$filter;
1504
-		}
1505
-		$combinedFilter.=')';
1506
-		return $combinedFilter;
1507
-	}
1508
-
1509
-	/**
1510
-	 * creates a filter part for to perform search for users
1511
-	 * @param string $search the search term
1512
-	 * @return string the final filter part to use in LDAP searches
1513
-	 */
1514
-	public function getFilterPartForUserSearch($search) {
1515
-		return $this->getFilterPartForSearch($search,
1516
-			$this->connection->ldapAttributesForUserSearch,
1517
-			$this->connection->ldapUserDisplayName);
1518
-	}
1519
-
1520
-	/**
1521
-	 * creates a filter part for to perform search for groups
1522
-	 * @param string $search the search term
1523
-	 * @return string the final filter part to use in LDAP searches
1524
-	 */
1525
-	public function getFilterPartForGroupSearch($search) {
1526
-		return $this->getFilterPartForSearch($search,
1527
-			$this->connection->ldapAttributesForGroupSearch,
1528
-			$this->connection->ldapGroupDisplayName);
1529
-	}
1530
-
1531
-	/**
1532
-	 * creates a filter part for searches by splitting up the given search
1533
-	 * string into single words
1534
-	 * @param string $search the search term
1535
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1536
-	 * otherwise it does not make sense :)
1537
-	 * @return string the final filter part to use in LDAP searches
1538
-	 * @throws \Exception
1539
-	 */
1540
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1541
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1542
-			throw new \Exception('searchAttributes must be an array with at least two string');
1543
-		}
1544
-		$searchWords = explode(' ', trim($search));
1545
-		$wordFilters = [];
1546
-		foreach($searchWords as $word) {
1547
-			$word = $this->prepareSearchTerm($word);
1548
-			//every word needs to appear at least once
1549
-			$wordMatchOneAttrFilters = [];
1550
-			foreach($searchAttributes as $attr) {
1551
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1552
-			}
1553
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1554
-		}
1555
-		return $this->combineFilterWithAnd($wordFilters);
1556
-	}
1557
-
1558
-	/**
1559
-	 * creates a filter part for searches
1560
-	 * @param string $search the search term
1561
-	 * @param string[]|null $searchAttributes
1562
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1563
-	 * did not define search attributes. Typically the display name attribute.
1564
-	 * @return string the final filter part to use in LDAP searches
1565
-	 */
1566
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1567
-		$filter = [];
1568
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1569
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1570
-			try {
1571
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1572
-			} catch(\Exception $e) {
1573
-				\OCP\Util::writeLog(
1574
-					'user_ldap',
1575
-					'Creating advanced filter for search failed, falling back to simple method.',
1576
-					ILogger::INFO
1577
-				);
1578
-			}
1579
-		}
1580
-
1581
-		$search = $this->prepareSearchTerm($search);
1582
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1583
-			if ($fallbackAttribute === '') {
1584
-				return '';
1585
-			}
1586
-			$filter[] = $fallbackAttribute . '=' . $search;
1587
-		} else {
1588
-			foreach($searchAttributes as $attribute) {
1589
-				$filter[] = $attribute . '=' . $search;
1590
-			}
1591
-		}
1592
-		if(count($filter) === 1) {
1593
-			return '('.$filter[0].')';
1594
-		}
1595
-		return $this->combineFilterWithOr($filter);
1596
-	}
1597
-
1598
-	/**
1599
-	 * returns the search term depending on whether we are allowed
1600
-	 * list users found by ldap with the current input appended by
1601
-	 * a *
1602
-	 * @return string
1603
-	 */
1604
-	private function prepareSearchTerm($term) {
1605
-		$config = \OC::$server->getConfig();
1606
-
1607
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1608
-
1609
-		$result = $term;
1610
-		if ($term === '') {
1611
-			$result = '*';
1612
-		} else if ($allowEnum !== 'no') {
1613
-			$result = $term . '*';
1614
-		}
1615
-		return $result;
1616
-	}
1617
-
1618
-	/**
1619
-	 * returns the filter used for counting users
1620
-	 * @return string
1621
-	 */
1622
-	public function getFilterForUserCount() {
1623
-		$filter = $this->combineFilterWithAnd([
1624
-			$this->connection->ldapUserFilter,
1625
-			$this->connection->ldapUserDisplayName . '=*'
1626
-		]);
1627
-
1628
-		return $filter;
1629
-	}
1630
-
1631
-	/**
1632
-	 * @param string $name
1633
-	 * @param string $password
1634
-	 * @return bool
1635
-	 */
1636
-	public function areCredentialsValid($name, $password) {
1637
-		$name = $this->helper->DNasBaseParameter($name);
1638
-		$testConnection = clone $this->connection;
1639
-		$credentials = [
1640
-			'ldapAgentName' => $name,
1641
-			'ldapAgentPassword' => $password
1642
-		];
1643
-		if(!$testConnection->setConfiguration($credentials)) {
1644
-			return false;
1645
-		}
1646
-		return $testConnection->bind();
1647
-	}
1648
-
1649
-	/**
1650
-	 * reverse lookup of a DN given a known UUID
1651
-	 *
1652
-	 * @param string $uuid
1653
-	 * @return string
1654
-	 * @throws \Exception
1655
-	 */
1656
-	public function getUserDnByUuid($uuid) {
1657
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1658
-		$filter       = $this->connection->ldapUserFilter;
1659
-		$base         = $this->connection->ldapBaseUsers;
1660
-
1661
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1662
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1663
-			// existing DN to be able to reliably detect it.
1664
-			$result = $this->search($filter, $base, ['dn'], 1);
1665
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1666
-				throw new \Exception('Cannot determine UUID attribute');
1667
-			}
1668
-			$dn = $result[0]['dn'][0];
1669
-			if(!$this->detectUuidAttribute($dn, true)) {
1670
-				throw new \Exception('Cannot determine UUID attribute');
1671
-			}
1672
-		} else {
1673
-			// The UUID attribute is either known or an override is given.
1674
-			// By calling this method we ensure that $this->connection->$uuidAttr
1675
-			// is definitely set
1676
-			if(!$this->detectUuidAttribute('', true)) {
1677
-				throw new \Exception('Cannot determine UUID attribute');
1678
-			}
1679
-		}
1680
-
1681
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1682
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1683
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1684
-		}
1685
-
1686
-		$filter = $uuidAttr . '=' . $uuid;
1687
-		$result = $this->searchUsers($filter, ['dn'], 2);
1688
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1689
-			// we put the count into account to make sure that this is
1690
-			// really unique
1691
-			return $result[0]['dn'][0];
1692
-		}
1693
-
1694
-		throw new \Exception('Cannot determine UUID attribute');
1695
-	}
1696
-
1697
-	/**
1698
-	 * auto-detects the directory's UUID attribute
1699
-	 *
1700
-	 * @param string $dn a known DN used to check against
1701
-	 * @param bool $isUser
1702
-	 * @param bool $force the detection should be run, even if it is not set to auto
1703
-	 * @param array|null $ldapRecord
1704
-	 * @return bool true on success, false otherwise
1705
-	 * @throws ServerNotAvailableException
1706
-	 */
1707
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1708
-		if($isUser) {
1709
-			$uuidAttr     = 'ldapUuidUserAttribute';
1710
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1711
-		} else {
1712
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1713
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1714
-		}
1715
-
1716
-		if(!$force) {
1717
-			if($this->connection->$uuidAttr !== 'auto') {
1718
-				return true;
1719
-			} else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1720
-				$this->connection->$uuidAttr = $uuidOverride;
1721
-				return true;
1722
-			}
1723
-
1724
-			$attribute = $this->connection->getFromCache($uuidAttr);
1725
-			if(!$attribute === null) {
1726
-				$this->connection->$uuidAttr = $attribute;
1727
-				return true;
1728
-			}
1729
-		}
1730
-
1731
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1732
-			if($ldapRecord !== null) {
1733
-				// we have the info from LDAP already, we don't need to talk to the server again
1734
-				if(isset($ldapRecord[$attribute])) {
1735
-					$this->connection->$uuidAttr = $attribute;
1736
-					return true;
1737
-				}
1738
-			}
1739
-
1740
-			$value = $this->readAttribute($dn, $attribute);
1741
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1742
-				\OC::$server->getLogger()->debug(
1743
-					'Setting {attribute} as {subject}',
1744
-					[
1745
-						'app' => 'user_ldap',
1746
-						'attribute' => $attribute,
1747
-						'subject' => $uuidAttr
1748
-					]
1749
-				);
1750
-				$this->connection->$uuidAttr = $attribute;
1751
-				$this->connection->writeToCache($uuidAttr, $attribute);
1752
-				return true;
1753
-			}
1754
-		}
1755
-		\OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1756
-
1757
-		return false;
1758
-	}
1759
-
1760
-	/**
1761
-	 * @param string $dn
1762
-	 * @param bool $isUser
1763
-	 * @param null $ldapRecord
1764
-	 * @return bool|string
1765
-	 * @throws ServerNotAvailableException
1766
-	 */
1767
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1768
-		if($isUser) {
1769
-			$uuidAttr     = 'ldapUuidUserAttribute';
1770
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1771
-		} else {
1772
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1773
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1774
-		}
1775
-
1776
-		$uuid = false;
1777
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1778
-			$attr = $this->connection->$uuidAttr;
1779
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1780
-			if( !is_array($uuid)
1781
-				&& $uuidOverride !== ''
1782
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1783
-			{
1784
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1785
-					? $ldapRecord[$this->connection->$uuidAttr]
1786
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1787
-			}
1788
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1789
-				$uuid = $uuid[0];
1790
-			}
1791
-		}
1792
-
1793
-		return $uuid;
1794
-	}
1795
-
1796
-	/**
1797
-	 * converts a binary ObjectGUID into a string representation
1798
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1799
-	 * @return string
1800
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1801
-	 */
1802
-	private function convertObjectGUID2Str($oguid) {
1803
-		$hex_guid = bin2hex($oguid);
1804
-		$hex_guid_to_guid_str = '';
1805
-		for($k = 1; $k <= 4; ++$k) {
1806
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1807
-		}
1808
-		$hex_guid_to_guid_str .= '-';
1809
-		for($k = 1; $k <= 2; ++$k) {
1810
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1811
-		}
1812
-		$hex_guid_to_guid_str .= '-';
1813
-		for($k = 1; $k <= 2; ++$k) {
1814
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1815
-		}
1816
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1817
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1818
-
1819
-		return strtoupper($hex_guid_to_guid_str);
1820
-	}
1821
-
1822
-	/**
1823
-	 * the first three blocks of the string-converted GUID happen to be in
1824
-	 * reverse order. In order to use it in a filter, this needs to be
1825
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1826
-	 * to every two hax figures.
1827
-	 *
1828
-	 * If an invalid string is passed, it will be returned without change.
1829
-	 *
1830
-	 * @param string $guid
1831
-	 * @return string
1832
-	 */
1833
-	public function formatGuid2ForFilterUser($guid) {
1834
-		if(!is_string($guid)) {
1835
-			throw new \InvalidArgumentException('String expected');
1836
-		}
1837
-		$blocks = explode('-', $guid);
1838
-		if(count($blocks) !== 5) {
1839
-			/*
1336
+        $findings = [];
1337
+        $savedoffset = $offset;
1338
+        do {
1339
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1340
+            if($search === false) {
1341
+                return [];
1342
+            }
1343
+            list($sr, $pagedSearchOK) = $search;
1344
+            $cr = $this->connection->getConnectionResource();
1345
+
1346
+            if($skipHandling) {
1347
+                //i.e. result do not need to be fetched, we just need the cookie
1348
+                //thus pass 1 or any other value as $iFoundItems because it is not
1349
+                //used
1350
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1351
+                                $offset, $pagedSearchOK,
1352
+                                $skipHandling);
1353
+                return [];
1354
+            }
1355
+
1356
+            $iFoundItems = 0;
1357
+            foreach($sr as $res) {
1358
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1359
+                $iFoundItems = max($iFoundItems, $findings['count']);
1360
+                unset($findings['count']);
1361
+            }
1362
+
1363
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1364
+                $limitPerPage, $offset, $pagedSearchOK,
1365
+                                        $skipHandling);
1366
+            $offset += $limitPerPage;
1367
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1368
+        // reseting offset
1369
+        $offset = $savedoffset;
1370
+
1371
+        // if we're here, probably no connection resource is returned.
1372
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1373
+        if(is_null($findings)) {
1374
+            return [];
1375
+        }
1376
+
1377
+        if(!is_null($attr)) {
1378
+            $selection = [];
1379
+            $i = 0;
1380
+            foreach($findings as $item) {
1381
+                if(!is_array($item)) {
1382
+                    continue;
1383
+                }
1384
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1385
+                foreach($attr as $key) {
1386
+                    if(isset($item[$key])) {
1387
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1388
+                            unset($item[$key]['count']);
1389
+                        }
1390
+                        if($key !== 'dn') {
1391
+                            if($this->resemblesDN($key)) {
1392
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1393
+                            } else if($key === 'objectguid' || $key === 'guid') {
1394
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1395
+                            } else {
1396
+                                $selection[$i][$key] = $item[$key];
1397
+                            }
1398
+                        } else {
1399
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1400
+                        }
1401
+                    }
1402
+
1403
+                }
1404
+                $i++;
1405
+            }
1406
+            $findings = $selection;
1407
+        }
1408
+        //we slice the findings, when
1409
+        //a) paged search unsuccessful, though attempted
1410
+        //b) no paged search, but limit set
1411
+        if((!$this->getPagedSearchResultState()
1412
+            && $pagedSearchOK)
1413
+            || (
1414
+                !$pagedSearchOK
1415
+                && !is_null($limit)
1416
+            )
1417
+        ) {
1418
+            $findings = array_slice($findings, (int)$offset, $limit);
1419
+        }
1420
+        return $findings;
1421
+    }
1422
+
1423
+    /**
1424
+     * @param string $name
1425
+     * @return string
1426
+     * @throws \InvalidArgumentException
1427
+     */
1428
+    public function sanitizeUsername($name) {
1429
+        $name = trim($name);
1430
+
1431
+        if($this->connection->ldapIgnoreNamingRules) {
1432
+            return $name;
1433
+        }
1434
+
1435
+        // Transliteration to ASCII
1436
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1437
+        if($transliterated !== false) {
1438
+            // depending on system config iconv can work or not
1439
+            $name = $transliterated;
1440
+        }
1441
+
1442
+        // Replacements
1443
+        $name = str_replace(' ', '_', $name);
1444
+
1445
+        // Every remaining disallowed characters will be removed
1446
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1447
+
1448
+        if($name === '') {
1449
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1450
+        }
1451
+
1452
+        return $name;
1453
+    }
1454
+
1455
+    /**
1456
+     * escapes (user provided) parts for LDAP filter
1457
+     * @param string $input, the provided value
1458
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1459
+     * @return string the escaped string
1460
+     */
1461
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1462
+        $asterisk = '';
1463
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1464
+            $asterisk = '*';
1465
+            $input = mb_substr($input, 1, null, 'UTF-8');
1466
+        }
1467
+        $search  = ['*', '\\', '(', ')'];
1468
+        $replace = ['\\*', '\\\\', '\\(', '\\)'];
1469
+        return $asterisk . str_replace($search, $replace, $input);
1470
+    }
1471
+
1472
+    /**
1473
+     * combines the input filters with AND
1474
+     * @param string[] $filters the filters to connect
1475
+     * @return string the combined filter
1476
+     */
1477
+    public function combineFilterWithAnd($filters) {
1478
+        return $this->combineFilter($filters, '&');
1479
+    }
1480
+
1481
+    /**
1482
+     * combines the input filters with OR
1483
+     * @param string[] $filters the filters to connect
1484
+     * @return string the combined filter
1485
+     * Combines Filter arguments with OR
1486
+     */
1487
+    public function combineFilterWithOr($filters) {
1488
+        return $this->combineFilter($filters, '|');
1489
+    }
1490
+
1491
+    /**
1492
+     * combines the input filters with given operator
1493
+     * @param string[] $filters the filters to connect
1494
+     * @param string $operator either & or |
1495
+     * @return string the combined filter
1496
+     */
1497
+    private function combineFilter($filters, $operator) {
1498
+        $combinedFilter = '('.$operator;
1499
+        foreach($filters as $filter) {
1500
+            if ($filter !== '' && $filter[0] !== '(') {
1501
+                $filter = '('.$filter.')';
1502
+            }
1503
+            $combinedFilter.=$filter;
1504
+        }
1505
+        $combinedFilter.=')';
1506
+        return $combinedFilter;
1507
+    }
1508
+
1509
+    /**
1510
+     * creates a filter part for to perform search for users
1511
+     * @param string $search the search term
1512
+     * @return string the final filter part to use in LDAP searches
1513
+     */
1514
+    public function getFilterPartForUserSearch($search) {
1515
+        return $this->getFilterPartForSearch($search,
1516
+            $this->connection->ldapAttributesForUserSearch,
1517
+            $this->connection->ldapUserDisplayName);
1518
+    }
1519
+
1520
+    /**
1521
+     * creates a filter part for to perform search for groups
1522
+     * @param string $search the search term
1523
+     * @return string the final filter part to use in LDAP searches
1524
+     */
1525
+    public function getFilterPartForGroupSearch($search) {
1526
+        return $this->getFilterPartForSearch($search,
1527
+            $this->connection->ldapAttributesForGroupSearch,
1528
+            $this->connection->ldapGroupDisplayName);
1529
+    }
1530
+
1531
+    /**
1532
+     * creates a filter part for searches by splitting up the given search
1533
+     * string into single words
1534
+     * @param string $search the search term
1535
+     * @param string[] $searchAttributes needs to have at least two attributes,
1536
+     * otherwise it does not make sense :)
1537
+     * @return string the final filter part to use in LDAP searches
1538
+     * @throws \Exception
1539
+     */
1540
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1541
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1542
+            throw new \Exception('searchAttributes must be an array with at least two string');
1543
+        }
1544
+        $searchWords = explode(' ', trim($search));
1545
+        $wordFilters = [];
1546
+        foreach($searchWords as $word) {
1547
+            $word = $this->prepareSearchTerm($word);
1548
+            //every word needs to appear at least once
1549
+            $wordMatchOneAttrFilters = [];
1550
+            foreach($searchAttributes as $attr) {
1551
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1552
+            }
1553
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1554
+        }
1555
+        return $this->combineFilterWithAnd($wordFilters);
1556
+    }
1557
+
1558
+    /**
1559
+     * creates a filter part for searches
1560
+     * @param string $search the search term
1561
+     * @param string[]|null $searchAttributes
1562
+     * @param string $fallbackAttribute a fallback attribute in case the user
1563
+     * did not define search attributes. Typically the display name attribute.
1564
+     * @return string the final filter part to use in LDAP searches
1565
+     */
1566
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1567
+        $filter = [];
1568
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1569
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1570
+            try {
1571
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1572
+            } catch(\Exception $e) {
1573
+                \OCP\Util::writeLog(
1574
+                    'user_ldap',
1575
+                    'Creating advanced filter for search failed, falling back to simple method.',
1576
+                    ILogger::INFO
1577
+                );
1578
+            }
1579
+        }
1580
+
1581
+        $search = $this->prepareSearchTerm($search);
1582
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1583
+            if ($fallbackAttribute === '') {
1584
+                return '';
1585
+            }
1586
+            $filter[] = $fallbackAttribute . '=' . $search;
1587
+        } else {
1588
+            foreach($searchAttributes as $attribute) {
1589
+                $filter[] = $attribute . '=' . $search;
1590
+            }
1591
+        }
1592
+        if(count($filter) === 1) {
1593
+            return '('.$filter[0].')';
1594
+        }
1595
+        return $this->combineFilterWithOr($filter);
1596
+    }
1597
+
1598
+    /**
1599
+     * returns the search term depending on whether we are allowed
1600
+     * list users found by ldap with the current input appended by
1601
+     * a *
1602
+     * @return string
1603
+     */
1604
+    private function prepareSearchTerm($term) {
1605
+        $config = \OC::$server->getConfig();
1606
+
1607
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1608
+
1609
+        $result = $term;
1610
+        if ($term === '') {
1611
+            $result = '*';
1612
+        } else if ($allowEnum !== 'no') {
1613
+            $result = $term . '*';
1614
+        }
1615
+        return $result;
1616
+    }
1617
+
1618
+    /**
1619
+     * returns the filter used for counting users
1620
+     * @return string
1621
+     */
1622
+    public function getFilterForUserCount() {
1623
+        $filter = $this->combineFilterWithAnd([
1624
+            $this->connection->ldapUserFilter,
1625
+            $this->connection->ldapUserDisplayName . '=*'
1626
+        ]);
1627
+
1628
+        return $filter;
1629
+    }
1630
+
1631
+    /**
1632
+     * @param string $name
1633
+     * @param string $password
1634
+     * @return bool
1635
+     */
1636
+    public function areCredentialsValid($name, $password) {
1637
+        $name = $this->helper->DNasBaseParameter($name);
1638
+        $testConnection = clone $this->connection;
1639
+        $credentials = [
1640
+            'ldapAgentName' => $name,
1641
+            'ldapAgentPassword' => $password
1642
+        ];
1643
+        if(!$testConnection->setConfiguration($credentials)) {
1644
+            return false;
1645
+        }
1646
+        return $testConnection->bind();
1647
+    }
1648
+
1649
+    /**
1650
+     * reverse lookup of a DN given a known UUID
1651
+     *
1652
+     * @param string $uuid
1653
+     * @return string
1654
+     * @throws \Exception
1655
+     */
1656
+    public function getUserDnByUuid($uuid) {
1657
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1658
+        $filter       = $this->connection->ldapUserFilter;
1659
+        $base         = $this->connection->ldapBaseUsers;
1660
+
1661
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1662
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1663
+            // existing DN to be able to reliably detect it.
1664
+            $result = $this->search($filter, $base, ['dn'], 1);
1665
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1666
+                throw new \Exception('Cannot determine UUID attribute');
1667
+            }
1668
+            $dn = $result[0]['dn'][0];
1669
+            if(!$this->detectUuidAttribute($dn, true)) {
1670
+                throw new \Exception('Cannot determine UUID attribute');
1671
+            }
1672
+        } else {
1673
+            // The UUID attribute is either known or an override is given.
1674
+            // By calling this method we ensure that $this->connection->$uuidAttr
1675
+            // is definitely set
1676
+            if(!$this->detectUuidAttribute('', true)) {
1677
+                throw new \Exception('Cannot determine UUID attribute');
1678
+            }
1679
+        }
1680
+
1681
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1682
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1683
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1684
+        }
1685
+
1686
+        $filter = $uuidAttr . '=' . $uuid;
1687
+        $result = $this->searchUsers($filter, ['dn'], 2);
1688
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1689
+            // we put the count into account to make sure that this is
1690
+            // really unique
1691
+            return $result[0]['dn'][0];
1692
+        }
1693
+
1694
+        throw new \Exception('Cannot determine UUID attribute');
1695
+    }
1696
+
1697
+    /**
1698
+     * auto-detects the directory's UUID attribute
1699
+     *
1700
+     * @param string $dn a known DN used to check against
1701
+     * @param bool $isUser
1702
+     * @param bool $force the detection should be run, even if it is not set to auto
1703
+     * @param array|null $ldapRecord
1704
+     * @return bool true on success, false otherwise
1705
+     * @throws ServerNotAvailableException
1706
+     */
1707
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1708
+        if($isUser) {
1709
+            $uuidAttr     = 'ldapUuidUserAttribute';
1710
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1711
+        } else {
1712
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1713
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1714
+        }
1715
+
1716
+        if(!$force) {
1717
+            if($this->connection->$uuidAttr !== 'auto') {
1718
+                return true;
1719
+            } else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1720
+                $this->connection->$uuidAttr = $uuidOverride;
1721
+                return true;
1722
+            }
1723
+
1724
+            $attribute = $this->connection->getFromCache($uuidAttr);
1725
+            if(!$attribute === null) {
1726
+                $this->connection->$uuidAttr = $attribute;
1727
+                return true;
1728
+            }
1729
+        }
1730
+
1731
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1732
+            if($ldapRecord !== null) {
1733
+                // we have the info from LDAP already, we don't need to talk to the server again
1734
+                if(isset($ldapRecord[$attribute])) {
1735
+                    $this->connection->$uuidAttr = $attribute;
1736
+                    return true;
1737
+                }
1738
+            }
1739
+
1740
+            $value = $this->readAttribute($dn, $attribute);
1741
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1742
+                \OC::$server->getLogger()->debug(
1743
+                    'Setting {attribute} as {subject}',
1744
+                    [
1745
+                        'app' => 'user_ldap',
1746
+                        'attribute' => $attribute,
1747
+                        'subject' => $uuidAttr
1748
+                    ]
1749
+                );
1750
+                $this->connection->$uuidAttr = $attribute;
1751
+                $this->connection->writeToCache($uuidAttr, $attribute);
1752
+                return true;
1753
+            }
1754
+        }
1755
+        \OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1756
+
1757
+        return false;
1758
+    }
1759
+
1760
+    /**
1761
+     * @param string $dn
1762
+     * @param bool $isUser
1763
+     * @param null $ldapRecord
1764
+     * @return bool|string
1765
+     * @throws ServerNotAvailableException
1766
+     */
1767
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1768
+        if($isUser) {
1769
+            $uuidAttr     = 'ldapUuidUserAttribute';
1770
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1771
+        } else {
1772
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1773
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1774
+        }
1775
+
1776
+        $uuid = false;
1777
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1778
+            $attr = $this->connection->$uuidAttr;
1779
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1780
+            if( !is_array($uuid)
1781
+                && $uuidOverride !== ''
1782
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1783
+            {
1784
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1785
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1786
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1787
+            }
1788
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1789
+                $uuid = $uuid[0];
1790
+            }
1791
+        }
1792
+
1793
+        return $uuid;
1794
+    }
1795
+
1796
+    /**
1797
+     * converts a binary ObjectGUID into a string representation
1798
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1799
+     * @return string
1800
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1801
+     */
1802
+    private function convertObjectGUID2Str($oguid) {
1803
+        $hex_guid = bin2hex($oguid);
1804
+        $hex_guid_to_guid_str = '';
1805
+        for($k = 1; $k <= 4; ++$k) {
1806
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1807
+        }
1808
+        $hex_guid_to_guid_str .= '-';
1809
+        for($k = 1; $k <= 2; ++$k) {
1810
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1811
+        }
1812
+        $hex_guid_to_guid_str .= '-';
1813
+        for($k = 1; $k <= 2; ++$k) {
1814
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1815
+        }
1816
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1817
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1818
+
1819
+        return strtoupper($hex_guid_to_guid_str);
1820
+    }
1821
+
1822
+    /**
1823
+     * the first three blocks of the string-converted GUID happen to be in
1824
+     * reverse order. In order to use it in a filter, this needs to be
1825
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1826
+     * to every two hax figures.
1827
+     *
1828
+     * If an invalid string is passed, it will be returned without change.
1829
+     *
1830
+     * @param string $guid
1831
+     * @return string
1832
+     */
1833
+    public function formatGuid2ForFilterUser($guid) {
1834
+        if(!is_string($guid)) {
1835
+            throw new \InvalidArgumentException('String expected');
1836
+        }
1837
+        $blocks = explode('-', $guid);
1838
+        if(count($blocks) !== 5) {
1839
+            /*
1840 1840
 			 * Why not throw an Exception instead? This method is a utility
1841 1841
 			 * called only when trying to figure out whether a "missing" known
1842 1842
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1847,283 +1847,283 @@  discard block
 block discarded – undo
1847 1847
 			 * an exception here would kill the experience for a valid, acting
1848 1848
 			 * user. Instead we write a log message.
1849 1849
 			 */
1850
-			\OC::$server->getLogger()->info(
1851
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1852
-				'({uuid}) probably does not match UUID configuration.',
1853
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1854
-			);
1855
-			return $guid;
1856
-		}
1857
-		for($i=0; $i < 3; $i++) {
1858
-			$pairs = str_split($blocks[$i], 2);
1859
-			$pairs = array_reverse($pairs);
1860
-			$blocks[$i] = implode('', $pairs);
1861
-		}
1862
-		for($i=0; $i < 5; $i++) {
1863
-			$pairs = str_split($blocks[$i], 2);
1864
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1865
-		}
1866
-		return implode('', $blocks);
1867
-	}
1868
-
1869
-	/**
1870
-	 * gets a SID of the domain of the given dn
1871
-	 *
1872
-	 * @param string $dn
1873
-	 * @return string|bool
1874
-	 * @throws ServerNotAvailableException
1875
-	 */
1876
-	public function getSID($dn) {
1877
-		$domainDN = $this->getDomainDNFromDN($dn);
1878
-		$cacheKey = 'getSID-'.$domainDN;
1879
-		$sid = $this->connection->getFromCache($cacheKey);
1880
-		if(!is_null($sid)) {
1881
-			return $sid;
1882
-		}
1883
-
1884
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1885
-		if(!is_array($objectSid) || empty($objectSid)) {
1886
-			$this->connection->writeToCache($cacheKey, false);
1887
-			return false;
1888
-		}
1889
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1890
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1891
-
1892
-		return $domainObjectSid;
1893
-	}
1894
-
1895
-	/**
1896
-	 * converts a binary SID into a string representation
1897
-	 * @param string $sid
1898
-	 * @return string
1899
-	 */
1900
-	public function convertSID2Str($sid) {
1901
-		// The format of a SID binary string is as follows:
1902
-		// 1 byte for the revision level
1903
-		// 1 byte for the number n of variable sub-ids
1904
-		// 6 bytes for identifier authority value
1905
-		// n*4 bytes for n sub-ids
1906
-		//
1907
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1908
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1909
-		$revision = ord($sid[0]);
1910
-		$numberSubID = ord($sid[1]);
1911
-
1912
-		$subIdStart = 8; // 1 + 1 + 6
1913
-		$subIdLength = 4;
1914
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1915
-			// Incorrect number of bytes present.
1916
-			return '';
1917
-		}
1918
-
1919
-		// 6 bytes = 48 bits can be represented using floats without loss of
1920
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1921
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1922
-
1923
-		$subIDs = [];
1924
-		for ($i = 0; $i < $numberSubID; $i++) {
1925
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1926
-			$subIDs[] = sprintf('%u', $subID[1]);
1927
-		}
1928
-
1929
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1930
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1931
-	}
1932
-
1933
-	/**
1934
-	 * checks if the given DN is part of the given base DN(s)
1935
-	 * @param string $dn the DN
1936
-	 * @param string[] $bases array containing the allowed base DN or DNs
1937
-	 * @return bool
1938
-	 */
1939
-	public function isDNPartOfBase($dn, $bases) {
1940
-		$belongsToBase = false;
1941
-		$bases = $this->helper->sanitizeDN($bases);
1942
-
1943
-		foreach($bases as $base) {
1944
-			$belongsToBase = true;
1945
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1946
-				$belongsToBase = false;
1947
-			}
1948
-			if($belongsToBase) {
1949
-				break;
1950
-			}
1951
-		}
1952
-		return $belongsToBase;
1953
-	}
1954
-
1955
-	/**
1956
-	 * resets a running Paged Search operation
1957
-	 *
1958
-	 * @throws ServerNotAvailableException
1959
-	 */
1960
-	private function abandonPagedSearch() {
1961
-		$cr = $this->connection->getConnectionResource();
1962
-		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1963
-		$this->getPagedSearchResultState();
1964
-		$this->lastCookie = '';
1965
-		$this->cookies = [];
1966
-	}
1967
-
1968
-	/**
1969
-	 * get a cookie for the next LDAP paged search
1970
-	 * @param string $base a string with the base DN for the search
1971
-	 * @param string $filter the search filter to identify the correct search
1972
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1973
-	 * @param int $offset the offset for the new search to identify the correct search really good
1974
-	 * @return string containing the key or empty if none is cached
1975
-	 */
1976
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1977
-		if($offset === 0) {
1978
-			return '';
1979
-		}
1980
-		$offset -= $limit;
1981
-		//we work with cache here
1982
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1983
-		$cookie = '';
1984
-		if(isset($this->cookies[$cacheKey])) {
1985
-			$cookie = $this->cookies[$cacheKey];
1986
-			if(is_null($cookie)) {
1987
-				$cookie = '';
1988
-			}
1989
-		}
1990
-		return $cookie;
1991
-	}
1992
-
1993
-	/**
1994
-	 * checks whether an LDAP paged search operation has more pages that can be
1995
-	 * retrieved, typically when offset and limit are provided.
1996
-	 *
1997
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1998
-	 * be reset by other operations. Best, call it immediately after a search(),
1999
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
2000
-	 * well. Don't rely on it with any fetchList-method.
2001
-	 * @return bool
2002
-	 */
2003
-	public function hasMoreResults() {
2004
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2005
-			// as in RFC 2696, when all results are returned, the cookie will
2006
-			// be empty.
2007
-			return false;
2008
-		}
2009
-
2010
-		return true;
2011
-	}
2012
-
2013
-	/**
2014
-	 * set a cookie for LDAP paged search run
2015
-	 * @param string $base a string with the base DN for the search
2016
-	 * @param string $filter the search filter to identify the correct search
2017
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
2018
-	 * @param int $offset the offset for the run search to identify the correct search really good
2019
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
2020
-	 * @return void
2021
-	 */
2022
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2023
-		// allow '0' for 389ds
2024
-		if(!empty($cookie) || $cookie === '0') {
2025
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2026
-			$this->cookies[$cacheKey] = $cookie;
2027
-			$this->lastCookie = $cookie;
2028
-		}
2029
-	}
2030
-
2031
-	/**
2032
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2033
-	 * @return boolean|null true on success, null or false otherwise
2034
-	 */
2035
-	public function getPagedSearchResultState() {
2036
-		$result = $this->pagedSearchedSuccessful;
2037
-		$this->pagedSearchedSuccessful = null;
2038
-		return $result;
2039
-	}
2040
-
2041
-	/**
2042
-	 * Prepares a paged search, if possible
2043
-	 *
2044
-	 * @param string $filter the LDAP filter for the search
2045
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2046
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
2047
-	 * @param int $limit
2048
-	 * @param int $offset
2049
-	 * @return bool|true
2050
-	 * @throws ServerNotAvailableException
2051
-	 */
2052
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2053
-		$pagedSearchOK = false;
2054
-		if ($limit !== 0) {
2055
-			$offset = (int)$offset; //can be null
2056
-			\OCP\Util::writeLog('user_ldap',
2057
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2058
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2059
-				ILogger::DEBUG);
2060
-			//get the cookie from the search for the previous search, required by LDAP
2061
-			foreach($bases as $base) {
2062
-
2063
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2064
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2065
-					// no cookie known from a potential previous search. We need
2066
-					// to start from 0 to come to the desired page. cookie value
2067
-					// of '0' is valid, because 389ds
2068
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2069
-					$this->search($filter, [$base], $attr, $limit, $reOffset, true);
2070
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2071
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2072
-					// '0' is valid, because 389ds
2073
-					//TODO: remember this, probably does not change in the next request...
2074
-					if(empty($cookie) && $cookie !== '0') {
2075
-						$cookie = null;
2076
-					}
2077
-				}
2078
-				if(!is_null($cookie)) {
2079
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2080
-					$this->abandonPagedSearch();
2081
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2082
-						$this->connection->getConnectionResource(), $limit,
2083
-						false, $cookie);
2084
-					if(!$pagedSearchOK) {
2085
-						return false;
2086
-					}
2087
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
2088
-				} else {
2089
-					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
2090
-					\OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
2091
-				}
2092
-
2093
-			}
2094
-		/* ++ Fixing RHDS searches with pages with zero results ++
1850
+            \OC::$server->getLogger()->info(
1851
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1852
+                '({uuid}) probably does not match UUID configuration.',
1853
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1854
+            );
1855
+            return $guid;
1856
+        }
1857
+        for($i=0; $i < 3; $i++) {
1858
+            $pairs = str_split($blocks[$i], 2);
1859
+            $pairs = array_reverse($pairs);
1860
+            $blocks[$i] = implode('', $pairs);
1861
+        }
1862
+        for($i=0; $i < 5; $i++) {
1863
+            $pairs = str_split($blocks[$i], 2);
1864
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1865
+        }
1866
+        return implode('', $blocks);
1867
+    }
1868
+
1869
+    /**
1870
+     * gets a SID of the domain of the given dn
1871
+     *
1872
+     * @param string $dn
1873
+     * @return string|bool
1874
+     * @throws ServerNotAvailableException
1875
+     */
1876
+    public function getSID($dn) {
1877
+        $domainDN = $this->getDomainDNFromDN($dn);
1878
+        $cacheKey = 'getSID-'.$domainDN;
1879
+        $sid = $this->connection->getFromCache($cacheKey);
1880
+        if(!is_null($sid)) {
1881
+            return $sid;
1882
+        }
1883
+
1884
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1885
+        if(!is_array($objectSid) || empty($objectSid)) {
1886
+            $this->connection->writeToCache($cacheKey, false);
1887
+            return false;
1888
+        }
1889
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1890
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1891
+
1892
+        return $domainObjectSid;
1893
+    }
1894
+
1895
+    /**
1896
+     * converts a binary SID into a string representation
1897
+     * @param string $sid
1898
+     * @return string
1899
+     */
1900
+    public function convertSID2Str($sid) {
1901
+        // The format of a SID binary string is as follows:
1902
+        // 1 byte for the revision level
1903
+        // 1 byte for the number n of variable sub-ids
1904
+        // 6 bytes for identifier authority value
1905
+        // n*4 bytes for n sub-ids
1906
+        //
1907
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1908
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1909
+        $revision = ord($sid[0]);
1910
+        $numberSubID = ord($sid[1]);
1911
+
1912
+        $subIdStart = 8; // 1 + 1 + 6
1913
+        $subIdLength = 4;
1914
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1915
+            // Incorrect number of bytes present.
1916
+            return '';
1917
+        }
1918
+
1919
+        // 6 bytes = 48 bits can be represented using floats without loss of
1920
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1921
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1922
+
1923
+        $subIDs = [];
1924
+        for ($i = 0; $i < $numberSubID; $i++) {
1925
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1926
+            $subIDs[] = sprintf('%u', $subID[1]);
1927
+        }
1928
+
1929
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1930
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1931
+    }
1932
+
1933
+    /**
1934
+     * checks if the given DN is part of the given base DN(s)
1935
+     * @param string $dn the DN
1936
+     * @param string[] $bases array containing the allowed base DN or DNs
1937
+     * @return bool
1938
+     */
1939
+    public function isDNPartOfBase($dn, $bases) {
1940
+        $belongsToBase = false;
1941
+        $bases = $this->helper->sanitizeDN($bases);
1942
+
1943
+        foreach($bases as $base) {
1944
+            $belongsToBase = true;
1945
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1946
+                $belongsToBase = false;
1947
+            }
1948
+            if($belongsToBase) {
1949
+                break;
1950
+            }
1951
+        }
1952
+        return $belongsToBase;
1953
+    }
1954
+
1955
+    /**
1956
+     * resets a running Paged Search operation
1957
+     *
1958
+     * @throws ServerNotAvailableException
1959
+     */
1960
+    private function abandonPagedSearch() {
1961
+        $cr = $this->connection->getConnectionResource();
1962
+        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1963
+        $this->getPagedSearchResultState();
1964
+        $this->lastCookie = '';
1965
+        $this->cookies = [];
1966
+    }
1967
+
1968
+    /**
1969
+     * get a cookie for the next LDAP paged search
1970
+     * @param string $base a string with the base DN for the search
1971
+     * @param string $filter the search filter to identify the correct search
1972
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1973
+     * @param int $offset the offset for the new search to identify the correct search really good
1974
+     * @return string containing the key or empty if none is cached
1975
+     */
1976
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1977
+        if($offset === 0) {
1978
+            return '';
1979
+        }
1980
+        $offset -= $limit;
1981
+        //we work with cache here
1982
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1983
+        $cookie = '';
1984
+        if(isset($this->cookies[$cacheKey])) {
1985
+            $cookie = $this->cookies[$cacheKey];
1986
+            if(is_null($cookie)) {
1987
+                $cookie = '';
1988
+            }
1989
+        }
1990
+        return $cookie;
1991
+    }
1992
+
1993
+    /**
1994
+     * checks whether an LDAP paged search operation has more pages that can be
1995
+     * retrieved, typically when offset and limit are provided.
1996
+     *
1997
+     * Be very careful to use it: the last cookie value, which is inspected, can
1998
+     * be reset by other operations. Best, call it immediately after a search(),
1999
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
2000
+     * well. Don't rely on it with any fetchList-method.
2001
+     * @return bool
2002
+     */
2003
+    public function hasMoreResults() {
2004
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2005
+            // as in RFC 2696, when all results are returned, the cookie will
2006
+            // be empty.
2007
+            return false;
2008
+        }
2009
+
2010
+        return true;
2011
+    }
2012
+
2013
+    /**
2014
+     * set a cookie for LDAP paged search run
2015
+     * @param string $base a string with the base DN for the search
2016
+     * @param string $filter the search filter to identify the correct search
2017
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
2018
+     * @param int $offset the offset for the run search to identify the correct search really good
2019
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
2020
+     * @return void
2021
+     */
2022
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2023
+        // allow '0' for 389ds
2024
+        if(!empty($cookie) || $cookie === '0') {
2025
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2026
+            $this->cookies[$cacheKey] = $cookie;
2027
+            $this->lastCookie = $cookie;
2028
+        }
2029
+    }
2030
+
2031
+    /**
2032
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2033
+     * @return boolean|null true on success, null or false otherwise
2034
+     */
2035
+    public function getPagedSearchResultState() {
2036
+        $result = $this->pagedSearchedSuccessful;
2037
+        $this->pagedSearchedSuccessful = null;
2038
+        return $result;
2039
+    }
2040
+
2041
+    /**
2042
+     * Prepares a paged search, if possible
2043
+     *
2044
+     * @param string $filter the LDAP filter for the search
2045
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2046
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
2047
+     * @param int $limit
2048
+     * @param int $offset
2049
+     * @return bool|true
2050
+     * @throws ServerNotAvailableException
2051
+     */
2052
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2053
+        $pagedSearchOK = false;
2054
+        if ($limit !== 0) {
2055
+            $offset = (int)$offset; //can be null
2056
+            \OCP\Util::writeLog('user_ldap',
2057
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2058
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2059
+                ILogger::DEBUG);
2060
+            //get the cookie from the search for the previous search, required by LDAP
2061
+            foreach($bases as $base) {
2062
+
2063
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2064
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2065
+                    // no cookie known from a potential previous search. We need
2066
+                    // to start from 0 to come to the desired page. cookie value
2067
+                    // of '0' is valid, because 389ds
2068
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2069
+                    $this->search($filter, [$base], $attr, $limit, $reOffset, true);
2070
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2071
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2072
+                    // '0' is valid, because 389ds
2073
+                    //TODO: remember this, probably does not change in the next request...
2074
+                    if(empty($cookie) && $cookie !== '0') {
2075
+                        $cookie = null;
2076
+                    }
2077
+                }
2078
+                if(!is_null($cookie)) {
2079
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2080
+                    $this->abandonPagedSearch();
2081
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2082
+                        $this->connection->getConnectionResource(), $limit,
2083
+                        false, $cookie);
2084
+                    if(!$pagedSearchOK) {
2085
+                        return false;
2086
+                    }
2087
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
2088
+                } else {
2089
+                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
2090
+                    \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
2091
+                }
2092
+
2093
+            }
2094
+        /* ++ Fixing RHDS searches with pages with zero results ++
2095 2095
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
2096 2096
 		 * due to pages with zero results.
2097 2097
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
2098 2098
 		 * if we don't have a previous paged search.
2099 2099
 		 */
2100
-		} else if ($limit === 0 && !empty($this->lastCookie)) {
2101
-			// a search without limit was requested. However, if we do use
2102
-			// Paged Search once, we always must do it. This requires us to
2103
-			// initialize it with the configured page size.
2104
-			$this->abandonPagedSearch();
2105
-			// in case someone set it to 0 … use 500, otherwise no results will
2106
-			// be returned.
2107
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2108
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2109
-				$this->connection->getConnectionResource(),
2110
-				$pageSize, false, '');
2111
-		}
2112
-
2113
-		return $pagedSearchOK;
2114
-	}
2115
-
2116
-	/**
2117
-	 * Is more than one $attr used for search?
2118
-	 *
2119
-	 * @param string|string[]|null $attr
2120
-	 * @return bool
2121
-	 */
2122
-	private function manyAttributes($attr): bool {
2123
-		if (\is_array($attr)) {
2124
-			return \count($attr) > 1;
2125
-		}
2126
-		return false;
2127
-	}
2100
+        } else if ($limit === 0 && !empty($this->lastCookie)) {
2101
+            // a search without limit was requested. However, if we do use
2102
+            // Paged Search once, we always must do it. This requires us to
2103
+            // initialize it with the configured page size.
2104
+            $this->abandonPagedSearch();
2105
+            // in case someone set it to 0 … use 500, otherwise no results will
2106
+            // be returned.
2107
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2108
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2109
+                $this->connection->getConnectionResource(),
2110
+                $pageSize, false, '');
2111
+        }
2112
+
2113
+        return $pagedSearchOK;
2114
+    }
2115
+
2116
+    /**
2117
+     * Is more than one $attr used for search?
2118
+     *
2119
+     * @param string|string[]|null $attr
2120
+     * @return bool
2121
+     */
2122
+    private function manyAttributes($attr): bool {
2123
+        if (\is_array($attr)) {
2124
+            return \count($attr) > 1;
2125
+        }
2126
+        return false;
2127
+    }
2128 2128
 
2129 2129
 }
Please login to merge, or discard this patch.
Spacing   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -134,7 +134,7 @@  discard block
 block discarded – undo
134 134
 	 * @return AbstractMapping
135 135
 	 */
136 136
 	public function getUserMapper() {
137
-		if(is_null($this->userMapper)) {
137
+		if (is_null($this->userMapper)) {
138 138
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
139 139
 		}
140 140
 		return $this->userMapper;
@@ -154,7 +154,7 @@  discard block
 block discarded – undo
154 154
 	 * @return AbstractMapping
155 155
 	 */
156 156
 	public function getGroupMapper() {
157
-		if(is_null($this->groupMapper)) {
157
+		if (is_null($this->groupMapper)) {
158 158
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
159 159
 		}
160 160
 		return $this->groupMapper;
@@ -187,14 +187,14 @@  discard block
 block discarded – undo
187 187
 	 * @throws ServerNotAvailableException
188 188
 	 */
189 189
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
190
-		if(!$this->checkConnection()) {
190
+		if (!$this->checkConnection()) {
191 191
 			\OCP\Util::writeLog('user_ldap',
192 192
 				'No LDAP Connector assigned, access impossible for readAttribute.',
193 193
 				ILogger::WARN);
194 194
 			return false;
195 195
 		}
196 196
 		$cr = $this->connection->getConnectionResource();
197
-		if(!$this->ldap->isResource($cr)) {
197
+		if (!$this->ldap->isResource($cr)) {
198 198
 			//LDAP not available
199 199
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
200 200
 			return false;
@@ -204,7 +204,7 @@  discard block
 block discarded – undo
204 204
 		$this->abandonPagedSearch();
205 205
 		// openLDAP requires that we init a new Paged Search. Not needed by AD,
206 206
 		// but does not hurt either.
207
-		$pagingSize = (int)$this->connection->ldapPagingSize;
207
+		$pagingSize = (int) $this->connection->ldapPagingSize;
208 208
 		// 0 won't result in replies, small numbers may leave out groups
209 209
 		// (cf. #12306), 500 is default for paging and should work everywhere.
210 210
 		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
@@ -217,7 +217,7 @@  discard block
 block discarded – undo
217 217
 		$isRangeRequest = false;
218 218
 		do {
219 219
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
220
-			if(is_bool($result)) {
220
+			if (is_bool($result)) {
221 221
 				// when an exists request was run and it was successful, an empty
222 222
 				// array must be returned
223 223
 				return $result ? [] : false;
@@ -234,22 +234,22 @@  discard block
 block discarded – undo
234 234
 			$result = $this->extractRangeData($result, $attr);
235 235
 			if (!empty($result)) {
236 236
 				$normalizedResult = $this->extractAttributeValuesFromResult(
237
-					[ $attr => $result['values'] ],
237
+					[$attr => $result['values']],
238 238
 					$attr
239 239
 				);
240 240
 				$values = array_merge($values, $normalizedResult);
241 241
 
242
-				if($result['rangeHigh'] === '*') {
242
+				if ($result['rangeHigh'] === '*') {
243 243
 					// when server replies with * as high range value, there are
244 244
 					// no more results left
245 245
 					return $values;
246 246
 				} else {
247
-					$low  = $result['rangeHigh'] + 1;
248
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
247
+					$low = $result['rangeHigh'] + 1;
248
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
249 249
 					$isRangeRequest = true;
250 250
 				}
251 251
 			}
252
-		} while($isRangeRequest);
252
+		} while ($isRangeRequest);
253 253
 
254 254
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
255 255
 		return false;
@@ -275,13 +275,13 @@  discard block
 block discarded – undo
275 275
 		if (!$this->ldap->isResource($rr)) {
276 276
 			if ($attribute !== '') {
277 277
 				//do not throw this message on userExists check, irritates
278
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
278
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, ILogger::DEBUG);
279 279
 			}
280 280
 			//in case an error occurs , e.g. object does not exist
281 281
 			return false;
282 282
 		}
283 283
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
284
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
284
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', ILogger::DEBUG);
285 285
 			return true;
286 286
 		}
287 287
 		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
@@ -306,12 +306,12 @@  discard block
 block discarded – undo
306 306
 	 */
307 307
 	public function extractAttributeValuesFromResult($result, $attribute) {
308 308
 		$values = [];
309
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
309
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
310 310
 			$lowercaseAttribute = strtolower($attribute);
311
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
312
-				if($this->resemblesDN($attribute)) {
311
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
312
+				if ($this->resemblesDN($attribute)) {
313 313
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
314
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
314
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
315 315
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
316 316
 				} else {
317 317
 					$values[] = $result[$attribute][$i];
@@ -333,10 +333,10 @@  discard block
 block discarded – undo
333 333
 	 */
334 334
 	public function extractRangeData($result, $attribute) {
335 335
 		$keys = array_keys($result);
336
-		foreach($keys as $key) {
337
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
336
+		foreach ($keys as $key) {
337
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
338 338
 				$queryData = explode(';', $key);
339
-				if(strpos($queryData[1], 'range=') === 0) {
339
+				if (strpos($queryData[1], 'range=') === 0) {
340 340
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
341 341
 					$data = [
342 342
 						'values' => $result[$key],
@@ -361,11 +361,11 @@  discard block
 block discarded – undo
361 361
 	 * @throws \Exception
362 362
 	 */
363 363
 	public function setPassword($userDN, $password) {
364
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
364
+		if ((int) $this->connection->turnOnPasswordChange !== 1) {
365 365
 			throw new \Exception('LDAP password changes are disabled.');
366 366
 		}
367 367
 		$cr = $this->connection->getConnectionResource();
368
-		if(!$this->ldap->isResource($cr)) {
368
+		if (!$this->ldap->isResource($cr)) {
369 369
 			//LDAP not available
370 370
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
371 371
 			return false;
@@ -374,7 +374,7 @@  discard block
 block discarded – undo
374 374
 			// try PASSWD extended operation first
375 375
 			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
376 376
 						@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
377
-		} catch(ConstraintViolationException $e) {
377
+		} catch (ConstraintViolationException $e) {
378 378
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
379 379
 		}
380 380
 	}
@@ -416,17 +416,17 @@  discard block
 block discarded – undo
416 416
 	 */
417 417
 	public function getDomainDNFromDN($dn) {
418 418
 		$allParts = $this->ldap->explodeDN($dn, 0);
419
-		if($allParts === false) {
419
+		if ($allParts === false) {
420 420
 			//not a valid DN
421 421
 			return '';
422 422
 		}
423 423
 		$domainParts = [];
424 424
 		$dcFound = false;
425
-		foreach($allParts as $part) {
426
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
425
+		foreach ($allParts as $part) {
426
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
427 427
 				$dcFound = true;
428 428
 			}
429
-			if($dcFound) {
429
+			if ($dcFound) {
430 430
 				$domainParts[] = $part;
431 431
 			}
432 432
 		}
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 
453 453
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
454 454
 		//server setups
455
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
455
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
456 456
 			return $fdn;
457 457
 		}
458 458
 
@@ -471,7 +471,7 @@  discard block
 block discarded – undo
471 471
 		//To avoid bypassing the base DN settings under certain circumstances
472 472
 		//with the group support, check whether the provided DN matches one of
473 473
 		//the given Bases
474
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
474
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
475 475
 			return false;
476 476
 		}
477 477
 
@@ -489,11 +489,11 @@  discard block
 block discarded – undo
489 489
 	 */
490 490
 	public function groupsMatchFilter($groupDNs) {
491 491
 		$validGroupDNs = [];
492
-		foreach($groupDNs as $dn) {
492
+		foreach ($groupDNs as $dn) {
493 493
 			$cacheKey = 'groupsMatchFilter-'.$dn;
494 494
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
495
-			if(!is_null($groupMatchFilter)) {
496
-				if($groupMatchFilter) {
495
+			if (!is_null($groupMatchFilter)) {
496
+				if ($groupMatchFilter) {
497 497
 					$validGroupDNs[] = $dn;
498 498
 				}
499 499
 				continue;
@@ -501,13 +501,13 @@  discard block
 block discarded – undo
501 501
 
502 502
 			// Check the base DN first. If this is not met already, we don't
503 503
 			// need to ask the server at all.
504
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
504
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
505 505
 				$this->connection->writeToCache($cacheKey, false);
506 506
 				continue;
507 507
 			}
508 508
 
509 509
 			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
510
-			if(is_array($result)) {
510
+			if (is_array($result)) {
511 511
 				$this->connection->writeToCache($cacheKey, true);
512 512
 				$validGroupDNs[] = $dn;
513 513
 			} else {
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 		//To avoid bypassing the base DN settings under certain circumstances
531 531
 		//with the group support, check whether the provided DN matches one of
532 532
 		//the given Bases
533
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
533
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
534 534
 			return false;
535 535
 		}
536 536
 
@@ -550,7 +550,7 @@  discard block
 block discarded – undo
550 550
 	 */
551 551
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
552 552
 		$newlyMapped = false;
553
-		if($isUser) {
553
+		if ($isUser) {
554 554
 			$mapper = $this->getUserMapper();
555 555
 			$nameAttribute = $this->connection->ldapUserDisplayName;
556 556
 			$filter = $this->connection->ldapUserFilter;
@@ -562,15 +562,15 @@  discard block
 block discarded – undo
562 562
 
563 563
 		//let's try to retrieve the Nextcloud name from the mappings table
564 564
 		$ncName = $mapper->getNameByDN($fdn);
565
-		if(is_string($ncName)) {
565
+		if (is_string($ncName)) {
566 566
 			return $ncName;
567 567
 		}
568 568
 
569 569
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
570 570
 		$uuid = $this->getUUID($fdn, $isUser, $record);
571
-		if(is_string($uuid)) {
571
+		if (is_string($uuid)) {
572 572
 			$ncName = $mapper->getNameByUUID($uuid);
573
-			if(is_string($ncName)) {
573
+			if (is_string($ncName)) {
574 574
 				$mapper->setDNbyUUID($fdn, $uuid);
575 575
 				return $ncName;
576 576
 			}
@@ -580,17 +580,17 @@  discard block
 block discarded – undo
580 580
 			return false;
581 581
 		}
582 582
 
583
-		if(is_null($ldapName)) {
583
+		if (is_null($ldapName)) {
584 584
 			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
585
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
585
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
586 586
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
587 587
 				return false;
588 588
 			}
589 589
 			$ldapName = $ldapName[0];
590 590
 		}
591 591
 
592
-		if($isUser) {
593
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
592
+		if ($isUser) {
593
+			$usernameAttribute = (string) $this->connection->ldapExpertUsernameAttr;
594 594
 			if ($usernameAttribute !== '') {
595 595
 				$username = $this->readAttribute($fdn, $usernameAttribute);
596 596
 				$username = $username[0];
@@ -620,14 +620,14 @@  discard block
 block discarded – undo
620 620
 		// outside of core user management will still cache the user as non-existing.
621 621
 		$originalTTL = $this->connection->ldapCacheTTL;
622 622
 		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
623
-		if( $intName !== ''
623
+		if ($intName !== ''
624 624
 			&& (($isUser && !$this->ncUserManager->userExists($intName))
625 625
 				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
626 626
 			)
627 627
 		) {
628 628
 			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
629 629
 			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
630
-			if($newlyMapped) {
630
+			if ($newlyMapped) {
631 631
 				return $intName;
632 632
 			}
633 633
 		}
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
636 636
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
637 637
 		if (is_string($altName)) {
638
-			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
638
+			if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
639 639
 				$newlyMapped = true;
640 640
 				return $altName;
641 641
 			}
@@ -653,7 +653,7 @@  discard block
 block discarded – undo
653 653
 		string $uuid,
654 654
 		bool $isUser
655 655
 	) :bool {
656
-		if($mapper->map($fdn, $name, $uuid)) {
656
+		if ($mapper->map($fdn, $name, $uuid)) {
657 657
 			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
658 658
 				$this->cacheUserExists($name);
659 659
 				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
@@ -698,7 +698,7 @@  discard block
 block discarded – undo
698 698
 	 * @throws \Exception
699 699
 	 */
700 700
 	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
701
-		if($isUsers) {
701
+		if ($isUsers) {
702 702
 			$nameAttribute = $this->connection->ldapUserDisplayName;
703 703
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
704 704
 		} else {
@@ -706,9 +706,9 @@  discard block
 block discarded – undo
706 706
 		}
707 707
 		$nextcloudNames = [];
708 708
 
709
-		foreach($ldapObjects as $ldapObject) {
709
+		foreach ($ldapObjects as $ldapObject) {
710 710
 			$nameByLDAP = null;
711
-			if(    isset($ldapObject[$nameAttribute])
711
+			if (isset($ldapObject[$nameAttribute])
712 712
 				&& is_array($ldapObject[$nameAttribute])
713 713
 				&& isset($ldapObject[$nameAttribute][0])
714 714
 			) {
@@ -717,19 +717,19 @@  discard block
 block discarded – undo
717 717
 			}
718 718
 
719 719
 			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
720
-			if($ncName) {
720
+			if ($ncName) {
721 721
 				$nextcloudNames[] = $ncName;
722
-				if($isUsers) {
722
+				if ($isUsers) {
723 723
 					$this->updateUserState($ncName);
724 724
 					//cache the user names so it does not need to be retrieved
725 725
 					//again later (e.g. sharing dialogue).
726
-					if(is_null($nameByLDAP)) {
726
+					if (is_null($nameByLDAP)) {
727 727
 						continue;
728 728
 					}
729 729
 					$sndName = isset($ldapObject[$sndAttribute][0])
730 730
 						? $ldapObject[$sndAttribute][0] : '';
731 731
 					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
732
-				} else if($nameByLDAP !== null) {
732
+				} else if ($nameByLDAP !== null) {
733 733
 					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
734 734
 				}
735 735
 			}
@@ -745,7 +745,7 @@  discard block
 block discarded – undo
745 745
 	 */
746 746
 	public function updateUserState($ncname) {
747 747
 		$user = $this->userManager->get($ncname);
748
-		if($user instanceof OfflineUser) {
748
+		if ($user instanceof OfflineUser) {
749 749
 			$user->unmark();
750 750
 		}
751 751
 	}
@@ -785,7 +785,7 @@  discard block
 block discarded – undo
785 785
 	 */
786 786
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
787 787
 		$user = $this->userManager->get($ocName);
788
-		if($user === null) {
788
+		if ($user === null) {
789 789
 			return;
790 790
 		}
791 791
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -794,7 +794,7 @@  discard block
 block discarded – undo
794 794
 	}
795 795
 
796 796
 	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
797
-		$cacheKey = 'group_getDisplayName' . $ncName;
797
+		$cacheKey = 'group_getDisplayName'.$ncName;
798 798
 		$this->connection->writeToCache($cacheKey, $displayName);
799 799
 	}
800 800
 
@@ -810,9 +810,9 @@  discard block
 block discarded – undo
810 810
 		$attempts = 0;
811 811
 		//while loop is just a precaution. If a name is not generated within
812 812
 		//20 attempts, something else is very wrong. Avoids infinite loop.
813
-		while($attempts < 20){
814
-			$altName = $name . '_' . rand(1000,9999);
815
-			if(!$this->ncUserManager->userExists($altName)) {
813
+		while ($attempts < 20) {
814
+			$altName = $name.'_'.rand(1000, 9999);
815
+			if (!$this->ncUserManager->userExists($altName)) {
816 816
 				return $altName;
817 817
 			}
818 818
 			$attempts++;
@@ -834,25 +834,25 @@  discard block
 block discarded – undo
834 834
 	 */
835 835
 	private function _createAltInternalOwnCloudNameForGroups($name) {
836 836
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
837
-		if(!$usedNames || count($usedNames) === 0) {
837
+		if (!$usedNames || count($usedNames) === 0) {
838 838
 			$lastNo = 1; //will become name_2
839 839
 		} else {
840 840
 			natsort($usedNames);
841 841
 			$lastName = array_pop($usedNames);
842
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
842
+			$lastNo = (int) substr($lastName, strrpos($lastName, '_') + 1);
843 843
 		}
844
-		$altName = $name.'_'. (string)($lastNo+1);
844
+		$altName = $name.'_'.(string) ($lastNo + 1);
845 845
 		unset($usedNames);
846 846
 
847 847
 		$attempts = 1;
848
-		while($attempts < 21){
848
+		while ($attempts < 21) {
849 849
 			// Check to be really sure it is unique
850 850
 			// while loop is just a precaution. If a name is not generated within
851 851
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
852
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
852
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
853 853
 				return $altName;
854 854
 			}
855
-			$altName = $name . '_' . ($lastNo + $attempts);
855
+			$altName = $name.'_'.($lastNo + $attempts);
856 856
 			$attempts++;
857 857
 		}
858 858
 		return false;
@@ -867,7 +867,7 @@  discard block
 block discarded – undo
867 867
 	private function createAltInternalOwnCloudName($name, $isUser) {
868 868
 		$originalTTL = $this->connection->ldapCacheTTL;
869 869
 		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
870
-		if($isUser) {
870
+		if ($isUser) {
871 871
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
872 872
 		} else {
873 873
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -916,13 +916,13 @@  discard block
 block discarded – undo
916 916
 	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
917 917
 		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
918 918
 		$recordsToUpdate = $ldapRecords;
919
-		if(!$forceApplyAttributes) {
919
+		if (!$forceApplyAttributes) {
920 920
 			$isBackgroundJobModeAjax = $this->config
921 921
 					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
922
-			$recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) {
922
+			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
923 923
 				$newlyMapped = false;
924 924
 				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
925
-				if(is_string($uid)) {
925
+				if (is_string($uid)) {
926 926
 					$this->cacheUserExists($uid);
927 927
 				}
928 928
 				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
@@ -942,13 +942,13 @@  discard block
 block discarded – undo
942 942
 	 */
943 943
 	public function batchApplyUserAttributes(array $ldapRecords) {
944 944
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
945
-		foreach($ldapRecords as $userRecord) {
946
-			if(!isset($userRecord[$displayNameAttribute])) {
945
+		foreach ($ldapRecords as $userRecord) {
946
+			if (!isset($userRecord[$displayNameAttribute])) {
947 947
 				// displayName is obligatory
948 948
 				continue;
949 949
 			}
950
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
951
-			if($ocName === false) {
950
+			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
951
+			if ($ocName === false) {
952 952
 				continue;
953 953
 			}
954 954
 			$this->updateUserState($ocName);
@@ -973,10 +973,10 @@  discard block
 block discarded – undo
973 973
 	 */
974 974
 	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
975 975
 		$groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
976
-		array_walk($groupRecords, function ($record) {
976
+		array_walk($groupRecords, function($record) {
977 977
 			$newlyMapped = false;
978 978
 			$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
979
-			if(!$newlyMapped && is_string($gid)) {
979
+			if (!$newlyMapped && is_string($gid)) {
980 980
 				$this->cacheGroupExists($gid);
981 981
 			}
982 982
 		});
@@ -989,11 +989,11 @@  discard block
 block discarded – undo
989 989
 	 * @return array
990 990
 	 */
991 991
 	private function fetchList($list, $manyAttributes) {
992
-		if(is_array($list)) {
993
-			if($manyAttributes) {
992
+		if (is_array($list)) {
993
+			if ($manyAttributes) {
994 994
 				return $list;
995 995
 			} else {
996
-				$list = array_reduce($list, function ($carry, $item) {
996
+				$list = array_reduce($list, function($carry, $item) {
997 997
 					$attribute = array_keys($item)[0];
998 998
 					$carry[] = $item[$attribute][0];
999 999
 					return $carry;
@@ -1020,7 +1020,7 @@  discard block
 block discarded – undo
1020 1020
 	 */
1021 1021
 	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1022 1022
 		$result = [];
1023
-		foreach($this->connection->ldapBaseUsers as $base) {
1023
+		foreach ($this->connection->ldapBaseUsers as $base) {
1024 1024
 			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1025 1025
 		}
1026 1026
 		return $result;
@@ -1036,9 +1036,9 @@  discard block
 block discarded – undo
1036 1036
 	 */
1037 1037
 	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1038 1038
 		$result = false;
1039
-		foreach($this->connection->ldapBaseUsers as $base) {
1039
+		foreach ($this->connection->ldapBaseUsers as $base) {
1040 1040
 			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1041
-			$result = is_int($count) ? (int)$result + $count : $result;
1041
+			$result = is_int($count) ? (int) $result + $count : $result;
1042 1042
 		}
1043 1043
 		return $result;
1044 1044
 	}
@@ -1057,7 +1057,7 @@  discard block
 block discarded – undo
1057 1057
 	 */
1058 1058
 	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1059 1059
 		$result = [];
1060
-		foreach($this->connection->ldapBaseGroups as $base) {
1060
+		foreach ($this->connection->ldapBaseGroups as $base) {
1061 1061
 			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1062 1062
 		}
1063 1063
 		return $result;
@@ -1075,9 +1075,9 @@  discard block
 block discarded – undo
1075 1075
 	 */
1076 1076
 	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1077 1077
 		$result = false;
1078
-		foreach($this->connection->ldapBaseGroups as $base) {
1078
+		foreach ($this->connection->ldapBaseGroups as $base) {
1079 1079
 			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1080
-			$result = is_int($count) ? (int)$result + $count : $result;
1080
+			$result = is_int($count) ? (int) $result + $count : $result;
1081 1081
 		}
1082 1082
 		return $result;
1083 1083
 	}
@@ -1092,9 +1092,9 @@  discard block
 block discarded – undo
1092 1092
 	 */
1093 1093
 	public function countObjects($limit = null, $offset = null) {
1094 1094
 		$result = false;
1095
-		foreach($this->connection->ldapBase as $base) {
1095
+		foreach ($this->connection->ldapBase as $base) {
1096 1096
 			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1097
-			$result = is_int($count) ? (int)$result + $count : $result;
1097
+			$result = is_int($count) ? (int) $result + $count : $result;
1098 1098
 		}
1099 1099
 		return $result;
1100 1100
 	}
@@ -1119,7 +1119,7 @@  discard block
 block discarded – undo
1119 1119
 		// php no longer supports call-time pass-by-reference
1120 1120
 		// thus cannot support controlPagedResultResponse as the third argument
1121 1121
 		// is a reference
1122
-		$doMethod = function () use ($command, &$arguments) {
1122
+		$doMethod = function() use ($command, &$arguments) {
1123 1123
 			if ($command == 'controlPagedResultResponse') {
1124 1124
 				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1125 1125
 			} else {
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
 			$this->connection->resetConnectionResource();
1138 1138
 			$cr = $this->connection->getConnectionResource();
1139 1139
 
1140
-			if(!$this->ldap->isResource($cr)) {
1140
+			if (!$this->ldap->isResource($cr)) {
1141 1141
 				// Seems like we didn't find any resource.
1142 1142
 				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1143 1143
 				throw $e;
@@ -1162,13 +1162,13 @@  discard block
 block discarded – undo
1162 1162
 	 * @throws ServerNotAvailableException
1163 1163
 	 */
1164 1164
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1165
-		if(!is_null($attr) && !is_array($attr)) {
1165
+		if (!is_null($attr) && !is_array($attr)) {
1166 1166
 			$attr = [mb_strtolower($attr, 'UTF-8')];
1167 1167
 		}
1168 1168
 
1169 1169
 		// See if we have a resource, in case not cancel with message
1170 1170
 		$cr = $this->connection->getConnectionResource();
1171
-		if(!$this->ldap->isResource($cr)) {
1171
+		if (!$this->ldap->isResource($cr)) {
1172 1172
 			// Seems like we didn't find any resource.
1173 1173
 			// Return an empty array just like before.
1174 1174
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
@@ -1176,13 +1176,13 @@  discard block
 block discarded – undo
1176 1176
 		}
1177 1177
 
1178 1178
 		//check whether paged search should be attempted
1179
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1179
+		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int) $limit, $offset);
1180 1180
 
1181 1181
 		$linkResources = array_pad([], count($base), $cr);
1182 1182
 		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1183 1183
 		// cannot use $cr anymore, might have changed in the previous call!
1184 1184
 		$error = $this->ldap->errno($this->connection->getConnectionResource());
1185
-		if(!is_array($sr) || $error !== 0) {
1185
+		if (!is_array($sr) || $error !== 0) {
1186 1186
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1187 1187
 			return false;
1188 1188
 		}
@@ -1207,29 +1207,29 @@  discard block
 block discarded – undo
1207 1207
 	 */
1208 1208
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1209 1209
 		$cookie = null;
1210
-		if($pagedSearchOK) {
1210
+		if ($pagedSearchOK) {
1211 1211
 			$cr = $this->connection->getConnectionResource();
1212
-			foreach($sr as $key => $res) {
1213
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1212
+			foreach ($sr as $key => $res) {
1213
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1214 1214
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1215 1215
 				}
1216 1216
 			}
1217 1217
 
1218 1218
 			//browsing through prior pages to get the cookie for the new one
1219
-			if($skipHandling) {
1219
+			if ($skipHandling) {
1220 1220
 				return false;
1221 1221
 			}
1222 1222
 			// if count is bigger, then the server does not support
1223 1223
 			// paged search. Instead, he did a normal search. We set a
1224 1224
 			// flag here, so the callee knows how to deal with it.
1225
-			if($iFoundItems <= $limit) {
1225
+			if ($iFoundItems <= $limit) {
1226 1226
 				$this->pagedSearchedSuccessful = true;
1227 1227
 			}
1228 1228
 		} else {
1229
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1229
+			if (!is_null($limit) && (int) $this->connection->ldapPagingSize !== 0) {
1230 1230
 				\OC::$server->getLogger()->debug(
1231 1231
 					'Paged search was not available',
1232
-					[ 'app' => 'user_ldap' ]
1232
+					['app' => 'user_ldap']
1233 1233
 				);
1234 1234
 			}
1235 1235
 		}
@@ -1258,8 +1258,8 @@  discard block
 block discarded – undo
1258 1258
 	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1259 1259
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1260 1260
 
1261
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1262
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1261
+		$limitPerPage = (int) $this->connection->ldapPagingSize;
1262
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1263 1263
 			$limitPerPage = $limit;
1264 1264
 		}
1265 1265
 
@@ -1269,7 +1269,7 @@  discard block
 block discarded – undo
1269 1269
 
1270 1270
 		do {
1271 1271
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1272
-			if($search === false) {
1272
+			if ($search === false) {
1273 1273
 				return $counter > 0 ? $counter : false;
1274 1274
 			}
1275 1275
 			list($sr, $pagedSearchOK) = $search;
@@ -1288,7 +1288,7 @@  discard block
 block discarded – undo
1288 1288
 			 * Continue now depends on $hasMorePages value
1289 1289
 			 */
1290 1290
 			$continue = $pagedSearchOK && $hasMorePages;
1291
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1291
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1292 1292
 
1293 1293
 		return $counter;
1294 1294
 	}
@@ -1301,8 +1301,8 @@  discard block
 block discarded – undo
1301 1301
 	private function countEntriesInSearchResults($searchResults) {
1302 1302
 		$counter = 0;
1303 1303
 
1304
-		foreach($searchResults as $res) {
1305
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1304
+		foreach ($searchResults as $res) {
1305
+			$count = (int) $this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1306 1306
 			$counter += $count;
1307 1307
 		}
1308 1308
 
@@ -1322,8 +1322,8 @@  discard block
 block discarded – undo
1322 1322
 	 * @throws ServerNotAvailableException
1323 1323
 	 */
1324 1324
 	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1325
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1326
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1325
+		$limitPerPage = (int) $this->connection->ldapPagingSize;
1326
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1327 1327
 			$limitPerPage = $limit;
1328 1328
 		}
1329 1329
 
@@ -1337,13 +1337,13 @@  discard block
 block discarded – undo
1337 1337
 		$savedoffset = $offset;
1338 1338
 		do {
1339 1339
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1340
-			if($search === false) {
1340
+			if ($search === false) {
1341 1341
 				return [];
1342 1342
 			}
1343 1343
 			list($sr, $pagedSearchOK) = $search;
1344 1344
 			$cr = $this->connection->getConnectionResource();
1345 1345
 
1346
-			if($skipHandling) {
1346
+			if ($skipHandling) {
1347 1347
 				//i.e. result do not need to be fetched, we just need the cookie
1348 1348
 				//thus pass 1 or any other value as $iFoundItems because it is not
1349 1349
 				//used
@@ -1354,7 +1354,7 @@  discard block
 block discarded – undo
1354 1354
 			}
1355 1355
 
1356 1356
 			$iFoundItems = 0;
1357
-			foreach($sr as $res) {
1357
+			foreach ($sr as $res) {
1358 1358
 				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1359 1359
 				$iFoundItems = max($iFoundItems, $findings['count']);
1360 1360
 				unset($findings['count']);
@@ -1370,27 +1370,27 @@  discard block
 block discarded – undo
1370 1370
 
1371 1371
 		// if we're here, probably no connection resource is returned.
1372 1372
 		// to make Nextcloud behave nicely, we simply give back an empty array.
1373
-		if(is_null($findings)) {
1373
+		if (is_null($findings)) {
1374 1374
 			return [];
1375 1375
 		}
1376 1376
 
1377
-		if(!is_null($attr)) {
1377
+		if (!is_null($attr)) {
1378 1378
 			$selection = [];
1379 1379
 			$i = 0;
1380
-			foreach($findings as $item) {
1381
-				if(!is_array($item)) {
1380
+			foreach ($findings as $item) {
1381
+				if (!is_array($item)) {
1382 1382
 					continue;
1383 1383
 				}
1384 1384
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1385
-				foreach($attr as $key) {
1386
-					if(isset($item[$key])) {
1387
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1385
+				foreach ($attr as $key) {
1386
+					if (isset($item[$key])) {
1387
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1388 1388
 							unset($item[$key]['count']);
1389 1389
 						}
1390
-						if($key !== 'dn') {
1391
-							if($this->resemblesDN($key)) {
1390
+						if ($key !== 'dn') {
1391
+							if ($this->resemblesDN($key)) {
1392 1392
 								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1393
-							} else if($key === 'objectguid' || $key === 'guid') {
1393
+							} else if ($key === 'objectguid' || $key === 'guid') {
1394 1394
 								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1395 1395
 							} else {
1396 1396
 								$selection[$i][$key] = $item[$key];
@@ -1408,14 +1408,14 @@  discard block
 block discarded – undo
1408 1408
 		//we slice the findings, when
1409 1409
 		//a) paged search unsuccessful, though attempted
1410 1410
 		//b) no paged search, but limit set
1411
-		if((!$this->getPagedSearchResultState()
1411
+		if ((!$this->getPagedSearchResultState()
1412 1412
 			&& $pagedSearchOK)
1413 1413
 			|| (
1414 1414
 				!$pagedSearchOK
1415 1415
 				&& !is_null($limit)
1416 1416
 			)
1417 1417
 		) {
1418
-			$findings = array_slice($findings, (int)$offset, $limit);
1418
+			$findings = array_slice($findings, (int) $offset, $limit);
1419 1419
 		}
1420 1420
 		return $findings;
1421 1421
 	}
@@ -1428,13 +1428,13 @@  discard block
 block discarded – undo
1428 1428
 	public function sanitizeUsername($name) {
1429 1429
 		$name = trim($name);
1430 1430
 
1431
-		if($this->connection->ldapIgnoreNamingRules) {
1431
+		if ($this->connection->ldapIgnoreNamingRules) {
1432 1432
 			return $name;
1433 1433
 		}
1434 1434
 
1435 1435
 		// Transliteration to ASCII
1436 1436
 		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1437
-		if($transliterated !== false) {
1437
+		if ($transliterated !== false) {
1438 1438
 			// depending on system config iconv can work or not
1439 1439
 			$name = $transliterated;
1440 1440
 		}
@@ -1445,7 +1445,7 @@  discard block
 block discarded – undo
1445 1445
 		// Every remaining disallowed characters will be removed
1446 1446
 		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1447 1447
 
1448
-		if($name === '') {
1448
+		if ($name === '') {
1449 1449
 			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1450 1450
 		}
1451 1451
 
@@ -1460,13 +1460,13 @@  discard block
 block discarded – undo
1460 1460
 	 */
1461 1461
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1462 1462
 		$asterisk = '';
1463
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1463
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1464 1464
 			$asterisk = '*';
1465 1465
 			$input = mb_substr($input, 1, null, 'UTF-8');
1466 1466
 		}
1467 1467
 		$search  = ['*', '\\', '(', ')'];
1468 1468
 		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1469
-		return $asterisk . str_replace($search, $replace, $input);
1469
+		return $asterisk.str_replace($search, $replace, $input);
1470 1470
 	}
1471 1471
 
1472 1472
 	/**
@@ -1496,13 +1496,13 @@  discard block
 block discarded – undo
1496 1496
 	 */
1497 1497
 	private function combineFilter($filters, $operator) {
1498 1498
 		$combinedFilter = '('.$operator;
1499
-		foreach($filters as $filter) {
1499
+		foreach ($filters as $filter) {
1500 1500
 			if ($filter !== '' && $filter[0] !== '(') {
1501 1501
 				$filter = '('.$filter.')';
1502 1502
 			}
1503
-			$combinedFilter.=$filter;
1503
+			$combinedFilter .= $filter;
1504 1504
 		}
1505
-		$combinedFilter.=')';
1505
+		$combinedFilter .= ')';
1506 1506
 		return $combinedFilter;
1507 1507
 	}
1508 1508
 
@@ -1538,17 +1538,17 @@  discard block
 block discarded – undo
1538 1538
 	 * @throws \Exception
1539 1539
 	 */
1540 1540
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1541
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1541
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1542 1542
 			throw new \Exception('searchAttributes must be an array with at least two string');
1543 1543
 		}
1544 1544
 		$searchWords = explode(' ', trim($search));
1545 1545
 		$wordFilters = [];
1546
-		foreach($searchWords as $word) {
1546
+		foreach ($searchWords as $word) {
1547 1547
 			$word = $this->prepareSearchTerm($word);
1548 1548
 			//every word needs to appear at least once
1549 1549
 			$wordMatchOneAttrFilters = [];
1550
-			foreach($searchAttributes as $attr) {
1551
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1550
+			foreach ($searchAttributes as $attr) {
1551
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1552 1552
 			}
1553 1553
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1554 1554
 		}
@@ -1566,10 +1566,10 @@  discard block
 block discarded – undo
1566 1566
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1567 1567
 		$filter = [];
1568 1568
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1569
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1569
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1570 1570
 			try {
1571 1571
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1572
-			} catch(\Exception $e) {
1572
+			} catch (\Exception $e) {
1573 1573
 				\OCP\Util::writeLog(
1574 1574
 					'user_ldap',
1575 1575
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1579,17 +1579,17 @@  discard block
 block discarded – undo
1579 1579
 		}
1580 1580
 
1581 1581
 		$search = $this->prepareSearchTerm($search);
1582
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1582
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1583 1583
 			if ($fallbackAttribute === '') {
1584 1584
 				return '';
1585 1585
 			}
1586
-			$filter[] = $fallbackAttribute . '=' . $search;
1586
+			$filter[] = $fallbackAttribute.'='.$search;
1587 1587
 		} else {
1588
-			foreach($searchAttributes as $attribute) {
1589
-				$filter[] = $attribute . '=' . $search;
1588
+			foreach ($searchAttributes as $attribute) {
1589
+				$filter[] = $attribute.'='.$search;
1590 1590
 			}
1591 1591
 		}
1592
-		if(count($filter) === 1) {
1592
+		if (count($filter) === 1) {
1593 1593
 			return '('.$filter[0].')';
1594 1594
 		}
1595 1595
 		return $this->combineFilterWithOr($filter);
@@ -1610,7 +1610,7 @@  discard block
 block discarded – undo
1610 1610
 		if ($term === '') {
1611 1611
 			$result = '*';
1612 1612
 		} else if ($allowEnum !== 'no') {
1613
-			$result = $term . '*';
1613
+			$result = $term.'*';
1614 1614
 		}
1615 1615
 		return $result;
1616 1616
 	}
@@ -1622,7 +1622,7 @@  discard block
 block discarded – undo
1622 1622
 	public function getFilterForUserCount() {
1623 1623
 		$filter = $this->combineFilterWithAnd([
1624 1624
 			$this->connection->ldapUserFilter,
1625
-			$this->connection->ldapUserDisplayName . '=*'
1625
+			$this->connection->ldapUserDisplayName.'=*'
1626 1626
 		]);
1627 1627
 
1628 1628
 		return $filter;
@@ -1640,7 +1640,7 @@  discard block
 block discarded – undo
1640 1640
 			'ldapAgentName' => $name,
1641 1641
 			'ldapAgentPassword' => $password
1642 1642
 		];
1643
-		if(!$testConnection->setConfiguration($credentials)) {
1643
+		if (!$testConnection->setConfiguration($credentials)) {
1644 1644
 			return false;
1645 1645
 		}
1646 1646
 		return $testConnection->bind();
@@ -1662,30 +1662,30 @@  discard block
 block discarded – undo
1662 1662
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1663 1663
 			// existing DN to be able to reliably detect it.
1664 1664
 			$result = $this->search($filter, $base, ['dn'], 1);
1665
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1665
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1666 1666
 				throw new \Exception('Cannot determine UUID attribute');
1667 1667
 			}
1668 1668
 			$dn = $result[0]['dn'][0];
1669
-			if(!$this->detectUuidAttribute($dn, true)) {
1669
+			if (!$this->detectUuidAttribute($dn, true)) {
1670 1670
 				throw new \Exception('Cannot determine UUID attribute');
1671 1671
 			}
1672 1672
 		} else {
1673 1673
 			// The UUID attribute is either known or an override is given.
1674 1674
 			// By calling this method we ensure that $this->connection->$uuidAttr
1675 1675
 			// is definitely set
1676
-			if(!$this->detectUuidAttribute('', true)) {
1676
+			if (!$this->detectUuidAttribute('', true)) {
1677 1677
 				throw new \Exception('Cannot determine UUID attribute');
1678 1678
 			}
1679 1679
 		}
1680 1680
 
1681 1681
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1682
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1682
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1683 1683
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1684 1684
 		}
1685 1685
 
1686
-		$filter = $uuidAttr . '=' . $uuid;
1686
+		$filter = $uuidAttr.'='.$uuid;
1687 1687
 		$result = $this->searchUsers($filter, ['dn'], 2);
1688
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1688
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1689 1689
 			// we put the count into account to make sure that this is
1690 1690
 			// really unique
1691 1691
 			return $result[0]['dn'][0];
@@ -1705,7 +1705,7 @@  discard block
 block discarded – undo
1705 1705
 	 * @throws ServerNotAvailableException
1706 1706
 	 */
1707 1707
 	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1708
-		if($isUser) {
1708
+		if ($isUser) {
1709 1709
 			$uuidAttr     = 'ldapUuidUserAttribute';
1710 1710
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1711 1711
 		} else {
@@ -1713,8 +1713,8 @@  discard block
 block discarded – undo
1713 1713
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1714 1714
 		}
1715 1715
 
1716
-		if(!$force) {
1717
-			if($this->connection->$uuidAttr !== 'auto') {
1716
+		if (!$force) {
1717
+			if ($this->connection->$uuidAttr !== 'auto') {
1718 1718
 				return true;
1719 1719
 			} else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1720 1720
 				$this->connection->$uuidAttr = $uuidOverride;
@@ -1722,23 +1722,23 @@  discard block
 block discarded – undo
1722 1722
 			}
1723 1723
 
1724 1724
 			$attribute = $this->connection->getFromCache($uuidAttr);
1725
-			if(!$attribute === null) {
1725
+			if (!$attribute === null) {
1726 1726
 				$this->connection->$uuidAttr = $attribute;
1727 1727
 				return true;
1728 1728
 			}
1729 1729
 		}
1730 1730
 
1731
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1732
-			if($ldapRecord !== null) {
1731
+		foreach (self::UUID_ATTRIBUTES as $attribute) {
1732
+			if ($ldapRecord !== null) {
1733 1733
 				// we have the info from LDAP already, we don't need to talk to the server again
1734
-				if(isset($ldapRecord[$attribute])) {
1734
+				if (isset($ldapRecord[$attribute])) {
1735 1735
 					$this->connection->$uuidAttr = $attribute;
1736 1736
 					return true;
1737 1737
 				}
1738 1738
 			}
1739 1739
 
1740 1740
 			$value = $this->readAttribute($dn, $attribute);
1741
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1741
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1742 1742
 				\OC::$server->getLogger()->debug(
1743 1743
 					'Setting {attribute} as {subject}',
1744 1744
 					[
@@ -1765,7 +1765,7 @@  discard block
 block discarded – undo
1765 1765
 	 * @throws ServerNotAvailableException
1766 1766
 	 */
1767 1767
 	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1768
-		if($isUser) {
1768
+		if ($isUser) {
1769 1769
 			$uuidAttr     = 'ldapUuidUserAttribute';
1770 1770
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1771 1771
 		} else {
@@ -1774,10 +1774,10 @@  discard block
 block discarded – undo
1774 1774
 		}
1775 1775
 
1776 1776
 		$uuid = false;
1777
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1777
+		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1778 1778
 			$attr = $this->connection->$uuidAttr;
1779 1779
 			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1780
-			if( !is_array($uuid)
1780
+			if (!is_array($uuid)
1781 1781
 				&& $uuidOverride !== ''
1782 1782
 				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1783 1783
 			{
@@ -1785,7 +1785,7 @@  discard block
 block discarded – undo
1785 1785
 					? $ldapRecord[$this->connection->$uuidAttr]
1786 1786
 					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1787 1787
 			}
1788
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1788
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1789 1789
 				$uuid = $uuid[0];
1790 1790
 			}
1791 1791
 		}
@@ -1802,19 +1802,19 @@  discard block
 block discarded – undo
1802 1802
 	private function convertObjectGUID2Str($oguid) {
1803 1803
 		$hex_guid = bin2hex($oguid);
1804 1804
 		$hex_guid_to_guid_str = '';
1805
-		for($k = 1; $k <= 4; ++$k) {
1805
+		for ($k = 1; $k <= 4; ++$k) {
1806 1806
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1807 1807
 		}
1808 1808
 		$hex_guid_to_guid_str .= '-';
1809
-		for($k = 1; $k <= 2; ++$k) {
1809
+		for ($k = 1; $k <= 2; ++$k) {
1810 1810
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1811 1811
 		}
1812 1812
 		$hex_guid_to_guid_str .= '-';
1813
-		for($k = 1; $k <= 2; ++$k) {
1813
+		for ($k = 1; $k <= 2; ++$k) {
1814 1814
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1815 1815
 		}
1816
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1817
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1816
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1817
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1818 1818
 
1819 1819
 		return strtoupper($hex_guid_to_guid_str);
1820 1820
 	}
@@ -1831,11 +1831,11 @@  discard block
 block discarded – undo
1831 1831
 	 * @return string
1832 1832
 	 */
1833 1833
 	public function formatGuid2ForFilterUser($guid) {
1834
-		if(!is_string($guid)) {
1834
+		if (!is_string($guid)) {
1835 1835
 			throw new \InvalidArgumentException('String expected');
1836 1836
 		}
1837 1837
 		$blocks = explode('-', $guid);
1838
-		if(count($blocks) !== 5) {
1838
+		if (count($blocks) !== 5) {
1839 1839
 			/*
1840 1840
 			 * Why not throw an Exception instead? This method is a utility
1841 1841
 			 * called only when trying to figure out whether a "missing" known
@@ -1848,20 +1848,20 @@  discard block
 block discarded – undo
1848 1848
 			 * user. Instead we write a log message.
1849 1849
 			 */
1850 1850
 			\OC::$server->getLogger()->info(
1851
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1851
+				'Passed string does not resemble a valid GUID. Known UUID '.
1852 1852
 				'({uuid}) probably does not match UUID configuration.',
1853
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1853
+				['app' => 'user_ldap', 'uuid' => $guid]
1854 1854
 			);
1855 1855
 			return $guid;
1856 1856
 		}
1857
-		for($i=0; $i < 3; $i++) {
1857
+		for ($i = 0; $i < 3; $i++) {
1858 1858
 			$pairs = str_split($blocks[$i], 2);
1859 1859
 			$pairs = array_reverse($pairs);
1860 1860
 			$blocks[$i] = implode('', $pairs);
1861 1861
 		}
1862
-		for($i=0; $i < 5; $i++) {
1862
+		for ($i = 0; $i < 5; $i++) {
1863 1863
 			$pairs = str_split($blocks[$i], 2);
1864
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1864
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1865 1865
 		}
1866 1866
 		return implode('', $blocks);
1867 1867
 	}
@@ -1877,12 +1877,12 @@  discard block
 block discarded – undo
1877 1877
 		$domainDN = $this->getDomainDNFromDN($dn);
1878 1878
 		$cacheKey = 'getSID-'.$domainDN;
1879 1879
 		$sid = $this->connection->getFromCache($cacheKey);
1880
-		if(!is_null($sid)) {
1880
+		if (!is_null($sid)) {
1881 1881
 			return $sid;
1882 1882
 		}
1883 1883
 
1884 1884
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1885
-		if(!is_array($objectSid) || empty($objectSid)) {
1885
+		if (!is_array($objectSid) || empty($objectSid)) {
1886 1886
 			$this->connection->writeToCache($cacheKey, false);
1887 1887
 			return false;
1888 1888
 		}
@@ -1940,12 +1940,12 @@  discard block
 block discarded – undo
1940 1940
 		$belongsToBase = false;
1941 1941
 		$bases = $this->helper->sanitizeDN($bases);
1942 1942
 
1943
-		foreach($bases as $base) {
1943
+		foreach ($bases as $base) {
1944 1944
 			$belongsToBase = true;
1945
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1945
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1946 1946
 				$belongsToBase = false;
1947 1947
 			}
1948
-			if($belongsToBase) {
1948
+			if ($belongsToBase) {
1949 1949
 				break;
1950 1950
 			}
1951 1951
 		}
@@ -1974,16 +1974,16 @@  discard block
 block discarded – undo
1974 1974
 	 * @return string containing the key or empty if none is cached
1975 1975
 	 */
1976 1976
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1977
-		if($offset === 0) {
1977
+		if ($offset === 0) {
1978 1978
 			return '';
1979 1979
 		}
1980 1980
 		$offset -= $limit;
1981 1981
 		//we work with cache here
1982
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1982
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset;
1983 1983
 		$cookie = '';
1984
-		if(isset($this->cookies[$cacheKey])) {
1984
+		if (isset($this->cookies[$cacheKey])) {
1985 1985
 			$cookie = $this->cookies[$cacheKey];
1986
-			if(is_null($cookie)) {
1986
+			if (is_null($cookie)) {
1987 1987
 				$cookie = '';
1988 1988
 			}
1989 1989
 		}
@@ -2001,7 +2001,7 @@  discard block
 block discarded – undo
2001 2001
 	 * @return bool
2002 2002
 	 */
2003 2003
 	public function hasMoreResults() {
2004
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2004
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
2005 2005
 			// as in RFC 2696, when all results are returned, the cookie will
2006 2006
 			// be empty.
2007 2007
 			return false;
@@ -2021,8 +2021,8 @@  discard block
 block discarded – undo
2021 2021
 	 */
2022 2022
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2023 2023
 		// allow '0' for 389ds
2024
-		if(!empty($cookie) || $cookie === '0') {
2025
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2024
+		if (!empty($cookie) || $cookie === '0') {
2025
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset;
2026 2026
 			$this->cookies[$cacheKey] = $cookie;
2027 2027
 			$this->lastCookie = $cookie;
2028 2028
 		}
@@ -2052,16 +2052,16 @@  discard block
 block discarded – undo
2052 2052
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2053 2053
 		$pagedSearchOK = false;
2054 2054
 		if ($limit !== 0) {
2055
-			$offset = (int)$offset; //can be null
2055
+			$offset = (int) $offset; //can be null
2056 2056
 			\OCP\Util::writeLog('user_ldap',
2057 2057
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2058
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2058
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
2059 2059
 				ILogger::DEBUG);
2060 2060
 			//get the cookie from the search for the previous search, required by LDAP
2061
-			foreach($bases as $base) {
2061
+			foreach ($bases as $base) {
2062 2062
 
2063 2063
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2064
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2064
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2065 2065
 					// no cookie known from a potential previous search. We need
2066 2066
 					// to start from 0 to come to the desired page. cookie value
2067 2067
 					// of '0' is valid, because 389ds
@@ -2071,17 +2071,17 @@  discard block
 block discarded – undo
2071 2071
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2072 2072
 					// '0' is valid, because 389ds
2073 2073
 					//TODO: remember this, probably does not change in the next request...
2074
-					if(empty($cookie) && $cookie !== '0') {
2074
+					if (empty($cookie) && $cookie !== '0') {
2075 2075
 						$cookie = null;
2076 2076
 					}
2077 2077
 				}
2078
-				if(!is_null($cookie)) {
2078
+				if (!is_null($cookie)) {
2079 2079
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2080 2080
 					$this->abandonPagedSearch();
2081 2081
 					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2082 2082
 						$this->connection->getConnectionResource(), $limit,
2083 2083
 						false, $cookie);
2084
-					if(!$pagedSearchOK) {
2084
+					if (!$pagedSearchOK) {
2085 2085
 						return false;
2086 2086
 					}
2087 2087
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
@@ -2104,7 +2104,7 @@  discard block
 block discarded – undo
2104 2104
 			$this->abandonPagedSearch();
2105 2105
 			// in case someone set it to 0 … use 500, otherwise no results will
2106 2106
 			// be returned.
2107
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2107
+			$pageSize = (int) $this->connection->ldapPagingSize > 0 ? (int) $this->connection->ldapPagingSize : 500;
2108 2108
 			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2109 2109
 				$this->connection->getConnectionResource(),
2110 2110
 				$pageSize, false, '');
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_LDAP.php 2 patches
Indentation   +1231 added lines, -1231 removed lines patch added patch discarded remove patch
@@ -49,1235 +49,1235 @@
 block discarded – undo
49 49
 use OCP\ILogger;
50 50
 
51 51
 class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend {
52
-	protected $enabled = false;
53
-
54
-	/**
55
-	 * @var string[] $cachedGroupMembers array of users with gid as key
56
-	 */
57
-	protected $cachedGroupMembers;
58
-
59
-	/**
60
-	 * @var string[] $cachedGroupsByMember array of groups with uid as key
61
-	 */
62
-	protected $cachedGroupsByMember;
63
-
64
-	/**
65
-	 * @var string[] $cachedNestedGroups array of groups with gid (DN) as key
66
-	 */
67
-	protected $cachedNestedGroups;
68
-
69
-	/** @var GroupPluginManager */
70
-	protected $groupPluginManager;
71
-
72
-	public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
73
-		parent::__construct($access);
74
-		$filter = $this->access->connection->ldapGroupFilter;
75
-		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
76
-		if(!empty($filter) && !empty($gassoc)) {
77
-			$this->enabled = true;
78
-		}
79
-
80
-		$this->cachedGroupMembers = new CappedMemoryCache();
81
-		$this->cachedGroupsByMember = new CappedMemoryCache();
82
-		$this->cachedNestedGroups = new CappedMemoryCache();
83
-		$this->groupPluginManager = $groupPluginManager;
84
-	}
85
-
86
-	/**
87
-	 * is user in group?
88
-	 * @param string $uid uid of the user
89
-	 * @param string $gid gid of the group
90
-	 * @return bool
91
-	 *
92
-	 * Checks whether the user is member of a group or not.
93
-	 */
94
-	public function inGroup($uid, $gid) {
95
-		if(!$this->enabled) {
96
-			return false;
97
-		}
98
-		$cacheKey = 'inGroup'.$uid.':'.$gid;
99
-		$inGroup = $this->access->connection->getFromCache($cacheKey);
100
-		if(!is_null($inGroup)) {
101
-			return (bool)$inGroup;
102
-		}
103
-
104
-		$userDN = $this->access->username2dn($uid);
105
-
106
-		if(isset($this->cachedGroupMembers[$gid])) {
107
-			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
108
-			return $isInGroup;
109
-		}
110
-
111
-		$cacheKeyMembers = 'inGroup-members:'.$gid;
112
-		$members = $this->access->connection->getFromCache($cacheKeyMembers);
113
-		if(!is_null($members)) {
114
-			$this->cachedGroupMembers[$gid] = $members;
115
-			$isInGroup = in_array($userDN, $members, true);
116
-			$this->access->connection->writeToCache($cacheKey, $isInGroup);
117
-			return $isInGroup;
118
-		}
119
-
120
-		$groupDN = $this->access->groupname2dn($gid);
121
-		// just in case
122
-		if(!$groupDN || !$userDN) {
123
-			$this->access->connection->writeToCache($cacheKey, false);
124
-			return false;
125
-		}
126
-
127
-		//check primary group first
128
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
129
-			$this->access->connection->writeToCache($cacheKey, true);
130
-			return true;
131
-		}
132
-
133
-		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
134
-		$members = $this->_groupMembers($groupDN);
135
-		if(!is_array($members) || count($members) === 0) {
136
-			$this->access->connection->writeToCache($cacheKey, false);
137
-			return false;
138
-		}
139
-
140
-		//extra work if we don't get back user DNs
141
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
142
-			$dns = [];
143
-			$filterParts = [];
144
-			$bytes = 0;
145
-			foreach($members as $mid) {
146
-				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
147
-				$filterParts[] = $filter;
148
-				$bytes += strlen($filter);
149
-				if($bytes >= 9000000) {
150
-					// AD has a default input buffer of 10 MB, we do not want
151
-					// to take even the chance to exceed it
152
-					$filter = $this->access->combineFilterWithOr($filterParts);
153
-					$bytes = 0;
154
-					$filterParts = [];
155
-					$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
156
-					$dns = array_merge($dns, $users);
157
-				}
158
-			}
159
-			if(count($filterParts) > 0) {
160
-				$filter = $this->access->combineFilterWithOr($filterParts);
161
-				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
162
-				$dns = array_merge($dns, $users);
163
-			}
164
-			$members = $dns;
165
-		}
166
-
167
-		$isInGroup = in_array($userDN, $members);
168
-		$this->access->connection->writeToCache($cacheKey, $isInGroup);
169
-		$this->access->connection->writeToCache($cacheKeyMembers, $members);
170
-		$this->cachedGroupMembers[$gid] = $members;
171
-
172
-		return $isInGroup;
173
-	}
174
-
175
-	/**
176
-	 * @param string $dnGroup
177
-	 * @return array
178
-	 *
179
-	 * For a group that has user membership defined by an LDAP search url attribute returns the users
180
-	 * that match the search url otherwise returns an empty array.
181
-	 */
182
-	public function getDynamicGroupMembers($dnGroup) {
183
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
184
-
185
-		if (empty($dynamicGroupMemberURL)) {
186
-			return [];
187
-		}
188
-
189
-		$dynamicMembers = [];
190
-		$memberURLs = $this->access->readAttribute(
191
-			$dnGroup,
192
-			$dynamicGroupMemberURL,
193
-			$this->access->connection->ldapGroupFilter
194
-		);
195
-		if ($memberURLs !== false) {
196
-			// this group has the 'memberURL' attribute so this is a dynamic group
197
-			// example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
198
-			// example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
199
-			$pos = strpos($memberURLs[0], '(');
200
-			if ($pos !== false) {
201
-				$memberUrlFilter = substr($memberURLs[0], $pos);
202
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
203
-				$dynamicMembers = [];
204
-				foreach($foundMembers as $value) {
205
-					$dynamicMembers[$value['dn'][0]] = 1;
206
-				}
207
-			} else {
208
-				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
209
-					'of group ' . $dnGroup, ILogger::DEBUG);
210
-			}
211
-		}
212
-		return $dynamicMembers;
213
-	}
214
-
215
-	/**
216
-	 * @param string $dnGroup
217
-	 * @param array|null &$seen
218
-	 * @return array|mixed|null
219
-	 * @throws \OC\ServerNotAvailableException
220
-	 */
221
-	private function _groupMembers($dnGroup, &$seen = null) {
222
-		if ($seen === null) {
223
-			$seen = [];
224
-		}
225
-		$allMembers = [];
226
-		if (array_key_exists($dnGroup, $seen)) {
227
-			// avoid loops
228
-			return [];
229
-		}
230
-		// used extensively in cron job, caching makes sense for nested groups
231
-		$cacheKey = '_groupMembers'.$dnGroup;
232
-		$groupMembers = $this->access->connection->getFromCache($cacheKey);
233
-		if($groupMembers !== null) {
234
-			return $groupMembers;
235
-		}
236
-		$seen[$dnGroup] = 1;
237
-		$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
238
-		if (is_array($members)) {
239
-			$fetcher = function ($memberDN, &$seen) {
240
-				return $this->_groupMembers($memberDN, $seen);
241
-			};
242
-			$allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
243
-		}
244
-
245
-		$allMembers += $this->getDynamicGroupMembers($dnGroup);
246
-
247
-		$this->access->connection->writeToCache($cacheKey, $allMembers);
248
-		return $allMembers;
249
-	}
250
-
251
-	/**
252
-	 * @param string $DN
253
-	 * @param array|null &$seen
254
-	 * @return array
255
-	 * @throws \OC\ServerNotAvailableException
256
-	 */
257
-	private function _getGroupDNsFromMemberOf($DN) {
258
-		$groups = $this->access->readAttribute($DN, 'memberOf');
259
-		if (!is_array($groups)) {
260
-			return [];
261
-		}
262
-
263
-		$fetcher = function ($groupDN) {
264
-			if (isset($this->cachedNestedGroups[$groupDN])) {
265
-				$nestedGroups = $this->cachedNestedGroups[$groupDN];
266
-			} else {
267
-				$nestedGroups = $this->access->readAttribute($groupDN, 'memberOf');
268
-				if (!is_array($nestedGroups)) {
269
-					$nestedGroups = [];
270
-				}
271
-				$this->cachedNestedGroups[$groupDN] = $nestedGroups;
272
-			}
273
-			return $nestedGroups;
274
-		};
275
-
276
-		$groups = $this->walkNestedGroups($DN, $fetcher, $groups);
277
-		return $this->access->groupsMatchFilter($groups);
278
-	}
279
-
280
-	/**
281
-	 * @param string $dn
282
-	 * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns
283
-	 * @param array $list
284
-	 * @return array
285
-	 */
286
-	private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array {
287
-		$nesting = (int) $this->access->connection->ldapNestedGroups;
288
-		// depending on the input, we either have a list of DNs or a list of LDAP records
289
-		// also, the output expects either DNs or records. Testing the first element should suffice.
290
-		$recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
291
-
292
-		if ($nesting !== 1) {
293
-			if($recordMode) {
294
-				// the keys are numeric, but should hold the DN
295
-				return array_reduce($list, function ($transformed, $record) use ($dn) {
296
-					if($record['dn'][0] != $dn) {
297
-						$transformed[$record['dn'][0]] = $record;
298
-					}
299
-					return $transformed;
300
-				}, []);
301
-			}
302
-			return $list;
303
-		}
304
-
305
-		$seen = [];
306
-		while ($record = array_pop($list)) {
307
-			$recordDN = $recordMode ? $record['dn'][0] : $record;
308
-			if ($recordDN === $dn || array_key_exists($recordDN, $seen)) {
309
-				// Prevent loops
310
-				continue;
311
-			}
312
-			$fetched = $fetcher($record, $seen);
313
-			$list = array_merge($list, $fetched);
314
-			$seen[$recordDN] = $record;
315
-		}
316
-
317
-		return $recordMode ? $seen : array_keys($seen);
318
-	}
319
-
320
-	/**
321
-	 * translates a gidNumber into an ownCloud internal name
322
-	 * @param string $gid as given by gidNumber on POSIX LDAP
323
-	 * @param string $dn a DN that belongs to the same domain as the group
324
-	 * @return string|bool
325
-	 */
326
-	public function gidNumber2Name($gid, $dn) {
327
-		$cacheKey = 'gidNumberToName' . $gid;
328
-		$groupName = $this->access->connection->getFromCache($cacheKey);
329
-		if(!is_null($groupName) && isset($groupName)) {
330
-			return $groupName;
331
-		}
332
-
333
-		//we need to get the DN from LDAP
334
-		$filter = $this->access->combineFilterWithAnd([
335
-			$this->access->connection->ldapGroupFilter,
336
-			'objectClass=posixGroup',
337
-			$this->access->connection->ldapGidNumber . '=' . $gid
338
-		]);
339
-		$result = $this->access->searchGroups($filter, ['dn'], 1);
340
-		if(empty($result)) {
341
-			return false;
342
-		}
343
-		$dn = $result[0]['dn'][0];
344
-
345
-		//and now the group name
346
-		//NOTE once we have separate ownCloud group IDs and group names we can
347
-		//directly read the display name attribute instead of the DN
348
-		$name = $this->access->dn2groupname($dn);
349
-
350
-		$this->access->connection->writeToCache($cacheKey, $name);
351
-
352
-		return $name;
353
-	}
354
-
355
-	/**
356
-	 * returns the entry's gidNumber
357
-	 * @param string $dn
358
-	 * @param string $attribute
359
-	 * @return string|bool
360
-	 */
361
-	private function getEntryGidNumber($dn, $attribute) {
362
-		$value = $this->access->readAttribute($dn, $attribute);
363
-		if(is_array($value) && !empty($value)) {
364
-			return $value[0];
365
-		}
366
-		return false;
367
-	}
368
-
369
-	/**
370
-	 * returns the group's primary ID
371
-	 * @param string $dn
372
-	 * @return string|bool
373
-	 */
374
-	public function getGroupGidNumber($dn) {
375
-		return $this->getEntryGidNumber($dn, 'gidNumber');
376
-	}
377
-
378
-	/**
379
-	 * returns the user's gidNumber
380
-	 * @param string $dn
381
-	 * @return string|bool
382
-	 */
383
-	public function getUserGidNumber($dn) {
384
-		$gidNumber = false;
385
-		if($this->access->connection->hasGidNumber) {
386
-			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
387
-			if($gidNumber === false) {
388
-				$this->access->connection->hasGidNumber = false;
389
-			}
390
-		}
391
-		return $gidNumber;
392
-	}
393
-
394
-	/**
395
-	 * returns a filter for a "users has specific gid" search or count operation
396
-	 *
397
-	 * @param string $groupDN
398
-	 * @param string $search
399
-	 * @return string
400
-	 * @throws \Exception
401
-	 */
402
-	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
403
-		$groupID = $this->getGroupGidNumber($groupDN);
404
-		if($groupID === false) {
405
-			throw new \Exception('Not a valid group');
406
-		}
407
-
408
-		$filterParts = [];
409
-		$filterParts[] = $this->access->getFilterForUserCount();
410
-		if ($search !== '') {
411
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
412
-		}
413
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
414
-
415
-		return $this->access->combineFilterWithAnd($filterParts);
416
-	}
417
-
418
-	/**
419
-	 * returns a list of users that have the given group as gid number
420
-	 *
421
-	 * @param string $groupDN
422
-	 * @param string $search
423
-	 * @param int $limit
424
-	 * @param int $offset
425
-	 * @return string[]
426
-	 */
427
-	public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
428
-		try {
429
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
430
-			$users = $this->access->fetchListOfUsers(
431
-				$filter,
432
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
433
-				$limit,
434
-				$offset
435
-			);
436
-			return $this->access->nextcloudUserNames($users);
437
-		} catch (\Exception $e) {
438
-			return [];
439
-		}
440
-	}
441
-
442
-	/**
443
-	 * returns the number of users that have the given group as gid number
444
-	 *
445
-	 * @param string $groupDN
446
-	 * @param string $search
447
-	 * @param int $limit
448
-	 * @param int $offset
449
-	 * @return int
450
-	 */
451
-	public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
452
-		try {
453
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
454
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
455
-			return (int)$users;
456
-		} catch (\Exception $e) {
457
-			return 0;
458
-		}
459
-	}
460
-
461
-	/**
462
-	 * gets the gidNumber of a user
463
-	 * @param string $dn
464
-	 * @return string
465
-	 */
466
-	public function getUserGroupByGid($dn) {
467
-		$groupID = $this->getUserGidNumber($dn);
468
-		if($groupID !== false) {
469
-			$groupName = $this->gidNumber2Name($groupID, $dn);
470
-			if($groupName !== false) {
471
-				return $groupName;
472
-			}
473
-		}
474
-
475
-		return false;
476
-	}
477
-
478
-	/**
479
-	 * translates a primary group ID into an Nextcloud internal name
480
-	 * @param string $gid as given by primaryGroupID on AD
481
-	 * @param string $dn a DN that belongs to the same domain as the group
482
-	 * @return string|bool
483
-	 */
484
-	public function primaryGroupID2Name($gid, $dn) {
485
-		$cacheKey = 'primaryGroupIDtoName';
486
-		$groupNames = $this->access->connection->getFromCache($cacheKey);
487
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
488
-			return $groupNames[$gid];
489
-		}
490
-
491
-		$domainObjectSid = $this->access->getSID($dn);
492
-		if($domainObjectSid === false) {
493
-			return false;
494
-		}
495
-
496
-		//we need to get the DN from LDAP
497
-		$filter = $this->access->combineFilterWithAnd([
498
-			$this->access->connection->ldapGroupFilter,
499
-			'objectsid=' . $domainObjectSid . '-' . $gid
500
-		]);
501
-		$result = $this->access->searchGroups($filter, ['dn'], 1);
502
-		if(empty($result)) {
503
-			return false;
504
-		}
505
-		$dn = $result[0]['dn'][0];
506
-
507
-		//and now the group name
508
-		//NOTE once we have separate Nextcloud group IDs and group names we can
509
-		//directly read the display name attribute instead of the DN
510
-		$name = $this->access->dn2groupname($dn);
511
-
512
-		$this->access->connection->writeToCache($cacheKey, $name);
513
-
514
-		return $name;
515
-	}
516
-
517
-	/**
518
-	 * returns the entry's primary group ID
519
-	 * @param string $dn
520
-	 * @param string $attribute
521
-	 * @return string|bool
522
-	 */
523
-	private function getEntryGroupID($dn, $attribute) {
524
-		$value = $this->access->readAttribute($dn, $attribute);
525
-		if(is_array($value) && !empty($value)) {
526
-			return $value[0];
527
-		}
528
-		return false;
529
-	}
530
-
531
-	/**
532
-	 * returns the group's primary ID
533
-	 * @param string $dn
534
-	 * @return string|bool
535
-	 */
536
-	public function getGroupPrimaryGroupID($dn) {
537
-		return $this->getEntryGroupID($dn, 'primaryGroupToken');
538
-	}
539
-
540
-	/**
541
-	 * returns the user's primary group ID
542
-	 * @param string $dn
543
-	 * @return string|bool
544
-	 */
545
-	public function getUserPrimaryGroupIDs($dn) {
546
-		$primaryGroupID = false;
547
-		if($this->access->connection->hasPrimaryGroups) {
548
-			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
549
-			if($primaryGroupID === false) {
550
-				$this->access->connection->hasPrimaryGroups = false;
551
-			}
552
-		}
553
-		return $primaryGroupID;
554
-	}
555
-
556
-	/**
557
-	 * returns a filter for a "users in primary group" search or count operation
558
-	 *
559
-	 * @param string $groupDN
560
-	 * @param string $search
561
-	 * @return string
562
-	 * @throws \Exception
563
-	 */
564
-	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
565
-		$groupID = $this->getGroupPrimaryGroupID($groupDN);
566
-		if($groupID === false) {
567
-			throw new \Exception('Not a valid group');
568
-		}
569
-
570
-		$filterParts = [];
571
-		$filterParts[] = $this->access->getFilterForUserCount();
572
-		if ($search !== '') {
573
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
574
-		}
575
-		$filterParts[] = 'primaryGroupID=' . $groupID;
576
-
577
-		return $this->access->combineFilterWithAnd($filterParts);
578
-	}
579
-
580
-	/**
581
-	 * returns a list of users that have the given group as primary group
582
-	 *
583
-	 * @param string $groupDN
584
-	 * @param string $search
585
-	 * @param int $limit
586
-	 * @param int $offset
587
-	 * @return string[]
588
-	 */
589
-	public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
590
-		try {
591
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
592
-			$users = $this->access->fetchListOfUsers(
593
-				$filter,
594
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
595
-				$limit,
596
-				$offset
597
-			);
598
-			return $this->access->nextcloudUserNames($users);
599
-		} catch (\Exception $e) {
600
-			return [];
601
-		}
602
-	}
603
-
604
-	/**
605
-	 * returns the number of users that have the given group as primary group
606
-	 *
607
-	 * @param string $groupDN
608
-	 * @param string $search
609
-	 * @param int $limit
610
-	 * @param int $offset
611
-	 * @return int
612
-	 */
613
-	public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
614
-		try {
615
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
616
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
617
-			return (int)$users;
618
-		} catch (\Exception $e) {
619
-			return 0;
620
-		}
621
-	}
622
-
623
-	/**
624
-	 * gets the primary group of a user
625
-	 * @param string $dn
626
-	 * @return string
627
-	 */
628
-	public function getUserPrimaryGroup($dn) {
629
-		$groupID = $this->getUserPrimaryGroupIDs($dn);
630
-		if($groupID !== false) {
631
-			$groupName = $this->primaryGroupID2Name($groupID, $dn);
632
-			if($groupName !== false) {
633
-				return $groupName;
634
-			}
635
-		}
636
-
637
-		return false;
638
-	}
639
-
640
-	/**
641
-	 * Get all groups a user belongs to
642
-	 * @param string $uid Name of the user
643
-	 * @return array with group names
644
-	 *
645
-	 * This function fetches all groups a user belongs to. It does not check
646
-	 * if the user exists at all.
647
-	 *
648
-	 * This function includes groups based on dynamic group membership.
649
-	 */
650
-	public function getUserGroups($uid) {
651
-		if(!$this->enabled) {
652
-			return [];
653
-		}
654
-		$cacheKey = 'getUserGroups'.$uid;
655
-		$userGroups = $this->access->connection->getFromCache($cacheKey);
656
-		if(!is_null($userGroups)) {
657
-			return $userGroups;
658
-		}
659
-		$userDN = $this->access->username2dn($uid);
660
-		if(!$userDN) {
661
-			$this->access->connection->writeToCache($cacheKey, []);
662
-			return [];
663
-		}
664
-
665
-		$groups = [];
666
-		$primaryGroup = $this->getUserPrimaryGroup($userDN);
667
-		$gidGroupName = $this->getUserGroupByGid($userDN);
668
-
669
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
670
-
671
-		if (!empty($dynamicGroupMemberURL)) {
672
-			// look through dynamic groups to add them to the result array if needed
673
-			$groupsToMatch = $this->access->fetchListOfGroups(
674
-				$this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
675
-			foreach($groupsToMatch as $dynamicGroup) {
676
-				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
677
-					continue;
678
-				}
679
-				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
680
-				if ($pos !== false) {
681
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
682
-					// apply filter via ldap search to see if this user is in this
683
-					// dynamic group
684
-					$userMatch = $this->access->readAttribute(
685
-						$userDN,
686
-						$this->access->connection->ldapUserDisplayName,
687
-						$memberUrlFilter
688
-					);
689
-					if ($userMatch !== false) {
690
-						// match found so this user is in this group
691
-						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
692
-						if(is_string($groupName)) {
693
-							// be sure to never return false if the dn could not be
694
-							// resolved to a name, for whatever reason.
695
-							$groups[] = $groupName;
696
-						}
697
-					}
698
-				} else {
699
-					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
700
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
701
-				}
702
-			}
703
-		}
704
-
705
-		// if possible, read out membership via memberOf. It's far faster than
706
-		// performing a search, which still is a fallback later.
707
-		// memberof doesn't support memberuid, so skip it here.
708
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
709
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
710
-			&& strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
711
-			) {
712
-			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
713
-			if (is_array($groupDNs)) {
714
-				foreach ($groupDNs as $dn) {
715
-					$groupName = $this->access->dn2groupname($dn);
716
-					if(is_string($groupName)) {
717
-						// be sure to never return false if the dn could not be
718
-						// resolved to a name, for whatever reason.
719
-						$groups[] = $groupName;
720
-					}
721
-				}
722
-			}
723
-
724
-			if($primaryGroup !== false) {
725
-				$groups[] = $primaryGroup;
726
-			}
727
-			if($gidGroupName !== false) {
728
-				$groups[] = $gidGroupName;
729
-			}
730
-			$this->access->connection->writeToCache($cacheKey, $groups);
731
-			return $groups;
732
-		}
733
-
734
-		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
735
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
736
-			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
737
-		) {
738
-			$uid = $userDN;
739
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
740
-			$result = $this->access->readAttribute($userDN, 'uid');
741
-			if ($result === false) {
742
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
743
-					$this->access->connection->ldapHost, ILogger::DEBUG);
744
-				$uid = false;
745
-			} else {
746
-				$uid = $result[0];
747
-			}
748
-		} else {
749
-			// just in case
750
-			$uid = $userDN;
751
-		}
752
-
753
-		if($uid !== false) {
754
-			if (isset($this->cachedGroupsByMember[$uid])) {
755
-				$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
756
-			} else {
757
-				$groupsByMember = array_values($this->getGroupsByMember($uid));
758
-				$groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
759
-				$this->cachedGroupsByMember[$uid] = $groupsByMember;
760
-				$groups = array_merge($groups, $groupsByMember);
761
-			}
762
-		}
763
-
764
-		if($primaryGroup !== false) {
765
-			$groups[] = $primaryGroup;
766
-		}
767
-		if($gidGroupName !== false) {
768
-			$groups[] = $gidGroupName;
769
-		}
770
-
771
-		$groups = array_unique($groups, SORT_LOCALE_STRING);
772
-		$this->access->connection->writeToCache($cacheKey, $groups);
773
-
774
-		return $groups;
775
-	}
776
-
777
-	/**
778
-	 * @param string $dn
779
-	 * @param array|null &$seen
780
-	 * @return array
781
-	 */
782
-	private function getGroupsByMember($dn, &$seen = null) {
783
-		if ($seen === null) {
784
-			$seen = [];
785
-		}
786
-		if (array_key_exists($dn, $seen)) {
787
-			// avoid loops
788
-			return [];
789
-		}
790
-		$allGroups = [];
791
-		$seen[$dn] = true;
792
-		$filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn;
793
-		$groups = $this->access->fetchListOfGroups($filter,
794
-			[$this->access->connection->ldapGroupDisplayName, 'dn']);
795
-		if (is_array($groups)) {
796
-			$fetcher = function ($dn, &$seen) {
797
-				if(is_array($dn) && isset($dn['dn'][0])) {
798
-					$dn = $dn['dn'][0];
799
-				}
800
-				return $this->getGroupsByMember($dn, $seen);
801
-			};
802
-			$allGroups = $this->walkNestedGroups($dn, $fetcher, $groups);
803
-		}
804
-		$visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups));
805
-		return array_intersect_key($allGroups, array_flip($visibleGroups));
806
-	}
807
-
808
-	/**
809
-	 * get a list of all users in a group
810
-	 *
811
-	 * @param string $gid
812
-	 * @param string $search
813
-	 * @param int $limit
814
-	 * @param int $offset
815
-	 * @return array with user ids
816
-	 * @throws \Exception
817
-	 */
818
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
819
-		if(!$this->enabled) {
820
-			return [];
821
-		}
822
-		if(!$this->groupExists($gid)) {
823
-			return [];
824
-		}
825
-		$search = $this->access->escapeFilterPart($search, true);
826
-		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
827
-		// check for cache of the exact query
828
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
829
-		if(!is_null($groupUsers)) {
830
-			return $groupUsers;
831
-		}
832
-
833
-		// check for cache of the query without limit and offset
834
-		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
835
-		if(!is_null($groupUsers)) {
836
-			$groupUsers = array_slice($groupUsers, $offset, $limit);
837
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
838
-			return $groupUsers;
839
-		}
840
-
841
-		if($limit === -1) {
842
-			$limit = null;
843
-		}
844
-		$groupDN = $this->access->groupname2dn($gid);
845
-		if(!$groupDN) {
846
-			// group couldn't be found, return empty resultset
847
-			$this->access->connection->writeToCache($cacheKey, []);
848
-			return [];
849
-		}
850
-
851
-		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
852
-		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
853
-		$members = $this->_groupMembers($groupDN);
854
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
855
-			//in case users could not be retrieved, return empty result set
856
-			$this->access->connection->writeToCache($cacheKey, []);
857
-			return [];
858
-		}
859
-
860
-		$groupUsers = [];
861
-		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
862
-		$attrs = $this->access->userManager->getAttributes(true);
863
-		foreach($members as $member) {
864
-			if($isMemberUid) {
865
-				//we got uids, need to get their DNs to 'translate' them to user names
866
-				$filter = $this->access->combineFilterWithAnd([
867
-					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
868
-					$this->access->combineFilterWithAnd([
869
-						$this->access->getFilterPartForUserSearch($search),
870
-						$this->access->connection->ldapUserFilter
871
-					])
872
-				]);
873
-				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
874
-				if(count($ldap_users) < 1) {
875
-					continue;
876
-				}
877
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
878
-			} else {
879
-				//we got DNs, check if we need to filter by search or we can give back all of them
880
-				$uid = $this->access->dn2username($member);
881
-				if(!$uid) {
882
-					continue;
883
-				}
884
-
885
-				$cacheKey = 'userExistsOnLDAP' . $uid;
886
-				$userExists = $this->access->connection->getFromCache($cacheKey);
887
-				if($userExists === false) {
888
-					continue;
889
-				}
890
-				if($userExists === null || $search !== '') {
891
-					if (!$this->access->readAttribute($member,
892
-						$this->access->connection->ldapUserDisplayName,
893
-						$this->access->combineFilterWithAnd([
894
-							$this->access->getFilterPartForUserSearch($search),
895
-							$this->access->connection->ldapUserFilter
896
-						])))
897
-					{
898
-						if($search === '') {
899
-							$this->access->connection->writeToCache($cacheKey, false);
900
-						}
901
-						continue;
902
-					}
903
-					$this->access->connection->writeToCache($cacheKey, true);
904
-				}
905
-				$groupUsers[] = $uid;
906
-			}
907
-		}
908
-
909
-		$groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
910
-		natsort($groupUsers);
911
-		$this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
912
-		$groupUsers = array_slice($groupUsers, $offset, $limit);
913
-
914
-		$this->access->connection->writeToCache($cacheKey, $groupUsers);
915
-
916
-		return $groupUsers;
917
-	}
918
-
919
-	/**
920
-	 * returns the number of users in a group, who match the search term
921
-	 * @param string $gid the internal group name
922
-	 * @param string $search optional, a search string
923
-	 * @return int|bool
924
-	 */
925
-	public function countUsersInGroup($gid, $search = '') {
926
-		if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
927
-			return $this->groupPluginManager->countUsersInGroup($gid, $search);
928
-		}
929
-
930
-		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
931
-		if(!$this->enabled || !$this->groupExists($gid)) {
932
-			return false;
933
-		}
934
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
935
-		if(!is_null($groupUsers)) {
936
-			return $groupUsers;
937
-		}
938
-
939
-		$groupDN = $this->access->groupname2dn($gid);
940
-		if(!$groupDN) {
941
-			// group couldn't be found, return empty result set
942
-			$this->access->connection->writeToCache($cacheKey, false);
943
-			return false;
944
-		}
945
-
946
-		$members = $this->_groupMembers($groupDN);
947
-		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
948
-		if(!$members && $primaryUserCount === 0) {
949
-			//in case users could not be retrieved, return empty result set
950
-			$this->access->connection->writeToCache($cacheKey, false);
951
-			return false;
952
-		}
953
-
954
-		if ($search === '') {
955
-			$groupUsers = count($members) + $primaryUserCount;
956
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
957
-			return $groupUsers;
958
-		}
959
-		$search = $this->access->escapeFilterPart($search, true);
960
-		$isMemberUid =
961
-			(strtolower($this->access->connection->ldapGroupMemberAssocAttr)
962
-			=== 'memberuid');
963
-
964
-		//we need to apply the search filter
965
-		//alternatives that need to be checked:
966
-		//a) get all users by search filter and array_intersect them
967
-		//b) a, but only when less than 1k 10k ?k users like it is
968
-		//c) put all DNs|uids in a LDAP filter, combine with the search string
969
-		//   and let it count.
970
-		//For now this is not important, because the only use of this method
971
-		//does not supply a search string
972
-		$groupUsers = [];
973
-		foreach($members as $member) {
974
-			if($isMemberUid) {
975
-				//we got uids, need to get their DNs to 'translate' them to user names
976
-				$filter = $this->access->combineFilterWithAnd([
977
-					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
978
-					$this->access->getFilterPartForUserSearch($search)
979
-				]);
980
-				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
981
-				if(count($ldap_users) < 1) {
982
-					continue;
983
-				}
984
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
985
-			} else {
986
-				//we need to apply the search filter now
987
-				if(!$this->access->readAttribute($member,
988
-					$this->access->connection->ldapUserDisplayName,
989
-					$this->access->getFilterPartForUserSearch($search))) {
990
-					continue;
991
-				}
992
-				// dn2username will also check if the users belong to the allowed base
993
-				if($ocname = $this->access->dn2username($member)) {
994
-					$groupUsers[] = $ocname;
995
-				}
996
-			}
997
-		}
998
-
999
-		//and get users that have the group as primary
1000
-		$primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
1001
-
1002
-		return count($groupUsers) + $primaryUsers;
1003
-	}
1004
-
1005
-	/**
1006
-	 * get a list of all groups
1007
-	 *
1008
-	 * @param string $search
1009
-	 * @param $limit
1010
-	 * @param int $offset
1011
-	 * @return array with group names
1012
-	 *
1013
-	 * Returns a list with all groups (used by getGroups)
1014
-	 */
1015
-	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1016
-		if(!$this->enabled) {
1017
-			return [];
1018
-		}
1019
-		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
1020
-
1021
-		//Check cache before driving unnecessary searches
1022
-		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1023
-		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
1024
-		if(!is_null($ldap_groups)) {
1025
-			return $ldap_groups;
1026
-		}
1027
-
1028
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
1029
-		// error. With a limit of 0, we get 0 results. So we pass null.
1030
-		if($limit <= 0) {
1031
-			$limit = null;
1032
-		}
1033
-		$filter = $this->access->combineFilterWithAnd([
1034
-			$this->access->connection->ldapGroupFilter,
1035
-			$this->access->getFilterPartForGroupSearch($search)
1036
-		]);
1037
-		\OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
1038
-		$ldap_groups = $this->access->fetchListOfGroups($filter,
1039
-				[$this->access->connection->ldapGroupDisplayName, 'dn'],
1040
-				$limit,
1041
-				$offset);
1042
-		$ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
1043
-
1044
-		$this->access->connection->writeToCache($cacheKey, $ldap_groups);
1045
-		return $ldap_groups;
1046
-	}
1047
-
1048
-	/**
1049
-	 * get a list of all groups using a paged search
1050
-	 *
1051
-	 * @param string $search
1052
-	 * @param int $limit
1053
-	 * @param int $offset
1054
-	 * @return array with group names
1055
-	 *
1056
-	 * Returns a list with all groups
1057
-	 * Uses a paged search if available to override a
1058
-	 * server side search limit.
1059
-	 * (active directory has a limit of 1000 by default)
1060
-	 */
1061
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
1062
-		if(!$this->enabled) {
1063
-			return [];
1064
-		}
1065
-		$search = $this->access->escapeFilterPart($search, true);
1066
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1067
-		if ($pagingSize <= 0) {
1068
-			return $this->getGroupsChunk($search, $limit, $offset);
1069
-		}
1070
-		$maxGroups = 100000; // limit max results (just for safety reasons)
1071
-		if ($limit > -1) {
1072
-		   $overallLimit = min($limit + $offset, $maxGroups);
1073
-		} else {
1074
-		   $overallLimit = $maxGroups;
1075
-		}
1076
-		$chunkOffset = $offset;
1077
-		$allGroups = [];
1078
-		while ($chunkOffset < $overallLimit) {
1079
-			$chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1080
-			$ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1081
-			$nread = count($ldapGroups);
1082
-			\OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1083
-			if ($nread) {
1084
-				$allGroups = array_merge($allGroups, $ldapGroups);
1085
-				$chunkOffset += $nread;
1086
-			}
1087
-			if ($nread < $chunkLimit) {
1088
-				break;
1089
-			}
1090
-		}
1091
-		return $allGroups;
1092
-	}
1093
-
1094
-	/**
1095
-	 * @param string $group
1096
-	 * @return bool
1097
-	 */
1098
-	public function groupMatchesFilter($group) {
1099
-		return (strripos($group, $this->groupSearch) !== false);
1100
-	}
1101
-
1102
-	/**
1103
-	 * check if a group exists
1104
-	 * @param string $gid
1105
-	 * @return bool
1106
-	 */
1107
-	public function groupExists($gid) {
1108
-		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1109
-		if(!is_null($groupExists)) {
1110
-			return (bool)$groupExists;
1111
-		}
1112
-
1113
-		//getting dn, if false the group does not exist. If dn, it may be mapped
1114
-		//only, requires more checking.
1115
-		$dn = $this->access->groupname2dn($gid);
1116
-		if(!$dn) {
1117
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1118
-			return false;
1119
-		}
1120
-
1121
-		//if group really still exists, we will be able to read its objectclass
1122
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1123
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1124
-			return false;
1125
-		}
1126
-
1127
-		$this->access->connection->writeToCache('groupExists'.$gid, true);
1128
-		return true;
1129
-	}
1130
-
1131
-	/**
1132
-	 * Check if backend implements actions
1133
-	 * @param int $actions bitwise-or'ed actions
1134
-	 * @return boolean
1135
-	 *
1136
-	 * Returns the supported actions as int to be
1137
-	 * compared with GroupInterface::CREATE_GROUP etc.
1138
-	 */
1139
-	public function implementsActions($actions) {
1140
-		return (bool)((GroupInterface::COUNT_USERS |
1141
-				$this->groupPluginManager->getImplementedActions()) & $actions);
1142
-	}
1143
-
1144
-	/**
1145
-	 * Return access for LDAP interaction.
1146
-	 * @return Access instance of Access for LDAP interaction
1147
-	 */
1148
-	public function getLDAPAccess($gid) {
1149
-		return $this->access;
1150
-	}
1151
-
1152
-	/**
1153
-	 * create a group
1154
-	 * @param string $gid
1155
-	 * @return bool
1156
-	 * @throws \Exception
1157
-	 */
1158
-	public function createGroup($gid) {
1159
-		if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1160
-			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1161
-				//updates group mapping
1162
-				$uuid = $this->access->getUUID($dn, false);
1163
-				if(is_string($uuid)) {
1164
-					$this->access->mapAndAnnounceIfApplicable(
1165
-						$this->access->getGroupMapper(),
1166
-						$dn,
1167
-						$gid,
1168
-						$uuid,
1169
-						false
1170
-					);
1171
-					$this->access->cacheGroupExists($gid);
1172
-				}
1173
-			}
1174
-			return $dn != null;
1175
-		}
1176
-		throw new \Exception('Could not create group in LDAP backend.');
1177
-	}
1178
-
1179
-	/**
1180
-	 * delete a group
1181
-	 * @param string $gid gid of the group to delete
1182
-	 * @return bool
1183
-	 * @throws \Exception
1184
-	 */
1185
-	public function deleteGroup($gid) {
1186
-		if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1187
-			if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1188
-				#delete group in nextcloud internal db
1189
-				$this->access->getGroupMapper()->unmap($gid);
1190
-				$this->access->connection->writeToCache("groupExists".$gid, false);
1191
-			}
1192
-			return $ret;
1193
-		}
1194
-		throw new \Exception('Could not delete group in LDAP backend.');
1195
-	}
1196
-
1197
-	/**
1198
-	 * Add a user to a group
1199
-	 * @param string $uid Name of the user to add to group
1200
-	 * @param string $gid Name of the group in which add the user
1201
-	 * @return bool
1202
-	 * @throws \Exception
1203
-	 */
1204
-	public function addToGroup($uid, $gid) {
1205
-		if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1206
-			if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1207
-				$this->access->connection->clearCache();
1208
-				unset($this->cachedGroupMembers[$gid]);
1209
-			}
1210
-			return $ret;
1211
-		}
1212
-		throw new \Exception('Could not add user to group in LDAP backend.');
1213
-	}
1214
-
1215
-	/**
1216
-	 * Removes a user from a group
1217
-	 * @param string $uid Name of the user to remove from group
1218
-	 * @param string $gid Name of the group from which remove the user
1219
-	 * @return bool
1220
-	 * @throws \Exception
1221
-	 */
1222
-	public function removeFromGroup($uid, $gid) {
1223
-		if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1224
-			if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1225
-				$this->access->connection->clearCache();
1226
-				unset($this->cachedGroupMembers[$gid]);
1227
-			}
1228
-			return $ret;
1229
-		}
1230
-		throw new \Exception('Could not remove user from group in LDAP backend.');
1231
-	}
1232
-
1233
-	/**
1234
-	 * Gets group details
1235
-	 * @param string $gid Name of the group
1236
-	 * @return array | false
1237
-	 * @throws \Exception
1238
-	 */
1239
-	public function getGroupDetails($gid) {
1240
-		if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1241
-			return $this->groupPluginManager->getGroupDetails($gid);
1242
-		}
1243
-		throw new \Exception('Could not get group details in LDAP backend.');
1244
-	}
1245
-
1246
-	/**
1247
-	 * Return LDAP connection resource from a cloned connection.
1248
-	 * The cloned connection needs to be closed manually.
1249
-	 * of the current access.
1250
-	 * @param string $gid
1251
-	 * @return resource of the LDAP connection
1252
-	 */
1253
-	public function getNewLDAPConnection($gid) {
1254
-		$connection = clone $this->access->getConnection();
1255
-		return $connection->getConnectionResource();
1256
-	}
1257
-
1258
-	/**
1259
-	 * @throws \OC\ServerNotAvailableException
1260
-	 */
1261
-	public function getDisplayName(string $gid): string {
1262
-		if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
1263
-			return $this->groupPluginManager->getDisplayName($gid);
1264
-		}
1265
-
1266
-		$cacheKey = 'group_getDisplayName' . $gid;
1267
-		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1268
-			return $displayName;
1269
-		}
1270
-
1271
-		$displayName = $this->access->readAttribute(
1272
-			$this->access->groupname2dn($gid),
1273
-			$this->access->connection->ldapGroupDisplayName);
1274
-
1275
-		if ($displayName && (count($displayName) > 0)) {
1276
-			$displayName = $displayName[0];
1277
-			$this->access->connection->writeToCache($cacheKey, $displayName);
1278
-			return $displayName;
1279
-		}
1280
-
1281
-		return '';
1282
-	}
52
+    protected $enabled = false;
53
+
54
+    /**
55
+     * @var string[] $cachedGroupMembers array of users with gid as key
56
+     */
57
+    protected $cachedGroupMembers;
58
+
59
+    /**
60
+     * @var string[] $cachedGroupsByMember array of groups with uid as key
61
+     */
62
+    protected $cachedGroupsByMember;
63
+
64
+    /**
65
+     * @var string[] $cachedNestedGroups array of groups with gid (DN) as key
66
+     */
67
+    protected $cachedNestedGroups;
68
+
69
+    /** @var GroupPluginManager */
70
+    protected $groupPluginManager;
71
+
72
+    public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
73
+        parent::__construct($access);
74
+        $filter = $this->access->connection->ldapGroupFilter;
75
+        $gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
76
+        if(!empty($filter) && !empty($gassoc)) {
77
+            $this->enabled = true;
78
+        }
79
+
80
+        $this->cachedGroupMembers = new CappedMemoryCache();
81
+        $this->cachedGroupsByMember = new CappedMemoryCache();
82
+        $this->cachedNestedGroups = new CappedMemoryCache();
83
+        $this->groupPluginManager = $groupPluginManager;
84
+    }
85
+
86
+    /**
87
+     * is user in group?
88
+     * @param string $uid uid of the user
89
+     * @param string $gid gid of the group
90
+     * @return bool
91
+     *
92
+     * Checks whether the user is member of a group or not.
93
+     */
94
+    public function inGroup($uid, $gid) {
95
+        if(!$this->enabled) {
96
+            return false;
97
+        }
98
+        $cacheKey = 'inGroup'.$uid.':'.$gid;
99
+        $inGroup = $this->access->connection->getFromCache($cacheKey);
100
+        if(!is_null($inGroup)) {
101
+            return (bool)$inGroup;
102
+        }
103
+
104
+        $userDN = $this->access->username2dn($uid);
105
+
106
+        if(isset($this->cachedGroupMembers[$gid])) {
107
+            $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
108
+            return $isInGroup;
109
+        }
110
+
111
+        $cacheKeyMembers = 'inGroup-members:'.$gid;
112
+        $members = $this->access->connection->getFromCache($cacheKeyMembers);
113
+        if(!is_null($members)) {
114
+            $this->cachedGroupMembers[$gid] = $members;
115
+            $isInGroup = in_array($userDN, $members, true);
116
+            $this->access->connection->writeToCache($cacheKey, $isInGroup);
117
+            return $isInGroup;
118
+        }
119
+
120
+        $groupDN = $this->access->groupname2dn($gid);
121
+        // just in case
122
+        if(!$groupDN || !$userDN) {
123
+            $this->access->connection->writeToCache($cacheKey, false);
124
+            return false;
125
+        }
126
+
127
+        //check primary group first
128
+        if($gid === $this->getUserPrimaryGroup($userDN)) {
129
+            $this->access->connection->writeToCache($cacheKey, true);
130
+            return true;
131
+        }
132
+
133
+        //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
134
+        $members = $this->_groupMembers($groupDN);
135
+        if(!is_array($members) || count($members) === 0) {
136
+            $this->access->connection->writeToCache($cacheKey, false);
137
+            return false;
138
+        }
139
+
140
+        //extra work if we don't get back user DNs
141
+        if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
142
+            $dns = [];
143
+            $filterParts = [];
144
+            $bytes = 0;
145
+            foreach($members as $mid) {
146
+                $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
147
+                $filterParts[] = $filter;
148
+                $bytes += strlen($filter);
149
+                if($bytes >= 9000000) {
150
+                    // AD has a default input buffer of 10 MB, we do not want
151
+                    // to take even the chance to exceed it
152
+                    $filter = $this->access->combineFilterWithOr($filterParts);
153
+                    $bytes = 0;
154
+                    $filterParts = [];
155
+                    $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
156
+                    $dns = array_merge($dns, $users);
157
+                }
158
+            }
159
+            if(count($filterParts) > 0) {
160
+                $filter = $this->access->combineFilterWithOr($filterParts);
161
+                $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
162
+                $dns = array_merge($dns, $users);
163
+            }
164
+            $members = $dns;
165
+        }
166
+
167
+        $isInGroup = in_array($userDN, $members);
168
+        $this->access->connection->writeToCache($cacheKey, $isInGroup);
169
+        $this->access->connection->writeToCache($cacheKeyMembers, $members);
170
+        $this->cachedGroupMembers[$gid] = $members;
171
+
172
+        return $isInGroup;
173
+    }
174
+
175
+    /**
176
+     * @param string $dnGroup
177
+     * @return array
178
+     *
179
+     * For a group that has user membership defined by an LDAP search url attribute returns the users
180
+     * that match the search url otherwise returns an empty array.
181
+     */
182
+    public function getDynamicGroupMembers($dnGroup) {
183
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
184
+
185
+        if (empty($dynamicGroupMemberURL)) {
186
+            return [];
187
+        }
188
+
189
+        $dynamicMembers = [];
190
+        $memberURLs = $this->access->readAttribute(
191
+            $dnGroup,
192
+            $dynamicGroupMemberURL,
193
+            $this->access->connection->ldapGroupFilter
194
+        );
195
+        if ($memberURLs !== false) {
196
+            // this group has the 'memberURL' attribute so this is a dynamic group
197
+            // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
198
+            // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
199
+            $pos = strpos($memberURLs[0], '(');
200
+            if ($pos !== false) {
201
+                $memberUrlFilter = substr($memberURLs[0], $pos);
202
+                $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
203
+                $dynamicMembers = [];
204
+                foreach($foundMembers as $value) {
205
+                    $dynamicMembers[$value['dn'][0]] = 1;
206
+                }
207
+            } else {
208
+                \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
209
+                    'of group ' . $dnGroup, ILogger::DEBUG);
210
+            }
211
+        }
212
+        return $dynamicMembers;
213
+    }
214
+
215
+    /**
216
+     * @param string $dnGroup
217
+     * @param array|null &$seen
218
+     * @return array|mixed|null
219
+     * @throws \OC\ServerNotAvailableException
220
+     */
221
+    private function _groupMembers($dnGroup, &$seen = null) {
222
+        if ($seen === null) {
223
+            $seen = [];
224
+        }
225
+        $allMembers = [];
226
+        if (array_key_exists($dnGroup, $seen)) {
227
+            // avoid loops
228
+            return [];
229
+        }
230
+        // used extensively in cron job, caching makes sense for nested groups
231
+        $cacheKey = '_groupMembers'.$dnGroup;
232
+        $groupMembers = $this->access->connection->getFromCache($cacheKey);
233
+        if($groupMembers !== null) {
234
+            return $groupMembers;
235
+        }
236
+        $seen[$dnGroup] = 1;
237
+        $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
238
+        if (is_array($members)) {
239
+            $fetcher = function ($memberDN, &$seen) {
240
+                return $this->_groupMembers($memberDN, $seen);
241
+            };
242
+            $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
243
+        }
244
+
245
+        $allMembers += $this->getDynamicGroupMembers($dnGroup);
246
+
247
+        $this->access->connection->writeToCache($cacheKey, $allMembers);
248
+        return $allMembers;
249
+    }
250
+
251
+    /**
252
+     * @param string $DN
253
+     * @param array|null &$seen
254
+     * @return array
255
+     * @throws \OC\ServerNotAvailableException
256
+     */
257
+    private function _getGroupDNsFromMemberOf($DN) {
258
+        $groups = $this->access->readAttribute($DN, 'memberOf');
259
+        if (!is_array($groups)) {
260
+            return [];
261
+        }
262
+
263
+        $fetcher = function ($groupDN) {
264
+            if (isset($this->cachedNestedGroups[$groupDN])) {
265
+                $nestedGroups = $this->cachedNestedGroups[$groupDN];
266
+            } else {
267
+                $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf');
268
+                if (!is_array($nestedGroups)) {
269
+                    $nestedGroups = [];
270
+                }
271
+                $this->cachedNestedGroups[$groupDN] = $nestedGroups;
272
+            }
273
+            return $nestedGroups;
274
+        };
275
+
276
+        $groups = $this->walkNestedGroups($DN, $fetcher, $groups);
277
+        return $this->access->groupsMatchFilter($groups);
278
+    }
279
+
280
+    /**
281
+     * @param string $dn
282
+     * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns
283
+     * @param array $list
284
+     * @return array
285
+     */
286
+    private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array {
287
+        $nesting = (int) $this->access->connection->ldapNestedGroups;
288
+        // depending on the input, we either have a list of DNs or a list of LDAP records
289
+        // also, the output expects either DNs or records. Testing the first element should suffice.
290
+        $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
291
+
292
+        if ($nesting !== 1) {
293
+            if($recordMode) {
294
+                // the keys are numeric, but should hold the DN
295
+                return array_reduce($list, function ($transformed, $record) use ($dn) {
296
+                    if($record['dn'][0] != $dn) {
297
+                        $transformed[$record['dn'][0]] = $record;
298
+                    }
299
+                    return $transformed;
300
+                }, []);
301
+            }
302
+            return $list;
303
+        }
304
+
305
+        $seen = [];
306
+        while ($record = array_pop($list)) {
307
+            $recordDN = $recordMode ? $record['dn'][0] : $record;
308
+            if ($recordDN === $dn || array_key_exists($recordDN, $seen)) {
309
+                // Prevent loops
310
+                continue;
311
+            }
312
+            $fetched = $fetcher($record, $seen);
313
+            $list = array_merge($list, $fetched);
314
+            $seen[$recordDN] = $record;
315
+        }
316
+
317
+        return $recordMode ? $seen : array_keys($seen);
318
+    }
319
+
320
+    /**
321
+     * translates a gidNumber into an ownCloud internal name
322
+     * @param string $gid as given by gidNumber on POSIX LDAP
323
+     * @param string $dn a DN that belongs to the same domain as the group
324
+     * @return string|bool
325
+     */
326
+    public function gidNumber2Name($gid, $dn) {
327
+        $cacheKey = 'gidNumberToName' . $gid;
328
+        $groupName = $this->access->connection->getFromCache($cacheKey);
329
+        if(!is_null($groupName) && isset($groupName)) {
330
+            return $groupName;
331
+        }
332
+
333
+        //we need to get the DN from LDAP
334
+        $filter = $this->access->combineFilterWithAnd([
335
+            $this->access->connection->ldapGroupFilter,
336
+            'objectClass=posixGroup',
337
+            $this->access->connection->ldapGidNumber . '=' . $gid
338
+        ]);
339
+        $result = $this->access->searchGroups($filter, ['dn'], 1);
340
+        if(empty($result)) {
341
+            return false;
342
+        }
343
+        $dn = $result[0]['dn'][0];
344
+
345
+        //and now the group name
346
+        //NOTE once we have separate ownCloud group IDs and group names we can
347
+        //directly read the display name attribute instead of the DN
348
+        $name = $this->access->dn2groupname($dn);
349
+
350
+        $this->access->connection->writeToCache($cacheKey, $name);
351
+
352
+        return $name;
353
+    }
354
+
355
+    /**
356
+     * returns the entry's gidNumber
357
+     * @param string $dn
358
+     * @param string $attribute
359
+     * @return string|bool
360
+     */
361
+    private function getEntryGidNumber($dn, $attribute) {
362
+        $value = $this->access->readAttribute($dn, $attribute);
363
+        if(is_array($value) && !empty($value)) {
364
+            return $value[0];
365
+        }
366
+        return false;
367
+    }
368
+
369
+    /**
370
+     * returns the group's primary ID
371
+     * @param string $dn
372
+     * @return string|bool
373
+     */
374
+    public function getGroupGidNumber($dn) {
375
+        return $this->getEntryGidNumber($dn, 'gidNumber');
376
+    }
377
+
378
+    /**
379
+     * returns the user's gidNumber
380
+     * @param string $dn
381
+     * @return string|bool
382
+     */
383
+    public function getUserGidNumber($dn) {
384
+        $gidNumber = false;
385
+        if($this->access->connection->hasGidNumber) {
386
+            $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
387
+            if($gidNumber === false) {
388
+                $this->access->connection->hasGidNumber = false;
389
+            }
390
+        }
391
+        return $gidNumber;
392
+    }
393
+
394
+    /**
395
+     * returns a filter for a "users has specific gid" search or count operation
396
+     *
397
+     * @param string $groupDN
398
+     * @param string $search
399
+     * @return string
400
+     * @throws \Exception
401
+     */
402
+    private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
403
+        $groupID = $this->getGroupGidNumber($groupDN);
404
+        if($groupID === false) {
405
+            throw new \Exception('Not a valid group');
406
+        }
407
+
408
+        $filterParts = [];
409
+        $filterParts[] = $this->access->getFilterForUserCount();
410
+        if ($search !== '') {
411
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
412
+        }
413
+        $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
414
+
415
+        return $this->access->combineFilterWithAnd($filterParts);
416
+    }
417
+
418
+    /**
419
+     * returns a list of users that have the given group as gid number
420
+     *
421
+     * @param string $groupDN
422
+     * @param string $search
423
+     * @param int $limit
424
+     * @param int $offset
425
+     * @return string[]
426
+     */
427
+    public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
428
+        try {
429
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
430
+            $users = $this->access->fetchListOfUsers(
431
+                $filter,
432
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
433
+                $limit,
434
+                $offset
435
+            );
436
+            return $this->access->nextcloudUserNames($users);
437
+        } catch (\Exception $e) {
438
+            return [];
439
+        }
440
+    }
441
+
442
+    /**
443
+     * returns the number of users that have the given group as gid number
444
+     *
445
+     * @param string $groupDN
446
+     * @param string $search
447
+     * @param int $limit
448
+     * @param int $offset
449
+     * @return int
450
+     */
451
+    public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
452
+        try {
453
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
454
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
455
+            return (int)$users;
456
+        } catch (\Exception $e) {
457
+            return 0;
458
+        }
459
+    }
460
+
461
+    /**
462
+     * gets the gidNumber of a user
463
+     * @param string $dn
464
+     * @return string
465
+     */
466
+    public function getUserGroupByGid($dn) {
467
+        $groupID = $this->getUserGidNumber($dn);
468
+        if($groupID !== false) {
469
+            $groupName = $this->gidNumber2Name($groupID, $dn);
470
+            if($groupName !== false) {
471
+                return $groupName;
472
+            }
473
+        }
474
+
475
+        return false;
476
+    }
477
+
478
+    /**
479
+     * translates a primary group ID into an Nextcloud internal name
480
+     * @param string $gid as given by primaryGroupID on AD
481
+     * @param string $dn a DN that belongs to the same domain as the group
482
+     * @return string|bool
483
+     */
484
+    public function primaryGroupID2Name($gid, $dn) {
485
+        $cacheKey = 'primaryGroupIDtoName';
486
+        $groupNames = $this->access->connection->getFromCache($cacheKey);
487
+        if(!is_null($groupNames) && isset($groupNames[$gid])) {
488
+            return $groupNames[$gid];
489
+        }
490
+
491
+        $domainObjectSid = $this->access->getSID($dn);
492
+        if($domainObjectSid === false) {
493
+            return false;
494
+        }
495
+
496
+        //we need to get the DN from LDAP
497
+        $filter = $this->access->combineFilterWithAnd([
498
+            $this->access->connection->ldapGroupFilter,
499
+            'objectsid=' . $domainObjectSid . '-' . $gid
500
+        ]);
501
+        $result = $this->access->searchGroups($filter, ['dn'], 1);
502
+        if(empty($result)) {
503
+            return false;
504
+        }
505
+        $dn = $result[0]['dn'][0];
506
+
507
+        //and now the group name
508
+        //NOTE once we have separate Nextcloud group IDs and group names we can
509
+        //directly read the display name attribute instead of the DN
510
+        $name = $this->access->dn2groupname($dn);
511
+
512
+        $this->access->connection->writeToCache($cacheKey, $name);
513
+
514
+        return $name;
515
+    }
516
+
517
+    /**
518
+     * returns the entry's primary group ID
519
+     * @param string $dn
520
+     * @param string $attribute
521
+     * @return string|bool
522
+     */
523
+    private function getEntryGroupID($dn, $attribute) {
524
+        $value = $this->access->readAttribute($dn, $attribute);
525
+        if(is_array($value) && !empty($value)) {
526
+            return $value[0];
527
+        }
528
+        return false;
529
+    }
530
+
531
+    /**
532
+     * returns the group's primary ID
533
+     * @param string $dn
534
+     * @return string|bool
535
+     */
536
+    public function getGroupPrimaryGroupID($dn) {
537
+        return $this->getEntryGroupID($dn, 'primaryGroupToken');
538
+    }
539
+
540
+    /**
541
+     * returns the user's primary group ID
542
+     * @param string $dn
543
+     * @return string|bool
544
+     */
545
+    public function getUserPrimaryGroupIDs($dn) {
546
+        $primaryGroupID = false;
547
+        if($this->access->connection->hasPrimaryGroups) {
548
+            $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
549
+            if($primaryGroupID === false) {
550
+                $this->access->connection->hasPrimaryGroups = false;
551
+            }
552
+        }
553
+        return $primaryGroupID;
554
+    }
555
+
556
+    /**
557
+     * returns a filter for a "users in primary group" search or count operation
558
+     *
559
+     * @param string $groupDN
560
+     * @param string $search
561
+     * @return string
562
+     * @throws \Exception
563
+     */
564
+    private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
565
+        $groupID = $this->getGroupPrimaryGroupID($groupDN);
566
+        if($groupID === false) {
567
+            throw new \Exception('Not a valid group');
568
+        }
569
+
570
+        $filterParts = [];
571
+        $filterParts[] = $this->access->getFilterForUserCount();
572
+        if ($search !== '') {
573
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
574
+        }
575
+        $filterParts[] = 'primaryGroupID=' . $groupID;
576
+
577
+        return $this->access->combineFilterWithAnd($filterParts);
578
+    }
579
+
580
+    /**
581
+     * returns a list of users that have the given group as primary group
582
+     *
583
+     * @param string $groupDN
584
+     * @param string $search
585
+     * @param int $limit
586
+     * @param int $offset
587
+     * @return string[]
588
+     */
589
+    public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
590
+        try {
591
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
592
+            $users = $this->access->fetchListOfUsers(
593
+                $filter,
594
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
595
+                $limit,
596
+                $offset
597
+            );
598
+            return $this->access->nextcloudUserNames($users);
599
+        } catch (\Exception $e) {
600
+            return [];
601
+        }
602
+    }
603
+
604
+    /**
605
+     * returns the number of users that have the given group as primary group
606
+     *
607
+     * @param string $groupDN
608
+     * @param string $search
609
+     * @param int $limit
610
+     * @param int $offset
611
+     * @return int
612
+     */
613
+    public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
614
+        try {
615
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
616
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
617
+            return (int)$users;
618
+        } catch (\Exception $e) {
619
+            return 0;
620
+        }
621
+    }
622
+
623
+    /**
624
+     * gets the primary group of a user
625
+     * @param string $dn
626
+     * @return string
627
+     */
628
+    public function getUserPrimaryGroup($dn) {
629
+        $groupID = $this->getUserPrimaryGroupIDs($dn);
630
+        if($groupID !== false) {
631
+            $groupName = $this->primaryGroupID2Name($groupID, $dn);
632
+            if($groupName !== false) {
633
+                return $groupName;
634
+            }
635
+        }
636
+
637
+        return false;
638
+    }
639
+
640
+    /**
641
+     * Get all groups a user belongs to
642
+     * @param string $uid Name of the user
643
+     * @return array with group names
644
+     *
645
+     * This function fetches all groups a user belongs to. It does not check
646
+     * if the user exists at all.
647
+     *
648
+     * This function includes groups based on dynamic group membership.
649
+     */
650
+    public function getUserGroups($uid) {
651
+        if(!$this->enabled) {
652
+            return [];
653
+        }
654
+        $cacheKey = 'getUserGroups'.$uid;
655
+        $userGroups = $this->access->connection->getFromCache($cacheKey);
656
+        if(!is_null($userGroups)) {
657
+            return $userGroups;
658
+        }
659
+        $userDN = $this->access->username2dn($uid);
660
+        if(!$userDN) {
661
+            $this->access->connection->writeToCache($cacheKey, []);
662
+            return [];
663
+        }
664
+
665
+        $groups = [];
666
+        $primaryGroup = $this->getUserPrimaryGroup($userDN);
667
+        $gidGroupName = $this->getUserGroupByGid($userDN);
668
+
669
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
670
+
671
+        if (!empty($dynamicGroupMemberURL)) {
672
+            // look through dynamic groups to add them to the result array if needed
673
+            $groupsToMatch = $this->access->fetchListOfGroups(
674
+                $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
675
+            foreach($groupsToMatch as $dynamicGroup) {
676
+                if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
677
+                    continue;
678
+                }
679
+                $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
680
+                if ($pos !== false) {
681
+                    $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
682
+                    // apply filter via ldap search to see if this user is in this
683
+                    // dynamic group
684
+                    $userMatch = $this->access->readAttribute(
685
+                        $userDN,
686
+                        $this->access->connection->ldapUserDisplayName,
687
+                        $memberUrlFilter
688
+                    );
689
+                    if ($userMatch !== false) {
690
+                        // match found so this user is in this group
691
+                        $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
692
+                        if(is_string($groupName)) {
693
+                            // be sure to never return false if the dn could not be
694
+                            // resolved to a name, for whatever reason.
695
+                            $groups[] = $groupName;
696
+                        }
697
+                    }
698
+                } else {
699
+                    \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
700
+                        'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
701
+                }
702
+            }
703
+        }
704
+
705
+        // if possible, read out membership via memberOf. It's far faster than
706
+        // performing a search, which still is a fallback later.
707
+        // memberof doesn't support memberuid, so skip it here.
708
+        if((int)$this->access->connection->hasMemberOfFilterSupport === 1
709
+            && (int)$this->access->connection->useMemberOfToDetectMembership === 1
710
+            && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
711
+            ) {
712
+            $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
713
+            if (is_array($groupDNs)) {
714
+                foreach ($groupDNs as $dn) {
715
+                    $groupName = $this->access->dn2groupname($dn);
716
+                    if(is_string($groupName)) {
717
+                        // be sure to never return false if the dn could not be
718
+                        // resolved to a name, for whatever reason.
719
+                        $groups[] = $groupName;
720
+                    }
721
+                }
722
+            }
723
+
724
+            if($primaryGroup !== false) {
725
+                $groups[] = $primaryGroup;
726
+            }
727
+            if($gidGroupName !== false) {
728
+                $groups[] = $gidGroupName;
729
+            }
730
+            $this->access->connection->writeToCache($cacheKey, $groups);
731
+            return $groups;
732
+        }
733
+
734
+        //uniqueMember takes DN, memberuid the uid, so we need to distinguish
735
+        if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
736
+            || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
737
+        ) {
738
+            $uid = $userDN;
739
+        } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
740
+            $result = $this->access->readAttribute($userDN, 'uid');
741
+            if ($result === false) {
742
+                \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
743
+                    $this->access->connection->ldapHost, ILogger::DEBUG);
744
+                $uid = false;
745
+            } else {
746
+                $uid = $result[0];
747
+            }
748
+        } else {
749
+            // just in case
750
+            $uid = $userDN;
751
+        }
752
+
753
+        if($uid !== false) {
754
+            if (isset($this->cachedGroupsByMember[$uid])) {
755
+                $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
756
+            } else {
757
+                $groupsByMember = array_values($this->getGroupsByMember($uid));
758
+                $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
759
+                $this->cachedGroupsByMember[$uid] = $groupsByMember;
760
+                $groups = array_merge($groups, $groupsByMember);
761
+            }
762
+        }
763
+
764
+        if($primaryGroup !== false) {
765
+            $groups[] = $primaryGroup;
766
+        }
767
+        if($gidGroupName !== false) {
768
+            $groups[] = $gidGroupName;
769
+        }
770
+
771
+        $groups = array_unique($groups, SORT_LOCALE_STRING);
772
+        $this->access->connection->writeToCache($cacheKey, $groups);
773
+
774
+        return $groups;
775
+    }
776
+
777
+    /**
778
+     * @param string $dn
779
+     * @param array|null &$seen
780
+     * @return array
781
+     */
782
+    private function getGroupsByMember($dn, &$seen = null) {
783
+        if ($seen === null) {
784
+            $seen = [];
785
+        }
786
+        if (array_key_exists($dn, $seen)) {
787
+            // avoid loops
788
+            return [];
789
+        }
790
+        $allGroups = [];
791
+        $seen[$dn] = true;
792
+        $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn;
793
+        $groups = $this->access->fetchListOfGroups($filter,
794
+            [$this->access->connection->ldapGroupDisplayName, 'dn']);
795
+        if (is_array($groups)) {
796
+            $fetcher = function ($dn, &$seen) {
797
+                if(is_array($dn) && isset($dn['dn'][0])) {
798
+                    $dn = $dn['dn'][0];
799
+                }
800
+                return $this->getGroupsByMember($dn, $seen);
801
+            };
802
+            $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups);
803
+        }
804
+        $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups));
805
+        return array_intersect_key($allGroups, array_flip($visibleGroups));
806
+    }
807
+
808
+    /**
809
+     * get a list of all users in a group
810
+     *
811
+     * @param string $gid
812
+     * @param string $search
813
+     * @param int $limit
814
+     * @param int $offset
815
+     * @return array with user ids
816
+     * @throws \Exception
817
+     */
818
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
819
+        if(!$this->enabled) {
820
+            return [];
821
+        }
822
+        if(!$this->groupExists($gid)) {
823
+            return [];
824
+        }
825
+        $search = $this->access->escapeFilterPart($search, true);
826
+        $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
827
+        // check for cache of the exact query
828
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
829
+        if(!is_null($groupUsers)) {
830
+            return $groupUsers;
831
+        }
832
+
833
+        // check for cache of the query without limit and offset
834
+        $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
835
+        if(!is_null($groupUsers)) {
836
+            $groupUsers = array_slice($groupUsers, $offset, $limit);
837
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
838
+            return $groupUsers;
839
+        }
840
+
841
+        if($limit === -1) {
842
+            $limit = null;
843
+        }
844
+        $groupDN = $this->access->groupname2dn($gid);
845
+        if(!$groupDN) {
846
+            // group couldn't be found, return empty resultset
847
+            $this->access->connection->writeToCache($cacheKey, []);
848
+            return [];
849
+        }
850
+
851
+        $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
852
+        $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
853
+        $members = $this->_groupMembers($groupDN);
854
+        if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
855
+            //in case users could not be retrieved, return empty result set
856
+            $this->access->connection->writeToCache($cacheKey, []);
857
+            return [];
858
+        }
859
+
860
+        $groupUsers = [];
861
+        $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
862
+        $attrs = $this->access->userManager->getAttributes(true);
863
+        foreach($members as $member) {
864
+            if($isMemberUid) {
865
+                //we got uids, need to get their DNs to 'translate' them to user names
866
+                $filter = $this->access->combineFilterWithAnd([
867
+                    str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
868
+                    $this->access->combineFilterWithAnd([
869
+                        $this->access->getFilterPartForUserSearch($search),
870
+                        $this->access->connection->ldapUserFilter
871
+                    ])
872
+                ]);
873
+                $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
874
+                if(count($ldap_users) < 1) {
875
+                    continue;
876
+                }
877
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
878
+            } else {
879
+                //we got DNs, check if we need to filter by search or we can give back all of them
880
+                $uid = $this->access->dn2username($member);
881
+                if(!$uid) {
882
+                    continue;
883
+                }
884
+
885
+                $cacheKey = 'userExistsOnLDAP' . $uid;
886
+                $userExists = $this->access->connection->getFromCache($cacheKey);
887
+                if($userExists === false) {
888
+                    continue;
889
+                }
890
+                if($userExists === null || $search !== '') {
891
+                    if (!$this->access->readAttribute($member,
892
+                        $this->access->connection->ldapUserDisplayName,
893
+                        $this->access->combineFilterWithAnd([
894
+                            $this->access->getFilterPartForUserSearch($search),
895
+                            $this->access->connection->ldapUserFilter
896
+                        ])))
897
+                    {
898
+                        if($search === '') {
899
+                            $this->access->connection->writeToCache($cacheKey, false);
900
+                        }
901
+                        continue;
902
+                    }
903
+                    $this->access->connection->writeToCache($cacheKey, true);
904
+                }
905
+                $groupUsers[] = $uid;
906
+            }
907
+        }
908
+
909
+        $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
910
+        natsort($groupUsers);
911
+        $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
912
+        $groupUsers = array_slice($groupUsers, $offset, $limit);
913
+
914
+        $this->access->connection->writeToCache($cacheKey, $groupUsers);
915
+
916
+        return $groupUsers;
917
+    }
918
+
919
+    /**
920
+     * returns the number of users in a group, who match the search term
921
+     * @param string $gid the internal group name
922
+     * @param string $search optional, a search string
923
+     * @return int|bool
924
+     */
925
+    public function countUsersInGroup($gid, $search = '') {
926
+        if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
927
+            return $this->groupPluginManager->countUsersInGroup($gid, $search);
928
+        }
929
+
930
+        $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
931
+        if(!$this->enabled || !$this->groupExists($gid)) {
932
+            return false;
933
+        }
934
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
935
+        if(!is_null($groupUsers)) {
936
+            return $groupUsers;
937
+        }
938
+
939
+        $groupDN = $this->access->groupname2dn($gid);
940
+        if(!$groupDN) {
941
+            // group couldn't be found, return empty result set
942
+            $this->access->connection->writeToCache($cacheKey, false);
943
+            return false;
944
+        }
945
+
946
+        $members = $this->_groupMembers($groupDN);
947
+        $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
948
+        if(!$members && $primaryUserCount === 0) {
949
+            //in case users could not be retrieved, return empty result set
950
+            $this->access->connection->writeToCache($cacheKey, false);
951
+            return false;
952
+        }
953
+
954
+        if ($search === '') {
955
+            $groupUsers = count($members) + $primaryUserCount;
956
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
957
+            return $groupUsers;
958
+        }
959
+        $search = $this->access->escapeFilterPart($search, true);
960
+        $isMemberUid =
961
+            (strtolower($this->access->connection->ldapGroupMemberAssocAttr)
962
+            === 'memberuid');
963
+
964
+        //we need to apply the search filter
965
+        //alternatives that need to be checked:
966
+        //a) get all users by search filter and array_intersect them
967
+        //b) a, but only when less than 1k 10k ?k users like it is
968
+        //c) put all DNs|uids in a LDAP filter, combine with the search string
969
+        //   and let it count.
970
+        //For now this is not important, because the only use of this method
971
+        //does not supply a search string
972
+        $groupUsers = [];
973
+        foreach($members as $member) {
974
+            if($isMemberUid) {
975
+                //we got uids, need to get their DNs to 'translate' them to user names
976
+                $filter = $this->access->combineFilterWithAnd([
977
+                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
978
+                    $this->access->getFilterPartForUserSearch($search)
979
+                ]);
980
+                $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
981
+                if(count($ldap_users) < 1) {
982
+                    continue;
983
+                }
984
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]);
985
+            } else {
986
+                //we need to apply the search filter now
987
+                if(!$this->access->readAttribute($member,
988
+                    $this->access->connection->ldapUserDisplayName,
989
+                    $this->access->getFilterPartForUserSearch($search))) {
990
+                    continue;
991
+                }
992
+                // dn2username will also check if the users belong to the allowed base
993
+                if($ocname = $this->access->dn2username($member)) {
994
+                    $groupUsers[] = $ocname;
995
+                }
996
+            }
997
+        }
998
+
999
+        //and get users that have the group as primary
1000
+        $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
1001
+
1002
+        return count($groupUsers) + $primaryUsers;
1003
+    }
1004
+
1005
+    /**
1006
+     * get a list of all groups
1007
+     *
1008
+     * @param string $search
1009
+     * @param $limit
1010
+     * @param int $offset
1011
+     * @return array with group names
1012
+     *
1013
+     * Returns a list with all groups (used by getGroups)
1014
+     */
1015
+    protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1016
+        if(!$this->enabled) {
1017
+            return [];
1018
+        }
1019
+        $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
1020
+
1021
+        //Check cache before driving unnecessary searches
1022
+        \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1023
+        $ldap_groups = $this->access->connection->getFromCache($cacheKey);
1024
+        if(!is_null($ldap_groups)) {
1025
+            return $ldap_groups;
1026
+        }
1027
+
1028
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
1029
+        // error. With a limit of 0, we get 0 results. So we pass null.
1030
+        if($limit <= 0) {
1031
+            $limit = null;
1032
+        }
1033
+        $filter = $this->access->combineFilterWithAnd([
1034
+            $this->access->connection->ldapGroupFilter,
1035
+            $this->access->getFilterPartForGroupSearch($search)
1036
+        ]);
1037
+        \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
1038
+        $ldap_groups = $this->access->fetchListOfGroups($filter,
1039
+                [$this->access->connection->ldapGroupDisplayName, 'dn'],
1040
+                $limit,
1041
+                $offset);
1042
+        $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
1043
+
1044
+        $this->access->connection->writeToCache($cacheKey, $ldap_groups);
1045
+        return $ldap_groups;
1046
+    }
1047
+
1048
+    /**
1049
+     * get a list of all groups using a paged search
1050
+     *
1051
+     * @param string $search
1052
+     * @param int $limit
1053
+     * @param int $offset
1054
+     * @return array with group names
1055
+     *
1056
+     * Returns a list with all groups
1057
+     * Uses a paged search if available to override a
1058
+     * server side search limit.
1059
+     * (active directory has a limit of 1000 by default)
1060
+     */
1061
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
1062
+        if(!$this->enabled) {
1063
+            return [];
1064
+        }
1065
+        $search = $this->access->escapeFilterPart($search, true);
1066
+        $pagingSize = (int)$this->access->connection->ldapPagingSize;
1067
+        if ($pagingSize <= 0) {
1068
+            return $this->getGroupsChunk($search, $limit, $offset);
1069
+        }
1070
+        $maxGroups = 100000; // limit max results (just for safety reasons)
1071
+        if ($limit > -1) {
1072
+            $overallLimit = min($limit + $offset, $maxGroups);
1073
+        } else {
1074
+            $overallLimit = $maxGroups;
1075
+        }
1076
+        $chunkOffset = $offset;
1077
+        $allGroups = [];
1078
+        while ($chunkOffset < $overallLimit) {
1079
+            $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1080
+            $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1081
+            $nread = count($ldapGroups);
1082
+            \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1083
+            if ($nread) {
1084
+                $allGroups = array_merge($allGroups, $ldapGroups);
1085
+                $chunkOffset += $nread;
1086
+            }
1087
+            if ($nread < $chunkLimit) {
1088
+                break;
1089
+            }
1090
+        }
1091
+        return $allGroups;
1092
+    }
1093
+
1094
+    /**
1095
+     * @param string $group
1096
+     * @return bool
1097
+     */
1098
+    public function groupMatchesFilter($group) {
1099
+        return (strripos($group, $this->groupSearch) !== false);
1100
+    }
1101
+
1102
+    /**
1103
+     * check if a group exists
1104
+     * @param string $gid
1105
+     * @return bool
1106
+     */
1107
+    public function groupExists($gid) {
1108
+        $groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1109
+        if(!is_null($groupExists)) {
1110
+            return (bool)$groupExists;
1111
+        }
1112
+
1113
+        //getting dn, if false the group does not exist. If dn, it may be mapped
1114
+        //only, requires more checking.
1115
+        $dn = $this->access->groupname2dn($gid);
1116
+        if(!$dn) {
1117
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1118
+            return false;
1119
+        }
1120
+
1121
+        //if group really still exists, we will be able to read its objectclass
1122
+        if(!is_array($this->access->readAttribute($dn, ''))) {
1123
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1124
+            return false;
1125
+        }
1126
+
1127
+        $this->access->connection->writeToCache('groupExists'.$gid, true);
1128
+        return true;
1129
+    }
1130
+
1131
+    /**
1132
+     * Check if backend implements actions
1133
+     * @param int $actions bitwise-or'ed actions
1134
+     * @return boolean
1135
+     *
1136
+     * Returns the supported actions as int to be
1137
+     * compared with GroupInterface::CREATE_GROUP etc.
1138
+     */
1139
+    public function implementsActions($actions) {
1140
+        return (bool)((GroupInterface::COUNT_USERS |
1141
+                $this->groupPluginManager->getImplementedActions()) & $actions);
1142
+    }
1143
+
1144
+    /**
1145
+     * Return access for LDAP interaction.
1146
+     * @return Access instance of Access for LDAP interaction
1147
+     */
1148
+    public function getLDAPAccess($gid) {
1149
+        return $this->access;
1150
+    }
1151
+
1152
+    /**
1153
+     * create a group
1154
+     * @param string $gid
1155
+     * @return bool
1156
+     * @throws \Exception
1157
+     */
1158
+    public function createGroup($gid) {
1159
+        if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1160
+            if ($dn = $this->groupPluginManager->createGroup($gid)) {
1161
+                //updates group mapping
1162
+                $uuid = $this->access->getUUID($dn, false);
1163
+                if(is_string($uuid)) {
1164
+                    $this->access->mapAndAnnounceIfApplicable(
1165
+                        $this->access->getGroupMapper(),
1166
+                        $dn,
1167
+                        $gid,
1168
+                        $uuid,
1169
+                        false
1170
+                    );
1171
+                    $this->access->cacheGroupExists($gid);
1172
+                }
1173
+            }
1174
+            return $dn != null;
1175
+        }
1176
+        throw new \Exception('Could not create group in LDAP backend.');
1177
+    }
1178
+
1179
+    /**
1180
+     * delete a group
1181
+     * @param string $gid gid of the group to delete
1182
+     * @return bool
1183
+     * @throws \Exception
1184
+     */
1185
+    public function deleteGroup($gid) {
1186
+        if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1187
+            if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1188
+                #delete group in nextcloud internal db
1189
+                $this->access->getGroupMapper()->unmap($gid);
1190
+                $this->access->connection->writeToCache("groupExists".$gid, false);
1191
+            }
1192
+            return $ret;
1193
+        }
1194
+        throw new \Exception('Could not delete group in LDAP backend.');
1195
+    }
1196
+
1197
+    /**
1198
+     * Add a user to a group
1199
+     * @param string $uid Name of the user to add to group
1200
+     * @param string $gid Name of the group in which add the user
1201
+     * @return bool
1202
+     * @throws \Exception
1203
+     */
1204
+    public function addToGroup($uid, $gid) {
1205
+        if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1206
+            if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1207
+                $this->access->connection->clearCache();
1208
+                unset($this->cachedGroupMembers[$gid]);
1209
+            }
1210
+            return $ret;
1211
+        }
1212
+        throw new \Exception('Could not add user to group in LDAP backend.');
1213
+    }
1214
+
1215
+    /**
1216
+     * Removes a user from a group
1217
+     * @param string $uid Name of the user to remove from group
1218
+     * @param string $gid Name of the group from which remove the user
1219
+     * @return bool
1220
+     * @throws \Exception
1221
+     */
1222
+    public function removeFromGroup($uid, $gid) {
1223
+        if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1224
+            if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1225
+                $this->access->connection->clearCache();
1226
+                unset($this->cachedGroupMembers[$gid]);
1227
+            }
1228
+            return $ret;
1229
+        }
1230
+        throw new \Exception('Could not remove user from group in LDAP backend.');
1231
+    }
1232
+
1233
+    /**
1234
+     * Gets group details
1235
+     * @param string $gid Name of the group
1236
+     * @return array | false
1237
+     * @throws \Exception
1238
+     */
1239
+    public function getGroupDetails($gid) {
1240
+        if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1241
+            return $this->groupPluginManager->getGroupDetails($gid);
1242
+        }
1243
+        throw new \Exception('Could not get group details in LDAP backend.');
1244
+    }
1245
+
1246
+    /**
1247
+     * Return LDAP connection resource from a cloned connection.
1248
+     * The cloned connection needs to be closed manually.
1249
+     * of the current access.
1250
+     * @param string $gid
1251
+     * @return resource of the LDAP connection
1252
+     */
1253
+    public function getNewLDAPConnection($gid) {
1254
+        $connection = clone $this->access->getConnection();
1255
+        return $connection->getConnectionResource();
1256
+    }
1257
+
1258
+    /**
1259
+     * @throws \OC\ServerNotAvailableException
1260
+     */
1261
+    public function getDisplayName(string $gid): string {
1262
+        if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
1263
+            return $this->groupPluginManager->getDisplayName($gid);
1264
+        }
1265
+
1266
+        $cacheKey = 'group_getDisplayName' . $gid;
1267
+        if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1268
+            return $displayName;
1269
+        }
1270
+
1271
+        $displayName = $this->access->readAttribute(
1272
+            $this->access->groupname2dn($gid),
1273
+            $this->access->connection->ldapGroupDisplayName);
1274
+
1275
+        if ($displayName && (count($displayName) > 0)) {
1276
+            $displayName = $displayName[0];
1277
+            $this->access->connection->writeToCache($cacheKey, $displayName);
1278
+            return $displayName;
1279
+        }
1280
+
1281
+        return '';
1282
+    }
1283 1283
 }
Please login to merge, or discard this patch.
Spacing   +103 added lines, -103 removed lines patch added patch discarded remove patch
@@ -73,7 +73,7 @@  discard block
 block discarded – undo
73 73
 		parent::__construct($access);
74 74
 		$filter = $this->access->connection->ldapGroupFilter;
75 75
 		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
76
-		if(!empty($filter) && !empty($gassoc)) {
76
+		if (!empty($filter) && !empty($gassoc)) {
77 77
 			$this->enabled = true;
78 78
 		}
79 79
 
@@ -92,25 +92,25 @@  discard block
 block discarded – undo
92 92
 	 * Checks whether the user is member of a group or not.
93 93
 	 */
94 94
 	public function inGroup($uid, $gid) {
95
-		if(!$this->enabled) {
95
+		if (!$this->enabled) {
96 96
 			return false;
97 97
 		}
98 98
 		$cacheKey = 'inGroup'.$uid.':'.$gid;
99 99
 		$inGroup = $this->access->connection->getFromCache($cacheKey);
100
-		if(!is_null($inGroup)) {
101
-			return (bool)$inGroup;
100
+		if (!is_null($inGroup)) {
101
+			return (bool) $inGroup;
102 102
 		}
103 103
 
104 104
 		$userDN = $this->access->username2dn($uid);
105 105
 
106
-		if(isset($this->cachedGroupMembers[$gid])) {
106
+		if (isset($this->cachedGroupMembers[$gid])) {
107 107
 			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
108 108
 			return $isInGroup;
109 109
 		}
110 110
 
111 111
 		$cacheKeyMembers = 'inGroup-members:'.$gid;
112 112
 		$members = $this->access->connection->getFromCache($cacheKeyMembers);
113
-		if(!is_null($members)) {
113
+		if (!is_null($members)) {
114 114
 			$this->cachedGroupMembers[$gid] = $members;
115 115
 			$isInGroup = in_array($userDN, $members, true);
116 116
 			$this->access->connection->writeToCache($cacheKey, $isInGroup);
@@ -119,34 +119,34 @@  discard block
 block discarded – undo
119 119
 
120 120
 		$groupDN = $this->access->groupname2dn($gid);
121 121
 		// just in case
122
-		if(!$groupDN || !$userDN) {
122
+		if (!$groupDN || !$userDN) {
123 123
 			$this->access->connection->writeToCache($cacheKey, false);
124 124
 			return false;
125 125
 		}
126 126
 
127 127
 		//check primary group first
128
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
128
+		if ($gid === $this->getUserPrimaryGroup($userDN)) {
129 129
 			$this->access->connection->writeToCache($cacheKey, true);
130 130
 			return true;
131 131
 		}
132 132
 
133 133
 		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
134 134
 		$members = $this->_groupMembers($groupDN);
135
-		if(!is_array($members) || count($members) === 0) {
135
+		if (!is_array($members) || count($members) === 0) {
136 136
 			$this->access->connection->writeToCache($cacheKey, false);
137 137
 			return false;
138 138
 		}
139 139
 
140 140
 		//extra work if we don't get back user DNs
141
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
141
+		if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
142 142
 			$dns = [];
143 143
 			$filterParts = [];
144 144
 			$bytes = 0;
145
-			foreach($members as $mid) {
145
+			foreach ($members as $mid) {
146 146
 				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
147 147
 				$filterParts[] = $filter;
148 148
 				$bytes += strlen($filter);
149
-				if($bytes >= 9000000) {
149
+				if ($bytes >= 9000000) {
150 150
 					// AD has a default input buffer of 10 MB, we do not want
151 151
 					// to take even the chance to exceed it
152 152
 					$filter = $this->access->combineFilterWithOr($filterParts);
@@ -156,7 +156,7 @@  discard block
 block discarded – undo
156 156
 					$dns = array_merge($dns, $users);
157 157
 				}
158 158
 			}
159
-			if(count($filterParts) > 0) {
159
+			if (count($filterParts) > 0) {
160 160
 				$filter = $this->access->combineFilterWithOr($filterParts);
161 161
 				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
162 162
 				$dns = array_merge($dns, $users);
@@ -199,14 +199,14 @@  discard block
 block discarded – undo
199 199
 			$pos = strpos($memberURLs[0], '(');
200 200
 			if ($pos !== false) {
201 201
 				$memberUrlFilter = substr($memberURLs[0], $pos);
202
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
202
+				$foundMembers = $this->access->searchUsers($memberUrlFilter, 'dn');
203 203
 				$dynamicMembers = [];
204
-				foreach($foundMembers as $value) {
204
+				foreach ($foundMembers as $value) {
205 205
 					$dynamicMembers[$value['dn'][0]] = 1;
206 206
 				}
207 207
 			} else {
208 208
 				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
209
-					'of group ' . $dnGroup, ILogger::DEBUG);
209
+					'of group '.$dnGroup, ILogger::DEBUG);
210 210
 			}
211 211
 		}
212 212
 		return $dynamicMembers;
@@ -230,13 +230,13 @@  discard block
 block discarded – undo
230 230
 		// used extensively in cron job, caching makes sense for nested groups
231 231
 		$cacheKey = '_groupMembers'.$dnGroup;
232 232
 		$groupMembers = $this->access->connection->getFromCache($cacheKey);
233
-		if($groupMembers !== null) {
233
+		if ($groupMembers !== null) {
234 234
 			return $groupMembers;
235 235
 		}
236 236
 		$seen[$dnGroup] = 1;
237 237
 		$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
238 238
 		if (is_array($members)) {
239
-			$fetcher = function ($memberDN, &$seen) {
239
+			$fetcher = function($memberDN, &$seen) {
240 240
 				return $this->_groupMembers($memberDN, $seen);
241 241
 			};
242 242
 			$allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
@@ -260,7 +260,7 @@  discard block
 block discarded – undo
260 260
 			return [];
261 261
 		}
262 262
 
263
-		$fetcher = function ($groupDN) {
263
+		$fetcher = function($groupDN) {
264 264
 			if (isset($this->cachedNestedGroups[$groupDN])) {
265 265
 				$nestedGroups = $this->cachedNestedGroups[$groupDN];
266 266
 			} else {
@@ -290,10 +290,10 @@  discard block
 block discarded – undo
290 290
 		$recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
291 291
 
292 292
 		if ($nesting !== 1) {
293
-			if($recordMode) {
293
+			if ($recordMode) {
294 294
 				// the keys are numeric, but should hold the DN
295
-				return array_reduce($list, function ($transformed, $record) use ($dn) {
296
-					if($record['dn'][0] != $dn) {
295
+				return array_reduce($list, function($transformed, $record) use ($dn) {
296
+					if ($record['dn'][0] != $dn) {
297 297
 						$transformed[$record['dn'][0]] = $record;
298 298
 					}
299 299
 					return $transformed;
@@ -324,9 +324,9 @@  discard block
 block discarded – undo
324 324
 	 * @return string|bool
325 325
 	 */
326 326
 	public function gidNumber2Name($gid, $dn) {
327
-		$cacheKey = 'gidNumberToName' . $gid;
327
+		$cacheKey = 'gidNumberToName'.$gid;
328 328
 		$groupName = $this->access->connection->getFromCache($cacheKey);
329
-		if(!is_null($groupName) && isset($groupName)) {
329
+		if (!is_null($groupName) && isset($groupName)) {
330 330
 			return $groupName;
331 331
 		}
332 332
 
@@ -334,10 +334,10 @@  discard block
 block discarded – undo
334 334
 		$filter = $this->access->combineFilterWithAnd([
335 335
 			$this->access->connection->ldapGroupFilter,
336 336
 			'objectClass=posixGroup',
337
-			$this->access->connection->ldapGidNumber . '=' . $gid
337
+			$this->access->connection->ldapGidNumber.'='.$gid
338 338
 		]);
339 339
 		$result = $this->access->searchGroups($filter, ['dn'], 1);
340
-		if(empty($result)) {
340
+		if (empty($result)) {
341 341
 			return false;
342 342
 		}
343 343
 		$dn = $result[0]['dn'][0];
@@ -360,7 +360,7 @@  discard block
 block discarded – undo
360 360
 	 */
361 361
 	private function getEntryGidNumber($dn, $attribute) {
362 362
 		$value = $this->access->readAttribute($dn, $attribute);
363
-		if(is_array($value) && !empty($value)) {
363
+		if (is_array($value) && !empty($value)) {
364 364
 			return $value[0];
365 365
 		}
366 366
 		return false;
@@ -382,9 +382,9 @@  discard block
 block discarded – undo
382 382
 	 */
383 383
 	public function getUserGidNumber($dn) {
384 384
 		$gidNumber = false;
385
-		if($this->access->connection->hasGidNumber) {
385
+		if ($this->access->connection->hasGidNumber) {
386 386
 			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
387
-			if($gidNumber === false) {
387
+			if ($gidNumber === false) {
388 388
 				$this->access->connection->hasGidNumber = false;
389 389
 			}
390 390
 		}
@@ -401,7 +401,7 @@  discard block
 block discarded – undo
401 401
 	 */
402 402
 	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
403 403
 		$groupID = $this->getGroupGidNumber($groupDN);
404
-		if($groupID === false) {
404
+		if ($groupID === false) {
405 405
 			throw new \Exception('Not a valid group');
406 406
 		}
407 407
 
@@ -410,7 +410,7 @@  discard block
 block discarded – undo
410 410
 		if ($search !== '') {
411 411
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
412 412
 		}
413
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
413
+		$filterParts[] = $this->access->connection->ldapGidNumber.'='.$groupID;
414 414
 
415 415
 		return $this->access->combineFilterWithAnd($filterParts);
416 416
 	}
@@ -452,7 +452,7 @@  discard block
 block discarded – undo
452 452
 		try {
453 453
 			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
454 454
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
455
-			return (int)$users;
455
+			return (int) $users;
456 456
 		} catch (\Exception $e) {
457 457
 			return 0;
458 458
 		}
@@ -465,9 +465,9 @@  discard block
 block discarded – undo
465 465
 	 */
466 466
 	public function getUserGroupByGid($dn) {
467 467
 		$groupID = $this->getUserGidNumber($dn);
468
-		if($groupID !== false) {
468
+		if ($groupID !== false) {
469 469
 			$groupName = $this->gidNumber2Name($groupID, $dn);
470
-			if($groupName !== false) {
470
+			if ($groupName !== false) {
471 471
 				return $groupName;
472 472
 			}
473 473
 		}
@@ -484,22 +484,22 @@  discard block
 block discarded – undo
484 484
 	public function primaryGroupID2Name($gid, $dn) {
485 485
 		$cacheKey = 'primaryGroupIDtoName';
486 486
 		$groupNames = $this->access->connection->getFromCache($cacheKey);
487
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
487
+		if (!is_null($groupNames) && isset($groupNames[$gid])) {
488 488
 			return $groupNames[$gid];
489 489
 		}
490 490
 
491 491
 		$domainObjectSid = $this->access->getSID($dn);
492
-		if($domainObjectSid === false) {
492
+		if ($domainObjectSid === false) {
493 493
 			return false;
494 494
 		}
495 495
 
496 496
 		//we need to get the DN from LDAP
497 497
 		$filter = $this->access->combineFilterWithAnd([
498 498
 			$this->access->connection->ldapGroupFilter,
499
-			'objectsid=' . $domainObjectSid . '-' . $gid
499
+			'objectsid='.$domainObjectSid.'-'.$gid
500 500
 		]);
501 501
 		$result = $this->access->searchGroups($filter, ['dn'], 1);
502
-		if(empty($result)) {
502
+		if (empty($result)) {
503 503
 			return false;
504 504
 		}
505 505
 		$dn = $result[0]['dn'][0];
@@ -522,7 +522,7 @@  discard block
 block discarded – undo
522 522
 	 */
523 523
 	private function getEntryGroupID($dn, $attribute) {
524 524
 		$value = $this->access->readAttribute($dn, $attribute);
525
-		if(is_array($value) && !empty($value)) {
525
+		if (is_array($value) && !empty($value)) {
526 526
 			return $value[0];
527 527
 		}
528 528
 		return false;
@@ -544,9 +544,9 @@  discard block
 block discarded – undo
544 544
 	 */
545 545
 	public function getUserPrimaryGroupIDs($dn) {
546 546
 		$primaryGroupID = false;
547
-		if($this->access->connection->hasPrimaryGroups) {
547
+		if ($this->access->connection->hasPrimaryGroups) {
548 548
 			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
549
-			if($primaryGroupID === false) {
549
+			if ($primaryGroupID === false) {
550 550
 				$this->access->connection->hasPrimaryGroups = false;
551 551
 			}
552 552
 		}
@@ -563,7 +563,7 @@  discard block
 block discarded – undo
563 563
 	 */
564 564
 	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
565 565
 		$groupID = $this->getGroupPrimaryGroupID($groupDN);
566
-		if($groupID === false) {
566
+		if ($groupID === false) {
567 567
 			throw new \Exception('Not a valid group');
568 568
 		}
569 569
 
@@ -572,7 +572,7 @@  discard block
 block discarded – undo
572 572
 		if ($search !== '') {
573 573
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
574 574
 		}
575
-		$filterParts[] = 'primaryGroupID=' . $groupID;
575
+		$filterParts[] = 'primaryGroupID='.$groupID;
576 576
 
577 577
 		return $this->access->combineFilterWithAnd($filterParts);
578 578
 	}
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 		try {
615 615
 			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
616 616
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
617
-			return (int)$users;
617
+			return (int) $users;
618 618
 		} catch (\Exception $e) {
619 619
 			return 0;
620 620
 		}
@@ -627,9 +627,9 @@  discard block
 block discarded – undo
627 627
 	 */
628 628
 	public function getUserPrimaryGroup($dn) {
629 629
 		$groupID = $this->getUserPrimaryGroupIDs($dn);
630
-		if($groupID !== false) {
630
+		if ($groupID !== false) {
631 631
 			$groupName = $this->primaryGroupID2Name($groupID, $dn);
632
-			if($groupName !== false) {
632
+			if ($groupName !== false) {
633 633
 				return $groupName;
634 634
 			}
635 635
 		}
@@ -648,16 +648,16 @@  discard block
 block discarded – undo
648 648
 	 * This function includes groups based on dynamic group membership.
649 649
 	 */
650 650
 	public function getUserGroups($uid) {
651
-		if(!$this->enabled) {
651
+		if (!$this->enabled) {
652 652
 			return [];
653 653
 		}
654 654
 		$cacheKey = 'getUserGroups'.$uid;
655 655
 		$userGroups = $this->access->connection->getFromCache($cacheKey);
656
-		if(!is_null($userGroups)) {
656
+		if (!is_null($userGroups)) {
657 657
 			return $userGroups;
658 658
 		}
659 659
 		$userDN = $this->access->username2dn($uid);
660
-		if(!$userDN) {
660
+		if (!$userDN) {
661 661
 			$this->access->connection->writeToCache($cacheKey, []);
662 662
 			return [];
663 663
 		}
@@ -671,14 +671,14 @@  discard block
 block discarded – undo
671 671
 		if (!empty($dynamicGroupMemberURL)) {
672 672
 			// look through dynamic groups to add them to the result array if needed
673 673
 			$groupsToMatch = $this->access->fetchListOfGroups(
674
-				$this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
675
-			foreach($groupsToMatch as $dynamicGroup) {
674
+				$this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
675
+			foreach ($groupsToMatch as $dynamicGroup) {
676 676
 				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
677 677
 					continue;
678 678
 				}
679 679
 				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
680 680
 				if ($pos !== false) {
681
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
681
+					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
682 682
 					// apply filter via ldap search to see if this user is in this
683 683
 					// dynamic group
684 684
 					$userMatch = $this->access->readAttribute(
@@ -689,7 +689,7 @@  discard block
 block discarded – undo
689 689
 					if ($userMatch !== false) {
690 690
 						// match found so this user is in this group
691 691
 						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
692
-						if(is_string($groupName)) {
692
+						if (is_string($groupName)) {
693 693
 							// be sure to never return false if the dn could not be
694 694
 							// resolved to a name, for whatever reason.
695 695
 							$groups[] = $groupName;
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 					}
698 698
 				} else {
699 699
 					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
700
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
700
+						'of group '.print_r($dynamicGroup, true), ILogger::DEBUG);
701 701
 				}
702 702
 			}
703 703
 		}
@@ -705,15 +705,15 @@  discard block
 block discarded – undo
705 705
 		// if possible, read out membership via memberOf. It's far faster than
706 706
 		// performing a search, which still is a fallback later.
707 707
 		// memberof doesn't support memberuid, so skip it here.
708
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
709
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
708
+		if ((int) $this->access->connection->hasMemberOfFilterSupport === 1
709
+			&& (int) $this->access->connection->useMemberOfToDetectMembership === 1
710 710
 			&& strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
711 711
 			) {
712 712
 			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
713 713
 			if (is_array($groupDNs)) {
714 714
 				foreach ($groupDNs as $dn) {
715 715
 					$groupName = $this->access->dn2groupname($dn);
716
-					if(is_string($groupName)) {
716
+					if (is_string($groupName)) {
717 717
 						// be sure to never return false if the dn could not be
718 718
 						// resolved to a name, for whatever reason.
719 719
 						$groups[] = $groupName;
@@ -721,10 +721,10 @@  discard block
 block discarded – undo
721 721
 				}
722 722
 			}
723 723
 
724
-			if($primaryGroup !== false) {
724
+			if ($primaryGroup !== false) {
725 725
 				$groups[] = $primaryGroup;
726 726
 			}
727
-			if($gidGroupName !== false) {
727
+			if ($gidGroupName !== false) {
728 728
 				$groups[] = $gidGroupName;
729 729
 			}
730 730
 			$this->access->connection->writeToCache($cacheKey, $groups);
@@ -732,14 +732,14 @@  discard block
 block discarded – undo
732 732
 		}
733 733
 
734 734
 		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
735
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
735
+		if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
736 736
 			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
737 737
 		) {
738 738
 			$uid = $userDN;
739
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
739
+		} else if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
740 740
 			$result = $this->access->readAttribute($userDN, 'uid');
741 741
 			if ($result === false) {
742
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
742
+				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN '.$userDN.' on '.
743 743
 					$this->access->connection->ldapHost, ILogger::DEBUG);
744 744
 				$uid = false;
745 745
 			} else {
@@ -750,7 +750,7 @@  discard block
 block discarded – undo
750 750
 			$uid = $userDN;
751 751
 		}
752 752
 
753
-		if($uid !== false) {
753
+		if ($uid !== false) {
754 754
 			if (isset($this->cachedGroupsByMember[$uid])) {
755 755
 				$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
756 756
 			} else {
@@ -761,10 +761,10 @@  discard block
 block discarded – undo
761 761
 			}
762 762
 		}
763 763
 
764
-		if($primaryGroup !== false) {
764
+		if ($primaryGroup !== false) {
765 765
 			$groups[] = $primaryGroup;
766 766
 		}
767
-		if($gidGroupName !== false) {
767
+		if ($gidGroupName !== false) {
768 768
 			$groups[] = $gidGroupName;
769 769
 		}
770 770
 
@@ -793,8 +793,8 @@  discard block
 block discarded – undo
793 793
 		$groups = $this->access->fetchListOfGroups($filter,
794 794
 			[$this->access->connection->ldapGroupDisplayName, 'dn']);
795 795
 		if (is_array($groups)) {
796
-			$fetcher = function ($dn, &$seen) {
797
-				if(is_array($dn) && isset($dn['dn'][0])) {
796
+			$fetcher = function($dn, &$seen) {
797
+				if (is_array($dn) && isset($dn['dn'][0])) {
798 798
 					$dn = $dn['dn'][0];
799 799
 				}
800 800
 				return $this->getGroupsByMember($dn, $seen);
@@ -816,33 +816,33 @@  discard block
 block discarded – undo
816 816
 	 * @throws \Exception
817 817
 	 */
818 818
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
819
-		if(!$this->enabled) {
819
+		if (!$this->enabled) {
820 820
 			return [];
821 821
 		}
822
-		if(!$this->groupExists($gid)) {
822
+		if (!$this->groupExists($gid)) {
823 823
 			return [];
824 824
 		}
825 825
 		$search = $this->access->escapeFilterPart($search, true);
826 826
 		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
827 827
 		// check for cache of the exact query
828 828
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
829
-		if(!is_null($groupUsers)) {
829
+		if (!is_null($groupUsers)) {
830 830
 			return $groupUsers;
831 831
 		}
832 832
 
833 833
 		// check for cache of the query without limit and offset
834 834
 		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
835
-		if(!is_null($groupUsers)) {
835
+		if (!is_null($groupUsers)) {
836 836
 			$groupUsers = array_slice($groupUsers, $offset, $limit);
837 837
 			$this->access->connection->writeToCache($cacheKey, $groupUsers);
838 838
 			return $groupUsers;
839 839
 		}
840 840
 
841
-		if($limit === -1) {
841
+		if ($limit === -1) {
842 842
 			$limit = null;
843 843
 		}
844 844
 		$groupDN = $this->access->groupname2dn($gid);
845
-		if(!$groupDN) {
845
+		if (!$groupDN) {
846 846
 			// group couldn't be found, return empty resultset
847 847
 			$this->access->connection->writeToCache($cacheKey, []);
848 848
 			return [];
@@ -851,7 +851,7 @@  discard block
 block discarded – undo
851 851
 		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
852 852
 		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
853 853
 		$members = $this->_groupMembers($groupDN);
854
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
854
+		if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
855 855
 			//in case users could not be retrieved, return empty result set
856 856
 			$this->access->connection->writeToCache($cacheKey, []);
857 857
 			return [];
@@ -860,8 +860,8 @@  discard block
 block discarded – undo
860 860
 		$groupUsers = [];
861 861
 		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
862 862
 		$attrs = $this->access->userManager->getAttributes(true);
863
-		foreach($members as $member) {
864
-			if($isMemberUid) {
863
+		foreach ($members as $member) {
864
+			if ($isMemberUid) {
865 865
 				//we got uids, need to get their DNs to 'translate' them to user names
866 866
 				$filter = $this->access->combineFilterWithAnd([
867 867
 					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
@@ -871,23 +871,23 @@  discard block
 block discarded – undo
871 871
 					])
872 872
 				]);
873 873
 				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
874
-				if(count($ldap_users) < 1) {
874
+				if (count($ldap_users) < 1) {
875 875
 					continue;
876 876
 				}
877 877
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
878 878
 			} else {
879 879
 				//we got DNs, check if we need to filter by search or we can give back all of them
880 880
 				$uid = $this->access->dn2username($member);
881
-				if(!$uid) {
881
+				if (!$uid) {
882 882
 					continue;
883 883
 				}
884 884
 
885
-				$cacheKey = 'userExistsOnLDAP' . $uid;
885
+				$cacheKey = 'userExistsOnLDAP'.$uid;
886 886
 				$userExists = $this->access->connection->getFromCache($cacheKey);
887
-				if($userExists === false) {
887
+				if ($userExists === false) {
888 888
 					continue;
889 889
 				}
890
-				if($userExists === null || $search !== '') {
890
+				if ($userExists === null || $search !== '') {
891 891
 					if (!$this->access->readAttribute($member,
892 892
 						$this->access->connection->ldapUserDisplayName,
893 893
 						$this->access->combineFilterWithAnd([
@@ -895,7 +895,7 @@  discard block
 block discarded – undo
895 895
 							$this->access->connection->ldapUserFilter
896 896
 						])))
897 897
 					{
898
-						if($search === '') {
898
+						if ($search === '') {
899 899
 							$this->access->connection->writeToCache($cacheKey, false);
900 900
 						}
901 901
 						continue;
@@ -928,16 +928,16 @@  discard block
 block discarded – undo
928 928
 		}
929 929
 
930 930
 		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
931
-		if(!$this->enabled || !$this->groupExists($gid)) {
931
+		if (!$this->enabled || !$this->groupExists($gid)) {
932 932
 			return false;
933 933
 		}
934 934
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
935
-		if(!is_null($groupUsers)) {
935
+		if (!is_null($groupUsers)) {
936 936
 			return $groupUsers;
937 937
 		}
938 938
 
939 939
 		$groupDN = $this->access->groupname2dn($gid);
940
-		if(!$groupDN) {
940
+		if (!$groupDN) {
941 941
 			// group couldn't be found, return empty result set
942 942
 			$this->access->connection->writeToCache($cacheKey, false);
943 943
 			return false;
@@ -945,7 +945,7 @@  discard block
 block discarded – undo
945 945
 
946 946
 		$members = $this->_groupMembers($groupDN);
947 947
 		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
948
-		if(!$members && $primaryUserCount === 0) {
948
+		if (!$members && $primaryUserCount === 0) {
949 949
 			//in case users could not be retrieved, return empty result set
950 950
 			$this->access->connection->writeToCache($cacheKey, false);
951 951
 			return false;
@@ -970,27 +970,27 @@  discard block
 block discarded – undo
970 970
 		//For now this is not important, because the only use of this method
971 971
 		//does not supply a search string
972 972
 		$groupUsers = [];
973
-		foreach($members as $member) {
974
-			if($isMemberUid) {
973
+		foreach ($members as $member) {
974
+			if ($isMemberUid) {
975 975
 				//we got uids, need to get their DNs to 'translate' them to user names
976 976
 				$filter = $this->access->combineFilterWithAnd([
977 977
 					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
978 978
 					$this->access->getFilterPartForUserSearch($search)
979 979
 				]);
980 980
 				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
981
-				if(count($ldap_users) < 1) {
981
+				if (count($ldap_users) < 1) {
982 982
 					continue;
983 983
 				}
984 984
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
985 985
 			} else {
986 986
 				//we need to apply the search filter now
987
-				if(!$this->access->readAttribute($member,
987
+				if (!$this->access->readAttribute($member,
988 988
 					$this->access->connection->ldapUserDisplayName,
989 989
 					$this->access->getFilterPartForUserSearch($search))) {
990 990
 					continue;
991 991
 				}
992 992
 				// dn2username will also check if the users belong to the allowed base
993
-				if($ocname = $this->access->dn2username($member)) {
993
+				if ($ocname = $this->access->dn2username($member)) {
994 994
 					$groupUsers[] = $ocname;
995 995
 				}
996 996
 			}
@@ -1013,7 +1013,7 @@  discard block
 block discarded – undo
1013 1013
 	 * Returns a list with all groups (used by getGroups)
1014 1014
 	 */
1015 1015
 	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1016
-		if(!$this->enabled) {
1016
+		if (!$this->enabled) {
1017 1017
 			return [];
1018 1018
 		}
1019 1019
 		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
@@ -1021,13 +1021,13 @@  discard block
 block discarded – undo
1021 1021
 		//Check cache before driving unnecessary searches
1022 1022
 		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1023 1023
 		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
1024
-		if(!is_null($ldap_groups)) {
1024
+		if (!is_null($ldap_groups)) {
1025 1025
 			return $ldap_groups;
1026 1026
 		}
1027 1027
 
1028 1028
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
1029 1029
 		// error. With a limit of 0, we get 0 results. So we pass null.
1030
-		if($limit <= 0) {
1030
+		if ($limit <= 0) {
1031 1031
 			$limit = null;
1032 1032
 		}
1033 1033
 		$filter = $this->access->combineFilterWithAnd([
@@ -1059,11 +1059,11 @@  discard block
 block discarded – undo
1059 1059
 	 * (active directory has a limit of 1000 by default)
1060 1060
 	 */
1061 1061
 	public function getGroups($search = '', $limit = -1, $offset = 0) {
1062
-		if(!$this->enabled) {
1062
+		if (!$this->enabled) {
1063 1063
 			return [];
1064 1064
 		}
1065 1065
 		$search = $this->access->escapeFilterPart($search, true);
1066
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1066
+		$pagingSize = (int) $this->access->connection->ldapPagingSize;
1067 1067
 		if ($pagingSize <= 0) {
1068 1068
 			return $this->getGroupsChunk($search, $limit, $offset);
1069 1069
 		}
@@ -1106,20 +1106,20 @@  discard block
 block discarded – undo
1106 1106
 	 */
1107 1107
 	public function groupExists($gid) {
1108 1108
 		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1109
-		if(!is_null($groupExists)) {
1110
-			return (bool)$groupExists;
1109
+		if (!is_null($groupExists)) {
1110
+			return (bool) $groupExists;
1111 1111
 		}
1112 1112
 
1113 1113
 		//getting dn, if false the group does not exist. If dn, it may be mapped
1114 1114
 		//only, requires more checking.
1115 1115
 		$dn = $this->access->groupname2dn($gid);
1116
-		if(!$dn) {
1116
+		if (!$dn) {
1117 1117
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1118 1118
 			return false;
1119 1119
 		}
1120 1120
 
1121 1121
 		//if group really still exists, we will be able to read its objectclass
1122
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1122
+		if (!is_array($this->access->readAttribute($dn, ''))) {
1123 1123
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1124 1124
 			return false;
1125 1125
 		}
@@ -1137,7 +1137,7 @@  discard block
 block discarded – undo
1137 1137
 	 * compared with GroupInterface::CREATE_GROUP etc.
1138 1138
 	 */
1139 1139
 	public function implementsActions($actions) {
1140
-		return (bool)((GroupInterface::COUNT_USERS |
1140
+		return (bool) ((GroupInterface::COUNT_USERS |
1141 1141
 				$this->groupPluginManager->getImplementedActions()) & $actions);
1142 1142
 	}
1143 1143
 
@@ -1160,7 +1160,7 @@  discard block
 block discarded – undo
1160 1160
 			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1161 1161
 				//updates group mapping
1162 1162
 				$uuid = $this->access->getUUID($dn, false);
1163
-				if(is_string($uuid)) {
1163
+				if (is_string($uuid)) {
1164 1164
 					$this->access->mapAndAnnounceIfApplicable(
1165 1165
 						$this->access->getGroupMapper(),
1166 1166
 						$dn,
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
 			return $this->groupPluginManager->getDisplayName($gid);
1264 1264
 		}
1265 1265
 
1266
-		$cacheKey = 'group_getDisplayName' . $gid;
1266
+		$cacheKey = 'group_getDisplayName'.$gid;
1267 1267
 		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1268 1268
 			return $displayName;
1269 1269
 		}
Please login to merge, or discard this patch.