Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/user_ldap/lib/Mapping/AbstractMapping.php 2 patches
Indentation   +239 added lines, -239 removed lines patch added patch discarded remove patch
@@ -30,293 +30,293 @@
 block discarded – undo
30 30
 * @package OCA\User_LDAP\Mapping
31 31
 */
32 32
 abstract class AbstractMapping {
33
-	/**
34
-	 * @var \OCP\IDBConnection $dbc
35
-	 */
36
-	protected $dbc;
33
+    /**
34
+     * @var \OCP\IDBConnection $dbc
35
+     */
36
+    protected $dbc;
37 37
 
38
-	/**
39
-	 * returns the DB table name which holds the mappings
40
-	 * @return string
41
-	 */
42
-	abstract protected function getTableName();
38
+    /**
39
+     * returns the DB table name which holds the mappings
40
+     * @return string
41
+     */
42
+    abstract protected function getTableName();
43 43
 
44
-	/**
45
-	 * @param \OCP\IDBConnection $dbc
46
-	 */
47
-	public function __construct(\OCP\IDBConnection $dbc) {
48
-		$this->dbc = $dbc;
49
-	}
44
+    /**
45
+     * @param \OCP\IDBConnection $dbc
46
+     */
47
+    public function __construct(\OCP\IDBConnection $dbc) {
48
+        $this->dbc = $dbc;
49
+    }
50 50
 
51
-	/**
52
-	 * checks whether a provided string represents an existing table col
53
-	 * @param string $col
54
-	 * @return bool
55
-	 */
56
-	public function isColNameValid($col) {
57
-		switch($col) {
58
-			case 'ldap_dn':
59
-			case 'owncloud_name':
60
-			case 'directory_uuid':
61
-				return true;
62
-			default:
63
-				return false;
64
-		}
65
-	}
51
+    /**
52
+     * checks whether a provided string represents an existing table col
53
+     * @param string $col
54
+     * @return bool
55
+     */
56
+    public function isColNameValid($col) {
57
+        switch($col) {
58
+            case 'ldap_dn':
59
+            case 'owncloud_name':
60
+            case 'directory_uuid':
61
+                return true;
62
+            default:
63
+                return false;
64
+        }
65
+    }
66 66
 
67
-	/**
68
-	 * Gets the value of one column based on a provided value of another column
69
-	 * @param string $fetchCol
70
-	 * @param string $compareCol
71
-	 * @param string $search
72
-	 * @throws \Exception
73
-	 * @return string|false
74
-	 */
75
-	protected function getXbyY($fetchCol, $compareCol, $search) {
76
-		if(!$this->isColNameValid($fetchCol)) {
77
-			//this is used internally only, but we don't want to risk
78
-			//having SQL injection at all.
79
-			throw new \Exception('Invalid Column Name');
80
-		}
81
-		$query = $this->dbc->prepare('
67
+    /**
68
+     * Gets the value of one column based on a provided value of another column
69
+     * @param string $fetchCol
70
+     * @param string $compareCol
71
+     * @param string $search
72
+     * @throws \Exception
73
+     * @return string|false
74
+     */
75
+    protected function getXbyY($fetchCol, $compareCol, $search) {
76
+        if(!$this->isColNameValid($fetchCol)) {
77
+            //this is used internally only, but we don't want to risk
78
+            //having SQL injection at all.
79
+            throw new \Exception('Invalid Column Name');
80
+        }
81
+        $query = $this->dbc->prepare('
82 82
 			SELECT `' . $fetchCol . '`
83 83
 			FROM `'. $this->getTableName() .'`
84 84
 			WHERE `' . $compareCol . '` = ?
85 85
 		');
86 86
 
87
-		$res = $query->execute([$search]);
88
-		if($res !== false) {
89
-			return $query->fetchColumn();
90
-		}
87
+        $res = $query->execute([$search]);
88
+        if($res !== false) {
89
+            return $query->fetchColumn();
90
+        }
91 91
 
92
-		return false;
93
-	}
92
+        return false;
93
+    }
94 94
 
95
-	/**
96
-	 * Performs a DELETE or UPDATE query to the database.
97
-	 * @param \Doctrine\DBAL\Driver\Statement $query
98
-	 * @param array $parameters
99
-	 * @return bool true if at least one row was modified, false otherwise
100
-	 */
101
-	protected function modify($query, $parameters) {
102
-		$result = $query->execute($parameters);
103
-		return ($result === true && $query->rowCount() > 0);
104
-	}
95
+    /**
96
+     * Performs a DELETE or UPDATE query to the database.
97
+     * @param \Doctrine\DBAL\Driver\Statement $query
98
+     * @param array $parameters
99
+     * @return bool true if at least one row was modified, false otherwise
100
+     */
101
+    protected function modify($query, $parameters) {
102
+        $result = $query->execute($parameters);
103
+        return ($result === true && $query->rowCount() > 0);
104
+    }
105 105
 
106
-	/**
107
-	 * Gets the LDAP DN based on the provided name.
108
-	 * Replaces Access::ocname2dn
109
-	 * @param string $name
110
-	 * @return string|false
111
-	 */
112
-	public function getDNByName($name) {
113
-		return $this->getXbyY('ldap_dn', 'owncloud_name', $name);
114
-	}
106
+    /**
107
+     * Gets the LDAP DN based on the provided name.
108
+     * Replaces Access::ocname2dn
109
+     * @param string $name
110
+     * @return string|false
111
+     */
112
+    public function getDNByName($name) {
113
+        return $this->getXbyY('ldap_dn', 'owncloud_name', $name);
114
+    }
115 115
 
116
-	/**
117
-	 * Updates the DN based on the given UUID
118
-	 * @param string $fdn
119
-	 * @param string $uuid
120
-	 * @return bool
121
-	 */
122
-	public function setDNbyUUID($fdn, $uuid) {
123
-		$query = $this->dbc->prepare('
116
+    /**
117
+     * Updates the DN based on the given UUID
118
+     * @param string $fdn
119
+     * @param string $uuid
120
+     * @return bool
121
+     */
122
+    public function setDNbyUUID($fdn, $uuid) {
123
+        $query = $this->dbc->prepare('
124 124
 			UPDATE `' . $this->getTableName() . '`
125 125
 			SET `ldap_dn` = ?
126 126
 			WHERE `directory_uuid` = ?
127 127
 		');
128 128
 
129
-		return $this->modify($query, [$fdn, $uuid]);
130
-	}
129
+        return $this->modify($query, [$fdn, $uuid]);
130
+    }
131 131
 
132
-	/**
133
-	 * Updates the UUID based on the given DN
134
-	 *
135
-	 * required by Migration/UUIDFix
136
-	 *
137
-	 * @param $uuid
138
-	 * @param $fdn
139
-	 * @return bool
140
-	 */
141
-	public function setUUIDbyDN($uuid, $fdn) {
142
-		$query = $this->dbc->prepare('
132
+    /**
133
+     * Updates the UUID based on the given DN
134
+     *
135
+     * required by Migration/UUIDFix
136
+     *
137
+     * @param $uuid
138
+     * @param $fdn
139
+     * @return bool
140
+     */
141
+    public function setUUIDbyDN($uuid, $fdn) {
142
+        $query = $this->dbc->prepare('
143 143
 			UPDATE `' . $this->getTableName() . '`
144 144
 			SET `directory_uuid` = ?
145 145
 			WHERE `ldap_dn` = ?
146 146
 		');
147 147
 
148
-		return $this->modify($query, [$uuid, $fdn]);
149
-	}
148
+        return $this->modify($query, [$uuid, $fdn]);
149
+    }
150 150
 
151
-	/**
152
-	 * Gets the name based on the provided LDAP DN.
153
-	 * @param string $fdn
154
-	 * @return string|false
155
-	 */
156
-	public function getNameByDN($fdn) {
157
-		return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn);
158
-	}
151
+    /**
152
+     * Gets the name based on the provided LDAP DN.
153
+     * @param string $fdn
154
+     * @return string|false
155
+     */
156
+    public function getNameByDN($fdn) {
157
+        return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn);
158
+    }
159 159
 
160
-	/**
161
-	 * Searches mapped names by the giving string in the name column
162
-	 * @param string $search
163
-	 * @param string $prefixMatch
164
-	 * @param string $postfixMatch
165
-	 * @return string[]
166
-	 */
167
-	public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
168
-		$query = $this->dbc->prepare('
160
+    /**
161
+     * Searches mapped names by the giving string in the name column
162
+     * @param string $search
163
+     * @param string $prefixMatch
164
+     * @param string $postfixMatch
165
+     * @return string[]
166
+     */
167
+    public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
168
+        $query = $this->dbc->prepare('
169 169
 			SELECT `owncloud_name`
170 170
 			FROM `'. $this->getTableName() .'`
171 171
 			WHERE `owncloud_name` LIKE ?
172 172
 		');
173 173
 
174
-		$res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]);
175
-		$names = [];
176
-		if($res !== false) {
177
-			while($row = $query->fetch()) {
178
-				$names[] = $row['owncloud_name'];
179
-			}
180
-		}
181
-		return $names;
182
-	}
174
+        $res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]);
175
+        $names = [];
176
+        if($res !== false) {
177
+            while($row = $query->fetch()) {
178
+                $names[] = $row['owncloud_name'];
179
+            }
180
+        }
181
+        return $names;
182
+    }
183 183
 
184
-	/**
185
-	 * Gets the name based on the provided LDAP UUID.
186
-	 * @param string $uuid
187
-	 * @return string|false
188
-	 */
189
-	public function getNameByUUID($uuid) {
190
-		return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
191
-	}
184
+    /**
185
+     * Gets the name based on the provided LDAP UUID.
186
+     * @param string $uuid
187
+     * @return string|false
188
+     */
189
+    public function getNameByUUID($uuid) {
190
+        return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
191
+    }
192 192
 
193
-	/**
194
-	 * Gets the UUID based on the provided LDAP DN
195
-	 * @param string $dn
196
-	 * @return false|string
197
-	 * @throws \Exception
198
-	 */
199
-	public function getUUIDByDN($dn) {
200
-		return $this->getXbyY('directory_uuid', 'ldap_dn', $dn);
201
-	}
193
+    /**
194
+     * Gets the UUID based on the provided LDAP DN
195
+     * @param string $dn
196
+     * @return false|string
197
+     * @throws \Exception
198
+     */
199
+    public function getUUIDByDN($dn) {
200
+        return $this->getXbyY('directory_uuid', 'ldap_dn', $dn);
201
+    }
202 202
 
203
-	/**
204
-	 * gets a piece of the mapping list
205
-	 * @param int $offset
206
-	 * @param int $limit
207
-	 * @return array
208
-	 */
209
-	public function getList($offset = null, $limit = null) {
210
-		$query = $this->dbc->prepare('
203
+    /**
204
+     * gets a piece of the mapping list
205
+     * @param int $offset
206
+     * @param int $limit
207
+     * @return array
208
+     */
209
+    public function getList($offset = null, $limit = null) {
210
+        $query = $this->dbc->prepare('
211 211
 			SELECT
212 212
 				`ldap_dn` AS `dn`,
213 213
 				`owncloud_name` AS `name`,
214 214
 				`directory_uuid` AS `uuid`
215 215
 			FROM `' . $this->getTableName() . '`',
216
-			$limit,
217
-			$offset
218
-		);
216
+            $limit,
217
+            $offset
218
+        );
219 219
 
220
-		$query->execute();
221
-		return $query->fetchAll();
222
-	}
220
+        $query->execute();
221
+        return $query->fetchAll();
222
+    }
223 223
 
224
-	/**
225
-	 * attempts to map the given entry
226
-	 * @param string $fdn fully distinguished name (from LDAP)
227
-	 * @param string $name
228
-	 * @param string $uuid a unique identifier as used in LDAP
229
-	 * @return bool
230
-	 */
231
-	public function map($fdn, $name, $uuid) {
232
-		if(mb_strlen($fdn) > 255) {
233
-			\OC::$server->getLogger()->error(
234
-				'Cannot map, because the DN exceeds 255 characters: {dn}',
235
-				[
236
-					'app' => 'user_ldap',
237
-					'dn' => $fdn,
238
-				]
239
-			);
240
-			return false;
241
-		}
224
+    /**
225
+     * attempts to map the given entry
226
+     * @param string $fdn fully distinguished name (from LDAP)
227
+     * @param string $name
228
+     * @param string $uuid a unique identifier as used in LDAP
229
+     * @return bool
230
+     */
231
+    public function map($fdn, $name, $uuid) {
232
+        if(mb_strlen($fdn) > 255) {
233
+            \OC::$server->getLogger()->error(
234
+                'Cannot map, because the DN exceeds 255 characters: {dn}',
235
+                [
236
+                    'app' => 'user_ldap',
237
+                    'dn' => $fdn,
238
+                ]
239
+            );
240
+            return false;
241
+        }
242 242
 
243
-		$row = [
244
-			'ldap_dn'        => $fdn,
245
-			'owncloud_name'  => $name,
246
-			'directory_uuid' => $uuid
247
-		];
243
+        $row = [
244
+            'ldap_dn'        => $fdn,
245
+            'owncloud_name'  => $name,
246
+            'directory_uuid' => $uuid
247
+        ];
248 248
 
249
-		try {
250
-			$result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
251
-			// insertIfNotExist returns values as int
252
-			return (bool)$result;
253
-		} catch (\Exception $e) {
254
-			return false;
255
-		}
256
-	}
249
+        try {
250
+            $result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
251
+            // insertIfNotExist returns values as int
252
+            return (bool)$result;
253
+        } catch (\Exception $e) {
254
+            return false;
255
+        }
256
+    }
257 257
 
258
-	/**
259
-	 * removes a mapping based on the owncloud_name of the entry
260
-	 * @param string $name
261
-	 * @return bool
262
-	 */
263
-	public function unmap($name) {
264
-		$query = $this->dbc->prepare('
258
+    /**
259
+     * removes a mapping based on the owncloud_name of the entry
260
+     * @param string $name
261
+     * @return bool
262
+     */
263
+    public function unmap($name) {
264
+        $query = $this->dbc->prepare('
265 265
 			DELETE FROM `'. $this->getTableName() .'`
266 266
 			WHERE `owncloud_name` = ?');
267 267
 
268
-		return $this->modify($query, [$name]);
269
-	}
268
+        return $this->modify($query, [$name]);
269
+    }
270 270
 
271
-	/**
272
-	 * Truncate's the mapping table
273
-	 * @return bool
274
-	 */
275
-	public function clear() {
276
-		$sql = $this->dbc
277
-			->getDatabasePlatform()
278
-			->getTruncateTableSQL('`' . $this->getTableName() . '`');
279
-		return $this->dbc->prepare($sql)->execute();
280
-	}
271
+    /**
272
+     * Truncate's the mapping table
273
+     * @return bool
274
+     */
275
+    public function clear() {
276
+        $sql = $this->dbc
277
+            ->getDatabasePlatform()
278
+            ->getTruncateTableSQL('`' . $this->getTableName() . '`');
279
+        return $this->dbc->prepare($sql)->execute();
280
+    }
281 281
 
282
-	/**
283
-	 * clears the mapping table one by one and executing a callback with
284
-	 * each row's id (=owncloud_name col)
285
-	 *
286
-	 * @param callable $preCallback
287
-	 * @param callable $postCallback
288
-	 * @return bool true on success, false when at least one row was not
289
-	 * deleted
290
-	 */
291
-	public function clearCb(Callable $preCallback, Callable $postCallback): bool {
292
-		$picker = $this->dbc->getQueryBuilder();
293
-		$picker->select('owncloud_name')
294
-			->from($this->getTableName());
295
-		$cursor = $picker->execute();
296
-		$result = true;
297
-		while($id = $cursor->fetchColumn(0)) {
298
-			$preCallback($id);
299
-			if($isUnmapped = $this->unmap($id)) {
300
-				$postCallback($id);
301
-			}
302
-			$result &= $isUnmapped;
303
-		}
304
-		$cursor->closeCursor();
305
-		return $result;
306
-	}
282
+    /**
283
+     * clears the mapping table one by one and executing a callback with
284
+     * each row's id (=owncloud_name col)
285
+     *
286
+     * @param callable $preCallback
287
+     * @param callable $postCallback
288
+     * @return bool true on success, false when at least one row was not
289
+     * deleted
290
+     */
291
+    public function clearCb(Callable $preCallback, Callable $postCallback): bool {
292
+        $picker = $this->dbc->getQueryBuilder();
293
+        $picker->select('owncloud_name')
294
+            ->from($this->getTableName());
295
+        $cursor = $picker->execute();
296
+        $result = true;
297
+        while($id = $cursor->fetchColumn(0)) {
298
+            $preCallback($id);
299
+            if($isUnmapped = $this->unmap($id)) {
300
+                $postCallback($id);
301
+            }
302
+            $result &= $isUnmapped;
303
+        }
304
+        $cursor->closeCursor();
305
+        return $result;
306
+    }
307 307
 
308
-	/**
309
-	 * returns the number of entries in the mappings table
310
-	 *
311
-	 * @return int
312
-	 */
313
-	public function count() {
314
-		$qb = $this->dbc->getQueryBuilder();
315
-		$query = $qb->select($qb->func()->count('ldap_dn'))
316
-			->from($this->getTableName());
317
-		$res = $query->execute();
318
-		$count = $res->fetchColumn();
319
-		$res->closeCursor();
320
-		return (int)$count;
321
-	}
308
+    /**
309
+     * returns the number of entries in the mappings table
310
+     *
311
+     * @return int
312
+     */
313
+    public function count() {
314
+        $qb = $this->dbc->getQueryBuilder();
315
+        $query = $qb->select($qb->func()->count('ldap_dn'))
316
+            ->from($this->getTableName());
317
+        $res = $query->execute();
318
+        $count = $res->fetchColumn();
319
+        $res->closeCursor();
320
+        return (int)$count;
321
+    }
322 322
 }
Please login to merge, or discard this patch.
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -54,7 +54,7 @@  discard block
 block discarded – undo
54 54
 	 * @return bool
55 55
 	 */
56 56
 	public function isColNameValid($col) {
57
-		switch($col) {
57
+		switch ($col) {
58 58
 			case 'ldap_dn':
59 59
 			case 'owncloud_name':
60 60
 			case 'directory_uuid':
@@ -73,19 +73,19 @@  discard block
 block discarded – undo
73 73
 	 * @return string|false
74 74
 	 */
75 75
 	protected function getXbyY($fetchCol, $compareCol, $search) {
76
-		if(!$this->isColNameValid($fetchCol)) {
76
+		if (!$this->isColNameValid($fetchCol)) {
77 77
 			//this is used internally only, but we don't want to risk
78 78
 			//having SQL injection at all.
79 79
 			throw new \Exception('Invalid Column Name');
80 80
 		}
81 81
 		$query = $this->dbc->prepare('
82
-			SELECT `' . $fetchCol . '`
83
-			FROM `'. $this->getTableName() .'`
84
-			WHERE `' . $compareCol . '` = ?
82
+			SELECT `' . $fetchCol.'`
83
+			FROM `'. $this->getTableName().'`
84
+			WHERE `' . $compareCol.'` = ?
85 85
 		');
86 86
 
87 87
 		$res = $query->execute([$search]);
88
-		if($res !== false) {
88
+		if ($res !== false) {
89 89
 			return $query->fetchColumn();
90 90
 		}
91 91
 
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	 */
122 122
 	public function setDNbyUUID($fdn, $uuid) {
123 123
 		$query = $this->dbc->prepare('
124
-			UPDATE `' . $this->getTableName() . '`
124
+			UPDATE `' . $this->getTableName().'`
125 125
 			SET `ldap_dn` = ?
126 126
 			WHERE `directory_uuid` = ?
127 127
 		');
@@ -140,7 +140,7 @@  discard block
 block discarded – undo
140 140
 	 */
141 141
 	public function setUUIDbyDN($uuid, $fdn) {
142 142
 		$query = $this->dbc->prepare('
143
-			UPDATE `' . $this->getTableName() . '`
143
+			UPDATE `' . $this->getTableName().'`
144 144
 			SET `directory_uuid` = ?
145 145
 			WHERE `ldap_dn` = ?
146 146
 		');
@@ -167,14 +167,14 @@  discard block
 block discarded – undo
167 167
 	public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
168 168
 		$query = $this->dbc->prepare('
169 169
 			SELECT `owncloud_name`
170
-			FROM `'. $this->getTableName() .'`
170
+			FROM `'. $this->getTableName().'`
171 171
 			WHERE `owncloud_name` LIKE ?
172 172
 		');
173 173
 
174 174
 		$res = $query->execute([$prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch]);
175 175
 		$names = [];
176
-		if($res !== false) {
177
-			while($row = $query->fetch()) {
176
+		if ($res !== false) {
177
+			while ($row = $query->fetch()) {
178 178
 				$names[] = $row['owncloud_name'];
179 179
 			}
180 180
 		}
@@ -212,7 +212,7 @@  discard block
 block discarded – undo
212 212
 				`ldap_dn` AS `dn`,
213 213
 				`owncloud_name` AS `name`,
214 214
 				`directory_uuid` AS `uuid`
215
-			FROM `' . $this->getTableName() . '`',
215
+			FROM `' . $this->getTableName().'`',
216 216
 			$limit,
217 217
 			$offset
218 218
 		);
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 	 * @return bool
230 230
 	 */
231 231
 	public function map($fdn, $name, $uuid) {
232
-		if(mb_strlen($fdn) > 255) {
232
+		if (mb_strlen($fdn) > 255) {
233 233
 			\OC::$server->getLogger()->error(
234 234
 				'Cannot map, because the DN exceeds 255 characters: {dn}',
235 235
 				[
@@ -249,7 +249,7 @@  discard block
 block discarded – undo
249 249
 		try {
250 250
 			$result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
251 251
 			// insertIfNotExist returns values as int
252
-			return (bool)$result;
252
+			return (bool) $result;
253 253
 		} catch (\Exception $e) {
254 254
 			return false;
255 255
 		}
@@ -262,7 +262,7 @@  discard block
 block discarded – undo
262 262
 	 */
263 263
 	public function unmap($name) {
264 264
 		$query = $this->dbc->prepare('
265
-			DELETE FROM `'. $this->getTableName() .'`
265
+			DELETE FROM `'. $this->getTableName().'`
266 266
 			WHERE `owncloud_name` = ?');
267 267
 
268 268
 		return $this->modify($query, [$name]);
@@ -275,7 +275,7 @@  discard block
 block discarded – undo
275 275
 	public function clear() {
276 276
 		$sql = $this->dbc
277 277
 			->getDatabasePlatform()
278
-			->getTruncateTableSQL('`' . $this->getTableName() . '`');
278
+			->getTruncateTableSQL('`'.$this->getTableName().'`');
279 279
 		return $this->dbc->prepare($sql)->execute();
280 280
 	}
281 281
 
@@ -294,9 +294,9 @@  discard block
 block discarded – undo
294 294
 			->from($this->getTableName());
295 295
 		$cursor = $picker->execute();
296 296
 		$result = true;
297
-		while($id = $cursor->fetchColumn(0)) {
297
+		while ($id = $cursor->fetchColumn(0)) {
298 298
 			$preCallback($id);
299
-			if($isUnmapped = $this->unmap($id)) {
299
+			if ($isUnmapped = $this->unmap($id)) {
300 300
 				$postCallback($id);
301 301
 			}
302 302
 			$result &= $isUnmapped;
@@ -317,6 +317,6 @@  discard block
 block discarded – undo
317 317
 		$res = $query->execute();
318 318
 		$count = $res->fetchColumn();
319 319
 		$res->closeCursor();
320
-		return (int)$count;
320
+		return (int) $count;
321 321
 	}
322 322
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/LDAP.php 1 patch
Indentation   +357 added lines, -357 removed lines patch added patch discarded remove patch
@@ -34,361 +34,361 @@
 block discarded – undo
34 34
 use OCA\User_LDAP\Exceptions\ConstraintViolationException;
35 35
 
36 36
 class LDAP implements ILDAPWrapper {
37
-	protected $curFunc = '';
38
-	protected $curArgs = [];
39
-
40
-	/**
41
-	 * @param resource $link
42
-	 * @param string $dn
43
-	 * @param string $password
44
-	 * @return bool|mixed
45
-	 */
46
-	public function bind($link, $dn, $password) {
47
-		return $this->invokeLDAPMethod('bind', $link, $dn, $password);
48
-	}
49
-
50
-	/**
51
-	 * @param string $host
52
-	 * @param string $port
53
-	 * @return mixed
54
-	 */
55
-	public function connect($host, $port) {
56
-		if(strpos($host, '://') === false) {
57
-			$host = 'ldap://' . $host;
58
-		}
59
-		if(strpos($host, ':', strpos($host, '://') + 1) === false) {
60
-			//ldap_connect ignores port parameter when URLs are passed
61
-			$host .= ':' . $port;
62
-		}
63
-		return $this->invokeLDAPMethod('connect', $host);
64
-	}
65
-
66
-	/**
67
-	 * @param resource $link
68
-	 * @param resource $result
69
-	 * @param string $cookie
70
-	 * @return bool|LDAP
71
-	 */
72
-	public function controlPagedResultResponse($link, $result, &$cookie) {
73
-		$this->preFunctionCall('ldap_control_paged_result_response',
74
-			[$link, $result, $cookie]);
75
-		$result = ldap_control_paged_result_response($link, $result, $cookie);
76
-		$this->postFunctionCall();
77
-
78
-		return $result;
79
-	}
80
-
81
-	/**
82
-	 * @param LDAP $link
83
-	 * @param int $pageSize
84
-	 * @param bool $isCritical
85
-	 * @param string $cookie
86
-	 * @return mixed|true
87
-	 */
88
-	public function controlPagedResult($link, $pageSize, $isCritical, $cookie) {
89
-		return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize,
90
-										$isCritical, $cookie);
91
-	}
92
-
93
-	/**
94
-	 * @param LDAP $link
95
-	 * @param LDAP $result
96
-	 * @return mixed
97
-	 */
98
-	public function countEntries($link, $result) {
99
-		return $this->invokeLDAPMethod('count_entries', $link, $result);
100
-	}
101
-
102
-	/**
103
-	 * @param LDAP $link
104
-	 * @return integer
105
-	 */
106
-	public function errno($link) {
107
-		return $this->invokeLDAPMethod('errno', $link);
108
-	}
109
-
110
-	/**
111
-	 * @param LDAP $link
112
-	 * @return string
113
-	 */
114
-	public function error($link) {
115
-		return $this->invokeLDAPMethod('error', $link);
116
-	}
117
-
118
-	/**
119
-	 * Splits DN into its component parts
120
-	 * @param string $dn
121
-	 * @param int @withAttrib
122
-	 * @return array|false
123
-	 * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
124
-	 */
125
-	public function explodeDN($dn, $withAttrib) {
126
-		return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
127
-	}
128
-
129
-	/**
130
-	 * @param LDAP $link
131
-	 * @param LDAP $result
132
-	 * @return mixed
133
-	 */
134
-	public function firstEntry($link, $result) {
135
-		return $this->invokeLDAPMethod('first_entry', $link, $result);
136
-	}
137
-
138
-	/**
139
-	 * @param LDAP $link
140
-	 * @param LDAP $result
141
-	 * @return array|mixed
142
-	 */
143
-	public function getAttributes($link, $result) {
144
-		return $this->invokeLDAPMethod('get_attributes', $link, $result);
145
-	}
146
-
147
-	/**
148
-	 * @param LDAP $link
149
-	 * @param LDAP $result
150
-	 * @return mixed|string
151
-	 */
152
-	public function getDN($link, $result) {
153
-		return $this->invokeLDAPMethod('get_dn', $link, $result);
154
-	}
155
-
156
-	/**
157
-	 * @param LDAP $link
158
-	 * @param LDAP $result
159
-	 * @return array|mixed
160
-	 */
161
-	public function getEntries($link, $result) {
162
-		return $this->invokeLDAPMethod('get_entries', $link, $result);
163
-	}
164
-
165
-	/**
166
-	 * @param LDAP $link
167
-	 * @param resource $result
168
-	 * @return mixed
169
-	 */
170
-	public function nextEntry($link, $result) {
171
-		return $this->invokeLDAPMethod('next_entry', $link, $result);
172
-	}
173
-
174
-	/**
175
-	 * @param LDAP $link
176
-	 * @param string $baseDN
177
-	 * @param string $filter
178
-	 * @param array $attr
179
-	 * @return mixed
180
-	 */
181
-	public function read($link, $baseDN, $filter, $attr) {
182
-		return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr);
183
-	}
184
-
185
-	/**
186
-	 * @param LDAP $link
187
-	 * @param string $baseDN
188
-	 * @param string $filter
189
-	 * @param array $attr
190
-	 * @param int $attrsOnly
191
-	 * @param int $limit
192
-	 * @return mixed
193
-	 * @throws \Exception
194
-	 */
195
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
196
-		$oldHandler = set_error_handler(function($no, $message, $file, $line) use (&$oldHandler) {
197
-			if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
198
-				return true;
199
-			}
200
-			$oldHandler($no, $message, $file, $line);
201
-			return true;
202
-		});
203
-		try {
204
-			$result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
205
-			restore_error_handler();
206
-			return $result;
207
-		} catch (\Exception $e) {
208
-			restore_error_handler();
209
-			throw $e;
210
-		}
211
-	}
212
-
213
-	/**
214
-	 * @param LDAP $link
215
-	 * @param string $userDN
216
-	 * @param string $password
217
-	 * @return bool
218
-	 */
219
-	public function modReplace($link, $userDN, $password) {
220
-		return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
221
-	}
222
-
223
-	/**
224
-	 * @param LDAP $link
225
-	 * @param string $userDN
226
-	 * @param string $oldPassword
227
-	 * @param string $password
228
-	 * @return bool
229
-	 */
230
-	public function exopPasswd($link, $userDN, $oldPassword, $password) {
231
-		return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
232
-	}
233
-
234
-	/**
235
-	 * @param LDAP $link
236
-	 * @param string $option
237
-	 * @param int $value
238
-	 * @return bool|mixed
239
-	 */
240
-	public function setOption($link, $option, $value) {
241
-		return $this->invokeLDAPMethod('set_option', $link, $option, $value);
242
-	}
243
-
244
-	/**
245
-	 * @param LDAP $link
246
-	 * @return mixed|true
247
-	 */
248
-	public function startTls($link) {
249
-		return $this->invokeLDAPMethod('start_tls', $link);
250
-	}
251
-
252
-	/**
253
-	 * @param resource $link
254
-	 * @return bool|mixed
255
-	 */
256
-	public function unbind($link) {
257
-		return $this->invokeLDAPMethod('unbind', $link);
258
-	}
259
-
260
-	/**
261
-	 * Checks whether the server supports LDAP
262
-	 * @return boolean if it the case, false otherwise
263
-	 * */
264
-	public function areLDAPFunctionsAvailable() {
265
-		return function_exists('ldap_connect');
266
-	}
267
-
268
-	/**
269
-	 * Checks whether the submitted parameter is a resource
270
-	 * @param Resource $resource the resource variable to check
271
-	 * @return bool true if it is a resource, false otherwise
272
-	 */
273
-	public function isResource($resource) {
274
-		return is_resource($resource);
275
-	}
276
-
277
-	/**
278
-	 * Checks whether the return value from LDAP is wrong or not.
279
-	 *
280
-	 * When using ldap_search we provide an array, in case multiple bases are
281
-	 * configured. Thus, we need to check the array elements.
282
-	 *
283
-	 * @param $result
284
-	 * @return bool
285
-	 */
286
-	protected function isResultFalse($result) {
287
-		if($result === false) {
288
-			return true;
289
-		}
290
-
291
-		if($this->curFunc === 'ldap_search' && is_array($result)) {
292
-			foreach ($result as $singleResult) {
293
-				if($singleResult === false) {
294
-					return true;
295
-				}
296
-			}
297
-		}
298
-
299
-		return false;
300
-	}
301
-
302
-	/**
303
-	 * @return mixed
304
-	 */
305
-	protected function invokeLDAPMethod() {
306
-		$arguments = func_get_args();
307
-		$func = 'ldap_' . array_shift($arguments);
308
-		if(function_exists($func)) {
309
-			$this->preFunctionCall($func, $arguments);
310
-			$result = call_user_func_array($func, $arguments);
311
-			if ($this->isResultFalse($result)) {
312
-				$this->postFunctionCall();
313
-			}
314
-			return $result;
315
-		}
316
-		return null;
317
-	}
318
-
319
-	/**
320
-	 * @param string $functionName
321
-	 * @param array $args
322
-	 */
323
-	private function preFunctionCall($functionName, $args) {
324
-		$this->curFunc = $functionName;
325
-		$this->curArgs = $args;
326
-	}
327
-
328
-	/**
329
-	 * Analyzes the returned LDAP error and acts accordingly if not 0
330
-	 *
331
-	 * @param resource $resource the LDAP Connection resource
332
-	 * @throws ConstraintViolationException
333
-	 * @throws ServerNotAvailableException
334
-	 * @throws \Exception
335
-	 */
336
-	private function processLDAPError($resource) {
337
-		$errorCode = ldap_errno($resource);
338
-		if($errorCode === 0) {
339
-			return;
340
-		}
341
-		$errorMsg  = ldap_error($resource);
342
-
343
-		if($this->curFunc === 'ldap_get_entries'
344
-			&& $errorCode === -4) {
345
-		} else if ($errorCode === 32) {
346
-			//for now
347
-		} else if ($errorCode === 10) {
348
-			//referrals, we switch them off, but then there is AD :)
349
-		} else if ($errorCode === -1) {
350
-			throw new ServerNotAvailableException('Lost connection to LDAP server.');
351
-		} else if ($errorCode === 52) {
352
-			throw new ServerNotAvailableException('LDAP server is shutting down.');
353
-		} else if ($errorCode === 48) {
354
-			throw new \Exception('LDAP authentication method rejected', $errorCode);
355
-		} else if ($errorCode === 1) {
356
-			throw new \Exception('LDAP Operations error', $errorCode);
357
-		} else if ($errorCode === 19) {
358
-			ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
359
-			throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
360
-		} else {
361
-			\OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
362
-				'app' => 'user_ldap',
363
-				'message' => $errorMsg,
364
-				'code' => $errorCode,
365
-				'func' => $this->curFunc,
366
-			]);
367
-		}
368
-	}
369
-
370
-	/**
371
-	 * Called after an ldap method is run to act on LDAP error if necessary
372
-	 * @throw \Exception
373
-	 */
374
-	private function postFunctionCall() {
375
-		if($this->isResource($this->curArgs[0])) {
376
-			$resource = $this->curArgs[0];
377
-		} else if(
378
-			   $this->curFunc === 'ldap_search'
379
-			&& is_array($this->curArgs[0])
380
-			&& $this->isResource($this->curArgs[0][0])
381
-		) {
382
-			// we use always the same LDAP connection resource, is enough to
383
-			// take the first one.
384
-			$resource = $this->curArgs[0][0];
385
-		} else {
386
-			return;
387
-		}
388
-
389
-		$this->processLDAPError($resource);
390
-
391
-		$this->curFunc = '';
392
-		$this->curArgs = [];
393
-	}
37
+    protected $curFunc = '';
38
+    protected $curArgs = [];
39
+
40
+    /**
41
+     * @param resource $link
42
+     * @param string $dn
43
+     * @param string $password
44
+     * @return bool|mixed
45
+     */
46
+    public function bind($link, $dn, $password) {
47
+        return $this->invokeLDAPMethod('bind', $link, $dn, $password);
48
+    }
49
+
50
+    /**
51
+     * @param string $host
52
+     * @param string $port
53
+     * @return mixed
54
+     */
55
+    public function connect($host, $port) {
56
+        if(strpos($host, '://') === false) {
57
+            $host = 'ldap://' . $host;
58
+        }
59
+        if(strpos($host, ':', strpos($host, '://') + 1) === false) {
60
+            //ldap_connect ignores port parameter when URLs are passed
61
+            $host .= ':' . $port;
62
+        }
63
+        return $this->invokeLDAPMethod('connect', $host);
64
+    }
65
+
66
+    /**
67
+     * @param resource $link
68
+     * @param resource $result
69
+     * @param string $cookie
70
+     * @return bool|LDAP
71
+     */
72
+    public function controlPagedResultResponse($link, $result, &$cookie) {
73
+        $this->preFunctionCall('ldap_control_paged_result_response',
74
+            [$link, $result, $cookie]);
75
+        $result = ldap_control_paged_result_response($link, $result, $cookie);
76
+        $this->postFunctionCall();
77
+
78
+        return $result;
79
+    }
80
+
81
+    /**
82
+     * @param LDAP $link
83
+     * @param int $pageSize
84
+     * @param bool $isCritical
85
+     * @param string $cookie
86
+     * @return mixed|true
87
+     */
88
+    public function controlPagedResult($link, $pageSize, $isCritical, $cookie) {
89
+        return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize,
90
+                                        $isCritical, $cookie);
91
+    }
92
+
93
+    /**
94
+     * @param LDAP $link
95
+     * @param LDAP $result
96
+     * @return mixed
97
+     */
98
+    public function countEntries($link, $result) {
99
+        return $this->invokeLDAPMethod('count_entries', $link, $result);
100
+    }
101
+
102
+    /**
103
+     * @param LDAP $link
104
+     * @return integer
105
+     */
106
+    public function errno($link) {
107
+        return $this->invokeLDAPMethod('errno', $link);
108
+    }
109
+
110
+    /**
111
+     * @param LDAP $link
112
+     * @return string
113
+     */
114
+    public function error($link) {
115
+        return $this->invokeLDAPMethod('error', $link);
116
+    }
117
+
118
+    /**
119
+     * Splits DN into its component parts
120
+     * @param string $dn
121
+     * @param int @withAttrib
122
+     * @return array|false
123
+     * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
124
+     */
125
+    public function explodeDN($dn, $withAttrib) {
126
+        return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
127
+    }
128
+
129
+    /**
130
+     * @param LDAP $link
131
+     * @param LDAP $result
132
+     * @return mixed
133
+     */
134
+    public function firstEntry($link, $result) {
135
+        return $this->invokeLDAPMethod('first_entry', $link, $result);
136
+    }
137
+
138
+    /**
139
+     * @param LDAP $link
140
+     * @param LDAP $result
141
+     * @return array|mixed
142
+     */
143
+    public function getAttributes($link, $result) {
144
+        return $this->invokeLDAPMethod('get_attributes', $link, $result);
145
+    }
146
+
147
+    /**
148
+     * @param LDAP $link
149
+     * @param LDAP $result
150
+     * @return mixed|string
151
+     */
152
+    public function getDN($link, $result) {
153
+        return $this->invokeLDAPMethod('get_dn', $link, $result);
154
+    }
155
+
156
+    /**
157
+     * @param LDAP $link
158
+     * @param LDAP $result
159
+     * @return array|mixed
160
+     */
161
+    public function getEntries($link, $result) {
162
+        return $this->invokeLDAPMethod('get_entries', $link, $result);
163
+    }
164
+
165
+    /**
166
+     * @param LDAP $link
167
+     * @param resource $result
168
+     * @return mixed
169
+     */
170
+    public function nextEntry($link, $result) {
171
+        return $this->invokeLDAPMethod('next_entry', $link, $result);
172
+    }
173
+
174
+    /**
175
+     * @param LDAP $link
176
+     * @param string $baseDN
177
+     * @param string $filter
178
+     * @param array $attr
179
+     * @return mixed
180
+     */
181
+    public function read($link, $baseDN, $filter, $attr) {
182
+        return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr);
183
+    }
184
+
185
+    /**
186
+     * @param LDAP $link
187
+     * @param string $baseDN
188
+     * @param string $filter
189
+     * @param array $attr
190
+     * @param int $attrsOnly
191
+     * @param int $limit
192
+     * @return mixed
193
+     * @throws \Exception
194
+     */
195
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
196
+        $oldHandler = set_error_handler(function($no, $message, $file, $line) use (&$oldHandler) {
197
+            if(strpos($message, 'Partial search results returned: Sizelimit exceeded') !== false) {
198
+                return true;
199
+            }
200
+            $oldHandler($no, $message, $file, $line);
201
+            return true;
202
+        });
203
+        try {
204
+            $result = $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
205
+            restore_error_handler();
206
+            return $result;
207
+        } catch (\Exception $e) {
208
+            restore_error_handler();
209
+            throw $e;
210
+        }
211
+    }
212
+
213
+    /**
214
+     * @param LDAP $link
215
+     * @param string $userDN
216
+     * @param string $password
217
+     * @return bool
218
+     */
219
+    public function modReplace($link, $userDN, $password) {
220
+        return $this->invokeLDAPMethod('mod_replace', $link, $userDN, ['userPassword' => $password]);
221
+    }
222
+
223
+    /**
224
+     * @param LDAP $link
225
+     * @param string $userDN
226
+     * @param string $oldPassword
227
+     * @param string $password
228
+     * @return bool
229
+     */
230
+    public function exopPasswd($link, $userDN, $oldPassword, $password) {
231
+        return $this->invokeLDAPMethod('exop_passwd', $link, $userDN, $oldPassword, $password);
232
+    }
233
+
234
+    /**
235
+     * @param LDAP $link
236
+     * @param string $option
237
+     * @param int $value
238
+     * @return bool|mixed
239
+     */
240
+    public function setOption($link, $option, $value) {
241
+        return $this->invokeLDAPMethod('set_option', $link, $option, $value);
242
+    }
243
+
244
+    /**
245
+     * @param LDAP $link
246
+     * @return mixed|true
247
+     */
248
+    public function startTls($link) {
249
+        return $this->invokeLDAPMethod('start_tls', $link);
250
+    }
251
+
252
+    /**
253
+     * @param resource $link
254
+     * @return bool|mixed
255
+     */
256
+    public function unbind($link) {
257
+        return $this->invokeLDAPMethod('unbind', $link);
258
+    }
259
+
260
+    /**
261
+     * Checks whether the server supports LDAP
262
+     * @return boolean if it the case, false otherwise
263
+     * */
264
+    public function areLDAPFunctionsAvailable() {
265
+        return function_exists('ldap_connect');
266
+    }
267
+
268
+    /**
269
+     * Checks whether the submitted parameter is a resource
270
+     * @param Resource $resource the resource variable to check
271
+     * @return bool true if it is a resource, false otherwise
272
+     */
273
+    public function isResource($resource) {
274
+        return is_resource($resource);
275
+    }
276
+
277
+    /**
278
+     * Checks whether the return value from LDAP is wrong or not.
279
+     *
280
+     * When using ldap_search we provide an array, in case multiple bases are
281
+     * configured. Thus, we need to check the array elements.
282
+     *
283
+     * @param $result
284
+     * @return bool
285
+     */
286
+    protected function isResultFalse($result) {
287
+        if($result === false) {
288
+            return true;
289
+        }
290
+
291
+        if($this->curFunc === 'ldap_search' && is_array($result)) {
292
+            foreach ($result as $singleResult) {
293
+                if($singleResult === false) {
294
+                    return true;
295
+                }
296
+            }
297
+        }
298
+
299
+        return false;
300
+    }
301
+
302
+    /**
303
+     * @return mixed
304
+     */
305
+    protected function invokeLDAPMethod() {
306
+        $arguments = func_get_args();
307
+        $func = 'ldap_' . array_shift($arguments);
308
+        if(function_exists($func)) {
309
+            $this->preFunctionCall($func, $arguments);
310
+            $result = call_user_func_array($func, $arguments);
311
+            if ($this->isResultFalse($result)) {
312
+                $this->postFunctionCall();
313
+            }
314
+            return $result;
315
+        }
316
+        return null;
317
+    }
318
+
319
+    /**
320
+     * @param string $functionName
321
+     * @param array $args
322
+     */
323
+    private function preFunctionCall($functionName, $args) {
324
+        $this->curFunc = $functionName;
325
+        $this->curArgs = $args;
326
+    }
327
+
328
+    /**
329
+     * Analyzes the returned LDAP error and acts accordingly if not 0
330
+     *
331
+     * @param resource $resource the LDAP Connection resource
332
+     * @throws ConstraintViolationException
333
+     * @throws ServerNotAvailableException
334
+     * @throws \Exception
335
+     */
336
+    private function processLDAPError($resource) {
337
+        $errorCode = ldap_errno($resource);
338
+        if($errorCode === 0) {
339
+            return;
340
+        }
341
+        $errorMsg  = ldap_error($resource);
342
+
343
+        if($this->curFunc === 'ldap_get_entries'
344
+            && $errorCode === -4) {
345
+        } else if ($errorCode === 32) {
346
+            //for now
347
+        } else if ($errorCode === 10) {
348
+            //referrals, we switch them off, but then there is AD :)
349
+        } else if ($errorCode === -1) {
350
+            throw new ServerNotAvailableException('Lost connection to LDAP server.');
351
+        } else if ($errorCode === 52) {
352
+            throw new ServerNotAvailableException('LDAP server is shutting down.');
353
+        } else if ($errorCode === 48) {
354
+            throw new \Exception('LDAP authentication method rejected', $errorCode);
355
+        } else if ($errorCode === 1) {
356
+            throw new \Exception('LDAP Operations error', $errorCode);
357
+        } else if ($errorCode === 19) {
358
+            ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
359
+            throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
360
+        } else {
361
+            \OC::$server->getLogger()->debug('LDAP error {message} ({code}) after calling {func}', [
362
+                'app' => 'user_ldap',
363
+                'message' => $errorMsg,
364
+                'code' => $errorCode,
365
+                'func' => $this->curFunc,
366
+            ]);
367
+        }
368
+    }
369
+
370
+    /**
371
+     * Called after an ldap method is run to act on LDAP error if necessary
372
+     * @throw \Exception
373
+     */
374
+    private function postFunctionCall() {
375
+        if($this->isResource($this->curArgs[0])) {
376
+            $resource = $this->curArgs[0];
377
+        } else if(
378
+                $this->curFunc === 'ldap_search'
379
+            && is_array($this->curArgs[0])
380
+            && $this->isResource($this->curArgs[0][0])
381
+        ) {
382
+            // we use always the same LDAP connection resource, is enough to
383
+            // take the first one.
384
+            $resource = $this->curArgs[0][0];
385
+        } else {
386
+            return;
387
+        }
388
+
389
+        $this->processLDAPError($resource);
390
+
391
+        $this->curFunc = '';
392
+        $this->curArgs = [];
393
+    }
394 394
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Connection.php 2 patches
Indentation   +616 added lines, -616 removed lines patch added patch discarded remove patch
@@ -68,621 +68,621 @@
 block discarded – undo
68 68
  * @property string ldapGroupDisplayName
69 69
  */
70 70
 class Connection extends LDAPUtility {
71
-	private $ldapConnectionRes = null;
72
-	private $configPrefix;
73
-	private $configID;
74
-	private $configured = false;
75
-	//whether connection should be kept on __destruct
76
-	private $dontDestruct = false;
77
-
78
-	/**
79
-	 * @var bool runtime flag that indicates whether supported primary groups are available
80
-	 */
81
-	public $hasPrimaryGroups = true;
82
-
83
-	/**
84
-	 * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
85
-	 */
86
-	public $hasGidNumber = true;
87
-
88
-	//cache handler
89
-	protected $cache;
90
-
91
-	/** @var Configuration settings handler **/
92
-	protected $configuration;
93
-
94
-	protected $doNotValidate = false;
95
-
96
-	protected $ignoreValidation = false;
97
-
98
-	protected $bindResult = [];
99
-
100
-	/**
101
-	 * Constructor
102
-	 * @param ILDAPWrapper $ldap
103
-	 * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
104
-	 * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
105
-	 */
106
-	public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
107
-		parent::__construct($ldap);
108
-		$this->configPrefix = $configPrefix;
109
-		$this->configID = $configID;
110
-		$this->configuration = new Configuration($configPrefix,
111
-												 !is_null($configID));
112
-		$memcache = \OC::$server->getMemCacheFactory();
113
-		if($memcache->isAvailable()) {
114
-			$this->cache = $memcache->createDistributed();
115
-		}
116
-		$helper = new Helper(\OC::$server->getConfig());
117
-		$this->doNotValidate = !in_array($this->configPrefix,
118
-			$helper->getServerConfigurationPrefixes());
119
-	}
120
-
121
-	public function __destruct() {
122
-		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
123
-			@$this->ldap->unbind($this->ldapConnectionRes);
124
-			$this->bindResult = [];
125
-		}
126
-	}
127
-
128
-	/**
129
-	 * defines behaviour when the instance is cloned
130
-	 */
131
-	public function __clone() {
132
-		$this->configuration = new Configuration($this->configPrefix,
133
-												 !is_null($this->configID));
134
-		if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
135
-			$this->bindResult = [];
136
-		}
137
-		$this->ldapConnectionRes = null;
138
-		$this->dontDestruct = true;
139
-	}
140
-
141
-	/**
142
-	 * @param string $name
143
-	 * @return bool|mixed
144
-	 */
145
-	public function __get($name) {
146
-		if(!$this->configured) {
147
-			$this->readConfiguration();
148
-		}
149
-
150
-		return $this->configuration->$name;
151
-	}
152
-
153
-	/**
154
-	 * @param string $name
155
-	 * @param mixed $value
156
-	 */
157
-	public function __set($name, $value) {
158
-		$this->doNotValidate = false;
159
-		$before = $this->configuration->$name;
160
-		$this->configuration->$name = $value;
161
-		$after = $this->configuration->$name;
162
-		if($before !== $after) {
163
-			if ($this->configID !== '' && $this->configID !== null) {
164
-				$this->configuration->saveConfiguration();
165
-			}
166
-			$this->validateConfiguration();
167
-		}
168
-	}
169
-
170
-	/**
171
-	 * @param string $rule
172
-	 * @return array
173
-	 * @throws \RuntimeException
174
-	 */
175
-	public function resolveRule($rule) {
176
-		return $this->configuration->resolveRule($rule);
177
-	}
178
-
179
-	/**
180
-	 * sets whether the result of the configuration validation shall
181
-	 * be ignored when establishing the connection. Used by the Wizard
182
-	 * in early configuration state.
183
-	 * @param bool $state
184
-	 */
185
-	public function setIgnoreValidation($state) {
186
-		$this->ignoreValidation = (bool)$state;
187
-	}
188
-
189
-	/**
190
-	 * initializes the LDAP backend
191
-	 * @param bool $force read the config settings no matter what
192
-	 */
193
-	public function init($force = false) {
194
-		$this->readConfiguration($force);
195
-		$this->establishConnection();
196
-	}
197
-
198
-	/**
199
-	 * Returns the LDAP handler
200
-	 */
201
-	public function getConnectionResource() {
202
-		if(!$this->ldapConnectionRes) {
203
-			$this->init();
204
-		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
205
-			$this->ldapConnectionRes = null;
206
-			$this->establishConnection();
207
-		}
208
-		if(is_null($this->ldapConnectionRes)) {
209
-			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR);
210
-			throw new ServerNotAvailableException('Connection to LDAP server could not be established');
211
-		}
212
-		return $this->ldapConnectionRes;
213
-	}
214
-
215
-	/**
216
-	 * resets the connection resource
217
-	 */
218
-	public function resetConnectionResource() {
219
-		if(!is_null($this->ldapConnectionRes)) {
220
-			@$this->ldap->unbind($this->ldapConnectionRes);
221
-			$this->ldapConnectionRes = null;
222
-			$this->bindResult = [];
223
-		}
224
-	}
225
-
226
-	/**
227
-	 * @param string|null $key
228
-	 * @return string
229
-	 */
230
-	private function getCacheKey($key) {
231
-		$prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
232
-		if(is_null($key)) {
233
-			return $prefix;
234
-		}
235
-		return $prefix.hash('sha256', $key);
236
-	}
237
-
238
-	/**
239
-	 * @param string $key
240
-	 * @return mixed|null
241
-	 */
242
-	public function getFromCache($key) {
243
-		if(!$this->configured) {
244
-			$this->readConfiguration();
245
-		}
246
-		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
247
-			return null;
248
-		}
249
-		$key = $this->getCacheKey($key);
250
-
251
-		return json_decode(base64_decode($this->cache->get($key)), true);
252
-	}
253
-
254
-	/**
255
-	 * @param string $key
256
-	 * @param mixed $value
257
-	 *
258
-	 * @return string
259
-	 */
260
-	public function writeToCache($key, $value) {
261
-		if(!$this->configured) {
262
-			$this->readConfiguration();
263
-		}
264
-		if(is_null($this->cache)
265
-			|| !$this->configuration->ldapCacheTTL
266
-			|| !$this->configuration->ldapConfigurationActive) {
267
-			return null;
268
-		}
269
-		$key   = $this->getCacheKey($key);
270
-		$value = base64_encode(json_encode($value));
271
-		$this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
272
-	}
273
-
274
-	public function clearCache() {
275
-		if(!is_null($this->cache)) {
276
-			$this->cache->clear($this->getCacheKey(null));
277
-		}
278
-	}
279
-
280
-	/**
281
-	 * Caches the general LDAP configuration.
282
-	 * @param bool $force optional. true, if the re-read should be forced. defaults
283
-	 * to false.
284
-	 * @return null
285
-	 */
286
-	private function readConfiguration($force = false) {
287
-		if((!$this->configured || $force) && !is_null($this->configID)) {
288
-			$this->configuration->readConfiguration();
289
-			$this->configured = $this->validateConfiguration();
290
-		}
291
-	}
292
-
293
-	/**
294
-	 * set LDAP configuration with values delivered by an array, not read from configuration
295
-	 * @param array $config array that holds the config parameters in an associated array
296
-	 * @param array &$setParameters optional; array where the set fields will be given to
297
-	 * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
298
-	 */
299
-	public function setConfiguration($config, &$setParameters = null) {
300
-		if(is_null($setParameters)) {
301
-			$setParameters = [];
302
-		}
303
-		$this->doNotValidate = false;
304
-		$this->configuration->setConfiguration($config, $setParameters);
305
-		if(count($setParameters) > 0) {
306
-			$this->configured = $this->validateConfiguration();
307
-		}
308
-
309
-
310
-		return $this->configured;
311
-	}
312
-
313
-	/**
314
-	 * saves the current Configuration in the database and empties the
315
-	 * cache
316
-	 * @return null
317
-	 */
318
-	public function saveConfiguration() {
319
-		$this->configuration->saveConfiguration();
320
-		$this->clearCache();
321
-	}
322
-
323
-	/**
324
-	 * get the current LDAP configuration
325
-	 * @return array
326
-	 */
327
-	public function getConfiguration() {
328
-		$this->readConfiguration();
329
-		$config = $this->configuration->getConfiguration();
330
-		$cta = $this->configuration->getConfigTranslationArray();
331
-		$result = [];
332
-		foreach($cta as $dbkey => $configkey) {
333
-			switch($configkey) {
334
-				case 'homeFolderNamingRule':
335
-					if(strpos($config[$configkey], 'attr:') === 0) {
336
-						$result[$dbkey] = substr($config[$configkey], 5);
337
-					} else {
338
-						$result[$dbkey] = '';
339
-					}
340
-					break;
341
-				case 'ldapBase':
342
-				case 'ldapBaseUsers':
343
-				case 'ldapBaseGroups':
344
-				case 'ldapAttributesForUserSearch':
345
-				case 'ldapAttributesForGroupSearch':
346
-					if(is_array($config[$configkey])) {
347
-						$result[$dbkey] = implode("\n", $config[$configkey]);
348
-						break;
349
-					} //else follows default
350
-				default:
351
-					$result[$dbkey] = $config[$configkey];
352
-			}
353
-		}
354
-		return $result;
355
-	}
356
-
357
-	private function doSoftValidation() {
358
-		//if User or Group Base are not set, take over Base DN setting
359
-		foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
360
-			$val = $this->configuration->$keyBase;
361
-			if(empty($val)) {
362
-				$this->configuration->$keyBase = $this->configuration->ldapBase;
363
-			}
364
-		}
365
-
366
-		foreach(['ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
367
-					  'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
368
-				as $expertSetting => $effectiveSetting) {
369
-			$uuidOverride = $this->configuration->$expertSetting;
370
-			if(!empty($uuidOverride)) {
371
-				$this->configuration->$effectiveSetting = $uuidOverride;
372
-			} else {
373
-				$uuidAttributes = Access::UUID_ATTRIBUTES;
374
-				array_unshift($uuidAttributes, 'auto');
375
-				if(!in_array($this->configuration->$effectiveSetting,
376
-							$uuidAttributes)
377
-					&& (!is_null($this->configID))) {
378
-					$this->configuration->$effectiveSetting = 'auto';
379
-					$this->configuration->saveConfiguration();
380
-					\OCP\Util::writeLog('user_ldap',
381
-										'Illegal value for the '.
382
-										$effectiveSetting.', '.'reset to '.
383
-										'autodetect.', ILogger::INFO);
384
-				}
385
-
386
-			}
387
-		}
388
-
389
-		$backupPort = (int)$this->configuration->ldapBackupPort;
390
-		if ($backupPort <= 0) {
391
-			$this->configuration->backupPort = $this->configuration->ldapPort;
392
-		}
393
-
394
-		//make sure empty search attributes are saved as simple, empty array
395
-		$saKeys = ['ldapAttributesForUserSearch',
396
-						'ldapAttributesForGroupSearch'];
397
-		foreach($saKeys as $key) {
398
-			$val = $this->configuration->$key;
399
-			if(is_array($val) && count($val) === 1 && empty($val[0])) {
400
-				$this->configuration->$key = [];
401
-			}
402
-		}
403
-
404
-		if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
405
-			&& $this->configuration->ldapTLS) {
406
-			$this->configuration->ldapTLS = false;
407
-			\OCP\Util::writeLog(
408
-				'user_ldap',
409
-				'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
410
-				ILogger::INFO
411
-			);
412
-		}
413
-	}
414
-
415
-	/**
416
-	 * @return bool
417
-	 */
418
-	private function doCriticalValidation() {
419
-		$configurationOK = true;
420
-		$errorStr = 'Configuration Error (prefix '.
421
-			(string)$this->configPrefix .'): ';
422
-
423
-		//options that shall not be empty
424
-		$options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName',
425
-						 'ldapGroupDisplayName', 'ldapLoginFilter'];
426
-		foreach($options as $key) {
427
-			$val = $this->configuration->$key;
428
-			if(empty($val)) {
429
-				switch($key) {
430
-					case 'ldapHost':
431
-						$subj = 'LDAP Host';
432
-						break;
433
-					case 'ldapPort':
434
-						$subj = 'LDAP Port';
435
-						break;
436
-					case 'ldapUserDisplayName':
437
-						$subj = 'LDAP User Display Name';
438
-						break;
439
-					case 'ldapGroupDisplayName':
440
-						$subj = 'LDAP Group Display Name';
441
-						break;
442
-					case 'ldapLoginFilter':
443
-						$subj = 'LDAP Login Filter';
444
-						break;
445
-					default:
446
-						$subj = $key;
447
-						break;
448
-				}
449
-				$configurationOK = false;
450
-				\OCP\Util::writeLog(
451
-					'user_ldap',
452
-					$errorStr.'No '.$subj.' given!',
453
-					ILogger::WARN
454
-				);
455
-			}
456
-		}
457
-
458
-		//combinations
459
-		$agent = $this->configuration->ldapAgentName;
460
-		$pwd = $this->configuration->ldapAgentPassword;
461
-		if (
462
-			($agent === ''  && $pwd !== '')
463
-			|| ($agent !== '' && $pwd === '')
464
-		) {
465
-			\OCP\Util::writeLog(
466
-				'user_ldap',
467
-				$errorStr.'either no password is given for the user ' .
468
-					'agent or a password is given, but not an LDAP agent.',
469
-				ILogger::WARN);
470
-			$configurationOK = false;
471
-		}
472
-
473
-		$base = $this->configuration->ldapBase;
474
-		$baseUsers = $this->configuration->ldapBaseUsers;
475
-		$baseGroups = $this->configuration->ldapBaseGroups;
476
-
477
-		if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
478
-			\OCP\Util::writeLog(
479
-				'user_ldap',
480
-				$errorStr.'Not a single Base DN given.',
481
-				ILogger::WARN
482
-			);
483
-			$configurationOK = false;
484
-		}
485
-
486
-		if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
487
-		   === false) {
488
-			\OCP\Util::writeLog(
489
-				'user_ldap',
490
-				$errorStr.'login filter does not contain %uid place holder.',
491
-				ILogger::WARN
492
-			);
493
-			$configurationOK = false;
494
-		}
495
-
496
-		return $configurationOK;
497
-	}
498
-
499
-	/**
500
-	 * Validates the user specified configuration
501
-	 * @return bool true if configuration seems OK, false otherwise
502
-	 */
503
-	private function validateConfiguration() {
504
-
505
-		if($this->doNotValidate) {
506
-			//don't do a validation if it is a new configuration with pure
507
-			//default values. Will be allowed on changes via __set or
508
-			//setConfiguration
509
-			return false;
510
-		}
511
-
512
-		// first step: "soft" checks: settings that are not really
513
-		// necessary, but advisable. If left empty, give an info message
514
-		$this->doSoftValidation();
515
-
516
-		//second step: critical checks. If left empty or filled wrong, mark as
517
-		//not configured and give a warning.
518
-		return $this->doCriticalValidation();
519
-	}
520
-
521
-
522
-	/**
523
-	 * Connects and Binds to LDAP
524
-	 *
525
-	 * @throws ServerNotAvailableException
526
-	 */
527
-	private function establishConnection() {
528
-		if(!$this->configuration->ldapConfigurationActive) {
529
-			return null;
530
-		}
531
-		static $phpLDAPinstalled = true;
532
-		if(!$phpLDAPinstalled) {
533
-			return false;
534
-		}
535
-		if(!$this->ignoreValidation && !$this->configured) {
536
-			\OCP\Util::writeLog(
537
-				'user_ldap',
538
-				'Configuration is invalid, cannot connect',
539
-				ILogger::WARN
540
-			);
541
-			return false;
542
-		}
543
-		if(!$this->ldapConnectionRes) {
544
-			if(!$this->ldap->areLDAPFunctionsAvailable()) {
545
-				$phpLDAPinstalled = false;
546
-				\OCP\Util::writeLog(
547
-					'user_ldap',
548
-					'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
549
-					ILogger::ERROR
550
-				);
551
-
552
-				return false;
553
-			}
554
-			if($this->configuration->turnOffCertCheck) {
555
-				if(putenv('LDAPTLS_REQCERT=never')) {
556
-					\OCP\Util::writeLog('user_ldap',
557
-						'Turned off SSL certificate validation successfully.',
558
-						ILogger::DEBUG);
559
-				} else {
560
-					\OCP\Util::writeLog(
561
-						'user_ldap',
562
-						'Could not turn off SSL certificate validation.',
563
-						ILogger::WARN
564
-					);
565
-				}
566
-			}
567
-
568
-			$isOverrideMainServer = ($this->configuration->ldapOverrideMainServer
569
-				|| $this->getFromCache('overrideMainServer'));
570
-			$isBackupHost = (trim($this->configuration->ldapBackupHost) !== "");
571
-			$bindStatus = false;
572
-			try {
573
-				if (!$isOverrideMainServer) {
574
-					$this->doConnect($this->configuration->ldapHost,
575
-						$this->configuration->ldapPort);
576
-					return $this->bind();
577
-				}
578
-			} catch (ServerNotAvailableException $e) {
579
-				if(!$isBackupHost) {
580
-					throw $e;
581
-				}
582
-			}
583
-
584
-			//if LDAP server is not reachable, try the Backup (Replica!) Server
585
-			if($isBackupHost || $isOverrideMainServer) {
586
-				$this->doConnect($this->configuration->ldapBackupHost,
587
-								 $this->configuration->ldapBackupPort);
588
-				$this->bindResult = [];
589
-				$bindStatus = $this->bind();
590
-				$error = $this->ldap->isResource($this->ldapConnectionRes) ?
591
-					$this->ldap->errno($this->ldapConnectionRes) : -1;
592
-				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
593
-					//when bind to backup server succeeded and failed to main server,
594
-					//skip contacting him until next cache refresh
595
-					$this->writeToCache('overrideMainServer', true);
596
-				}
597
-			}
598
-
599
-			return $bindStatus;
600
-		}
601
-		return null;
602
-	}
603
-
604
-	/**
605
-	 * @param string $host
606
-	 * @param string $port
607
-	 * @return bool
608
-	 * @throws \OC\ServerNotAvailableException
609
-	 */
610
-	private function doConnect($host, $port) {
611
-		if ($host === '') {
612
-			return false;
613
-		}
614
-
615
-		$this->ldapConnectionRes = $this->ldap->connect($host, $port);
616
-
617
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
618
-			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
619
-		}
620
-
621
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
622
-			throw new ServerNotAvailableException('Could not disable LDAP referrals.');
623
-		}
624
-
625
-		if($this->configuration->ldapTLS) {
626
-			if(!$this->ldap->startTls($this->ldapConnectionRes)) {
627
-				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
628
-			}
629
-		}
630
-
631
-		return true;
632
-	}
633
-
634
-	/**
635
-	 * Binds to LDAP
636
-	 */
637
-	public function bind() {
638
-		if(!$this->configuration->ldapConfigurationActive) {
639
-			return false;
640
-		}
641
-		$cr = $this->ldapConnectionRes;
642
-		if(!$this->ldap->isResource($cr)) {
643
-			$cr = $this->getConnectionResource();
644
-		}
645
-
646
-		if(
647
-			count($this->bindResult) !== 0
648
-			&& $this->bindResult['dn'] === $this->configuration->ldapAgentName
649
-			&& \OC::$server->getHasher()->verify(
650
-				$this->configPrefix . $this->configuration->ldapAgentPassword,
651
-				$this->bindResult['hash']
652
-			)
653
-		) {
654
-			// don't attempt to bind again with the same data as before
655
-			// bind might have been invoked via getConnectionResource(),
656
-			// but we need results specifically for e.g. user login
657
-			return $this->bindResult['result'];
658
-		}
659
-
660
-		$ldapLogin = @$this->ldap->bind($cr,
661
-										$this->configuration->ldapAgentName,
662
-										$this->configuration->ldapAgentPassword);
663
-
664
-		$this->bindResult = [
665
-			'dn' => $this->configuration->ldapAgentName,
666
-			'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword),
667
-			'result' => $ldapLogin,
668
-		];
669
-
670
-		if(!$ldapLogin) {
671
-			$errno = $this->ldap->errno($cr);
672
-
673
-			\OCP\Util::writeLog('user_ldap',
674
-				'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
675
-				ILogger::WARN);
676
-
677
-			// Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
678
-			// or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS
679
-			if($errno !== 0 && $errno !== 49 && $errno !== 50) {
680
-				$this->ldapConnectionRes = null;
681
-			}
682
-
683
-			return false;
684
-		}
685
-		return true;
686
-	}
71
+    private $ldapConnectionRes = null;
72
+    private $configPrefix;
73
+    private $configID;
74
+    private $configured = false;
75
+    //whether connection should be kept on __destruct
76
+    private $dontDestruct = false;
77
+
78
+    /**
79
+     * @var bool runtime flag that indicates whether supported primary groups are available
80
+     */
81
+    public $hasPrimaryGroups = true;
82
+
83
+    /**
84
+     * @var bool runtime flag that indicates whether supported POSIX gidNumber are available
85
+     */
86
+    public $hasGidNumber = true;
87
+
88
+    //cache handler
89
+    protected $cache;
90
+
91
+    /** @var Configuration settings handler **/
92
+    protected $configuration;
93
+
94
+    protected $doNotValidate = false;
95
+
96
+    protected $ignoreValidation = false;
97
+
98
+    protected $bindResult = [];
99
+
100
+    /**
101
+     * Constructor
102
+     * @param ILDAPWrapper $ldap
103
+     * @param string $configPrefix a string with the prefix for the configkey column (appconfig table)
104
+     * @param string|null $configID a string with the value for the appid column (appconfig table) or null for on-the-fly connections
105
+     */
106
+    public function __construct(ILDAPWrapper $ldap, $configPrefix = '', $configID = 'user_ldap') {
107
+        parent::__construct($ldap);
108
+        $this->configPrefix = $configPrefix;
109
+        $this->configID = $configID;
110
+        $this->configuration = new Configuration($configPrefix,
111
+                                                    !is_null($configID));
112
+        $memcache = \OC::$server->getMemCacheFactory();
113
+        if($memcache->isAvailable()) {
114
+            $this->cache = $memcache->createDistributed();
115
+        }
116
+        $helper = new Helper(\OC::$server->getConfig());
117
+        $this->doNotValidate = !in_array($this->configPrefix,
118
+            $helper->getServerConfigurationPrefixes());
119
+    }
120
+
121
+    public function __destruct() {
122
+        if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
123
+            @$this->ldap->unbind($this->ldapConnectionRes);
124
+            $this->bindResult = [];
125
+        }
126
+    }
127
+
128
+    /**
129
+     * defines behaviour when the instance is cloned
130
+     */
131
+    public function __clone() {
132
+        $this->configuration = new Configuration($this->configPrefix,
133
+                                                    !is_null($this->configID));
134
+        if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
135
+            $this->bindResult = [];
136
+        }
137
+        $this->ldapConnectionRes = null;
138
+        $this->dontDestruct = true;
139
+    }
140
+
141
+    /**
142
+     * @param string $name
143
+     * @return bool|mixed
144
+     */
145
+    public function __get($name) {
146
+        if(!$this->configured) {
147
+            $this->readConfiguration();
148
+        }
149
+
150
+        return $this->configuration->$name;
151
+    }
152
+
153
+    /**
154
+     * @param string $name
155
+     * @param mixed $value
156
+     */
157
+    public function __set($name, $value) {
158
+        $this->doNotValidate = false;
159
+        $before = $this->configuration->$name;
160
+        $this->configuration->$name = $value;
161
+        $after = $this->configuration->$name;
162
+        if($before !== $after) {
163
+            if ($this->configID !== '' && $this->configID !== null) {
164
+                $this->configuration->saveConfiguration();
165
+            }
166
+            $this->validateConfiguration();
167
+        }
168
+    }
169
+
170
+    /**
171
+     * @param string $rule
172
+     * @return array
173
+     * @throws \RuntimeException
174
+     */
175
+    public function resolveRule($rule) {
176
+        return $this->configuration->resolveRule($rule);
177
+    }
178
+
179
+    /**
180
+     * sets whether the result of the configuration validation shall
181
+     * be ignored when establishing the connection. Used by the Wizard
182
+     * in early configuration state.
183
+     * @param bool $state
184
+     */
185
+    public function setIgnoreValidation($state) {
186
+        $this->ignoreValidation = (bool)$state;
187
+    }
188
+
189
+    /**
190
+     * initializes the LDAP backend
191
+     * @param bool $force read the config settings no matter what
192
+     */
193
+    public function init($force = false) {
194
+        $this->readConfiguration($force);
195
+        $this->establishConnection();
196
+    }
197
+
198
+    /**
199
+     * Returns the LDAP handler
200
+     */
201
+    public function getConnectionResource() {
202
+        if(!$this->ldapConnectionRes) {
203
+            $this->init();
204
+        } else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
205
+            $this->ldapConnectionRes = null;
206
+            $this->establishConnection();
207
+        }
208
+        if(is_null($this->ldapConnectionRes)) {
209
+            \OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR);
210
+            throw new ServerNotAvailableException('Connection to LDAP server could not be established');
211
+        }
212
+        return $this->ldapConnectionRes;
213
+    }
214
+
215
+    /**
216
+     * resets the connection resource
217
+     */
218
+    public function resetConnectionResource() {
219
+        if(!is_null($this->ldapConnectionRes)) {
220
+            @$this->ldap->unbind($this->ldapConnectionRes);
221
+            $this->ldapConnectionRes = null;
222
+            $this->bindResult = [];
223
+        }
224
+    }
225
+
226
+    /**
227
+     * @param string|null $key
228
+     * @return string
229
+     */
230
+    private function getCacheKey($key) {
231
+        $prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
232
+        if(is_null($key)) {
233
+            return $prefix;
234
+        }
235
+        return $prefix.hash('sha256', $key);
236
+    }
237
+
238
+    /**
239
+     * @param string $key
240
+     * @return mixed|null
241
+     */
242
+    public function getFromCache($key) {
243
+        if(!$this->configured) {
244
+            $this->readConfiguration();
245
+        }
246
+        if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
247
+            return null;
248
+        }
249
+        $key = $this->getCacheKey($key);
250
+
251
+        return json_decode(base64_decode($this->cache->get($key)), true);
252
+    }
253
+
254
+    /**
255
+     * @param string $key
256
+     * @param mixed $value
257
+     *
258
+     * @return string
259
+     */
260
+    public function writeToCache($key, $value) {
261
+        if(!$this->configured) {
262
+            $this->readConfiguration();
263
+        }
264
+        if(is_null($this->cache)
265
+            || !$this->configuration->ldapCacheTTL
266
+            || !$this->configuration->ldapConfigurationActive) {
267
+            return null;
268
+        }
269
+        $key   = $this->getCacheKey($key);
270
+        $value = base64_encode(json_encode($value));
271
+        $this->cache->set($key, $value, $this->configuration->ldapCacheTTL);
272
+    }
273
+
274
+    public function clearCache() {
275
+        if(!is_null($this->cache)) {
276
+            $this->cache->clear($this->getCacheKey(null));
277
+        }
278
+    }
279
+
280
+    /**
281
+     * Caches the general LDAP configuration.
282
+     * @param bool $force optional. true, if the re-read should be forced. defaults
283
+     * to false.
284
+     * @return null
285
+     */
286
+    private function readConfiguration($force = false) {
287
+        if((!$this->configured || $force) && !is_null($this->configID)) {
288
+            $this->configuration->readConfiguration();
289
+            $this->configured = $this->validateConfiguration();
290
+        }
291
+    }
292
+
293
+    /**
294
+     * set LDAP configuration with values delivered by an array, not read from configuration
295
+     * @param array $config array that holds the config parameters in an associated array
296
+     * @param array &$setParameters optional; array where the set fields will be given to
297
+     * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
298
+     */
299
+    public function setConfiguration($config, &$setParameters = null) {
300
+        if(is_null($setParameters)) {
301
+            $setParameters = [];
302
+        }
303
+        $this->doNotValidate = false;
304
+        $this->configuration->setConfiguration($config, $setParameters);
305
+        if(count($setParameters) > 0) {
306
+            $this->configured = $this->validateConfiguration();
307
+        }
308
+
309
+
310
+        return $this->configured;
311
+    }
312
+
313
+    /**
314
+     * saves the current Configuration in the database and empties the
315
+     * cache
316
+     * @return null
317
+     */
318
+    public function saveConfiguration() {
319
+        $this->configuration->saveConfiguration();
320
+        $this->clearCache();
321
+    }
322
+
323
+    /**
324
+     * get the current LDAP configuration
325
+     * @return array
326
+     */
327
+    public function getConfiguration() {
328
+        $this->readConfiguration();
329
+        $config = $this->configuration->getConfiguration();
330
+        $cta = $this->configuration->getConfigTranslationArray();
331
+        $result = [];
332
+        foreach($cta as $dbkey => $configkey) {
333
+            switch($configkey) {
334
+                case 'homeFolderNamingRule':
335
+                    if(strpos($config[$configkey], 'attr:') === 0) {
336
+                        $result[$dbkey] = substr($config[$configkey], 5);
337
+                    } else {
338
+                        $result[$dbkey] = '';
339
+                    }
340
+                    break;
341
+                case 'ldapBase':
342
+                case 'ldapBaseUsers':
343
+                case 'ldapBaseGroups':
344
+                case 'ldapAttributesForUserSearch':
345
+                case 'ldapAttributesForGroupSearch':
346
+                    if(is_array($config[$configkey])) {
347
+                        $result[$dbkey] = implode("\n", $config[$configkey]);
348
+                        break;
349
+                    } //else follows default
350
+                default:
351
+                    $result[$dbkey] = $config[$configkey];
352
+            }
353
+        }
354
+        return $result;
355
+    }
356
+
357
+    private function doSoftValidation() {
358
+        //if User or Group Base are not set, take over Base DN setting
359
+        foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
360
+            $val = $this->configuration->$keyBase;
361
+            if(empty($val)) {
362
+                $this->configuration->$keyBase = $this->configuration->ldapBase;
363
+            }
364
+        }
365
+
366
+        foreach(['ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
367
+                        'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
368
+                as $expertSetting => $effectiveSetting) {
369
+            $uuidOverride = $this->configuration->$expertSetting;
370
+            if(!empty($uuidOverride)) {
371
+                $this->configuration->$effectiveSetting = $uuidOverride;
372
+            } else {
373
+                $uuidAttributes = Access::UUID_ATTRIBUTES;
374
+                array_unshift($uuidAttributes, 'auto');
375
+                if(!in_array($this->configuration->$effectiveSetting,
376
+                            $uuidAttributes)
377
+                    && (!is_null($this->configID))) {
378
+                    $this->configuration->$effectiveSetting = 'auto';
379
+                    $this->configuration->saveConfiguration();
380
+                    \OCP\Util::writeLog('user_ldap',
381
+                                        'Illegal value for the '.
382
+                                        $effectiveSetting.', '.'reset to '.
383
+                                        'autodetect.', ILogger::INFO);
384
+                }
385
+
386
+            }
387
+        }
388
+
389
+        $backupPort = (int)$this->configuration->ldapBackupPort;
390
+        if ($backupPort <= 0) {
391
+            $this->configuration->backupPort = $this->configuration->ldapPort;
392
+        }
393
+
394
+        //make sure empty search attributes are saved as simple, empty array
395
+        $saKeys = ['ldapAttributesForUserSearch',
396
+                        'ldapAttributesForGroupSearch'];
397
+        foreach($saKeys as $key) {
398
+            $val = $this->configuration->$key;
399
+            if(is_array($val) && count($val) === 1 && empty($val[0])) {
400
+                $this->configuration->$key = [];
401
+            }
402
+        }
403
+
404
+        if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
405
+            && $this->configuration->ldapTLS) {
406
+            $this->configuration->ldapTLS = false;
407
+            \OCP\Util::writeLog(
408
+                'user_ldap',
409
+                'LDAPS (already using secure connection) and TLS do not work together. Switched off TLS.',
410
+                ILogger::INFO
411
+            );
412
+        }
413
+    }
414
+
415
+    /**
416
+     * @return bool
417
+     */
418
+    private function doCriticalValidation() {
419
+        $configurationOK = true;
420
+        $errorStr = 'Configuration Error (prefix '.
421
+            (string)$this->configPrefix .'): ';
422
+
423
+        //options that shall not be empty
424
+        $options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName',
425
+                            'ldapGroupDisplayName', 'ldapLoginFilter'];
426
+        foreach($options as $key) {
427
+            $val = $this->configuration->$key;
428
+            if(empty($val)) {
429
+                switch($key) {
430
+                    case 'ldapHost':
431
+                        $subj = 'LDAP Host';
432
+                        break;
433
+                    case 'ldapPort':
434
+                        $subj = 'LDAP Port';
435
+                        break;
436
+                    case 'ldapUserDisplayName':
437
+                        $subj = 'LDAP User Display Name';
438
+                        break;
439
+                    case 'ldapGroupDisplayName':
440
+                        $subj = 'LDAP Group Display Name';
441
+                        break;
442
+                    case 'ldapLoginFilter':
443
+                        $subj = 'LDAP Login Filter';
444
+                        break;
445
+                    default:
446
+                        $subj = $key;
447
+                        break;
448
+                }
449
+                $configurationOK = false;
450
+                \OCP\Util::writeLog(
451
+                    'user_ldap',
452
+                    $errorStr.'No '.$subj.' given!',
453
+                    ILogger::WARN
454
+                );
455
+            }
456
+        }
457
+
458
+        //combinations
459
+        $agent = $this->configuration->ldapAgentName;
460
+        $pwd = $this->configuration->ldapAgentPassword;
461
+        if (
462
+            ($agent === ''  && $pwd !== '')
463
+            || ($agent !== '' && $pwd === '')
464
+        ) {
465
+            \OCP\Util::writeLog(
466
+                'user_ldap',
467
+                $errorStr.'either no password is given for the user ' .
468
+                    'agent or a password is given, but not an LDAP agent.',
469
+                ILogger::WARN);
470
+            $configurationOK = false;
471
+        }
472
+
473
+        $base = $this->configuration->ldapBase;
474
+        $baseUsers = $this->configuration->ldapBaseUsers;
475
+        $baseGroups = $this->configuration->ldapBaseGroups;
476
+
477
+        if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
478
+            \OCP\Util::writeLog(
479
+                'user_ldap',
480
+                $errorStr.'Not a single Base DN given.',
481
+                ILogger::WARN
482
+            );
483
+            $configurationOK = false;
484
+        }
485
+
486
+        if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
487
+            === false) {
488
+            \OCP\Util::writeLog(
489
+                'user_ldap',
490
+                $errorStr.'login filter does not contain %uid place holder.',
491
+                ILogger::WARN
492
+            );
493
+            $configurationOK = false;
494
+        }
495
+
496
+        return $configurationOK;
497
+    }
498
+
499
+    /**
500
+     * Validates the user specified configuration
501
+     * @return bool true if configuration seems OK, false otherwise
502
+     */
503
+    private function validateConfiguration() {
504
+
505
+        if($this->doNotValidate) {
506
+            //don't do a validation if it is a new configuration with pure
507
+            //default values. Will be allowed on changes via __set or
508
+            //setConfiguration
509
+            return false;
510
+        }
511
+
512
+        // first step: "soft" checks: settings that are not really
513
+        // necessary, but advisable. If left empty, give an info message
514
+        $this->doSoftValidation();
515
+
516
+        //second step: critical checks. If left empty or filled wrong, mark as
517
+        //not configured and give a warning.
518
+        return $this->doCriticalValidation();
519
+    }
520
+
521
+
522
+    /**
523
+     * Connects and Binds to LDAP
524
+     *
525
+     * @throws ServerNotAvailableException
526
+     */
527
+    private function establishConnection() {
528
+        if(!$this->configuration->ldapConfigurationActive) {
529
+            return null;
530
+        }
531
+        static $phpLDAPinstalled = true;
532
+        if(!$phpLDAPinstalled) {
533
+            return false;
534
+        }
535
+        if(!$this->ignoreValidation && !$this->configured) {
536
+            \OCP\Util::writeLog(
537
+                'user_ldap',
538
+                'Configuration is invalid, cannot connect',
539
+                ILogger::WARN
540
+            );
541
+            return false;
542
+        }
543
+        if(!$this->ldapConnectionRes) {
544
+            if(!$this->ldap->areLDAPFunctionsAvailable()) {
545
+                $phpLDAPinstalled = false;
546
+                \OCP\Util::writeLog(
547
+                    'user_ldap',
548
+                    'function ldap_connect is not available. Make sure that the PHP ldap module is installed.',
549
+                    ILogger::ERROR
550
+                );
551
+
552
+                return false;
553
+            }
554
+            if($this->configuration->turnOffCertCheck) {
555
+                if(putenv('LDAPTLS_REQCERT=never')) {
556
+                    \OCP\Util::writeLog('user_ldap',
557
+                        'Turned off SSL certificate validation successfully.',
558
+                        ILogger::DEBUG);
559
+                } else {
560
+                    \OCP\Util::writeLog(
561
+                        'user_ldap',
562
+                        'Could not turn off SSL certificate validation.',
563
+                        ILogger::WARN
564
+                    );
565
+                }
566
+            }
567
+
568
+            $isOverrideMainServer = ($this->configuration->ldapOverrideMainServer
569
+                || $this->getFromCache('overrideMainServer'));
570
+            $isBackupHost = (trim($this->configuration->ldapBackupHost) !== "");
571
+            $bindStatus = false;
572
+            try {
573
+                if (!$isOverrideMainServer) {
574
+                    $this->doConnect($this->configuration->ldapHost,
575
+                        $this->configuration->ldapPort);
576
+                    return $this->bind();
577
+                }
578
+            } catch (ServerNotAvailableException $e) {
579
+                if(!$isBackupHost) {
580
+                    throw $e;
581
+                }
582
+            }
583
+
584
+            //if LDAP server is not reachable, try the Backup (Replica!) Server
585
+            if($isBackupHost || $isOverrideMainServer) {
586
+                $this->doConnect($this->configuration->ldapBackupHost,
587
+                                    $this->configuration->ldapBackupPort);
588
+                $this->bindResult = [];
589
+                $bindStatus = $this->bind();
590
+                $error = $this->ldap->isResource($this->ldapConnectionRes) ?
591
+                    $this->ldap->errno($this->ldapConnectionRes) : -1;
592
+                if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
593
+                    //when bind to backup server succeeded and failed to main server,
594
+                    //skip contacting him until next cache refresh
595
+                    $this->writeToCache('overrideMainServer', true);
596
+                }
597
+            }
598
+
599
+            return $bindStatus;
600
+        }
601
+        return null;
602
+    }
603
+
604
+    /**
605
+     * @param string $host
606
+     * @param string $port
607
+     * @return bool
608
+     * @throws \OC\ServerNotAvailableException
609
+     */
610
+    private function doConnect($host, $port) {
611
+        if ($host === '') {
612
+            return false;
613
+        }
614
+
615
+        $this->ldapConnectionRes = $this->ldap->connect($host, $port);
616
+
617
+        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
618
+            throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
619
+        }
620
+
621
+        if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
622
+            throw new ServerNotAvailableException('Could not disable LDAP referrals.');
623
+        }
624
+
625
+        if($this->configuration->ldapTLS) {
626
+            if(!$this->ldap->startTls($this->ldapConnectionRes)) {
627
+                throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
628
+            }
629
+        }
630
+
631
+        return true;
632
+    }
633
+
634
+    /**
635
+     * Binds to LDAP
636
+     */
637
+    public function bind() {
638
+        if(!$this->configuration->ldapConfigurationActive) {
639
+            return false;
640
+        }
641
+        $cr = $this->ldapConnectionRes;
642
+        if(!$this->ldap->isResource($cr)) {
643
+            $cr = $this->getConnectionResource();
644
+        }
645
+
646
+        if(
647
+            count($this->bindResult) !== 0
648
+            && $this->bindResult['dn'] === $this->configuration->ldapAgentName
649
+            && \OC::$server->getHasher()->verify(
650
+                $this->configPrefix . $this->configuration->ldapAgentPassword,
651
+                $this->bindResult['hash']
652
+            )
653
+        ) {
654
+            // don't attempt to bind again with the same data as before
655
+            // bind might have been invoked via getConnectionResource(),
656
+            // but we need results specifically for e.g. user login
657
+            return $this->bindResult['result'];
658
+        }
659
+
660
+        $ldapLogin = @$this->ldap->bind($cr,
661
+                                        $this->configuration->ldapAgentName,
662
+                                        $this->configuration->ldapAgentPassword);
663
+
664
+        $this->bindResult = [
665
+            'dn' => $this->configuration->ldapAgentName,
666
+            'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword),
667
+            'result' => $ldapLogin,
668
+        ];
669
+
670
+        if(!$ldapLogin) {
671
+            $errno = $this->ldap->errno($cr);
672
+
673
+            \OCP\Util::writeLog('user_ldap',
674
+                'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
675
+                ILogger::WARN);
676
+
677
+            // Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
678
+            // or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS
679
+            if($errno !== 0 && $errno !== 49 && $errno !== 50) {
680
+                $this->ldapConnectionRes = null;
681
+            }
682
+
683
+            return false;
684
+        }
685
+        return true;
686
+    }
687 687
 
688 688
 }
Please login to merge, or discard this patch.
Spacing   +65 added lines, -65 removed lines patch added patch discarded remove patch
@@ -110,7 +110,7 @@  discard block
 block discarded – undo
110 110
 		$this->configuration = new Configuration($configPrefix,
111 111
 												 !is_null($configID));
112 112
 		$memcache = \OC::$server->getMemCacheFactory();
113
-		if($memcache->isAvailable()) {
113
+		if ($memcache->isAvailable()) {
114 114
 			$this->cache = $memcache->createDistributed();
115 115
 		}
116 116
 		$helper = new Helper(\OC::$server->getConfig());
@@ -119,7 +119,7 @@  discard block
 block discarded – undo
119 119
 	}
120 120
 
121 121
 	public function __destruct() {
122
-		if(!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
122
+		if (!$this->dontDestruct && $this->ldap->isResource($this->ldapConnectionRes)) {
123 123
 			@$this->ldap->unbind($this->ldapConnectionRes);
124 124
 			$this->bindResult = [];
125 125
 		}
@@ -131,7 +131,7 @@  discard block
 block discarded – undo
131 131
 	public function __clone() {
132 132
 		$this->configuration = new Configuration($this->configPrefix,
133 133
 												 !is_null($this->configID));
134
-		if(count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
134
+		if (count($this->bindResult) !== 0 && $this->bindResult['result'] === true) {
135 135
 			$this->bindResult = [];
136 136
 		}
137 137
 		$this->ldapConnectionRes = null;
@@ -143,7 +143,7 @@  discard block
 block discarded – undo
143 143
 	 * @return bool|mixed
144 144
 	 */
145 145
 	public function __get($name) {
146
-		if(!$this->configured) {
146
+		if (!$this->configured) {
147 147
 			$this->readConfiguration();
148 148
 		}
149 149
 
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 		$before = $this->configuration->$name;
160 160
 		$this->configuration->$name = $value;
161 161
 		$after = $this->configuration->$name;
162
-		if($before !== $after) {
162
+		if ($before !== $after) {
163 163
 			if ($this->configID !== '' && $this->configID !== null) {
164 164
 				$this->configuration->saveConfiguration();
165 165
 			}
@@ -183,7 +183,7 @@  discard block
 block discarded – undo
183 183
 	 * @param bool $state
184 184
 	 */
185 185
 	public function setIgnoreValidation($state) {
186
-		$this->ignoreValidation = (bool)$state;
186
+		$this->ignoreValidation = (bool) $state;
187 187
 	}
188 188
 
189 189
 	/**
@@ -199,14 +199,14 @@  discard block
 block discarded – undo
199 199
 	 * Returns the LDAP handler
200 200
 	 */
201 201
 	public function getConnectionResource() {
202
-		if(!$this->ldapConnectionRes) {
202
+		if (!$this->ldapConnectionRes) {
203 203
 			$this->init();
204
-		} else if(!$this->ldap->isResource($this->ldapConnectionRes)) {
204
+		} else if (!$this->ldap->isResource($this->ldapConnectionRes)) {
205 205
 			$this->ldapConnectionRes = null;
206 206
 			$this->establishConnection();
207 207
 		}
208
-		if(is_null($this->ldapConnectionRes)) {
209
-			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server ' . $this->configuration->ldapHost, ILogger::ERROR);
208
+		if (is_null($this->ldapConnectionRes)) {
209
+			\OCP\Util::writeLog('user_ldap', 'No LDAP Connection to server '.$this->configuration->ldapHost, ILogger::ERROR);
210 210
 			throw new ServerNotAvailableException('Connection to LDAP server could not be established');
211 211
 		}
212 212
 		return $this->ldapConnectionRes;
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 	 * resets the connection resource
217 217
 	 */
218 218
 	public function resetConnectionResource() {
219
-		if(!is_null($this->ldapConnectionRes)) {
219
+		if (!is_null($this->ldapConnectionRes)) {
220 220
 			@$this->ldap->unbind($this->ldapConnectionRes);
221 221
 			$this->ldapConnectionRes = null;
222 222
 			$this->bindResult = [];
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 	 */
230 230
 	private function getCacheKey($key) {
231 231
 		$prefix = 'LDAP-'.$this->configID.'-'.$this->configPrefix.'-';
232
-		if(is_null($key)) {
232
+		if (is_null($key)) {
233 233
 			return $prefix;
234 234
 		}
235 235
 		return $prefix.hash('sha256', $key);
@@ -240,10 +240,10 @@  discard block
 block discarded – undo
240 240
 	 * @return mixed|null
241 241
 	 */
242 242
 	public function getFromCache($key) {
243
-		if(!$this->configured) {
243
+		if (!$this->configured) {
244 244
 			$this->readConfiguration();
245 245
 		}
246
-		if(is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
246
+		if (is_null($this->cache) || !$this->configuration->ldapCacheTTL) {
247 247
 			return null;
248 248
 		}
249 249
 		$key = $this->getCacheKey($key);
@@ -258,10 +258,10 @@  discard block
 block discarded – undo
258 258
 	 * @return string
259 259
 	 */
260 260
 	public function writeToCache($key, $value) {
261
-		if(!$this->configured) {
261
+		if (!$this->configured) {
262 262
 			$this->readConfiguration();
263 263
 		}
264
-		if(is_null($this->cache)
264
+		if (is_null($this->cache)
265 265
 			|| !$this->configuration->ldapCacheTTL
266 266
 			|| !$this->configuration->ldapConfigurationActive) {
267 267
 			return null;
@@ -272,7 +272,7 @@  discard block
 block discarded – undo
272 272
 	}
273 273
 
274 274
 	public function clearCache() {
275
-		if(!is_null($this->cache)) {
275
+		if (!is_null($this->cache)) {
276 276
 			$this->cache->clear($this->getCacheKey(null));
277 277
 		}
278 278
 	}
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 	 * @return null
285 285
 	 */
286 286
 	private function readConfiguration($force = false) {
287
-		if((!$this->configured || $force) && !is_null($this->configID)) {
287
+		if ((!$this->configured || $force) && !is_null($this->configID)) {
288 288
 			$this->configuration->readConfiguration();
289 289
 			$this->configured = $this->validateConfiguration();
290 290
 		}
@@ -297,12 +297,12 @@  discard block
 block discarded – undo
297 297
 	 * @return boolean true if config validates, false otherwise. Check with $setParameters for detailed success on single parameters
298 298
 	 */
299 299
 	public function setConfiguration($config, &$setParameters = null) {
300
-		if(is_null($setParameters)) {
300
+		if (is_null($setParameters)) {
301 301
 			$setParameters = [];
302 302
 		}
303 303
 		$this->doNotValidate = false;
304 304
 		$this->configuration->setConfiguration($config, $setParameters);
305
-		if(count($setParameters) > 0) {
305
+		if (count($setParameters) > 0) {
306 306
 			$this->configured = $this->validateConfiguration();
307 307
 		}
308 308
 
@@ -329,10 +329,10 @@  discard block
 block discarded – undo
329 329
 		$config = $this->configuration->getConfiguration();
330 330
 		$cta = $this->configuration->getConfigTranslationArray();
331 331
 		$result = [];
332
-		foreach($cta as $dbkey => $configkey) {
333
-			switch($configkey) {
332
+		foreach ($cta as $dbkey => $configkey) {
333
+			switch ($configkey) {
334 334
 				case 'homeFolderNamingRule':
335
-					if(strpos($config[$configkey], 'attr:') === 0) {
335
+					if (strpos($config[$configkey], 'attr:') === 0) {
336 336
 						$result[$dbkey] = substr($config[$configkey], 5);
337 337
 					} else {
338 338
 						$result[$dbkey] = '';
@@ -343,7 +343,7 @@  discard block
 block discarded – undo
343 343
 				case 'ldapBaseGroups':
344 344
 				case 'ldapAttributesForUserSearch':
345 345
 				case 'ldapAttributesForGroupSearch':
346
-					if(is_array($config[$configkey])) {
346
+					if (is_array($config[$configkey])) {
347 347
 						$result[$dbkey] = implode("\n", $config[$configkey]);
348 348
 						break;
349 349
 					} //else follows default
@@ -356,23 +356,23 @@  discard block
 block discarded – undo
356 356
 
357 357
 	private function doSoftValidation() {
358 358
 		//if User or Group Base are not set, take over Base DN setting
359
-		foreach(['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
359
+		foreach (['ldapBaseUsers', 'ldapBaseGroups'] as $keyBase) {
360 360
 			$val = $this->configuration->$keyBase;
361
-			if(empty($val)) {
361
+			if (empty($val)) {
362 362
 				$this->configuration->$keyBase = $this->configuration->ldapBase;
363 363
 			}
364 364
 		}
365 365
 
366
-		foreach(['ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
366
+		foreach (['ldapExpertUUIDUserAttr'  => 'ldapUuidUserAttribute',
367 367
 					  'ldapExpertUUIDGroupAttr' => 'ldapUuidGroupAttribute']
368 368
 				as $expertSetting => $effectiveSetting) {
369 369
 			$uuidOverride = $this->configuration->$expertSetting;
370
-			if(!empty($uuidOverride)) {
370
+			if (!empty($uuidOverride)) {
371 371
 				$this->configuration->$effectiveSetting = $uuidOverride;
372 372
 			} else {
373 373
 				$uuidAttributes = Access::UUID_ATTRIBUTES;
374 374
 				array_unshift($uuidAttributes, 'auto');
375
-				if(!in_array($this->configuration->$effectiveSetting,
375
+				if (!in_array($this->configuration->$effectiveSetting,
376 376
 							$uuidAttributes)
377 377
 					&& (!is_null($this->configID))) {
378 378
 					$this->configuration->$effectiveSetting = 'auto';
@@ -386,7 +386,7 @@  discard block
 block discarded – undo
386 386
 			}
387 387
 		}
388 388
 
389
-		$backupPort = (int)$this->configuration->ldapBackupPort;
389
+		$backupPort = (int) $this->configuration->ldapBackupPort;
390 390
 		if ($backupPort <= 0) {
391 391
 			$this->configuration->backupPort = $this->configuration->ldapPort;
392 392
 		}
@@ -394,14 +394,14 @@  discard block
 block discarded – undo
394 394
 		//make sure empty search attributes are saved as simple, empty array
395 395
 		$saKeys = ['ldapAttributesForUserSearch',
396 396
 						'ldapAttributesForGroupSearch'];
397
-		foreach($saKeys as $key) {
397
+		foreach ($saKeys as $key) {
398 398
 			$val = $this->configuration->$key;
399
-			if(is_array($val) && count($val) === 1 && empty($val[0])) {
399
+			if (is_array($val) && count($val) === 1 && empty($val[0])) {
400 400
 				$this->configuration->$key = [];
401 401
 			}
402 402
 		}
403 403
 
404
-		if((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
404
+		if ((stripos($this->configuration->ldapHost, 'ldaps://') === 0)
405 405
 			&& $this->configuration->ldapTLS) {
406 406
 			$this->configuration->ldapTLS = false;
407 407
 			\OCP\Util::writeLog(
@@ -418,15 +418,15 @@  discard block
 block discarded – undo
418 418
 	private function doCriticalValidation() {
419 419
 		$configurationOK = true;
420 420
 		$errorStr = 'Configuration Error (prefix '.
421
-			(string)$this->configPrefix .'): ';
421
+			(string) $this->configPrefix.'): ';
422 422
 
423 423
 		//options that shall not be empty
424 424
 		$options = ['ldapHost', 'ldapPort', 'ldapUserDisplayName',
425 425
 						 'ldapGroupDisplayName', 'ldapLoginFilter'];
426
-		foreach($options as $key) {
426
+		foreach ($options as $key) {
427 427
 			$val = $this->configuration->$key;
428
-			if(empty($val)) {
429
-				switch($key) {
428
+			if (empty($val)) {
429
+				switch ($key) {
430 430
 					case 'ldapHost':
431 431
 						$subj = 'LDAP Host';
432 432
 						break;
@@ -459,12 +459,12 @@  discard block
 block discarded – undo
459 459
 		$agent = $this->configuration->ldapAgentName;
460 460
 		$pwd = $this->configuration->ldapAgentPassword;
461 461
 		if (
462
-			($agent === ''  && $pwd !== '')
462
+			($agent === '' && $pwd !== '')
463 463
 			|| ($agent !== '' && $pwd === '')
464 464
 		) {
465 465
 			\OCP\Util::writeLog(
466 466
 				'user_ldap',
467
-				$errorStr.'either no password is given for the user ' .
467
+				$errorStr.'either no password is given for the user '.
468 468
 					'agent or a password is given, but not an LDAP agent.',
469 469
 				ILogger::WARN);
470 470
 			$configurationOK = false;
@@ -474,7 +474,7 @@  discard block
 block discarded – undo
474 474
 		$baseUsers = $this->configuration->ldapBaseUsers;
475 475
 		$baseGroups = $this->configuration->ldapBaseGroups;
476 476
 
477
-		if(empty($base) && empty($baseUsers) && empty($baseGroups)) {
477
+		if (empty($base) && empty($baseUsers) && empty($baseGroups)) {
478 478
 			\OCP\Util::writeLog(
479 479
 				'user_ldap',
480 480
 				$errorStr.'Not a single Base DN given.',
@@ -483,7 +483,7 @@  discard block
 block discarded – undo
483 483
 			$configurationOK = false;
484 484
 		}
485 485
 
486
-		if(mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
486
+		if (mb_strpos($this->configuration->ldapLoginFilter, '%uid', 0, 'UTF-8')
487 487
 		   === false) {
488 488
 			\OCP\Util::writeLog(
489 489
 				'user_ldap',
@@ -502,7 +502,7 @@  discard block
 block discarded – undo
502 502
 	 */
503 503
 	private function validateConfiguration() {
504 504
 
505
-		if($this->doNotValidate) {
505
+		if ($this->doNotValidate) {
506 506
 			//don't do a validation if it is a new configuration with pure
507 507
 			//default values. Will be allowed on changes via __set or
508 508
 			//setConfiguration
@@ -525,14 +525,14 @@  discard block
 block discarded – undo
525 525
 	 * @throws ServerNotAvailableException
526 526
 	 */
527 527
 	private function establishConnection() {
528
-		if(!$this->configuration->ldapConfigurationActive) {
528
+		if (!$this->configuration->ldapConfigurationActive) {
529 529
 			return null;
530 530
 		}
531 531
 		static $phpLDAPinstalled = true;
532
-		if(!$phpLDAPinstalled) {
532
+		if (!$phpLDAPinstalled) {
533 533
 			return false;
534 534
 		}
535
-		if(!$this->ignoreValidation && !$this->configured) {
535
+		if (!$this->ignoreValidation && !$this->configured) {
536 536
 			\OCP\Util::writeLog(
537 537
 				'user_ldap',
538 538
 				'Configuration is invalid, cannot connect',
@@ -540,8 +540,8 @@  discard block
 block discarded – undo
540 540
 			);
541 541
 			return false;
542 542
 		}
543
-		if(!$this->ldapConnectionRes) {
544
-			if(!$this->ldap->areLDAPFunctionsAvailable()) {
543
+		if (!$this->ldapConnectionRes) {
544
+			if (!$this->ldap->areLDAPFunctionsAvailable()) {
545 545
 				$phpLDAPinstalled = false;
546 546
 				\OCP\Util::writeLog(
547 547
 					'user_ldap',
@@ -551,8 +551,8 @@  discard block
 block discarded – undo
551 551
 
552 552
 				return false;
553 553
 			}
554
-			if($this->configuration->turnOffCertCheck) {
555
-				if(putenv('LDAPTLS_REQCERT=never')) {
554
+			if ($this->configuration->turnOffCertCheck) {
555
+				if (putenv('LDAPTLS_REQCERT=never')) {
556 556
 					\OCP\Util::writeLog('user_ldap',
557 557
 						'Turned off SSL certificate validation successfully.',
558 558
 						ILogger::DEBUG);
@@ -576,20 +576,20 @@  discard block
 block discarded – undo
576 576
 					return $this->bind();
577 577
 				}
578 578
 			} catch (ServerNotAvailableException $e) {
579
-				if(!$isBackupHost) {
579
+				if (!$isBackupHost) {
580 580
 					throw $e;
581 581
 				}
582 582
 			}
583 583
 
584 584
 			//if LDAP server is not reachable, try the Backup (Replica!) Server
585
-			if($isBackupHost || $isOverrideMainServer) {
585
+			if ($isBackupHost || $isOverrideMainServer) {
586 586
 				$this->doConnect($this->configuration->ldapBackupHost,
587 587
 								 $this->configuration->ldapBackupPort);
588 588
 				$this->bindResult = [];
589 589
 				$bindStatus = $this->bind();
590 590
 				$error = $this->ldap->isResource($this->ldapConnectionRes) ?
591 591
 					$this->ldap->errno($this->ldapConnectionRes) : -1;
592
-				if($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
592
+				if ($bindStatus && $error === 0 && !$this->getFromCache('overrideMainServer')) {
593 593
 					//when bind to backup server succeeded and failed to main server,
594 594
 					//skip contacting him until next cache refresh
595 595
 					$this->writeToCache('overrideMainServer', true);
@@ -614,17 +614,17 @@  discard block
 block discarded – undo
614 614
 
615 615
 		$this->ldapConnectionRes = $this->ldap->connect($host, $port);
616 616
 
617
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
617
+		if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_PROTOCOL_VERSION, 3)) {
618 618
 			throw new ServerNotAvailableException('Could not set required LDAP Protocol version.');
619 619
 		}
620 620
 
621
-		if(!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
621
+		if (!$this->ldap->setOption($this->ldapConnectionRes, LDAP_OPT_REFERRALS, 0)) {
622 622
 			throw new ServerNotAvailableException('Could not disable LDAP referrals.');
623 623
 		}
624 624
 
625
-		if($this->configuration->ldapTLS) {
626
-			if(!$this->ldap->startTls($this->ldapConnectionRes)) {
627
-				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host ' . $host . '.');
625
+		if ($this->configuration->ldapTLS) {
626
+			if (!$this->ldap->startTls($this->ldapConnectionRes)) {
627
+				throw new ServerNotAvailableException('Start TLS failed, when connecting to LDAP host '.$host.'.');
628 628
 			}
629 629
 		}
630 630
 
@@ -635,19 +635,19 @@  discard block
 block discarded – undo
635 635
 	 * Binds to LDAP
636 636
 	 */
637 637
 	public function bind() {
638
-		if(!$this->configuration->ldapConfigurationActive) {
638
+		if (!$this->configuration->ldapConfigurationActive) {
639 639
 			return false;
640 640
 		}
641 641
 		$cr = $this->ldapConnectionRes;
642
-		if(!$this->ldap->isResource($cr)) {
642
+		if (!$this->ldap->isResource($cr)) {
643 643
 			$cr = $this->getConnectionResource();
644 644
 		}
645 645
 
646
-		if(
646
+		if (
647 647
 			count($this->bindResult) !== 0
648 648
 			&& $this->bindResult['dn'] === $this->configuration->ldapAgentName
649 649
 			&& \OC::$server->getHasher()->verify(
650
-				$this->configPrefix . $this->configuration->ldapAgentPassword,
650
+				$this->configPrefix.$this->configuration->ldapAgentPassword,
651 651
 				$this->bindResult['hash']
652 652
 			)
653 653
 		) {
@@ -663,20 +663,20 @@  discard block
 block discarded – undo
663 663
 
664 664
 		$this->bindResult = [
665 665
 			'dn' => $this->configuration->ldapAgentName,
666
-			'hash' => \OC::$server->getHasher()->hash($this->configPrefix . $this->configuration->ldapAgentPassword),
666
+			'hash' => \OC::$server->getHasher()->hash($this->configPrefix.$this->configuration->ldapAgentPassword),
667 667
 			'result' => $ldapLogin,
668 668
 		];
669 669
 
670
-		if(!$ldapLogin) {
670
+		if (!$ldapLogin) {
671 671
 			$errno = $this->ldap->errno($cr);
672 672
 
673 673
 			\OCP\Util::writeLog('user_ldap',
674
-				'Bind failed: ' . $errno . ': ' . $this->ldap->error($cr),
674
+				'Bind failed: '.$errno.': '.$this->ldap->error($cr),
675 675
 				ILogger::WARN);
676 676
 
677 677
 			// Set to failure mode, if LDAP error code is not LDAP_SUCCESS or LDAP_INVALID_CREDENTIALS
678 678
 			// or (needed for Apple Open Directory:) LDAP_INSUFFICIENT_ACCESS
679
-			if($errno !== 0 && $errno !== 49 && $errno !== 50) {
679
+			if ($errno !== 0 && $errno !== 49 && $errno !== 50) {
680 680
 				$this->ldapConnectionRes = null;
681 681
 			}
682 682
 
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/GroupPluginManager.php 1 patch
Indentation   +139 added lines, -139 removed lines patch added patch discarded remove patch
@@ -27,143 +27,143 @@
 block discarded – undo
27 27
 
28 28
 class GroupPluginManager {
29 29
 
30
-	private $respondToActions = 0;
31
-
32
-	private $which = [
33
-		GroupInterface::CREATE_GROUP => null,
34
-		GroupInterface::DELETE_GROUP => null,
35
-		GroupInterface::ADD_TO_GROUP => null,
36
-		GroupInterface::REMOVE_FROM_GROUP => null,
37
-		GroupInterface::COUNT_USERS => null,
38
-		GroupInterface::GROUP_DETAILS => null
39
-	];
40
-
41
-	/**
42
-	 * @return int All implemented actions
43
-	 */
44
-	public function getImplementedActions() {
45
-		return $this->respondToActions;
46
-	}
47
-
48
-	/**
49
-	 * Registers a group plugin that may implement some actions, overriding User_LDAP's group actions.
50
-	 * @param ILDAPGroupPlugin $plugin
51
-	 */
52
-	public function register(ILDAPGroupPlugin $plugin) {
53
-		$respondToActions = $plugin->respondToActions();
54
-		$this->respondToActions |= $respondToActions;
55
-
56
-		foreach($this->which as $action => $v) {
57
-			if ((bool)($respondToActions & $action)) {
58
-				$this->which[$action] = $plugin;
59
-				\OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']);
60
-			}
61
-		}
62
-	}
63
-
64
-	/**
65
-	 * Signal if there is a registered plugin that implements some given actions
66
-	 * @param int $actions Actions defined in \OCP\GroupInterface, like GroupInterface::REMOVE_FROM_GROUP
67
-	 * @return bool
68
-	 */
69
-	public function implementsActions($actions) {
70
-		return ($actions & $this->respondToActions) == $actions;
71
-	}
72
-
73
-	/**
74
-	 * Create a group
75
-	 * @param string $gid Group Id
76
-	 * @return string | null The group DN if group creation was successful.
77
-	 * @throws \Exception
78
-	 */
79
-	public function createGroup($gid) {
80
-		$plugin = $this->which[GroupInterface::CREATE_GROUP];
81
-
82
-		if ($plugin) {
83
-			return $plugin->createGroup($gid);
84
-		}
85
-		throw new \Exception('No plugin implements createGroup in this LDAP Backend.');
86
-	}
87
-
88
-	/**
89
-	 * Delete a group
90
-	 * @param string $gid Group Id of the group to delete
91
-	 * @return bool
92
-	 * @throws \Exception
93
-	 */
94
-	public function deleteGroup($gid) {
95
-		$plugin = $this->which[GroupInterface::DELETE_GROUP];
96
-
97
-		if ($plugin) {
98
-			return $plugin->deleteGroup($gid);
99
-		}
100
-		throw new \Exception('No plugin implements deleteGroup in this LDAP Backend.');
101
-	}
102
-
103
-	/**
104
-	 * Add a user to a group
105
-	 * @param string $uid ID of the user to add to group
106
-	 * @param string $gid ID of the group in which add the user
107
-	 * @return bool
108
-	 * @throws \Exception
109
-	 *
110
-	 * Adds a user to a group.
111
-	 */
112
-	public function addToGroup($uid, $gid) {
113
-		$plugin = $this->which[GroupInterface::ADD_TO_GROUP];
114
-
115
-		if ($plugin) {
116
-			return $plugin->addToGroup($uid, $gid);
117
-		}
118
-		throw new \Exception('No plugin implements addToGroup in this LDAP Backend.');
119
-	}
120
-
121
-	/**
122
-	 * Removes a user from a group
123
-	 * @param string $uid ID of the user to remove from group
124
-	 * @param string $gid ID of the group from which remove the user
125
-	 * @return bool
126
-	 * @throws \Exception
127
-	 *
128
-	 * removes the user from a group.
129
-	 */
130
-	public function removeFromGroup($uid, $gid) {
131
-		$plugin = $this->which[GroupInterface::REMOVE_FROM_GROUP];
132
-
133
-		if ($plugin) {
134
-			return $plugin->removeFromGroup($uid, $gid);
135
-		}
136
-		throw new \Exception('No plugin implements removeFromGroup in this LDAP Backend.');
137
-	}
138
-
139
-	/**
140
-	 * get the number of all users matching the search string in a group
141
-	 * @param string $gid ID of the group
142
-	 * @param string $search query string
143
-	 * @return int|false
144
-	 * @throws \Exception
145
-	 */
146
-	public function countUsersInGroup($gid, $search = '') {
147
-		$plugin = $this->which[GroupInterface::COUNT_USERS];
148
-
149
-		if ($plugin) {
150
-			return $plugin->countUsersInGroup($gid,$search);
151
-		}
152
-		throw new \Exception('No plugin implements countUsersInGroup in this LDAP Backend.');
153
-	}
154
-
155
-	/**
156
-	 * get an array with group details
157
-	 * @param string $gid
158
-	 * @return array|false
159
-	 * @throws \Exception
160
-	 */
161
-	public function getGroupDetails($gid) {
162
-		$plugin = $this->which[GroupInterface::GROUP_DETAILS];
163
-
164
-		if ($plugin) {
165
-			return $plugin->getGroupDetails($gid);
166
-		}
167
-		throw new \Exception('No plugin implements getGroupDetails in this LDAP Backend.');
168
-	}
30
+    private $respondToActions = 0;
31
+
32
+    private $which = [
33
+        GroupInterface::CREATE_GROUP => null,
34
+        GroupInterface::DELETE_GROUP => null,
35
+        GroupInterface::ADD_TO_GROUP => null,
36
+        GroupInterface::REMOVE_FROM_GROUP => null,
37
+        GroupInterface::COUNT_USERS => null,
38
+        GroupInterface::GROUP_DETAILS => null
39
+    ];
40
+
41
+    /**
42
+     * @return int All implemented actions
43
+     */
44
+    public function getImplementedActions() {
45
+        return $this->respondToActions;
46
+    }
47
+
48
+    /**
49
+     * Registers a group plugin that may implement some actions, overriding User_LDAP's group actions.
50
+     * @param ILDAPGroupPlugin $plugin
51
+     */
52
+    public function register(ILDAPGroupPlugin $plugin) {
53
+        $respondToActions = $plugin->respondToActions();
54
+        $this->respondToActions |= $respondToActions;
55
+
56
+        foreach($this->which as $action => $v) {
57
+            if ((bool)($respondToActions & $action)) {
58
+                $this->which[$action] = $plugin;
59
+                \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']);
60
+            }
61
+        }
62
+    }
63
+
64
+    /**
65
+     * Signal if there is a registered plugin that implements some given actions
66
+     * @param int $actions Actions defined in \OCP\GroupInterface, like GroupInterface::REMOVE_FROM_GROUP
67
+     * @return bool
68
+     */
69
+    public function implementsActions($actions) {
70
+        return ($actions & $this->respondToActions) == $actions;
71
+    }
72
+
73
+    /**
74
+     * Create a group
75
+     * @param string $gid Group Id
76
+     * @return string | null The group DN if group creation was successful.
77
+     * @throws \Exception
78
+     */
79
+    public function createGroup($gid) {
80
+        $plugin = $this->which[GroupInterface::CREATE_GROUP];
81
+
82
+        if ($plugin) {
83
+            return $plugin->createGroup($gid);
84
+        }
85
+        throw new \Exception('No plugin implements createGroup in this LDAP Backend.');
86
+    }
87
+
88
+    /**
89
+     * Delete a group
90
+     * @param string $gid Group Id of the group to delete
91
+     * @return bool
92
+     * @throws \Exception
93
+     */
94
+    public function deleteGroup($gid) {
95
+        $plugin = $this->which[GroupInterface::DELETE_GROUP];
96
+
97
+        if ($plugin) {
98
+            return $plugin->deleteGroup($gid);
99
+        }
100
+        throw new \Exception('No plugin implements deleteGroup in this LDAP Backend.');
101
+    }
102
+
103
+    /**
104
+     * Add a user to a group
105
+     * @param string $uid ID of the user to add to group
106
+     * @param string $gid ID of the group in which add the user
107
+     * @return bool
108
+     * @throws \Exception
109
+     *
110
+     * Adds a user to a group.
111
+     */
112
+    public function addToGroup($uid, $gid) {
113
+        $plugin = $this->which[GroupInterface::ADD_TO_GROUP];
114
+
115
+        if ($plugin) {
116
+            return $plugin->addToGroup($uid, $gid);
117
+        }
118
+        throw new \Exception('No plugin implements addToGroup in this LDAP Backend.');
119
+    }
120
+
121
+    /**
122
+     * Removes a user from a group
123
+     * @param string $uid ID of the user to remove from group
124
+     * @param string $gid ID of the group from which remove the user
125
+     * @return bool
126
+     * @throws \Exception
127
+     *
128
+     * removes the user from a group.
129
+     */
130
+    public function removeFromGroup($uid, $gid) {
131
+        $plugin = $this->which[GroupInterface::REMOVE_FROM_GROUP];
132
+
133
+        if ($plugin) {
134
+            return $plugin->removeFromGroup($uid, $gid);
135
+        }
136
+        throw new \Exception('No plugin implements removeFromGroup in this LDAP Backend.');
137
+    }
138
+
139
+    /**
140
+     * get the number of all users matching the search string in a group
141
+     * @param string $gid ID of the group
142
+     * @param string $search query string
143
+     * @return int|false
144
+     * @throws \Exception
145
+     */
146
+    public function countUsersInGroup($gid, $search = '') {
147
+        $plugin = $this->which[GroupInterface::COUNT_USERS];
148
+
149
+        if ($plugin) {
150
+            return $plugin->countUsersInGroup($gid,$search);
151
+        }
152
+        throw new \Exception('No plugin implements countUsersInGroup in this LDAP Backend.');
153
+    }
154
+
155
+    /**
156
+     * get an array with group details
157
+     * @param string $gid
158
+     * @return array|false
159
+     * @throws \Exception
160
+     */
161
+    public function getGroupDetails($gid) {
162
+        $plugin = $this->which[GroupInterface::GROUP_DETAILS];
163
+
164
+        if ($plugin) {
165
+            return $plugin->getGroupDetails($gid);
166
+        }
167
+        throw new \Exception('No plugin implements getGroupDetails in this LDAP Backend.');
168
+    }
169 169
 }
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
@@ -63,1779 +63,1779 @@  discard block
 block discarded – undo
63 63
  * @package OCA\User_LDAP
64 64
  */
65 65
 class Access extends LDAPUtility {
66
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
67
-
68
-	/** @var \OCA\User_LDAP\Connection */
69
-	public $connection;
70
-	/** @var Manager */
71
-	public $userManager;
72
-	//never ever check this var directly, always use getPagedSearchResultState
73
-	protected $pagedSearchedSuccessful;
74
-
75
-	/**
76
-	 * @var string[] $cookies an array of returned Paged Result cookies
77
-	 */
78
-	protected $cookies = [];
79
-
80
-	/**
81
-	 * @var string $lastCookie the last cookie returned from a Paged Results
82
-	 * operation, defaults to an empty string
83
-	 */
84
-	protected $lastCookie = '';
85
-
86
-	/**
87
-	 * @var AbstractMapping $userMapper
88
-	 */
89
-	protected $userMapper;
90
-
91
-	/**
92
-	* @var AbstractMapping $userMapper
93
-	*/
94
-	protected $groupMapper;
95
-
96
-	/**
97
-	 * @var \OCA\User_LDAP\Helper
98
-	 */
99
-	private $helper;
100
-	/** @var IConfig */
101
-	private $config;
102
-	/** @var IUserManager */
103
-	private $ncUserManager;
104
-
105
-	public function __construct(
106
-		Connection $connection,
107
-		ILDAPWrapper $ldap,
108
-		Manager $userManager,
109
-		Helper $helper,
110
-		IConfig $config,
111
-		IUserManager $ncUserManager
112
-	) {
113
-		parent::__construct($ldap);
114
-		$this->connection = $connection;
115
-		$this->userManager = $userManager;
116
-		$this->userManager->setLdapAccess($this);
117
-		$this->helper = $helper;
118
-		$this->config = $config;
119
-		$this->ncUserManager = $ncUserManager;
120
-	}
121
-
122
-	/**
123
-	 * sets the User Mapper
124
-	 * @param AbstractMapping $mapper
125
-	 */
126
-	public function setUserMapper(AbstractMapping $mapper) {
127
-		$this->userMapper = $mapper;
128
-	}
129
-
130
-	/**
131
-	 * returns the User Mapper
132
-	 * @throws \Exception
133
-	 * @return AbstractMapping
134
-	 */
135
-	public function getUserMapper() {
136
-		if(is_null($this->userMapper)) {
137
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
138
-		}
139
-		return $this->userMapper;
140
-	}
141
-
142
-	/**
143
-	 * sets the Group Mapper
144
-	 * @param AbstractMapping $mapper
145
-	 */
146
-	public function setGroupMapper(AbstractMapping $mapper) {
147
-		$this->groupMapper = $mapper;
148
-	}
149
-
150
-	/**
151
-	 * returns the Group Mapper
152
-	 * @throws \Exception
153
-	 * @return AbstractMapping
154
-	 */
155
-	public function getGroupMapper() {
156
-		if(is_null($this->groupMapper)) {
157
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
158
-		}
159
-		return $this->groupMapper;
160
-	}
161
-
162
-	/**
163
-	 * @return bool
164
-	 */
165
-	private function checkConnection() {
166
-		return ($this->connection instanceof Connection);
167
-	}
168
-
169
-	/**
170
-	 * returns the Connection instance
171
-	 * @return \OCA\User_LDAP\Connection
172
-	 */
173
-	public function getConnection() {
174
-		return $this->connection;
175
-	}
176
-
177
-	/**
178
-	 * reads a given attribute for an LDAP record identified by a DN
179
-	 *
180
-	 * @param string $dn the record in question
181
-	 * @param string $attr the attribute that shall be retrieved
182
-	 *        if empty, just check the record's existence
183
-	 * @param string $filter
184
-	 * @return array|false an array of values on success or an empty
185
-	 *          array if $attr is empty, false otherwise
186
-	 * @throws ServerNotAvailableException
187
-	 */
188
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
189
-		if(!$this->checkConnection()) {
190
-			\OCP\Util::writeLog('user_ldap',
191
-				'No LDAP Connector assigned, access impossible for readAttribute.',
192
-				ILogger::WARN);
193
-			return false;
194
-		}
195
-		$cr = $this->connection->getConnectionResource();
196
-		if(!$this->ldap->isResource($cr)) {
197
-			//LDAP not available
198
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
199
-			return false;
200
-		}
201
-		//Cancel possibly running Paged Results operation, otherwise we run in
202
-		//LDAP protocol errors
203
-		$this->abandonPagedSearch();
204
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
205
-		// but does not hurt either.
206
-		$pagingSize = (int)$this->connection->ldapPagingSize;
207
-		// 0 won't result in replies, small numbers may leave out groups
208
-		// (cf. #12306), 500 is default for paging and should work everywhere.
209
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
210
-		$attr = mb_strtolower($attr, 'UTF-8');
211
-		// the actual read attribute later may contain parameters on a ranged
212
-		// request, e.g. member;range=99-199. Depends on server reply.
213
-		$attrToRead = $attr;
214
-
215
-		$values = [];
216
-		$isRangeRequest = false;
217
-		do {
218
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
219
-			if(is_bool($result)) {
220
-				// when an exists request was run and it was successful, an empty
221
-				// array must be returned
222
-				return $result ? [] : false;
223
-			}
224
-
225
-			if (!$isRangeRequest) {
226
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
227
-				if (!empty($values)) {
228
-					return $values;
229
-				}
230
-			}
231
-
232
-			$isRangeRequest = false;
233
-			$result = $this->extractRangeData($result, $attr);
234
-			if (!empty($result)) {
235
-				$normalizedResult = $this->extractAttributeValuesFromResult(
236
-					[ $attr => $result['values'] ],
237
-					$attr
238
-				);
239
-				$values = array_merge($values, $normalizedResult);
240
-
241
-				if($result['rangeHigh'] === '*') {
242
-					// when server replies with * as high range value, there are
243
-					// no more results left
244
-					return $values;
245
-				} else {
246
-					$low  = $result['rangeHigh'] + 1;
247
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
248
-					$isRangeRequest = true;
249
-				}
250
-			}
251
-		} while($isRangeRequest);
252
-
253
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
254
-		return false;
255
-	}
256
-
257
-	/**
258
-	 * Runs an read operation against LDAP
259
-	 *
260
-	 * @param resource $cr the LDAP connection
261
-	 * @param string $dn
262
-	 * @param string $attribute
263
-	 * @param string $filter
264
-	 * @param int $maxResults
265
-	 * @return array|bool false if there was any error, true if an exists check
266
-	 *                    was performed and the requested DN found, array with the
267
-	 *                    returned data on a successful usual operation
268
-	 * @throws ServerNotAvailableException
269
-	 */
270
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
271
-		$this->initPagedSearch($filter, [$dn], [$attribute], $maxResults, 0);
272
-		$dn = $this->helper->DNasBaseParameter($dn);
273
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
274
-		if (!$this->ldap->isResource($rr)) {
275
-			if ($attribute !== '') {
276
-				//do not throw this message on userExists check, irritates
277
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
278
-			}
279
-			//in case an error occurs , e.g. object does not exist
280
-			return false;
281
-		}
282
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
283
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
284
-			return true;
285
-		}
286
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
287
-		if (!$this->ldap->isResource($er)) {
288
-			//did not match the filter, return false
289
-			return false;
290
-		}
291
-		//LDAP attributes are not case sensitive
292
-		$result = \OCP\Util::mb_array_change_key_case(
293
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
294
-
295
-		return $result;
296
-	}
297
-
298
-	/**
299
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
300
-	 * data if present.
301
-	 *
302
-	 * @param array $result from ILDAPWrapper::getAttributes()
303
-	 * @param string $attribute the attribute name that was read
304
-	 * @return string[]
305
-	 */
306
-	public function extractAttributeValuesFromResult($result, $attribute) {
307
-		$values = [];
308
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
309
-			$lowercaseAttribute = strtolower($attribute);
310
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
311
-				if($this->resemblesDN($attribute)) {
312
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
313
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
314
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
315
-				} else {
316
-					$values[] = $result[$attribute][$i];
317
-				}
318
-			}
319
-		}
320
-		return $values;
321
-	}
322
-
323
-	/**
324
-	 * Attempts to find ranged data in a getAttribute results and extracts the
325
-	 * returned values as well as information on the range and full attribute
326
-	 * name for further processing.
327
-	 *
328
-	 * @param array $result from ILDAPWrapper::getAttributes()
329
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
330
-	 * @return array If a range was detected with keys 'values', 'attributeName',
331
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
332
-	 */
333
-	public function extractRangeData($result, $attribute) {
334
-		$keys = array_keys($result);
335
-		foreach($keys as $key) {
336
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
337
-				$queryData = explode(';', $key);
338
-				if(strpos($queryData[1], 'range=') === 0) {
339
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
340
-					$data = [
341
-						'values' => $result[$key],
342
-						'attributeName' => $queryData[0],
343
-						'attributeFull' => $key,
344
-						'rangeHigh' => $high,
345
-					];
346
-					return $data;
347
-				}
348
-			}
349
-		}
350
-		return [];
351
-	}
352
-
353
-	/**
354
-	 * Set password for an LDAP user identified by a DN
355
-	 *
356
-	 * @param string $userDN the user in question
357
-	 * @param string $password the new password
358
-	 * @return bool
359
-	 * @throws HintException
360
-	 * @throws \Exception
361
-	 */
362
-	public function setPassword($userDN, $password) {
363
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
364
-			throw new \Exception('LDAP password changes are disabled.');
365
-		}
366
-		$cr = $this->connection->getConnectionResource();
367
-		if(!$this->ldap->isResource($cr)) {
368
-			//LDAP not available
369
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
370
-			return false;
371
-		}
372
-		try {
373
-			// try PASSWD extended operation first
374
-			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
375
-						@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
376
-		} catch(ConstraintViolationException $e) {
377
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
378
-		}
379
-	}
380
-
381
-	/**
382
-	 * checks whether the given attributes value is probably a DN
383
-	 * @param string $attr the attribute in question
384
-	 * @return boolean if so true, otherwise false
385
-	 */
386
-	private function resemblesDN($attr) {
387
-		$resemblingAttributes = [
388
-			'dn',
389
-			'uniquemember',
390
-			'member',
391
-			// memberOf is an "operational" attribute, without a definition in any RFC
392
-			'memberof'
393
-		];
394
-		return in_array($attr, $resemblingAttributes);
395
-	}
396
-
397
-	/**
398
-	 * checks whether the given string is probably a DN
399
-	 * @param string $string
400
-	 * @return boolean
401
-	 */
402
-	public function stringResemblesDN($string) {
403
-		$r = $this->ldap->explodeDN($string, 0);
404
-		// if exploding a DN succeeds and does not end up in
405
-		// an empty array except for $r[count] being 0.
406
-		return (is_array($r) && count($r) > 1);
407
-	}
408
-
409
-	/**
410
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
411
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
412
-	 * becomes dc=foobar,dc=server,dc=org
413
-	 * @param string $dn
414
-	 * @return string
415
-	 */
416
-	public function getDomainDNFromDN($dn) {
417
-		$allParts = $this->ldap->explodeDN($dn, 0);
418
-		if($allParts === false) {
419
-			//not a valid DN
420
-			return '';
421
-		}
422
-		$domainParts = [];
423
-		$dcFound = false;
424
-		foreach($allParts as $part) {
425
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
426
-				$dcFound = true;
427
-			}
428
-			if($dcFound) {
429
-				$domainParts[] = $part;
430
-			}
431
-		}
432
-		return implode(',', $domainParts);
433
-	}
434
-
435
-	/**
436
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
437
-	 * @param string $name the Nextcloud name in question
438
-	 * @return string|false LDAP DN on success, otherwise false
439
-	 */
440
-	public function groupname2dn($name) {
441
-		return $this->groupMapper->getDNByName($name);
442
-	}
443
-
444
-	/**
445
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
446
-	 * @param string $name the Nextcloud name in question
447
-	 * @return string|false with the LDAP DN on success, otherwise false
448
-	 */
449
-	public function username2dn($name) {
450
-		$fdn = $this->userMapper->getDNByName($name);
451
-
452
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
453
-		//server setups
454
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
455
-			return $fdn;
456
-		}
457
-
458
-		return false;
459
-	}
460
-
461
-	/**
462
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
463
-	 *
464
-	 * @param string $fdn the dn of the group object
465
-	 * @param string $ldapName optional, the display name of the object
466
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
467
-	 * @throws \Exception
468
-	 */
469
-	public function dn2groupname($fdn, $ldapName = null) {
470
-		//To avoid bypassing the base DN settings under certain circumstances
471
-		//with the group support, check whether the provided DN matches one of
472
-		//the given Bases
473
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
474
-			return false;
475
-		}
476
-
477
-		return $this->dn2ocname($fdn, $ldapName, false);
478
-	}
479
-
480
-	/**
481
-	 * accepts an array of group DNs and tests whether they match the user
482
-	 * filter by doing read operations against the group entries. Returns an
483
-	 * array of DNs that match the filter.
484
-	 *
485
-	 * @param string[] $groupDNs
486
-	 * @return string[]
487
-	 * @throws ServerNotAvailableException
488
-	 */
489
-	public function groupsMatchFilter($groupDNs) {
490
-		$validGroupDNs = [];
491
-		foreach($groupDNs as $dn) {
492
-			$cacheKey = 'groupsMatchFilter-'.$dn;
493
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
494
-			if(!is_null($groupMatchFilter)) {
495
-				if($groupMatchFilter) {
496
-					$validGroupDNs[] = $dn;
497
-				}
498
-				continue;
499
-			}
500
-
501
-			// Check the base DN first. If this is not met already, we don't
502
-			// need to ask the server at all.
503
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
504
-				$this->connection->writeToCache($cacheKey, false);
505
-				continue;
506
-			}
507
-
508
-			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
509
-			if(is_array($result)) {
510
-				$this->connection->writeToCache($cacheKey, true);
511
-				$validGroupDNs[] = $dn;
512
-			} else {
513
-				$this->connection->writeToCache($cacheKey, false);
514
-			}
515
-
516
-		}
517
-		return $validGroupDNs;
518
-	}
519
-
520
-	/**
521
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
522
-	 *
523
-	 * @param string $dn the dn of the user object
524
-	 * @param string $ldapName optional, the display name of the object
525
-	 * @return string|false with with the name to use in Nextcloud
526
-	 * @throws \Exception
527
-	 */
528
-	public function dn2username($fdn, $ldapName = null) {
529
-		//To avoid bypassing the base DN settings under certain circumstances
530
-		//with the group support, check whether the provided DN matches one of
531
-		//the given Bases
532
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
533
-			return false;
534
-		}
535
-
536
-		return $this->dn2ocname($fdn, $ldapName, true);
537
-	}
538
-
539
-	/**
540
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
541
-	 *
542
-	 * @param string $fdn the dn of the user object
543
-	 * @param string|null $ldapName optional, the display name of the object
544
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
545
-	 * @param bool|null $newlyMapped
546
-	 * @param array|null $record
547
-	 * @return false|string with with the name to use in Nextcloud
548
-	 * @throws \Exception
549
-	 */
550
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
551
-		$newlyMapped = false;
552
-		if($isUser) {
553
-			$mapper = $this->getUserMapper();
554
-			$nameAttribute = $this->connection->ldapUserDisplayName;
555
-			$filter = $this->connection->ldapUserFilter;
556
-		} else {
557
-			$mapper = $this->getGroupMapper();
558
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
559
-			$filter = $this->connection->ldapGroupFilter;
560
-		}
561
-
562
-		//let's try to retrieve the Nextcloud name from the mappings table
563
-		$ncName = $mapper->getNameByDN($fdn);
564
-		if(is_string($ncName)) {
565
-			return $ncName;
566
-		}
567
-
568
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
569
-		$uuid = $this->getUUID($fdn, $isUser, $record);
570
-		if(is_string($uuid)) {
571
-			$ncName = $mapper->getNameByUUID($uuid);
572
-			if(is_string($ncName)) {
573
-				$mapper->setDNbyUUID($fdn, $uuid);
574
-				return $ncName;
575
-			}
576
-		} else {
577
-			//If the UUID can't be detected something is foul.
578
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
579
-			return false;
580
-		}
581
-
582
-		if(is_null($ldapName)) {
583
-			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
584
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
585
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
586
-				return false;
587
-			}
588
-			$ldapName = $ldapName[0];
589
-		}
590
-
591
-		if($isUser) {
592
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
593
-			if ($usernameAttribute !== '') {
594
-				$username = $this->readAttribute($fdn, $usernameAttribute);
595
-				$username = $username[0];
596
-			} else {
597
-				$username = $uuid;
598
-			}
599
-			try {
600
-				$intName = $this->sanitizeUsername($username);
601
-			} catch (\InvalidArgumentException $e) {
602
-				\OC::$server->getLogger()->logException($e, [
603
-					'app' => 'user_ldap',
604
-					'level' => ILogger::WARN,
605
-				]);
606
-				// we don't attempt to set a username here. We can go for
607
-				// for an alternative 4 digit random number as we would append
608
-				// otherwise, however it's likely not enough space in bigger
609
-				// setups, and most importantly: this is not intended.
610
-				return false;
611
-			}
612
-		} else {
613
-			$intName = $ldapName;
614
-		}
615
-
616
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
617
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
618
-		//NOTE: mind, disabling cache affects only this instance! Using it
619
-		// outside of core user management will still cache the user as non-existing.
620
-		$originalTTL = $this->connection->ldapCacheTTL;
621
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
622
-		if( $intName !== ''
623
-			&& (($isUser && !$this->ncUserManager->userExists($intName))
624
-				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
625
-			)
626
-		) {
627
-			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
628
-			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
629
-			if($newlyMapped) {
630
-				return $intName;
631
-			}
632
-		}
633
-
634
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
635
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
636
-		if (is_string($altName)) {
637
-			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
638
-				$newlyMapped = true;
639
-				return $altName;
640
-			}
641
-		}
642
-
643
-		//if everything else did not help..
644
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
645
-		return false;
646
-	}
647
-
648
-	public function mapAndAnnounceIfApplicable(
649
-		AbstractMapping $mapper,
650
-		string $fdn,
651
-		string $name,
652
-		string $uuid,
653
-		bool $isUser
654
-	) :bool {
655
-		if($mapper->map($fdn, $name, $uuid)) {
656
-			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
657
-				$this->cacheUserExists($name);
658
-				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
659
-			} elseif (!$isUser) {
660
-				$this->cacheGroupExists($name);
661
-			}
662
-			return true;
663
-		}
664
-		return false;
665
-	}
666
-
667
-	/**
668
-	 * gives back the user names as they are used ownClod internally
669
-	 *
670
-	 * @param array $ldapUsers as returned by fetchList()
671
-	 * @return array an array with the user names to use in Nextcloud
672
-	 *
673
-	 * gives back the user names as they are used ownClod internally
674
-	 * @throws \Exception
675
-	 */
676
-	public function nextcloudUserNames($ldapUsers) {
677
-		return $this->ldap2NextcloudNames($ldapUsers, true);
678
-	}
679
-
680
-	/**
681
-	 * gives back the group names as they are used ownClod internally
682
-	 *
683
-	 * @param array $ldapGroups as returned by fetchList()
684
-	 * @return array an array with the group names to use in Nextcloud
685
-	 *
686
-	 * gives back the group names as they are used ownClod internally
687
-	 * @throws \Exception
688
-	 */
689
-	public function nextcloudGroupNames($ldapGroups) {
690
-		return $this->ldap2NextcloudNames($ldapGroups, false);
691
-	}
692
-
693
-	/**
694
-	 * @param array $ldapObjects as returned by fetchList()
695
-	 * @param bool $isUsers
696
-	 * @return array
697
-	 * @throws \Exception
698
-	 */
699
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
700
-		if($isUsers) {
701
-			$nameAttribute = $this->connection->ldapUserDisplayName;
702
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
703
-		} else {
704
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
705
-		}
706
-		$nextcloudNames = [];
707
-
708
-		foreach($ldapObjects as $ldapObject) {
709
-			$nameByLDAP = null;
710
-			if(    isset($ldapObject[$nameAttribute])
711
-				&& is_array($ldapObject[$nameAttribute])
712
-				&& isset($ldapObject[$nameAttribute][0])
713
-			) {
714
-				// might be set, but not necessarily. if so, we use it.
715
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
716
-			}
717
-
718
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
719
-			if($ncName) {
720
-				$nextcloudNames[] = $ncName;
721
-				if($isUsers) {
722
-					$this->updateUserState($ncName);
723
-					//cache the user names so it does not need to be retrieved
724
-					//again later (e.g. sharing dialogue).
725
-					if(is_null($nameByLDAP)) {
726
-						continue;
727
-					}
728
-					$sndName = isset($ldapObject[$sndAttribute][0])
729
-						? $ldapObject[$sndAttribute][0] : '';
730
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
731
-				} else if($nameByLDAP !== null) {
732
-					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
733
-				}
734
-			}
735
-		}
736
-		return $nextcloudNames;
737
-	}
738
-
739
-	/**
740
-	 * removes the deleted-flag of a user if it was set
741
-	 *
742
-	 * @param string $ncname
743
-	 * @throws \Exception
744
-	 */
745
-	public function updateUserState($ncname) {
746
-		$user = $this->userManager->get($ncname);
747
-		if($user instanceof OfflineUser) {
748
-			$user->unmark();
749
-		}
750
-	}
751
-
752
-	/**
753
-	 * caches the user display name
754
-	 * @param string $ocName the internal Nextcloud username
755
-	 * @param string|false $home the home directory path
756
-	 */
757
-	public function cacheUserHome($ocName, $home) {
758
-		$cacheKey = 'getHome'.$ocName;
759
-		$this->connection->writeToCache($cacheKey, $home);
760
-	}
761
-
762
-	/**
763
-	 * caches a user as existing
764
-	 * @param string $ocName the internal Nextcloud username
765
-	 */
766
-	public function cacheUserExists($ocName) {
767
-		$this->connection->writeToCache('userExists'.$ocName, true);
768
-	}
769
-
770
-	/**
771
-	 * caches a group as existing
772
-	 */
773
-	public function cacheGroupExists(string $gid): void {
774
-		$this->connection->writeToCache('groupExists'.$gid, true);
775
-	}
776
-
777
-	/**
778
-	 * caches the user display name
779
-	 *
780
-	 * @param string $ocName the internal Nextcloud username
781
-	 * @param string $displayName the display name
782
-	 * @param string $displayName2 the second display name
783
-	 * @throws \Exception
784
-	 */
785
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
786
-		$user = $this->userManager->get($ocName);
787
-		if($user === null) {
788
-			return;
789
-		}
790
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
791
-		$cacheKeyTrunk = 'getDisplayName';
792
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
793
-	}
794
-
795
-	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
796
-		$cacheKey = 'group_getDisplayName' . $ncName;
797
-		$this->connection->writeToCache($cacheKey, $displayName);
798
-	}
799
-
800
-	/**
801
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
802
-	 * @param string $name the display name of the object
803
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
804
-	 *
805
-	 * Instead of using this method directly, call
806
-	 * createAltInternalOwnCloudName($name, true)
807
-	 */
808
-	private function _createAltInternalOwnCloudNameForUsers($name) {
809
-		$attempts = 0;
810
-		//while loop is just a precaution. If a name is not generated within
811
-		//20 attempts, something else is very wrong. Avoids infinite loop.
812
-		while($attempts < 20){
813
-			$altName = $name . '_' . rand(1000,9999);
814
-			if(!$this->ncUserManager->userExists($altName)) {
815
-				return $altName;
816
-			}
817
-			$attempts++;
818
-		}
819
-		return false;
820
-	}
821
-
822
-	/**
823
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
824
-	 * @param string $name the display name of the object
825
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
826
-	 *
827
-	 * Instead of using this method directly, call
828
-	 * createAltInternalOwnCloudName($name, false)
829
-	 *
830
-	 * Group names are also used as display names, so we do a sequential
831
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
832
-	 * "Developers"
833
-	 */
834
-	private function _createAltInternalOwnCloudNameForGroups($name) {
835
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
836
-		if(!$usedNames || count($usedNames) === 0) {
837
-			$lastNo = 1; //will become name_2
838
-		} else {
839
-			natsort($usedNames);
840
-			$lastName = array_pop($usedNames);
841
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
842
-		}
843
-		$altName = $name.'_'. (string)($lastNo+1);
844
-		unset($usedNames);
845
-
846
-		$attempts = 1;
847
-		while($attempts < 21){
848
-			// Check to be really sure it is unique
849
-			// while loop is just a precaution. If a name is not generated within
850
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
851
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
852
-				return $altName;
853
-			}
854
-			$altName = $name . '_' . ($lastNo + $attempts);
855
-			$attempts++;
856
-		}
857
-		return false;
858
-	}
859
-
860
-	/**
861
-	 * creates a unique name for internal Nextcloud use.
862
-	 * @param string $name the display name of the object
863
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
864
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
865
-	 */
866
-	private function createAltInternalOwnCloudName($name, $isUser) {
867
-		$originalTTL = $this->connection->ldapCacheTTL;
868
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
869
-		if($isUser) {
870
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
871
-		} else {
872
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
873
-		}
874
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
875
-
876
-		return $altName;
877
-	}
878
-
879
-	/**
880
-	 * fetches a list of users according to a provided loginName and utilizing
881
-	 * the login filter.
882
-	 *
883
-	 * @param string $loginName
884
-	 * @param array $attributes optional, list of attributes to read
885
-	 * @return array
886
-	 */
887
-	public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
888
-		$loginName = $this->escapeFilterPart($loginName);
889
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
890
-		return $this->fetchListOfUsers($filter, $attributes);
891
-	}
892
-
893
-	/**
894
-	 * counts the number of users according to a provided loginName and
895
-	 * utilizing the login filter.
896
-	 *
897
-	 * @param string $loginName
898
-	 * @return int
899
-	 */
900
-	public function countUsersByLoginName($loginName) {
901
-		$loginName = $this->escapeFilterPart($loginName);
902
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
903
-		return $this->countUsers($filter);
904
-	}
905
-
906
-	/**
907
-	 * @param string $filter
908
-	 * @param string|string[] $attr
909
-	 * @param int $limit
910
-	 * @param int $offset
911
-	 * @param bool $forceApplyAttributes
912
-	 * @return array
913
-	 * @throws \Exception
914
-	 */
915
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
916
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
917
-		$recordsToUpdate = $ldapRecords;
918
-		if(!$forceApplyAttributes) {
919
-			$isBackgroundJobModeAjax = $this->config
920
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
921
-			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
922
-				$newlyMapped = false;
923
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
924
-				if(is_string($uid)) {
925
-					$this->cacheUserExists($uid);
926
-				}
927
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
928
-			});
929
-		}
930
-		$this->batchApplyUserAttributes($recordsToUpdate);
931
-		return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
932
-	}
933
-
934
-	/**
935
-	 * provided with an array of LDAP user records the method will fetch the
936
-	 * user object and requests it to process the freshly fetched attributes and
937
-	 * and their values
938
-	 *
939
-	 * @param array $ldapRecords
940
-	 * @throws \Exception
941
-	 */
942
-	public function batchApplyUserAttributes(array $ldapRecords){
943
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
944
-		foreach($ldapRecords as $userRecord) {
945
-			if(!isset($userRecord[$displayNameAttribute])) {
946
-				// displayName is obligatory
947
-				continue;
948
-			}
949
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
950
-			if($ocName === false) {
951
-				continue;
952
-			}
953
-			$this->updateUserState($ocName);
954
-			$user = $this->userManager->get($ocName);
955
-			if ($user !== null) {
956
-				$user->processAttributes($userRecord);
957
-			} else {
958
-				\OC::$server->getLogger()->debug(
959
-					"The ldap user manager returned null for $ocName",
960
-					['app'=>'user_ldap']
961
-				);
962
-			}
963
-		}
964
-	}
965
-
966
-	/**
967
-	 * @param string $filter
968
-	 * @param string|string[] $attr
969
-	 * @param int $limit
970
-	 * @param int $offset
971
-	 * @return array
972
-	 */
973
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
974
-		$groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
975
-		array_walk($groupRecords, function($record) {
976
-			$newlyMapped = false;
977
-			$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
978
-			if(!$newlyMapped && is_string($gid)) {
979
-				$this->cacheGroupExists($gid);
980
-			}
981
-		});
982
-		return $this->fetchList($groupRecords, $this->manyAttributes($attr));
983
-	}
984
-
985
-	/**
986
-	 * @param array $list
987
-	 * @param bool $manyAttributes
988
-	 * @return array
989
-	 */
990
-	private function fetchList($list, $manyAttributes) {
991
-		if(is_array($list)) {
992
-			if($manyAttributes) {
993
-				return $list;
994
-			} else {
995
-				$list = array_reduce($list, function($carry, $item) {
996
-					$attribute = array_keys($item)[0];
997
-					$carry[] = $item[$attribute][0];
998
-					return $carry;
999
-				}, []);
1000
-				return array_unique($list, SORT_LOCALE_STRING);
1001
-			}
1002
-		}
1003
-
1004
-		//error cause actually, maybe throw an exception in future.
1005
-		return [];
1006
-	}
1007
-
1008
-	/**
1009
-	 * executes an LDAP search, optimized for Users
1010
-	 *
1011
-	 * @param string $filter the LDAP filter for the search
1012
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1013
-	 * @param integer $limit
1014
-	 * @param integer $offset
1015
-	 * @return array with the search result
1016
-	 *
1017
-	 * Executes an LDAP search
1018
-	 * @throws ServerNotAvailableException
1019
-	 */
1020
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1021
-		$result = [];
1022
-		foreach($this->connection->ldapBaseUsers as $base) {
1023
-			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1024
-		}
1025
-		return $result;
1026
-	}
1027
-
1028
-	/**
1029
-	 * @param string $filter
1030
-	 * @param string|string[] $attr
1031
-	 * @param int $limit
1032
-	 * @param int $offset
1033
-	 * @return false|int
1034
-	 * @throws ServerNotAvailableException
1035
-	 */
1036
-	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1037
-		$result = false;
1038
-		foreach($this->connection->ldapBaseUsers as $base) {
1039
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1040
-			$result = is_int($count) ? (int)$result + $count : $result;
1041
-		}
1042
-		return $result;
1043
-	}
1044
-
1045
-	/**
1046
-	 * executes an LDAP search, optimized for Groups
1047
-	 *
1048
-	 * @param string $filter the LDAP filter for the search
1049
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1050
-	 * @param integer $limit
1051
-	 * @param integer $offset
1052
-	 * @return array with the search result
1053
-	 *
1054
-	 * Executes an LDAP search
1055
-	 * @throws ServerNotAvailableException
1056
-	 */
1057
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1058
-		$result = [];
1059
-		foreach($this->connection->ldapBaseGroups as $base) {
1060
-			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1061
-		}
1062
-		return $result;
1063
-	}
1064
-
1065
-	/**
1066
-	 * returns the number of available groups
1067
-	 *
1068
-	 * @param string $filter the LDAP search filter
1069
-	 * @param string[] $attr optional
1070
-	 * @param int|null $limit
1071
-	 * @param int|null $offset
1072
-	 * @return int|bool
1073
-	 * @throws ServerNotAvailableException
1074
-	 */
1075
-	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1076
-		$result = false;
1077
-		foreach($this->connection->ldapBaseGroups as $base) {
1078
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1079
-			$result = is_int($count) ? (int)$result + $count : $result;
1080
-		}
1081
-		return $result;
1082
-	}
1083
-
1084
-	/**
1085
-	 * returns the number of available objects on the base DN
1086
-	 *
1087
-	 * @param int|null $limit
1088
-	 * @param int|null $offset
1089
-	 * @return int|bool
1090
-	 * @throws ServerNotAvailableException
1091
-	 */
1092
-	public function countObjects($limit = null, $offset = null) {
1093
-		$result = false;
1094
-		foreach($this->connection->ldapBase as $base) {
1095
-			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1096
-			$result = is_int($count) ? (int)$result + $count : $result;
1097
-		}
1098
-		return $result;
1099
-	}
1100
-
1101
-	/**
1102
-	 * Returns the LDAP handler
1103
-	 * @throws \OC\ServerNotAvailableException
1104
-	 */
1105
-
1106
-	/**
1107
-	 * @return mixed
1108
-	 * @throws \OC\ServerNotAvailableException
1109
-	 */
1110
-	private function invokeLDAPMethod() {
1111
-		$arguments = func_get_args();
1112
-		$command = array_shift($arguments);
1113
-		$cr = array_shift($arguments);
1114
-		if (!method_exists($this->ldap, $command)) {
1115
-			return null;
1116
-		}
1117
-		array_unshift($arguments, $cr);
1118
-		// php no longer supports call-time pass-by-reference
1119
-		// thus cannot support controlPagedResultResponse as the third argument
1120
-		// is a reference
1121
-		$doMethod = function () use ($command, &$arguments) {
1122
-			if ($command == 'controlPagedResultResponse') {
1123
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1124
-			} else {
1125
-				return call_user_func_array([$this->ldap, $command], $arguments);
1126
-			}
1127
-		};
1128
-		try {
1129
-			$ret = $doMethod();
1130
-		} catch (ServerNotAvailableException $e) {
1131
-			/* Server connection lost, attempt to reestablish it
66
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
67
+
68
+    /** @var \OCA\User_LDAP\Connection */
69
+    public $connection;
70
+    /** @var Manager */
71
+    public $userManager;
72
+    //never ever check this var directly, always use getPagedSearchResultState
73
+    protected $pagedSearchedSuccessful;
74
+
75
+    /**
76
+     * @var string[] $cookies an array of returned Paged Result cookies
77
+     */
78
+    protected $cookies = [];
79
+
80
+    /**
81
+     * @var string $lastCookie the last cookie returned from a Paged Results
82
+     * operation, defaults to an empty string
83
+     */
84
+    protected $lastCookie = '';
85
+
86
+    /**
87
+     * @var AbstractMapping $userMapper
88
+     */
89
+    protected $userMapper;
90
+
91
+    /**
92
+     * @var AbstractMapping $userMapper
93
+     */
94
+    protected $groupMapper;
95
+
96
+    /**
97
+     * @var \OCA\User_LDAP\Helper
98
+     */
99
+    private $helper;
100
+    /** @var IConfig */
101
+    private $config;
102
+    /** @var IUserManager */
103
+    private $ncUserManager;
104
+
105
+    public function __construct(
106
+        Connection $connection,
107
+        ILDAPWrapper $ldap,
108
+        Manager $userManager,
109
+        Helper $helper,
110
+        IConfig $config,
111
+        IUserManager $ncUserManager
112
+    ) {
113
+        parent::__construct($ldap);
114
+        $this->connection = $connection;
115
+        $this->userManager = $userManager;
116
+        $this->userManager->setLdapAccess($this);
117
+        $this->helper = $helper;
118
+        $this->config = $config;
119
+        $this->ncUserManager = $ncUserManager;
120
+    }
121
+
122
+    /**
123
+     * sets the User Mapper
124
+     * @param AbstractMapping $mapper
125
+     */
126
+    public function setUserMapper(AbstractMapping $mapper) {
127
+        $this->userMapper = $mapper;
128
+    }
129
+
130
+    /**
131
+     * returns the User Mapper
132
+     * @throws \Exception
133
+     * @return AbstractMapping
134
+     */
135
+    public function getUserMapper() {
136
+        if(is_null($this->userMapper)) {
137
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
138
+        }
139
+        return $this->userMapper;
140
+    }
141
+
142
+    /**
143
+     * sets the Group Mapper
144
+     * @param AbstractMapping $mapper
145
+     */
146
+    public function setGroupMapper(AbstractMapping $mapper) {
147
+        $this->groupMapper = $mapper;
148
+    }
149
+
150
+    /**
151
+     * returns the Group Mapper
152
+     * @throws \Exception
153
+     * @return AbstractMapping
154
+     */
155
+    public function getGroupMapper() {
156
+        if(is_null($this->groupMapper)) {
157
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
158
+        }
159
+        return $this->groupMapper;
160
+    }
161
+
162
+    /**
163
+     * @return bool
164
+     */
165
+    private function checkConnection() {
166
+        return ($this->connection instanceof Connection);
167
+    }
168
+
169
+    /**
170
+     * returns the Connection instance
171
+     * @return \OCA\User_LDAP\Connection
172
+     */
173
+    public function getConnection() {
174
+        return $this->connection;
175
+    }
176
+
177
+    /**
178
+     * reads a given attribute for an LDAP record identified by a DN
179
+     *
180
+     * @param string $dn the record in question
181
+     * @param string $attr the attribute that shall be retrieved
182
+     *        if empty, just check the record's existence
183
+     * @param string $filter
184
+     * @return array|false an array of values on success or an empty
185
+     *          array if $attr is empty, false otherwise
186
+     * @throws ServerNotAvailableException
187
+     */
188
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
189
+        if(!$this->checkConnection()) {
190
+            \OCP\Util::writeLog('user_ldap',
191
+                'No LDAP Connector assigned, access impossible for readAttribute.',
192
+                ILogger::WARN);
193
+            return false;
194
+        }
195
+        $cr = $this->connection->getConnectionResource();
196
+        if(!$this->ldap->isResource($cr)) {
197
+            //LDAP not available
198
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
199
+            return false;
200
+        }
201
+        //Cancel possibly running Paged Results operation, otherwise we run in
202
+        //LDAP protocol errors
203
+        $this->abandonPagedSearch();
204
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
205
+        // but does not hurt either.
206
+        $pagingSize = (int)$this->connection->ldapPagingSize;
207
+        // 0 won't result in replies, small numbers may leave out groups
208
+        // (cf. #12306), 500 is default for paging and should work everywhere.
209
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
210
+        $attr = mb_strtolower($attr, 'UTF-8');
211
+        // the actual read attribute later may contain parameters on a ranged
212
+        // request, e.g. member;range=99-199. Depends on server reply.
213
+        $attrToRead = $attr;
214
+
215
+        $values = [];
216
+        $isRangeRequest = false;
217
+        do {
218
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
219
+            if(is_bool($result)) {
220
+                // when an exists request was run and it was successful, an empty
221
+                // array must be returned
222
+                return $result ? [] : false;
223
+            }
224
+
225
+            if (!$isRangeRequest) {
226
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
227
+                if (!empty($values)) {
228
+                    return $values;
229
+                }
230
+            }
231
+
232
+            $isRangeRequest = false;
233
+            $result = $this->extractRangeData($result, $attr);
234
+            if (!empty($result)) {
235
+                $normalizedResult = $this->extractAttributeValuesFromResult(
236
+                    [ $attr => $result['values'] ],
237
+                    $attr
238
+                );
239
+                $values = array_merge($values, $normalizedResult);
240
+
241
+                if($result['rangeHigh'] === '*') {
242
+                    // when server replies with * as high range value, there are
243
+                    // no more results left
244
+                    return $values;
245
+                } else {
246
+                    $low  = $result['rangeHigh'] + 1;
247
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
248
+                    $isRangeRequest = true;
249
+                }
250
+            }
251
+        } while($isRangeRequest);
252
+
253
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
254
+        return false;
255
+    }
256
+
257
+    /**
258
+     * Runs an read operation against LDAP
259
+     *
260
+     * @param resource $cr the LDAP connection
261
+     * @param string $dn
262
+     * @param string $attribute
263
+     * @param string $filter
264
+     * @param int $maxResults
265
+     * @return array|bool false if there was any error, true if an exists check
266
+     *                    was performed and the requested DN found, array with the
267
+     *                    returned data on a successful usual operation
268
+     * @throws ServerNotAvailableException
269
+     */
270
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
271
+        $this->initPagedSearch($filter, [$dn], [$attribute], $maxResults, 0);
272
+        $dn = $this->helper->DNasBaseParameter($dn);
273
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
274
+        if (!$this->ldap->isResource($rr)) {
275
+            if ($attribute !== '') {
276
+                //do not throw this message on userExists check, irritates
277
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
278
+            }
279
+            //in case an error occurs , e.g. object does not exist
280
+            return false;
281
+        }
282
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
283
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
284
+            return true;
285
+        }
286
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
287
+        if (!$this->ldap->isResource($er)) {
288
+            //did not match the filter, return false
289
+            return false;
290
+        }
291
+        //LDAP attributes are not case sensitive
292
+        $result = \OCP\Util::mb_array_change_key_case(
293
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
294
+
295
+        return $result;
296
+    }
297
+
298
+    /**
299
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
300
+     * data if present.
301
+     *
302
+     * @param array $result from ILDAPWrapper::getAttributes()
303
+     * @param string $attribute the attribute name that was read
304
+     * @return string[]
305
+     */
306
+    public function extractAttributeValuesFromResult($result, $attribute) {
307
+        $values = [];
308
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
309
+            $lowercaseAttribute = strtolower($attribute);
310
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
311
+                if($this->resemblesDN($attribute)) {
312
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
313
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
314
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
315
+                } else {
316
+                    $values[] = $result[$attribute][$i];
317
+                }
318
+            }
319
+        }
320
+        return $values;
321
+    }
322
+
323
+    /**
324
+     * Attempts to find ranged data in a getAttribute results and extracts the
325
+     * returned values as well as information on the range and full attribute
326
+     * name for further processing.
327
+     *
328
+     * @param array $result from ILDAPWrapper::getAttributes()
329
+     * @param string $attribute the attribute name that was read. Without ";range=…"
330
+     * @return array If a range was detected with keys 'values', 'attributeName',
331
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
332
+     */
333
+    public function extractRangeData($result, $attribute) {
334
+        $keys = array_keys($result);
335
+        foreach($keys as $key) {
336
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
337
+                $queryData = explode(';', $key);
338
+                if(strpos($queryData[1], 'range=') === 0) {
339
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
340
+                    $data = [
341
+                        'values' => $result[$key],
342
+                        'attributeName' => $queryData[0],
343
+                        'attributeFull' => $key,
344
+                        'rangeHigh' => $high,
345
+                    ];
346
+                    return $data;
347
+                }
348
+            }
349
+        }
350
+        return [];
351
+    }
352
+
353
+    /**
354
+     * Set password for an LDAP user identified by a DN
355
+     *
356
+     * @param string $userDN the user in question
357
+     * @param string $password the new password
358
+     * @return bool
359
+     * @throws HintException
360
+     * @throws \Exception
361
+     */
362
+    public function setPassword($userDN, $password) {
363
+        if((int)$this->connection->turnOnPasswordChange !== 1) {
364
+            throw new \Exception('LDAP password changes are disabled.');
365
+        }
366
+        $cr = $this->connection->getConnectionResource();
367
+        if(!$this->ldap->isResource($cr)) {
368
+            //LDAP not available
369
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
370
+            return false;
371
+        }
372
+        try {
373
+            // try PASSWD extended operation first
374
+            return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
375
+                        @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
376
+        } catch(ConstraintViolationException $e) {
377
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
378
+        }
379
+    }
380
+
381
+    /**
382
+     * checks whether the given attributes value is probably a DN
383
+     * @param string $attr the attribute in question
384
+     * @return boolean if so true, otherwise false
385
+     */
386
+    private function resemblesDN($attr) {
387
+        $resemblingAttributes = [
388
+            'dn',
389
+            'uniquemember',
390
+            'member',
391
+            // memberOf is an "operational" attribute, without a definition in any RFC
392
+            'memberof'
393
+        ];
394
+        return in_array($attr, $resemblingAttributes);
395
+    }
396
+
397
+    /**
398
+     * checks whether the given string is probably a DN
399
+     * @param string $string
400
+     * @return boolean
401
+     */
402
+    public function stringResemblesDN($string) {
403
+        $r = $this->ldap->explodeDN($string, 0);
404
+        // if exploding a DN succeeds and does not end up in
405
+        // an empty array except for $r[count] being 0.
406
+        return (is_array($r) && count($r) > 1);
407
+    }
408
+
409
+    /**
410
+     * returns a DN-string that is cleaned from not domain parts, e.g.
411
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
412
+     * becomes dc=foobar,dc=server,dc=org
413
+     * @param string $dn
414
+     * @return string
415
+     */
416
+    public function getDomainDNFromDN($dn) {
417
+        $allParts = $this->ldap->explodeDN($dn, 0);
418
+        if($allParts === false) {
419
+            //not a valid DN
420
+            return '';
421
+        }
422
+        $domainParts = [];
423
+        $dcFound = false;
424
+        foreach($allParts as $part) {
425
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
426
+                $dcFound = true;
427
+            }
428
+            if($dcFound) {
429
+                $domainParts[] = $part;
430
+            }
431
+        }
432
+        return implode(',', $domainParts);
433
+    }
434
+
435
+    /**
436
+     * returns the LDAP DN for the given internal Nextcloud name of the group
437
+     * @param string $name the Nextcloud name in question
438
+     * @return string|false LDAP DN on success, otherwise false
439
+     */
440
+    public function groupname2dn($name) {
441
+        return $this->groupMapper->getDNByName($name);
442
+    }
443
+
444
+    /**
445
+     * returns the LDAP DN for the given internal Nextcloud name of the user
446
+     * @param string $name the Nextcloud name in question
447
+     * @return string|false with the LDAP DN on success, otherwise false
448
+     */
449
+    public function username2dn($name) {
450
+        $fdn = $this->userMapper->getDNByName($name);
451
+
452
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
453
+        //server setups
454
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
455
+            return $fdn;
456
+        }
457
+
458
+        return false;
459
+    }
460
+
461
+    /**
462
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
463
+     *
464
+     * @param string $fdn the dn of the group object
465
+     * @param string $ldapName optional, the display name of the object
466
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
467
+     * @throws \Exception
468
+     */
469
+    public function dn2groupname($fdn, $ldapName = null) {
470
+        //To avoid bypassing the base DN settings under certain circumstances
471
+        //with the group support, check whether the provided DN matches one of
472
+        //the given Bases
473
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
474
+            return false;
475
+        }
476
+
477
+        return $this->dn2ocname($fdn, $ldapName, false);
478
+    }
479
+
480
+    /**
481
+     * accepts an array of group DNs and tests whether they match the user
482
+     * filter by doing read operations against the group entries. Returns an
483
+     * array of DNs that match the filter.
484
+     *
485
+     * @param string[] $groupDNs
486
+     * @return string[]
487
+     * @throws ServerNotAvailableException
488
+     */
489
+    public function groupsMatchFilter($groupDNs) {
490
+        $validGroupDNs = [];
491
+        foreach($groupDNs as $dn) {
492
+            $cacheKey = 'groupsMatchFilter-'.$dn;
493
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
494
+            if(!is_null($groupMatchFilter)) {
495
+                if($groupMatchFilter) {
496
+                    $validGroupDNs[] = $dn;
497
+                }
498
+                continue;
499
+            }
500
+
501
+            // Check the base DN first. If this is not met already, we don't
502
+            // need to ask the server at all.
503
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
504
+                $this->connection->writeToCache($cacheKey, false);
505
+                continue;
506
+            }
507
+
508
+            $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
509
+            if(is_array($result)) {
510
+                $this->connection->writeToCache($cacheKey, true);
511
+                $validGroupDNs[] = $dn;
512
+            } else {
513
+                $this->connection->writeToCache($cacheKey, false);
514
+            }
515
+
516
+        }
517
+        return $validGroupDNs;
518
+    }
519
+
520
+    /**
521
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
522
+     *
523
+     * @param string $dn the dn of the user object
524
+     * @param string $ldapName optional, the display name of the object
525
+     * @return string|false with with the name to use in Nextcloud
526
+     * @throws \Exception
527
+     */
528
+    public function dn2username($fdn, $ldapName = null) {
529
+        //To avoid bypassing the base DN settings under certain circumstances
530
+        //with the group support, check whether the provided DN matches one of
531
+        //the given Bases
532
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
533
+            return false;
534
+        }
535
+
536
+        return $this->dn2ocname($fdn, $ldapName, true);
537
+    }
538
+
539
+    /**
540
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
541
+     *
542
+     * @param string $fdn the dn of the user object
543
+     * @param string|null $ldapName optional, the display name of the object
544
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
545
+     * @param bool|null $newlyMapped
546
+     * @param array|null $record
547
+     * @return false|string with with the name to use in Nextcloud
548
+     * @throws \Exception
549
+     */
550
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
551
+        $newlyMapped = false;
552
+        if($isUser) {
553
+            $mapper = $this->getUserMapper();
554
+            $nameAttribute = $this->connection->ldapUserDisplayName;
555
+            $filter = $this->connection->ldapUserFilter;
556
+        } else {
557
+            $mapper = $this->getGroupMapper();
558
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
559
+            $filter = $this->connection->ldapGroupFilter;
560
+        }
561
+
562
+        //let's try to retrieve the Nextcloud name from the mappings table
563
+        $ncName = $mapper->getNameByDN($fdn);
564
+        if(is_string($ncName)) {
565
+            return $ncName;
566
+        }
567
+
568
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
569
+        $uuid = $this->getUUID($fdn, $isUser, $record);
570
+        if(is_string($uuid)) {
571
+            $ncName = $mapper->getNameByUUID($uuid);
572
+            if(is_string($ncName)) {
573
+                $mapper->setDNbyUUID($fdn, $uuid);
574
+                return $ncName;
575
+            }
576
+        } else {
577
+            //If the UUID can't be detected something is foul.
578
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
579
+            return false;
580
+        }
581
+
582
+        if(is_null($ldapName)) {
583
+            $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
584
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
585
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
586
+                return false;
587
+            }
588
+            $ldapName = $ldapName[0];
589
+        }
590
+
591
+        if($isUser) {
592
+            $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
593
+            if ($usernameAttribute !== '') {
594
+                $username = $this->readAttribute($fdn, $usernameAttribute);
595
+                $username = $username[0];
596
+            } else {
597
+                $username = $uuid;
598
+            }
599
+            try {
600
+                $intName = $this->sanitizeUsername($username);
601
+            } catch (\InvalidArgumentException $e) {
602
+                \OC::$server->getLogger()->logException($e, [
603
+                    'app' => 'user_ldap',
604
+                    'level' => ILogger::WARN,
605
+                ]);
606
+                // we don't attempt to set a username here. We can go for
607
+                // for an alternative 4 digit random number as we would append
608
+                // otherwise, however it's likely not enough space in bigger
609
+                // setups, and most importantly: this is not intended.
610
+                return false;
611
+            }
612
+        } else {
613
+            $intName = $ldapName;
614
+        }
615
+
616
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
617
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
618
+        //NOTE: mind, disabling cache affects only this instance! Using it
619
+        // outside of core user management will still cache the user as non-existing.
620
+        $originalTTL = $this->connection->ldapCacheTTL;
621
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
622
+        if( $intName !== ''
623
+            && (($isUser && !$this->ncUserManager->userExists($intName))
624
+                || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
625
+            )
626
+        ) {
627
+            $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
628
+            $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
629
+            if($newlyMapped) {
630
+                return $intName;
631
+            }
632
+        }
633
+
634
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
635
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
636
+        if (is_string($altName)) {
637
+            if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
638
+                $newlyMapped = true;
639
+                return $altName;
640
+            }
641
+        }
642
+
643
+        //if everything else did not help..
644
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
645
+        return false;
646
+    }
647
+
648
+    public function mapAndAnnounceIfApplicable(
649
+        AbstractMapping $mapper,
650
+        string $fdn,
651
+        string $name,
652
+        string $uuid,
653
+        bool $isUser
654
+    ) :bool {
655
+        if($mapper->map($fdn, $name, $uuid)) {
656
+            if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
657
+                $this->cacheUserExists($name);
658
+                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
659
+            } elseif (!$isUser) {
660
+                $this->cacheGroupExists($name);
661
+            }
662
+            return true;
663
+        }
664
+        return false;
665
+    }
666
+
667
+    /**
668
+     * gives back the user names as they are used ownClod internally
669
+     *
670
+     * @param array $ldapUsers as returned by fetchList()
671
+     * @return array an array with the user names to use in Nextcloud
672
+     *
673
+     * gives back the user names as they are used ownClod internally
674
+     * @throws \Exception
675
+     */
676
+    public function nextcloudUserNames($ldapUsers) {
677
+        return $this->ldap2NextcloudNames($ldapUsers, true);
678
+    }
679
+
680
+    /**
681
+     * gives back the group names as they are used ownClod internally
682
+     *
683
+     * @param array $ldapGroups as returned by fetchList()
684
+     * @return array an array with the group names to use in Nextcloud
685
+     *
686
+     * gives back the group names as they are used ownClod internally
687
+     * @throws \Exception
688
+     */
689
+    public function nextcloudGroupNames($ldapGroups) {
690
+        return $this->ldap2NextcloudNames($ldapGroups, false);
691
+    }
692
+
693
+    /**
694
+     * @param array $ldapObjects as returned by fetchList()
695
+     * @param bool $isUsers
696
+     * @return array
697
+     * @throws \Exception
698
+     */
699
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
700
+        if($isUsers) {
701
+            $nameAttribute = $this->connection->ldapUserDisplayName;
702
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
703
+        } else {
704
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
705
+        }
706
+        $nextcloudNames = [];
707
+
708
+        foreach($ldapObjects as $ldapObject) {
709
+            $nameByLDAP = null;
710
+            if(    isset($ldapObject[$nameAttribute])
711
+                && is_array($ldapObject[$nameAttribute])
712
+                && isset($ldapObject[$nameAttribute][0])
713
+            ) {
714
+                // might be set, but not necessarily. if so, we use it.
715
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
716
+            }
717
+
718
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
719
+            if($ncName) {
720
+                $nextcloudNames[] = $ncName;
721
+                if($isUsers) {
722
+                    $this->updateUserState($ncName);
723
+                    //cache the user names so it does not need to be retrieved
724
+                    //again later (e.g. sharing dialogue).
725
+                    if(is_null($nameByLDAP)) {
726
+                        continue;
727
+                    }
728
+                    $sndName = isset($ldapObject[$sndAttribute][0])
729
+                        ? $ldapObject[$sndAttribute][0] : '';
730
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
731
+                } else if($nameByLDAP !== null) {
732
+                    $this->cacheGroupDisplayName($ncName, $nameByLDAP);
733
+                }
734
+            }
735
+        }
736
+        return $nextcloudNames;
737
+    }
738
+
739
+    /**
740
+     * removes the deleted-flag of a user if it was set
741
+     *
742
+     * @param string $ncname
743
+     * @throws \Exception
744
+     */
745
+    public function updateUserState($ncname) {
746
+        $user = $this->userManager->get($ncname);
747
+        if($user instanceof OfflineUser) {
748
+            $user->unmark();
749
+        }
750
+    }
751
+
752
+    /**
753
+     * caches the user display name
754
+     * @param string $ocName the internal Nextcloud username
755
+     * @param string|false $home the home directory path
756
+     */
757
+    public function cacheUserHome($ocName, $home) {
758
+        $cacheKey = 'getHome'.$ocName;
759
+        $this->connection->writeToCache($cacheKey, $home);
760
+    }
761
+
762
+    /**
763
+     * caches a user as existing
764
+     * @param string $ocName the internal Nextcloud username
765
+     */
766
+    public function cacheUserExists($ocName) {
767
+        $this->connection->writeToCache('userExists'.$ocName, true);
768
+    }
769
+
770
+    /**
771
+     * caches a group as existing
772
+     */
773
+    public function cacheGroupExists(string $gid): void {
774
+        $this->connection->writeToCache('groupExists'.$gid, true);
775
+    }
776
+
777
+    /**
778
+     * caches the user display name
779
+     *
780
+     * @param string $ocName the internal Nextcloud username
781
+     * @param string $displayName the display name
782
+     * @param string $displayName2 the second display name
783
+     * @throws \Exception
784
+     */
785
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
786
+        $user = $this->userManager->get($ocName);
787
+        if($user === null) {
788
+            return;
789
+        }
790
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
791
+        $cacheKeyTrunk = 'getDisplayName';
792
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
793
+    }
794
+
795
+    public function cacheGroupDisplayName(string $ncName, string $displayName): void {
796
+        $cacheKey = 'group_getDisplayName' . $ncName;
797
+        $this->connection->writeToCache($cacheKey, $displayName);
798
+    }
799
+
800
+    /**
801
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
802
+     * @param string $name the display name of the object
803
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
804
+     *
805
+     * Instead of using this method directly, call
806
+     * createAltInternalOwnCloudName($name, true)
807
+     */
808
+    private function _createAltInternalOwnCloudNameForUsers($name) {
809
+        $attempts = 0;
810
+        //while loop is just a precaution. If a name is not generated within
811
+        //20 attempts, something else is very wrong. Avoids infinite loop.
812
+        while($attempts < 20){
813
+            $altName = $name . '_' . rand(1000,9999);
814
+            if(!$this->ncUserManager->userExists($altName)) {
815
+                return $altName;
816
+            }
817
+            $attempts++;
818
+        }
819
+        return false;
820
+    }
821
+
822
+    /**
823
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
824
+     * @param string $name the display name of the object
825
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
826
+     *
827
+     * Instead of using this method directly, call
828
+     * createAltInternalOwnCloudName($name, false)
829
+     *
830
+     * Group names are also used as display names, so we do a sequential
831
+     * numbering, e.g. Developers_42 when there are 41 other groups called
832
+     * "Developers"
833
+     */
834
+    private function _createAltInternalOwnCloudNameForGroups($name) {
835
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
836
+        if(!$usedNames || count($usedNames) === 0) {
837
+            $lastNo = 1; //will become name_2
838
+        } else {
839
+            natsort($usedNames);
840
+            $lastName = array_pop($usedNames);
841
+            $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
842
+        }
843
+        $altName = $name.'_'. (string)($lastNo+1);
844
+        unset($usedNames);
845
+
846
+        $attempts = 1;
847
+        while($attempts < 21){
848
+            // Check to be really sure it is unique
849
+            // while loop is just a precaution. If a name is not generated within
850
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
851
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
852
+                return $altName;
853
+            }
854
+            $altName = $name . '_' . ($lastNo + $attempts);
855
+            $attempts++;
856
+        }
857
+        return false;
858
+    }
859
+
860
+    /**
861
+     * creates a unique name for internal Nextcloud use.
862
+     * @param string $name the display name of the object
863
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
864
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
865
+     */
866
+    private function createAltInternalOwnCloudName($name, $isUser) {
867
+        $originalTTL = $this->connection->ldapCacheTTL;
868
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
869
+        if($isUser) {
870
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
871
+        } else {
872
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
873
+        }
874
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
875
+
876
+        return $altName;
877
+    }
878
+
879
+    /**
880
+     * fetches a list of users according to a provided loginName and utilizing
881
+     * the login filter.
882
+     *
883
+     * @param string $loginName
884
+     * @param array $attributes optional, list of attributes to read
885
+     * @return array
886
+     */
887
+    public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
888
+        $loginName = $this->escapeFilterPart($loginName);
889
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
890
+        return $this->fetchListOfUsers($filter, $attributes);
891
+    }
892
+
893
+    /**
894
+     * counts the number of users according to a provided loginName and
895
+     * utilizing the login filter.
896
+     *
897
+     * @param string $loginName
898
+     * @return int
899
+     */
900
+    public function countUsersByLoginName($loginName) {
901
+        $loginName = $this->escapeFilterPart($loginName);
902
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
903
+        return $this->countUsers($filter);
904
+    }
905
+
906
+    /**
907
+     * @param string $filter
908
+     * @param string|string[] $attr
909
+     * @param int $limit
910
+     * @param int $offset
911
+     * @param bool $forceApplyAttributes
912
+     * @return array
913
+     * @throws \Exception
914
+     */
915
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
916
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
917
+        $recordsToUpdate = $ldapRecords;
918
+        if(!$forceApplyAttributes) {
919
+            $isBackgroundJobModeAjax = $this->config
920
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
921
+            $recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
922
+                $newlyMapped = false;
923
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
924
+                if(is_string($uid)) {
925
+                    $this->cacheUserExists($uid);
926
+                }
927
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
928
+            });
929
+        }
930
+        $this->batchApplyUserAttributes($recordsToUpdate);
931
+        return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
932
+    }
933
+
934
+    /**
935
+     * provided with an array of LDAP user records the method will fetch the
936
+     * user object and requests it to process the freshly fetched attributes and
937
+     * and their values
938
+     *
939
+     * @param array $ldapRecords
940
+     * @throws \Exception
941
+     */
942
+    public function batchApplyUserAttributes(array $ldapRecords){
943
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
944
+        foreach($ldapRecords as $userRecord) {
945
+            if(!isset($userRecord[$displayNameAttribute])) {
946
+                // displayName is obligatory
947
+                continue;
948
+            }
949
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
950
+            if($ocName === false) {
951
+                continue;
952
+            }
953
+            $this->updateUserState($ocName);
954
+            $user = $this->userManager->get($ocName);
955
+            if ($user !== null) {
956
+                $user->processAttributes($userRecord);
957
+            } else {
958
+                \OC::$server->getLogger()->debug(
959
+                    "The ldap user manager returned null for $ocName",
960
+                    ['app'=>'user_ldap']
961
+                );
962
+            }
963
+        }
964
+    }
965
+
966
+    /**
967
+     * @param string $filter
968
+     * @param string|string[] $attr
969
+     * @param int $limit
970
+     * @param int $offset
971
+     * @return array
972
+     */
973
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
974
+        $groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
975
+        array_walk($groupRecords, function($record) {
976
+            $newlyMapped = false;
977
+            $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
978
+            if(!$newlyMapped && is_string($gid)) {
979
+                $this->cacheGroupExists($gid);
980
+            }
981
+        });
982
+        return $this->fetchList($groupRecords, $this->manyAttributes($attr));
983
+    }
984
+
985
+    /**
986
+     * @param array $list
987
+     * @param bool $manyAttributes
988
+     * @return array
989
+     */
990
+    private function fetchList($list, $manyAttributes) {
991
+        if(is_array($list)) {
992
+            if($manyAttributes) {
993
+                return $list;
994
+            } else {
995
+                $list = array_reduce($list, function($carry, $item) {
996
+                    $attribute = array_keys($item)[0];
997
+                    $carry[] = $item[$attribute][0];
998
+                    return $carry;
999
+                }, []);
1000
+                return array_unique($list, SORT_LOCALE_STRING);
1001
+            }
1002
+        }
1003
+
1004
+        //error cause actually, maybe throw an exception in future.
1005
+        return [];
1006
+    }
1007
+
1008
+    /**
1009
+     * executes an LDAP search, optimized for Users
1010
+     *
1011
+     * @param string $filter the LDAP filter for the search
1012
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1013
+     * @param integer $limit
1014
+     * @param integer $offset
1015
+     * @return array with the search result
1016
+     *
1017
+     * Executes an LDAP search
1018
+     * @throws ServerNotAvailableException
1019
+     */
1020
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1021
+        $result = [];
1022
+        foreach($this->connection->ldapBaseUsers as $base) {
1023
+            $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1024
+        }
1025
+        return $result;
1026
+    }
1027
+
1028
+    /**
1029
+     * @param string $filter
1030
+     * @param string|string[] $attr
1031
+     * @param int $limit
1032
+     * @param int $offset
1033
+     * @return false|int
1034
+     * @throws ServerNotAvailableException
1035
+     */
1036
+    public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1037
+        $result = false;
1038
+        foreach($this->connection->ldapBaseUsers as $base) {
1039
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1040
+            $result = is_int($count) ? (int)$result + $count : $result;
1041
+        }
1042
+        return $result;
1043
+    }
1044
+
1045
+    /**
1046
+     * executes an LDAP search, optimized for Groups
1047
+     *
1048
+     * @param string $filter the LDAP filter for the search
1049
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1050
+     * @param integer $limit
1051
+     * @param integer $offset
1052
+     * @return array with the search result
1053
+     *
1054
+     * Executes an LDAP search
1055
+     * @throws ServerNotAvailableException
1056
+     */
1057
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1058
+        $result = [];
1059
+        foreach($this->connection->ldapBaseGroups as $base) {
1060
+            $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1061
+        }
1062
+        return $result;
1063
+    }
1064
+
1065
+    /**
1066
+     * returns the number of available groups
1067
+     *
1068
+     * @param string $filter the LDAP search filter
1069
+     * @param string[] $attr optional
1070
+     * @param int|null $limit
1071
+     * @param int|null $offset
1072
+     * @return int|bool
1073
+     * @throws ServerNotAvailableException
1074
+     */
1075
+    public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1076
+        $result = false;
1077
+        foreach($this->connection->ldapBaseGroups as $base) {
1078
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1079
+            $result = is_int($count) ? (int)$result + $count : $result;
1080
+        }
1081
+        return $result;
1082
+    }
1083
+
1084
+    /**
1085
+     * returns the number of available objects on the base DN
1086
+     *
1087
+     * @param int|null $limit
1088
+     * @param int|null $offset
1089
+     * @return int|bool
1090
+     * @throws ServerNotAvailableException
1091
+     */
1092
+    public function countObjects($limit = null, $offset = null) {
1093
+        $result = false;
1094
+        foreach($this->connection->ldapBase as $base) {
1095
+            $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1096
+            $result = is_int($count) ? (int)$result + $count : $result;
1097
+        }
1098
+        return $result;
1099
+    }
1100
+
1101
+    /**
1102
+     * Returns the LDAP handler
1103
+     * @throws \OC\ServerNotAvailableException
1104
+     */
1105
+
1106
+    /**
1107
+     * @return mixed
1108
+     * @throws \OC\ServerNotAvailableException
1109
+     */
1110
+    private function invokeLDAPMethod() {
1111
+        $arguments = func_get_args();
1112
+        $command = array_shift($arguments);
1113
+        $cr = array_shift($arguments);
1114
+        if (!method_exists($this->ldap, $command)) {
1115
+            return null;
1116
+        }
1117
+        array_unshift($arguments, $cr);
1118
+        // php no longer supports call-time pass-by-reference
1119
+        // thus cannot support controlPagedResultResponse as the third argument
1120
+        // is a reference
1121
+        $doMethod = function () use ($command, &$arguments) {
1122
+            if ($command == 'controlPagedResultResponse') {
1123
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1124
+            } else {
1125
+                return call_user_func_array([$this->ldap, $command], $arguments);
1126
+            }
1127
+        };
1128
+        try {
1129
+            $ret = $doMethod();
1130
+        } catch (ServerNotAvailableException $e) {
1131
+            /* Server connection lost, attempt to reestablish it
1132 1132
 			 * Maybe implement exponential backoff?
1133 1133
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1134 1134
 			 */
1135
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1136
-			$this->connection->resetConnectionResource();
1137
-			$cr = $this->connection->getConnectionResource();
1138
-
1139
-			if(!$this->ldap->isResource($cr)) {
1140
-				// Seems like we didn't find any resource.
1141
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1142
-				throw $e;
1143
-			}
1144
-
1145
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1146
-			$ret = $doMethod();
1147
-		}
1148
-		return $ret;
1149
-	}
1150
-
1151
-	/**
1152
-	 * retrieved. Results will according to the order in the array.
1153
-	 *
1154
-	 * @param $filter
1155
-	 * @param $base
1156
-	 * @param string[]|string|null $attr
1157
-	 * @param int $limit optional, maximum results to be counted
1158
-	 * @param int $offset optional, a starting point
1159
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1160
-	 * second | false if not successful
1161
-	 * @throws ServerNotAvailableException
1162
-	 */
1163
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1164
-		if(!is_null($attr) && !is_array($attr)) {
1165
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1166
-		}
1167
-
1168
-		// See if we have a resource, in case not cancel with message
1169
-		$cr = $this->connection->getConnectionResource();
1170
-		if(!$this->ldap->isResource($cr)) {
1171
-			// Seems like we didn't find any resource.
1172
-			// Return an empty array just like before.
1173
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1174
-			return false;
1175
-		}
1176
-
1177
-		//check whether paged search should be attempted
1178
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1179
-
1180
-		$linkResources = array_pad([], count($base), $cr);
1181
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1182
-		// cannot use $cr anymore, might have changed in the previous call!
1183
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1184
-		if(!is_array($sr) || $error !== 0) {
1185
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1186
-			return false;
1187
-		}
1188
-
1189
-		return [$sr, $pagedSearchOK];
1190
-	}
1191
-
1192
-	/**
1193
-	 * processes an LDAP paged search operation
1194
-	 *
1195
-	 * @param array $sr the array containing the LDAP search resources
1196
-	 * @param string $filter the LDAP filter for the search
1197
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1198
-	 * @param int $iFoundItems number of results in the single search operation
1199
-	 * @param int $limit maximum results to be counted
1200
-	 * @param int $offset a starting point
1201
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1202
-	 * @param bool $skipHandling required for paged search when cookies to
1203
-	 * prior results need to be gained
1204
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1205
-	 * @throws ServerNotAvailableException
1206
-	 */
1207
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1208
-		$cookie = null;
1209
-		if($pagedSearchOK) {
1210
-			$cr = $this->connection->getConnectionResource();
1211
-			foreach($sr as $key => $res) {
1212
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1213
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1214
-				}
1215
-			}
1216
-
1217
-			//browsing through prior pages to get the cookie for the new one
1218
-			if($skipHandling) {
1219
-				return false;
1220
-			}
1221
-			// if count is bigger, then the server does not support
1222
-			// paged search. Instead, he did a normal search. We set a
1223
-			// flag here, so the callee knows how to deal with it.
1224
-			if($iFoundItems <= $limit) {
1225
-				$this->pagedSearchedSuccessful = true;
1226
-			}
1227
-		} else {
1228
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1229
-				\OC::$server->getLogger()->debug(
1230
-					'Paged search was not available',
1231
-					[ 'app' => 'user_ldap' ]
1232
-				);
1233
-			}
1234
-		}
1235
-		/* ++ Fixing RHDS searches with pages with zero results ++
1135
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1136
+            $this->connection->resetConnectionResource();
1137
+            $cr = $this->connection->getConnectionResource();
1138
+
1139
+            if(!$this->ldap->isResource($cr)) {
1140
+                // Seems like we didn't find any resource.
1141
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1142
+                throw $e;
1143
+            }
1144
+
1145
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1146
+            $ret = $doMethod();
1147
+        }
1148
+        return $ret;
1149
+    }
1150
+
1151
+    /**
1152
+     * retrieved. Results will according to the order in the array.
1153
+     *
1154
+     * @param $filter
1155
+     * @param $base
1156
+     * @param string[]|string|null $attr
1157
+     * @param int $limit optional, maximum results to be counted
1158
+     * @param int $offset optional, a starting point
1159
+     * @return array|false array with the search result as first value and pagedSearchOK as
1160
+     * second | false if not successful
1161
+     * @throws ServerNotAvailableException
1162
+     */
1163
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1164
+        if(!is_null($attr) && !is_array($attr)) {
1165
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1166
+        }
1167
+
1168
+        // See if we have a resource, in case not cancel with message
1169
+        $cr = $this->connection->getConnectionResource();
1170
+        if(!$this->ldap->isResource($cr)) {
1171
+            // Seems like we didn't find any resource.
1172
+            // Return an empty array just like before.
1173
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1174
+            return false;
1175
+        }
1176
+
1177
+        //check whether paged search should be attempted
1178
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1179
+
1180
+        $linkResources = array_pad([], count($base), $cr);
1181
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1182
+        // cannot use $cr anymore, might have changed in the previous call!
1183
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1184
+        if(!is_array($sr) || $error !== 0) {
1185
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1186
+            return false;
1187
+        }
1188
+
1189
+        return [$sr, $pagedSearchOK];
1190
+    }
1191
+
1192
+    /**
1193
+     * processes an LDAP paged search operation
1194
+     *
1195
+     * @param array $sr the array containing the LDAP search resources
1196
+     * @param string $filter the LDAP filter for the search
1197
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1198
+     * @param int $iFoundItems number of results in the single search operation
1199
+     * @param int $limit maximum results to be counted
1200
+     * @param int $offset a starting point
1201
+     * @param bool $pagedSearchOK whether a paged search has been executed
1202
+     * @param bool $skipHandling required for paged search when cookies to
1203
+     * prior results need to be gained
1204
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1205
+     * @throws ServerNotAvailableException
1206
+     */
1207
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1208
+        $cookie = null;
1209
+        if($pagedSearchOK) {
1210
+            $cr = $this->connection->getConnectionResource();
1211
+            foreach($sr as $key => $res) {
1212
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1213
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1214
+                }
1215
+            }
1216
+
1217
+            //browsing through prior pages to get the cookie for the new one
1218
+            if($skipHandling) {
1219
+                return false;
1220
+            }
1221
+            // if count is bigger, then the server does not support
1222
+            // paged search. Instead, he did a normal search. We set a
1223
+            // flag here, so the callee knows how to deal with it.
1224
+            if($iFoundItems <= $limit) {
1225
+                $this->pagedSearchedSuccessful = true;
1226
+            }
1227
+        } else {
1228
+            if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1229
+                \OC::$server->getLogger()->debug(
1230
+                    'Paged search was not available',
1231
+                    [ 'app' => 'user_ldap' ]
1232
+                );
1233
+            }
1234
+        }
1235
+        /* ++ Fixing RHDS searches with pages with zero results ++
1236 1236
 		 * Return cookie status. If we don't have more pages, with RHDS
1237 1237
 		 * cookie is null, with openldap cookie is an empty string and
1238 1238
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1239 1239
 		 */
1240
-		return !empty($cookie) || $cookie === '0';
1241
-	}
1242
-
1243
-	/**
1244
-	 * executes an LDAP search, but counts the results only
1245
-	 *
1246
-	 * @param string $filter the LDAP filter for the search
1247
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1248
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1249
-	 * retrieved. Results will according to the order in the array.
1250
-	 * @param int $limit optional, maximum results to be counted
1251
-	 * @param int $offset optional, a starting point
1252
-	 * @param bool $skipHandling indicates whether the pages search operation is
1253
-	 * completed
1254
-	 * @return int|false Integer or false if the search could not be initialized
1255
-	 * @throws ServerNotAvailableException
1256
-	 */
1257
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1258
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1259
-
1260
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1261
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1262
-			$limitPerPage = $limit;
1263
-		}
1264
-
1265
-		$counter = 0;
1266
-		$count = null;
1267
-		$this->connection->getConnectionResource();
1268
-
1269
-		do {
1270
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1271
-			if($search === false) {
1272
-				return $counter > 0 ? $counter : false;
1273
-			}
1274
-			list($sr, $pagedSearchOK) = $search;
1275
-
1276
-			/* ++ Fixing RHDS searches with pages with zero results ++
1240
+        return !empty($cookie) || $cookie === '0';
1241
+    }
1242
+
1243
+    /**
1244
+     * executes an LDAP search, but counts the results only
1245
+     *
1246
+     * @param string $filter the LDAP filter for the search
1247
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1248
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1249
+     * retrieved. Results will according to the order in the array.
1250
+     * @param int $limit optional, maximum results to be counted
1251
+     * @param int $offset optional, a starting point
1252
+     * @param bool $skipHandling indicates whether the pages search operation is
1253
+     * completed
1254
+     * @return int|false Integer or false if the search could not be initialized
1255
+     * @throws ServerNotAvailableException
1256
+     */
1257
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1258
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1259
+
1260
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1261
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1262
+            $limitPerPage = $limit;
1263
+        }
1264
+
1265
+        $counter = 0;
1266
+        $count = null;
1267
+        $this->connection->getConnectionResource();
1268
+
1269
+        do {
1270
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1271
+            if($search === false) {
1272
+                return $counter > 0 ? $counter : false;
1273
+            }
1274
+            list($sr, $pagedSearchOK) = $search;
1275
+
1276
+            /* ++ Fixing RHDS searches with pages with zero results ++
1277 1277
 			 * countEntriesInSearchResults() method signature changed
1278 1278
 			 * by removing $limit and &$hasHitLimit parameters
1279 1279
 			 */
1280
-			$count = $this->countEntriesInSearchResults($sr);
1281
-			$counter += $count;
1280
+            $count = $this->countEntriesInSearchResults($sr);
1281
+            $counter += $count;
1282 1282
 
1283
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1284
-										$offset, $pagedSearchOK, $skipHandling);
1285
-			$offset += $limitPerPage;
1286
-			/* ++ Fixing RHDS searches with pages with zero results ++
1283
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1284
+                                        $offset, $pagedSearchOK, $skipHandling);
1285
+            $offset += $limitPerPage;
1286
+            /* ++ Fixing RHDS searches with pages with zero results ++
1287 1287
 			 * Continue now depends on $hasMorePages value
1288 1288
 			 */
1289
-			$continue = $pagedSearchOK && $hasMorePages;
1290
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1291
-
1292
-		return $counter;
1293
-	}
1294
-
1295
-	/**
1296
-	 * @param array $searchResults
1297
-	 * @return int
1298
-	 * @throws ServerNotAvailableException
1299
-	 */
1300
-	private function countEntriesInSearchResults($searchResults) {
1301
-		$counter = 0;
1302
-
1303
-		foreach($searchResults as $res) {
1304
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1305
-			$counter += $count;
1306
-		}
1307
-
1308
-		return $counter;
1309
-	}
1310
-
1311
-	/**
1312
-	 * Executes an LDAP search
1313
-	 *
1314
-	 * @param string $filter the LDAP filter for the search
1315
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1316
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1317
-	 * @param int $limit
1318
-	 * @param int $offset
1319
-	 * @param bool $skipHandling
1320
-	 * @return array with the search result
1321
-	 * @throws ServerNotAvailableException
1322
-	 */
1323
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1324
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1325
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1326
-			$limitPerPage = $limit;
1327
-		}
1328
-
1329
-		/* ++ Fixing RHDS searches with pages with zero results ++
1289
+            $continue = $pagedSearchOK && $hasMorePages;
1290
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1291
+
1292
+        return $counter;
1293
+    }
1294
+
1295
+    /**
1296
+     * @param array $searchResults
1297
+     * @return int
1298
+     * @throws ServerNotAvailableException
1299
+     */
1300
+    private function countEntriesInSearchResults($searchResults) {
1301
+        $counter = 0;
1302
+
1303
+        foreach($searchResults as $res) {
1304
+            $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1305
+            $counter += $count;
1306
+        }
1307
+
1308
+        return $counter;
1309
+    }
1310
+
1311
+    /**
1312
+     * Executes an LDAP search
1313
+     *
1314
+     * @param string $filter the LDAP filter for the search
1315
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1316
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1317
+     * @param int $limit
1318
+     * @param int $offset
1319
+     * @param bool $skipHandling
1320
+     * @return array with the search result
1321
+     * @throws ServerNotAvailableException
1322
+     */
1323
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1324
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1325
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1326
+            $limitPerPage = $limit;
1327
+        }
1328
+
1329
+        /* ++ Fixing RHDS searches with pages with zero results ++
1330 1330
 		 * As we can have pages with zero results and/or pages with less
1331 1331
 		 * than $limit results but with a still valid server 'cookie',
1332 1332
 		 * loops through until we get $continue equals true and
1333 1333
 		 * $findings['count'] < $limit
1334 1334
 		 */
1335
-		$findings = [];
1336
-		$savedoffset = $offset;
1337
-		do {
1338
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1339
-			if($search === false) {
1340
-				return [];
1341
-			}
1342
-			list($sr, $pagedSearchOK) = $search;
1343
-			$cr = $this->connection->getConnectionResource();
1344
-
1345
-			if($skipHandling) {
1346
-				//i.e. result do not need to be fetched, we just need the cookie
1347
-				//thus pass 1 or any other value as $iFoundItems because it is not
1348
-				//used
1349
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1350
-								$offset, $pagedSearchOK,
1351
-								$skipHandling);
1352
-				return [];
1353
-			}
1354
-
1355
-			$iFoundItems = 0;
1356
-			foreach($sr as $res) {
1357
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1358
-				$iFoundItems = max($iFoundItems, $findings['count']);
1359
-				unset($findings['count']);
1360
-			}
1361
-
1362
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1363
-				$limitPerPage, $offset, $pagedSearchOK,
1364
-										$skipHandling);
1365
-			$offset += $limitPerPage;
1366
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1367
-		// reseting offset
1368
-		$offset = $savedoffset;
1369
-
1370
-		// if we're here, probably no connection resource is returned.
1371
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1372
-		if(is_null($findings)) {
1373
-			return [];
1374
-		}
1375
-
1376
-		if(!is_null($attr)) {
1377
-			$selection = [];
1378
-			$i = 0;
1379
-			foreach($findings as $item) {
1380
-				if(!is_array($item)) {
1381
-					continue;
1382
-				}
1383
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1384
-				foreach($attr as $key) {
1385
-					if(isset($item[$key])) {
1386
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1387
-							unset($item[$key]['count']);
1388
-						}
1389
-						if($key !== 'dn') {
1390
-							if($this->resemblesDN($key)) {
1391
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1392
-							} else if($key === 'objectguid' || $key === 'guid') {
1393
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1394
-							} else {
1395
-								$selection[$i][$key] = $item[$key];
1396
-							}
1397
-						} else {
1398
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1399
-						}
1400
-					}
1401
-
1402
-				}
1403
-				$i++;
1404
-			}
1405
-			$findings = $selection;
1406
-		}
1407
-		//we slice the findings, when
1408
-		//a) paged search unsuccessful, though attempted
1409
-		//b) no paged search, but limit set
1410
-		if((!$this->getPagedSearchResultState()
1411
-			&& $pagedSearchOK)
1412
-			|| (
1413
-				!$pagedSearchOK
1414
-				&& !is_null($limit)
1415
-			)
1416
-		) {
1417
-			$findings = array_slice($findings, (int)$offset, $limit);
1418
-		}
1419
-		return $findings;
1420
-	}
1421
-
1422
-	/**
1423
-	 * @param string $name
1424
-	 * @return string
1425
-	 * @throws \InvalidArgumentException
1426
-	 */
1427
-	public function sanitizeUsername($name) {
1428
-		$name = trim($name);
1429
-
1430
-		if($this->connection->ldapIgnoreNamingRules) {
1431
-			return $name;
1432
-		}
1433
-
1434
-		// Transliteration to ASCII
1435
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1436
-		if($transliterated !== false) {
1437
-			// depending on system config iconv can work or not
1438
-			$name = $transliterated;
1439
-		}
1440
-
1441
-		// Replacements
1442
-		$name = str_replace(' ', '_', $name);
1443
-
1444
-		// Every remaining disallowed characters will be removed
1445
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1446
-
1447
-		if($name === '') {
1448
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1449
-		}
1450
-
1451
-		return $name;
1452
-	}
1453
-
1454
-	/**
1455
-	* escapes (user provided) parts for LDAP filter
1456
-	* @param string $input, the provided value
1457
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1458
-	* @return string the escaped string
1459
-	*/
1460
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1461
-		$asterisk = '';
1462
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1463
-			$asterisk = '*';
1464
-			$input = mb_substr($input, 1, null, 'UTF-8');
1465
-		}
1466
-		$search  = ['*', '\\', '(', ')'];
1467
-		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1468
-		return $asterisk . str_replace($search, $replace, $input);
1469
-	}
1470
-
1471
-	/**
1472
-	 * combines the input filters with AND
1473
-	 * @param string[] $filters the filters to connect
1474
-	 * @return string the combined filter
1475
-	 */
1476
-	public function combineFilterWithAnd($filters) {
1477
-		return $this->combineFilter($filters, '&');
1478
-	}
1479
-
1480
-	/**
1481
-	 * combines the input filters with OR
1482
-	 * @param string[] $filters the filters to connect
1483
-	 * @return string the combined filter
1484
-	 * Combines Filter arguments with OR
1485
-	 */
1486
-	public function combineFilterWithOr($filters) {
1487
-		return $this->combineFilter($filters, '|');
1488
-	}
1489
-
1490
-	/**
1491
-	 * combines the input filters with given operator
1492
-	 * @param string[] $filters the filters to connect
1493
-	 * @param string $operator either & or |
1494
-	 * @return string the combined filter
1495
-	 */
1496
-	private function combineFilter($filters, $operator) {
1497
-		$combinedFilter = '('.$operator;
1498
-		foreach($filters as $filter) {
1499
-			if ($filter !== '' && $filter[0] !== '(') {
1500
-				$filter = '('.$filter.')';
1501
-			}
1502
-			$combinedFilter.=$filter;
1503
-		}
1504
-		$combinedFilter.=')';
1505
-		return $combinedFilter;
1506
-	}
1507
-
1508
-	/**
1509
-	 * creates a filter part for to perform search for users
1510
-	 * @param string $search the search term
1511
-	 * @return string the final filter part to use in LDAP searches
1512
-	 */
1513
-	public function getFilterPartForUserSearch($search) {
1514
-		return $this->getFilterPartForSearch($search,
1515
-			$this->connection->ldapAttributesForUserSearch,
1516
-			$this->connection->ldapUserDisplayName);
1517
-	}
1518
-
1519
-	/**
1520
-	 * creates a filter part for to perform search for groups
1521
-	 * @param string $search the search term
1522
-	 * @return string the final filter part to use in LDAP searches
1523
-	 */
1524
-	public function getFilterPartForGroupSearch($search) {
1525
-		return $this->getFilterPartForSearch($search,
1526
-			$this->connection->ldapAttributesForGroupSearch,
1527
-			$this->connection->ldapGroupDisplayName);
1528
-	}
1529
-
1530
-	/**
1531
-	 * creates a filter part for searches by splitting up the given search
1532
-	 * string into single words
1533
-	 * @param string $search the search term
1534
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1535
-	 * otherwise it does not make sense :)
1536
-	 * @return string the final filter part to use in LDAP searches
1537
-	 * @throws \Exception
1538
-	 */
1539
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1540
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1541
-			throw new \Exception('searchAttributes must be an array with at least two string');
1542
-		}
1543
-		$searchWords = explode(' ', trim($search));
1544
-		$wordFilters = [];
1545
-		foreach($searchWords as $word) {
1546
-			$word = $this->prepareSearchTerm($word);
1547
-			//every word needs to appear at least once
1548
-			$wordMatchOneAttrFilters = [];
1549
-			foreach($searchAttributes as $attr) {
1550
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1551
-			}
1552
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1553
-		}
1554
-		return $this->combineFilterWithAnd($wordFilters);
1555
-	}
1556
-
1557
-	/**
1558
-	 * creates a filter part for searches
1559
-	 * @param string $search the search term
1560
-	 * @param string[]|null $searchAttributes
1561
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1562
-	 * did not define search attributes. Typically the display name attribute.
1563
-	 * @return string the final filter part to use in LDAP searches
1564
-	 */
1565
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1566
-		$filter = [];
1567
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1568
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1569
-			try {
1570
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1571
-			} catch(\Exception $e) {
1572
-				\OCP\Util::writeLog(
1573
-					'user_ldap',
1574
-					'Creating advanced filter for search failed, falling back to simple method.',
1575
-					ILogger::INFO
1576
-				);
1577
-			}
1578
-		}
1579
-
1580
-		$search = $this->prepareSearchTerm($search);
1581
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1582
-			if ($fallbackAttribute === '') {
1583
-				return '';
1584
-			}
1585
-			$filter[] = $fallbackAttribute . '=' . $search;
1586
-		} else {
1587
-			foreach($searchAttributes as $attribute) {
1588
-				$filter[] = $attribute . '=' . $search;
1589
-			}
1590
-		}
1591
-		if(count($filter) === 1) {
1592
-			return '('.$filter[0].')';
1593
-		}
1594
-		return $this->combineFilterWithOr($filter);
1595
-	}
1596
-
1597
-	/**
1598
-	 * returns the search term depending on whether we are allowed
1599
-	 * list users found by ldap with the current input appended by
1600
-	 * a *
1601
-	 * @return string
1602
-	 */
1603
-	private function prepareSearchTerm($term) {
1604
-		$config = \OC::$server->getConfig();
1605
-
1606
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1607
-
1608
-		$result = $term;
1609
-		if ($term === '') {
1610
-			$result = '*';
1611
-		} else if ($allowEnum !== 'no') {
1612
-			$result = $term . '*';
1613
-		}
1614
-		return $result;
1615
-	}
1616
-
1617
-	/**
1618
-	 * returns the filter used for counting users
1619
-	 * @return string
1620
-	 */
1621
-	public function getFilterForUserCount() {
1622
-		$filter = $this->combineFilterWithAnd([
1623
-			$this->connection->ldapUserFilter,
1624
-			$this->connection->ldapUserDisplayName . '=*'
1625
-		]);
1626
-
1627
-		return $filter;
1628
-	}
1629
-
1630
-	/**
1631
-	 * @param string $name
1632
-	 * @param string $password
1633
-	 * @return bool
1634
-	 */
1635
-	public function areCredentialsValid($name, $password) {
1636
-		$name = $this->helper->DNasBaseParameter($name);
1637
-		$testConnection = clone $this->connection;
1638
-		$credentials = [
1639
-			'ldapAgentName' => $name,
1640
-			'ldapAgentPassword' => $password
1641
-		];
1642
-		if(!$testConnection->setConfiguration($credentials)) {
1643
-			return false;
1644
-		}
1645
-		return $testConnection->bind();
1646
-	}
1647
-
1648
-	/**
1649
-	 * reverse lookup of a DN given a known UUID
1650
-	 *
1651
-	 * @param string $uuid
1652
-	 * @return string
1653
-	 * @throws \Exception
1654
-	 */
1655
-	public function getUserDnByUuid($uuid) {
1656
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1657
-		$filter       = $this->connection->ldapUserFilter;
1658
-		$base         = $this->connection->ldapBaseUsers;
1659
-
1660
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1661
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1662
-			// existing DN to be able to reliably detect it.
1663
-			$result = $this->search($filter, $base, ['dn'], 1);
1664
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1665
-				throw new \Exception('Cannot determine UUID attribute');
1666
-			}
1667
-			$dn = $result[0]['dn'][0];
1668
-			if(!$this->detectUuidAttribute($dn, true)) {
1669
-				throw new \Exception('Cannot determine UUID attribute');
1670
-			}
1671
-		} else {
1672
-			// The UUID attribute is either known or an override is given.
1673
-			// By calling this method we ensure that $this->connection->$uuidAttr
1674
-			// is definitely set
1675
-			if(!$this->detectUuidAttribute('', true)) {
1676
-				throw new \Exception('Cannot determine UUID attribute');
1677
-			}
1678
-		}
1679
-
1680
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1681
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1682
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1683
-		}
1684
-
1685
-		$filter = $uuidAttr . '=' . $uuid;
1686
-		$result = $this->searchUsers($filter, ['dn'], 2);
1687
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1688
-			// we put the count into account to make sure that this is
1689
-			// really unique
1690
-			return $result[0]['dn'][0];
1691
-		}
1692
-
1693
-		throw new \Exception('Cannot determine UUID attribute');
1694
-	}
1695
-
1696
-	/**
1697
-	 * auto-detects the directory's UUID attribute
1698
-	 *
1699
-	 * @param string $dn a known DN used to check against
1700
-	 * @param bool $isUser
1701
-	 * @param bool $force the detection should be run, even if it is not set to auto
1702
-	 * @param array|null $ldapRecord
1703
-	 * @return bool true on success, false otherwise
1704
-	 * @throws ServerNotAvailableException
1705
-	 */
1706
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1707
-		if($isUser) {
1708
-			$uuidAttr     = 'ldapUuidUserAttribute';
1709
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1710
-		} else {
1711
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1712
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1713
-		}
1714
-
1715
-		if(!$force) {
1716
-			if($this->connection->$uuidAttr !== 'auto') {
1717
-				return true;
1718
-			} else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1719
-				$this->connection->$uuidAttr = $uuidOverride;
1720
-				return true;
1721
-			}
1722
-
1723
-			$attribute = $this->connection->getFromCache($uuidAttr);
1724
-			if(!$attribute === null) {
1725
-				$this->connection->$uuidAttr = $attribute;
1726
-				return true;
1727
-			}
1728
-		}
1729
-
1730
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1731
-			if($ldapRecord !== null) {
1732
-				// we have the info from LDAP already, we don't need to talk to the server again
1733
-				if(isset($ldapRecord[$attribute])) {
1734
-					$this->connection->$uuidAttr = $attribute;
1735
-					return true;
1736
-				}
1737
-			}
1738
-
1739
-			$value = $this->readAttribute($dn, $attribute);
1740
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1741
-				\OC::$server->getLogger()->debug(
1742
-					'Setting {attribute} as {subject}',
1743
-					[
1744
-						'app' => 'user_ldap',
1745
-						'attribute' => $attribute,
1746
-						'subject' => $uuidAttr
1747
-					]
1748
-				);
1749
-				$this->connection->$uuidAttr = $attribute;
1750
-				$this->connection->writeToCache($uuidAttr, $attribute);
1751
-				return true;
1752
-			}
1753
-		}
1754
-		\OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1755
-
1756
-		return false;
1757
-	}
1758
-
1759
-	/**
1760
-	 * @param string $dn
1761
-	 * @param bool $isUser
1762
-	 * @param null $ldapRecord
1763
-	 * @return bool|string
1764
-	 * @throws ServerNotAvailableException
1765
-	 */
1766
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1767
-		if($isUser) {
1768
-			$uuidAttr     = 'ldapUuidUserAttribute';
1769
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1770
-		} else {
1771
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1772
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1773
-		}
1774
-
1775
-		$uuid = false;
1776
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1777
-			$attr = $this->connection->$uuidAttr;
1778
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1779
-			if( !is_array($uuid)
1780
-				&& $uuidOverride !== ''
1781
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1782
-			{
1783
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1784
-					? $ldapRecord[$this->connection->$uuidAttr]
1785
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1786
-			}
1787
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1788
-				$uuid = $uuid[0];
1789
-			}
1790
-		}
1791
-
1792
-		return $uuid;
1793
-	}
1794
-
1795
-	/**
1796
-	 * converts a binary ObjectGUID into a string representation
1797
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1798
-	 * @return string
1799
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1800
-	 */
1801
-	private function convertObjectGUID2Str($oguid) {
1802
-		$hex_guid = bin2hex($oguid);
1803
-		$hex_guid_to_guid_str = '';
1804
-		for($k = 1; $k <= 4; ++$k) {
1805
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1806
-		}
1807
-		$hex_guid_to_guid_str .= '-';
1808
-		for($k = 1; $k <= 2; ++$k) {
1809
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1810
-		}
1811
-		$hex_guid_to_guid_str .= '-';
1812
-		for($k = 1; $k <= 2; ++$k) {
1813
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1814
-		}
1815
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1816
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1817
-
1818
-		return strtoupper($hex_guid_to_guid_str);
1819
-	}
1820
-
1821
-	/**
1822
-	 * the first three blocks of the string-converted GUID happen to be in
1823
-	 * reverse order. In order to use it in a filter, this needs to be
1824
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1825
-	 * to every two hax figures.
1826
-	 *
1827
-	 * If an invalid string is passed, it will be returned without change.
1828
-	 *
1829
-	 * @param string $guid
1830
-	 * @return string
1831
-	 */
1832
-	public function formatGuid2ForFilterUser($guid) {
1833
-		if(!is_string($guid)) {
1834
-			throw new \InvalidArgumentException('String expected');
1835
-		}
1836
-		$blocks = explode('-', $guid);
1837
-		if(count($blocks) !== 5) {
1838
-			/*
1335
+        $findings = [];
1336
+        $savedoffset = $offset;
1337
+        do {
1338
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1339
+            if($search === false) {
1340
+                return [];
1341
+            }
1342
+            list($sr, $pagedSearchOK) = $search;
1343
+            $cr = $this->connection->getConnectionResource();
1344
+
1345
+            if($skipHandling) {
1346
+                //i.e. result do not need to be fetched, we just need the cookie
1347
+                //thus pass 1 or any other value as $iFoundItems because it is not
1348
+                //used
1349
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1350
+                                $offset, $pagedSearchOK,
1351
+                                $skipHandling);
1352
+                return [];
1353
+            }
1354
+
1355
+            $iFoundItems = 0;
1356
+            foreach($sr as $res) {
1357
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1358
+                $iFoundItems = max($iFoundItems, $findings['count']);
1359
+                unset($findings['count']);
1360
+            }
1361
+
1362
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1363
+                $limitPerPage, $offset, $pagedSearchOK,
1364
+                                        $skipHandling);
1365
+            $offset += $limitPerPage;
1366
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1367
+        // reseting offset
1368
+        $offset = $savedoffset;
1369
+
1370
+        // if we're here, probably no connection resource is returned.
1371
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1372
+        if(is_null($findings)) {
1373
+            return [];
1374
+        }
1375
+
1376
+        if(!is_null($attr)) {
1377
+            $selection = [];
1378
+            $i = 0;
1379
+            foreach($findings as $item) {
1380
+                if(!is_array($item)) {
1381
+                    continue;
1382
+                }
1383
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1384
+                foreach($attr as $key) {
1385
+                    if(isset($item[$key])) {
1386
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1387
+                            unset($item[$key]['count']);
1388
+                        }
1389
+                        if($key !== 'dn') {
1390
+                            if($this->resemblesDN($key)) {
1391
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1392
+                            } else if($key === 'objectguid' || $key === 'guid') {
1393
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1394
+                            } else {
1395
+                                $selection[$i][$key] = $item[$key];
1396
+                            }
1397
+                        } else {
1398
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1399
+                        }
1400
+                    }
1401
+
1402
+                }
1403
+                $i++;
1404
+            }
1405
+            $findings = $selection;
1406
+        }
1407
+        //we slice the findings, when
1408
+        //a) paged search unsuccessful, though attempted
1409
+        //b) no paged search, but limit set
1410
+        if((!$this->getPagedSearchResultState()
1411
+            && $pagedSearchOK)
1412
+            || (
1413
+                !$pagedSearchOK
1414
+                && !is_null($limit)
1415
+            )
1416
+        ) {
1417
+            $findings = array_slice($findings, (int)$offset, $limit);
1418
+        }
1419
+        return $findings;
1420
+    }
1421
+
1422
+    /**
1423
+     * @param string $name
1424
+     * @return string
1425
+     * @throws \InvalidArgumentException
1426
+     */
1427
+    public function sanitizeUsername($name) {
1428
+        $name = trim($name);
1429
+
1430
+        if($this->connection->ldapIgnoreNamingRules) {
1431
+            return $name;
1432
+        }
1433
+
1434
+        // Transliteration to ASCII
1435
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1436
+        if($transliterated !== false) {
1437
+            // depending on system config iconv can work or not
1438
+            $name = $transliterated;
1439
+        }
1440
+
1441
+        // Replacements
1442
+        $name = str_replace(' ', '_', $name);
1443
+
1444
+        // Every remaining disallowed characters will be removed
1445
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1446
+
1447
+        if($name === '') {
1448
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1449
+        }
1450
+
1451
+        return $name;
1452
+    }
1453
+
1454
+    /**
1455
+     * escapes (user provided) parts for LDAP filter
1456
+     * @param string $input, the provided value
1457
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1458
+     * @return string the escaped string
1459
+     */
1460
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1461
+        $asterisk = '';
1462
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1463
+            $asterisk = '*';
1464
+            $input = mb_substr($input, 1, null, 'UTF-8');
1465
+        }
1466
+        $search  = ['*', '\\', '(', ')'];
1467
+        $replace = ['\\*', '\\\\', '\\(', '\\)'];
1468
+        return $asterisk . str_replace($search, $replace, $input);
1469
+    }
1470
+
1471
+    /**
1472
+     * combines the input filters with AND
1473
+     * @param string[] $filters the filters to connect
1474
+     * @return string the combined filter
1475
+     */
1476
+    public function combineFilterWithAnd($filters) {
1477
+        return $this->combineFilter($filters, '&');
1478
+    }
1479
+
1480
+    /**
1481
+     * combines the input filters with OR
1482
+     * @param string[] $filters the filters to connect
1483
+     * @return string the combined filter
1484
+     * Combines Filter arguments with OR
1485
+     */
1486
+    public function combineFilterWithOr($filters) {
1487
+        return $this->combineFilter($filters, '|');
1488
+    }
1489
+
1490
+    /**
1491
+     * combines the input filters with given operator
1492
+     * @param string[] $filters the filters to connect
1493
+     * @param string $operator either & or |
1494
+     * @return string the combined filter
1495
+     */
1496
+    private function combineFilter($filters, $operator) {
1497
+        $combinedFilter = '('.$operator;
1498
+        foreach($filters as $filter) {
1499
+            if ($filter !== '' && $filter[0] !== '(') {
1500
+                $filter = '('.$filter.')';
1501
+            }
1502
+            $combinedFilter.=$filter;
1503
+        }
1504
+        $combinedFilter.=')';
1505
+        return $combinedFilter;
1506
+    }
1507
+
1508
+    /**
1509
+     * creates a filter part for to perform search for users
1510
+     * @param string $search the search term
1511
+     * @return string the final filter part to use in LDAP searches
1512
+     */
1513
+    public function getFilterPartForUserSearch($search) {
1514
+        return $this->getFilterPartForSearch($search,
1515
+            $this->connection->ldapAttributesForUserSearch,
1516
+            $this->connection->ldapUserDisplayName);
1517
+    }
1518
+
1519
+    /**
1520
+     * creates a filter part for to perform search for groups
1521
+     * @param string $search the search term
1522
+     * @return string the final filter part to use in LDAP searches
1523
+     */
1524
+    public function getFilterPartForGroupSearch($search) {
1525
+        return $this->getFilterPartForSearch($search,
1526
+            $this->connection->ldapAttributesForGroupSearch,
1527
+            $this->connection->ldapGroupDisplayName);
1528
+    }
1529
+
1530
+    /**
1531
+     * creates a filter part for searches by splitting up the given search
1532
+     * string into single words
1533
+     * @param string $search the search term
1534
+     * @param string[] $searchAttributes needs to have at least two attributes,
1535
+     * otherwise it does not make sense :)
1536
+     * @return string the final filter part to use in LDAP searches
1537
+     * @throws \Exception
1538
+     */
1539
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1540
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1541
+            throw new \Exception('searchAttributes must be an array with at least two string');
1542
+        }
1543
+        $searchWords = explode(' ', trim($search));
1544
+        $wordFilters = [];
1545
+        foreach($searchWords as $word) {
1546
+            $word = $this->prepareSearchTerm($word);
1547
+            //every word needs to appear at least once
1548
+            $wordMatchOneAttrFilters = [];
1549
+            foreach($searchAttributes as $attr) {
1550
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1551
+            }
1552
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1553
+        }
1554
+        return $this->combineFilterWithAnd($wordFilters);
1555
+    }
1556
+
1557
+    /**
1558
+     * creates a filter part for searches
1559
+     * @param string $search the search term
1560
+     * @param string[]|null $searchAttributes
1561
+     * @param string $fallbackAttribute a fallback attribute in case the user
1562
+     * did not define search attributes. Typically the display name attribute.
1563
+     * @return string the final filter part to use in LDAP searches
1564
+     */
1565
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1566
+        $filter = [];
1567
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1568
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1569
+            try {
1570
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1571
+            } catch(\Exception $e) {
1572
+                \OCP\Util::writeLog(
1573
+                    'user_ldap',
1574
+                    'Creating advanced filter for search failed, falling back to simple method.',
1575
+                    ILogger::INFO
1576
+                );
1577
+            }
1578
+        }
1579
+
1580
+        $search = $this->prepareSearchTerm($search);
1581
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1582
+            if ($fallbackAttribute === '') {
1583
+                return '';
1584
+            }
1585
+            $filter[] = $fallbackAttribute . '=' . $search;
1586
+        } else {
1587
+            foreach($searchAttributes as $attribute) {
1588
+                $filter[] = $attribute . '=' . $search;
1589
+            }
1590
+        }
1591
+        if(count($filter) === 1) {
1592
+            return '('.$filter[0].')';
1593
+        }
1594
+        return $this->combineFilterWithOr($filter);
1595
+    }
1596
+
1597
+    /**
1598
+     * returns the search term depending on whether we are allowed
1599
+     * list users found by ldap with the current input appended by
1600
+     * a *
1601
+     * @return string
1602
+     */
1603
+    private function prepareSearchTerm($term) {
1604
+        $config = \OC::$server->getConfig();
1605
+
1606
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1607
+
1608
+        $result = $term;
1609
+        if ($term === '') {
1610
+            $result = '*';
1611
+        } else if ($allowEnum !== 'no') {
1612
+            $result = $term . '*';
1613
+        }
1614
+        return $result;
1615
+    }
1616
+
1617
+    /**
1618
+     * returns the filter used for counting users
1619
+     * @return string
1620
+     */
1621
+    public function getFilterForUserCount() {
1622
+        $filter = $this->combineFilterWithAnd([
1623
+            $this->connection->ldapUserFilter,
1624
+            $this->connection->ldapUserDisplayName . '=*'
1625
+        ]);
1626
+
1627
+        return $filter;
1628
+    }
1629
+
1630
+    /**
1631
+     * @param string $name
1632
+     * @param string $password
1633
+     * @return bool
1634
+     */
1635
+    public function areCredentialsValid($name, $password) {
1636
+        $name = $this->helper->DNasBaseParameter($name);
1637
+        $testConnection = clone $this->connection;
1638
+        $credentials = [
1639
+            'ldapAgentName' => $name,
1640
+            'ldapAgentPassword' => $password
1641
+        ];
1642
+        if(!$testConnection->setConfiguration($credentials)) {
1643
+            return false;
1644
+        }
1645
+        return $testConnection->bind();
1646
+    }
1647
+
1648
+    /**
1649
+     * reverse lookup of a DN given a known UUID
1650
+     *
1651
+     * @param string $uuid
1652
+     * @return string
1653
+     * @throws \Exception
1654
+     */
1655
+    public function getUserDnByUuid($uuid) {
1656
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1657
+        $filter       = $this->connection->ldapUserFilter;
1658
+        $base         = $this->connection->ldapBaseUsers;
1659
+
1660
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1661
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1662
+            // existing DN to be able to reliably detect it.
1663
+            $result = $this->search($filter, $base, ['dn'], 1);
1664
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1665
+                throw new \Exception('Cannot determine UUID attribute');
1666
+            }
1667
+            $dn = $result[0]['dn'][0];
1668
+            if(!$this->detectUuidAttribute($dn, true)) {
1669
+                throw new \Exception('Cannot determine UUID attribute');
1670
+            }
1671
+        } else {
1672
+            // The UUID attribute is either known or an override is given.
1673
+            // By calling this method we ensure that $this->connection->$uuidAttr
1674
+            // is definitely set
1675
+            if(!$this->detectUuidAttribute('', true)) {
1676
+                throw new \Exception('Cannot determine UUID attribute');
1677
+            }
1678
+        }
1679
+
1680
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1681
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1682
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1683
+        }
1684
+
1685
+        $filter = $uuidAttr . '=' . $uuid;
1686
+        $result = $this->searchUsers($filter, ['dn'], 2);
1687
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1688
+            // we put the count into account to make sure that this is
1689
+            // really unique
1690
+            return $result[0]['dn'][0];
1691
+        }
1692
+
1693
+        throw new \Exception('Cannot determine UUID attribute');
1694
+    }
1695
+
1696
+    /**
1697
+     * auto-detects the directory's UUID attribute
1698
+     *
1699
+     * @param string $dn a known DN used to check against
1700
+     * @param bool $isUser
1701
+     * @param bool $force the detection should be run, even if it is not set to auto
1702
+     * @param array|null $ldapRecord
1703
+     * @return bool true on success, false otherwise
1704
+     * @throws ServerNotAvailableException
1705
+     */
1706
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1707
+        if($isUser) {
1708
+            $uuidAttr     = 'ldapUuidUserAttribute';
1709
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1710
+        } else {
1711
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1712
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1713
+        }
1714
+
1715
+        if(!$force) {
1716
+            if($this->connection->$uuidAttr !== 'auto') {
1717
+                return true;
1718
+            } else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1719
+                $this->connection->$uuidAttr = $uuidOverride;
1720
+                return true;
1721
+            }
1722
+
1723
+            $attribute = $this->connection->getFromCache($uuidAttr);
1724
+            if(!$attribute === null) {
1725
+                $this->connection->$uuidAttr = $attribute;
1726
+                return true;
1727
+            }
1728
+        }
1729
+
1730
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1731
+            if($ldapRecord !== null) {
1732
+                // we have the info from LDAP already, we don't need to talk to the server again
1733
+                if(isset($ldapRecord[$attribute])) {
1734
+                    $this->connection->$uuidAttr = $attribute;
1735
+                    return true;
1736
+                }
1737
+            }
1738
+
1739
+            $value = $this->readAttribute($dn, $attribute);
1740
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1741
+                \OC::$server->getLogger()->debug(
1742
+                    'Setting {attribute} as {subject}',
1743
+                    [
1744
+                        'app' => 'user_ldap',
1745
+                        'attribute' => $attribute,
1746
+                        'subject' => $uuidAttr
1747
+                    ]
1748
+                );
1749
+                $this->connection->$uuidAttr = $attribute;
1750
+                $this->connection->writeToCache($uuidAttr, $attribute);
1751
+                return true;
1752
+            }
1753
+        }
1754
+        \OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1755
+
1756
+        return false;
1757
+    }
1758
+
1759
+    /**
1760
+     * @param string $dn
1761
+     * @param bool $isUser
1762
+     * @param null $ldapRecord
1763
+     * @return bool|string
1764
+     * @throws ServerNotAvailableException
1765
+     */
1766
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1767
+        if($isUser) {
1768
+            $uuidAttr     = 'ldapUuidUserAttribute';
1769
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1770
+        } else {
1771
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1772
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1773
+        }
1774
+
1775
+        $uuid = false;
1776
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1777
+            $attr = $this->connection->$uuidAttr;
1778
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1779
+            if( !is_array($uuid)
1780
+                && $uuidOverride !== ''
1781
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1782
+            {
1783
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1784
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1785
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1786
+            }
1787
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1788
+                $uuid = $uuid[0];
1789
+            }
1790
+        }
1791
+
1792
+        return $uuid;
1793
+    }
1794
+
1795
+    /**
1796
+     * converts a binary ObjectGUID into a string representation
1797
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1798
+     * @return string
1799
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1800
+     */
1801
+    private function convertObjectGUID2Str($oguid) {
1802
+        $hex_guid = bin2hex($oguid);
1803
+        $hex_guid_to_guid_str = '';
1804
+        for($k = 1; $k <= 4; ++$k) {
1805
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1806
+        }
1807
+        $hex_guid_to_guid_str .= '-';
1808
+        for($k = 1; $k <= 2; ++$k) {
1809
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1810
+        }
1811
+        $hex_guid_to_guid_str .= '-';
1812
+        for($k = 1; $k <= 2; ++$k) {
1813
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1814
+        }
1815
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1816
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1817
+
1818
+        return strtoupper($hex_guid_to_guid_str);
1819
+    }
1820
+
1821
+    /**
1822
+     * the first three blocks of the string-converted GUID happen to be in
1823
+     * reverse order. In order to use it in a filter, this needs to be
1824
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1825
+     * to every two hax figures.
1826
+     *
1827
+     * If an invalid string is passed, it will be returned without change.
1828
+     *
1829
+     * @param string $guid
1830
+     * @return string
1831
+     */
1832
+    public function formatGuid2ForFilterUser($guid) {
1833
+        if(!is_string($guid)) {
1834
+            throw new \InvalidArgumentException('String expected');
1835
+        }
1836
+        $blocks = explode('-', $guid);
1837
+        if(count($blocks) !== 5) {
1838
+            /*
1839 1839
 			 * Why not throw an Exception instead? This method is a utility
1840 1840
 			 * called only when trying to figure out whether a "missing" known
1841 1841
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1846,283 +1846,283 @@  discard block
 block discarded – undo
1846 1846
 			 * an exception here would kill the experience for a valid, acting
1847 1847
 			 * user. Instead we write a log message.
1848 1848
 			 */
1849
-			\OC::$server->getLogger()->info(
1850
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1851
-				'({uuid}) probably does not match UUID configuration.',
1852
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1853
-			);
1854
-			return $guid;
1855
-		}
1856
-		for($i=0; $i < 3; $i++) {
1857
-			$pairs = str_split($blocks[$i], 2);
1858
-			$pairs = array_reverse($pairs);
1859
-			$blocks[$i] = implode('', $pairs);
1860
-		}
1861
-		for($i=0; $i < 5; $i++) {
1862
-			$pairs = str_split($blocks[$i], 2);
1863
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1864
-		}
1865
-		return implode('', $blocks);
1866
-	}
1867
-
1868
-	/**
1869
-	 * gets a SID of the domain of the given dn
1870
-	 *
1871
-	 * @param string $dn
1872
-	 * @return string|bool
1873
-	 * @throws ServerNotAvailableException
1874
-	 */
1875
-	public function getSID($dn) {
1876
-		$domainDN = $this->getDomainDNFromDN($dn);
1877
-		$cacheKey = 'getSID-'.$domainDN;
1878
-		$sid = $this->connection->getFromCache($cacheKey);
1879
-		if(!is_null($sid)) {
1880
-			return $sid;
1881
-		}
1882
-
1883
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1884
-		if(!is_array($objectSid) || empty($objectSid)) {
1885
-			$this->connection->writeToCache($cacheKey, false);
1886
-			return false;
1887
-		}
1888
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1889
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1890
-
1891
-		return $domainObjectSid;
1892
-	}
1893
-
1894
-	/**
1895
-	 * converts a binary SID into a string representation
1896
-	 * @param string $sid
1897
-	 * @return string
1898
-	 */
1899
-	public function convertSID2Str($sid) {
1900
-		// The format of a SID binary string is as follows:
1901
-		// 1 byte for the revision level
1902
-		// 1 byte for the number n of variable sub-ids
1903
-		// 6 bytes for identifier authority value
1904
-		// n*4 bytes for n sub-ids
1905
-		//
1906
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1907
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1908
-		$revision = ord($sid[0]);
1909
-		$numberSubID = ord($sid[1]);
1910
-
1911
-		$subIdStart = 8; // 1 + 1 + 6
1912
-		$subIdLength = 4;
1913
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1914
-			// Incorrect number of bytes present.
1915
-			return '';
1916
-		}
1917
-
1918
-		// 6 bytes = 48 bits can be represented using floats without loss of
1919
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1920
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1921
-
1922
-		$subIDs = [];
1923
-		for ($i = 0; $i < $numberSubID; $i++) {
1924
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1925
-			$subIDs[] = sprintf('%u', $subID[1]);
1926
-		}
1927
-
1928
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1929
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1930
-	}
1931
-
1932
-	/**
1933
-	 * checks if the given DN is part of the given base DN(s)
1934
-	 * @param string $dn the DN
1935
-	 * @param string[] $bases array containing the allowed base DN or DNs
1936
-	 * @return bool
1937
-	 */
1938
-	public function isDNPartOfBase($dn, $bases) {
1939
-		$belongsToBase = false;
1940
-		$bases = $this->helper->sanitizeDN($bases);
1941
-
1942
-		foreach($bases as $base) {
1943
-			$belongsToBase = true;
1944
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1945
-				$belongsToBase = false;
1946
-			}
1947
-			if($belongsToBase) {
1948
-				break;
1949
-			}
1950
-		}
1951
-		return $belongsToBase;
1952
-	}
1953
-
1954
-	/**
1955
-	 * resets a running Paged Search operation
1956
-	 *
1957
-	 * @throws ServerNotAvailableException
1958
-	 */
1959
-	private function abandonPagedSearch() {
1960
-		$cr = $this->connection->getConnectionResource();
1961
-		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1962
-		$this->getPagedSearchResultState();
1963
-		$this->lastCookie = '';
1964
-		$this->cookies = [];
1965
-	}
1966
-
1967
-	/**
1968
-	 * get a cookie for the next LDAP paged search
1969
-	 * @param string $base a string with the base DN for the search
1970
-	 * @param string $filter the search filter to identify the correct search
1971
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1972
-	 * @param int $offset the offset for the new search to identify the correct search really good
1973
-	 * @return string containing the key or empty if none is cached
1974
-	 */
1975
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1976
-		if($offset === 0) {
1977
-			return '';
1978
-		}
1979
-		$offset -= $limit;
1980
-		//we work with cache here
1981
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1982
-		$cookie = '';
1983
-		if(isset($this->cookies[$cacheKey])) {
1984
-			$cookie = $this->cookies[$cacheKey];
1985
-			if(is_null($cookie)) {
1986
-				$cookie = '';
1987
-			}
1988
-		}
1989
-		return $cookie;
1990
-	}
1991
-
1992
-	/**
1993
-	 * checks whether an LDAP paged search operation has more pages that can be
1994
-	 * retrieved, typically when offset and limit are provided.
1995
-	 *
1996
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1997
-	 * be reset by other operations. Best, call it immediately after a search(),
1998
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1999
-	 * well. Don't rely on it with any fetchList-method.
2000
-	 * @return bool
2001
-	 */
2002
-	public function hasMoreResults() {
2003
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2004
-			// as in RFC 2696, when all results are returned, the cookie will
2005
-			// be empty.
2006
-			return false;
2007
-		}
2008
-
2009
-		return true;
2010
-	}
2011
-
2012
-	/**
2013
-	 * set a cookie for LDAP paged search run
2014
-	 * @param string $base a string with the base DN for the search
2015
-	 * @param string $filter the search filter to identify the correct search
2016
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
2017
-	 * @param int $offset the offset for the run search to identify the correct search really good
2018
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
2019
-	 * @return void
2020
-	 */
2021
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2022
-		// allow '0' for 389ds
2023
-		if(!empty($cookie) || $cookie === '0') {
2024
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2025
-			$this->cookies[$cacheKey] = $cookie;
2026
-			$this->lastCookie = $cookie;
2027
-		}
2028
-	}
2029
-
2030
-	/**
2031
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2032
-	 * @return boolean|null true on success, null or false otherwise
2033
-	 */
2034
-	public function getPagedSearchResultState() {
2035
-		$result = $this->pagedSearchedSuccessful;
2036
-		$this->pagedSearchedSuccessful = null;
2037
-		return $result;
2038
-	}
2039
-
2040
-	/**
2041
-	 * Prepares a paged search, if possible
2042
-	 *
2043
-	 * @param string $filter the LDAP filter for the search
2044
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2045
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
2046
-	 * @param int $limit
2047
-	 * @param int $offset
2048
-	 * @return bool|true
2049
-	 * @throws ServerNotAvailableException
2050
-	 */
2051
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2052
-		$pagedSearchOK = false;
2053
-		if ($limit !== 0) {
2054
-			$offset = (int)$offset; //can be null
2055
-			\OCP\Util::writeLog('user_ldap',
2056
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2057
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2058
-				ILogger::DEBUG);
2059
-			//get the cookie from the search for the previous search, required by LDAP
2060
-			foreach($bases as $base) {
2061
-
2062
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2063
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2064
-					// no cookie known from a potential previous search. We need
2065
-					// to start from 0 to come to the desired page. cookie value
2066
-					// of '0' is valid, because 389ds
2067
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2068
-					$this->search($filter, [$base], $attr, $limit, $reOffset, true);
2069
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2070
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2071
-					// '0' is valid, because 389ds
2072
-					//TODO: remember this, probably does not change in the next request...
2073
-					if(empty($cookie) && $cookie !== '0') {
2074
-						$cookie = null;
2075
-					}
2076
-				}
2077
-				if(!is_null($cookie)) {
2078
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2079
-					$this->abandonPagedSearch();
2080
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2081
-						$this->connection->getConnectionResource(), $limit,
2082
-						false, $cookie);
2083
-					if(!$pagedSearchOK) {
2084
-						return false;
2085
-					}
2086
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
2087
-				} else {
2088
-					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
2089
-					\OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
2090
-				}
2091
-
2092
-			}
2093
-		/* ++ Fixing RHDS searches with pages with zero results ++
1849
+            \OC::$server->getLogger()->info(
1850
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1851
+                '({uuid}) probably does not match UUID configuration.',
1852
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1853
+            );
1854
+            return $guid;
1855
+        }
1856
+        for($i=0; $i < 3; $i++) {
1857
+            $pairs = str_split($blocks[$i], 2);
1858
+            $pairs = array_reverse($pairs);
1859
+            $blocks[$i] = implode('', $pairs);
1860
+        }
1861
+        for($i=0; $i < 5; $i++) {
1862
+            $pairs = str_split($blocks[$i], 2);
1863
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1864
+        }
1865
+        return implode('', $blocks);
1866
+    }
1867
+
1868
+    /**
1869
+     * gets a SID of the domain of the given dn
1870
+     *
1871
+     * @param string $dn
1872
+     * @return string|bool
1873
+     * @throws ServerNotAvailableException
1874
+     */
1875
+    public function getSID($dn) {
1876
+        $domainDN = $this->getDomainDNFromDN($dn);
1877
+        $cacheKey = 'getSID-'.$domainDN;
1878
+        $sid = $this->connection->getFromCache($cacheKey);
1879
+        if(!is_null($sid)) {
1880
+            return $sid;
1881
+        }
1882
+
1883
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1884
+        if(!is_array($objectSid) || empty($objectSid)) {
1885
+            $this->connection->writeToCache($cacheKey, false);
1886
+            return false;
1887
+        }
1888
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1889
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1890
+
1891
+        return $domainObjectSid;
1892
+    }
1893
+
1894
+    /**
1895
+     * converts a binary SID into a string representation
1896
+     * @param string $sid
1897
+     * @return string
1898
+     */
1899
+    public function convertSID2Str($sid) {
1900
+        // The format of a SID binary string is as follows:
1901
+        // 1 byte for the revision level
1902
+        // 1 byte for the number n of variable sub-ids
1903
+        // 6 bytes for identifier authority value
1904
+        // n*4 bytes for n sub-ids
1905
+        //
1906
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1907
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1908
+        $revision = ord($sid[0]);
1909
+        $numberSubID = ord($sid[1]);
1910
+
1911
+        $subIdStart = 8; // 1 + 1 + 6
1912
+        $subIdLength = 4;
1913
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1914
+            // Incorrect number of bytes present.
1915
+            return '';
1916
+        }
1917
+
1918
+        // 6 bytes = 48 bits can be represented using floats without loss of
1919
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1920
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1921
+
1922
+        $subIDs = [];
1923
+        for ($i = 0; $i < $numberSubID; $i++) {
1924
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1925
+            $subIDs[] = sprintf('%u', $subID[1]);
1926
+        }
1927
+
1928
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1929
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1930
+    }
1931
+
1932
+    /**
1933
+     * checks if the given DN is part of the given base DN(s)
1934
+     * @param string $dn the DN
1935
+     * @param string[] $bases array containing the allowed base DN or DNs
1936
+     * @return bool
1937
+     */
1938
+    public function isDNPartOfBase($dn, $bases) {
1939
+        $belongsToBase = false;
1940
+        $bases = $this->helper->sanitizeDN($bases);
1941
+
1942
+        foreach($bases as $base) {
1943
+            $belongsToBase = true;
1944
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1945
+                $belongsToBase = false;
1946
+            }
1947
+            if($belongsToBase) {
1948
+                break;
1949
+            }
1950
+        }
1951
+        return $belongsToBase;
1952
+    }
1953
+
1954
+    /**
1955
+     * resets a running Paged Search operation
1956
+     *
1957
+     * @throws ServerNotAvailableException
1958
+     */
1959
+    private function abandonPagedSearch() {
1960
+        $cr = $this->connection->getConnectionResource();
1961
+        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1962
+        $this->getPagedSearchResultState();
1963
+        $this->lastCookie = '';
1964
+        $this->cookies = [];
1965
+    }
1966
+
1967
+    /**
1968
+     * get a cookie for the next LDAP paged search
1969
+     * @param string $base a string with the base DN for the search
1970
+     * @param string $filter the search filter to identify the correct search
1971
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1972
+     * @param int $offset the offset for the new search to identify the correct search really good
1973
+     * @return string containing the key or empty if none is cached
1974
+     */
1975
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1976
+        if($offset === 0) {
1977
+            return '';
1978
+        }
1979
+        $offset -= $limit;
1980
+        //we work with cache here
1981
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1982
+        $cookie = '';
1983
+        if(isset($this->cookies[$cacheKey])) {
1984
+            $cookie = $this->cookies[$cacheKey];
1985
+            if(is_null($cookie)) {
1986
+                $cookie = '';
1987
+            }
1988
+        }
1989
+        return $cookie;
1990
+    }
1991
+
1992
+    /**
1993
+     * checks whether an LDAP paged search operation has more pages that can be
1994
+     * retrieved, typically when offset and limit are provided.
1995
+     *
1996
+     * Be very careful to use it: the last cookie value, which is inspected, can
1997
+     * be reset by other operations. Best, call it immediately after a search(),
1998
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1999
+     * well. Don't rely on it with any fetchList-method.
2000
+     * @return bool
2001
+     */
2002
+    public function hasMoreResults() {
2003
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2004
+            // as in RFC 2696, when all results are returned, the cookie will
2005
+            // be empty.
2006
+            return false;
2007
+        }
2008
+
2009
+        return true;
2010
+    }
2011
+
2012
+    /**
2013
+     * set a cookie for LDAP paged search run
2014
+     * @param string $base a string with the base DN for the search
2015
+     * @param string $filter the search filter to identify the correct search
2016
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
2017
+     * @param int $offset the offset for the run search to identify the correct search really good
2018
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
2019
+     * @return void
2020
+     */
2021
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2022
+        // allow '0' for 389ds
2023
+        if(!empty($cookie) || $cookie === '0') {
2024
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2025
+            $this->cookies[$cacheKey] = $cookie;
2026
+            $this->lastCookie = $cookie;
2027
+        }
2028
+    }
2029
+
2030
+    /**
2031
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2032
+     * @return boolean|null true on success, null or false otherwise
2033
+     */
2034
+    public function getPagedSearchResultState() {
2035
+        $result = $this->pagedSearchedSuccessful;
2036
+        $this->pagedSearchedSuccessful = null;
2037
+        return $result;
2038
+    }
2039
+
2040
+    /**
2041
+     * Prepares a paged search, if possible
2042
+     *
2043
+     * @param string $filter the LDAP filter for the search
2044
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2045
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
2046
+     * @param int $limit
2047
+     * @param int $offset
2048
+     * @return bool|true
2049
+     * @throws ServerNotAvailableException
2050
+     */
2051
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2052
+        $pagedSearchOK = false;
2053
+        if ($limit !== 0) {
2054
+            $offset = (int)$offset; //can be null
2055
+            \OCP\Util::writeLog('user_ldap',
2056
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2057
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2058
+                ILogger::DEBUG);
2059
+            //get the cookie from the search for the previous search, required by LDAP
2060
+            foreach($bases as $base) {
2061
+
2062
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2063
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2064
+                    // no cookie known from a potential previous search. We need
2065
+                    // to start from 0 to come to the desired page. cookie value
2066
+                    // of '0' is valid, because 389ds
2067
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2068
+                    $this->search($filter, [$base], $attr, $limit, $reOffset, true);
2069
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2070
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2071
+                    // '0' is valid, because 389ds
2072
+                    //TODO: remember this, probably does not change in the next request...
2073
+                    if(empty($cookie) && $cookie !== '0') {
2074
+                        $cookie = null;
2075
+                    }
2076
+                }
2077
+                if(!is_null($cookie)) {
2078
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2079
+                    $this->abandonPagedSearch();
2080
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2081
+                        $this->connection->getConnectionResource(), $limit,
2082
+                        false, $cookie);
2083
+                    if(!$pagedSearchOK) {
2084
+                        return false;
2085
+                    }
2086
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
2087
+                } else {
2088
+                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
2089
+                    \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
2090
+                }
2091
+
2092
+            }
2093
+        /* ++ Fixing RHDS searches with pages with zero results ++
2094 2094
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
2095 2095
 		 * due to pages with zero results.
2096 2096
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
2097 2097
 		 * if we don't have a previous paged search.
2098 2098
 		 */
2099
-		} else if ($limit === 0 && !empty($this->lastCookie)) {
2100
-			// a search without limit was requested. However, if we do use
2101
-			// Paged Search once, we always must do it. This requires us to
2102
-			// initialize it with the configured page size.
2103
-			$this->abandonPagedSearch();
2104
-			// in case someone set it to 0 … use 500, otherwise no results will
2105
-			// be returned.
2106
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2107
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2108
-				$this->connection->getConnectionResource(),
2109
-				$pageSize, false, '');
2110
-		}
2111
-
2112
-		return $pagedSearchOK;
2113
-	}
2114
-
2115
-	/**
2116
-	 * Is more than one $attr used for search?
2117
-	 *
2118
-	 * @param string|string[]|null $attr
2119
-	 * @return bool
2120
-	 */
2121
-	private function manyAttributes($attr): bool {
2122
-		if (\is_array($attr)) {
2123
-			return \count($attr) > 1;
2124
-		}
2125
-		return false;
2126
-	}
2099
+        } else if ($limit === 0 && !empty($this->lastCookie)) {
2100
+            // a search without limit was requested. However, if we do use
2101
+            // Paged Search once, we always must do it. This requires us to
2102
+            // initialize it with the configured page size.
2103
+            $this->abandonPagedSearch();
2104
+            // in case someone set it to 0 … use 500, otherwise no results will
2105
+            // be returned.
2106
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2107
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2108
+                $this->connection->getConnectionResource(),
2109
+                $pageSize, false, '');
2110
+        }
2111
+
2112
+        return $pagedSearchOK;
2113
+    }
2114
+
2115
+    /**
2116
+     * Is more than one $attr used for search?
2117
+     *
2118
+     * @param string|string[]|null $attr
2119
+     * @return bool
2120
+     */
2121
+    private function manyAttributes($attr): bool {
2122
+        if (\is_array($attr)) {
2123
+            return \count($attr) > 1;
2124
+        }
2125
+        return false;
2126
+    }
2127 2127
 
2128 2128
 }
Please login to merge, or discard this patch.
Spacing   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -133,7 +133,7 @@  discard block
 block discarded – undo
133 133
 	 * @return AbstractMapping
134 134
 	 */
135 135
 	public function getUserMapper() {
136
-		if(is_null($this->userMapper)) {
136
+		if (is_null($this->userMapper)) {
137 137
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
138 138
 		}
139 139
 		return $this->userMapper;
@@ -153,7 +153,7 @@  discard block
 block discarded – undo
153 153
 	 * @return AbstractMapping
154 154
 	 */
155 155
 	public function getGroupMapper() {
156
-		if(is_null($this->groupMapper)) {
156
+		if (is_null($this->groupMapper)) {
157 157
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
158 158
 		}
159 159
 		return $this->groupMapper;
@@ -186,14 +186,14 @@  discard block
 block discarded – undo
186 186
 	 * @throws ServerNotAvailableException
187 187
 	 */
188 188
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
189
-		if(!$this->checkConnection()) {
189
+		if (!$this->checkConnection()) {
190 190
 			\OCP\Util::writeLog('user_ldap',
191 191
 				'No LDAP Connector assigned, access impossible for readAttribute.',
192 192
 				ILogger::WARN);
193 193
 			return false;
194 194
 		}
195 195
 		$cr = $this->connection->getConnectionResource();
196
-		if(!$this->ldap->isResource($cr)) {
196
+		if (!$this->ldap->isResource($cr)) {
197 197
 			//LDAP not available
198 198
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
199 199
 			return false;
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 		$this->abandonPagedSearch();
204 204
 		// openLDAP requires that we init a new Paged Search. Not needed by AD,
205 205
 		// but does not hurt either.
206
-		$pagingSize = (int)$this->connection->ldapPagingSize;
206
+		$pagingSize = (int) $this->connection->ldapPagingSize;
207 207
 		// 0 won't result in replies, small numbers may leave out groups
208 208
 		// (cf. #12306), 500 is default for paging and should work everywhere.
209 209
 		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
@@ -216,7 +216,7 @@  discard block
 block discarded – undo
216 216
 		$isRangeRequest = false;
217 217
 		do {
218 218
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
219
-			if(is_bool($result)) {
219
+			if (is_bool($result)) {
220 220
 				// when an exists request was run and it was successful, an empty
221 221
 				// array must be returned
222 222
 				return $result ? [] : false;
@@ -233,22 +233,22 @@  discard block
 block discarded – undo
233 233
 			$result = $this->extractRangeData($result, $attr);
234 234
 			if (!empty($result)) {
235 235
 				$normalizedResult = $this->extractAttributeValuesFromResult(
236
-					[ $attr => $result['values'] ],
236
+					[$attr => $result['values']],
237 237
 					$attr
238 238
 				);
239 239
 				$values = array_merge($values, $normalizedResult);
240 240
 
241
-				if($result['rangeHigh'] === '*') {
241
+				if ($result['rangeHigh'] === '*') {
242 242
 					// when server replies with * as high range value, there are
243 243
 					// no more results left
244 244
 					return $values;
245 245
 				} else {
246
-					$low  = $result['rangeHigh'] + 1;
247
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
246
+					$low = $result['rangeHigh'] + 1;
247
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
248 248
 					$isRangeRequest = true;
249 249
 				}
250 250
 			}
251
-		} while($isRangeRequest);
251
+		} while ($isRangeRequest);
252 252
 
253 253
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
254 254
 		return false;
@@ -274,13 +274,13 @@  discard block
 block discarded – undo
274 274
 		if (!$this->ldap->isResource($rr)) {
275 275
 			if ($attribute !== '') {
276 276
 				//do not throw this message on userExists check, irritates
277
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
277
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, ILogger::DEBUG);
278 278
 			}
279 279
 			//in case an error occurs , e.g. object does not exist
280 280
 			return false;
281 281
 		}
282 282
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
283
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
283
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', ILogger::DEBUG);
284 284
 			return true;
285 285
 		}
286 286
 		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
@@ -305,12 +305,12 @@  discard block
 block discarded – undo
305 305
 	 */
306 306
 	public function extractAttributeValuesFromResult($result, $attribute) {
307 307
 		$values = [];
308
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
308
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
309 309
 			$lowercaseAttribute = strtolower($attribute);
310
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
311
-				if($this->resemblesDN($attribute)) {
310
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
311
+				if ($this->resemblesDN($attribute)) {
312 312
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
313
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
313
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
314 314
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
315 315
 				} else {
316 316
 					$values[] = $result[$attribute][$i];
@@ -332,10 +332,10 @@  discard block
 block discarded – undo
332 332
 	 */
333 333
 	public function extractRangeData($result, $attribute) {
334 334
 		$keys = array_keys($result);
335
-		foreach($keys as $key) {
336
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
335
+		foreach ($keys as $key) {
336
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
337 337
 				$queryData = explode(';', $key);
338
-				if(strpos($queryData[1], 'range=') === 0) {
338
+				if (strpos($queryData[1], 'range=') === 0) {
339 339
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
340 340
 					$data = [
341 341
 						'values' => $result[$key],
@@ -360,11 +360,11 @@  discard block
 block discarded – undo
360 360
 	 * @throws \Exception
361 361
 	 */
362 362
 	public function setPassword($userDN, $password) {
363
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
363
+		if ((int) $this->connection->turnOnPasswordChange !== 1) {
364 364
 			throw new \Exception('LDAP password changes are disabled.');
365 365
 		}
366 366
 		$cr = $this->connection->getConnectionResource();
367
-		if(!$this->ldap->isResource($cr)) {
367
+		if (!$this->ldap->isResource($cr)) {
368 368
 			//LDAP not available
369 369
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
370 370
 			return false;
@@ -373,7 +373,7 @@  discard block
 block discarded – undo
373 373
 			// try PASSWD extended operation first
374 374
 			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
375 375
 						@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
376
-		} catch(ConstraintViolationException $e) {
376
+		} catch (ConstraintViolationException $e) {
377 377
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
378 378
 		}
379 379
 	}
@@ -415,17 +415,17 @@  discard block
 block discarded – undo
415 415
 	 */
416 416
 	public function getDomainDNFromDN($dn) {
417 417
 		$allParts = $this->ldap->explodeDN($dn, 0);
418
-		if($allParts === false) {
418
+		if ($allParts === false) {
419 419
 			//not a valid DN
420 420
 			return '';
421 421
 		}
422 422
 		$domainParts = [];
423 423
 		$dcFound = false;
424
-		foreach($allParts as $part) {
425
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
424
+		foreach ($allParts as $part) {
425
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
426 426
 				$dcFound = true;
427 427
 			}
428
-			if($dcFound) {
428
+			if ($dcFound) {
429 429
 				$domainParts[] = $part;
430 430
 			}
431 431
 		}
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 
452 452
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
453 453
 		//server setups
454
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
454
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
455 455
 			return $fdn;
456 456
 		}
457 457
 
@@ -470,7 +470,7 @@  discard block
 block discarded – undo
470 470
 		//To avoid bypassing the base DN settings under certain circumstances
471 471
 		//with the group support, check whether the provided DN matches one of
472 472
 		//the given Bases
473
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
473
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
474 474
 			return false;
475 475
 		}
476 476
 
@@ -488,11 +488,11 @@  discard block
 block discarded – undo
488 488
 	 */
489 489
 	public function groupsMatchFilter($groupDNs) {
490 490
 		$validGroupDNs = [];
491
-		foreach($groupDNs as $dn) {
491
+		foreach ($groupDNs as $dn) {
492 492
 			$cacheKey = 'groupsMatchFilter-'.$dn;
493 493
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
494
-			if(!is_null($groupMatchFilter)) {
495
-				if($groupMatchFilter) {
494
+			if (!is_null($groupMatchFilter)) {
495
+				if ($groupMatchFilter) {
496 496
 					$validGroupDNs[] = $dn;
497 497
 				}
498 498
 				continue;
@@ -500,13 +500,13 @@  discard block
 block discarded – undo
500 500
 
501 501
 			// Check the base DN first. If this is not met already, we don't
502 502
 			// need to ask the server at all.
503
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
503
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
504 504
 				$this->connection->writeToCache($cacheKey, false);
505 505
 				continue;
506 506
 			}
507 507
 
508 508
 			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
509
-			if(is_array($result)) {
509
+			if (is_array($result)) {
510 510
 				$this->connection->writeToCache($cacheKey, true);
511 511
 				$validGroupDNs[] = $dn;
512 512
 			} else {
@@ -529,7 +529,7 @@  discard block
 block discarded – undo
529 529
 		//To avoid bypassing the base DN settings under certain circumstances
530 530
 		//with the group support, check whether the provided DN matches one of
531 531
 		//the given Bases
532
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
532
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
533 533
 			return false;
534 534
 		}
535 535
 
@@ -549,7 +549,7 @@  discard block
 block discarded – undo
549 549
 	 */
550 550
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
551 551
 		$newlyMapped = false;
552
-		if($isUser) {
552
+		if ($isUser) {
553 553
 			$mapper = $this->getUserMapper();
554 554
 			$nameAttribute = $this->connection->ldapUserDisplayName;
555 555
 			$filter = $this->connection->ldapUserFilter;
@@ -561,15 +561,15 @@  discard block
 block discarded – undo
561 561
 
562 562
 		//let's try to retrieve the Nextcloud name from the mappings table
563 563
 		$ncName = $mapper->getNameByDN($fdn);
564
-		if(is_string($ncName)) {
564
+		if (is_string($ncName)) {
565 565
 			return $ncName;
566 566
 		}
567 567
 
568 568
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
569 569
 		$uuid = $this->getUUID($fdn, $isUser, $record);
570
-		if(is_string($uuid)) {
570
+		if (is_string($uuid)) {
571 571
 			$ncName = $mapper->getNameByUUID($uuid);
572
-			if(is_string($ncName)) {
572
+			if (is_string($ncName)) {
573 573
 				$mapper->setDNbyUUID($fdn, $uuid);
574 574
 				return $ncName;
575 575
 			}
@@ -579,17 +579,17 @@  discard block
 block discarded – undo
579 579
 			return false;
580 580
 		}
581 581
 
582
-		if(is_null($ldapName)) {
582
+		if (is_null($ldapName)) {
583 583
 			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
584
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
584
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
585 585
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
586 586
 				return false;
587 587
 			}
588 588
 			$ldapName = $ldapName[0];
589 589
 		}
590 590
 
591
-		if($isUser) {
592
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
591
+		if ($isUser) {
592
+			$usernameAttribute = (string) $this->connection->ldapExpertUsernameAttr;
593 593
 			if ($usernameAttribute !== '') {
594 594
 				$username = $this->readAttribute($fdn, $usernameAttribute);
595 595
 				$username = $username[0];
@@ -619,14 +619,14 @@  discard block
 block discarded – undo
619 619
 		// outside of core user management will still cache the user as non-existing.
620 620
 		$originalTTL = $this->connection->ldapCacheTTL;
621 621
 		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
622
-		if( $intName !== ''
622
+		if ($intName !== ''
623 623
 			&& (($isUser && !$this->ncUserManager->userExists($intName))
624 624
 				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
625 625
 			)
626 626
 		) {
627 627
 			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
628 628
 			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
629
-			if($newlyMapped) {
629
+			if ($newlyMapped) {
630 630
 				return $intName;
631 631
 			}
632 632
 		}
@@ -634,7 +634,7 @@  discard block
 block discarded – undo
634 634
 		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
635 635
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
636 636
 		if (is_string($altName)) {
637
-			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
637
+			if ($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
638 638
 				$newlyMapped = true;
639 639
 				return $altName;
640 640
 			}
@@ -652,7 +652,7 @@  discard block
 block discarded – undo
652 652
 		string $uuid,
653 653
 		bool $isUser
654 654
 	) :bool {
655
-		if($mapper->map($fdn, $name, $uuid)) {
655
+		if ($mapper->map($fdn, $name, $uuid)) {
656 656
 			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
657 657
 				$this->cacheUserExists($name);
658 658
 				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 	 * @throws \Exception
698 698
 	 */
699 699
 	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
700
-		if($isUsers) {
700
+		if ($isUsers) {
701 701
 			$nameAttribute = $this->connection->ldapUserDisplayName;
702 702
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
703 703
 		} else {
@@ -705,9 +705,9 @@  discard block
 block discarded – undo
705 705
 		}
706 706
 		$nextcloudNames = [];
707 707
 
708
-		foreach($ldapObjects as $ldapObject) {
708
+		foreach ($ldapObjects as $ldapObject) {
709 709
 			$nameByLDAP = null;
710
-			if(    isset($ldapObject[$nameAttribute])
710
+			if (isset($ldapObject[$nameAttribute])
711 711
 				&& is_array($ldapObject[$nameAttribute])
712 712
 				&& isset($ldapObject[$nameAttribute][0])
713 713
 			) {
@@ -716,19 +716,19 @@  discard block
 block discarded – undo
716 716
 			}
717 717
 
718 718
 			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
719
-			if($ncName) {
719
+			if ($ncName) {
720 720
 				$nextcloudNames[] = $ncName;
721
-				if($isUsers) {
721
+				if ($isUsers) {
722 722
 					$this->updateUserState($ncName);
723 723
 					//cache the user names so it does not need to be retrieved
724 724
 					//again later (e.g. sharing dialogue).
725
-					if(is_null($nameByLDAP)) {
725
+					if (is_null($nameByLDAP)) {
726 726
 						continue;
727 727
 					}
728 728
 					$sndName = isset($ldapObject[$sndAttribute][0])
729 729
 						? $ldapObject[$sndAttribute][0] : '';
730 730
 					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
731
-				} else if($nameByLDAP !== null) {
731
+				} else if ($nameByLDAP !== null) {
732 732
 					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
733 733
 				}
734 734
 			}
@@ -744,7 +744,7 @@  discard block
 block discarded – undo
744 744
 	 */
745 745
 	public function updateUserState($ncname) {
746 746
 		$user = $this->userManager->get($ncname);
747
-		if($user instanceof OfflineUser) {
747
+		if ($user instanceof OfflineUser) {
748 748
 			$user->unmark();
749 749
 		}
750 750
 	}
@@ -784,7 +784,7 @@  discard block
 block discarded – undo
784 784
 	 */
785 785
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
786 786
 		$user = $this->userManager->get($ocName);
787
-		if($user === null) {
787
+		if ($user === null) {
788 788
 			return;
789 789
 		}
790 790
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -793,7 +793,7 @@  discard block
 block discarded – undo
793 793
 	}
794 794
 
795 795
 	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
796
-		$cacheKey = 'group_getDisplayName' . $ncName;
796
+		$cacheKey = 'group_getDisplayName'.$ncName;
797 797
 		$this->connection->writeToCache($cacheKey, $displayName);
798 798
 	}
799 799
 
@@ -809,9 +809,9 @@  discard block
 block discarded – undo
809 809
 		$attempts = 0;
810 810
 		//while loop is just a precaution. If a name is not generated within
811 811
 		//20 attempts, something else is very wrong. Avoids infinite loop.
812
-		while($attempts < 20){
813
-			$altName = $name . '_' . rand(1000,9999);
814
-			if(!$this->ncUserManager->userExists($altName)) {
812
+		while ($attempts < 20) {
813
+			$altName = $name.'_'.rand(1000, 9999);
814
+			if (!$this->ncUserManager->userExists($altName)) {
815 815
 				return $altName;
816 816
 			}
817 817
 			$attempts++;
@@ -833,25 +833,25 @@  discard block
 block discarded – undo
833 833
 	 */
834 834
 	private function _createAltInternalOwnCloudNameForGroups($name) {
835 835
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
836
-		if(!$usedNames || count($usedNames) === 0) {
836
+		if (!$usedNames || count($usedNames) === 0) {
837 837
 			$lastNo = 1; //will become name_2
838 838
 		} else {
839 839
 			natsort($usedNames);
840 840
 			$lastName = array_pop($usedNames);
841
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
841
+			$lastNo = (int) substr($lastName, strrpos($lastName, '_') + 1);
842 842
 		}
843
-		$altName = $name.'_'. (string)($lastNo+1);
843
+		$altName = $name.'_'.(string) ($lastNo + 1);
844 844
 		unset($usedNames);
845 845
 
846 846
 		$attempts = 1;
847
-		while($attempts < 21){
847
+		while ($attempts < 21) {
848 848
 			// Check to be really sure it is unique
849 849
 			// while loop is just a precaution. If a name is not generated within
850 850
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
851
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
851
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
852 852
 				return $altName;
853 853
 			}
854
-			$altName = $name . '_' . ($lastNo + $attempts);
854
+			$altName = $name.'_'.($lastNo + $attempts);
855 855
 			$attempts++;
856 856
 		}
857 857
 		return false;
@@ -866,7 +866,7 @@  discard block
 block discarded – undo
866 866
 	private function createAltInternalOwnCloudName($name, $isUser) {
867 867
 		$originalTTL = $this->connection->ldapCacheTTL;
868 868
 		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
869
-		if($isUser) {
869
+		if ($isUser) {
870 870
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
871 871
 		} else {
872 872
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -915,13 +915,13 @@  discard block
 block discarded – undo
915 915
 	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
916 916
 		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
917 917
 		$recordsToUpdate = $ldapRecords;
918
-		if(!$forceApplyAttributes) {
918
+		if (!$forceApplyAttributes) {
919 919
 			$isBackgroundJobModeAjax = $this->config
920 920
 					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
921 921
 			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
922 922
 				$newlyMapped = false;
923 923
 				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
924
-				if(is_string($uid)) {
924
+				if (is_string($uid)) {
925 925
 					$this->cacheUserExists($uid);
926 926
 				}
927 927
 				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
@@ -939,15 +939,15 @@  discard block
 block discarded – undo
939 939
 	 * @param array $ldapRecords
940 940
 	 * @throws \Exception
941 941
 	 */
942
-	public function batchApplyUserAttributes(array $ldapRecords){
942
+	public function batchApplyUserAttributes(array $ldapRecords) {
943 943
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
944
-		foreach($ldapRecords as $userRecord) {
945
-			if(!isset($userRecord[$displayNameAttribute])) {
944
+		foreach ($ldapRecords as $userRecord) {
945
+			if (!isset($userRecord[$displayNameAttribute])) {
946 946
 				// displayName is obligatory
947 947
 				continue;
948 948
 			}
949
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
950
-			if($ocName === false) {
949
+			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
950
+			if ($ocName === false) {
951 951
 				continue;
952 952
 			}
953 953
 			$this->updateUserState($ocName);
@@ -975,7 +975,7 @@  discard block
 block discarded – undo
975 975
 		array_walk($groupRecords, function($record) {
976 976
 			$newlyMapped = false;
977 977
 			$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
978
-			if(!$newlyMapped && is_string($gid)) {
978
+			if (!$newlyMapped && is_string($gid)) {
979 979
 				$this->cacheGroupExists($gid);
980 980
 			}
981 981
 		});
@@ -988,8 +988,8 @@  discard block
 block discarded – undo
988 988
 	 * @return array
989 989
 	 */
990 990
 	private function fetchList($list, $manyAttributes) {
991
-		if(is_array($list)) {
992
-			if($manyAttributes) {
991
+		if (is_array($list)) {
992
+			if ($manyAttributes) {
993 993
 				return $list;
994 994
 			} else {
995 995
 				$list = array_reduce($list, function($carry, $item) {
@@ -1019,7 +1019,7 @@  discard block
 block discarded – undo
1019 1019
 	 */
1020 1020
 	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1021 1021
 		$result = [];
1022
-		foreach($this->connection->ldapBaseUsers as $base) {
1022
+		foreach ($this->connection->ldapBaseUsers as $base) {
1023 1023
 			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1024 1024
 		}
1025 1025
 		return $result;
@@ -1035,9 +1035,9 @@  discard block
 block discarded – undo
1035 1035
 	 */
1036 1036
 	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1037 1037
 		$result = false;
1038
-		foreach($this->connection->ldapBaseUsers as $base) {
1038
+		foreach ($this->connection->ldapBaseUsers as $base) {
1039 1039
 			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1040
-			$result = is_int($count) ? (int)$result + $count : $result;
1040
+			$result = is_int($count) ? (int) $result + $count : $result;
1041 1041
 		}
1042 1042
 		return $result;
1043 1043
 	}
@@ -1056,7 +1056,7 @@  discard block
 block discarded – undo
1056 1056
 	 */
1057 1057
 	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1058 1058
 		$result = [];
1059
-		foreach($this->connection->ldapBaseGroups as $base) {
1059
+		foreach ($this->connection->ldapBaseGroups as $base) {
1060 1060
 			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1061 1061
 		}
1062 1062
 		return $result;
@@ -1074,9 +1074,9 @@  discard block
 block discarded – undo
1074 1074
 	 */
1075 1075
 	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1076 1076
 		$result = false;
1077
-		foreach($this->connection->ldapBaseGroups as $base) {
1077
+		foreach ($this->connection->ldapBaseGroups as $base) {
1078 1078
 			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1079
-			$result = is_int($count) ? (int)$result + $count : $result;
1079
+			$result = is_int($count) ? (int) $result + $count : $result;
1080 1080
 		}
1081 1081
 		return $result;
1082 1082
 	}
@@ -1091,9 +1091,9 @@  discard block
 block discarded – undo
1091 1091
 	 */
1092 1092
 	public function countObjects($limit = null, $offset = null) {
1093 1093
 		$result = false;
1094
-		foreach($this->connection->ldapBase as $base) {
1094
+		foreach ($this->connection->ldapBase as $base) {
1095 1095
 			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1096
-			$result = is_int($count) ? (int)$result + $count : $result;
1096
+			$result = is_int($count) ? (int) $result + $count : $result;
1097 1097
 		}
1098 1098
 		return $result;
1099 1099
 	}
@@ -1118,7 +1118,7 @@  discard block
 block discarded – undo
1118 1118
 		// php no longer supports call-time pass-by-reference
1119 1119
 		// thus cannot support controlPagedResultResponse as the third argument
1120 1120
 		// is a reference
1121
-		$doMethod = function () use ($command, &$arguments) {
1121
+		$doMethod = function() use ($command, &$arguments) {
1122 1122
 			if ($command == 'controlPagedResultResponse') {
1123 1123
 				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1124 1124
 			} else {
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 			$this->connection->resetConnectionResource();
1137 1137
 			$cr = $this->connection->getConnectionResource();
1138 1138
 
1139
-			if(!$this->ldap->isResource($cr)) {
1139
+			if (!$this->ldap->isResource($cr)) {
1140 1140
 				// Seems like we didn't find any resource.
1141 1141
 				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1142 1142
 				throw $e;
@@ -1161,13 +1161,13 @@  discard block
 block discarded – undo
1161 1161
 	 * @throws ServerNotAvailableException
1162 1162
 	 */
1163 1163
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1164
-		if(!is_null($attr) && !is_array($attr)) {
1164
+		if (!is_null($attr) && !is_array($attr)) {
1165 1165
 			$attr = [mb_strtolower($attr, 'UTF-8')];
1166 1166
 		}
1167 1167
 
1168 1168
 		// See if we have a resource, in case not cancel with message
1169 1169
 		$cr = $this->connection->getConnectionResource();
1170
-		if(!$this->ldap->isResource($cr)) {
1170
+		if (!$this->ldap->isResource($cr)) {
1171 1171
 			// Seems like we didn't find any resource.
1172 1172
 			// Return an empty array just like before.
1173 1173
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
@@ -1175,13 +1175,13 @@  discard block
 block discarded – undo
1175 1175
 		}
1176 1176
 
1177 1177
 		//check whether paged search should be attempted
1178
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1178
+		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int) $limit, $offset);
1179 1179
 
1180 1180
 		$linkResources = array_pad([], count($base), $cr);
1181 1181
 		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1182 1182
 		// cannot use $cr anymore, might have changed in the previous call!
1183 1183
 		$error = $this->ldap->errno($this->connection->getConnectionResource());
1184
-		if(!is_array($sr) || $error !== 0) {
1184
+		if (!is_array($sr) || $error !== 0) {
1185 1185
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1186 1186
 			return false;
1187 1187
 		}
@@ -1206,29 +1206,29 @@  discard block
 block discarded – undo
1206 1206
 	 */
1207 1207
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1208 1208
 		$cookie = null;
1209
-		if($pagedSearchOK) {
1209
+		if ($pagedSearchOK) {
1210 1210
 			$cr = $this->connection->getConnectionResource();
1211
-			foreach($sr as $key => $res) {
1212
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1211
+			foreach ($sr as $key => $res) {
1212
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1213 1213
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1214 1214
 				}
1215 1215
 			}
1216 1216
 
1217 1217
 			//browsing through prior pages to get the cookie for the new one
1218
-			if($skipHandling) {
1218
+			if ($skipHandling) {
1219 1219
 				return false;
1220 1220
 			}
1221 1221
 			// if count is bigger, then the server does not support
1222 1222
 			// paged search. Instead, he did a normal search. We set a
1223 1223
 			// flag here, so the callee knows how to deal with it.
1224
-			if($iFoundItems <= $limit) {
1224
+			if ($iFoundItems <= $limit) {
1225 1225
 				$this->pagedSearchedSuccessful = true;
1226 1226
 			}
1227 1227
 		} else {
1228
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1228
+			if (!is_null($limit) && (int) $this->connection->ldapPagingSize !== 0) {
1229 1229
 				\OC::$server->getLogger()->debug(
1230 1230
 					'Paged search was not available',
1231
-					[ 'app' => 'user_ldap' ]
1231
+					['app' => 'user_ldap']
1232 1232
 				);
1233 1233
 			}
1234 1234
 		}
@@ -1257,8 +1257,8 @@  discard block
 block discarded – undo
1257 1257
 	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1258 1258
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1259 1259
 
1260
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1261
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1260
+		$limitPerPage = (int) $this->connection->ldapPagingSize;
1261
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1262 1262
 			$limitPerPage = $limit;
1263 1263
 		}
1264 1264
 
@@ -1268,7 +1268,7 @@  discard block
 block discarded – undo
1268 1268
 
1269 1269
 		do {
1270 1270
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1271
-			if($search === false) {
1271
+			if ($search === false) {
1272 1272
 				return $counter > 0 ? $counter : false;
1273 1273
 			}
1274 1274
 			list($sr, $pagedSearchOK) = $search;
@@ -1287,7 +1287,7 @@  discard block
 block discarded – undo
1287 1287
 			 * Continue now depends on $hasMorePages value
1288 1288
 			 */
1289 1289
 			$continue = $pagedSearchOK && $hasMorePages;
1290
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1290
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1291 1291
 
1292 1292
 		return $counter;
1293 1293
 	}
@@ -1300,8 +1300,8 @@  discard block
 block discarded – undo
1300 1300
 	private function countEntriesInSearchResults($searchResults) {
1301 1301
 		$counter = 0;
1302 1302
 
1303
-		foreach($searchResults as $res) {
1304
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1303
+		foreach ($searchResults as $res) {
1304
+			$count = (int) $this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1305 1305
 			$counter += $count;
1306 1306
 		}
1307 1307
 
@@ -1321,8 +1321,8 @@  discard block
 block discarded – undo
1321 1321
 	 * @throws ServerNotAvailableException
1322 1322
 	 */
1323 1323
 	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1324
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1325
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1324
+		$limitPerPage = (int) $this->connection->ldapPagingSize;
1325
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1326 1326
 			$limitPerPage = $limit;
1327 1327
 		}
1328 1328
 
@@ -1336,13 +1336,13 @@  discard block
 block discarded – undo
1336 1336
 		$savedoffset = $offset;
1337 1337
 		do {
1338 1338
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1339
-			if($search === false) {
1339
+			if ($search === false) {
1340 1340
 				return [];
1341 1341
 			}
1342 1342
 			list($sr, $pagedSearchOK) = $search;
1343 1343
 			$cr = $this->connection->getConnectionResource();
1344 1344
 
1345
-			if($skipHandling) {
1345
+			if ($skipHandling) {
1346 1346
 				//i.e. result do not need to be fetched, we just need the cookie
1347 1347
 				//thus pass 1 or any other value as $iFoundItems because it is not
1348 1348
 				//used
@@ -1353,7 +1353,7 @@  discard block
 block discarded – undo
1353 1353
 			}
1354 1354
 
1355 1355
 			$iFoundItems = 0;
1356
-			foreach($sr as $res) {
1356
+			foreach ($sr as $res) {
1357 1357
 				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1358 1358
 				$iFoundItems = max($iFoundItems, $findings['count']);
1359 1359
 				unset($findings['count']);
@@ -1369,27 +1369,27 @@  discard block
 block discarded – undo
1369 1369
 
1370 1370
 		// if we're here, probably no connection resource is returned.
1371 1371
 		// to make Nextcloud behave nicely, we simply give back an empty array.
1372
-		if(is_null($findings)) {
1372
+		if (is_null($findings)) {
1373 1373
 			return [];
1374 1374
 		}
1375 1375
 
1376
-		if(!is_null($attr)) {
1376
+		if (!is_null($attr)) {
1377 1377
 			$selection = [];
1378 1378
 			$i = 0;
1379
-			foreach($findings as $item) {
1380
-				if(!is_array($item)) {
1379
+			foreach ($findings as $item) {
1380
+				if (!is_array($item)) {
1381 1381
 					continue;
1382 1382
 				}
1383 1383
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1384
-				foreach($attr as $key) {
1385
-					if(isset($item[$key])) {
1386
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1384
+				foreach ($attr as $key) {
1385
+					if (isset($item[$key])) {
1386
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1387 1387
 							unset($item[$key]['count']);
1388 1388
 						}
1389
-						if($key !== 'dn') {
1390
-							if($this->resemblesDN($key)) {
1389
+						if ($key !== 'dn') {
1390
+							if ($this->resemblesDN($key)) {
1391 1391
 								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1392
-							} else if($key === 'objectguid' || $key === 'guid') {
1392
+							} else if ($key === 'objectguid' || $key === 'guid') {
1393 1393
 								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1394 1394
 							} else {
1395 1395
 								$selection[$i][$key] = $item[$key];
@@ -1407,14 +1407,14 @@  discard block
 block discarded – undo
1407 1407
 		//we slice the findings, when
1408 1408
 		//a) paged search unsuccessful, though attempted
1409 1409
 		//b) no paged search, but limit set
1410
-		if((!$this->getPagedSearchResultState()
1410
+		if ((!$this->getPagedSearchResultState()
1411 1411
 			&& $pagedSearchOK)
1412 1412
 			|| (
1413 1413
 				!$pagedSearchOK
1414 1414
 				&& !is_null($limit)
1415 1415
 			)
1416 1416
 		) {
1417
-			$findings = array_slice($findings, (int)$offset, $limit);
1417
+			$findings = array_slice($findings, (int) $offset, $limit);
1418 1418
 		}
1419 1419
 		return $findings;
1420 1420
 	}
@@ -1427,13 +1427,13 @@  discard block
 block discarded – undo
1427 1427
 	public function sanitizeUsername($name) {
1428 1428
 		$name = trim($name);
1429 1429
 
1430
-		if($this->connection->ldapIgnoreNamingRules) {
1430
+		if ($this->connection->ldapIgnoreNamingRules) {
1431 1431
 			return $name;
1432 1432
 		}
1433 1433
 
1434 1434
 		// Transliteration to ASCII
1435 1435
 		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1436
-		if($transliterated !== false) {
1436
+		if ($transliterated !== false) {
1437 1437
 			// depending on system config iconv can work or not
1438 1438
 			$name = $transliterated;
1439 1439
 		}
@@ -1444,7 +1444,7 @@  discard block
 block discarded – undo
1444 1444
 		// Every remaining disallowed characters will be removed
1445 1445
 		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1446 1446
 
1447
-		if($name === '') {
1447
+		if ($name === '') {
1448 1448
 			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1449 1449
 		}
1450 1450
 
@@ -1459,13 +1459,13 @@  discard block
 block discarded – undo
1459 1459
 	*/
1460 1460
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1461 1461
 		$asterisk = '';
1462
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1462
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1463 1463
 			$asterisk = '*';
1464 1464
 			$input = mb_substr($input, 1, null, 'UTF-8');
1465 1465
 		}
1466 1466
 		$search  = ['*', '\\', '(', ')'];
1467 1467
 		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1468
-		return $asterisk . str_replace($search, $replace, $input);
1468
+		return $asterisk.str_replace($search, $replace, $input);
1469 1469
 	}
1470 1470
 
1471 1471
 	/**
@@ -1495,13 +1495,13 @@  discard block
 block discarded – undo
1495 1495
 	 */
1496 1496
 	private function combineFilter($filters, $operator) {
1497 1497
 		$combinedFilter = '('.$operator;
1498
-		foreach($filters as $filter) {
1498
+		foreach ($filters as $filter) {
1499 1499
 			if ($filter !== '' && $filter[0] !== '(') {
1500 1500
 				$filter = '('.$filter.')';
1501 1501
 			}
1502
-			$combinedFilter.=$filter;
1502
+			$combinedFilter .= $filter;
1503 1503
 		}
1504
-		$combinedFilter.=')';
1504
+		$combinedFilter .= ')';
1505 1505
 		return $combinedFilter;
1506 1506
 	}
1507 1507
 
@@ -1537,17 +1537,17 @@  discard block
 block discarded – undo
1537 1537
 	 * @throws \Exception
1538 1538
 	 */
1539 1539
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1540
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1540
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1541 1541
 			throw new \Exception('searchAttributes must be an array with at least two string');
1542 1542
 		}
1543 1543
 		$searchWords = explode(' ', trim($search));
1544 1544
 		$wordFilters = [];
1545
-		foreach($searchWords as $word) {
1545
+		foreach ($searchWords as $word) {
1546 1546
 			$word = $this->prepareSearchTerm($word);
1547 1547
 			//every word needs to appear at least once
1548 1548
 			$wordMatchOneAttrFilters = [];
1549
-			foreach($searchAttributes as $attr) {
1550
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1549
+			foreach ($searchAttributes as $attr) {
1550
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1551 1551
 			}
1552 1552
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1553 1553
 		}
@@ -1565,10 +1565,10 @@  discard block
 block discarded – undo
1565 1565
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1566 1566
 		$filter = [];
1567 1567
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1568
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1568
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1569 1569
 			try {
1570 1570
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1571
-			} catch(\Exception $e) {
1571
+			} catch (\Exception $e) {
1572 1572
 				\OCP\Util::writeLog(
1573 1573
 					'user_ldap',
1574 1574
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1578,17 +1578,17 @@  discard block
 block discarded – undo
1578 1578
 		}
1579 1579
 
1580 1580
 		$search = $this->prepareSearchTerm($search);
1581
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1581
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1582 1582
 			if ($fallbackAttribute === '') {
1583 1583
 				return '';
1584 1584
 			}
1585
-			$filter[] = $fallbackAttribute . '=' . $search;
1585
+			$filter[] = $fallbackAttribute.'='.$search;
1586 1586
 		} else {
1587
-			foreach($searchAttributes as $attribute) {
1588
-				$filter[] = $attribute . '=' . $search;
1587
+			foreach ($searchAttributes as $attribute) {
1588
+				$filter[] = $attribute.'='.$search;
1589 1589
 			}
1590 1590
 		}
1591
-		if(count($filter) === 1) {
1591
+		if (count($filter) === 1) {
1592 1592
 			return '('.$filter[0].')';
1593 1593
 		}
1594 1594
 		return $this->combineFilterWithOr($filter);
@@ -1609,7 +1609,7 @@  discard block
 block discarded – undo
1609 1609
 		if ($term === '') {
1610 1610
 			$result = '*';
1611 1611
 		} else if ($allowEnum !== 'no') {
1612
-			$result = $term . '*';
1612
+			$result = $term.'*';
1613 1613
 		}
1614 1614
 		return $result;
1615 1615
 	}
@@ -1621,7 +1621,7 @@  discard block
 block discarded – undo
1621 1621
 	public function getFilterForUserCount() {
1622 1622
 		$filter = $this->combineFilterWithAnd([
1623 1623
 			$this->connection->ldapUserFilter,
1624
-			$this->connection->ldapUserDisplayName . '=*'
1624
+			$this->connection->ldapUserDisplayName.'=*'
1625 1625
 		]);
1626 1626
 
1627 1627
 		return $filter;
@@ -1639,7 +1639,7 @@  discard block
 block discarded – undo
1639 1639
 			'ldapAgentName' => $name,
1640 1640
 			'ldapAgentPassword' => $password
1641 1641
 		];
1642
-		if(!$testConnection->setConfiguration($credentials)) {
1642
+		if (!$testConnection->setConfiguration($credentials)) {
1643 1643
 			return false;
1644 1644
 		}
1645 1645
 		return $testConnection->bind();
@@ -1661,30 +1661,30 @@  discard block
 block discarded – undo
1661 1661
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1662 1662
 			// existing DN to be able to reliably detect it.
1663 1663
 			$result = $this->search($filter, $base, ['dn'], 1);
1664
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1664
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1665 1665
 				throw new \Exception('Cannot determine UUID attribute');
1666 1666
 			}
1667 1667
 			$dn = $result[0]['dn'][0];
1668
-			if(!$this->detectUuidAttribute($dn, true)) {
1668
+			if (!$this->detectUuidAttribute($dn, true)) {
1669 1669
 				throw new \Exception('Cannot determine UUID attribute');
1670 1670
 			}
1671 1671
 		} else {
1672 1672
 			// The UUID attribute is either known or an override is given.
1673 1673
 			// By calling this method we ensure that $this->connection->$uuidAttr
1674 1674
 			// is definitely set
1675
-			if(!$this->detectUuidAttribute('', true)) {
1675
+			if (!$this->detectUuidAttribute('', true)) {
1676 1676
 				throw new \Exception('Cannot determine UUID attribute');
1677 1677
 			}
1678 1678
 		}
1679 1679
 
1680 1680
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1681
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1681
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1682 1682
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1683 1683
 		}
1684 1684
 
1685
-		$filter = $uuidAttr . '=' . $uuid;
1685
+		$filter = $uuidAttr.'='.$uuid;
1686 1686
 		$result = $this->searchUsers($filter, ['dn'], 2);
1687
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1687
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1688 1688
 			// we put the count into account to make sure that this is
1689 1689
 			// really unique
1690 1690
 			return $result[0]['dn'][0];
@@ -1704,7 +1704,7 @@  discard block
 block discarded – undo
1704 1704
 	 * @throws ServerNotAvailableException
1705 1705
 	 */
1706 1706
 	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1707
-		if($isUser) {
1707
+		if ($isUser) {
1708 1708
 			$uuidAttr     = 'ldapUuidUserAttribute';
1709 1709
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1710 1710
 		} else {
@@ -1712,8 +1712,8 @@  discard block
 block discarded – undo
1712 1712
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1713 1713
 		}
1714 1714
 
1715
-		if(!$force) {
1716
-			if($this->connection->$uuidAttr !== 'auto') {
1715
+		if (!$force) {
1716
+			if ($this->connection->$uuidAttr !== 'auto') {
1717 1717
 				return true;
1718 1718
 			} else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1719 1719
 				$this->connection->$uuidAttr = $uuidOverride;
@@ -1721,23 +1721,23 @@  discard block
 block discarded – undo
1721 1721
 			}
1722 1722
 
1723 1723
 			$attribute = $this->connection->getFromCache($uuidAttr);
1724
-			if(!$attribute === null) {
1724
+			if (!$attribute === null) {
1725 1725
 				$this->connection->$uuidAttr = $attribute;
1726 1726
 				return true;
1727 1727
 			}
1728 1728
 		}
1729 1729
 
1730
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1731
-			if($ldapRecord !== null) {
1730
+		foreach (self::UUID_ATTRIBUTES as $attribute) {
1731
+			if ($ldapRecord !== null) {
1732 1732
 				// we have the info from LDAP already, we don't need to talk to the server again
1733
-				if(isset($ldapRecord[$attribute])) {
1733
+				if (isset($ldapRecord[$attribute])) {
1734 1734
 					$this->connection->$uuidAttr = $attribute;
1735 1735
 					return true;
1736 1736
 				}
1737 1737
 			}
1738 1738
 
1739 1739
 			$value = $this->readAttribute($dn, $attribute);
1740
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1740
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1741 1741
 				\OC::$server->getLogger()->debug(
1742 1742
 					'Setting {attribute} as {subject}',
1743 1743
 					[
@@ -1764,7 +1764,7 @@  discard block
 block discarded – undo
1764 1764
 	 * @throws ServerNotAvailableException
1765 1765
 	 */
1766 1766
 	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1767
-		if($isUser) {
1767
+		if ($isUser) {
1768 1768
 			$uuidAttr     = 'ldapUuidUserAttribute';
1769 1769
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1770 1770
 		} else {
@@ -1773,10 +1773,10 @@  discard block
 block discarded – undo
1773 1773
 		}
1774 1774
 
1775 1775
 		$uuid = false;
1776
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1776
+		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1777 1777
 			$attr = $this->connection->$uuidAttr;
1778 1778
 			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1779
-			if( !is_array($uuid)
1779
+			if (!is_array($uuid)
1780 1780
 				&& $uuidOverride !== ''
1781 1781
 				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1782 1782
 			{
@@ -1784,7 +1784,7 @@  discard block
 block discarded – undo
1784 1784
 					? $ldapRecord[$this->connection->$uuidAttr]
1785 1785
 					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1786 1786
 			}
1787
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1787
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1788 1788
 				$uuid = $uuid[0];
1789 1789
 			}
1790 1790
 		}
@@ -1801,19 +1801,19 @@  discard block
 block discarded – undo
1801 1801
 	private function convertObjectGUID2Str($oguid) {
1802 1802
 		$hex_guid = bin2hex($oguid);
1803 1803
 		$hex_guid_to_guid_str = '';
1804
-		for($k = 1; $k <= 4; ++$k) {
1804
+		for ($k = 1; $k <= 4; ++$k) {
1805 1805
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1806 1806
 		}
1807 1807
 		$hex_guid_to_guid_str .= '-';
1808
-		for($k = 1; $k <= 2; ++$k) {
1808
+		for ($k = 1; $k <= 2; ++$k) {
1809 1809
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1810 1810
 		}
1811 1811
 		$hex_guid_to_guid_str .= '-';
1812
-		for($k = 1; $k <= 2; ++$k) {
1812
+		for ($k = 1; $k <= 2; ++$k) {
1813 1813
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1814 1814
 		}
1815
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1816
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1815
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1816
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1817 1817
 
1818 1818
 		return strtoupper($hex_guid_to_guid_str);
1819 1819
 	}
@@ -1830,11 +1830,11 @@  discard block
 block discarded – undo
1830 1830
 	 * @return string
1831 1831
 	 */
1832 1832
 	public function formatGuid2ForFilterUser($guid) {
1833
-		if(!is_string($guid)) {
1833
+		if (!is_string($guid)) {
1834 1834
 			throw new \InvalidArgumentException('String expected');
1835 1835
 		}
1836 1836
 		$blocks = explode('-', $guid);
1837
-		if(count($blocks) !== 5) {
1837
+		if (count($blocks) !== 5) {
1838 1838
 			/*
1839 1839
 			 * Why not throw an Exception instead? This method is a utility
1840 1840
 			 * called only when trying to figure out whether a "missing" known
@@ -1847,20 +1847,20 @@  discard block
 block discarded – undo
1847 1847
 			 * user. Instead we write a log message.
1848 1848
 			 */
1849 1849
 			\OC::$server->getLogger()->info(
1850
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1850
+				'Passed string does not resemble a valid GUID. Known UUID '.
1851 1851
 				'({uuid}) probably does not match UUID configuration.',
1852
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1852
+				['app' => 'user_ldap', 'uuid' => $guid]
1853 1853
 			);
1854 1854
 			return $guid;
1855 1855
 		}
1856
-		for($i=0; $i < 3; $i++) {
1856
+		for ($i = 0; $i < 3; $i++) {
1857 1857
 			$pairs = str_split($blocks[$i], 2);
1858 1858
 			$pairs = array_reverse($pairs);
1859 1859
 			$blocks[$i] = implode('', $pairs);
1860 1860
 		}
1861
-		for($i=0; $i < 5; $i++) {
1861
+		for ($i = 0; $i < 5; $i++) {
1862 1862
 			$pairs = str_split($blocks[$i], 2);
1863
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1863
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1864 1864
 		}
1865 1865
 		return implode('', $blocks);
1866 1866
 	}
@@ -1876,12 +1876,12 @@  discard block
 block discarded – undo
1876 1876
 		$domainDN = $this->getDomainDNFromDN($dn);
1877 1877
 		$cacheKey = 'getSID-'.$domainDN;
1878 1878
 		$sid = $this->connection->getFromCache($cacheKey);
1879
-		if(!is_null($sid)) {
1879
+		if (!is_null($sid)) {
1880 1880
 			return $sid;
1881 1881
 		}
1882 1882
 
1883 1883
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1884
-		if(!is_array($objectSid) || empty($objectSid)) {
1884
+		if (!is_array($objectSid) || empty($objectSid)) {
1885 1885
 			$this->connection->writeToCache($cacheKey, false);
1886 1886
 			return false;
1887 1887
 		}
@@ -1939,12 +1939,12 @@  discard block
 block discarded – undo
1939 1939
 		$belongsToBase = false;
1940 1940
 		$bases = $this->helper->sanitizeDN($bases);
1941 1941
 
1942
-		foreach($bases as $base) {
1942
+		foreach ($bases as $base) {
1943 1943
 			$belongsToBase = true;
1944
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1944
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1945 1945
 				$belongsToBase = false;
1946 1946
 			}
1947
-			if($belongsToBase) {
1947
+			if ($belongsToBase) {
1948 1948
 				break;
1949 1949
 			}
1950 1950
 		}
@@ -1973,16 +1973,16 @@  discard block
 block discarded – undo
1973 1973
 	 * @return string containing the key or empty if none is cached
1974 1974
 	 */
1975 1975
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1976
-		if($offset === 0) {
1976
+		if ($offset === 0) {
1977 1977
 			return '';
1978 1978
 		}
1979 1979
 		$offset -= $limit;
1980 1980
 		//we work with cache here
1981
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1981
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset;
1982 1982
 		$cookie = '';
1983
-		if(isset($this->cookies[$cacheKey])) {
1983
+		if (isset($this->cookies[$cacheKey])) {
1984 1984
 			$cookie = $this->cookies[$cacheKey];
1985
-			if(is_null($cookie)) {
1985
+			if (is_null($cookie)) {
1986 1986
 				$cookie = '';
1987 1987
 			}
1988 1988
 		}
@@ -2000,7 +2000,7 @@  discard block
 block discarded – undo
2000 2000
 	 * @return bool
2001 2001
 	 */
2002 2002
 	public function hasMoreResults() {
2003
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2003
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
2004 2004
 			// as in RFC 2696, when all results are returned, the cookie will
2005 2005
 			// be empty.
2006 2006
 			return false;
@@ -2020,8 +2020,8 @@  discard block
 block discarded – undo
2020 2020
 	 */
2021 2021
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2022 2022
 		// allow '0' for 389ds
2023
-		if(!empty($cookie) || $cookie === '0') {
2024
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2023
+		if (!empty($cookie) || $cookie === '0') {
2024
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.(int) $limit.'-'.(int) $offset;
2025 2025
 			$this->cookies[$cacheKey] = $cookie;
2026 2026
 			$this->lastCookie = $cookie;
2027 2027
 		}
@@ -2051,16 +2051,16 @@  discard block
 block discarded – undo
2051 2051
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2052 2052
 		$pagedSearchOK = false;
2053 2053
 		if ($limit !== 0) {
2054
-			$offset = (int)$offset; //can be null
2054
+			$offset = (int) $offset; //can be null
2055 2055
 			\OCP\Util::writeLog('user_ldap',
2056 2056
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2057
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2057
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
2058 2058
 				ILogger::DEBUG);
2059 2059
 			//get the cookie from the search for the previous search, required by LDAP
2060
-			foreach($bases as $base) {
2060
+			foreach ($bases as $base) {
2061 2061
 
2062 2062
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2063
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2063
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2064 2064
 					// no cookie known from a potential previous search. We need
2065 2065
 					// to start from 0 to come to the desired page. cookie value
2066 2066
 					// of '0' is valid, because 389ds
@@ -2070,17 +2070,17 @@  discard block
 block discarded – undo
2070 2070
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2071 2071
 					// '0' is valid, because 389ds
2072 2072
 					//TODO: remember this, probably does not change in the next request...
2073
-					if(empty($cookie) && $cookie !== '0') {
2073
+					if (empty($cookie) && $cookie !== '0') {
2074 2074
 						$cookie = null;
2075 2075
 					}
2076 2076
 				}
2077
-				if(!is_null($cookie)) {
2077
+				if (!is_null($cookie)) {
2078 2078
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2079 2079
 					$this->abandonPagedSearch();
2080 2080
 					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2081 2081
 						$this->connection->getConnectionResource(), $limit,
2082 2082
 						false, $cookie);
2083
-					if(!$pagedSearchOK) {
2083
+					if (!$pagedSearchOK) {
2084 2084
 						return false;
2085 2085
 					}
2086 2086
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
@@ -2103,7 +2103,7 @@  discard block
 block discarded – undo
2103 2103
 			$this->abandonPagedSearch();
2104 2104
 			// in case someone set it to 0 … use 500, otherwise no results will
2105 2105
 			// be returned.
2106
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2106
+			$pageSize = (int) $this->connection->ldapPagingSize > 0 ? (int) $this->connection->ldapPagingSize : 500;
2107 2107
 			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2108 2108
 				$this->connection->getConnectionResource(),
2109 2109
 				$pageSize, false, '');
Please login to merge, or discard this patch.
apps/user_ldap/lib/UserPluginManager.php 1 patch
Indentation   +179 added lines, -179 removed lines patch added patch discarded remove patch
@@ -28,183 +28,183 @@
 block discarded – undo
28 28
 
29 29
 class UserPluginManager {
30 30
 
31
-	public $test = false;
32
-
33
-	private $respondToActions = 0;
34
-
35
-	private $which = [
36
-		Backend::CREATE_USER => null,
37
-		Backend::SET_PASSWORD => null,
38
-		Backend::GET_HOME => null,
39
-		Backend::GET_DISPLAYNAME => null,
40
-		Backend::SET_DISPLAYNAME => null,
41
-		Backend::PROVIDE_AVATAR => null,
42
-		Backend::COUNT_USERS => null,
43
-		'deleteUser' => null
44
-	];
45
-
46
-	/**
47
-	 * @return int All implemented actions, except for 'deleteUser'
48
-	 */
49
-	public function getImplementedActions() {
50
-		return $this->respondToActions;
51
-	}
52
-
53
-	/**
54
-	 * Registers a user plugin that may implement some actions, overriding User_LDAP's user actions.
55
-	 *
56
-	 * @param ILDAPUserPlugin $plugin
57
-	 */
58
-	public function register(ILDAPUserPlugin $plugin) {
59
-		$respondToActions = $plugin->respondToActions();
60
-		$this->respondToActions |= $respondToActions;
61
-
62
-		foreach($this->which as $action => $v) {
63
-			if (is_int($action) && (bool)($respondToActions & $action)) {
64
-				$this->which[$action] = $plugin;
65
-				\OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']);
66
-			}
67
-		}
68
-		if (method_exists($plugin,'deleteUser')) {
69
-			$this->which['deleteUser'] = $plugin;
70
-			\OC::$server->getLogger()->debug("Registered action deleteUser to plugin ".get_class($plugin), ['app' => 'user_ldap']);
71
-		}
72
-	}
73
-
74
-	/**
75
-	 * Signal if there is a registered plugin that implements some given actions
76
-	 * @param int $actions Actions defined in \OC\User\Backend, like Backend::CREATE_USER
77
-	 * @return bool
78
-	 */
79
-	public function implementsActions($actions) {
80
-		return ($actions & $this->respondToActions) == $actions;
81
-	}
82
-
83
-	/**
84
-	 * Create a new user in LDAP Backend
85
-	 *
86
-	 * @param string $username The username of the user to create
87
-	 * @param string $password The password of the new user
88
-	 * @return string | false The user DN if user creation was successful.
89
-	 * @throws \Exception
90
-	 */
91
-	public function createUser($username, $password) {
92
-		$plugin = $this->which[Backend::CREATE_USER];
93
-
94
-		if ($plugin) {
95
-			return $plugin->createUser($username,$password);
96
-		}
97
-		throw new \Exception('No plugin implements createUser in this LDAP Backend.');
98
-	}
99
-
100
-	/**
101
-	 * Change the password of a user*
102
-	 * @param string $uid The username
103
-	 * @param string $password The new password
104
-	 * @return bool
105
-	 * @throws \Exception
106
-	 */
107
-	public function setPassword($uid, $password) {
108
-		$plugin = $this->which[Backend::SET_PASSWORD];
109
-
110
-		if ($plugin) {
111
-			return $plugin->setPassword($uid,$password);
112
-		}
113
-		throw new \Exception('No plugin implements setPassword in this LDAP Backend.');
114
-	}
115
-
116
-	/**
117
-	 * checks whether the user is allowed to change his avatar in Nextcloud
118
-	 * @param string $uid the Nextcloud user name
119
-	 * @return boolean either the user can or cannot
120
-	 * @throws \Exception
121
-	 */
122
-	public function canChangeAvatar($uid) {
123
-		$plugin = $this->which[Backend::PROVIDE_AVATAR];
124
-
125
-		if ($plugin) {
126
-			return $plugin->canChangeAvatar($uid);
127
-		}
128
-		throw new \Exception('No plugin implements canChangeAvatar in this LDAP Backend.');
129
-	}
130
-
131
-	/**
132
-	 * Get the user's home directory
133
-	 * @param string $uid the username
134
-	 * @return boolean
135
-	 * @throws \Exception
136
-	 */
137
-	public function getHome($uid) {
138
-		$plugin = $this->which[Backend::GET_HOME];
139
-
140
-		if ($plugin) {
141
-			return $plugin->getHome($uid);
142
-		}
143
-		throw new \Exception('No plugin implements getHome in this LDAP Backend.');
144
-	}
145
-
146
-	/**
147
-	 * Get display name of the user
148
-	 * @param string $uid user ID of the user
149
-	 * @return string display name
150
-	 * @throws \Exception
151
-	 */
152
-	public function getDisplayName($uid) {
153
-		$plugin = $this->which[Backend::GET_DISPLAYNAME];
154
-
155
-		if ($plugin) {
156
-			return $plugin->getDisplayName($uid);
157
-		}
158
-		throw new \Exception('No plugin implements getDisplayName in this LDAP Backend.');
159
-	}
160
-
161
-	/**
162
-	 * Set display name of the user
163
-	 * @param string $uid user ID of the user
164
-	 * @param string $displayName new user's display name
165
-	 * @return string display name
166
-	 * @throws \Exception
167
-	 */
168
-	public function setDisplayName($uid, $displayName) {
169
-		$plugin = $this->which[Backend::SET_DISPLAYNAME];
170
-
171
-		if ($plugin) {
172
-			return $plugin->setDisplayName($uid, $displayName);
173
-		}
174
-		throw new \Exception('No plugin implements setDisplayName in this LDAP Backend.');
175
-	}
176
-
177
-	/**
178
-	 * Count the number of users
179
-	 * @return int|bool
180
-	 * @throws \Exception
181
-	 */
182
-	public function countUsers() {
183
-		$plugin = $this->which[Backend::COUNT_USERS];
184
-
185
-		if ($plugin) {
186
-			return $plugin->countUsers();
187
-		}
188
-		throw new \Exception('No plugin implements countUsers in this LDAP Backend.');
189
-	}
190
-
191
-	/**
192
-	 * @return bool
193
-	 */
194
-	public function canDeleteUser() {
195
-		return $this->which['deleteUser'] !== null;
196
-	}
197
-
198
-	/**
199
-	 * @param $uid
200
-	 * @return bool
201
-	 * @throws \Exception
202
-	 */
203
-	public function deleteUser($uid) {
204
-		$plugin = $this->which['deleteUser'];
205
-		if ($plugin) {
206
-			return $plugin->deleteUser($uid);
207
-		}
208
-		throw new \Exception('No plugin implements deleteUser in this LDAP Backend.');
209
-	}
31
+    public $test = false;
32
+
33
+    private $respondToActions = 0;
34
+
35
+    private $which = [
36
+        Backend::CREATE_USER => null,
37
+        Backend::SET_PASSWORD => null,
38
+        Backend::GET_HOME => null,
39
+        Backend::GET_DISPLAYNAME => null,
40
+        Backend::SET_DISPLAYNAME => null,
41
+        Backend::PROVIDE_AVATAR => null,
42
+        Backend::COUNT_USERS => null,
43
+        'deleteUser' => null
44
+    ];
45
+
46
+    /**
47
+     * @return int All implemented actions, except for 'deleteUser'
48
+     */
49
+    public function getImplementedActions() {
50
+        return $this->respondToActions;
51
+    }
52
+
53
+    /**
54
+     * Registers a user plugin that may implement some actions, overriding User_LDAP's user actions.
55
+     *
56
+     * @param ILDAPUserPlugin $plugin
57
+     */
58
+    public function register(ILDAPUserPlugin $plugin) {
59
+        $respondToActions = $plugin->respondToActions();
60
+        $this->respondToActions |= $respondToActions;
61
+
62
+        foreach($this->which as $action => $v) {
63
+            if (is_int($action) && (bool)($respondToActions & $action)) {
64
+                $this->which[$action] = $plugin;
65
+                \OC::$server->getLogger()->debug("Registered action ".$action." to plugin ".get_class($plugin), ['app' => 'user_ldap']);
66
+            }
67
+        }
68
+        if (method_exists($plugin,'deleteUser')) {
69
+            $this->which['deleteUser'] = $plugin;
70
+            \OC::$server->getLogger()->debug("Registered action deleteUser to plugin ".get_class($plugin), ['app' => 'user_ldap']);
71
+        }
72
+    }
73
+
74
+    /**
75
+     * Signal if there is a registered plugin that implements some given actions
76
+     * @param int $actions Actions defined in \OC\User\Backend, like Backend::CREATE_USER
77
+     * @return bool
78
+     */
79
+    public function implementsActions($actions) {
80
+        return ($actions & $this->respondToActions) == $actions;
81
+    }
82
+
83
+    /**
84
+     * Create a new user in LDAP Backend
85
+     *
86
+     * @param string $username The username of the user to create
87
+     * @param string $password The password of the new user
88
+     * @return string | false The user DN if user creation was successful.
89
+     * @throws \Exception
90
+     */
91
+    public function createUser($username, $password) {
92
+        $plugin = $this->which[Backend::CREATE_USER];
93
+
94
+        if ($plugin) {
95
+            return $plugin->createUser($username,$password);
96
+        }
97
+        throw new \Exception('No plugin implements createUser in this LDAP Backend.');
98
+    }
99
+
100
+    /**
101
+     * Change the password of a user*
102
+     * @param string $uid The username
103
+     * @param string $password The new password
104
+     * @return bool
105
+     * @throws \Exception
106
+     */
107
+    public function setPassword($uid, $password) {
108
+        $plugin = $this->which[Backend::SET_PASSWORD];
109
+
110
+        if ($plugin) {
111
+            return $plugin->setPassword($uid,$password);
112
+        }
113
+        throw new \Exception('No plugin implements setPassword in this LDAP Backend.');
114
+    }
115
+
116
+    /**
117
+     * checks whether the user is allowed to change his avatar in Nextcloud
118
+     * @param string $uid the Nextcloud user name
119
+     * @return boolean either the user can or cannot
120
+     * @throws \Exception
121
+     */
122
+    public function canChangeAvatar($uid) {
123
+        $plugin = $this->which[Backend::PROVIDE_AVATAR];
124
+
125
+        if ($plugin) {
126
+            return $plugin->canChangeAvatar($uid);
127
+        }
128
+        throw new \Exception('No plugin implements canChangeAvatar in this LDAP Backend.');
129
+    }
130
+
131
+    /**
132
+     * Get the user's home directory
133
+     * @param string $uid the username
134
+     * @return boolean
135
+     * @throws \Exception
136
+     */
137
+    public function getHome($uid) {
138
+        $plugin = $this->which[Backend::GET_HOME];
139
+
140
+        if ($plugin) {
141
+            return $plugin->getHome($uid);
142
+        }
143
+        throw new \Exception('No plugin implements getHome in this LDAP Backend.');
144
+    }
145
+
146
+    /**
147
+     * Get display name of the user
148
+     * @param string $uid user ID of the user
149
+     * @return string display name
150
+     * @throws \Exception
151
+     */
152
+    public function getDisplayName($uid) {
153
+        $plugin = $this->which[Backend::GET_DISPLAYNAME];
154
+
155
+        if ($plugin) {
156
+            return $plugin->getDisplayName($uid);
157
+        }
158
+        throw new \Exception('No plugin implements getDisplayName in this LDAP Backend.');
159
+    }
160
+
161
+    /**
162
+     * Set display name of the user
163
+     * @param string $uid user ID of the user
164
+     * @param string $displayName new user's display name
165
+     * @return string display name
166
+     * @throws \Exception
167
+     */
168
+    public function setDisplayName($uid, $displayName) {
169
+        $plugin = $this->which[Backend::SET_DISPLAYNAME];
170
+
171
+        if ($plugin) {
172
+            return $plugin->setDisplayName($uid, $displayName);
173
+        }
174
+        throw new \Exception('No plugin implements setDisplayName in this LDAP Backend.');
175
+    }
176
+
177
+    /**
178
+     * Count the number of users
179
+     * @return int|bool
180
+     * @throws \Exception
181
+     */
182
+    public function countUsers() {
183
+        $plugin = $this->which[Backend::COUNT_USERS];
184
+
185
+        if ($plugin) {
186
+            return $plugin->countUsers();
187
+        }
188
+        throw new \Exception('No plugin implements countUsers in this LDAP Backend.');
189
+    }
190
+
191
+    /**
192
+     * @return bool
193
+     */
194
+    public function canDeleteUser() {
195
+        return $this->which['deleteUser'] !== null;
196
+    }
197
+
198
+    /**
199
+     * @param $uid
200
+     * @return bool
201
+     * @throws \Exception
202
+     */
203
+    public function deleteUser($uid) {
204
+        $plugin = $this->which['deleteUser'];
205
+        if ($plugin) {
206
+            return $plugin->deleteUser($uid);
207
+        }
208
+        throw new \Exception('No plugin implements deleteUser in this LDAP Backend.');
209
+    }
210 210
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/WizardResult.php 2 patches
Indentation   +40 added lines, -40 removed lines patch added patch discarded remove patch
@@ -29,50 +29,50 @@
 block discarded – undo
29 29
 namespace OCA\User_LDAP;
30 30
 
31 31
 class WizardResult {
32
-	protected $changes = [];
33
-	protected $options = [];
34
-	protected $markedChange = false;
32
+    protected $changes = [];
33
+    protected $options = [];
34
+    protected $markedChange = false;
35 35
 
36
-	/**
37
-	 * @param string $key
38
-	 * @param mixed $value
39
-	 */
40
-	public function addChange($key, $value) {
41
-		$this->changes[$key] = $value;
42
-	}
36
+    /**
37
+     * @param string $key
38
+     * @param mixed $value
39
+     */
40
+    public function addChange($key, $value) {
41
+        $this->changes[$key] = $value;
42
+    }
43 43
 
44 44
 	
45
-	public function markChange() {
46
-		$this->markedChange = true;
47
-	}
45
+    public function markChange() {
46
+        $this->markedChange = true;
47
+    }
48 48
 
49
-	/**
50
-	 * @param string $key
51
-	 * @param array|string $values
52
-	 */
53
-	public function addOptions($key, $values) {
54
-		if(!is_array($values)) {
55
-			$values = [$values];
56
-		}
57
-		$this->options[$key] = $values;
58
-	}
49
+    /**
50
+     * @param string $key
51
+     * @param array|string $values
52
+     */
53
+    public function addOptions($key, $values) {
54
+        if(!is_array($values)) {
55
+            $values = [$values];
56
+        }
57
+        $this->options[$key] = $values;
58
+    }
59 59
 
60
-	/**
61
-	 * @return bool
62
-	 */
63
-	public function hasChanges() {
64
-		return (count($this->changes) > 0 || $this->markedChange);
65
-	}
60
+    /**
61
+     * @return bool
62
+     */
63
+    public function hasChanges() {
64
+        return (count($this->changes) > 0 || $this->markedChange);
65
+    }
66 66
 
67
-	/**
68
-	 * @return array
69
-	 */
70
-	public function getResultArray() {
71
-		$result = [];
72
-		$result['changes'] = $this->changes;
73
-		if(count($this->options) > 0) {
74
-			$result['options'] = $this->options;
75
-		}
76
-		return $result;
77
-	}
67
+    /**
68
+     * @return array
69
+     */
70
+    public function getResultArray() {
71
+        $result = [];
72
+        $result['changes'] = $this->changes;
73
+        if(count($this->options) > 0) {
74
+            $result['options'] = $this->options;
75
+        }
76
+        return $result;
77
+    }
78 78
 }
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -51,7 +51,7 @@  discard block
 block discarded – undo
51 51
 	 * @param array|string $values
52 52
 	 */
53 53
 	public function addOptions($key, $values) {
54
-		if(!is_array($values)) {
54
+		if (!is_array($values)) {
55 55
 			$values = [$values];
56 56
 		}
57 57
 		$this->options[$key] = $values;
@@ -70,7 +70,7 @@  discard block
 block discarded – undo
70 70
 	public function getResultArray() {
71 71
 		$result = [];
72 72
 		$result['changes'] = $this->changes;
73
-		if(count($this->options) > 0) {
73
+		if (count($this->options) > 0) {
74 74
 			$result['options'] = $this->options;
75 75
 		}
76 76
 		return $result;
Please login to merge, or discard this patch.
apps/user_ldap/lib/Configuration.php 2 patches
Indentation   +510 added lines, -510 removed lines patch added patch discarded remove patch
@@ -40,543 +40,543 @@
 block discarded – undo
40 40
  * @property string ldapUserAvatarRule
41 41
  */
42 42
 class Configuration {
43
-	const AVATAR_PREFIX_DEFAULT = 'default';
44
-	const AVATAR_PREFIX_NONE = 'none';
45
-	const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
43
+    const AVATAR_PREFIX_DEFAULT = 'default';
44
+    const AVATAR_PREFIX_NONE = 'none';
45
+    const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
46 46
 
47
-	protected $configPrefix = null;
48
-	protected $configRead = false;
49
-	/**
50
-	 * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
51
-	 *               the config ID is registered
52
-	 */
53
-	protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
47
+    protected $configPrefix = null;
48
+    protected $configRead = false;
49
+    /**
50
+     * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
51
+     *               the config ID is registered
52
+     */
53
+    protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
54 54
 
55
-	//settings
56
-	protected $config = [
57
-		'ldapHost' => null,
58
-		'ldapPort' => null,
59
-		'ldapBackupHost' => null,
60
-		'ldapBackupPort' => null,
61
-		'ldapBase' => null,
62
-		'ldapBaseUsers' => null,
63
-		'ldapBaseGroups' => null,
64
-		'ldapAgentName' => null,
65
-		'ldapAgentPassword' => null,
66
-		'ldapTLS' => null,
67
-		'turnOffCertCheck' => null,
68
-		'ldapIgnoreNamingRules' => null,
69
-		'ldapUserDisplayName' => null,
70
-		'ldapUserDisplayName2' => null,
71
-		'ldapUserAvatarRule' => null,
72
-		'ldapGidNumber' => null,
73
-		'ldapUserFilterObjectclass' => null,
74
-		'ldapUserFilterGroups' => null,
75
-		'ldapUserFilter' => null,
76
-		'ldapUserFilterMode' => null,
77
-		'ldapGroupFilter' => null,
78
-		'ldapGroupFilterMode' => null,
79
-		'ldapGroupFilterObjectclass' => null,
80
-		'ldapGroupFilterGroups' => null,
81
-		'ldapGroupDisplayName' => null,
82
-		'ldapGroupMemberAssocAttr' => null,
83
-		'ldapLoginFilter' => null,
84
-		'ldapLoginFilterMode' => null,
85
-		'ldapLoginFilterEmail' => null,
86
-		'ldapLoginFilterUsername' => null,
87
-		'ldapLoginFilterAttributes' => null,
88
-		'ldapQuotaAttribute' => null,
89
-		'ldapQuotaDefault' => null,
90
-		'ldapEmailAttribute' => null,
91
-		'ldapCacheTTL' => null,
92
-		'ldapUuidUserAttribute' => 'auto',
93
-		'ldapUuidGroupAttribute' => 'auto',
94
-		'ldapOverrideMainServer' => false,
95
-		'ldapConfigurationActive' => false,
96
-		'ldapAttributesForUserSearch' => null,
97
-		'ldapAttributesForGroupSearch' => null,
98
-		'ldapExperiencedAdmin' => false,
99
-		'homeFolderNamingRule' => null,
100
-		'hasMemberOfFilterSupport' => false,
101
-		'useMemberOfToDetectMembership' => true,
102
-		'ldapExpertUsernameAttr' => null,
103
-		'ldapExpertUUIDUserAttr' => null,
104
-		'ldapExpertUUIDGroupAttr' => null,
105
-		'lastJpegPhotoLookup' => null,
106
-		'ldapNestedGroups' => false,
107
-		'ldapPagingSize' => null,
108
-		'turnOnPasswordChange' => false,
109
-		'ldapDynamicGroupMemberURL' => null,
110
-		'ldapDefaultPPolicyDN' => null,
111
-		'ldapExtStorageHomeAttribute' => null,
112
-	];
55
+    //settings
56
+    protected $config = [
57
+        'ldapHost' => null,
58
+        'ldapPort' => null,
59
+        'ldapBackupHost' => null,
60
+        'ldapBackupPort' => null,
61
+        'ldapBase' => null,
62
+        'ldapBaseUsers' => null,
63
+        'ldapBaseGroups' => null,
64
+        'ldapAgentName' => null,
65
+        'ldapAgentPassword' => null,
66
+        'ldapTLS' => null,
67
+        'turnOffCertCheck' => null,
68
+        'ldapIgnoreNamingRules' => null,
69
+        'ldapUserDisplayName' => null,
70
+        'ldapUserDisplayName2' => null,
71
+        'ldapUserAvatarRule' => null,
72
+        'ldapGidNumber' => null,
73
+        'ldapUserFilterObjectclass' => null,
74
+        'ldapUserFilterGroups' => null,
75
+        'ldapUserFilter' => null,
76
+        'ldapUserFilterMode' => null,
77
+        'ldapGroupFilter' => null,
78
+        'ldapGroupFilterMode' => null,
79
+        'ldapGroupFilterObjectclass' => null,
80
+        'ldapGroupFilterGroups' => null,
81
+        'ldapGroupDisplayName' => null,
82
+        'ldapGroupMemberAssocAttr' => null,
83
+        'ldapLoginFilter' => null,
84
+        'ldapLoginFilterMode' => null,
85
+        'ldapLoginFilterEmail' => null,
86
+        'ldapLoginFilterUsername' => null,
87
+        'ldapLoginFilterAttributes' => null,
88
+        'ldapQuotaAttribute' => null,
89
+        'ldapQuotaDefault' => null,
90
+        'ldapEmailAttribute' => null,
91
+        'ldapCacheTTL' => null,
92
+        'ldapUuidUserAttribute' => 'auto',
93
+        'ldapUuidGroupAttribute' => 'auto',
94
+        'ldapOverrideMainServer' => false,
95
+        'ldapConfigurationActive' => false,
96
+        'ldapAttributesForUserSearch' => null,
97
+        'ldapAttributesForGroupSearch' => null,
98
+        'ldapExperiencedAdmin' => false,
99
+        'homeFolderNamingRule' => null,
100
+        'hasMemberOfFilterSupport' => false,
101
+        'useMemberOfToDetectMembership' => true,
102
+        'ldapExpertUsernameAttr' => null,
103
+        'ldapExpertUUIDUserAttr' => null,
104
+        'ldapExpertUUIDGroupAttr' => null,
105
+        'lastJpegPhotoLookup' => null,
106
+        'ldapNestedGroups' => false,
107
+        'ldapPagingSize' => null,
108
+        'turnOnPasswordChange' => false,
109
+        'ldapDynamicGroupMemberURL' => null,
110
+        'ldapDefaultPPolicyDN' => null,
111
+        'ldapExtStorageHomeAttribute' => null,
112
+    ];
113 113
 
114
-	/**
115
-	 * @param string $configPrefix
116
-	 * @param bool $autoRead
117
-	 */
118
-	public function __construct($configPrefix, $autoRead = true) {
119
-		$this->configPrefix = $configPrefix;
120
-		if($autoRead) {
121
-			$this->readConfiguration();
122
-		}
123
-	}
114
+    /**
115
+     * @param string $configPrefix
116
+     * @param bool $autoRead
117
+     */
118
+    public function __construct($configPrefix, $autoRead = true) {
119
+        $this->configPrefix = $configPrefix;
120
+        if($autoRead) {
121
+            $this->readConfiguration();
122
+        }
123
+    }
124 124
 
125
-	/**
126
-	 * @param string $name
127
-	 * @return mixed|null
128
-	 */
129
-	public function __get($name) {
130
-		if(isset($this->config[$name])) {
131
-			return $this->config[$name];
132
-		}
133
-		return null;
134
-	}
125
+    /**
126
+     * @param string $name
127
+     * @return mixed|null
128
+     */
129
+    public function __get($name) {
130
+        if(isset($this->config[$name])) {
131
+            return $this->config[$name];
132
+        }
133
+        return null;
134
+    }
135 135
 
136
-	/**
137
-	 * @param string $name
138
-	 * @param mixed $value
139
-	 */
140
-	public function __set($name, $value) {
141
-		$this->setConfiguration([$name => $value]);
142
-	}
136
+    /**
137
+     * @param string $name
138
+     * @param mixed $value
139
+     */
140
+    public function __set($name, $value) {
141
+        $this->setConfiguration([$name => $value]);
142
+    }
143 143
 
144
-	/**
145
-	 * @return array
146
-	 */
147
-	public function getConfiguration() {
148
-		return $this->config;
149
-	}
144
+    /**
145
+     * @return array
146
+     */
147
+    public function getConfiguration() {
148
+        return $this->config;
149
+    }
150 150
 
151
-	/**
152
-	 * set LDAP configuration with values delivered by an array, not read
153
-	 * from configuration. It does not save the configuration! To do so, you
154
-	 * must call saveConfiguration afterwards.
155
-	 * @param array $config array that holds the config parameters in an associated
156
-	 * array
157
-	 * @param array &$applied optional; array where the set fields will be given to
158
-	 * @return false|null
159
-	 */
160
-	public function setConfiguration($config, &$applied = null) {
161
-		if(!is_array($config)) {
162
-			return false;
163
-		}
151
+    /**
152
+     * set LDAP configuration with values delivered by an array, not read
153
+     * from configuration. It does not save the configuration! To do so, you
154
+     * must call saveConfiguration afterwards.
155
+     * @param array $config array that holds the config parameters in an associated
156
+     * array
157
+     * @param array &$applied optional; array where the set fields will be given to
158
+     * @return false|null
159
+     */
160
+    public function setConfiguration($config, &$applied = null) {
161
+        if(!is_array($config)) {
162
+            return false;
163
+        }
164 164
 
165
-		$cta = $this->getConfigTranslationArray();
166
-		foreach($config as $inputKey => $val) {
167
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
168
-				$key = $cta[$inputKey];
169
-			} elseif(array_key_exists($inputKey, $this->config)) {
170
-				$key = $inputKey;
171
-			} else {
172
-				continue;
173
-			}
165
+        $cta = $this->getConfigTranslationArray();
166
+        foreach($config as $inputKey => $val) {
167
+            if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
168
+                $key = $cta[$inputKey];
169
+            } elseif(array_key_exists($inputKey, $this->config)) {
170
+                $key = $inputKey;
171
+            } else {
172
+                continue;
173
+            }
174 174
 
175
-			$setMethod = 'setValue';
176
-			switch($key) {
177
-				case 'ldapAgentPassword':
178
-					$setMethod = 'setRawValue';
179
-					break;
180
-				case 'homeFolderNamingRule':
181
-					$trimmedVal = trim($val);
182
-					if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
183
-						$val = 'attr:'.$trimmedVal;
184
-					}
185
-					break;
186
-				case 'ldapBase':
187
-				case 'ldapBaseUsers':
188
-				case 'ldapBaseGroups':
189
-				case 'ldapAttributesForUserSearch':
190
-				case 'ldapAttributesForGroupSearch':
191
-				case 'ldapUserFilterObjectclass':
192
-				case 'ldapUserFilterGroups':
193
-				case 'ldapGroupFilterObjectclass':
194
-				case 'ldapGroupFilterGroups':
195
-				case 'ldapLoginFilterAttributes':
196
-					$setMethod = 'setMultiLine';
197
-					break;
198
-			}
199
-			$this->$setMethod($key, $val);
200
-			if(is_array($applied)) {
201
-				$applied[] = $inputKey;
202
-				// storing key as index avoids duplication, and as value for simplicity
203
-			}
204
-			$this->unsavedChanges[$key] = $key;
205
-		}
206
-		return null;
207
-	}
175
+            $setMethod = 'setValue';
176
+            switch($key) {
177
+                case 'ldapAgentPassword':
178
+                    $setMethod = 'setRawValue';
179
+                    break;
180
+                case 'homeFolderNamingRule':
181
+                    $trimmedVal = trim($val);
182
+                    if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
183
+                        $val = 'attr:'.$trimmedVal;
184
+                    }
185
+                    break;
186
+                case 'ldapBase':
187
+                case 'ldapBaseUsers':
188
+                case 'ldapBaseGroups':
189
+                case 'ldapAttributesForUserSearch':
190
+                case 'ldapAttributesForGroupSearch':
191
+                case 'ldapUserFilterObjectclass':
192
+                case 'ldapUserFilterGroups':
193
+                case 'ldapGroupFilterObjectclass':
194
+                case 'ldapGroupFilterGroups':
195
+                case 'ldapLoginFilterAttributes':
196
+                    $setMethod = 'setMultiLine';
197
+                    break;
198
+            }
199
+            $this->$setMethod($key, $val);
200
+            if(is_array($applied)) {
201
+                $applied[] = $inputKey;
202
+                // storing key as index avoids duplication, and as value for simplicity
203
+            }
204
+            $this->unsavedChanges[$key] = $key;
205
+        }
206
+        return null;
207
+    }
208 208
 
209
-	public function readConfiguration() {
210
-		if(!$this->configRead && !is_null($this->configPrefix)) {
211
-			$cta = array_flip($this->getConfigTranslationArray());
212
-			foreach($this->config as $key => $val) {
213
-				if(!isset($cta[$key])) {
214
-					//some are determined
215
-					continue;
216
-				}
217
-				$dbKey = $cta[$key];
218
-				switch($key) {
219
-					case 'ldapBase':
220
-					case 'ldapBaseUsers':
221
-					case 'ldapBaseGroups':
222
-					case 'ldapAttributesForUserSearch':
223
-					case 'ldapAttributesForGroupSearch':
224
-					case 'ldapUserFilterObjectclass':
225
-					case 'ldapUserFilterGroups':
226
-					case 'ldapGroupFilterObjectclass':
227
-					case 'ldapGroupFilterGroups':
228
-					case 'ldapLoginFilterAttributes':
229
-						$readMethod = 'getMultiLine';
230
-						break;
231
-					case 'ldapIgnoreNamingRules':
232
-						$readMethod = 'getSystemValue';
233
-						$dbKey = $key;
234
-						break;
235
-					case 'ldapAgentPassword':
236
-						$readMethod = 'getPwd';
237
-						break;
238
-					case 'ldapUserDisplayName2':
239
-					case 'ldapGroupDisplayName':
240
-						$readMethod = 'getLcValue';
241
-						break;
242
-					case 'ldapUserDisplayName':
243
-					default:
244
-						// user display name does not lower case because
245
-						// we rely on an upper case N as indicator whether to
246
-						// auto-detect it or not. FIXME
247
-						$readMethod = 'getValue';
248
-						break;
249
-				}
250
-				$this->config[$key] = $this->$readMethod($dbKey);
251
-			}
252
-			$this->configRead = true;
253
-		}
254
-	}
209
+    public function readConfiguration() {
210
+        if(!$this->configRead && !is_null($this->configPrefix)) {
211
+            $cta = array_flip($this->getConfigTranslationArray());
212
+            foreach($this->config as $key => $val) {
213
+                if(!isset($cta[$key])) {
214
+                    //some are determined
215
+                    continue;
216
+                }
217
+                $dbKey = $cta[$key];
218
+                switch($key) {
219
+                    case 'ldapBase':
220
+                    case 'ldapBaseUsers':
221
+                    case 'ldapBaseGroups':
222
+                    case 'ldapAttributesForUserSearch':
223
+                    case 'ldapAttributesForGroupSearch':
224
+                    case 'ldapUserFilterObjectclass':
225
+                    case 'ldapUserFilterGroups':
226
+                    case 'ldapGroupFilterObjectclass':
227
+                    case 'ldapGroupFilterGroups':
228
+                    case 'ldapLoginFilterAttributes':
229
+                        $readMethod = 'getMultiLine';
230
+                        break;
231
+                    case 'ldapIgnoreNamingRules':
232
+                        $readMethod = 'getSystemValue';
233
+                        $dbKey = $key;
234
+                        break;
235
+                    case 'ldapAgentPassword':
236
+                        $readMethod = 'getPwd';
237
+                        break;
238
+                    case 'ldapUserDisplayName2':
239
+                    case 'ldapGroupDisplayName':
240
+                        $readMethod = 'getLcValue';
241
+                        break;
242
+                    case 'ldapUserDisplayName':
243
+                    default:
244
+                        // user display name does not lower case because
245
+                        // we rely on an upper case N as indicator whether to
246
+                        // auto-detect it or not. FIXME
247
+                        $readMethod = 'getValue';
248
+                        break;
249
+                }
250
+                $this->config[$key] = $this->$readMethod($dbKey);
251
+            }
252
+            $this->configRead = true;
253
+        }
254
+    }
255 255
 
256
-	/**
257
-	 * saves the current config changes in the database
258
-	 */
259
-	public function saveConfiguration() {
260
-		$cta = array_flip($this->getConfigTranslationArray());
261
-		foreach($this->unsavedChanges as $key) {
262
-			$value = $this->config[$key];
263
-			switch ($key) {
264
-				case 'ldapAgentPassword':
265
-					$value = base64_encode($value);
266
-					break;
267
-				case 'ldapBase':
268
-				case 'ldapBaseUsers':
269
-				case 'ldapBaseGroups':
270
-				case 'ldapAttributesForUserSearch':
271
-				case 'ldapAttributesForGroupSearch':
272
-				case 'ldapUserFilterObjectclass':
273
-				case 'ldapUserFilterGroups':
274
-				case 'ldapGroupFilterObjectclass':
275
-				case 'ldapGroupFilterGroups':
276
-				case 'ldapLoginFilterAttributes':
277
-					if(is_array($value)) {
278
-						$value = implode("\n", $value);
279
-					}
280
-					break;
281
-				//following options are not stored but detected, skip them
282
-				case 'ldapIgnoreNamingRules':
283
-				case 'ldapUuidUserAttribute':
284
-				case 'ldapUuidGroupAttribute':
285
-					continue 2;
286
-			}
287
-			if(is_null($value)) {
288
-				$value = '';
289
-			}
290
-			$this->saveValue($cta[$key], $value);
291
-		}
292
-		$this->saveValue('_lastChange', time());
293
-		$this->unsavedChanges = [];
294
-	}
256
+    /**
257
+     * saves the current config changes in the database
258
+     */
259
+    public function saveConfiguration() {
260
+        $cta = array_flip($this->getConfigTranslationArray());
261
+        foreach($this->unsavedChanges as $key) {
262
+            $value = $this->config[$key];
263
+            switch ($key) {
264
+                case 'ldapAgentPassword':
265
+                    $value = base64_encode($value);
266
+                    break;
267
+                case 'ldapBase':
268
+                case 'ldapBaseUsers':
269
+                case 'ldapBaseGroups':
270
+                case 'ldapAttributesForUserSearch':
271
+                case 'ldapAttributesForGroupSearch':
272
+                case 'ldapUserFilterObjectclass':
273
+                case 'ldapUserFilterGroups':
274
+                case 'ldapGroupFilterObjectclass':
275
+                case 'ldapGroupFilterGroups':
276
+                case 'ldapLoginFilterAttributes':
277
+                    if(is_array($value)) {
278
+                        $value = implode("\n", $value);
279
+                    }
280
+                    break;
281
+                //following options are not stored but detected, skip them
282
+                case 'ldapIgnoreNamingRules':
283
+                case 'ldapUuidUserAttribute':
284
+                case 'ldapUuidGroupAttribute':
285
+                    continue 2;
286
+            }
287
+            if(is_null($value)) {
288
+                $value = '';
289
+            }
290
+            $this->saveValue($cta[$key], $value);
291
+        }
292
+        $this->saveValue('_lastChange', time());
293
+        $this->unsavedChanges = [];
294
+    }
295 295
 
296
-	/**
297
-	 * @param string $varName
298
-	 * @return array|string
299
-	 */
300
-	protected function getMultiLine($varName) {
301
-		$value = $this->getValue($varName);
302
-		if(empty($value)) {
303
-			$value = '';
304
-		} else {
305
-			$value = preg_split('/\r\n|\r|\n/', $value);
306
-		}
296
+    /**
297
+     * @param string $varName
298
+     * @return array|string
299
+     */
300
+    protected function getMultiLine($varName) {
301
+        $value = $this->getValue($varName);
302
+        if(empty($value)) {
303
+            $value = '';
304
+        } else {
305
+            $value = preg_split('/\r\n|\r|\n/', $value);
306
+        }
307 307
 
308
-		return $value;
309
-	}
308
+        return $value;
309
+    }
310 310
 
311
-	/**
312
-	 * Sets multi-line values as arrays
313
-	 * 
314
-	 * @param string $varName name of config-key
315
-	 * @param array|string $value to set
316
-	 */
317
-	protected function setMultiLine($varName, $value) {
318
-		if(empty($value)) {
319
-			$value = '';
320
-		} else if (!is_array($value)) {
321
-			$value = preg_split('/\r\n|\r|\n|;/', $value);
322
-			if($value === false) {
323
-				$value = '';
324
-			}
325
-		}
311
+    /**
312
+     * Sets multi-line values as arrays
313
+     * 
314
+     * @param string $varName name of config-key
315
+     * @param array|string $value to set
316
+     */
317
+    protected function setMultiLine($varName, $value) {
318
+        if(empty($value)) {
319
+            $value = '';
320
+        } else if (!is_array($value)) {
321
+            $value = preg_split('/\r\n|\r|\n|;/', $value);
322
+            if($value === false) {
323
+                $value = '';
324
+            }
325
+        }
326 326
 
327
-		if(!is_array($value)) {
328
-			$finalValue = trim($value);
329
-		} else {
330
-			$finalValue = [];
331
-			foreach($value as $key => $val) {
332
-				if(is_string($val)) {
333
-					$val = trim($val);
334
-					if ($val !== '') {
335
-						//accidental line breaks are not wanted and can cause
336
-						// odd behaviour. Thus, away with them.
337
-						$finalValue[] = $val;
338
-					}
339
-				} else {
340
-					$finalValue[] = $val;
341
-				}
342
-			}
343
-		}
327
+        if(!is_array($value)) {
328
+            $finalValue = trim($value);
329
+        } else {
330
+            $finalValue = [];
331
+            foreach($value as $key => $val) {
332
+                if(is_string($val)) {
333
+                    $val = trim($val);
334
+                    if ($val !== '') {
335
+                        //accidental line breaks are not wanted and can cause
336
+                        // odd behaviour. Thus, away with them.
337
+                        $finalValue[] = $val;
338
+                    }
339
+                } else {
340
+                    $finalValue[] = $val;
341
+                }
342
+            }
343
+        }
344 344
 
345
-		$this->setRawValue($varName, $finalValue);
346
-	}
345
+        $this->setRawValue($varName, $finalValue);
346
+    }
347 347
 
348
-	/**
349
-	 * @param string $varName
350
-	 * @return string
351
-	 */
352
-	protected function getPwd($varName) {
353
-		return base64_decode($this->getValue($varName));
354
-	}
348
+    /**
349
+     * @param string $varName
350
+     * @return string
351
+     */
352
+    protected function getPwd($varName) {
353
+        return base64_decode($this->getValue($varName));
354
+    }
355 355
 
356
-	/**
357
-	 * @param string $varName
358
-	 * @return string
359
-	 */
360
-	protected function getLcValue($varName) {
361
-		return mb_strtolower($this->getValue($varName), 'UTF-8');
362
-	}
356
+    /**
357
+     * @param string $varName
358
+     * @return string
359
+     */
360
+    protected function getLcValue($varName) {
361
+        return mb_strtolower($this->getValue($varName), 'UTF-8');
362
+    }
363 363
 
364
-	/**
365
-	 * @param string $varName
366
-	 * @return string
367
-	 */
368
-	protected function getSystemValue($varName) {
369
-		//FIXME: if another system value is added, softcode the default value
370
-		return \OC::$server->getConfig()->getSystemValue($varName, false);
371
-	}
364
+    /**
365
+     * @param string $varName
366
+     * @return string
367
+     */
368
+    protected function getSystemValue($varName) {
369
+        //FIXME: if another system value is added, softcode the default value
370
+        return \OC::$server->getConfig()->getSystemValue($varName, false);
371
+    }
372 372
 
373
-	/**
374
-	 * @param string $varName
375
-	 * @return string
376
-	 */
377
-	protected function getValue($varName) {
378
-		static $defaults;
379
-		if(is_null($defaults)) {
380
-			$defaults = $this->getDefaults();
381
-		}
382
-		return \OC::$server->getConfig()->getAppValue('user_ldap',
383
-										$this->configPrefix.$varName,
384
-										$defaults[$varName]);
385
-	}
373
+    /**
374
+     * @param string $varName
375
+     * @return string
376
+     */
377
+    protected function getValue($varName) {
378
+        static $defaults;
379
+        if(is_null($defaults)) {
380
+            $defaults = $this->getDefaults();
381
+        }
382
+        return \OC::$server->getConfig()->getAppValue('user_ldap',
383
+                                        $this->configPrefix.$varName,
384
+                                        $defaults[$varName]);
385
+    }
386 386
 
387
-	/**
388
-	 * Sets a scalar value.
389
-	 * 
390
-	 * @param string $varName name of config key
391
-	 * @param mixed $value to set
392
-	 */
393
-	protected function setValue($varName, $value) {
394
-		if(is_string($value)) {
395
-			$value = trim($value);
396
-		}
397
-		$this->config[$varName] = $value;
398
-	}
387
+    /**
388
+     * Sets a scalar value.
389
+     * 
390
+     * @param string $varName name of config key
391
+     * @param mixed $value to set
392
+     */
393
+    protected function setValue($varName, $value) {
394
+        if(is_string($value)) {
395
+            $value = trim($value);
396
+        }
397
+        $this->config[$varName] = $value;
398
+    }
399 399
 
400
-	/**
401
-	 * Sets a scalar value without trimming.
402
-	 *
403
-	 * @param string $varName name of config key
404
-	 * @param mixed $value to set
405
-	 */
406
-	protected function setRawValue($varName, $value) {
407
-		$this->config[$varName] = $value;
408
-	}
400
+    /**
401
+     * Sets a scalar value without trimming.
402
+     *
403
+     * @param string $varName name of config key
404
+     * @param mixed $value to set
405
+     */
406
+    protected function setRawValue($varName, $value) {
407
+        $this->config[$varName] = $value;
408
+    }
409 409
 
410
-	/**
411
-	 * @param string $varName
412
-	 * @param string $value
413
-	 * @return bool
414
-	 */
415
-	protected function saveValue($varName, $value) {
416
-		\OC::$server->getConfig()->setAppValue(
417
-			'user_ldap',
418
-			$this->configPrefix.$varName,
419
-			$value
420
-		);
421
-		return true;
422
-	}
410
+    /**
411
+     * @param string $varName
412
+     * @param string $value
413
+     * @return bool
414
+     */
415
+    protected function saveValue($varName, $value) {
416
+        \OC::$server->getConfig()->setAppValue(
417
+            'user_ldap',
418
+            $this->configPrefix.$varName,
419
+            $value
420
+        );
421
+        return true;
422
+    }
423 423
 
424
-	/**
425
-	 * @return array an associative array with the default values. Keys are correspond
426
-	 * to config-value entries in the database table
427
-	 */
428
-	public function getDefaults() {
429
-		return [
430
-			'ldap_host'                         => '',
431
-			'ldap_port'                         => '',
432
-			'ldap_backup_host'                  => '',
433
-			'ldap_backup_port'                  => '',
434
-			'ldap_override_main_server'         => '',
435
-			'ldap_dn'                           => '',
436
-			'ldap_agent_password'               => '',
437
-			'ldap_base'                         => '',
438
-			'ldap_base_users'                   => '',
439
-			'ldap_base_groups'                  => '',
440
-			'ldap_userlist_filter'              => '',
441
-			'ldap_user_filter_mode'             => 0,
442
-			'ldap_userfilter_objectclass'       => '',
443
-			'ldap_userfilter_groups'            => '',
444
-			'ldap_login_filter'                 => '',
445
-			'ldap_login_filter_mode'            => 0,
446
-			'ldap_loginfilter_email'            => 0,
447
-			'ldap_loginfilter_username'         => 1,
448
-			'ldap_loginfilter_attributes'       => '',
449
-			'ldap_group_filter'                 => '',
450
-			'ldap_group_filter_mode'            => 0,
451
-			'ldap_groupfilter_objectclass'      => '',
452
-			'ldap_groupfilter_groups'           => '',
453
-			'ldap_gid_number'                   => 'gidNumber',
454
-			'ldap_display_name'                 => 'displayName',
455
-			'ldap_user_display_name_2'			=> '',
456
-			'ldap_group_display_name'           => 'cn',
457
-			'ldap_tls'                          => 0,
458
-			'ldap_quota_def'                    => '',
459
-			'ldap_quota_attr'                   => '',
460
-			'ldap_email_attr'                   => '',
461
-			'ldap_group_member_assoc_attribute' => '',
462
-			'ldap_cache_ttl'                    => 600,
463
-			'ldap_uuid_user_attribute'          => 'auto',
464
-			'ldap_uuid_group_attribute'         => 'auto',
465
-			'home_folder_naming_rule'           => '',
466
-			'ldap_turn_off_cert_check'          => 0,
467
-			'ldap_configuration_active'         => 0,
468
-			'ldap_attributes_for_user_search'   => '',
469
-			'ldap_attributes_for_group_search'  => '',
470
-			'ldap_expert_username_attr'         => '',
471
-			'ldap_expert_uuid_user_attr'        => '',
472
-			'ldap_expert_uuid_group_attr'       => '',
473
-			'has_memberof_filter_support'       => 0,
474
-			'use_memberof_to_detect_membership' => 1,
475
-			'last_jpegPhoto_lookup'             => 0,
476
-			'ldap_nested_groups'                => 0,
477
-			'ldap_paging_size'                  => 500,
478
-			'ldap_turn_on_pwd_change'           => 0,
479
-			'ldap_experienced_admin'            => 0,
480
-			'ldap_dynamic_group_member_url'     => '',
481
-			'ldap_default_ppolicy_dn'           => '',
482
-			'ldap_user_avatar_rule'             => 'default',
483
-			'ldap_ext_storage_home_attribute'   => '',
484
-		];
485
-	}
424
+    /**
425
+     * @return array an associative array with the default values. Keys are correspond
426
+     * to config-value entries in the database table
427
+     */
428
+    public function getDefaults() {
429
+        return [
430
+            'ldap_host'                         => '',
431
+            'ldap_port'                         => '',
432
+            'ldap_backup_host'                  => '',
433
+            'ldap_backup_port'                  => '',
434
+            'ldap_override_main_server'         => '',
435
+            'ldap_dn'                           => '',
436
+            'ldap_agent_password'               => '',
437
+            'ldap_base'                         => '',
438
+            'ldap_base_users'                   => '',
439
+            'ldap_base_groups'                  => '',
440
+            'ldap_userlist_filter'              => '',
441
+            'ldap_user_filter_mode'             => 0,
442
+            'ldap_userfilter_objectclass'       => '',
443
+            'ldap_userfilter_groups'            => '',
444
+            'ldap_login_filter'                 => '',
445
+            'ldap_login_filter_mode'            => 0,
446
+            'ldap_loginfilter_email'            => 0,
447
+            'ldap_loginfilter_username'         => 1,
448
+            'ldap_loginfilter_attributes'       => '',
449
+            'ldap_group_filter'                 => '',
450
+            'ldap_group_filter_mode'            => 0,
451
+            'ldap_groupfilter_objectclass'      => '',
452
+            'ldap_groupfilter_groups'           => '',
453
+            'ldap_gid_number'                   => 'gidNumber',
454
+            'ldap_display_name'                 => 'displayName',
455
+            'ldap_user_display_name_2'			=> '',
456
+            'ldap_group_display_name'           => 'cn',
457
+            'ldap_tls'                          => 0,
458
+            'ldap_quota_def'                    => '',
459
+            'ldap_quota_attr'                   => '',
460
+            'ldap_email_attr'                   => '',
461
+            'ldap_group_member_assoc_attribute' => '',
462
+            'ldap_cache_ttl'                    => 600,
463
+            'ldap_uuid_user_attribute'          => 'auto',
464
+            'ldap_uuid_group_attribute'         => 'auto',
465
+            'home_folder_naming_rule'           => '',
466
+            'ldap_turn_off_cert_check'          => 0,
467
+            'ldap_configuration_active'         => 0,
468
+            'ldap_attributes_for_user_search'   => '',
469
+            'ldap_attributes_for_group_search'  => '',
470
+            'ldap_expert_username_attr'         => '',
471
+            'ldap_expert_uuid_user_attr'        => '',
472
+            'ldap_expert_uuid_group_attr'       => '',
473
+            'has_memberof_filter_support'       => 0,
474
+            'use_memberof_to_detect_membership' => 1,
475
+            'last_jpegPhoto_lookup'             => 0,
476
+            'ldap_nested_groups'                => 0,
477
+            'ldap_paging_size'                  => 500,
478
+            'ldap_turn_on_pwd_change'           => 0,
479
+            'ldap_experienced_admin'            => 0,
480
+            'ldap_dynamic_group_member_url'     => '',
481
+            'ldap_default_ppolicy_dn'           => '',
482
+            'ldap_user_avatar_rule'             => 'default',
483
+            'ldap_ext_storage_home_attribute'   => '',
484
+        ];
485
+    }
486 486
 
487
-	/**
488
-	 * @return array that maps internal variable names to database fields
489
-	 */
490
-	public function getConfigTranslationArray() {
491
-		//TODO: merge them into one representation
492
-		static $array = [
493
-			'ldap_host'                         => 'ldapHost',
494
-			'ldap_port'                         => 'ldapPort',
495
-			'ldap_backup_host'                  => 'ldapBackupHost',
496
-			'ldap_backup_port'                  => 'ldapBackupPort',
497
-			'ldap_override_main_server'         => 'ldapOverrideMainServer',
498
-			'ldap_dn'                           => 'ldapAgentName',
499
-			'ldap_agent_password'               => 'ldapAgentPassword',
500
-			'ldap_base'                         => 'ldapBase',
501
-			'ldap_base_users'                   => 'ldapBaseUsers',
502
-			'ldap_base_groups'                  => 'ldapBaseGroups',
503
-			'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
504
-			'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
505
-			'ldap_userlist_filter'              => 'ldapUserFilter',
506
-			'ldap_user_filter_mode'             => 'ldapUserFilterMode',
507
-			'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
508
-			'ldap_login_filter'                 => 'ldapLoginFilter',
509
-			'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
510
-			'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
511
-			'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
512
-			'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
513
-			'ldap_group_filter'                 => 'ldapGroupFilter',
514
-			'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
515
-			'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
516
-			'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
517
-			'ldap_gid_number'                   => 'ldapGidNumber',
518
-			'ldap_display_name'                 => 'ldapUserDisplayName',
519
-			'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
520
-			'ldap_group_display_name'           => 'ldapGroupDisplayName',
521
-			'ldap_tls'                          => 'ldapTLS',
522
-			'ldap_quota_def'                    => 'ldapQuotaDefault',
523
-			'ldap_quota_attr'                   => 'ldapQuotaAttribute',
524
-			'ldap_email_attr'                   => 'ldapEmailAttribute',
525
-			'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
526
-			'ldap_cache_ttl'                    => 'ldapCacheTTL',
527
-			'home_folder_naming_rule'           => 'homeFolderNamingRule',
528
-			'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
529
-			'ldap_configuration_active'         => 'ldapConfigurationActive',
530
-			'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
531
-			'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
532
-			'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
533
-			'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
534
-			'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
535
-			'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
536
-			'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
537
-			'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
538
-			'ldap_nested_groups'                => 'ldapNestedGroups',
539
-			'ldap_paging_size'                  => 'ldapPagingSize',
540
-			'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
541
-			'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
542
-			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
543
-			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
544
-			'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
545
-			'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
546
-		];
547
-		return $array;
548
-	}
487
+    /**
488
+     * @return array that maps internal variable names to database fields
489
+     */
490
+    public function getConfigTranslationArray() {
491
+        //TODO: merge them into one representation
492
+        static $array = [
493
+            'ldap_host'                         => 'ldapHost',
494
+            'ldap_port'                         => 'ldapPort',
495
+            'ldap_backup_host'                  => 'ldapBackupHost',
496
+            'ldap_backup_port'                  => 'ldapBackupPort',
497
+            'ldap_override_main_server'         => 'ldapOverrideMainServer',
498
+            'ldap_dn'                           => 'ldapAgentName',
499
+            'ldap_agent_password'               => 'ldapAgentPassword',
500
+            'ldap_base'                         => 'ldapBase',
501
+            'ldap_base_users'                   => 'ldapBaseUsers',
502
+            'ldap_base_groups'                  => 'ldapBaseGroups',
503
+            'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
504
+            'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
505
+            'ldap_userlist_filter'              => 'ldapUserFilter',
506
+            'ldap_user_filter_mode'             => 'ldapUserFilterMode',
507
+            'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
508
+            'ldap_login_filter'                 => 'ldapLoginFilter',
509
+            'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
510
+            'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
511
+            'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
512
+            'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
513
+            'ldap_group_filter'                 => 'ldapGroupFilter',
514
+            'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
515
+            'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
516
+            'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
517
+            'ldap_gid_number'                   => 'ldapGidNumber',
518
+            'ldap_display_name'                 => 'ldapUserDisplayName',
519
+            'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
520
+            'ldap_group_display_name'           => 'ldapGroupDisplayName',
521
+            'ldap_tls'                          => 'ldapTLS',
522
+            'ldap_quota_def'                    => 'ldapQuotaDefault',
523
+            'ldap_quota_attr'                   => 'ldapQuotaAttribute',
524
+            'ldap_email_attr'                   => 'ldapEmailAttribute',
525
+            'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
526
+            'ldap_cache_ttl'                    => 'ldapCacheTTL',
527
+            'home_folder_naming_rule'           => 'homeFolderNamingRule',
528
+            'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
529
+            'ldap_configuration_active'         => 'ldapConfigurationActive',
530
+            'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
531
+            'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
532
+            'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
533
+            'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
534
+            'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
535
+            'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
536
+            'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
537
+            'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
538
+            'ldap_nested_groups'                => 'ldapNestedGroups',
539
+            'ldap_paging_size'                  => 'ldapPagingSize',
540
+            'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
541
+            'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
542
+            'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
543
+            'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
544
+            'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
545
+            'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
546
+        ];
547
+        return $array;
548
+    }
549 549
 
550
-	/**
551
-	 * @param string $rule
552
-	 * @return array
553
-	 * @throws \RuntimeException
554
-	 */
555
-	public function resolveRule($rule) {
556
-		if($rule === 'avatar') {
557
-			return $this->getAvatarAttributes();
558
-		}
559
-		throw new \RuntimeException('Invalid rule');
560
-	}
550
+    /**
551
+     * @param string $rule
552
+     * @return array
553
+     * @throws \RuntimeException
554
+     */
555
+    public function resolveRule($rule) {
556
+        if($rule === 'avatar') {
557
+            return $this->getAvatarAttributes();
558
+        }
559
+        throw new \RuntimeException('Invalid rule');
560
+    }
561 561
 
562
-	public function getAvatarAttributes() {
563
-		$value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
564
-		$defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
562
+    public function getAvatarAttributes() {
563
+        $value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
564
+        $defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
565 565
 
566
-		if($value === self::AVATAR_PREFIX_NONE) {
567
-			return [];
568
-		}
569
-		if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
570
-			$attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
571
-			if($attribute === '') {
572
-				return $defaultAttributes;
573
-			}
574
-			return [strtolower($attribute)];
575
-		}
576
-		if($value !== self::AVATAR_PREFIX_DEFAULT) {
577
-			\OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
578
-		}
579
-		return $defaultAttributes;
580
-	}
566
+        if($value === self::AVATAR_PREFIX_NONE) {
567
+            return [];
568
+        }
569
+        if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
570
+            $attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
571
+            if($attribute === '') {
572
+                return $defaultAttributes;
573
+            }
574
+            return [strtolower($attribute)];
575
+        }
576
+        if($value !== self::AVATAR_PREFIX_DEFAULT) {
577
+            \OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
578
+        }
579
+        return $defaultAttributes;
580
+    }
581 581
 
582 582
 }
Please login to merge, or discard this patch.
Spacing   +29 added lines, -29 removed lines patch added patch discarded remove patch
@@ -117,7 +117,7 @@  discard block
 block discarded – undo
117 117
 	 */
118 118
 	public function __construct($configPrefix, $autoRead = true) {
119 119
 		$this->configPrefix = $configPrefix;
120
-		if($autoRead) {
120
+		if ($autoRead) {
121 121
 			$this->readConfiguration();
122 122
 		}
123 123
 	}
@@ -127,7 +127,7 @@  discard block
 block discarded – undo
127 127
 	 * @return mixed|null
128 128
 	 */
129 129
 	public function __get($name) {
130
-		if(isset($this->config[$name])) {
130
+		if (isset($this->config[$name])) {
131 131
 			return $this->config[$name];
132 132
 		}
133 133
 		return null;
@@ -158,22 +158,22 @@  discard block
 block discarded – undo
158 158
 	 * @return false|null
159 159
 	 */
160 160
 	public function setConfiguration($config, &$applied = null) {
161
-		if(!is_array($config)) {
161
+		if (!is_array($config)) {
162 162
 			return false;
163 163
 		}
164 164
 
165 165
 		$cta = $this->getConfigTranslationArray();
166
-		foreach($config as $inputKey => $val) {
167
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
166
+		foreach ($config as $inputKey => $val) {
167
+			if (strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
168 168
 				$key = $cta[$inputKey];
169
-			} elseif(array_key_exists($inputKey, $this->config)) {
169
+			} elseif (array_key_exists($inputKey, $this->config)) {
170 170
 				$key = $inputKey;
171 171
 			} else {
172 172
 				continue;
173 173
 			}
174 174
 
175 175
 			$setMethod = 'setValue';
176
-			switch($key) {
176
+			switch ($key) {
177 177
 				case 'ldapAgentPassword':
178 178
 					$setMethod = 'setRawValue';
179 179
 					break;
@@ -197,7 +197,7 @@  discard block
 block discarded – undo
197 197
 					break;
198 198
 			}
199 199
 			$this->$setMethod($key, $val);
200
-			if(is_array($applied)) {
200
+			if (is_array($applied)) {
201 201
 				$applied[] = $inputKey;
202 202
 				// storing key as index avoids duplication, and as value for simplicity
203 203
 			}
@@ -207,15 +207,15 @@  discard block
 block discarded – undo
207 207
 	}
208 208
 
209 209
 	public function readConfiguration() {
210
-		if(!$this->configRead && !is_null($this->configPrefix)) {
210
+		if (!$this->configRead && !is_null($this->configPrefix)) {
211 211
 			$cta = array_flip($this->getConfigTranslationArray());
212
-			foreach($this->config as $key => $val) {
213
-				if(!isset($cta[$key])) {
212
+			foreach ($this->config as $key => $val) {
213
+				if (!isset($cta[$key])) {
214 214
 					//some are determined
215 215
 					continue;
216 216
 				}
217 217
 				$dbKey = $cta[$key];
218
-				switch($key) {
218
+				switch ($key) {
219 219
 					case 'ldapBase':
220 220
 					case 'ldapBaseUsers':
221 221
 					case 'ldapBaseGroups':
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 	 */
259 259
 	public function saveConfiguration() {
260 260
 		$cta = array_flip($this->getConfigTranslationArray());
261
-		foreach($this->unsavedChanges as $key) {
261
+		foreach ($this->unsavedChanges as $key) {
262 262
 			$value = $this->config[$key];
263 263
 			switch ($key) {
264 264
 				case 'ldapAgentPassword':
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 				case 'ldapGroupFilterObjectclass':
275 275
 				case 'ldapGroupFilterGroups':
276 276
 				case 'ldapLoginFilterAttributes':
277
-					if(is_array($value)) {
277
+					if (is_array($value)) {
278 278
 						$value = implode("\n", $value);
279 279
 					}
280 280
 					break;
@@ -284,7 +284,7 @@  discard block
 block discarded – undo
284 284
 				case 'ldapUuidGroupAttribute':
285 285
 					continue 2;
286 286
 			}
287
-			if(is_null($value)) {
287
+			if (is_null($value)) {
288 288
 				$value = '';
289 289
 			}
290 290
 			$this->saveValue($cta[$key], $value);
@@ -299,7 +299,7 @@  discard block
 block discarded – undo
299 299
 	 */
300 300
 	protected function getMultiLine($varName) {
301 301
 		$value = $this->getValue($varName);
302
-		if(empty($value)) {
302
+		if (empty($value)) {
303 303
 			$value = '';
304 304
 		} else {
305 305
 			$value = preg_split('/\r\n|\r|\n/', $value);
@@ -315,21 +315,21 @@  discard block
 block discarded – undo
315 315
 	 * @param array|string $value to set
316 316
 	 */
317 317
 	protected function setMultiLine($varName, $value) {
318
-		if(empty($value)) {
318
+		if (empty($value)) {
319 319
 			$value = '';
320 320
 		} else if (!is_array($value)) {
321 321
 			$value = preg_split('/\r\n|\r|\n|;/', $value);
322
-			if($value === false) {
322
+			if ($value === false) {
323 323
 				$value = '';
324 324
 			}
325 325
 		}
326 326
 
327
-		if(!is_array($value)) {
327
+		if (!is_array($value)) {
328 328
 			$finalValue = trim($value);
329 329
 		} else {
330 330
 			$finalValue = [];
331
-			foreach($value as $key => $val) {
332
-				if(is_string($val)) {
331
+			foreach ($value as $key => $val) {
332
+				if (is_string($val)) {
333 333
 					$val = trim($val);
334 334
 					if ($val !== '') {
335 335
 						//accidental line breaks are not wanted and can cause
@@ -376,7 +376,7 @@  discard block
 block discarded – undo
376 376
 	 */
377 377
 	protected function getValue($varName) {
378 378
 		static $defaults;
379
-		if(is_null($defaults)) {
379
+		if (is_null($defaults)) {
380 380
 			$defaults = $this->getDefaults();
381 381
 		}
382 382
 		return \OC::$server->getConfig()->getAppValue('user_ldap',
@@ -391,7 +391,7 @@  discard block
 block discarded – undo
391 391
 	 * @param mixed $value to set
392 392
 	 */
393 393
 	protected function setValue($varName, $value) {
394
-		if(is_string($value)) {
394
+		if (is_string($value)) {
395 395
 			$value = trim($value);
396 396
 		}
397 397
 		$this->config[$varName] = $value;
@@ -542,7 +542,7 @@  discard block
 block discarded – undo
542 542
 			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
543 543
 			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
544 544
 			'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
545
-			'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
545
+			'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules', // sysconfig
546 546
 		];
547 547
 		return $array;
548 548
 	}
@@ -553,7 +553,7 @@  discard block
 block discarded – undo
553 553
 	 * @throws \RuntimeException
554 554
 	 */
555 555
 	public function resolveRule($rule) {
556
-		if($rule === 'avatar') {
556
+		if ($rule === 'avatar') {
557 557
 			return $this->getAvatarAttributes();
558 558
 		}
559 559
 		throw new \RuntimeException('Invalid rule');
@@ -563,17 +563,17 @@  discard block
 block discarded – undo
563 563
 		$value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
564 564
 		$defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
565 565
 
566
-		if($value === self::AVATAR_PREFIX_NONE) {
566
+		if ($value === self::AVATAR_PREFIX_NONE) {
567 567
 			return [];
568 568
 		}
569
-		if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
569
+		if (strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
570 570
 			$attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
571
-			if($attribute === '') {
571
+			if ($attribute === '') {
572 572
 				return $defaultAttributes;
573 573
 			}
574 574
 			return [strtolower($attribute)];
575 575
 		}
576
-		if($value !== self::AVATAR_PREFIX_DEFAULT) {
576
+		if ($value !== self::AVATAR_PREFIX_DEFAULT) {
577 577
 			\OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
578 578
 		}
579 579
 		return $defaultAttributes;
Please login to merge, or discard this patch.