Completed
Push — master ( ede649...d3e7dd )
by Lukas
16:27
created
apps/user_ldap/lib/Access.php 4 patches
Doc Comments   +7 added lines, -5 removed lines patch added patch discarded remove patch
@@ -500,7 +500,7 @@  discard block
 block discarded – undo
500 500
 
501 501
 	/**
502 502
 	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
503
-	 * @param string $dn the dn of the user object
503
+	 * @param string $fdn the dn of the user object
504 504
 	 * @param string $ldapName optional, the display name of the object
505 505
 	 * @return string|false with with the name to use in Nextcloud
506 506
 	 */
@@ -786,7 +786,7 @@  discard block
 block discarded – undo
786 786
 	 * the login filter.
787 787
 	 *
788 788
 	 * @param string $loginName
789
-	 * @param array $attributes optional, list of attributes to read
789
+	 * @param string[] $attributes optional, list of attributes to read
790 790
 	 * @return array
791 791
 	 */
792 792
 	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
@@ -870,7 +870,7 @@  discard block
 block discarded – undo
870 870
 
871 871
 	/**
872 872
 	 * @param string $filter
873
-	 * @param string|string[] $attr
873
+	 * @param string[] $attr
874 874
 	 * @param int $limit
875 875
 	 * @param int $offset
876 876
 	 * @return array
@@ -918,7 +918,7 @@  discard block
 block discarded – undo
918 918
 
919 919
 	/**
920 920
 	 * @param string $filter
921
-	 * @param string|string[] $attr
921
+	 * @param string[] $attr
922 922
 	 * @param int $limit
923 923
 	 * @param int $offset
924 924
 	 * @return false|int
@@ -1018,6 +1018,7 @@  discard block
 block discarded – undo
1018 1018
 	 * retrieved. Results will according to the order in the array.
1019 1019
 	 * @param int $limit optional, maximum results to be counted
1020 1020
 	 * @param int $offset optional, a starting point
1021
+	 * @param string $filter
1021 1022
 	 * @return array|false array with the search result as first value and pagedSearchOK as
1022 1023
 	 * second | false if not successful
1023 1024
 	 * @throws \OC\ServerNotAvailableException
@@ -1274,7 +1275,7 @@  discard block
 block discarded – undo
1274 1275
 
1275 1276
 	/**
1276 1277
 	 * @param string $name
1277
-	 * @return bool|mixed|string
1278
+	 * @return string
1278 1279
 	 */
1279 1280
 	public function sanitizeUsername($name) {
1280 1281
 		if($this->connection->ldapIgnoreNamingRules) {
@@ -1298,6 +1299,7 @@  discard block
 block discarded – undo
1298 1299
 	* escapes (user provided) parts for LDAP filter
1299 1300
 	* @param string $input, the provided value
1300 1301
 	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1302
+	* @param string $input
1301 1303
 	* @return string the escaped string
1302 1304
 	*/
1303 1305
 	public function escapeFilterPart($input, $allowAsterisk = false) {
Please login to merge, or discard this patch.
Unused Use Statements   -1 removed lines patch added patch discarded remove patch
@@ -49,7 +49,6 @@
 block discarded – undo
49 49
 use OCA\User_LDAP\User\Manager;
50 50
 use OCA\User_LDAP\User\OfflineUser;
51 51
 use OCA\User_LDAP\Mapping\AbstractMapping;
52
-
53 52
 use OC\ServerNotAvailableException;
54 53
 use OCP\IConfig;
55 54
 
Please login to merge, or discard this patch.
Indentation   +1859 added lines, -1859 removed lines patch added patch discarded remove patch
@@ -58,1620 +58,1620 @@  discard block
 block discarded – undo
58 58
  * @package OCA\User_LDAP
59 59
  */
60 60
 class Access extends LDAPUtility implements IUserTools {
61
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
62
-
63
-	/** @var \OCA\User_LDAP\Connection */
64
-	public $connection;
65
-	/** @var Manager */
66
-	public $userManager;
67
-	//never ever check this var directly, always use getPagedSearchResultState
68
-	protected $pagedSearchedSuccessful;
69
-
70
-	/**
71
-	 * @var string[] $cookies an array of returned Paged Result cookies
72
-	 */
73
-	protected $cookies = array();
74
-
75
-	/**
76
-	 * @var string $lastCookie the last cookie returned from a Paged Results
77
-	 * operation, defaults to an empty string
78
-	 */
79
-	protected $lastCookie = '';
80
-
81
-	/**
82
-	 * @var AbstractMapping $userMapper
83
-	 */
84
-	protected $userMapper;
85
-
86
-	/**
87
-	* @var AbstractMapping $userMapper
88
-	*/
89
-	protected $groupMapper;
90
-
91
-	/**
92
-	 * @var \OCA\User_LDAP\Helper
93
-	 */
94
-	private $helper;
95
-	/** @var IConfig */
96
-	private $config;
97
-
98
-	public function __construct(
99
-		Connection $connection,
100
-		ILDAPWrapper $ldap,
101
-		Manager $userManager,
102
-		Helper $helper,
103
-		IConfig $config
104
-	) {
105
-		parent::__construct($ldap);
106
-		$this->connection = $connection;
107
-		$this->userManager = $userManager;
108
-		$this->userManager->setLdapAccess($this);
109
-		$this->helper = $helper;
110
-		$this->config = $config;
111
-	}
112
-
113
-	/**
114
-	 * sets the User Mapper
115
-	 * @param AbstractMapping $mapper
116
-	 */
117
-	public function setUserMapper(AbstractMapping $mapper) {
118
-		$this->userMapper = $mapper;
119
-	}
120
-
121
-	/**
122
-	 * returns the User Mapper
123
-	 * @throws \Exception
124
-	 * @return AbstractMapping
125
-	 */
126
-	public function getUserMapper() {
127
-		if(is_null($this->userMapper)) {
128
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
129
-		}
130
-		return $this->userMapper;
131
-	}
132
-
133
-	/**
134
-	 * sets the Group Mapper
135
-	 * @param AbstractMapping $mapper
136
-	 */
137
-	public function setGroupMapper(AbstractMapping $mapper) {
138
-		$this->groupMapper = $mapper;
139
-	}
140
-
141
-	/**
142
-	 * returns the Group Mapper
143
-	 * @throws \Exception
144
-	 * @return AbstractMapping
145
-	 */
146
-	public function getGroupMapper() {
147
-		if(is_null($this->groupMapper)) {
148
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
149
-		}
150
-		return $this->groupMapper;
151
-	}
152
-
153
-	/**
154
-	 * @return bool
155
-	 */
156
-	private function checkConnection() {
157
-		return ($this->connection instanceof Connection);
158
-	}
159
-
160
-	/**
161
-	 * returns the Connection instance
162
-	 * @return \OCA\User_LDAP\Connection
163
-	 */
164
-	public function getConnection() {
165
-		return $this->connection;
166
-	}
167
-
168
-	/**
169
-	 * reads a given attribute for an LDAP record identified by a DN
170
-	 * @param string $dn the record in question
171
-	 * @param string $attr the attribute that shall be retrieved
172
-	 *        if empty, just check the record's existence
173
-	 * @param string $filter
174
-	 * @return array|false an array of values on success or an empty
175
-	 *          array if $attr is empty, false otherwise
176
-	 */
177
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
178
-		if(!$this->checkConnection()) {
179
-			\OCP\Util::writeLog('user_ldap',
180
-				'No LDAP Connector assigned, access impossible for readAttribute.',
181
-				\OCP\Util::WARN);
182
-			return false;
183
-		}
184
-		$cr = $this->connection->getConnectionResource();
185
-		if(!$this->ldap->isResource($cr)) {
186
-			//LDAP not available
187
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
188
-			return false;
189
-		}
190
-		//Cancel possibly running Paged Results operation, otherwise we run in
191
-		//LDAP protocol errors
192
-		$this->abandonPagedSearch();
193
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
194
-		// but does not hurt either.
195
-		$pagingSize = intval($this->connection->ldapPagingSize);
196
-		// 0 won't result in replies, small numbers may leave out groups
197
-		// (cf. #12306), 500 is default for paging and should work everywhere.
198
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
199
-		$attr = mb_strtolower($attr, 'UTF-8');
200
-		// the actual read attribute later may contain parameters on a ranged
201
-		// request, e.g. member;range=99-199. Depends on server reply.
202
-		$attrToRead = $attr;
203
-
204
-		$values = [];
205
-		$isRangeRequest = false;
206
-		do {
207
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
208
-			if(is_bool($result)) {
209
-				// when an exists request was run and it was successful, an empty
210
-				// array must be returned
211
-				return $result ? [] : false;
212
-			}
213
-
214
-			if (!$isRangeRequest) {
215
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
216
-				if (!empty($values)) {
217
-					return $values;
218
-				}
219
-			}
220
-
221
-			$isRangeRequest = false;
222
-			$result = $this->extractRangeData($result, $attr);
223
-			if (!empty($result)) {
224
-				$normalizedResult = $this->extractAttributeValuesFromResult(
225
-					[ $attr => $result['values'] ],
226
-					$attr
227
-				);
228
-				$values = array_merge($values, $normalizedResult);
229
-
230
-				if($result['rangeHigh'] === '*') {
231
-					// when server replies with * as high range value, there are
232
-					// no more results left
233
-					return $values;
234
-				} else {
235
-					$low  = $result['rangeHigh'] + 1;
236
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
237
-					$isRangeRequest = true;
238
-				}
239
-			}
240
-		} while($isRangeRequest);
241
-
242
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
243
-		return false;
244
-	}
245
-
246
-	/**
247
-	 * Runs an read operation against LDAP
248
-	 *
249
-	 * @param resource $cr the LDAP connection
250
-	 * @param string $dn
251
-	 * @param string $attribute
252
-	 * @param string $filter
253
-	 * @param int $maxResults
254
-	 * @return array|bool false if there was any error, true if an exists check
255
-	 *                    was performed and the requested DN found, array with the
256
-	 *                    returned data on a successful usual operation
257
-	 */
258
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
259
-		$this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
260
-		$dn = $this->helper->DNasBaseParameter($dn);
261
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
262
-		if (!$this->ldap->isResource($rr)) {
263
-			if ($attribute !== '') {
264
-				//do not throw this message on userExists check, irritates
265
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
266
-			}
267
-			//in case an error occurs , e.g. object does not exist
268
-			return false;
269
-		}
270
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
271
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
272
-			return true;
273
-		}
274
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
275
-		if (!$this->ldap->isResource($er)) {
276
-			//did not match the filter, return false
277
-			return false;
278
-		}
279
-		//LDAP attributes are not case sensitive
280
-		$result = \OCP\Util::mb_array_change_key_case(
281
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
282
-
283
-		return $result;
284
-	}
285
-
286
-	/**
287
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
288
-	 * data if present.
289
-	 *
290
-	 * @param array $result from ILDAPWrapper::getAttributes()
291
-	 * @param string $attribute the attribute name that was read
292
-	 * @return string[]
293
-	 */
294
-	public function extractAttributeValuesFromResult($result, $attribute) {
295
-		$values = [];
296
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297
-			$lowercaseAttribute = strtolower($attribute);
298
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
299
-				if($this->resemblesDN($attribute)) {
300
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
301
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
303
-				} else {
304
-					$values[] = $result[$attribute][$i];
305
-				}
306
-			}
307
-		}
308
-		return $values;
309
-	}
310
-
311
-	/**
312
-	 * Attempts to find ranged data in a getAttribute results and extracts the
313
-	 * returned values as well as information on the range and full attribute
314
-	 * name for further processing.
315
-	 *
316
-	 * @param array $result from ILDAPWrapper::getAttributes()
317
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
318
-	 * @return array If a range was detected with keys 'values', 'attributeName',
319
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
320
-	 */
321
-	public function extractRangeData($result, $attribute) {
322
-		$keys = array_keys($result);
323
-		foreach($keys as $key) {
324
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
325
-				$queryData = explode(';', $key);
326
-				if(strpos($queryData[1], 'range=') === 0) {
327
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
328
-					$data = [
329
-						'values' => $result[$key],
330
-						'attributeName' => $queryData[0],
331
-						'attributeFull' => $key,
332
-						'rangeHigh' => $high,
333
-					];
334
-					return $data;
335
-				}
336
-			}
337
-		}
338
-		return [];
339
-	}
61
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
62
+
63
+    /** @var \OCA\User_LDAP\Connection */
64
+    public $connection;
65
+    /** @var Manager */
66
+    public $userManager;
67
+    //never ever check this var directly, always use getPagedSearchResultState
68
+    protected $pagedSearchedSuccessful;
69
+
70
+    /**
71
+     * @var string[] $cookies an array of returned Paged Result cookies
72
+     */
73
+    protected $cookies = array();
74
+
75
+    /**
76
+     * @var string $lastCookie the last cookie returned from a Paged Results
77
+     * operation, defaults to an empty string
78
+     */
79
+    protected $lastCookie = '';
80
+
81
+    /**
82
+     * @var AbstractMapping $userMapper
83
+     */
84
+    protected $userMapper;
85
+
86
+    /**
87
+     * @var AbstractMapping $userMapper
88
+     */
89
+    protected $groupMapper;
90
+
91
+    /**
92
+     * @var \OCA\User_LDAP\Helper
93
+     */
94
+    private $helper;
95
+    /** @var IConfig */
96
+    private $config;
97
+
98
+    public function __construct(
99
+        Connection $connection,
100
+        ILDAPWrapper $ldap,
101
+        Manager $userManager,
102
+        Helper $helper,
103
+        IConfig $config
104
+    ) {
105
+        parent::__construct($ldap);
106
+        $this->connection = $connection;
107
+        $this->userManager = $userManager;
108
+        $this->userManager->setLdapAccess($this);
109
+        $this->helper = $helper;
110
+        $this->config = $config;
111
+    }
112
+
113
+    /**
114
+     * sets the User Mapper
115
+     * @param AbstractMapping $mapper
116
+     */
117
+    public function setUserMapper(AbstractMapping $mapper) {
118
+        $this->userMapper = $mapper;
119
+    }
120
+
121
+    /**
122
+     * returns the User Mapper
123
+     * @throws \Exception
124
+     * @return AbstractMapping
125
+     */
126
+    public function getUserMapper() {
127
+        if(is_null($this->userMapper)) {
128
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
129
+        }
130
+        return $this->userMapper;
131
+    }
132
+
133
+    /**
134
+     * sets the Group Mapper
135
+     * @param AbstractMapping $mapper
136
+     */
137
+    public function setGroupMapper(AbstractMapping $mapper) {
138
+        $this->groupMapper = $mapper;
139
+    }
140
+
141
+    /**
142
+     * returns the Group Mapper
143
+     * @throws \Exception
144
+     * @return AbstractMapping
145
+     */
146
+    public function getGroupMapper() {
147
+        if(is_null($this->groupMapper)) {
148
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
149
+        }
150
+        return $this->groupMapper;
151
+    }
152
+
153
+    /**
154
+     * @return bool
155
+     */
156
+    private function checkConnection() {
157
+        return ($this->connection instanceof Connection);
158
+    }
159
+
160
+    /**
161
+     * returns the Connection instance
162
+     * @return \OCA\User_LDAP\Connection
163
+     */
164
+    public function getConnection() {
165
+        return $this->connection;
166
+    }
167
+
168
+    /**
169
+     * reads a given attribute for an LDAP record identified by a DN
170
+     * @param string $dn the record in question
171
+     * @param string $attr the attribute that shall be retrieved
172
+     *        if empty, just check the record's existence
173
+     * @param string $filter
174
+     * @return array|false an array of values on success or an empty
175
+     *          array if $attr is empty, false otherwise
176
+     */
177
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
178
+        if(!$this->checkConnection()) {
179
+            \OCP\Util::writeLog('user_ldap',
180
+                'No LDAP Connector assigned, access impossible for readAttribute.',
181
+                \OCP\Util::WARN);
182
+            return false;
183
+        }
184
+        $cr = $this->connection->getConnectionResource();
185
+        if(!$this->ldap->isResource($cr)) {
186
+            //LDAP not available
187
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
188
+            return false;
189
+        }
190
+        //Cancel possibly running Paged Results operation, otherwise we run in
191
+        //LDAP protocol errors
192
+        $this->abandonPagedSearch();
193
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
194
+        // but does not hurt either.
195
+        $pagingSize = intval($this->connection->ldapPagingSize);
196
+        // 0 won't result in replies, small numbers may leave out groups
197
+        // (cf. #12306), 500 is default for paging and should work everywhere.
198
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
199
+        $attr = mb_strtolower($attr, 'UTF-8');
200
+        // the actual read attribute later may contain parameters on a ranged
201
+        // request, e.g. member;range=99-199. Depends on server reply.
202
+        $attrToRead = $attr;
203
+
204
+        $values = [];
205
+        $isRangeRequest = false;
206
+        do {
207
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
208
+            if(is_bool($result)) {
209
+                // when an exists request was run and it was successful, an empty
210
+                // array must be returned
211
+                return $result ? [] : false;
212
+            }
213
+
214
+            if (!$isRangeRequest) {
215
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
216
+                if (!empty($values)) {
217
+                    return $values;
218
+                }
219
+            }
220
+
221
+            $isRangeRequest = false;
222
+            $result = $this->extractRangeData($result, $attr);
223
+            if (!empty($result)) {
224
+                $normalizedResult = $this->extractAttributeValuesFromResult(
225
+                    [ $attr => $result['values'] ],
226
+                    $attr
227
+                );
228
+                $values = array_merge($values, $normalizedResult);
229
+
230
+                if($result['rangeHigh'] === '*') {
231
+                    // when server replies with * as high range value, there are
232
+                    // no more results left
233
+                    return $values;
234
+                } else {
235
+                    $low  = $result['rangeHigh'] + 1;
236
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
237
+                    $isRangeRequest = true;
238
+                }
239
+            }
240
+        } while($isRangeRequest);
241
+
242
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
243
+        return false;
244
+    }
245
+
246
+    /**
247
+     * Runs an read operation against LDAP
248
+     *
249
+     * @param resource $cr the LDAP connection
250
+     * @param string $dn
251
+     * @param string $attribute
252
+     * @param string $filter
253
+     * @param int $maxResults
254
+     * @return array|bool false if there was any error, true if an exists check
255
+     *                    was performed and the requested DN found, array with the
256
+     *                    returned data on a successful usual operation
257
+     */
258
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
259
+        $this->initPagedSearch($filter, array($dn), array($attribute), $maxResults, 0);
260
+        $dn = $this->helper->DNasBaseParameter($dn);
261
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, array($attribute));
262
+        if (!$this->ldap->isResource($rr)) {
263
+            if ($attribute !== '') {
264
+                //do not throw this message on userExists check, irritates
265
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
266
+            }
267
+            //in case an error occurs , e.g. object does not exist
268
+            return false;
269
+        }
270
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
271
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
272
+            return true;
273
+        }
274
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
275
+        if (!$this->ldap->isResource($er)) {
276
+            //did not match the filter, return false
277
+            return false;
278
+        }
279
+        //LDAP attributes are not case sensitive
280
+        $result = \OCP\Util::mb_array_change_key_case(
281
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
282
+
283
+        return $result;
284
+    }
285
+
286
+    /**
287
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
288
+     * data if present.
289
+     *
290
+     * @param array $result from ILDAPWrapper::getAttributes()
291
+     * @param string $attribute the attribute name that was read
292
+     * @return string[]
293
+     */
294
+    public function extractAttributeValuesFromResult($result, $attribute) {
295
+        $values = [];
296
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297
+            $lowercaseAttribute = strtolower($attribute);
298
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
299
+                if($this->resemblesDN($attribute)) {
300
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
301
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
303
+                } else {
304
+                    $values[] = $result[$attribute][$i];
305
+                }
306
+            }
307
+        }
308
+        return $values;
309
+    }
310
+
311
+    /**
312
+     * Attempts to find ranged data in a getAttribute results and extracts the
313
+     * returned values as well as information on the range and full attribute
314
+     * name for further processing.
315
+     *
316
+     * @param array $result from ILDAPWrapper::getAttributes()
317
+     * @param string $attribute the attribute name that was read. Without ";range=…"
318
+     * @return array If a range was detected with keys 'values', 'attributeName',
319
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
320
+     */
321
+    public function extractRangeData($result, $attribute) {
322
+        $keys = array_keys($result);
323
+        foreach($keys as $key) {
324
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
325
+                $queryData = explode(';', $key);
326
+                if(strpos($queryData[1], 'range=') === 0) {
327
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
328
+                    $data = [
329
+                        'values' => $result[$key],
330
+                        'attributeName' => $queryData[0],
331
+                        'attributeFull' => $key,
332
+                        'rangeHigh' => $high,
333
+                    ];
334
+                    return $data;
335
+                }
336
+            }
337
+        }
338
+        return [];
339
+    }
340 340
 	
341
-	/**
342
-	 * Set password for an LDAP user identified by a DN
343
-	 *
344
-	 * @param string $userDN the user in question
345
-	 * @param string $password the new password
346
-	 * @return bool
347
-	 * @throws HintException
348
-	 * @throws \Exception
349
-	 */
350
-	public function setPassword($userDN, $password) {
351
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
352
-			throw new \Exception('LDAP password changes are disabled.');
353
-		}
354
-		$cr = $this->connection->getConnectionResource();
355
-		if(!$this->ldap->isResource($cr)) {
356
-			//LDAP not available
357
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
358
-			return false;
359
-		}
360
-		try {
361
-			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
362
-		} catch(ConstraintViolationException $e) {
363
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
364
-		}
365
-	}
366
-
367
-	/**
368
-	 * checks whether the given attributes value is probably a DN
369
-	 * @param string $attr the attribute in question
370
-	 * @return boolean if so true, otherwise false
371
-	 */
372
-	private function resemblesDN($attr) {
373
-		$resemblingAttributes = array(
374
-			'dn',
375
-			'uniquemember',
376
-			'member',
377
-			// memberOf is an "operational" attribute, without a definition in any RFC
378
-			'memberof'
379
-		);
380
-		return in_array($attr, $resemblingAttributes);
381
-	}
382
-
383
-	/**
384
-	 * checks whether the given string is probably a DN
385
-	 * @param string $string
386
-	 * @return boolean
387
-	 */
388
-	public function stringResemblesDN($string) {
389
-		$r = $this->ldap->explodeDN($string, 0);
390
-		// if exploding a DN succeeds and does not end up in
391
-		// an empty array except for $r[count] being 0.
392
-		return (is_array($r) && count($r) > 1);
393
-	}
394
-
395
-	/**
396
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
397
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
398
-	 * becomes dc=foobar,dc=server,dc=org
399
-	 * @param string $dn
400
-	 * @return string
401
-	 */
402
-	public function getDomainDNFromDN($dn) {
403
-		$allParts = $this->ldap->explodeDN($dn, 0);
404
-		if($allParts === false) {
405
-			//not a valid DN
406
-			return '';
407
-		}
408
-		$domainParts = array();
409
-		$dcFound = false;
410
-		foreach($allParts as $part) {
411
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
412
-				$dcFound = true;
413
-			}
414
-			if($dcFound) {
415
-				$domainParts[] = $part;
416
-			}
417
-		}
418
-		$domainDN = implode(',', $domainParts);
419
-		return $domainDN;
420
-	}
421
-
422
-	/**
423
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
424
-	 * @param string $name the Nextcloud name in question
425
-	 * @return string|false LDAP DN on success, otherwise false
426
-	 */
427
-	public function groupname2dn($name) {
428
-		return $this->groupMapper->getDNByName($name);
429
-	}
430
-
431
-	/**
432
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
433
-	 * @param string $name the Nextcloud name in question
434
-	 * @return string|false with the LDAP DN on success, otherwise false
435
-	 */
436
-	public function username2dn($name) {
437
-		$fdn = $this->userMapper->getDNByName($name);
438
-
439
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
440
-		//server setups
441
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442
-			return $fdn;
443
-		}
444
-
445
-		return false;
446
-	}
447
-
448
-	/**
449
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
450
-	 * @param string $fdn the dn of the group object
451
-	 * @param string $ldapName optional, the display name of the object
452
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
453
-	 */
454
-	public function dn2groupname($fdn, $ldapName = null) {
455
-		//To avoid bypassing the base DN settings under certain circumstances
456
-		//with the group support, check whether the provided DN matches one of
457
-		//the given Bases
458
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459
-			return false;
460
-		}
461
-
462
-		return $this->dn2ocname($fdn, $ldapName, false);
463
-	}
464
-
465
-	/**
466
-	 * accepts an array of group DNs and tests whether they match the user
467
-	 * filter by doing read operations against the group entries. Returns an
468
-	 * array of DNs that match the filter.
469
-	 *
470
-	 * @param string[] $groupDNs
471
-	 * @return string[]
472
-	 */
473
-	public function groupsMatchFilter($groupDNs) {
474
-		$validGroupDNs = [];
475
-		foreach($groupDNs as $dn) {
476
-			$cacheKey = 'groupsMatchFilter-'.$dn;
477
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
478
-			if(!is_null($groupMatchFilter)) {
479
-				if($groupMatchFilter) {
480
-					$validGroupDNs[] = $dn;
481
-				}
482
-				continue;
483
-			}
484
-
485
-			// Check the base DN first. If this is not met already, we don't
486
-			// need to ask the server at all.
487
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488
-				$this->connection->writeToCache($cacheKey, false);
489
-				continue;
490
-			}
491
-
492
-			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
493
-			if(is_array($result)) {
494
-				$this->connection->writeToCache($cacheKey, true);
495
-				$validGroupDNs[] = $dn;
496
-			} else {
497
-				$this->connection->writeToCache($cacheKey, false);
498
-			}
499
-
500
-		}
501
-		return $validGroupDNs;
502
-	}
503
-
504
-	/**
505
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
506
-	 * @param string $dn the dn of the user object
507
-	 * @param string $ldapName optional, the display name of the object
508
-	 * @return string|false with with the name to use in Nextcloud
509
-	 */
510
-	public function dn2username($fdn, $ldapName = null) {
511
-		//To avoid bypassing the base DN settings under certain circumstances
512
-		//with the group support, check whether the provided DN matches one of
513
-		//the given Bases
514
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515
-			return false;
516
-		}
517
-
518
-		return $this->dn2ocname($fdn, $ldapName, true);
519
-	}
520
-
521
-	/**
522
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
523
-	 *
524
-	 * @param string $fdn the dn of the user object
525
-	 * @param string|null $ldapName optional, the display name of the object
526
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
527
-	 * @param bool|null $newlyMapped
528
-	 * @param array|null $record
529
-	 * @return false|string with with the name to use in Nextcloud
530
-	 */
531
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
532
-		$newlyMapped = false;
533
-		if($isUser) {
534
-			$mapper = $this->getUserMapper();
535
-			$nameAttribute = $this->connection->ldapUserDisplayName;
536
-		} else {
537
-			$mapper = $this->getGroupMapper();
538
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
539
-		}
540
-
541
-		//let's try to retrieve the Nextcloud name from the mappings table
542
-		$ncName = $mapper->getNameByDN($fdn);
543
-		if(is_string($ncName)) {
544
-			return $ncName;
545
-		}
546
-
547
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
548
-		$uuid = $this->getUUID($fdn, $isUser, $record);
549
-		if(is_string($uuid)) {
550
-			$ncName = $mapper->getNameByUUID($uuid);
551
-			if(is_string($ncName)) {
552
-				$mapper->setDNbyUUID($fdn, $uuid);
553
-				return $ncName;
554
-			}
555
-		} else {
556
-			//If the UUID can't be detected something is foul.
557
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
558
-			return false;
559
-		}
560
-
561
-		if(is_null($ldapName)) {
562
-			$ldapName = $this->readAttribute($fdn, $nameAttribute);
563
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
564
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
565
-				return false;
566
-			}
567
-			$ldapName = $ldapName[0];
568
-		}
569
-
570
-		if($isUser) {
571
-			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
572
-			if ($usernameAttribute !== '') {
573
-				$username = $this->readAttribute($fdn, $usernameAttribute);
574
-				$username = $username[0];
575
-			} else {
576
-				$username = $uuid;
577
-			}
578
-			$intName = $this->sanitizeUsername($username);
579
-		} else {
580
-			$intName = $ldapName;
581
-		}
582
-
583
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
584
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
585
-		//NOTE: mind, disabling cache affects only this instance! Using it
586
-		// outside of core user management will still cache the user as non-existing.
587
-		$originalTTL = $this->connection->ldapCacheTTL;
588
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
589
-		if(($isUser && !\OCP\User::userExists($intName))
590
-			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
591
-			if($mapper->map($fdn, $intName, $uuid)) {
592
-				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
593
-				$newlyMapped = true;
594
-				return $intName;
595
-			}
596
-		}
597
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
598
-
599
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
600
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
601
-			$newlyMapped = true;
602
-			return $altName;
603
-		}
604
-
605
-		//if everything else did not help..
606
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
607
-		return false;
608
-	}
609
-
610
-	/**
611
-	 * gives back the user names as they are used ownClod internally
612
-	 * @param array $ldapUsers as returned by fetchList()
613
-	 * @return array an array with the user names to use in Nextcloud
614
-	 *
615
-	 * gives back the user names as they are used ownClod internally
616
-	 */
617
-	public function nextcloudUserNames($ldapUsers) {
618
-		return $this->ldap2NextcloudNames($ldapUsers, true);
619
-	}
620
-
621
-	/**
622
-	 * gives back the group names as they are used ownClod internally
623
-	 * @param array $ldapGroups as returned by fetchList()
624
-	 * @return array an array with the group names to use in Nextcloud
625
-	 *
626
-	 * gives back the group names as they are used ownClod internally
627
-	 */
628
-	public function nextcloudGroupNames($ldapGroups) {
629
-		return $this->ldap2NextcloudNames($ldapGroups, false);
630
-	}
631
-
632
-	/**
633
-	 * @param array $ldapObjects as returned by fetchList()
634
-	 * @param bool $isUsers
635
-	 * @return array
636
-	 */
637
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
638
-		if($isUsers) {
639
-			$nameAttribute = $this->connection->ldapUserDisplayName;
640
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
641
-		} else {
642
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
643
-		}
644
-		$nextcloudNames = array();
645
-
646
-		foreach($ldapObjects as $ldapObject) {
647
-			$nameByLDAP = null;
648
-			if(    isset($ldapObject[$nameAttribute])
649
-				&& is_array($ldapObject[$nameAttribute])
650
-				&& isset($ldapObject[$nameAttribute][0])
651
-			) {
652
-				// might be set, but not necessarily. if so, we use it.
653
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
654
-			}
655
-
656
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
657
-			if($ncName) {
658
-				$nextcloudNames[] = $ncName;
659
-				if($isUsers) {
660
-					//cache the user names so it does not need to be retrieved
661
-					//again later (e.g. sharing dialogue).
662
-					if(is_null($nameByLDAP)) {
663
-						continue;
664
-					}
665
-					$sndName = isset($ldapObject[$sndAttribute][0])
666
-						? $ldapObject[$sndAttribute][0] : '';
667
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
668
-				}
669
-			}
670
-		}
671
-		return $nextcloudNames;
672
-	}
673
-
674
-	/**
675
-	 * caches the user display name
676
-	 * @param string $ocName the internal Nextcloud username
677
-	 * @param string|false $home the home directory path
678
-	 */
679
-	public function cacheUserHome($ocName, $home) {
680
-		$cacheKey = 'getHome'.$ocName;
681
-		$this->connection->writeToCache($cacheKey, $home);
682
-	}
683
-
684
-	/**
685
-	 * caches a user as existing
686
-	 * @param string $ocName the internal Nextcloud username
687
-	 */
688
-	public function cacheUserExists($ocName) {
689
-		$this->connection->writeToCache('userExists'.$ocName, true);
690
-	}
691
-
692
-	/**
693
-	 * caches the user display name
694
-	 * @param string $ocName the internal Nextcloud username
695
-	 * @param string $displayName the display name
696
-	 * @param string $displayName2 the second display name
697
-	 */
698
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
699
-		$user = $this->userManager->get($ocName);
700
-		if($user === null) {
701
-			return;
702
-		}
703
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
704
-		$cacheKeyTrunk = 'getDisplayName';
705
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
706
-	}
707
-
708
-	/**
709
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
710
-	 * @param string $name the display name of the object
711
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
712
-	 *
713
-	 * Instead of using this method directly, call
714
-	 * createAltInternalOwnCloudName($name, true)
715
-	 */
716
-	private function _createAltInternalOwnCloudNameForUsers($name) {
717
-		$attempts = 0;
718
-		//while loop is just a precaution. If a name is not generated within
719
-		//20 attempts, something else is very wrong. Avoids infinite loop.
720
-		while($attempts < 20){
721
-			$altName = $name . '_' . rand(1000,9999);
722
-			if(!\OCP\User::userExists($altName)) {
723
-				return $altName;
724
-			}
725
-			$attempts++;
726
-		}
727
-		return false;
728
-	}
729
-
730
-	/**
731
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
732
-	 * @param string $name the display name of the object
733
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
734
-	 *
735
-	 * Instead of using this method directly, call
736
-	 * createAltInternalOwnCloudName($name, false)
737
-	 *
738
-	 * Group names are also used as display names, so we do a sequential
739
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
740
-	 * "Developers"
741
-	 */
742
-	private function _createAltInternalOwnCloudNameForGroups($name) {
743
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
744
-		if(!($usedNames) || count($usedNames) === 0) {
745
-			$lastNo = 1; //will become name_2
746
-		} else {
747
-			natsort($usedNames);
748
-			$lastName = array_pop($usedNames);
749
-			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
750
-		}
751
-		$altName = $name.'_'.strval($lastNo+1);
752
-		unset($usedNames);
753
-
754
-		$attempts = 1;
755
-		while($attempts < 21){
756
-			// Check to be really sure it is unique
757
-			// while loop is just a precaution. If a name is not generated within
758
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
759
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
760
-				return $altName;
761
-			}
762
-			$altName = $name . '_' . ($lastNo + $attempts);
763
-			$attempts++;
764
-		}
765
-		return false;
766
-	}
767
-
768
-	/**
769
-	 * creates a unique name for internal Nextcloud use.
770
-	 * @param string $name the display name of the object
771
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
772
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
773
-	 */
774
-	private function createAltInternalOwnCloudName($name, $isUser) {
775
-		$originalTTL = $this->connection->ldapCacheTTL;
776
-		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
777
-		if($isUser) {
778
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
779
-		} else {
780
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
781
-		}
782
-		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
783
-
784
-		return $altName;
785
-	}
786
-
787
-	/**
788
-	 * fetches a list of users according to a provided loginName and utilizing
789
-	 * the login filter.
790
-	 *
791
-	 * @param string $loginName
792
-	 * @param array $attributes optional, list of attributes to read
793
-	 * @return array
794
-	 */
795
-	public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
796
-		$loginName = $this->escapeFilterPart($loginName);
797
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
798
-		$users = $this->fetchListOfUsers($filter, $attributes);
799
-		return $users;
800
-	}
801
-
802
-	/**
803
-	 * counts the number of users according to a provided loginName and
804
-	 * utilizing the login filter.
805
-	 *
806
-	 * @param string $loginName
807
-	 * @return int
808
-	 */
809
-	public function countUsersByLoginName($loginName) {
810
-		$loginName = $this->escapeFilterPart($loginName);
811
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
812
-		$users = $this->countUsers($filter);
813
-		return $users;
814
-	}
815
-
816
-	/**
817
-	 * @param string $filter
818
-	 * @param string|string[] $attr
819
-	 * @param int $limit
820
-	 * @param int $offset
821
-	 * @param bool $forceApplyAttributes
822
-	 * @return array
823
-	 */
824
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
825
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
826
-		$recordsToUpdate = $ldapRecords;
827
-		if(!$forceApplyAttributes) {
828
-			$isBackgroundJobModeAjax = $this->config
829
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
830
-			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
831
-				$newlyMapped = false;
832
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
833
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
834
-			});
835
-		}
836
-		$this->batchApplyUserAttributes($recordsToUpdate);
837
-		return $this->fetchList($ldapRecords, (count($attr) > 1));
838
-	}
839
-
840
-	/**
841
-	 * provided with an array of LDAP user records the method will fetch the
842
-	 * user object and requests it to process the freshly fetched attributes and
843
-	 * and their values
844
-	 * @param array $ldapRecords
845
-	 */
846
-	public function batchApplyUserAttributes(array $ldapRecords){
847
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
848
-		foreach($ldapRecords as $userRecord) {
849
-			if(!isset($userRecord[$displayNameAttribute])) {
850
-				// displayName is obligatory
851
-				continue;
852
-			}
853
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
854
-			if($ocName === false) {
855
-				continue;
856
-			}
857
-			$this->cacheUserExists($ocName);
858
-			$user = $this->userManager->get($ocName);
859
-			if($user instanceof OfflineUser) {
860
-				$user->unmark();
861
-				$user = $this->userManager->get($ocName);
862
-			}
863
-			if ($user !== null) {
864
-				$user->processAttributes($userRecord);
865
-			} else {
866
-				\OC::$server->getLogger()->debug(
867
-					"The ldap user manager returned null for $ocName",
868
-					['app'=>'user_ldap']
869
-				);
870
-			}
871
-		}
872
-	}
873
-
874
-	/**
875
-	 * @param string $filter
876
-	 * @param string|string[] $attr
877
-	 * @param int $limit
878
-	 * @param int $offset
879
-	 * @return array
880
-	 */
881
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
882
-		return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
883
-	}
884
-
885
-	/**
886
-	 * @param array $list
887
-	 * @param bool $manyAttributes
888
-	 * @return array
889
-	 */
890
-	private function fetchList($list, $manyAttributes) {
891
-		if(is_array($list)) {
892
-			if($manyAttributes) {
893
-				return $list;
894
-			} else {
895
-				$list = array_reduce($list, function($carry, $item) {
896
-					$attribute = array_keys($item)[0];
897
-					$carry[] = $item[$attribute][0];
898
-					return $carry;
899
-				}, array());
900
-				return array_unique($list, SORT_LOCALE_STRING);
901
-			}
902
-		}
903
-
904
-		//error cause actually, maybe throw an exception in future.
905
-		return array();
906
-	}
907
-
908
-	/**
909
-	 * executes an LDAP search, optimized for Users
910
-	 * @param string $filter the LDAP filter for the search
911
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
912
-	 * @param integer $limit
913
-	 * @param integer $offset
914
-	 * @return array with the search result
915
-	 *
916
-	 * Executes an LDAP search
917
-	 */
918
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
919
-		return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
920
-	}
921
-
922
-	/**
923
-	 * @param string $filter
924
-	 * @param string|string[] $attr
925
-	 * @param int $limit
926
-	 * @param int $offset
927
-	 * @return false|int
928
-	 */
929
-	public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
930
-		return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
931
-	}
932
-
933
-	/**
934
-	 * executes an LDAP search, optimized for Groups
935
-	 * @param string $filter the LDAP filter for the search
936
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
937
-	 * @param integer $limit
938
-	 * @param integer $offset
939
-	 * @return array with the search result
940
-	 *
941
-	 * Executes an LDAP search
942
-	 */
943
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
944
-		return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
945
-	}
946
-
947
-	/**
948
-	 * returns the number of available groups
949
-	 * @param string $filter the LDAP search filter
950
-	 * @param string[] $attr optional
951
-	 * @param int|null $limit
952
-	 * @param int|null $offset
953
-	 * @return int|bool
954
-	 */
955
-	public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
956
-		return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
957
-	}
958
-
959
-	/**
960
-	 * returns the number of available objects on the base DN
961
-	 *
962
-	 * @param int|null $limit
963
-	 * @param int|null $offset
964
-	 * @return int|bool
965
-	 */
966
-	public function countObjects($limit = null, $offset = null) {
967
-		return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
968
-	}
969
-
970
-	/**
971
-	 * Returns the LDAP handler
972
-	 * @throws \OC\ServerNotAvailableException
973
-	 */
974
-
975
-	/**
976
-	 * @return mixed
977
-	 * @throws \OC\ServerNotAvailableException
978
-	 */
979
-	private function invokeLDAPMethod() {
980
-		$arguments = func_get_args();
981
-		$command = array_shift($arguments);
982
-		$cr = array_shift($arguments);
983
-		if (!method_exists($this->ldap, $command)) {
984
-			return null;
985
-		}
986
-		array_unshift($arguments, $cr);
987
-		// php no longer supports call-time pass-by-reference
988
-		// thus cannot support controlPagedResultResponse as the third argument
989
-		// is a reference
990
-		$doMethod = function () use ($command, &$arguments) {
991
-			if ($command == 'controlPagedResultResponse') {
992
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
993
-			} else {
994
-				return call_user_func_array(array($this->ldap, $command), $arguments);
995
-			}
996
-		};
997
-		try {
998
-			$ret = $doMethod();
999
-		} catch (ServerNotAvailableException $e) {
1000
-			/* Server connection lost, attempt to reestablish it
341
+    /**
342
+     * Set password for an LDAP user identified by a DN
343
+     *
344
+     * @param string $userDN the user in question
345
+     * @param string $password the new password
346
+     * @return bool
347
+     * @throws HintException
348
+     * @throws \Exception
349
+     */
350
+    public function setPassword($userDN, $password) {
351
+        if(intval($this->connection->turnOnPasswordChange) !== 1) {
352
+            throw new \Exception('LDAP password changes are disabled.');
353
+        }
354
+        $cr = $this->connection->getConnectionResource();
355
+        if(!$this->ldap->isResource($cr)) {
356
+            //LDAP not available
357
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
358
+            return false;
359
+        }
360
+        try {
361
+            return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
362
+        } catch(ConstraintViolationException $e) {
363
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
364
+        }
365
+    }
366
+
367
+    /**
368
+     * checks whether the given attributes value is probably a DN
369
+     * @param string $attr the attribute in question
370
+     * @return boolean if so true, otherwise false
371
+     */
372
+    private function resemblesDN($attr) {
373
+        $resemblingAttributes = array(
374
+            'dn',
375
+            'uniquemember',
376
+            'member',
377
+            // memberOf is an "operational" attribute, without a definition in any RFC
378
+            'memberof'
379
+        );
380
+        return in_array($attr, $resemblingAttributes);
381
+    }
382
+
383
+    /**
384
+     * checks whether the given string is probably a DN
385
+     * @param string $string
386
+     * @return boolean
387
+     */
388
+    public function stringResemblesDN($string) {
389
+        $r = $this->ldap->explodeDN($string, 0);
390
+        // if exploding a DN succeeds and does not end up in
391
+        // an empty array except for $r[count] being 0.
392
+        return (is_array($r) && count($r) > 1);
393
+    }
394
+
395
+    /**
396
+     * returns a DN-string that is cleaned from not domain parts, e.g.
397
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
398
+     * becomes dc=foobar,dc=server,dc=org
399
+     * @param string $dn
400
+     * @return string
401
+     */
402
+    public function getDomainDNFromDN($dn) {
403
+        $allParts = $this->ldap->explodeDN($dn, 0);
404
+        if($allParts === false) {
405
+            //not a valid DN
406
+            return '';
407
+        }
408
+        $domainParts = array();
409
+        $dcFound = false;
410
+        foreach($allParts as $part) {
411
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
412
+                $dcFound = true;
413
+            }
414
+            if($dcFound) {
415
+                $domainParts[] = $part;
416
+            }
417
+        }
418
+        $domainDN = implode(',', $domainParts);
419
+        return $domainDN;
420
+    }
421
+
422
+    /**
423
+     * returns the LDAP DN for the given internal Nextcloud name of the group
424
+     * @param string $name the Nextcloud name in question
425
+     * @return string|false LDAP DN on success, otherwise false
426
+     */
427
+    public function groupname2dn($name) {
428
+        return $this->groupMapper->getDNByName($name);
429
+    }
430
+
431
+    /**
432
+     * returns the LDAP DN for the given internal Nextcloud name of the user
433
+     * @param string $name the Nextcloud name in question
434
+     * @return string|false with the LDAP DN on success, otherwise false
435
+     */
436
+    public function username2dn($name) {
437
+        $fdn = $this->userMapper->getDNByName($name);
438
+
439
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
440
+        //server setups
441
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442
+            return $fdn;
443
+        }
444
+
445
+        return false;
446
+    }
447
+
448
+    /**
449
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
450
+     * @param string $fdn the dn of the group object
451
+     * @param string $ldapName optional, the display name of the object
452
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
453
+     */
454
+    public function dn2groupname($fdn, $ldapName = null) {
455
+        //To avoid bypassing the base DN settings under certain circumstances
456
+        //with the group support, check whether the provided DN matches one of
457
+        //the given Bases
458
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459
+            return false;
460
+        }
461
+
462
+        return $this->dn2ocname($fdn, $ldapName, false);
463
+    }
464
+
465
+    /**
466
+     * accepts an array of group DNs and tests whether they match the user
467
+     * filter by doing read operations against the group entries. Returns an
468
+     * array of DNs that match the filter.
469
+     *
470
+     * @param string[] $groupDNs
471
+     * @return string[]
472
+     */
473
+    public function groupsMatchFilter($groupDNs) {
474
+        $validGroupDNs = [];
475
+        foreach($groupDNs as $dn) {
476
+            $cacheKey = 'groupsMatchFilter-'.$dn;
477
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
478
+            if(!is_null($groupMatchFilter)) {
479
+                if($groupMatchFilter) {
480
+                    $validGroupDNs[] = $dn;
481
+                }
482
+                continue;
483
+            }
484
+
485
+            // Check the base DN first. If this is not met already, we don't
486
+            // need to ask the server at all.
487
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488
+                $this->connection->writeToCache($cacheKey, false);
489
+                continue;
490
+            }
491
+
492
+            $result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
493
+            if(is_array($result)) {
494
+                $this->connection->writeToCache($cacheKey, true);
495
+                $validGroupDNs[] = $dn;
496
+            } else {
497
+                $this->connection->writeToCache($cacheKey, false);
498
+            }
499
+
500
+        }
501
+        return $validGroupDNs;
502
+    }
503
+
504
+    /**
505
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
506
+     * @param string $dn the dn of the user object
507
+     * @param string $ldapName optional, the display name of the object
508
+     * @return string|false with with the name to use in Nextcloud
509
+     */
510
+    public function dn2username($fdn, $ldapName = null) {
511
+        //To avoid bypassing the base DN settings under certain circumstances
512
+        //with the group support, check whether the provided DN matches one of
513
+        //the given Bases
514
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515
+            return false;
516
+        }
517
+
518
+        return $this->dn2ocname($fdn, $ldapName, true);
519
+    }
520
+
521
+    /**
522
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
523
+     *
524
+     * @param string $fdn the dn of the user object
525
+     * @param string|null $ldapName optional, the display name of the object
526
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
527
+     * @param bool|null $newlyMapped
528
+     * @param array|null $record
529
+     * @return false|string with with the name to use in Nextcloud
530
+     */
531
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
532
+        $newlyMapped = false;
533
+        if($isUser) {
534
+            $mapper = $this->getUserMapper();
535
+            $nameAttribute = $this->connection->ldapUserDisplayName;
536
+        } else {
537
+            $mapper = $this->getGroupMapper();
538
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
539
+        }
540
+
541
+        //let's try to retrieve the Nextcloud name from the mappings table
542
+        $ncName = $mapper->getNameByDN($fdn);
543
+        if(is_string($ncName)) {
544
+            return $ncName;
545
+        }
546
+
547
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
548
+        $uuid = $this->getUUID($fdn, $isUser, $record);
549
+        if(is_string($uuid)) {
550
+            $ncName = $mapper->getNameByUUID($uuid);
551
+            if(is_string($ncName)) {
552
+                $mapper->setDNbyUUID($fdn, $uuid);
553
+                return $ncName;
554
+            }
555
+        } else {
556
+            //If the UUID can't be detected something is foul.
557
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', \OCP\Util::INFO);
558
+            return false;
559
+        }
560
+
561
+        if(is_null($ldapName)) {
562
+            $ldapName = $this->readAttribute($fdn, $nameAttribute);
563
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
564
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
565
+                return false;
566
+            }
567
+            $ldapName = $ldapName[0];
568
+        }
569
+
570
+        if($isUser) {
571
+            $usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
572
+            if ($usernameAttribute !== '') {
573
+                $username = $this->readAttribute($fdn, $usernameAttribute);
574
+                $username = $username[0];
575
+            } else {
576
+                $username = $uuid;
577
+            }
578
+            $intName = $this->sanitizeUsername($username);
579
+        } else {
580
+            $intName = $ldapName;
581
+        }
582
+
583
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
584
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
585
+        //NOTE: mind, disabling cache affects only this instance! Using it
586
+        // outside of core user management will still cache the user as non-existing.
587
+        $originalTTL = $this->connection->ldapCacheTTL;
588
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
589
+        if(($isUser && !\OCP\User::userExists($intName))
590
+            || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
591
+            if($mapper->map($fdn, $intName, $uuid)) {
592
+                $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
593
+                $newlyMapped = true;
594
+                return $intName;
595
+            }
596
+        }
597
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
598
+
599
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
600
+        if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
601
+            $newlyMapped = true;
602
+            return $altName;
603
+        }
604
+
605
+        //if everything else did not help..
606
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', \OCP\Util::INFO);
607
+        return false;
608
+    }
609
+
610
+    /**
611
+     * gives back the user names as they are used ownClod internally
612
+     * @param array $ldapUsers as returned by fetchList()
613
+     * @return array an array with the user names to use in Nextcloud
614
+     *
615
+     * gives back the user names as they are used ownClod internally
616
+     */
617
+    public function nextcloudUserNames($ldapUsers) {
618
+        return $this->ldap2NextcloudNames($ldapUsers, true);
619
+    }
620
+
621
+    /**
622
+     * gives back the group names as they are used ownClod internally
623
+     * @param array $ldapGroups as returned by fetchList()
624
+     * @return array an array with the group names to use in Nextcloud
625
+     *
626
+     * gives back the group names as they are used ownClod internally
627
+     */
628
+    public function nextcloudGroupNames($ldapGroups) {
629
+        return $this->ldap2NextcloudNames($ldapGroups, false);
630
+    }
631
+
632
+    /**
633
+     * @param array $ldapObjects as returned by fetchList()
634
+     * @param bool $isUsers
635
+     * @return array
636
+     */
637
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
638
+        if($isUsers) {
639
+            $nameAttribute = $this->connection->ldapUserDisplayName;
640
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
641
+        } else {
642
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
643
+        }
644
+        $nextcloudNames = array();
645
+
646
+        foreach($ldapObjects as $ldapObject) {
647
+            $nameByLDAP = null;
648
+            if(    isset($ldapObject[$nameAttribute])
649
+                && is_array($ldapObject[$nameAttribute])
650
+                && isset($ldapObject[$nameAttribute][0])
651
+            ) {
652
+                // might be set, but not necessarily. if so, we use it.
653
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
654
+            }
655
+
656
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
657
+            if($ncName) {
658
+                $nextcloudNames[] = $ncName;
659
+                if($isUsers) {
660
+                    //cache the user names so it does not need to be retrieved
661
+                    //again later (e.g. sharing dialogue).
662
+                    if(is_null($nameByLDAP)) {
663
+                        continue;
664
+                    }
665
+                    $sndName = isset($ldapObject[$sndAttribute][0])
666
+                        ? $ldapObject[$sndAttribute][0] : '';
667
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
668
+                }
669
+            }
670
+        }
671
+        return $nextcloudNames;
672
+    }
673
+
674
+    /**
675
+     * caches the user display name
676
+     * @param string $ocName the internal Nextcloud username
677
+     * @param string|false $home the home directory path
678
+     */
679
+    public function cacheUserHome($ocName, $home) {
680
+        $cacheKey = 'getHome'.$ocName;
681
+        $this->connection->writeToCache($cacheKey, $home);
682
+    }
683
+
684
+    /**
685
+     * caches a user as existing
686
+     * @param string $ocName the internal Nextcloud username
687
+     */
688
+    public function cacheUserExists($ocName) {
689
+        $this->connection->writeToCache('userExists'.$ocName, true);
690
+    }
691
+
692
+    /**
693
+     * caches the user display name
694
+     * @param string $ocName the internal Nextcloud username
695
+     * @param string $displayName the display name
696
+     * @param string $displayName2 the second display name
697
+     */
698
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
699
+        $user = $this->userManager->get($ocName);
700
+        if($user === null) {
701
+            return;
702
+        }
703
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
704
+        $cacheKeyTrunk = 'getDisplayName';
705
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
706
+    }
707
+
708
+    /**
709
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
710
+     * @param string $name the display name of the object
711
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
712
+     *
713
+     * Instead of using this method directly, call
714
+     * createAltInternalOwnCloudName($name, true)
715
+     */
716
+    private function _createAltInternalOwnCloudNameForUsers($name) {
717
+        $attempts = 0;
718
+        //while loop is just a precaution. If a name is not generated within
719
+        //20 attempts, something else is very wrong. Avoids infinite loop.
720
+        while($attempts < 20){
721
+            $altName = $name . '_' . rand(1000,9999);
722
+            if(!\OCP\User::userExists($altName)) {
723
+                return $altName;
724
+            }
725
+            $attempts++;
726
+        }
727
+        return false;
728
+    }
729
+
730
+    /**
731
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
732
+     * @param string $name the display name of the object
733
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
734
+     *
735
+     * Instead of using this method directly, call
736
+     * createAltInternalOwnCloudName($name, false)
737
+     *
738
+     * Group names are also used as display names, so we do a sequential
739
+     * numbering, e.g. Developers_42 when there are 41 other groups called
740
+     * "Developers"
741
+     */
742
+    private function _createAltInternalOwnCloudNameForGroups($name) {
743
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
744
+        if(!($usedNames) || count($usedNames) === 0) {
745
+            $lastNo = 1; //will become name_2
746
+        } else {
747
+            natsort($usedNames);
748
+            $lastName = array_pop($usedNames);
749
+            $lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
750
+        }
751
+        $altName = $name.'_'.strval($lastNo+1);
752
+        unset($usedNames);
753
+
754
+        $attempts = 1;
755
+        while($attempts < 21){
756
+            // Check to be really sure it is unique
757
+            // while loop is just a precaution. If a name is not generated within
758
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
759
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
760
+                return $altName;
761
+            }
762
+            $altName = $name . '_' . ($lastNo + $attempts);
763
+            $attempts++;
764
+        }
765
+        return false;
766
+    }
767
+
768
+    /**
769
+     * creates a unique name for internal Nextcloud use.
770
+     * @param string $name the display name of the object
771
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
772
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
773
+     */
774
+    private function createAltInternalOwnCloudName($name, $isUser) {
775
+        $originalTTL = $this->connection->ldapCacheTTL;
776
+        $this->connection->setConfiguration(array('ldapCacheTTL' => 0));
777
+        if($isUser) {
778
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
779
+        } else {
780
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
781
+        }
782
+        $this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
783
+
784
+        return $altName;
785
+    }
786
+
787
+    /**
788
+     * fetches a list of users according to a provided loginName and utilizing
789
+     * the login filter.
790
+     *
791
+     * @param string $loginName
792
+     * @param array $attributes optional, list of attributes to read
793
+     * @return array
794
+     */
795
+    public function fetchUsersByLoginName($loginName, $attributes = array('dn')) {
796
+        $loginName = $this->escapeFilterPart($loginName);
797
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
798
+        $users = $this->fetchListOfUsers($filter, $attributes);
799
+        return $users;
800
+    }
801
+
802
+    /**
803
+     * counts the number of users according to a provided loginName and
804
+     * utilizing the login filter.
805
+     *
806
+     * @param string $loginName
807
+     * @return int
808
+     */
809
+    public function countUsersByLoginName($loginName) {
810
+        $loginName = $this->escapeFilterPart($loginName);
811
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
812
+        $users = $this->countUsers($filter);
813
+        return $users;
814
+    }
815
+
816
+    /**
817
+     * @param string $filter
818
+     * @param string|string[] $attr
819
+     * @param int $limit
820
+     * @param int $offset
821
+     * @param bool $forceApplyAttributes
822
+     * @return array
823
+     */
824
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
825
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
826
+        $recordsToUpdate = $ldapRecords;
827
+        if(!$forceApplyAttributes) {
828
+            $isBackgroundJobModeAjax = $this->config
829
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
830
+            $recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
831
+                $newlyMapped = false;
832
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
833
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
834
+            });
835
+        }
836
+        $this->batchApplyUserAttributes($recordsToUpdate);
837
+        return $this->fetchList($ldapRecords, (count($attr) > 1));
838
+    }
839
+
840
+    /**
841
+     * provided with an array of LDAP user records the method will fetch the
842
+     * user object and requests it to process the freshly fetched attributes and
843
+     * and their values
844
+     * @param array $ldapRecords
845
+     */
846
+    public function batchApplyUserAttributes(array $ldapRecords){
847
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
848
+        foreach($ldapRecords as $userRecord) {
849
+            if(!isset($userRecord[$displayNameAttribute])) {
850
+                // displayName is obligatory
851
+                continue;
852
+            }
853
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
854
+            if($ocName === false) {
855
+                continue;
856
+            }
857
+            $this->cacheUserExists($ocName);
858
+            $user = $this->userManager->get($ocName);
859
+            if($user instanceof OfflineUser) {
860
+                $user->unmark();
861
+                $user = $this->userManager->get($ocName);
862
+            }
863
+            if ($user !== null) {
864
+                $user->processAttributes($userRecord);
865
+            } else {
866
+                \OC::$server->getLogger()->debug(
867
+                    "The ldap user manager returned null for $ocName",
868
+                    ['app'=>'user_ldap']
869
+                );
870
+            }
871
+        }
872
+    }
873
+
874
+    /**
875
+     * @param string $filter
876
+     * @param string|string[] $attr
877
+     * @param int $limit
878
+     * @param int $offset
879
+     * @return array
880
+     */
881
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
882
+        return $this->fetchList($this->searchGroups($filter, $attr, $limit, $offset), (count($attr) > 1));
883
+    }
884
+
885
+    /**
886
+     * @param array $list
887
+     * @param bool $manyAttributes
888
+     * @return array
889
+     */
890
+    private function fetchList($list, $manyAttributes) {
891
+        if(is_array($list)) {
892
+            if($manyAttributes) {
893
+                return $list;
894
+            } else {
895
+                $list = array_reduce($list, function($carry, $item) {
896
+                    $attribute = array_keys($item)[0];
897
+                    $carry[] = $item[$attribute][0];
898
+                    return $carry;
899
+                }, array());
900
+                return array_unique($list, SORT_LOCALE_STRING);
901
+            }
902
+        }
903
+
904
+        //error cause actually, maybe throw an exception in future.
905
+        return array();
906
+    }
907
+
908
+    /**
909
+     * executes an LDAP search, optimized for Users
910
+     * @param string $filter the LDAP filter for the search
911
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
912
+     * @param integer $limit
913
+     * @param integer $offset
914
+     * @return array with the search result
915
+     *
916
+     * Executes an LDAP search
917
+     */
918
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
919
+        return $this->search($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
920
+    }
921
+
922
+    /**
923
+     * @param string $filter
924
+     * @param string|string[] $attr
925
+     * @param int $limit
926
+     * @param int $offset
927
+     * @return false|int
928
+     */
929
+    public function countUsers($filter, $attr = array('dn'), $limit = null, $offset = null) {
930
+        return $this->count($filter, $this->connection->ldapBaseUsers, $attr, $limit, $offset);
931
+    }
932
+
933
+    /**
934
+     * executes an LDAP search, optimized for Groups
935
+     * @param string $filter the LDAP filter for the search
936
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
937
+     * @param integer $limit
938
+     * @param integer $offset
939
+     * @return array with the search result
940
+     *
941
+     * Executes an LDAP search
942
+     */
943
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
944
+        return $this->search($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
945
+    }
946
+
947
+    /**
948
+     * returns the number of available groups
949
+     * @param string $filter the LDAP search filter
950
+     * @param string[] $attr optional
951
+     * @param int|null $limit
952
+     * @param int|null $offset
953
+     * @return int|bool
954
+     */
955
+    public function countGroups($filter, $attr = array('dn'), $limit = null, $offset = null) {
956
+        return $this->count($filter, $this->connection->ldapBaseGroups, $attr, $limit, $offset);
957
+    }
958
+
959
+    /**
960
+     * returns the number of available objects on the base DN
961
+     *
962
+     * @param int|null $limit
963
+     * @param int|null $offset
964
+     * @return int|bool
965
+     */
966
+    public function countObjects($limit = null, $offset = null) {
967
+        return $this->count('objectclass=*', $this->connection->ldapBase, array('dn'), $limit, $offset);
968
+    }
969
+
970
+    /**
971
+     * Returns the LDAP handler
972
+     * @throws \OC\ServerNotAvailableException
973
+     */
974
+
975
+    /**
976
+     * @return mixed
977
+     * @throws \OC\ServerNotAvailableException
978
+     */
979
+    private function invokeLDAPMethod() {
980
+        $arguments = func_get_args();
981
+        $command = array_shift($arguments);
982
+        $cr = array_shift($arguments);
983
+        if (!method_exists($this->ldap, $command)) {
984
+            return null;
985
+        }
986
+        array_unshift($arguments, $cr);
987
+        // php no longer supports call-time pass-by-reference
988
+        // thus cannot support controlPagedResultResponse as the third argument
989
+        // is a reference
990
+        $doMethod = function () use ($command, &$arguments) {
991
+            if ($command == 'controlPagedResultResponse') {
992
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
993
+            } else {
994
+                return call_user_func_array(array($this->ldap, $command), $arguments);
995
+            }
996
+        };
997
+        try {
998
+            $ret = $doMethod();
999
+        } catch (ServerNotAvailableException $e) {
1000
+            /* Server connection lost, attempt to reestablish it
1001 1001
 			 * Maybe implement exponential backoff?
1002 1002
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1003 1003
 			 */
1004
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
1005
-			$this->connection->resetConnectionResource();
1006
-			$cr = $this->connection->getConnectionResource();
1007
-
1008
-			if(!$this->ldap->isResource($cr)) {
1009
-				// Seems like we didn't find any resource.
1010
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1011
-				throw $e;
1012
-			}
1013
-
1014
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1015
-			$ret = $doMethod();
1016
-		}
1017
-		return $ret;
1018
-	}
1019
-
1020
-	/**
1021
-	 * retrieved. Results will according to the order in the array.
1022
-	 * @param int $limit optional, maximum results to be counted
1023
-	 * @param int $offset optional, a starting point
1024
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1025
-	 * second | false if not successful
1026
-	 * @throws \OC\ServerNotAvailableException
1027
-	 */
1028
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1029
-		if(!is_null($attr) && !is_array($attr)) {
1030
-			$attr = array(mb_strtolower($attr, 'UTF-8'));
1031
-		}
1032
-
1033
-		// See if we have a resource, in case not cancel with message
1034
-		$cr = $this->connection->getConnectionResource();
1035
-		if(!$this->ldap->isResource($cr)) {
1036
-			// Seems like we didn't find any resource.
1037
-			// Return an empty array just like before.
1038
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
1039
-			return false;
1040
-		}
1041
-
1042
-		//check whether paged search should be attempted
1043
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
1044
-
1045
-		$linkResources = array_pad(array(), count($base), $cr);
1046
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1047
-		// cannot use $cr anymore, might have changed in the previous call!
1048
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1049
-		if(!is_array($sr) || $error !== 0) {
1050
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1051
-			return false;
1052
-		}
1053
-
1054
-		return array($sr, $pagedSearchOK);
1055
-	}
1056
-
1057
-	/**
1058
-	 * processes an LDAP paged search operation
1059
-	 * @param array $sr the array containing the LDAP search resources
1060
-	 * @param string $filter the LDAP filter for the search
1061
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1062
-	 * @param int $iFoundItems number of results in the single search operation
1063
-	 * @param int $limit maximum results to be counted
1064
-	 * @param int $offset a starting point
1065
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1066
-	 * @param bool $skipHandling required for paged search when cookies to
1067
-	 * prior results need to be gained
1068
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1069
-	 */
1070
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1071
-		$cookie = null;
1072
-		if($pagedSearchOK) {
1073
-			$cr = $this->connection->getConnectionResource();
1074
-			foreach($sr as $key => $res) {
1075
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1076
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1077
-				}
1078
-			}
1079
-
1080
-			//browsing through prior pages to get the cookie for the new one
1081
-			if($skipHandling) {
1082
-				return false;
1083
-			}
1084
-			// if count is bigger, then the server does not support
1085
-			// paged search. Instead, he did a normal search. We set a
1086
-			// flag here, so the callee knows how to deal with it.
1087
-			if($iFoundItems <= $limit) {
1088
-				$this->pagedSearchedSuccessful = true;
1089
-			}
1090
-		} else {
1091
-			if(!is_null($limit)) {
1092
-				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1093
-			}
1094
-		}
1095
-		/* ++ Fixing RHDS searches with pages with zero results ++
1004
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", \OCP\Util::DEBUG);
1005
+            $this->connection->resetConnectionResource();
1006
+            $cr = $this->connection->getConnectionResource();
1007
+
1008
+            if(!$this->ldap->isResource($cr)) {
1009
+                // Seems like we didn't find any resource.
1010
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1011
+                throw $e;
1012
+            }
1013
+
1014
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1015
+            $ret = $doMethod();
1016
+        }
1017
+        return $ret;
1018
+    }
1019
+
1020
+    /**
1021
+     * retrieved. Results will according to the order in the array.
1022
+     * @param int $limit optional, maximum results to be counted
1023
+     * @param int $offset optional, a starting point
1024
+     * @return array|false array with the search result as first value and pagedSearchOK as
1025
+     * second | false if not successful
1026
+     * @throws \OC\ServerNotAvailableException
1027
+     */
1028
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1029
+        if(!is_null($attr) && !is_array($attr)) {
1030
+            $attr = array(mb_strtolower($attr, 'UTF-8'));
1031
+        }
1032
+
1033
+        // See if we have a resource, in case not cancel with message
1034
+        $cr = $this->connection->getConnectionResource();
1035
+        if(!$this->ldap->isResource($cr)) {
1036
+            // Seems like we didn't find any resource.
1037
+            // Return an empty array just like before.
1038
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
1039
+            return false;
1040
+        }
1041
+
1042
+        //check whether paged search should be attempted
1043
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, intval($limit), $offset);
1044
+
1045
+        $linkResources = array_pad(array(), count($base), $cr);
1046
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1047
+        // cannot use $cr anymore, might have changed in the previous call!
1048
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1049
+        if(!is_array($sr) || $error !== 0) {
1050
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1051
+            return false;
1052
+        }
1053
+
1054
+        return array($sr, $pagedSearchOK);
1055
+    }
1056
+
1057
+    /**
1058
+     * processes an LDAP paged search operation
1059
+     * @param array $sr the array containing the LDAP search resources
1060
+     * @param string $filter the LDAP filter for the search
1061
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1062
+     * @param int $iFoundItems number of results in the single search operation
1063
+     * @param int $limit maximum results to be counted
1064
+     * @param int $offset a starting point
1065
+     * @param bool $pagedSearchOK whether a paged search has been executed
1066
+     * @param bool $skipHandling required for paged search when cookies to
1067
+     * prior results need to be gained
1068
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1069
+     */
1070
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1071
+        $cookie = null;
1072
+        if($pagedSearchOK) {
1073
+            $cr = $this->connection->getConnectionResource();
1074
+            foreach($sr as $key => $res) {
1075
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1076
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1077
+                }
1078
+            }
1079
+
1080
+            //browsing through prior pages to get the cookie for the new one
1081
+            if($skipHandling) {
1082
+                return false;
1083
+            }
1084
+            // if count is bigger, then the server does not support
1085
+            // paged search. Instead, he did a normal search. We set a
1086
+            // flag here, so the callee knows how to deal with it.
1087
+            if($iFoundItems <= $limit) {
1088
+                $this->pagedSearchedSuccessful = true;
1089
+            }
1090
+        } else {
1091
+            if(!is_null($limit)) {
1092
+                \OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1093
+            }
1094
+        }
1095
+        /* ++ Fixing RHDS searches with pages with zero results ++
1096 1096
 		 * Return cookie status. If we don't have more pages, with RHDS
1097 1097
 		 * cookie is null, with openldap cookie is an empty string and
1098 1098
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1099 1099
 		 */
1100
-		return !empty($cookie) || $cookie === '0';
1101
-	}
1102
-
1103
-	/**
1104
-	 * executes an LDAP search, but counts the results only
1105
-	 * @param string $filter the LDAP filter for the search
1106
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1107
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1108
-	 * retrieved. Results will according to the order in the array.
1109
-	 * @param int $limit optional, maximum results to be counted
1110
-	 * @param int $offset optional, a starting point
1111
-	 * @param bool $skipHandling indicates whether the pages search operation is
1112
-	 * completed
1113
-	 * @return int|false Integer or false if the search could not be initialized
1114
-	 *
1115
-	 */
1116
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1117
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1118
-
1119
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1120
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1121
-			$limitPerPage = $limit;
1122
-		}
1123
-
1124
-		$counter = 0;
1125
-		$count = null;
1126
-		$this->connection->getConnectionResource();
1127
-
1128
-		do {
1129
-			$search = $this->executeSearch($filter, $base, $attr,
1130
-										   $limitPerPage, $offset);
1131
-			if($search === false) {
1132
-				return $counter > 0 ? $counter : false;
1133
-			}
1134
-			list($sr, $pagedSearchOK) = $search;
1135
-
1136
-			/* ++ Fixing RHDS searches with pages with zero results ++
1100
+        return !empty($cookie) || $cookie === '0';
1101
+    }
1102
+
1103
+    /**
1104
+     * executes an LDAP search, but counts the results only
1105
+     * @param string $filter the LDAP filter for the search
1106
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1107
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1108
+     * retrieved. Results will according to the order in the array.
1109
+     * @param int $limit optional, maximum results to be counted
1110
+     * @param int $offset optional, a starting point
1111
+     * @param bool $skipHandling indicates whether the pages search operation is
1112
+     * completed
1113
+     * @return int|false Integer or false if the search could not be initialized
1114
+     *
1115
+     */
1116
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1117
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1118
+
1119
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1120
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1121
+            $limitPerPage = $limit;
1122
+        }
1123
+
1124
+        $counter = 0;
1125
+        $count = null;
1126
+        $this->connection->getConnectionResource();
1127
+
1128
+        do {
1129
+            $search = $this->executeSearch($filter, $base, $attr,
1130
+                                            $limitPerPage, $offset);
1131
+            if($search === false) {
1132
+                return $counter > 0 ? $counter : false;
1133
+            }
1134
+            list($sr, $pagedSearchOK) = $search;
1135
+
1136
+            /* ++ Fixing RHDS searches with pages with zero results ++
1137 1137
 			 * countEntriesInSearchResults() method signature changed
1138 1138
 			 * by removing $limit and &$hasHitLimit parameters
1139 1139
 			 */
1140
-			$count = $this->countEntriesInSearchResults($sr);
1141
-			$counter += $count;
1140
+            $count = $this->countEntriesInSearchResults($sr);
1141
+            $counter += $count;
1142 1142
 
1143
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1144
-										$offset, $pagedSearchOK, $skipHandling);
1145
-			$offset += $limitPerPage;
1146
-			/* ++ Fixing RHDS searches with pages with zero results ++
1143
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1144
+                                        $offset, $pagedSearchOK, $skipHandling);
1145
+            $offset += $limitPerPage;
1146
+            /* ++ Fixing RHDS searches with pages with zero results ++
1147 1147
 			 * Continue now depends on $hasMorePages value
1148 1148
 			 */
1149
-			$continue = $pagedSearchOK && $hasMorePages;
1150
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1151
-
1152
-		return $counter;
1153
-	}
1154
-
1155
-	/**
1156
-	 * @param array $searchResults
1157
-	 * @return int
1158
-	 */
1159
-	private function countEntriesInSearchResults($searchResults) {
1160
-		$counter = 0;
1161
-
1162
-		foreach($searchResults as $res) {
1163
-			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1164
-			$counter += $count;
1165
-		}
1166
-
1167
-		return $counter;
1168
-	}
1169
-
1170
-	/**
1171
-	 * Executes an LDAP search
1172
-	 * @param string $filter the LDAP filter for the search
1173
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1174
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1175
-	 * @param int $limit
1176
-	 * @param int $offset
1177
-	 * @param bool $skipHandling
1178
-	 * @return array with the search result
1179
-	 */
1180
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1181
-		$limitPerPage = intval($this->connection->ldapPagingSize);
1182
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1183
-			$limitPerPage = $limit;
1184
-		}
1185
-
1186
-		/* ++ Fixing RHDS searches with pages with zero results ++
1149
+            $continue = $pagedSearchOK && $hasMorePages;
1150
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1151
+
1152
+        return $counter;
1153
+    }
1154
+
1155
+    /**
1156
+     * @param array $searchResults
1157
+     * @return int
1158
+     */
1159
+    private function countEntriesInSearchResults($searchResults) {
1160
+        $counter = 0;
1161
+
1162
+        foreach($searchResults as $res) {
1163
+            $count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1164
+            $counter += $count;
1165
+        }
1166
+
1167
+        return $counter;
1168
+    }
1169
+
1170
+    /**
1171
+     * Executes an LDAP search
1172
+     * @param string $filter the LDAP filter for the search
1173
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1174
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1175
+     * @param int $limit
1176
+     * @param int $offset
1177
+     * @param bool $skipHandling
1178
+     * @return array with the search result
1179
+     */
1180
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1181
+        $limitPerPage = intval($this->connection->ldapPagingSize);
1182
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1183
+            $limitPerPage = $limit;
1184
+        }
1185
+
1186
+        /* ++ Fixing RHDS searches with pages with zero results ++
1187 1187
 		 * As we can have pages with zero results and/or pages with less
1188 1188
 		 * than $limit results but with a still valid server 'cookie',
1189 1189
 		 * loops through until we get $continue equals true and
1190 1190
 		 * $findings['count'] < $limit
1191 1191
 		 */
1192
-		$findings = array();
1193
-		$savedoffset = $offset;
1194
-		do {
1195
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1196
-			if($search === false) {
1197
-				return array();
1198
-			}
1199
-			list($sr, $pagedSearchOK) = $search;
1200
-			$cr = $this->connection->getConnectionResource();
1201
-
1202
-			if($skipHandling) {
1203
-				//i.e. result do not need to be fetched, we just need the cookie
1204
-				//thus pass 1 or any other value as $iFoundItems because it is not
1205
-				//used
1206
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1207
-								$offset, $pagedSearchOK,
1208
-								$skipHandling);
1209
-				return array();
1210
-			}
1211
-
1212
-			$iFoundItems = 0;
1213
-			foreach($sr as $res) {
1214
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1215
-				$iFoundItems = max($iFoundItems, $findings['count']);
1216
-				unset($findings['count']);
1217
-			}
1218
-
1219
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1220
-				$limitPerPage, $offset, $pagedSearchOK,
1221
-										$skipHandling);
1222
-			$offset += $limitPerPage;
1223
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1224
-		// reseting offset
1225
-		$offset = $savedoffset;
1226
-
1227
-		// if we're here, probably no connection resource is returned.
1228
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1229
-		if(is_null($findings)) {
1230
-			return array();
1231
-		}
1232
-
1233
-		if(!is_null($attr)) {
1234
-			$selection = array();
1235
-			$i = 0;
1236
-			foreach($findings as $item) {
1237
-				if(!is_array($item)) {
1238
-					continue;
1239
-				}
1240
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1241
-				foreach($attr as $key) {
1242
-					$key = mb_strtolower($key, 'UTF-8');
1243
-					if(isset($item[$key])) {
1244
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1245
-							unset($item[$key]['count']);
1246
-						}
1247
-						if($key !== 'dn') {
1248
-							$selection[$i][$key] = $this->resemblesDN($key) ?
1249
-								$this->helper->sanitizeDN($item[$key])
1250
-								: $key === 'objectguid' || $key === 'guid' ?
1251
-									$selection[$i][$key] = $this->convertObjectGUID2Str($item[$key])
1252
-									: $item[$key];
1253
-						} else {
1254
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1255
-						}
1256
-					}
1257
-
1258
-				}
1259
-				$i++;
1260
-			}
1261
-			$findings = $selection;
1262
-		}
1263
-		//we slice the findings, when
1264
-		//a) paged search unsuccessful, though attempted
1265
-		//b) no paged search, but limit set
1266
-		if((!$this->getPagedSearchResultState()
1267
-			&& $pagedSearchOK)
1268
-			|| (
1269
-				!$pagedSearchOK
1270
-				&& !is_null($limit)
1271
-			)
1272
-		) {
1273
-			$findings = array_slice($findings, intval($offset), $limit);
1274
-		}
1275
-		return $findings;
1276
-	}
1277
-
1278
-	/**
1279
-	 * @param string $name
1280
-	 * @return bool|mixed|string
1281
-	 */
1282
-	public function sanitizeUsername($name) {
1283
-		if($this->connection->ldapIgnoreNamingRules) {
1284
-			return $name;
1285
-		}
1286
-
1287
-		// Transliteration
1288
-		// latin characters to ASCII
1289
-		$name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1290
-
1291
-		// Replacements
1292
-		$name = str_replace(' ', '_', $name);
1293
-
1294
-		// Every remaining disallowed characters will be removed
1295
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1296
-
1297
-		return $name;
1298
-	}
1299
-
1300
-	/**
1301
-	* escapes (user provided) parts for LDAP filter
1302
-	* @param string $input, the provided value
1303
-	* @param bool $allowAsterisk whether in * at the beginning should be preserved
1304
-	* @return string the escaped string
1305
-	*/
1306
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1307
-		$asterisk = '';
1308
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1309
-			$asterisk = '*';
1310
-			$input = mb_substr($input, 1, null, 'UTF-8');
1311
-		}
1312
-		$search  = array('*', '\\', '(', ')');
1313
-		$replace = array('\\*', '\\\\', '\\(', '\\)');
1314
-		return $asterisk . str_replace($search, $replace, $input);
1315
-	}
1316
-
1317
-	/**
1318
-	 * combines the input filters with AND
1319
-	 * @param string[] $filters the filters to connect
1320
-	 * @return string the combined filter
1321
-	 */
1322
-	public function combineFilterWithAnd($filters) {
1323
-		return $this->combineFilter($filters, '&');
1324
-	}
1325
-
1326
-	/**
1327
-	 * combines the input filters with OR
1328
-	 * @param string[] $filters the filters to connect
1329
-	 * @return string the combined filter
1330
-	 * Combines Filter arguments with OR
1331
-	 */
1332
-	public function combineFilterWithOr($filters) {
1333
-		return $this->combineFilter($filters, '|');
1334
-	}
1335
-
1336
-	/**
1337
-	 * combines the input filters with given operator
1338
-	 * @param string[] $filters the filters to connect
1339
-	 * @param string $operator either & or |
1340
-	 * @return string the combined filter
1341
-	 */
1342
-	private function combineFilter($filters, $operator) {
1343
-		$combinedFilter = '('.$operator;
1344
-		foreach($filters as $filter) {
1345
-			if ($filter !== '' && $filter[0] !== '(') {
1346
-				$filter = '('.$filter.')';
1347
-			}
1348
-			$combinedFilter.=$filter;
1349
-		}
1350
-		$combinedFilter.=')';
1351
-		return $combinedFilter;
1352
-	}
1353
-
1354
-	/**
1355
-	 * creates a filter part for to perform search for users
1356
-	 * @param string $search the search term
1357
-	 * @return string the final filter part to use in LDAP searches
1358
-	 */
1359
-	public function getFilterPartForUserSearch($search) {
1360
-		return $this->getFilterPartForSearch($search,
1361
-			$this->connection->ldapAttributesForUserSearch,
1362
-			$this->connection->ldapUserDisplayName);
1363
-	}
1364
-
1365
-	/**
1366
-	 * creates a filter part for to perform search for groups
1367
-	 * @param string $search the search term
1368
-	 * @return string the final filter part to use in LDAP searches
1369
-	 */
1370
-	public function getFilterPartForGroupSearch($search) {
1371
-		return $this->getFilterPartForSearch($search,
1372
-			$this->connection->ldapAttributesForGroupSearch,
1373
-			$this->connection->ldapGroupDisplayName);
1374
-	}
1375
-
1376
-	/**
1377
-	 * creates a filter part for searches by splitting up the given search
1378
-	 * string into single words
1379
-	 * @param string $search the search term
1380
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1381
-	 * otherwise it does not make sense :)
1382
-	 * @return string the final filter part to use in LDAP searches
1383
-	 * @throws \Exception
1384
-	 */
1385
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1386
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1387
-			throw new \Exception('searchAttributes must be an array with at least two string');
1388
-		}
1389
-		$searchWords = explode(' ', trim($search));
1390
-		$wordFilters = array();
1391
-		foreach($searchWords as $word) {
1392
-			$word = $this->prepareSearchTerm($word);
1393
-			//every word needs to appear at least once
1394
-			$wordMatchOneAttrFilters = array();
1395
-			foreach($searchAttributes as $attr) {
1396
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1397
-			}
1398
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1399
-		}
1400
-		return $this->combineFilterWithAnd($wordFilters);
1401
-	}
1402
-
1403
-	/**
1404
-	 * creates a filter part for searches
1405
-	 * @param string $search the search term
1406
-	 * @param string[]|null $searchAttributes
1407
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1408
-	 * did not define search attributes. Typically the display name attribute.
1409
-	 * @return string the final filter part to use in LDAP searches
1410
-	 */
1411
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1412
-		$filter = array();
1413
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1414
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1415
-			try {
1416
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1417
-			} catch(\Exception $e) {
1418
-				\OCP\Util::writeLog(
1419
-					'user_ldap',
1420
-					'Creating advanced filter for search failed, falling back to simple method.',
1421
-					\OCP\Util::INFO
1422
-				);
1423
-			}
1424
-		}
1425
-
1426
-		$search = $this->prepareSearchTerm($search);
1427
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1428
-			if ($fallbackAttribute === '') {
1429
-				return '';
1430
-			}
1431
-			$filter[] = $fallbackAttribute . '=' . $search;
1432
-		} else {
1433
-			foreach($searchAttributes as $attribute) {
1434
-				$filter[] = $attribute . '=' . $search;
1435
-			}
1436
-		}
1437
-		if(count($filter) === 1) {
1438
-			return '('.$filter[0].')';
1439
-		}
1440
-		return $this->combineFilterWithOr($filter);
1441
-	}
1442
-
1443
-	/**
1444
-	 * returns the search term depending on whether we are allowed
1445
-	 * list users found by ldap with the current input appended by
1446
-	 * a *
1447
-	 * @return string
1448
-	 */
1449
-	private function prepareSearchTerm($term) {
1450
-		$config = \OC::$server->getConfig();
1451
-
1452
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1453
-
1454
-		$result = $term;
1455
-		if ($term === '') {
1456
-			$result = '*';
1457
-		} else if ($allowEnum !== 'no') {
1458
-			$result = $term . '*';
1459
-		}
1460
-		return $result;
1461
-	}
1462
-
1463
-	/**
1464
-	 * returns the filter used for counting users
1465
-	 * @return string
1466
-	 */
1467
-	public function getFilterForUserCount() {
1468
-		$filter = $this->combineFilterWithAnd(array(
1469
-			$this->connection->ldapUserFilter,
1470
-			$this->connection->ldapUserDisplayName . '=*'
1471
-		));
1472
-
1473
-		return $filter;
1474
-	}
1475
-
1476
-	/**
1477
-	 * @param string $name
1478
-	 * @param string $password
1479
-	 * @return bool
1480
-	 */
1481
-	public function areCredentialsValid($name, $password) {
1482
-		$name = $this->helper->DNasBaseParameter($name);
1483
-		$testConnection = clone $this->connection;
1484
-		$credentials = array(
1485
-			'ldapAgentName' => $name,
1486
-			'ldapAgentPassword' => $password
1487
-		);
1488
-		if(!$testConnection->setConfiguration($credentials)) {
1489
-			return false;
1490
-		}
1491
-		return $testConnection->bind();
1492
-	}
1493
-
1494
-	/**
1495
-	 * reverse lookup of a DN given a known UUID
1496
-	 *
1497
-	 * @param string $uuid
1498
-	 * @return string
1499
-	 * @throws \Exception
1500
-	 */
1501
-	public function getUserDnByUuid($uuid) {
1502
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1503
-		$filter       = $this->connection->ldapUserFilter;
1504
-		$base         = $this->connection->ldapBaseUsers;
1505
-
1506
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1507
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1508
-			// existing DN to be able to reliably detect it.
1509
-			$result = $this->search($filter, $base, ['dn'], 1);
1510
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1511
-				throw new \Exception('Cannot determine UUID attribute');
1512
-			}
1513
-			$dn = $result[0]['dn'][0];
1514
-			if(!$this->detectUuidAttribute($dn, true)) {
1515
-				throw new \Exception('Cannot determine UUID attribute');
1516
-			}
1517
-		} else {
1518
-			// The UUID attribute is either known or an override is given.
1519
-			// By calling this method we ensure that $this->connection->$uuidAttr
1520
-			// is definitely set
1521
-			if(!$this->detectUuidAttribute('', true)) {
1522
-				throw new \Exception('Cannot determine UUID attribute');
1523
-			}
1524
-		}
1525
-
1526
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1527
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1528
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1529
-		}
1530
-
1531
-		$filter = $uuidAttr . '=' . $uuid;
1532
-		$result = $this->searchUsers($filter, ['dn'], 2);
1533
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1534
-			// we put the count into account to make sure that this is
1535
-			// really unique
1536
-			return $result[0]['dn'][0];
1537
-		}
1538
-
1539
-		throw new \Exception('Cannot determine UUID attribute');
1540
-	}
1541
-
1542
-	/**
1543
-	 * auto-detects the directory's UUID attribute
1544
-	 *
1545
-	 * @param string $dn a known DN used to check against
1546
-	 * @param bool $isUser
1547
-	 * @param bool $force the detection should be run, even if it is not set to auto
1548
-	 * @param array|null $ldapRecord
1549
-	 * @return bool true on success, false otherwise
1550
-	 */
1551
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1552
-		if($isUser) {
1553
-			$uuidAttr     = 'ldapUuidUserAttribute';
1554
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1555
-		} else {
1556
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1557
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1558
-		}
1559
-
1560
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1561
-			return true;
1562
-		}
1563
-
1564
-		if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1565
-			$this->connection->$uuidAttr = $uuidOverride;
1566
-			return true;
1567
-		}
1568
-
1569
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1570
-			if($ldapRecord !== null) {
1571
-				// we have the info from LDAP already, we don't need to talk to the server again
1572
-				if(isset($ldapRecord[$attribute])) {
1573
-					$this->connection->$uuidAttr = $attribute;
1574
-					return true;
1575
-				} else {
1576
-					continue;
1577
-				}
1578
-			}
1579
-
1580
-			$value = $this->readAttribute($dn, $attribute);
1581
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1582
-				\OCP\Util::writeLog('user_ldap',
1583
-									'Setting '.$attribute.' as '.$uuidAttr,
1584
-									\OCP\Util::DEBUG);
1585
-				$this->connection->$uuidAttr = $attribute;
1586
-				return true;
1587
-			}
1588
-		}
1589
-		\OCP\Util::writeLog('user_ldap',
1590
-							'Could not autodetect the UUID attribute',
1591
-							\OCP\Util::ERROR);
1592
-
1593
-		return false;
1594
-	}
1595
-
1596
-	/**
1597
-	 * @param string $dn
1598
-	 * @param bool $isUser
1599
-	 * @param null $ldapRecord
1600
-	 * @return bool|string
1601
-	 */
1602
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1603
-		if($isUser) {
1604
-			$uuidAttr     = 'ldapUuidUserAttribute';
1605
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1606
-		} else {
1607
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1608
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1609
-		}
1610
-
1611
-		$uuid = false;
1612
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1613
-			$attr = $this->connection->$uuidAttr;
1614
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1615
-			if( !is_array($uuid)
1616
-				&& $uuidOverride !== ''
1617
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1618
-			{
1619
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1620
-					? $ldapRecord[$this->connection->$uuidAttr]
1621
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1622
-			}
1623
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1624
-				$uuid = $uuid[0];
1625
-			}
1626
-		}
1627
-
1628
-		return $uuid;
1629
-	}
1630
-
1631
-	/**
1632
-	 * converts a binary ObjectGUID into a string representation
1633
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1634
-	 * @return string
1635
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1636
-	 */
1637
-	private function convertObjectGUID2Str($oguid) {
1638
-		$hex_guid = bin2hex($oguid);
1639
-		$hex_guid_to_guid_str = '';
1640
-		for($k = 1; $k <= 4; ++$k) {
1641
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1642
-		}
1643
-		$hex_guid_to_guid_str .= '-';
1644
-		for($k = 1; $k <= 2; ++$k) {
1645
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1646
-		}
1647
-		$hex_guid_to_guid_str .= '-';
1648
-		for($k = 1; $k <= 2; ++$k) {
1649
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1650
-		}
1651
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1652
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1653
-
1654
-		return strtoupper($hex_guid_to_guid_str);
1655
-	}
1656
-
1657
-	/**
1658
-	 * the first three blocks of the string-converted GUID happen to be in
1659
-	 * reverse order. In order to use it in a filter, this needs to be
1660
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1661
-	 * to every two hax figures.
1662
-	 *
1663
-	 * If an invalid string is passed, it will be returned without change.
1664
-	 *
1665
-	 * @param string $guid
1666
-	 * @return string
1667
-	 */
1668
-	public function formatGuid2ForFilterUser($guid) {
1669
-		if(!is_string($guid)) {
1670
-			throw new \InvalidArgumentException('String expected');
1671
-		}
1672
-		$blocks = explode('-', $guid);
1673
-		if(count($blocks) !== 5) {
1674
-			/*
1192
+        $findings = array();
1193
+        $savedoffset = $offset;
1194
+        do {
1195
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1196
+            if($search === false) {
1197
+                return array();
1198
+            }
1199
+            list($sr, $pagedSearchOK) = $search;
1200
+            $cr = $this->connection->getConnectionResource();
1201
+
1202
+            if($skipHandling) {
1203
+                //i.e. result do not need to be fetched, we just need the cookie
1204
+                //thus pass 1 or any other value as $iFoundItems because it is not
1205
+                //used
1206
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1207
+                                $offset, $pagedSearchOK,
1208
+                                $skipHandling);
1209
+                return array();
1210
+            }
1211
+
1212
+            $iFoundItems = 0;
1213
+            foreach($sr as $res) {
1214
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1215
+                $iFoundItems = max($iFoundItems, $findings['count']);
1216
+                unset($findings['count']);
1217
+            }
1218
+
1219
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1220
+                $limitPerPage, $offset, $pagedSearchOK,
1221
+                                        $skipHandling);
1222
+            $offset += $limitPerPage;
1223
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1224
+        // reseting offset
1225
+        $offset = $savedoffset;
1226
+
1227
+        // if we're here, probably no connection resource is returned.
1228
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1229
+        if(is_null($findings)) {
1230
+            return array();
1231
+        }
1232
+
1233
+        if(!is_null($attr)) {
1234
+            $selection = array();
1235
+            $i = 0;
1236
+            foreach($findings as $item) {
1237
+                if(!is_array($item)) {
1238
+                    continue;
1239
+                }
1240
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1241
+                foreach($attr as $key) {
1242
+                    $key = mb_strtolower($key, 'UTF-8');
1243
+                    if(isset($item[$key])) {
1244
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1245
+                            unset($item[$key]['count']);
1246
+                        }
1247
+                        if($key !== 'dn') {
1248
+                            $selection[$i][$key] = $this->resemblesDN($key) ?
1249
+                                $this->helper->sanitizeDN($item[$key])
1250
+                                : $key === 'objectguid' || $key === 'guid' ?
1251
+                                    $selection[$i][$key] = $this->convertObjectGUID2Str($item[$key])
1252
+                                    : $item[$key];
1253
+                        } else {
1254
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1255
+                        }
1256
+                    }
1257
+
1258
+                }
1259
+                $i++;
1260
+            }
1261
+            $findings = $selection;
1262
+        }
1263
+        //we slice the findings, when
1264
+        //a) paged search unsuccessful, though attempted
1265
+        //b) no paged search, but limit set
1266
+        if((!$this->getPagedSearchResultState()
1267
+            && $pagedSearchOK)
1268
+            || (
1269
+                !$pagedSearchOK
1270
+                && !is_null($limit)
1271
+            )
1272
+        ) {
1273
+            $findings = array_slice($findings, intval($offset), $limit);
1274
+        }
1275
+        return $findings;
1276
+    }
1277
+
1278
+    /**
1279
+     * @param string $name
1280
+     * @return bool|mixed|string
1281
+     */
1282
+    public function sanitizeUsername($name) {
1283
+        if($this->connection->ldapIgnoreNamingRules) {
1284
+            return $name;
1285
+        }
1286
+
1287
+        // Transliteration
1288
+        // latin characters to ASCII
1289
+        $name = iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1290
+
1291
+        // Replacements
1292
+        $name = str_replace(' ', '_', $name);
1293
+
1294
+        // Every remaining disallowed characters will be removed
1295
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1296
+
1297
+        return $name;
1298
+    }
1299
+
1300
+    /**
1301
+     * escapes (user provided) parts for LDAP filter
1302
+     * @param string $input, the provided value
1303
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1304
+     * @return string the escaped string
1305
+     */
1306
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1307
+        $asterisk = '';
1308
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1309
+            $asterisk = '*';
1310
+            $input = mb_substr($input, 1, null, 'UTF-8');
1311
+        }
1312
+        $search  = array('*', '\\', '(', ')');
1313
+        $replace = array('\\*', '\\\\', '\\(', '\\)');
1314
+        return $asterisk . str_replace($search, $replace, $input);
1315
+    }
1316
+
1317
+    /**
1318
+     * combines the input filters with AND
1319
+     * @param string[] $filters the filters to connect
1320
+     * @return string the combined filter
1321
+     */
1322
+    public function combineFilterWithAnd($filters) {
1323
+        return $this->combineFilter($filters, '&');
1324
+    }
1325
+
1326
+    /**
1327
+     * combines the input filters with OR
1328
+     * @param string[] $filters the filters to connect
1329
+     * @return string the combined filter
1330
+     * Combines Filter arguments with OR
1331
+     */
1332
+    public function combineFilterWithOr($filters) {
1333
+        return $this->combineFilter($filters, '|');
1334
+    }
1335
+
1336
+    /**
1337
+     * combines the input filters with given operator
1338
+     * @param string[] $filters the filters to connect
1339
+     * @param string $operator either & or |
1340
+     * @return string the combined filter
1341
+     */
1342
+    private function combineFilter($filters, $operator) {
1343
+        $combinedFilter = '('.$operator;
1344
+        foreach($filters as $filter) {
1345
+            if ($filter !== '' && $filter[0] !== '(') {
1346
+                $filter = '('.$filter.')';
1347
+            }
1348
+            $combinedFilter.=$filter;
1349
+        }
1350
+        $combinedFilter.=')';
1351
+        return $combinedFilter;
1352
+    }
1353
+
1354
+    /**
1355
+     * creates a filter part for to perform search for users
1356
+     * @param string $search the search term
1357
+     * @return string the final filter part to use in LDAP searches
1358
+     */
1359
+    public function getFilterPartForUserSearch($search) {
1360
+        return $this->getFilterPartForSearch($search,
1361
+            $this->connection->ldapAttributesForUserSearch,
1362
+            $this->connection->ldapUserDisplayName);
1363
+    }
1364
+
1365
+    /**
1366
+     * creates a filter part for to perform search for groups
1367
+     * @param string $search the search term
1368
+     * @return string the final filter part to use in LDAP searches
1369
+     */
1370
+    public function getFilterPartForGroupSearch($search) {
1371
+        return $this->getFilterPartForSearch($search,
1372
+            $this->connection->ldapAttributesForGroupSearch,
1373
+            $this->connection->ldapGroupDisplayName);
1374
+    }
1375
+
1376
+    /**
1377
+     * creates a filter part for searches by splitting up the given search
1378
+     * string into single words
1379
+     * @param string $search the search term
1380
+     * @param string[] $searchAttributes needs to have at least two attributes,
1381
+     * otherwise it does not make sense :)
1382
+     * @return string the final filter part to use in LDAP searches
1383
+     * @throws \Exception
1384
+     */
1385
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1386
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1387
+            throw new \Exception('searchAttributes must be an array with at least two string');
1388
+        }
1389
+        $searchWords = explode(' ', trim($search));
1390
+        $wordFilters = array();
1391
+        foreach($searchWords as $word) {
1392
+            $word = $this->prepareSearchTerm($word);
1393
+            //every word needs to appear at least once
1394
+            $wordMatchOneAttrFilters = array();
1395
+            foreach($searchAttributes as $attr) {
1396
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1397
+            }
1398
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1399
+        }
1400
+        return $this->combineFilterWithAnd($wordFilters);
1401
+    }
1402
+
1403
+    /**
1404
+     * creates a filter part for searches
1405
+     * @param string $search the search term
1406
+     * @param string[]|null $searchAttributes
1407
+     * @param string $fallbackAttribute a fallback attribute in case the user
1408
+     * did not define search attributes. Typically the display name attribute.
1409
+     * @return string the final filter part to use in LDAP searches
1410
+     */
1411
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1412
+        $filter = array();
1413
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1414
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1415
+            try {
1416
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1417
+            } catch(\Exception $e) {
1418
+                \OCP\Util::writeLog(
1419
+                    'user_ldap',
1420
+                    'Creating advanced filter for search failed, falling back to simple method.',
1421
+                    \OCP\Util::INFO
1422
+                );
1423
+            }
1424
+        }
1425
+
1426
+        $search = $this->prepareSearchTerm($search);
1427
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1428
+            if ($fallbackAttribute === '') {
1429
+                return '';
1430
+            }
1431
+            $filter[] = $fallbackAttribute . '=' . $search;
1432
+        } else {
1433
+            foreach($searchAttributes as $attribute) {
1434
+                $filter[] = $attribute . '=' . $search;
1435
+            }
1436
+        }
1437
+        if(count($filter) === 1) {
1438
+            return '('.$filter[0].')';
1439
+        }
1440
+        return $this->combineFilterWithOr($filter);
1441
+    }
1442
+
1443
+    /**
1444
+     * returns the search term depending on whether we are allowed
1445
+     * list users found by ldap with the current input appended by
1446
+     * a *
1447
+     * @return string
1448
+     */
1449
+    private function prepareSearchTerm($term) {
1450
+        $config = \OC::$server->getConfig();
1451
+
1452
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1453
+
1454
+        $result = $term;
1455
+        if ($term === '') {
1456
+            $result = '*';
1457
+        } else if ($allowEnum !== 'no') {
1458
+            $result = $term . '*';
1459
+        }
1460
+        return $result;
1461
+    }
1462
+
1463
+    /**
1464
+     * returns the filter used for counting users
1465
+     * @return string
1466
+     */
1467
+    public function getFilterForUserCount() {
1468
+        $filter = $this->combineFilterWithAnd(array(
1469
+            $this->connection->ldapUserFilter,
1470
+            $this->connection->ldapUserDisplayName . '=*'
1471
+        ));
1472
+
1473
+        return $filter;
1474
+    }
1475
+
1476
+    /**
1477
+     * @param string $name
1478
+     * @param string $password
1479
+     * @return bool
1480
+     */
1481
+    public function areCredentialsValid($name, $password) {
1482
+        $name = $this->helper->DNasBaseParameter($name);
1483
+        $testConnection = clone $this->connection;
1484
+        $credentials = array(
1485
+            'ldapAgentName' => $name,
1486
+            'ldapAgentPassword' => $password
1487
+        );
1488
+        if(!$testConnection->setConfiguration($credentials)) {
1489
+            return false;
1490
+        }
1491
+        return $testConnection->bind();
1492
+    }
1493
+
1494
+    /**
1495
+     * reverse lookup of a DN given a known UUID
1496
+     *
1497
+     * @param string $uuid
1498
+     * @return string
1499
+     * @throws \Exception
1500
+     */
1501
+    public function getUserDnByUuid($uuid) {
1502
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1503
+        $filter       = $this->connection->ldapUserFilter;
1504
+        $base         = $this->connection->ldapBaseUsers;
1505
+
1506
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1507
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1508
+            // existing DN to be able to reliably detect it.
1509
+            $result = $this->search($filter, $base, ['dn'], 1);
1510
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1511
+                throw new \Exception('Cannot determine UUID attribute');
1512
+            }
1513
+            $dn = $result[0]['dn'][0];
1514
+            if(!$this->detectUuidAttribute($dn, true)) {
1515
+                throw new \Exception('Cannot determine UUID attribute');
1516
+            }
1517
+        } else {
1518
+            // The UUID attribute is either known or an override is given.
1519
+            // By calling this method we ensure that $this->connection->$uuidAttr
1520
+            // is definitely set
1521
+            if(!$this->detectUuidAttribute('', true)) {
1522
+                throw new \Exception('Cannot determine UUID attribute');
1523
+            }
1524
+        }
1525
+
1526
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1527
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1528
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1529
+        }
1530
+
1531
+        $filter = $uuidAttr . '=' . $uuid;
1532
+        $result = $this->searchUsers($filter, ['dn'], 2);
1533
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1534
+            // we put the count into account to make sure that this is
1535
+            // really unique
1536
+            return $result[0]['dn'][0];
1537
+        }
1538
+
1539
+        throw new \Exception('Cannot determine UUID attribute');
1540
+    }
1541
+
1542
+    /**
1543
+     * auto-detects the directory's UUID attribute
1544
+     *
1545
+     * @param string $dn a known DN used to check against
1546
+     * @param bool $isUser
1547
+     * @param bool $force the detection should be run, even if it is not set to auto
1548
+     * @param array|null $ldapRecord
1549
+     * @return bool true on success, false otherwise
1550
+     */
1551
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1552
+        if($isUser) {
1553
+            $uuidAttr     = 'ldapUuidUserAttribute';
1554
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1555
+        } else {
1556
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1557
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1558
+        }
1559
+
1560
+        if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1561
+            return true;
1562
+        }
1563
+
1564
+        if (is_string($uuidOverride) && trim($uuidOverride) !== '' && !$force) {
1565
+            $this->connection->$uuidAttr = $uuidOverride;
1566
+            return true;
1567
+        }
1568
+
1569
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1570
+            if($ldapRecord !== null) {
1571
+                // we have the info from LDAP already, we don't need to talk to the server again
1572
+                if(isset($ldapRecord[$attribute])) {
1573
+                    $this->connection->$uuidAttr = $attribute;
1574
+                    return true;
1575
+                } else {
1576
+                    continue;
1577
+                }
1578
+            }
1579
+
1580
+            $value = $this->readAttribute($dn, $attribute);
1581
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1582
+                \OCP\Util::writeLog('user_ldap',
1583
+                                    'Setting '.$attribute.' as '.$uuidAttr,
1584
+                                    \OCP\Util::DEBUG);
1585
+                $this->connection->$uuidAttr = $attribute;
1586
+                return true;
1587
+            }
1588
+        }
1589
+        \OCP\Util::writeLog('user_ldap',
1590
+                            'Could not autodetect the UUID attribute',
1591
+                            \OCP\Util::ERROR);
1592
+
1593
+        return false;
1594
+    }
1595
+
1596
+    /**
1597
+     * @param string $dn
1598
+     * @param bool $isUser
1599
+     * @param null $ldapRecord
1600
+     * @return bool|string
1601
+     */
1602
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1603
+        if($isUser) {
1604
+            $uuidAttr     = 'ldapUuidUserAttribute';
1605
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1606
+        } else {
1607
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1608
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1609
+        }
1610
+
1611
+        $uuid = false;
1612
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1613
+            $attr = $this->connection->$uuidAttr;
1614
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1615
+            if( !is_array($uuid)
1616
+                && $uuidOverride !== ''
1617
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1618
+            {
1619
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1620
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1621
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1622
+            }
1623
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1624
+                $uuid = $uuid[0];
1625
+            }
1626
+        }
1627
+
1628
+        return $uuid;
1629
+    }
1630
+
1631
+    /**
1632
+     * converts a binary ObjectGUID into a string representation
1633
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1634
+     * @return string
1635
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1636
+     */
1637
+    private function convertObjectGUID2Str($oguid) {
1638
+        $hex_guid = bin2hex($oguid);
1639
+        $hex_guid_to_guid_str = '';
1640
+        for($k = 1; $k <= 4; ++$k) {
1641
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1642
+        }
1643
+        $hex_guid_to_guid_str .= '-';
1644
+        for($k = 1; $k <= 2; ++$k) {
1645
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1646
+        }
1647
+        $hex_guid_to_guid_str .= '-';
1648
+        for($k = 1; $k <= 2; ++$k) {
1649
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1650
+        }
1651
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1652
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1653
+
1654
+        return strtoupper($hex_guid_to_guid_str);
1655
+    }
1656
+
1657
+    /**
1658
+     * the first three blocks of the string-converted GUID happen to be in
1659
+     * reverse order. In order to use it in a filter, this needs to be
1660
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1661
+     * to every two hax figures.
1662
+     *
1663
+     * If an invalid string is passed, it will be returned without change.
1664
+     *
1665
+     * @param string $guid
1666
+     * @return string
1667
+     */
1668
+    public function formatGuid2ForFilterUser($guid) {
1669
+        if(!is_string($guid)) {
1670
+            throw new \InvalidArgumentException('String expected');
1671
+        }
1672
+        $blocks = explode('-', $guid);
1673
+        if(count($blocks) !== 5) {
1674
+            /*
1675 1675
 			 * Why not throw an Exception instead? This method is a utility
1676 1676
 			 * called only when trying to figure out whether a "missing" known
1677 1677
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1682,274 +1682,274 @@  discard block
 block discarded – undo
1682 1682
 			 * an exception here would kill the experience for a valid, acting
1683 1683
 			 * user. Instead we write a log message.
1684 1684
 			 */
1685
-			\OC::$server->getLogger()->info(
1686
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1687
-				'({uuid}) probably does not match UUID configuration.',
1688
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1689
-			);
1690
-			return $guid;
1691
-		}
1692
-		for($i=0; $i < 3; $i++) {
1693
-			$pairs = str_split($blocks[$i], 2);
1694
-			$pairs = array_reverse($pairs);
1695
-			$blocks[$i] = implode('', $pairs);
1696
-		}
1697
-		for($i=0; $i < 5; $i++) {
1698
-			$pairs = str_split($blocks[$i], 2);
1699
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1700
-		}
1701
-		return implode('', $blocks);
1702
-	}
1703
-
1704
-	/**
1705
-	 * gets a SID of the domain of the given dn
1706
-	 * @param string $dn
1707
-	 * @return string|bool
1708
-	 */
1709
-	public function getSID($dn) {
1710
-		$domainDN = $this->getDomainDNFromDN($dn);
1711
-		$cacheKey = 'getSID-'.$domainDN;
1712
-		$sid = $this->connection->getFromCache($cacheKey);
1713
-		if(!is_null($sid)) {
1714
-			return $sid;
1715
-		}
1716
-
1717
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1718
-		if(!is_array($objectSid) || empty($objectSid)) {
1719
-			$this->connection->writeToCache($cacheKey, false);
1720
-			return false;
1721
-		}
1722
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1723
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1724
-
1725
-		return $domainObjectSid;
1726
-	}
1727
-
1728
-	/**
1729
-	 * converts a binary SID into a string representation
1730
-	 * @param string $sid
1731
-	 * @return string
1732
-	 */
1733
-	public function convertSID2Str($sid) {
1734
-		// The format of a SID binary string is as follows:
1735
-		// 1 byte for the revision level
1736
-		// 1 byte for the number n of variable sub-ids
1737
-		// 6 bytes for identifier authority value
1738
-		// n*4 bytes for n sub-ids
1739
-		//
1740
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1741
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1742
-		$revision = ord($sid[0]);
1743
-		$numberSubID = ord($sid[1]);
1744
-
1745
-		$subIdStart = 8; // 1 + 1 + 6
1746
-		$subIdLength = 4;
1747
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1748
-			// Incorrect number of bytes present.
1749
-			return '';
1750
-		}
1751
-
1752
-		// 6 bytes = 48 bits can be represented using floats without loss of
1753
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1754
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1755
-
1756
-		$subIDs = array();
1757
-		for ($i = 0; $i < $numberSubID; $i++) {
1758
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1759
-			$subIDs[] = sprintf('%u', $subID[1]);
1760
-		}
1761
-
1762
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1763
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1764
-	}
1765
-
1766
-	/**
1767
-	 * checks if the given DN is part of the given base DN(s)
1768
-	 * @param string $dn the DN
1769
-	 * @param string[] $bases array containing the allowed base DN or DNs
1770
-	 * @return bool
1771
-	 */
1772
-	public function isDNPartOfBase($dn, $bases) {
1773
-		$belongsToBase = false;
1774
-		$bases = $this->helper->sanitizeDN($bases);
1775
-
1776
-		foreach($bases as $base) {
1777
-			$belongsToBase = true;
1778
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1779
-				$belongsToBase = false;
1780
-			}
1781
-			if($belongsToBase) {
1782
-				break;
1783
-			}
1784
-		}
1785
-		return $belongsToBase;
1786
-	}
1787
-
1788
-	/**
1789
-	 * resets a running Paged Search operation
1790
-	 */
1791
-	private function abandonPagedSearch() {
1792
-		if($this->connection->hasPagedResultSupport) {
1793
-			$cr = $this->connection->getConnectionResource();
1794
-			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1795
-			$this->getPagedSearchResultState();
1796
-			$this->lastCookie = '';
1797
-			$this->cookies = array();
1798
-		}
1799
-	}
1800
-
1801
-	/**
1802
-	 * get a cookie for the next LDAP paged search
1803
-	 * @param string $base a string with the base DN for the search
1804
-	 * @param string $filter the search filter to identify the correct search
1805
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1806
-	 * @param int $offset the offset for the new search to identify the correct search really good
1807
-	 * @return string containing the key or empty if none is cached
1808
-	 */
1809
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1810
-		if($offset === 0) {
1811
-			return '';
1812
-		}
1813
-		$offset -= $limit;
1814
-		//we work with cache here
1815
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1816
-		$cookie = '';
1817
-		if(isset($this->cookies[$cacheKey])) {
1818
-			$cookie = $this->cookies[$cacheKey];
1819
-			if(is_null($cookie)) {
1820
-				$cookie = '';
1821
-			}
1822
-		}
1823
-		return $cookie;
1824
-	}
1825
-
1826
-	/**
1827
-	 * checks whether an LDAP paged search operation has more pages that can be
1828
-	 * retrieved, typically when offset and limit are provided.
1829
-	 *
1830
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1831
-	 * be reset by other operations. Best, call it immediately after a search(),
1832
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
1833
-	 * well. Don't rely on it with any fetchList-method.
1834
-	 * @return bool
1835
-	 */
1836
-	public function hasMoreResults() {
1837
-		if(!$this->connection->hasPagedResultSupport) {
1838
-			return false;
1839
-		}
1840
-
1841
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1842
-			// as in RFC 2696, when all results are returned, the cookie will
1843
-			// be empty.
1844
-			return false;
1845
-		}
1846
-
1847
-		return true;
1848
-	}
1849
-
1850
-	/**
1851
-	 * set a cookie for LDAP paged search run
1852
-	 * @param string $base a string with the base DN for the search
1853
-	 * @param string $filter the search filter to identify the correct search
1854
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1855
-	 * @param int $offset the offset for the run search to identify the correct search really good
1856
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1857
-	 * @return void
1858
-	 */
1859
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1860
-		// allow '0' for 389ds
1861
-		if(!empty($cookie) || $cookie === '0') {
1862
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1863
-			$this->cookies[$cacheKey] = $cookie;
1864
-			$this->lastCookie = $cookie;
1865
-		}
1866
-	}
1867
-
1868
-	/**
1869
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1870
-	 * @return boolean|null true on success, null or false otherwise
1871
-	 */
1872
-	public function getPagedSearchResultState() {
1873
-		$result = $this->pagedSearchedSuccessful;
1874
-		$this->pagedSearchedSuccessful = null;
1875
-		return $result;
1876
-	}
1877
-
1878
-	/**
1879
-	 * Prepares a paged search, if possible
1880
-	 * @param string $filter the LDAP filter for the search
1881
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1882
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
1883
-	 * @param int $limit
1884
-	 * @param int $offset
1885
-	 * @return bool|true
1886
-	 */
1887
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1888
-		$pagedSearchOK = false;
1889
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1890
-			$offset = intval($offset); //can be null
1891
-			\OCP\Util::writeLog('user_ldap',
1892
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1893
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1894
-				\OCP\Util::DEBUG);
1895
-			//get the cookie from the search for the previous search, required by LDAP
1896
-			foreach($bases as $base) {
1897
-
1898
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1899
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1900
-					// no cookie known from a potential previous search. We need
1901
-					// to start from 0 to come to the desired page. cookie value
1902
-					// of '0' is valid, because 389ds
1903
-					$reOffset = 0;
1904
-					while($reOffset < $offset) {
1905
-						$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1906
-						$reOffset += $limit;
1907
-					}
1908
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1909
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1910
-					// '0' is valid, because 389ds
1911
-					//TODO: remember this, probably does not change in the next request...
1912
-					if(empty($cookie) && $cookie !== '0') {
1913
-						$cookie = null;
1914
-					}
1915
-				}
1916
-				if(!is_null($cookie)) {
1917
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1918
-					$this->abandonPagedSearch();
1919
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1920
-						$this->connection->getConnectionResource(), $limit,
1921
-						false, $cookie);
1922
-					if(!$pagedSearchOK) {
1923
-						return false;
1924
-					}
1925
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1926
-				} else {
1927
-					\OCP\Util::writeLog('user_ldap',
1928
-						'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1929
-						\OCP\Util::INFO);
1930
-				}
1931
-
1932
-			}
1933
-		/* ++ Fixing RHDS searches with pages with zero results ++
1685
+            \OC::$server->getLogger()->info(
1686
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1687
+                '({uuid}) probably does not match UUID configuration.',
1688
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1689
+            );
1690
+            return $guid;
1691
+        }
1692
+        for($i=0; $i < 3; $i++) {
1693
+            $pairs = str_split($blocks[$i], 2);
1694
+            $pairs = array_reverse($pairs);
1695
+            $blocks[$i] = implode('', $pairs);
1696
+        }
1697
+        for($i=0; $i < 5; $i++) {
1698
+            $pairs = str_split($blocks[$i], 2);
1699
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1700
+        }
1701
+        return implode('', $blocks);
1702
+    }
1703
+
1704
+    /**
1705
+     * gets a SID of the domain of the given dn
1706
+     * @param string $dn
1707
+     * @return string|bool
1708
+     */
1709
+    public function getSID($dn) {
1710
+        $domainDN = $this->getDomainDNFromDN($dn);
1711
+        $cacheKey = 'getSID-'.$domainDN;
1712
+        $sid = $this->connection->getFromCache($cacheKey);
1713
+        if(!is_null($sid)) {
1714
+            return $sid;
1715
+        }
1716
+
1717
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1718
+        if(!is_array($objectSid) || empty($objectSid)) {
1719
+            $this->connection->writeToCache($cacheKey, false);
1720
+            return false;
1721
+        }
1722
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1723
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1724
+
1725
+        return $domainObjectSid;
1726
+    }
1727
+
1728
+    /**
1729
+     * converts a binary SID into a string representation
1730
+     * @param string $sid
1731
+     * @return string
1732
+     */
1733
+    public function convertSID2Str($sid) {
1734
+        // The format of a SID binary string is as follows:
1735
+        // 1 byte for the revision level
1736
+        // 1 byte for the number n of variable sub-ids
1737
+        // 6 bytes for identifier authority value
1738
+        // n*4 bytes for n sub-ids
1739
+        //
1740
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1741
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1742
+        $revision = ord($sid[0]);
1743
+        $numberSubID = ord($sid[1]);
1744
+
1745
+        $subIdStart = 8; // 1 + 1 + 6
1746
+        $subIdLength = 4;
1747
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1748
+            // Incorrect number of bytes present.
1749
+            return '';
1750
+        }
1751
+
1752
+        // 6 bytes = 48 bits can be represented using floats without loss of
1753
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1754
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1755
+
1756
+        $subIDs = array();
1757
+        for ($i = 0; $i < $numberSubID; $i++) {
1758
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1759
+            $subIDs[] = sprintf('%u', $subID[1]);
1760
+        }
1761
+
1762
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1763
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1764
+    }
1765
+
1766
+    /**
1767
+     * checks if the given DN is part of the given base DN(s)
1768
+     * @param string $dn the DN
1769
+     * @param string[] $bases array containing the allowed base DN or DNs
1770
+     * @return bool
1771
+     */
1772
+    public function isDNPartOfBase($dn, $bases) {
1773
+        $belongsToBase = false;
1774
+        $bases = $this->helper->sanitizeDN($bases);
1775
+
1776
+        foreach($bases as $base) {
1777
+            $belongsToBase = true;
1778
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1779
+                $belongsToBase = false;
1780
+            }
1781
+            if($belongsToBase) {
1782
+                break;
1783
+            }
1784
+        }
1785
+        return $belongsToBase;
1786
+    }
1787
+
1788
+    /**
1789
+     * resets a running Paged Search operation
1790
+     */
1791
+    private function abandonPagedSearch() {
1792
+        if($this->connection->hasPagedResultSupport) {
1793
+            $cr = $this->connection->getConnectionResource();
1794
+            $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1795
+            $this->getPagedSearchResultState();
1796
+            $this->lastCookie = '';
1797
+            $this->cookies = array();
1798
+        }
1799
+    }
1800
+
1801
+    /**
1802
+     * get a cookie for the next LDAP paged search
1803
+     * @param string $base a string with the base DN for the search
1804
+     * @param string $filter the search filter to identify the correct search
1805
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1806
+     * @param int $offset the offset for the new search to identify the correct search really good
1807
+     * @return string containing the key or empty if none is cached
1808
+     */
1809
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1810
+        if($offset === 0) {
1811
+            return '';
1812
+        }
1813
+        $offset -= $limit;
1814
+        //we work with cache here
1815
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1816
+        $cookie = '';
1817
+        if(isset($this->cookies[$cacheKey])) {
1818
+            $cookie = $this->cookies[$cacheKey];
1819
+            if(is_null($cookie)) {
1820
+                $cookie = '';
1821
+            }
1822
+        }
1823
+        return $cookie;
1824
+    }
1825
+
1826
+    /**
1827
+     * checks whether an LDAP paged search operation has more pages that can be
1828
+     * retrieved, typically when offset and limit are provided.
1829
+     *
1830
+     * Be very careful to use it: the last cookie value, which is inspected, can
1831
+     * be reset by other operations. Best, call it immediately after a search(),
1832
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
1833
+     * well. Don't rely on it with any fetchList-method.
1834
+     * @return bool
1835
+     */
1836
+    public function hasMoreResults() {
1837
+        if(!$this->connection->hasPagedResultSupport) {
1838
+            return false;
1839
+        }
1840
+
1841
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1842
+            // as in RFC 2696, when all results are returned, the cookie will
1843
+            // be empty.
1844
+            return false;
1845
+        }
1846
+
1847
+        return true;
1848
+    }
1849
+
1850
+    /**
1851
+     * set a cookie for LDAP paged search run
1852
+     * @param string $base a string with the base DN for the search
1853
+     * @param string $filter the search filter to identify the correct search
1854
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1855
+     * @param int $offset the offset for the run search to identify the correct search really good
1856
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
1857
+     * @return void
1858
+     */
1859
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1860
+        // allow '0' for 389ds
1861
+        if(!empty($cookie) || $cookie === '0') {
1862
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1863
+            $this->cookies[$cacheKey] = $cookie;
1864
+            $this->lastCookie = $cookie;
1865
+        }
1866
+    }
1867
+
1868
+    /**
1869
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
1870
+     * @return boolean|null true on success, null or false otherwise
1871
+     */
1872
+    public function getPagedSearchResultState() {
1873
+        $result = $this->pagedSearchedSuccessful;
1874
+        $this->pagedSearchedSuccessful = null;
1875
+        return $result;
1876
+    }
1877
+
1878
+    /**
1879
+     * Prepares a paged search, if possible
1880
+     * @param string $filter the LDAP filter for the search
1881
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
1882
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
1883
+     * @param int $limit
1884
+     * @param int $offset
1885
+     * @return bool|true
1886
+     */
1887
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1888
+        $pagedSearchOK = false;
1889
+        if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1890
+            $offset = intval($offset); //can be null
1891
+            \OCP\Util::writeLog('user_ldap',
1892
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1893
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1894
+                \OCP\Util::DEBUG);
1895
+            //get the cookie from the search for the previous search, required by LDAP
1896
+            foreach($bases as $base) {
1897
+
1898
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1899
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1900
+                    // no cookie known from a potential previous search. We need
1901
+                    // to start from 0 to come to the desired page. cookie value
1902
+                    // of '0' is valid, because 389ds
1903
+                    $reOffset = 0;
1904
+                    while($reOffset < $offset) {
1905
+                        $this->search($filter, array($base), $attr, $limit, $reOffset, true);
1906
+                        $reOffset += $limit;
1907
+                    }
1908
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1909
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1910
+                    // '0' is valid, because 389ds
1911
+                    //TODO: remember this, probably does not change in the next request...
1912
+                    if(empty($cookie) && $cookie !== '0') {
1913
+                        $cookie = null;
1914
+                    }
1915
+                }
1916
+                if(!is_null($cookie)) {
1917
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1918
+                    $this->abandonPagedSearch();
1919
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1920
+                        $this->connection->getConnectionResource(), $limit,
1921
+                        false, $cookie);
1922
+                    if(!$pagedSearchOK) {
1923
+                        return false;
1924
+                    }
1925
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
1926
+                } else {
1927
+                    \OCP\Util::writeLog('user_ldap',
1928
+                        'No paged search for us, Cpt., Limit '.$limit.' Offset '.$offset,
1929
+                        \OCP\Util::INFO);
1930
+                }
1931
+
1932
+            }
1933
+        /* ++ Fixing RHDS searches with pages with zero results ++
1934 1934
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
1935 1935
 		 * due to pages with zero results.
1936 1936
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1937 1937
 		 * if we don't have a previous paged search.
1938 1938
 		 */
1939
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1940
-			// a search without limit was requested. However, if we do use
1941
-			// Paged Search once, we always must do it. This requires us to
1942
-			// initialize it with the configured page size.
1943
-			$this->abandonPagedSearch();
1944
-			// in case someone set it to 0 … use 500, otherwise no results will
1945
-			// be returned.
1946
-			$pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1947
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1948
-				$this->connection->getConnectionResource(),
1949
-				$pageSize, false, '');
1950
-		}
1951
-
1952
-		return $pagedSearchOK;
1953
-	}
1939
+        } else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1940
+            // a search without limit was requested. However, if we do use
1941
+            // Paged Search once, we always must do it. This requires us to
1942
+            // initialize it with the configured page size.
1943
+            $this->abandonPagedSearch();
1944
+            // in case someone set it to 0 … use 500, otherwise no results will
1945
+            // be returned.
1946
+            $pageSize = intval($this->connection->ldapPagingSize) > 0 ? intval($this->connection->ldapPagingSize) : 500;
1947
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1948
+                $this->connection->getConnectionResource(),
1949
+                $pageSize, false, '');
1950
+        }
1951
+
1952
+        return $pagedSearchOK;
1953
+    }
1954 1954
 
1955 1955
 }
Please login to merge, or discard this patch.
Spacing   +168 added lines, -168 removed lines patch added patch discarded remove patch
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
 	 * @return AbstractMapping
125 125
 	 */
126 126
 	public function getUserMapper() {
127
-		if(is_null($this->userMapper)) {
127
+		if (is_null($this->userMapper)) {
128 128
 			throw new \Exception('UserMapper was not assigned to this Access instance.');
129 129
 		}
130 130
 		return $this->userMapper;
@@ -144,7 +144,7 @@  discard block
 block discarded – undo
144 144
 	 * @return AbstractMapping
145 145
 	 */
146 146
 	public function getGroupMapper() {
147
-		if(is_null($this->groupMapper)) {
147
+		if (is_null($this->groupMapper)) {
148 148
 			throw new \Exception('GroupMapper was not assigned to this Access instance.');
149 149
 		}
150 150
 		return $this->groupMapper;
@@ -175,14 +175,14 @@  discard block
 block discarded – undo
175 175
 	 *          array if $attr is empty, false otherwise
176 176
 	 */
177 177
 	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
178
-		if(!$this->checkConnection()) {
178
+		if (!$this->checkConnection()) {
179 179
 			\OCP\Util::writeLog('user_ldap',
180 180
 				'No LDAP Connector assigned, access impossible for readAttribute.',
181 181
 				\OCP\Util::WARN);
182 182
 			return false;
183 183
 		}
184 184
 		$cr = $this->connection->getConnectionResource();
185
-		if(!$this->ldap->isResource($cr)) {
185
+		if (!$this->ldap->isResource($cr)) {
186 186
 			//LDAP not available
187 187
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
188 188
 			return false;
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
 		$isRangeRequest = false;
206 206
 		do {
207 207
 			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
208
-			if(is_bool($result)) {
208
+			if (is_bool($result)) {
209 209
 				// when an exists request was run and it was successful, an empty
210 210
 				// array must be returned
211 211
 				return $result ? [] : false;
@@ -222,22 +222,22 @@  discard block
 block discarded – undo
222 222
 			$result = $this->extractRangeData($result, $attr);
223 223
 			if (!empty($result)) {
224 224
 				$normalizedResult = $this->extractAttributeValuesFromResult(
225
-					[ $attr => $result['values'] ],
225
+					[$attr => $result['values']],
226 226
 					$attr
227 227
 				);
228 228
 				$values = array_merge($values, $normalizedResult);
229 229
 
230
-				if($result['rangeHigh'] === '*') {
230
+				if ($result['rangeHigh'] === '*') {
231 231
 					// when server replies with * as high range value, there are
232 232
 					// no more results left
233 233
 					return $values;
234 234
 				} else {
235
-					$low  = $result['rangeHigh'] + 1;
236
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
235
+					$low = $result['rangeHigh'] + 1;
236
+					$attrToRead = $result['attributeName'].';range='.$low.'-*';
237 237
 					$isRangeRequest = true;
238 238
 				}
239 239
 			}
240
-		} while($isRangeRequest);
240
+		} while ($isRangeRequest);
241 241
 
242 242
 		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, \OCP\Util::DEBUG);
243 243
 		return false;
@@ -262,13 +262,13 @@  discard block
 block discarded – undo
262 262
 		if (!$this->ldap->isResource($rr)) {
263 263
 			if ($attribute !== '') {
264 264
 				//do not throw this message on userExists check, irritates
265
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, \OCP\Util::DEBUG);
265
+				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN '.$dn, \OCP\Util::DEBUG);
266 266
 			}
267 267
 			//in case an error occurs , e.g. object does not exist
268 268
 			return false;
269 269
 		}
270 270
 		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
271
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', \OCP\Util::DEBUG);
271
+			\OCP\Util::writeLog('user_ldap', 'readAttribute: '.$dn.' found', \OCP\Util::DEBUG);
272 272
 			return true;
273 273
 		}
274 274
 		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
@@ -293,12 +293,12 @@  discard block
 block discarded – undo
293 293
 	 */
294 294
 	public function extractAttributeValuesFromResult($result, $attribute) {
295 295
 		$values = [];
296
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
296
+		if (isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
297 297
 			$lowercaseAttribute = strtolower($attribute);
298
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
299
-				if($this->resemblesDN($attribute)) {
298
+			for ($i = 0; $i < $result[$attribute]['count']; $i++) {
299
+				if ($this->resemblesDN($attribute)) {
300 300
 					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
301
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
301
+				} elseif ($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
302 302
 					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
303 303
 				} else {
304 304
 					$values[] = $result[$attribute][$i];
@@ -320,10 +320,10 @@  discard block
 block discarded – undo
320 320
 	 */
321 321
 	public function extractRangeData($result, $attribute) {
322 322
 		$keys = array_keys($result);
323
-		foreach($keys as $key) {
324
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
323
+		foreach ($keys as $key) {
324
+			if ($key !== $attribute && strpos($key, $attribute) === 0) {
325 325
 				$queryData = explode(';', $key);
326
-				if(strpos($queryData[1], 'range=') === 0) {
326
+				if (strpos($queryData[1], 'range=') === 0) {
327 327
 					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
328 328
 					$data = [
329 329
 						'values' => $result[$key],
@@ -348,18 +348,18 @@  discard block
 block discarded – undo
348 348
 	 * @throws \Exception
349 349
 	 */
350 350
 	public function setPassword($userDN, $password) {
351
-		if(intval($this->connection->turnOnPasswordChange) !== 1) {
351
+		if (intval($this->connection->turnOnPasswordChange) !== 1) {
352 352
 			throw new \Exception('LDAP password changes are disabled.');
353 353
 		}
354 354
 		$cr = $this->connection->getConnectionResource();
355
-		if(!$this->ldap->isResource($cr)) {
355
+		if (!$this->ldap->isResource($cr)) {
356 356
 			//LDAP not available
357 357
 			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', \OCP\Util::DEBUG);
358 358
 			return false;
359 359
 		}
360 360
 		try {
361 361
 			return @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
362
-		} catch(ConstraintViolationException $e) {
362
+		} catch (ConstraintViolationException $e) {
363 363
 			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
364 364
 		}
365 365
 	}
@@ -401,17 +401,17 @@  discard block
 block discarded – undo
401 401
 	 */
402 402
 	public function getDomainDNFromDN($dn) {
403 403
 		$allParts = $this->ldap->explodeDN($dn, 0);
404
-		if($allParts === false) {
404
+		if ($allParts === false) {
405 405
 			//not a valid DN
406 406
 			return '';
407 407
 		}
408 408
 		$domainParts = array();
409 409
 		$dcFound = false;
410
-		foreach($allParts as $part) {
411
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
410
+		foreach ($allParts as $part) {
411
+			if (!$dcFound && strpos($part, 'dc=') === 0) {
412 412
 				$dcFound = true;
413 413
 			}
414
-			if($dcFound) {
414
+			if ($dcFound) {
415 415
 				$domainParts[] = $part;
416 416
 			}
417 417
 		}
@@ -438,7 +438,7 @@  discard block
 block discarded – undo
438 438
 
439 439
 		//Check whether the DN belongs to the Base, to avoid issues on multi-
440 440
 		//server setups
441
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
441
+		if (is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
442 442
 			return $fdn;
443 443
 		}
444 444
 
@@ -455,7 +455,7 @@  discard block
 block discarded – undo
455 455
 		//To avoid bypassing the base DN settings under certain circumstances
456 456
 		//with the group support, check whether the provided DN matches one of
457 457
 		//the given Bases
458
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
458
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
459 459
 			return false;
460 460
 		}
461 461
 
@@ -472,11 +472,11 @@  discard block
 block discarded – undo
472 472
 	 */
473 473
 	public function groupsMatchFilter($groupDNs) {
474 474
 		$validGroupDNs = [];
475
-		foreach($groupDNs as $dn) {
475
+		foreach ($groupDNs as $dn) {
476 476
 			$cacheKey = 'groupsMatchFilter-'.$dn;
477 477
 			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
478
-			if(!is_null($groupMatchFilter)) {
479
-				if($groupMatchFilter) {
478
+			if (!is_null($groupMatchFilter)) {
479
+				if ($groupMatchFilter) {
480 480
 					$validGroupDNs[] = $dn;
481 481
 				}
482 482
 				continue;
@@ -484,13 +484,13 @@  discard block
 block discarded – undo
484 484
 
485 485
 			// Check the base DN first. If this is not met already, we don't
486 486
 			// need to ask the server at all.
487
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
487
+			if (!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
488 488
 				$this->connection->writeToCache($cacheKey, false);
489 489
 				continue;
490 490
 			}
491 491
 
492 492
 			$result = $this->readAttribute($dn, 'cn', $this->connection->ldapGroupFilter);
493
-			if(is_array($result)) {
493
+			if (is_array($result)) {
494 494
 				$this->connection->writeToCache($cacheKey, true);
495 495
 				$validGroupDNs[] = $dn;
496 496
 			} else {
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
 		//To avoid bypassing the base DN settings under certain circumstances
512 512
 		//with the group support, check whether the provided DN matches one of
513 513
 		//the given Bases
514
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
514
+		if (!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
515 515
 			return false;
516 516
 		}
517 517
 
@@ -530,7 +530,7 @@  discard block
 block discarded – undo
530 530
 	 */
531 531
 	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
532 532
 		$newlyMapped = false;
533
-		if($isUser) {
533
+		if ($isUser) {
534 534
 			$mapper = $this->getUserMapper();
535 535
 			$nameAttribute = $this->connection->ldapUserDisplayName;
536 536
 		} else {
@@ -540,15 +540,15 @@  discard block
 block discarded – undo
540 540
 
541 541
 		//let's try to retrieve the Nextcloud name from the mappings table
542 542
 		$ncName = $mapper->getNameByDN($fdn);
543
-		if(is_string($ncName)) {
543
+		if (is_string($ncName)) {
544 544
 			return $ncName;
545 545
 		}
546 546
 
547 547
 		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
548 548
 		$uuid = $this->getUUID($fdn, $isUser, $record);
549
-		if(is_string($uuid)) {
549
+		if (is_string($uuid)) {
550 550
 			$ncName = $mapper->getNameByUUID($uuid);
551
-			if(is_string($ncName)) {
551
+			if (is_string($ncName)) {
552 552
 				$mapper->setDNbyUUID($fdn, $uuid);
553 553
 				return $ncName;
554 554
 			}
@@ -558,16 +558,16 @@  discard block
 block discarded – undo
558 558
 			return false;
559 559
 		}
560 560
 
561
-		if(is_null($ldapName)) {
561
+		if (is_null($ldapName)) {
562 562
 			$ldapName = $this->readAttribute($fdn, $nameAttribute);
563
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
563
+			if (!isset($ldapName[0]) && empty($ldapName[0])) {
564 564
 				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.'.', \OCP\Util::INFO);
565 565
 				return false;
566 566
 			}
567 567
 			$ldapName = $ldapName[0];
568 568
 		}
569 569
 
570
-		if($isUser) {
570
+		if ($isUser) {
571 571
 			$usernameAttribute = strval($this->connection->ldapExpertUsernameAttr);
572 572
 			if ($usernameAttribute !== '') {
573 573
 				$username = $this->readAttribute($fdn, $usernameAttribute);
@@ -586,9 +586,9 @@  discard block
 block discarded – undo
586 586
 		// outside of core user management will still cache the user as non-existing.
587 587
 		$originalTTL = $this->connection->ldapCacheTTL;
588 588
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
589
-		if(($isUser && !\OCP\User::userExists($intName))
589
+		if (($isUser && !\OCP\User::userExists($intName))
590 590
 			|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))) {
591
-			if($mapper->map($fdn, $intName, $uuid)) {
591
+			if ($mapper->map($fdn, $intName, $uuid)) {
592 592
 				$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
593 593
 				$newlyMapped = true;
594 594
 				return $intName;
@@ -597,7 +597,7 @@  discard block
 block discarded – undo
597 597
 		$this->connection->setConfiguration(array('ldapCacheTTL' => $originalTTL));
598 598
 
599 599
 		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
600
-		if(is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
600
+		if (is_string($altName) && $mapper->map($fdn, $altName, $uuid)) {
601 601
 			$newlyMapped = true;
602 602
 			return $altName;
603 603
 		}
@@ -635,7 +635,7 @@  discard block
 block discarded – undo
635 635
 	 * @return array
636 636
 	 */
637 637
 	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
638
-		if($isUsers) {
638
+		if ($isUsers) {
639 639
 			$nameAttribute = $this->connection->ldapUserDisplayName;
640 640
 			$sndAttribute  = $this->connection->ldapUserDisplayName2;
641 641
 		} else {
@@ -643,9 +643,9 @@  discard block
 block discarded – undo
643 643
 		}
644 644
 		$nextcloudNames = array();
645 645
 
646
-		foreach($ldapObjects as $ldapObject) {
646
+		foreach ($ldapObjects as $ldapObject) {
647 647
 			$nameByLDAP = null;
648
-			if(    isset($ldapObject[$nameAttribute])
648
+			if (isset($ldapObject[$nameAttribute])
649 649
 				&& is_array($ldapObject[$nameAttribute])
650 650
 				&& isset($ldapObject[$nameAttribute][0])
651 651
 			) {
@@ -654,12 +654,12 @@  discard block
 block discarded – undo
654 654
 			}
655 655
 
656 656
 			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
657
-			if($ncName) {
657
+			if ($ncName) {
658 658
 				$nextcloudNames[] = $ncName;
659
-				if($isUsers) {
659
+				if ($isUsers) {
660 660
 					//cache the user names so it does not need to be retrieved
661 661
 					//again later (e.g. sharing dialogue).
662
-					if(is_null($nameByLDAP)) {
662
+					if (is_null($nameByLDAP)) {
663 663
 						continue;
664 664
 					}
665 665
 					$sndName = isset($ldapObject[$sndAttribute][0])
@@ -697,7 +697,7 @@  discard block
 block discarded – undo
697 697
 	 */
698 698
 	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
699 699
 		$user = $this->userManager->get($ocName);
700
-		if($user === null) {
700
+		if ($user === null) {
701 701
 			return;
702 702
 		}
703 703
 		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
@@ -717,9 +717,9 @@  discard block
 block discarded – undo
717 717
 		$attempts = 0;
718 718
 		//while loop is just a precaution. If a name is not generated within
719 719
 		//20 attempts, something else is very wrong. Avoids infinite loop.
720
-		while($attempts < 20){
721
-			$altName = $name . '_' . rand(1000,9999);
722
-			if(!\OCP\User::userExists($altName)) {
720
+		while ($attempts < 20) {
721
+			$altName = $name.'_'.rand(1000, 9999);
722
+			if (!\OCP\User::userExists($altName)) {
723 723
 				return $altName;
724 724
 			}
725 725
 			$attempts++;
@@ -741,25 +741,25 @@  discard block
 block discarded – undo
741 741
 	 */
742 742
 	private function _createAltInternalOwnCloudNameForGroups($name) {
743 743
 		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
744
-		if(!($usedNames) || count($usedNames) === 0) {
744
+		if (!($usedNames) || count($usedNames) === 0) {
745 745
 			$lastNo = 1; //will become name_2
746 746
 		} else {
747 747
 			natsort($usedNames);
748 748
 			$lastName = array_pop($usedNames);
749 749
 			$lastNo = intval(substr($lastName, strrpos($lastName, '_') + 1));
750 750
 		}
751
-		$altName = $name.'_'.strval($lastNo+1);
751
+		$altName = $name.'_'.strval($lastNo + 1);
752 752
 		unset($usedNames);
753 753
 
754 754
 		$attempts = 1;
755
-		while($attempts < 21){
755
+		while ($attempts < 21) {
756 756
 			// Check to be really sure it is unique
757 757
 			// while loop is just a precaution. If a name is not generated within
758 758
 			// 20 attempts, something else is very wrong. Avoids infinite loop.
759
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
759
+			if (!\OC::$server->getGroupManager()->groupExists($altName)) {
760 760
 				return $altName;
761 761
 			}
762
-			$altName = $name . '_' . ($lastNo + $attempts);
762
+			$altName = $name.'_'.($lastNo + $attempts);
763 763
 			$attempts++;
764 764
 		}
765 765
 		return false;
@@ -774,7 +774,7 @@  discard block
 block discarded – undo
774 774
 	private function createAltInternalOwnCloudName($name, $isUser) {
775 775
 		$originalTTL = $this->connection->ldapCacheTTL;
776 776
 		$this->connection->setConfiguration(array('ldapCacheTTL' => 0));
777
-		if($isUser) {
777
+		if ($isUser) {
778 778
 			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
779 779
 		} else {
780 780
 			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
@@ -824,7 +824,7 @@  discard block
 block discarded – undo
824 824
 	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
825 825
 		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
826 826
 		$recordsToUpdate = $ldapRecords;
827
-		if(!$forceApplyAttributes) {
827
+		if (!$forceApplyAttributes) {
828 828
 			$isBackgroundJobModeAjax = $this->config
829 829
 					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
830 830
 			$recordsToUpdate = array_filter($ldapRecords, function($record) use ($isBackgroundJobModeAjax) {
@@ -843,20 +843,20 @@  discard block
 block discarded – undo
843 843
 	 * and their values
844 844
 	 * @param array $ldapRecords
845 845
 	 */
846
-	public function batchApplyUserAttributes(array $ldapRecords){
846
+	public function batchApplyUserAttributes(array $ldapRecords) {
847 847
 		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
848
-		foreach($ldapRecords as $userRecord) {
849
-			if(!isset($userRecord[$displayNameAttribute])) {
848
+		foreach ($ldapRecords as $userRecord) {
849
+			if (!isset($userRecord[$displayNameAttribute])) {
850 850
 				// displayName is obligatory
851 851
 				continue;
852 852
 			}
853
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
854
-			if($ocName === false) {
853
+			$ocName = $this->dn2ocname($userRecord['dn'][0], null, true);
854
+			if ($ocName === false) {
855 855
 				continue;
856 856
 			}
857 857
 			$this->cacheUserExists($ocName);
858 858
 			$user = $this->userManager->get($ocName);
859
-			if($user instanceof OfflineUser) {
859
+			if ($user instanceof OfflineUser) {
860 860
 				$user->unmark();
861 861
 				$user = $this->userManager->get($ocName);
862 862
 			}
@@ -888,8 +888,8 @@  discard block
 block discarded – undo
888 888
 	 * @return array
889 889
 	 */
890 890
 	private function fetchList($list, $manyAttributes) {
891
-		if(is_array($list)) {
892
-			if($manyAttributes) {
891
+		if (is_array($list)) {
892
+			if ($manyAttributes) {
893 893
 				return $list;
894 894
 			} else {
895 895
 				$list = array_reduce($list, function($carry, $item) {
@@ -987,7 +987,7 @@  discard block
 block discarded – undo
987 987
 		// php no longer supports call-time pass-by-reference
988 988
 		// thus cannot support controlPagedResultResponse as the third argument
989 989
 		// is a reference
990
-		$doMethod = function () use ($command, &$arguments) {
990
+		$doMethod = function() use ($command, &$arguments) {
991 991
 			if ($command == 'controlPagedResultResponse') {
992 992
 				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
993 993
 			} else {
@@ -1005,7 +1005,7 @@  discard block
 block discarded – undo
1005 1005
 			$this->connection->resetConnectionResource();
1006 1006
 			$cr = $this->connection->getConnectionResource();
1007 1007
 
1008
-			if(!$this->ldap->isResource($cr)) {
1008
+			if (!$this->ldap->isResource($cr)) {
1009 1009
 				// Seems like we didn't find any resource.
1010 1010
 				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", \OCP\Util::DEBUG);
1011 1011
 				throw $e;
@@ -1026,13 +1026,13 @@  discard block
 block discarded – undo
1026 1026
 	 * @throws \OC\ServerNotAvailableException
1027 1027
 	 */
1028 1028
 	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1029
-		if(!is_null($attr) && !is_array($attr)) {
1029
+		if (!is_null($attr) && !is_array($attr)) {
1030 1030
 			$attr = array(mb_strtolower($attr, 'UTF-8'));
1031 1031
 		}
1032 1032
 
1033 1033
 		// See if we have a resource, in case not cancel with message
1034 1034
 		$cr = $this->connection->getConnectionResource();
1035
-		if(!$this->ldap->isResource($cr)) {
1035
+		if (!$this->ldap->isResource($cr)) {
1036 1036
 			// Seems like we didn't find any resource.
1037 1037
 			// Return an empty array just like before.
1038 1038
 			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', \OCP\Util::DEBUG);
@@ -1046,7 +1046,7 @@  discard block
 block discarded – undo
1046 1046
 		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1047 1047
 		// cannot use $cr anymore, might have changed in the previous call!
1048 1048
 		$error = $this->ldap->errno($this->connection->getConnectionResource());
1049
-		if(!is_array($sr) || $error !== 0) {
1049
+		if (!is_array($sr) || $error !== 0) {
1050 1050
 			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), \OCP\Util::ERROR);
1051 1051
 			return false;
1052 1052
 		}
@@ -1069,26 +1069,26 @@  discard block
 block discarded – undo
1069 1069
 	 */
1070 1070
 	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1071 1071
 		$cookie = null;
1072
-		if($pagedSearchOK) {
1072
+		if ($pagedSearchOK) {
1073 1073
 			$cr = $this->connection->getConnectionResource();
1074
-			foreach($sr as $key => $res) {
1075
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1074
+			foreach ($sr as $key => $res) {
1075
+				if ($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1076 1076
 					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1077 1077
 				}
1078 1078
 			}
1079 1079
 
1080 1080
 			//browsing through prior pages to get the cookie for the new one
1081
-			if($skipHandling) {
1081
+			if ($skipHandling) {
1082 1082
 				return false;
1083 1083
 			}
1084 1084
 			// if count is bigger, then the server does not support
1085 1085
 			// paged search. Instead, he did a normal search. We set a
1086 1086
 			// flag here, so the callee knows how to deal with it.
1087
-			if($iFoundItems <= $limit) {
1087
+			if ($iFoundItems <= $limit) {
1088 1088
 				$this->pagedSearchedSuccessful = true;
1089 1089
 			}
1090 1090
 		} else {
1091
-			if(!is_null($limit)) {
1091
+			if (!is_null($limit)) {
1092 1092
 				\OCP\Util::writeLog('user_ldap', 'Paged search was not available', \OCP\Util::INFO);
1093 1093
 			}
1094 1094
 		}
@@ -1117,7 +1117,7 @@  discard block
 block discarded – undo
1117 1117
 		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), \OCP\Util::DEBUG);
1118 1118
 
1119 1119
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1120
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1120
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1121 1121
 			$limitPerPage = $limit;
1122 1122
 		}
1123 1123
 
@@ -1128,7 +1128,7 @@  discard block
 block discarded – undo
1128 1128
 		do {
1129 1129
 			$search = $this->executeSearch($filter, $base, $attr,
1130 1130
 										   $limitPerPage, $offset);
1131
-			if($search === false) {
1131
+			if ($search === false) {
1132 1132
 				return $counter > 0 ? $counter : false;
1133 1133
 			}
1134 1134
 			list($sr, $pagedSearchOK) = $search;
@@ -1147,7 +1147,7 @@  discard block
 block discarded – undo
1147 1147
 			 * Continue now depends on $hasMorePages value
1148 1148
 			 */
1149 1149
 			$continue = $pagedSearchOK && $hasMorePages;
1150
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1150
+		} while ($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1151 1151
 
1152 1152
 		return $counter;
1153 1153
 	}
@@ -1159,7 +1159,7 @@  discard block
 block discarded – undo
1159 1159
 	private function countEntriesInSearchResults($searchResults) {
1160 1160
 		$counter = 0;
1161 1161
 
1162
-		foreach($searchResults as $res) {
1162
+		foreach ($searchResults as $res) {
1163 1163
 			$count = intval($this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res));
1164 1164
 			$counter += $count;
1165 1165
 		}
@@ -1179,7 +1179,7 @@  discard block
 block discarded – undo
1179 1179
 	 */
1180 1180
 	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1181 1181
 		$limitPerPage = intval($this->connection->ldapPagingSize);
1182
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1182
+		if (!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1183 1183
 			$limitPerPage = $limit;
1184 1184
 		}
1185 1185
 
@@ -1193,13 +1193,13 @@  discard block
 block discarded – undo
1193 1193
 		$savedoffset = $offset;
1194 1194
 		do {
1195 1195
 			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1196
-			if($search === false) {
1196
+			if ($search === false) {
1197 1197
 				return array();
1198 1198
 			}
1199 1199
 			list($sr, $pagedSearchOK) = $search;
1200 1200
 			$cr = $this->connection->getConnectionResource();
1201 1201
 
1202
-			if($skipHandling) {
1202
+			if ($skipHandling) {
1203 1203
 				//i.e. result do not need to be fetched, we just need the cookie
1204 1204
 				//thus pass 1 or any other value as $iFoundItems because it is not
1205 1205
 				//used
@@ -1210,7 +1210,7 @@  discard block
 block discarded – undo
1210 1210
 			}
1211 1211
 
1212 1212
 			$iFoundItems = 0;
1213
-			foreach($sr as $res) {
1213
+			foreach ($sr as $res) {
1214 1214
 				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1215 1215
 				$iFoundItems = max($iFoundItems, $findings['count']);
1216 1216
 				unset($findings['count']);
@@ -1226,25 +1226,25 @@  discard block
 block discarded – undo
1226 1226
 
1227 1227
 		// if we're here, probably no connection resource is returned.
1228 1228
 		// to make Nextcloud behave nicely, we simply give back an empty array.
1229
-		if(is_null($findings)) {
1229
+		if (is_null($findings)) {
1230 1230
 			return array();
1231 1231
 		}
1232 1232
 
1233
-		if(!is_null($attr)) {
1233
+		if (!is_null($attr)) {
1234 1234
 			$selection = array();
1235 1235
 			$i = 0;
1236
-			foreach($findings as $item) {
1237
-				if(!is_array($item)) {
1236
+			foreach ($findings as $item) {
1237
+				if (!is_array($item)) {
1238 1238
 					continue;
1239 1239
 				}
1240 1240
 				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1241
-				foreach($attr as $key) {
1241
+				foreach ($attr as $key) {
1242 1242
 					$key = mb_strtolower($key, 'UTF-8');
1243
-					if(isset($item[$key])) {
1244
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1243
+					if (isset($item[$key])) {
1244
+						if (is_array($item[$key]) && isset($item[$key]['count'])) {
1245 1245
 							unset($item[$key]['count']);
1246 1246
 						}
1247
-						if($key !== 'dn') {
1247
+						if ($key !== 'dn') {
1248 1248
 							$selection[$i][$key] = $this->resemblesDN($key) ?
1249 1249
 								$this->helper->sanitizeDN($item[$key])
1250 1250
 								: $key === 'objectguid' || $key === 'guid' ?
@@ -1263,7 +1263,7 @@  discard block
 block discarded – undo
1263 1263
 		//we slice the findings, when
1264 1264
 		//a) paged search unsuccessful, though attempted
1265 1265
 		//b) no paged search, but limit set
1266
-		if((!$this->getPagedSearchResultState()
1266
+		if ((!$this->getPagedSearchResultState()
1267 1267
 			&& $pagedSearchOK)
1268 1268
 			|| (
1269 1269
 				!$pagedSearchOK
@@ -1280,7 +1280,7 @@  discard block
 block discarded – undo
1280 1280
 	 * @return bool|mixed|string
1281 1281
 	 */
1282 1282
 	public function sanitizeUsername($name) {
1283
-		if($this->connection->ldapIgnoreNamingRules) {
1283
+		if ($this->connection->ldapIgnoreNamingRules) {
1284 1284
 			return $name;
1285 1285
 		}
1286 1286
 
@@ -1305,13 +1305,13 @@  discard block
 block discarded – undo
1305 1305
 	*/
1306 1306
 	public function escapeFilterPart($input, $allowAsterisk = false) {
1307 1307
 		$asterisk = '';
1308
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1308
+		if ($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1309 1309
 			$asterisk = '*';
1310 1310
 			$input = mb_substr($input, 1, null, 'UTF-8');
1311 1311
 		}
1312 1312
 		$search  = array('*', '\\', '(', ')');
1313 1313
 		$replace = array('\\*', '\\\\', '\\(', '\\)');
1314
-		return $asterisk . str_replace($search, $replace, $input);
1314
+		return $asterisk.str_replace($search, $replace, $input);
1315 1315
 	}
1316 1316
 
1317 1317
 	/**
@@ -1341,13 +1341,13 @@  discard block
 block discarded – undo
1341 1341
 	 */
1342 1342
 	private function combineFilter($filters, $operator) {
1343 1343
 		$combinedFilter = '('.$operator;
1344
-		foreach($filters as $filter) {
1344
+		foreach ($filters as $filter) {
1345 1345
 			if ($filter !== '' && $filter[0] !== '(') {
1346 1346
 				$filter = '('.$filter.')';
1347 1347
 			}
1348
-			$combinedFilter.=$filter;
1348
+			$combinedFilter .= $filter;
1349 1349
 		}
1350
-		$combinedFilter.=')';
1350
+		$combinedFilter .= ')';
1351 1351
 		return $combinedFilter;
1352 1352
 	}
1353 1353
 
@@ -1383,17 +1383,17 @@  discard block
 block discarded – undo
1383 1383
 	 * @throws \Exception
1384 1384
 	 */
1385 1385
 	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1386
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1386
+		if (!is_array($searchAttributes) || count($searchAttributes) < 2) {
1387 1387
 			throw new \Exception('searchAttributes must be an array with at least two string');
1388 1388
 		}
1389 1389
 		$searchWords = explode(' ', trim($search));
1390 1390
 		$wordFilters = array();
1391
-		foreach($searchWords as $word) {
1391
+		foreach ($searchWords as $word) {
1392 1392
 			$word = $this->prepareSearchTerm($word);
1393 1393
 			//every word needs to appear at least once
1394 1394
 			$wordMatchOneAttrFilters = array();
1395
-			foreach($searchAttributes as $attr) {
1396
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1395
+			foreach ($searchAttributes as $attr) {
1396
+				$wordMatchOneAttrFilters[] = $attr.'='.$word;
1397 1397
 			}
1398 1398
 			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1399 1399
 		}
@@ -1411,10 +1411,10 @@  discard block
 block discarded – undo
1411 1411
 	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1412 1412
 		$filter = array();
1413 1413
 		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1414
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1414
+		if ($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1415 1415
 			try {
1416 1416
 				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1417
-			} catch(\Exception $e) {
1417
+			} catch (\Exception $e) {
1418 1418
 				\OCP\Util::writeLog(
1419 1419
 					'user_ldap',
1420 1420
 					'Creating advanced filter for search failed, falling back to simple method.',
@@ -1424,17 +1424,17 @@  discard block
 block discarded – undo
1424 1424
 		}
1425 1425
 
1426 1426
 		$search = $this->prepareSearchTerm($search);
1427
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1427
+		if (!is_array($searchAttributes) || count($searchAttributes) === 0) {
1428 1428
 			if ($fallbackAttribute === '') {
1429 1429
 				return '';
1430 1430
 			}
1431
-			$filter[] = $fallbackAttribute . '=' . $search;
1431
+			$filter[] = $fallbackAttribute.'='.$search;
1432 1432
 		} else {
1433
-			foreach($searchAttributes as $attribute) {
1434
-				$filter[] = $attribute . '=' . $search;
1433
+			foreach ($searchAttributes as $attribute) {
1434
+				$filter[] = $attribute.'='.$search;
1435 1435
 			}
1436 1436
 		}
1437
-		if(count($filter) === 1) {
1437
+		if (count($filter) === 1) {
1438 1438
 			return '('.$filter[0].')';
1439 1439
 		}
1440 1440
 		return $this->combineFilterWithOr($filter);
@@ -1455,7 +1455,7 @@  discard block
 block discarded – undo
1455 1455
 		if ($term === '') {
1456 1456
 			$result = '*';
1457 1457
 		} else if ($allowEnum !== 'no') {
1458
-			$result = $term . '*';
1458
+			$result = $term.'*';
1459 1459
 		}
1460 1460
 		return $result;
1461 1461
 	}
@@ -1467,7 +1467,7 @@  discard block
 block discarded – undo
1467 1467
 	public function getFilterForUserCount() {
1468 1468
 		$filter = $this->combineFilterWithAnd(array(
1469 1469
 			$this->connection->ldapUserFilter,
1470
-			$this->connection->ldapUserDisplayName . '=*'
1470
+			$this->connection->ldapUserDisplayName.'=*'
1471 1471
 		));
1472 1472
 
1473 1473
 		return $filter;
@@ -1485,7 +1485,7 @@  discard block
 block discarded – undo
1485 1485
 			'ldapAgentName' => $name,
1486 1486
 			'ldapAgentPassword' => $password
1487 1487
 		);
1488
-		if(!$testConnection->setConfiguration($credentials)) {
1488
+		if (!$testConnection->setConfiguration($credentials)) {
1489 1489
 			return false;
1490 1490
 		}
1491 1491
 		return $testConnection->bind();
@@ -1507,30 +1507,30 @@  discard block
 block discarded – undo
1507 1507
 			// Sacrebleu! The UUID attribute is unknown :( We need first an
1508 1508
 			// existing DN to be able to reliably detect it.
1509 1509
 			$result = $this->search($filter, $base, ['dn'], 1);
1510
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1510
+			if (!isset($result[0]) || !isset($result[0]['dn'])) {
1511 1511
 				throw new \Exception('Cannot determine UUID attribute');
1512 1512
 			}
1513 1513
 			$dn = $result[0]['dn'][0];
1514
-			if(!$this->detectUuidAttribute($dn, true)) {
1514
+			if (!$this->detectUuidAttribute($dn, true)) {
1515 1515
 				throw new \Exception('Cannot determine UUID attribute');
1516 1516
 			}
1517 1517
 		} else {
1518 1518
 			// The UUID attribute is either known or an override is given.
1519 1519
 			// By calling this method we ensure that $this->connection->$uuidAttr
1520 1520
 			// is definitely set
1521
-			if(!$this->detectUuidAttribute('', true)) {
1521
+			if (!$this->detectUuidAttribute('', true)) {
1522 1522
 				throw new \Exception('Cannot determine UUID attribute');
1523 1523
 			}
1524 1524
 		}
1525 1525
 
1526 1526
 		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1527
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1527
+		if ($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1528 1528
 			$uuid = $this->formatGuid2ForFilterUser($uuid);
1529 1529
 		}
1530 1530
 
1531
-		$filter = $uuidAttr . '=' . $uuid;
1531
+		$filter = $uuidAttr.'='.$uuid;
1532 1532
 		$result = $this->searchUsers($filter, ['dn'], 2);
1533
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1533
+		if (is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1534 1534
 			// we put the count into account to make sure that this is
1535 1535
 			// really unique
1536 1536
 			return $result[0]['dn'][0];
@@ -1549,7 +1549,7 @@  discard block
 block discarded – undo
1549 1549
 	 * @return bool true on success, false otherwise
1550 1550
 	 */
1551 1551
 	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1552
-		if($isUser) {
1552
+		if ($isUser) {
1553 1553
 			$uuidAttr     = 'ldapUuidUserAttribute';
1554 1554
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1555 1555
 		} else {
@@ -1557,7 +1557,7 @@  discard block
 block discarded – undo
1557 1557
 			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1558 1558
 		}
1559 1559
 
1560
-		if(($this->connection->$uuidAttr !== 'auto') && !$force) {
1560
+		if (($this->connection->$uuidAttr !== 'auto') && !$force) {
1561 1561
 			return true;
1562 1562
 		}
1563 1563
 
@@ -1566,10 +1566,10 @@  discard block
 block discarded – undo
1566 1566
 			return true;
1567 1567
 		}
1568 1568
 
1569
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1570
-			if($ldapRecord !== null) {
1569
+		foreach (self::UUID_ATTRIBUTES as $attribute) {
1570
+			if ($ldapRecord !== null) {
1571 1571
 				// we have the info from LDAP already, we don't need to talk to the server again
1572
-				if(isset($ldapRecord[$attribute])) {
1572
+				if (isset($ldapRecord[$attribute])) {
1573 1573
 					$this->connection->$uuidAttr = $attribute;
1574 1574
 					return true;
1575 1575
 				} else {
@@ -1578,7 +1578,7 @@  discard block
 block discarded – undo
1578 1578
 			}
1579 1579
 
1580 1580
 			$value = $this->readAttribute($dn, $attribute);
1581
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1581
+			if (is_array($value) && isset($value[0]) && !empty($value[0])) {
1582 1582
 				\OCP\Util::writeLog('user_ldap',
1583 1583
 									'Setting '.$attribute.' as '.$uuidAttr,
1584 1584
 									\OCP\Util::DEBUG);
@@ -1600,7 +1600,7 @@  discard block
 block discarded – undo
1600 1600
 	 * @return bool|string
1601 1601
 	 */
1602 1602
 	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1603
-		if($isUser) {
1603
+		if ($isUser) {
1604 1604
 			$uuidAttr     = 'ldapUuidUserAttribute';
1605 1605
 			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1606 1606
 		} else {
@@ -1609,10 +1609,10 @@  discard block
 block discarded – undo
1609 1609
 		}
1610 1610
 
1611 1611
 		$uuid = false;
1612
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1612
+		if ($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1613 1613
 			$attr = $this->connection->$uuidAttr;
1614 1614
 			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1615
-			if( !is_array($uuid)
1615
+			if (!is_array($uuid)
1616 1616
 				&& $uuidOverride !== ''
1617 1617
 				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1618 1618
 			{
@@ -1620,7 +1620,7 @@  discard block
 block discarded – undo
1620 1620
 					? $ldapRecord[$this->connection->$uuidAttr]
1621 1621
 					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1622 1622
 			}
1623
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1623
+			if (is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1624 1624
 				$uuid = $uuid[0];
1625 1625
 			}
1626 1626
 		}
@@ -1637,19 +1637,19 @@  discard block
 block discarded – undo
1637 1637
 	private function convertObjectGUID2Str($oguid) {
1638 1638
 		$hex_guid = bin2hex($oguid);
1639 1639
 		$hex_guid_to_guid_str = '';
1640
-		for($k = 1; $k <= 4; ++$k) {
1640
+		for ($k = 1; $k <= 4; ++$k) {
1641 1641
 			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1642 1642
 		}
1643 1643
 		$hex_guid_to_guid_str .= '-';
1644
-		for($k = 1; $k <= 2; ++$k) {
1644
+		for ($k = 1; $k <= 2; ++$k) {
1645 1645
 			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1646 1646
 		}
1647 1647
 		$hex_guid_to_guid_str .= '-';
1648
-		for($k = 1; $k <= 2; ++$k) {
1648
+		for ($k = 1; $k <= 2; ++$k) {
1649 1649
 			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1650 1650
 		}
1651
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1652
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1651
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 16, 4);
1652
+		$hex_guid_to_guid_str .= '-'.substr($hex_guid, 20);
1653 1653
 
1654 1654
 		return strtoupper($hex_guid_to_guid_str);
1655 1655
 	}
@@ -1666,11 +1666,11 @@  discard block
 block discarded – undo
1666 1666
 	 * @return string
1667 1667
 	 */
1668 1668
 	public function formatGuid2ForFilterUser($guid) {
1669
-		if(!is_string($guid)) {
1669
+		if (!is_string($guid)) {
1670 1670
 			throw new \InvalidArgumentException('String expected');
1671 1671
 		}
1672 1672
 		$blocks = explode('-', $guid);
1673
-		if(count($blocks) !== 5) {
1673
+		if (count($blocks) !== 5) {
1674 1674
 			/*
1675 1675
 			 * Why not throw an Exception instead? This method is a utility
1676 1676
 			 * called only when trying to figure out whether a "missing" known
@@ -1683,20 +1683,20 @@  discard block
 block discarded – undo
1683 1683
 			 * user. Instead we write a log message.
1684 1684
 			 */
1685 1685
 			\OC::$server->getLogger()->info(
1686
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1686
+				'Passed string does not resemble a valid GUID. Known UUID '.
1687 1687
 				'({uuid}) probably does not match UUID configuration.',
1688
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1688
+				['app' => 'user_ldap', 'uuid' => $guid]
1689 1689
 			);
1690 1690
 			return $guid;
1691 1691
 		}
1692
-		for($i=0; $i < 3; $i++) {
1692
+		for ($i = 0; $i < 3; $i++) {
1693 1693
 			$pairs = str_split($blocks[$i], 2);
1694 1694
 			$pairs = array_reverse($pairs);
1695 1695
 			$blocks[$i] = implode('', $pairs);
1696 1696
 		}
1697
-		for($i=0; $i < 5; $i++) {
1697
+		for ($i = 0; $i < 5; $i++) {
1698 1698
 			$pairs = str_split($blocks[$i], 2);
1699
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1699
+			$blocks[$i] = '\\'.implode('\\', $pairs);
1700 1700
 		}
1701 1701
 		return implode('', $blocks);
1702 1702
 	}
@@ -1710,12 +1710,12 @@  discard block
 block discarded – undo
1710 1710
 		$domainDN = $this->getDomainDNFromDN($dn);
1711 1711
 		$cacheKey = 'getSID-'.$domainDN;
1712 1712
 		$sid = $this->connection->getFromCache($cacheKey);
1713
-		if(!is_null($sid)) {
1713
+		if (!is_null($sid)) {
1714 1714
 			return $sid;
1715 1715
 		}
1716 1716
 
1717 1717
 		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1718
-		if(!is_array($objectSid) || empty($objectSid)) {
1718
+		if (!is_array($objectSid) || empty($objectSid)) {
1719 1719
 			$this->connection->writeToCache($cacheKey, false);
1720 1720
 			return false;
1721 1721
 		}
@@ -1773,12 +1773,12 @@  discard block
 block discarded – undo
1773 1773
 		$belongsToBase = false;
1774 1774
 		$bases = $this->helper->sanitizeDN($bases);
1775 1775
 
1776
-		foreach($bases as $base) {
1776
+		foreach ($bases as $base) {
1777 1777
 			$belongsToBase = true;
1778
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1778
+			if (mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8') - mb_strlen($base, 'UTF-8'))) {
1779 1779
 				$belongsToBase = false;
1780 1780
 			}
1781
-			if($belongsToBase) {
1781
+			if ($belongsToBase) {
1782 1782
 				break;
1783 1783
 			}
1784 1784
 		}
@@ -1789,7 +1789,7 @@  discard block
 block discarded – undo
1789 1789
 	 * resets a running Paged Search operation
1790 1790
 	 */
1791 1791
 	private function abandonPagedSearch() {
1792
-		if($this->connection->hasPagedResultSupport) {
1792
+		if ($this->connection->hasPagedResultSupport) {
1793 1793
 			$cr = $this->connection->getConnectionResource();
1794 1794
 			$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1795 1795
 			$this->getPagedSearchResultState();
@@ -1807,16 +1807,16 @@  discard block
 block discarded – undo
1807 1807
 	 * @return string containing the key or empty if none is cached
1808 1808
 	 */
1809 1809
 	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1810
-		if($offset === 0) {
1810
+		if ($offset === 0) {
1811 1811
 			return '';
1812 1812
 		}
1813 1813
 		$offset -= $limit;
1814 1814
 		//we work with cache here
1815
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . intval($limit) . '-' . intval($offset);
1815
+		$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1816 1816
 		$cookie = '';
1817
-		if(isset($this->cookies[$cacheKey])) {
1817
+		if (isset($this->cookies[$cacheKey])) {
1818 1818
 			$cookie = $this->cookies[$cacheKey];
1819
-			if(is_null($cookie)) {
1819
+			if (is_null($cookie)) {
1820 1820
 				$cookie = '';
1821 1821
 			}
1822 1822
 		}
@@ -1834,11 +1834,11 @@  discard block
 block discarded – undo
1834 1834
 	 * @return bool
1835 1835
 	 */
1836 1836
 	public function hasMoreResults() {
1837
-		if(!$this->connection->hasPagedResultSupport) {
1837
+		if (!$this->connection->hasPagedResultSupport) {
1838 1838
 			return false;
1839 1839
 		}
1840 1840
 
1841
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
1841
+		if (empty($this->lastCookie) && $this->lastCookie !== '0') {
1842 1842
 			// as in RFC 2696, when all results are returned, the cookie will
1843 1843
 			// be empty.
1844 1844
 			return false;
@@ -1858,8 +1858,8 @@  discard block
 block discarded – undo
1858 1858
 	 */
1859 1859
 	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
1860 1860
 		// allow '0' for 389ds
1861
-		if(!empty($cookie) || $cookie === '0') {
1862
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' .intval($limit) . '-' . intval($offset);
1861
+		if (!empty($cookie) || $cookie === '0') {
1862
+			$cacheKey = 'lc'.crc32($base).'-'.crc32($filter).'-'.intval($limit).'-'.intval($offset);
1863 1863
 			$this->cookies[$cacheKey] = $cookie;
1864 1864
 			$this->lastCookie = $cookie;
1865 1865
 		}
@@ -1886,22 +1886,22 @@  discard block
 block discarded – undo
1886 1886
 	 */
1887 1887
 	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
1888 1888
 		$pagedSearchOK = false;
1889
-		if($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1889
+		if ($this->connection->hasPagedResultSupport && ($limit !== 0)) {
1890 1890
 			$offset = intval($offset); //can be null
1891 1891
 			\OCP\Util::writeLog('user_ldap',
1892 1892
 				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
1893
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
1893
+				.' attr '.print_r($attr, true).' limit '.$limit.' offset '.$offset,
1894 1894
 				\OCP\Util::DEBUG);
1895 1895
 			//get the cookie from the search for the previous search, required by LDAP
1896
-			foreach($bases as $base) {
1896
+			foreach ($bases as $base) {
1897 1897
 
1898 1898
 				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
1899
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1899
+				if (empty($cookie) && $cookie !== "0" && ($offset > 0)) {
1900 1900
 					// no cookie known from a potential previous search. We need
1901 1901
 					// to start from 0 to come to the desired page. cookie value
1902 1902
 					// of '0' is valid, because 389ds
1903 1903
 					$reOffset = 0;
1904
-					while($reOffset < $offset) {
1904
+					while ($reOffset < $offset) {
1905 1905
 						$this->search($filter, array($base), $attr, $limit, $reOffset, true);
1906 1906
 						$reOffset += $limit;
1907 1907
 					}
@@ -1909,17 +1909,17 @@  discard block
 block discarded – undo
1909 1909
 					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
1910 1910
 					// '0' is valid, because 389ds
1911 1911
 					//TODO: remember this, probably does not change in the next request...
1912
-					if(empty($cookie) && $cookie !== '0') {
1912
+					if (empty($cookie) && $cookie !== '0') {
1913 1913
 						$cookie = null;
1914 1914
 					}
1915 1915
 				}
1916
-				if(!is_null($cookie)) {
1916
+				if (!is_null($cookie)) {
1917 1917
 					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
1918 1918
 					$this->abandonPagedSearch();
1919 1919
 					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
1920 1920
 						$this->connection->getConnectionResource(), $limit,
1921 1921
 						false, $cookie);
1922
-					if(!$pagedSearchOK) {
1922
+					if (!$pagedSearchOK) {
1923 1923
 						return false;
1924 1924
 					}
1925 1925
 					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', \OCP\Util::DEBUG);
@@ -1936,7 +1936,7 @@  discard block
 block discarded – undo
1936 1936
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
1937 1937
 		 * if we don't have a previous paged search.
1938 1938
 		 */
1939
-		} else if($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1939
+		} else if ($this->connection->hasPagedResultSupport && $limit === 0 && !empty($this->lastCookie)) {
1940 1940
 			// a search without limit was requested. However, if we do use
1941 1941
 			// Paged Search once, we always must do it. This requires us to
1942 1942
 			// initialize it with the configured page size.
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/Manager.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -44,223 +44,223 @@
 block discarded – undo
44 44
  * cache
45 45
  */
46 46
 class Manager {
47
-	/** @var IUserTools */
48
-	protected $access;
47
+    /** @var IUserTools */
48
+    protected $access;
49 49
 
50
-	/** @var IConfig */
51
-	protected $ocConfig;
50
+    /** @var IConfig */
51
+    protected $ocConfig;
52 52
 
53
-	/** @var IDBConnection */
54
-	protected $db;
53
+    /** @var IDBConnection */
54
+    protected $db;
55 55
 
56
-	/** @var IUserManager */
57
-	protected $userManager;
56
+    /** @var IUserManager */
57
+    protected $userManager;
58 58
 
59
-	/** @var INotificationManager */
60
-	protected $notificationManager;
59
+    /** @var INotificationManager */
60
+    protected $notificationManager;
61 61
 
62
-	/** @var FilesystemHelper */
63
-	protected $ocFilesystem;
62
+    /** @var FilesystemHelper */
63
+    protected $ocFilesystem;
64 64
 
65
-	/** @var LogWrapper */
66
-	protected $ocLog;
65
+    /** @var LogWrapper */
66
+    protected $ocLog;
67 67
 
68
-	/** @var Image */
69
-	protected $image;
68
+    /** @var Image */
69
+    protected $image;
70 70
 
71
-	/** @param \OCP\IAvatarManager */
72
-	protected $avatarManager;
71
+    /** @param \OCP\IAvatarManager */
72
+    protected $avatarManager;
73 73
 
74
-	/**
75
-	 * @var CappedMemoryCache $usersByDN
76
-	 */
77
-	protected $usersByDN;
78
-	/**
79
-	 * @var CappedMemoryCache $usersByUid
80
-	 */
81
-	protected $usersByUid;
74
+    /**
75
+     * @var CappedMemoryCache $usersByDN
76
+     */
77
+    protected $usersByDN;
78
+    /**
79
+     * @var CappedMemoryCache $usersByUid
80
+     */
81
+    protected $usersByUid;
82 82
 
83
-	/**
84
-	 * @param IConfig $ocConfig
85
-	 * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
86
-	 * gives access to necessary functions from the OC filesystem
87
-	 * @param  \OCA\User_LDAP\LogWrapper $ocLog
88
-	 * @param IAvatarManager $avatarManager
89
-	 * @param Image $image an empty image instance
90
-	 * @param IDBConnection $db
91
-	 * @throws \Exception when the methods mentioned above do not exist
92
-	 */
93
-	public function __construct(IConfig $ocConfig,
94
-								FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
95
-								IAvatarManager $avatarManager, Image $image,
96
-								IDBConnection $db, IUserManager $userManager,
97
-								INotificationManager $notificationManager) {
83
+    /**
84
+     * @param IConfig $ocConfig
85
+     * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
86
+     * gives access to necessary functions from the OC filesystem
87
+     * @param  \OCA\User_LDAP\LogWrapper $ocLog
88
+     * @param IAvatarManager $avatarManager
89
+     * @param Image $image an empty image instance
90
+     * @param IDBConnection $db
91
+     * @throws \Exception when the methods mentioned above do not exist
92
+     */
93
+    public function __construct(IConfig $ocConfig,
94
+                                FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
95
+                                IAvatarManager $avatarManager, Image $image,
96
+                                IDBConnection $db, IUserManager $userManager,
97
+                                INotificationManager $notificationManager) {
98 98
 
99
-		$this->ocConfig            = $ocConfig;
100
-		$this->ocFilesystem        = $ocFilesystem;
101
-		$this->ocLog               = $ocLog;
102
-		$this->avatarManager       = $avatarManager;
103
-		$this->image               = $image;
104
-		$this->db                  = $db;
105
-		$this->userManager         = $userManager;
106
-		$this->notificationManager = $notificationManager;
107
-		$this->usersByDN           = new CappedMemoryCache();
108
-		$this->usersByUid          = new CappedMemoryCache();
109
-	}
99
+        $this->ocConfig            = $ocConfig;
100
+        $this->ocFilesystem        = $ocFilesystem;
101
+        $this->ocLog               = $ocLog;
102
+        $this->avatarManager       = $avatarManager;
103
+        $this->image               = $image;
104
+        $this->db                  = $db;
105
+        $this->userManager         = $userManager;
106
+        $this->notificationManager = $notificationManager;
107
+        $this->usersByDN           = new CappedMemoryCache();
108
+        $this->usersByUid          = new CappedMemoryCache();
109
+    }
110 110
 
111
-	/**
112
-	 * @brief binds manager to an instance of IUserTools (implemented by
113
-	 * Access). It needs to be assigned first before the manager can be used.
114
-	 * @param IUserTools
115
-	 */
116
-	public function setLdapAccess(IUserTools $access) {
117
-		$this->access = $access;
118
-	}
111
+    /**
112
+     * @brief binds manager to an instance of IUserTools (implemented by
113
+     * Access). It needs to be assigned first before the manager can be used.
114
+     * @param IUserTools
115
+     */
116
+    public function setLdapAccess(IUserTools $access) {
117
+        $this->access = $access;
118
+    }
119 119
 
120
-	/**
121
-	 * @brief creates an instance of User and caches (just runtime) it in the
122
-	 * property array
123
-	 * @param string $dn the DN of the user
124
-	 * @param string $uid the internal (owncloud) username
125
-	 * @return \OCA\User_LDAP\User\User
126
-	 */
127
-	private function createAndCache($dn, $uid) {
128
-		$this->checkAccess();
129
-		$user = new User($uid, $dn, $this->access, $this->ocConfig,
130
-			$this->ocFilesystem, clone $this->image, $this->ocLog,
131
-			$this->avatarManager, $this->userManager, 
132
-			$this->notificationManager);
133
-		$this->usersByDN[$dn]   = $user;
134
-		$this->usersByUid[$uid] = $user;
135
-		return $user;
136
-	}
120
+    /**
121
+     * @brief creates an instance of User and caches (just runtime) it in the
122
+     * property array
123
+     * @param string $dn the DN of the user
124
+     * @param string $uid the internal (owncloud) username
125
+     * @return \OCA\User_LDAP\User\User
126
+     */
127
+    private function createAndCache($dn, $uid) {
128
+        $this->checkAccess();
129
+        $user = new User($uid, $dn, $this->access, $this->ocConfig,
130
+            $this->ocFilesystem, clone $this->image, $this->ocLog,
131
+            $this->avatarManager, $this->userManager, 
132
+            $this->notificationManager);
133
+        $this->usersByDN[$dn]   = $user;
134
+        $this->usersByUid[$uid] = $user;
135
+        return $user;
136
+    }
137 137
 
138
-	/**
139
-	 * removes a user entry from the cache
140
-	 * @param $uid
141
-	 */
142
-	public function invalidate($uid) {
143
-		if(!isset($this->usersByUid[$uid])) {
144
-			return;
145
-		}
146
-		$dn = $this->usersByUid[$uid]->getDN();
147
-		unset($this->usersByUid[$uid]);
148
-		unset($this->usersByDN[$dn]);
149
-	}
138
+    /**
139
+     * removes a user entry from the cache
140
+     * @param $uid
141
+     */
142
+    public function invalidate($uid) {
143
+        if(!isset($this->usersByUid[$uid])) {
144
+            return;
145
+        }
146
+        $dn = $this->usersByUid[$uid]->getDN();
147
+        unset($this->usersByUid[$uid]);
148
+        unset($this->usersByDN[$dn]);
149
+    }
150 150
 
151
-	/**
152
-	 * @brief checks whether the Access instance has been set
153
-	 * @throws \Exception if Access has not been set
154
-	 * @return null
155
-	 */
156
-	private function checkAccess() {
157
-		if(is_null($this->access)) {
158
-			throw new \Exception('LDAP Access instance must be set first');
159
-		}
160
-	}
151
+    /**
152
+     * @brief checks whether the Access instance has been set
153
+     * @throws \Exception if Access has not been set
154
+     * @return null
155
+     */
156
+    private function checkAccess() {
157
+        if(is_null($this->access)) {
158
+            throw new \Exception('LDAP Access instance must be set first');
159
+        }
160
+    }
161 161
 
162
-	/**
163
-	 * returns a list of attributes that will be processed further, e.g. quota,
164
-	 * email, displayname, or others.
165
-	 * @param bool $minimal - optional, set to true to skip attributes with big
166
-	 * payload
167
-	 * @return string[]
168
-	 */
169
-	public function getAttributes($minimal = false) {
170
-		$attributes = array_merge(Access::UUID_ATTRIBUTES, ['dn', 'uid', 'samaccountname', 'memberof']);
171
-		$possible = array(
172
-			$this->access->getConnection()->ldapExpertUUIDUserAttr,
173
-			$this->access->getConnection()->ldapQuotaAttribute,
174
-			$this->access->getConnection()->ldapEmailAttribute,
175
-			$this->access->getConnection()->ldapUserDisplayName,
176
-			$this->access->getConnection()->ldapUserDisplayName2,
177
-		);
178
-		foreach($possible as $attr) {
179
-			if(!is_null($attr)) {
180
-				$attributes[] = $attr;
181
-			}
182
-		}
162
+    /**
163
+     * returns a list of attributes that will be processed further, e.g. quota,
164
+     * email, displayname, or others.
165
+     * @param bool $minimal - optional, set to true to skip attributes with big
166
+     * payload
167
+     * @return string[]
168
+     */
169
+    public function getAttributes($minimal = false) {
170
+        $attributes = array_merge(Access::UUID_ATTRIBUTES, ['dn', 'uid', 'samaccountname', 'memberof']);
171
+        $possible = array(
172
+            $this->access->getConnection()->ldapExpertUUIDUserAttr,
173
+            $this->access->getConnection()->ldapQuotaAttribute,
174
+            $this->access->getConnection()->ldapEmailAttribute,
175
+            $this->access->getConnection()->ldapUserDisplayName,
176
+            $this->access->getConnection()->ldapUserDisplayName2,
177
+        );
178
+        foreach($possible as $attr) {
179
+            if(!is_null($attr)) {
180
+                $attributes[] = $attr;
181
+            }
182
+        }
183 183
 
184
-		$homeRule = $this->access->getConnection()->homeFolderNamingRule;
185
-		if(strpos($homeRule, 'attr:') === 0) {
186
-			$attributes[] = substr($homeRule, strlen('attr:'));
187
-		}
184
+        $homeRule = $this->access->getConnection()->homeFolderNamingRule;
185
+        if(strpos($homeRule, 'attr:') === 0) {
186
+            $attributes[] = substr($homeRule, strlen('attr:'));
187
+        }
188 188
 
189
-		if(!$minimal) {
190
-			// attributes that are not really important but may come with big
191
-			// payload.
192
-			$attributes = array_merge($attributes, array(
193
-				'jpegphoto',
194
-				'thumbnailphoto'
195
-			));
196
-		}
189
+        if(!$minimal) {
190
+            // attributes that are not really important but may come with big
191
+            // payload.
192
+            $attributes = array_merge($attributes, array(
193
+                'jpegphoto',
194
+                'thumbnailphoto'
195
+            ));
196
+        }
197 197
 
198
-		return $attributes;
199
-	}
198
+        return $attributes;
199
+    }
200 200
 
201
-	/**
202
-	 * Checks whether the specified user is marked as deleted
203
-	 * @param string $id the Nextcloud user name
204
-	 * @return bool
205
-	 */
206
-	public function isDeletedUser($id) {
207
-		$isDeleted = $this->ocConfig->getUserValue(
208
-			$id, 'user_ldap', 'isDeleted', 0);
209
-		return intval($isDeleted) === 1;
210
-	}
201
+    /**
202
+     * Checks whether the specified user is marked as deleted
203
+     * @param string $id the Nextcloud user name
204
+     * @return bool
205
+     */
206
+    public function isDeletedUser($id) {
207
+        $isDeleted = $this->ocConfig->getUserValue(
208
+            $id, 'user_ldap', 'isDeleted', 0);
209
+        return intval($isDeleted) === 1;
210
+    }
211 211
 
212
-	/**
213
-	 * creates and returns an instance of OfflineUser for the specified user
214
-	 * @param string $id
215
-	 * @return \OCA\User_LDAP\User\OfflineUser
216
-	 */
217
-	public function getDeletedUser($id) {
218
-		return new OfflineUser(
219
-			$id,
220
-			$this->ocConfig,
221
-			$this->db,
222
-			$this->access->getUserMapper());
223
-	}
212
+    /**
213
+     * creates and returns an instance of OfflineUser for the specified user
214
+     * @param string $id
215
+     * @return \OCA\User_LDAP\User\OfflineUser
216
+     */
217
+    public function getDeletedUser($id) {
218
+        return new OfflineUser(
219
+            $id,
220
+            $this->ocConfig,
221
+            $this->db,
222
+            $this->access->getUserMapper());
223
+    }
224 224
 
225
-	/**
226
-	 * @brief returns a User object by it's Nextcloud username
227
-	 * @param string $id the DN or username of the user
228
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
229
-	 */
230
-	protected function createInstancyByUserName($id) {
231
-		//most likely a uid. Check whether it is a deleted user
232
-		if($this->isDeletedUser($id)) {
233
-			return $this->getDeletedUser($id);
234
-		}
235
-		$dn = $this->access->username2dn($id);
236
-		if($dn !== false) {
237
-			return $this->createAndCache($dn, $id);
238
-		}
239
-		return null;
240
-	}
225
+    /**
226
+     * @brief returns a User object by it's Nextcloud username
227
+     * @param string $id the DN or username of the user
228
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
229
+     */
230
+    protected function createInstancyByUserName($id) {
231
+        //most likely a uid. Check whether it is a deleted user
232
+        if($this->isDeletedUser($id)) {
233
+            return $this->getDeletedUser($id);
234
+        }
235
+        $dn = $this->access->username2dn($id);
236
+        if($dn !== false) {
237
+            return $this->createAndCache($dn, $id);
238
+        }
239
+        return null;
240
+    }
241 241
 
242
-	/**
243
-	 * @brief returns a User object by it's DN or Nextcloud username
244
-	 * @param string $id the DN or username of the user
245
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
246
-	 * @throws \Exception when connection could not be established
247
-	 */
248
-	public function get($id) {
249
-		$this->checkAccess();
250
-		if(isset($this->usersByDN[$id])) {
251
-			return $this->usersByDN[$id];
252
-		} else if(isset($this->usersByUid[$id])) {
253
-			return $this->usersByUid[$id];
254
-		}
242
+    /**
243
+     * @brief returns a User object by it's DN or Nextcloud username
244
+     * @param string $id the DN or username of the user
245
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
246
+     * @throws \Exception when connection could not be established
247
+     */
248
+    public function get($id) {
249
+        $this->checkAccess();
250
+        if(isset($this->usersByDN[$id])) {
251
+            return $this->usersByDN[$id];
252
+        } else if(isset($this->usersByUid[$id])) {
253
+            return $this->usersByUid[$id];
254
+        }
255 255
 
256
-		if($this->access->stringResemblesDN($id) ) {
257
-			$uid = $this->access->dn2username($id);
258
-			if($uid !== false) {
259
-				return $this->createAndCache($id, $uid);
260
-			}
261
-		}
256
+        if($this->access->stringResemblesDN($id) ) {
257
+            $uid = $this->access->dn2username($id);
258
+            if($uid !== false) {
259
+                return $this->createAndCache($id, $uid);
260
+            }
261
+        }
262 262
 
263
-		return $this->createInstancyByUserName($id);
264
-	}
263
+        return $this->createInstancyByUserName($id);
264
+    }
265 265
 
266 266
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/User.php 2 patches
Indentation   +644 added lines, -644 removed lines patch added patch discarded remove patch
@@ -43,654 +43,654 @@
 block discarded – undo
43 43
  * represents an LDAP user, gets and holds user-specific information from LDAP
44 44
  */
45 45
 class User {
46
-	/**
47
-	 * @var IUserTools
48
-	 */
49
-	protected $access;
50
-	/**
51
-	 * @var Connection
52
-	 */
53
-	protected $connection;
54
-	/**
55
-	 * @var IConfig
56
-	 */
57
-	protected $config;
58
-	/**
59
-	 * @var FilesystemHelper
60
-	 */
61
-	protected $fs;
62
-	/**
63
-	 * @var Image
64
-	 */
65
-	protected $image;
66
-	/**
67
-	 * @var LogWrapper
68
-	 */
69
-	protected $log;
70
-	/**
71
-	 * @var IAvatarManager
72
-	 */
73
-	protected $avatarManager;
74
-	/**
75
-	 * @var IUserManager
76
-	 */
77
-	protected $userManager;
78
-	/**
79
-	 * @var INotificationManager
80
-	 */
81
-	protected $notificationManager;
82
-	/**
83
-	 * @var string
84
-	 */
85
-	protected $dn;
86
-	/**
87
-	 * @var string
88
-	 */
89
-	protected $uid;
90
-	/**
91
-	 * @var string[]
92
-	 */
93
-	protected $refreshedFeatures = array();
94
-	/**
95
-	 * @var string
96
-	 */
97
-	protected $avatarImage;
98
-
99
-	/**
100
-	 * DB config keys for user preferences
101
-	 */
102
-	const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
103
-	const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
104
-
105
-	/**
106
-	 * @brief constructor, make sure the subclasses call this one!
107
-	 * @param string $username the internal username
108
-	 * @param string $dn the LDAP DN
109
-	 * @param IUserTools $access an instance that implements IUserTools for
110
-	 * LDAP interaction
111
-	 * @param IConfig $config
112
-	 * @param FilesystemHelper $fs
113
-	 * @param Image $image any empty instance
114
-	 * @param LogWrapper $log
115
-	 * @param IAvatarManager $avatarManager
116
-	 * @param IUserManager $userManager
117
-	 * @param INotificationManager $notificationManager
118
-	 */
119
-	public function __construct($username, $dn, IUserTools $access,
120
-		IConfig $config, FilesystemHelper $fs, Image $image,
121
-		LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
122
-		INotificationManager $notificationManager) {
46
+    /**
47
+     * @var IUserTools
48
+     */
49
+    protected $access;
50
+    /**
51
+     * @var Connection
52
+     */
53
+    protected $connection;
54
+    /**
55
+     * @var IConfig
56
+     */
57
+    protected $config;
58
+    /**
59
+     * @var FilesystemHelper
60
+     */
61
+    protected $fs;
62
+    /**
63
+     * @var Image
64
+     */
65
+    protected $image;
66
+    /**
67
+     * @var LogWrapper
68
+     */
69
+    protected $log;
70
+    /**
71
+     * @var IAvatarManager
72
+     */
73
+    protected $avatarManager;
74
+    /**
75
+     * @var IUserManager
76
+     */
77
+    protected $userManager;
78
+    /**
79
+     * @var INotificationManager
80
+     */
81
+    protected $notificationManager;
82
+    /**
83
+     * @var string
84
+     */
85
+    protected $dn;
86
+    /**
87
+     * @var string
88
+     */
89
+    protected $uid;
90
+    /**
91
+     * @var string[]
92
+     */
93
+    protected $refreshedFeatures = array();
94
+    /**
95
+     * @var string
96
+     */
97
+    protected $avatarImage;
98
+
99
+    /**
100
+     * DB config keys for user preferences
101
+     */
102
+    const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
103
+    const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
104
+
105
+    /**
106
+     * @brief constructor, make sure the subclasses call this one!
107
+     * @param string $username the internal username
108
+     * @param string $dn the LDAP DN
109
+     * @param IUserTools $access an instance that implements IUserTools for
110
+     * LDAP interaction
111
+     * @param IConfig $config
112
+     * @param FilesystemHelper $fs
113
+     * @param Image $image any empty instance
114
+     * @param LogWrapper $log
115
+     * @param IAvatarManager $avatarManager
116
+     * @param IUserManager $userManager
117
+     * @param INotificationManager $notificationManager
118
+     */
119
+    public function __construct($username, $dn, IUserTools $access,
120
+        IConfig $config, FilesystemHelper $fs, Image $image,
121
+        LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
122
+        INotificationManager $notificationManager) {
123 123
 	
124
-		if ($username === null) {
125
-			$log->log("uid for '$dn' must not be null!", Util::ERROR);
126
-			throw new \InvalidArgumentException('uid must not be null!');
127
-		} else if ($username === '') {
128
-			$log->log("uid for '$dn' must not be an empty string", Util::ERROR);
129
-			throw new \InvalidArgumentException('uid must not be an empty string!');
130
-		}
131
-
132
-		$this->access              = $access;
133
-		$this->connection          = $access->getConnection();
134
-		$this->config              = $config;
135
-		$this->fs                  = $fs;
136
-		$this->dn                  = $dn;
137
-		$this->uid                 = $username;
138
-		$this->image               = $image;
139
-		$this->log                 = $log;
140
-		$this->avatarManager       = $avatarManager;
141
-		$this->userManager         = $userManager;
142
-		$this->notificationManager = $notificationManager;
143
-
144
-		\OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
145
-	}
146
-
147
-	/**
148
-	 * @brief updates properties like email, quota or avatar provided by LDAP
149
-	 * @return null
150
-	 */
151
-	public function update() {
152
-		if(is_null($this->dn)) {
153
-			return null;
154
-		}
155
-
156
-		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157
-				self::USER_PREFKEY_FIRSTLOGIN, 0);
158
-
159
-		if($this->needsRefresh()) {
160
-			$this->updateEmail();
161
-			$this->updateQuota();
162
-			if($hasLoggedIn !== 0) {
163
-				//we do not need to try it, when the user has not been logged in
164
-				//before, because the file system will not be ready.
165
-				$this->updateAvatar();
166
-				//in order to get an avatar as soon as possible, mark the user
167
-				//as refreshed only when updating the avatar did happen
168
-				$this->markRefreshTime();
169
-			}
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * processes results from LDAP for attributes as returned by getAttributesToRead()
175
-	 * @param array $ldapEntry the user entry as retrieved from LDAP
176
-	 */
177
-	public function processAttributes($ldapEntry) {
178
-		$this->markRefreshTime();
179
-		//Quota
180
-		$attr = strtolower($this->connection->ldapQuotaAttribute);
181
-		if(isset($ldapEntry[$attr])) {
182
-			$this->updateQuota($ldapEntry[$attr][0]);
183
-		} else {
184
-			if ($this->connection->ldapQuotaDefault !== '') {
185
-				$this->updateQuota();
186
-			}
187
-		}
188
-		unset($attr);
189
-
190
-		//displayName
191
-		$displayName = $displayName2 = '';
192
-		$attr = strtolower($this->connection->ldapUserDisplayName);
193
-		if(isset($ldapEntry[$attr])) {
194
-			$displayName = strval($ldapEntry[$attr][0]);
195
-		}
196
-		$attr = strtolower($this->connection->ldapUserDisplayName2);
197
-		if(isset($ldapEntry[$attr])) {
198
-			$displayName2 = strval($ldapEntry[$attr][0]);
199
-		}
200
-		if ($displayName !== '') {
201
-			$this->composeAndStoreDisplayName($displayName);
202
-			$this->access->cacheUserDisplayName(
203
-				$this->getUsername(),
204
-				$displayName,
205
-				$displayName2
206
-			);
207
-		}
208
-		unset($attr);
209
-
210
-		//Email
211
-		//email must be stored after displayname, because it would cause a user
212
-		//change event that will trigger fetching the display name again
213
-		$attr = strtolower($this->connection->ldapEmailAttribute);
214
-		if(isset($ldapEntry[$attr])) {
215
-			$this->updateEmail($ldapEntry[$attr][0]);
216
-		}
217
-		unset($attr);
218
-
219
-		// LDAP Username, needed for s2s sharing
220
-		if(isset($ldapEntry['uid'])) {
221
-			$this->storeLDAPUserName($ldapEntry['uid'][0]);
222
-		} else if(isset($ldapEntry['samaccountname'])) {
223
-			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
224
-		}
225
-
226
-		//homePath
227
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
228
-			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
229
-			if(isset($ldapEntry[$attr])) {
230
-				$this->access->cacheUserHome(
231
-					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
232
-			}
233
-		}
234
-
235
-		//memberOf groups
236
-		$cacheKey = 'getMemberOf'.$this->getUsername();
237
-		$groups = false;
238
-		if(isset($ldapEntry['memberof'])) {
239
-			$groups = $ldapEntry['memberof'];
240
-		}
241
-		$this->connection->writeToCache($cacheKey, $groups);
242
-
243
-		//Avatar
244
-		$attrs = array('jpegphoto', 'thumbnailphoto');
245
-		foreach ($attrs as $attr)  {
246
-			if(isset($ldapEntry[$attr])) {
247
-				$this->avatarImage = $ldapEntry[$attr][0];
248
-				// the call to the method that saves the avatar in the file
249
-				// system must be postponed after the login. It is to ensure
250
-				// external mounts are mounted properly (e.g. with login
251
-				// credentials from the session).
252
-				\OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
253
-				break;
254
-			}
255
-		}
256
-	}
257
-
258
-	/**
259
-	 * @brief returns the LDAP DN of the user
260
-	 * @return string
261
-	 */
262
-	public function getDN() {
263
-		return $this->dn;
264
-	}
265
-
266
-	/**
267
-	 * @brief returns the Nextcloud internal username of the user
268
-	 * @return string
269
-	 */
270
-	public function getUsername() {
271
-		return $this->uid;
272
-	}
273
-
274
-	/**
275
-	 * returns the home directory of the user if specified by LDAP settings
276
-	 * @param string $valueFromLDAP
277
-	 * @return bool|string
278
-	 * @throws \Exception
279
-	 */
280
-	public function getHomePath($valueFromLDAP = null) {
281
-		$path = strval($valueFromLDAP);
282
-		$attr = null;
283
-
284
-		if (is_null($valueFromLDAP)
285
-		   && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
286
-		   && $this->access->connection->homeFolderNamingRule !== 'attr:')
287
-		{
288
-			$attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
289
-			$homedir = $this->access->readAttribute(
290
-				$this->access->username2dn($this->getUsername()), $attr);
291
-			if ($homedir && isset($homedir[0])) {
292
-				$path = $homedir[0];
293
-			}
294
-		}
295
-
296
-		if ($path !== '') {
297
-			//if attribute's value is an absolute path take this, otherwise append it to data dir
298
-			//check for / at the beginning or pattern c:\ resp. c:/
299
-			if(   '/' !== $path[0]
300
-			   && !(3 < strlen($path) && ctype_alpha($path[0])
301
-			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
302
-			) {
303
-				$path = $this->config->getSystemValue('datadirectory',
304
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
305
-			}
306
-			//we need it to store it in the DB as well in case a user gets
307
-			//deleted so we can clean up afterwards
308
-			$this->config->setUserValue(
309
-				$this->getUsername(), 'user_ldap', 'homePath', $path
310
-			);
311
-			return $path;
312
-		}
313
-
314
-		if(    !is_null($attr)
315
-			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
316
-		) {
317
-			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
318
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
319
-		}
320
-
321
-		//false will apply default behaviour as defined and done by OC_User
322
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
323
-		return false;
324
-	}
325
-
326
-	public function getMemberOfGroups() {
327
-		$cacheKey = 'getMemberOf'.$this->getUsername();
328
-		$memberOfGroups = $this->connection->getFromCache($cacheKey);
329
-		if(!is_null($memberOfGroups)) {
330
-			return $memberOfGroups;
331
-		}
332
-		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
333
-		$this->connection->writeToCache($cacheKey, $groupDNs);
334
-		return $groupDNs;
335
-	}
336
-
337
-	/**
338
-	 * @brief reads the image from LDAP that shall be used as Avatar
339
-	 * @return string data (provided by LDAP) | false
340
-	 */
341
-	public function getAvatarImage() {
342
-		if(!is_null($this->avatarImage)) {
343
-			return $this->avatarImage;
344
-		}
345
-
346
-		$this->avatarImage = false;
347
-		$attributes = array('jpegPhoto', 'thumbnailPhoto');
348
-		foreach($attributes as $attribute) {
349
-			$result = $this->access->readAttribute($this->dn, $attribute);
350
-			if($result !== false && is_array($result) && isset($result[0])) {
351
-				$this->avatarImage = $result[0];
352
-				break;
353
-			}
354
-		}
355
-
356
-		return $this->avatarImage;
357
-	}
358
-
359
-	/**
360
-	 * @brief marks the user as having logged in at least once
361
-	 * @return null
362
-	 */
363
-	public function markLogin() {
364
-		$this->config->setUserValue(
365
-			$this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
366
-	}
367
-
368
-	/**
369
-	 * @brief marks the time when user features like email have been updated
370
-	 * @return null
371
-	 */
372
-	public function markRefreshTime() {
373
-		$this->config->setUserValue(
374
-			$this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
375
-	}
376
-
377
-	/**
378
-	 * @brief checks whether user features needs to be updated again by
379
-	 * comparing the difference of time of the last refresh to now with the
380
-	 * desired interval
381
-	 * @return bool
382
-	 */
383
-	private function needsRefresh() {
384
-		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
385
-			self::USER_PREFKEY_LASTREFRESH, 0);
386
-
387
-		//TODO make interval configurable
388
-		if((time() - intval($lastChecked)) < 86400 ) {
389
-			return false;
390
-		}
391
-		return  true;
392
-	}
393
-
394
-	/**
395
-	 * Stores a key-value pair in relation to this user
396
-	 *
397
-	 * @param string $key
398
-	 * @param string $value
399
-	 */
400
-	private function store($key, $value) {
401
-		$this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
402
-	}
403
-
404
-	/**
405
-	 * Composes the display name and stores it in the database. The final
406
-	 * display name is returned.
407
-	 *
408
-	 * @param string $displayName
409
-	 * @param string $displayName2
410
-	 * @returns string the effective display name
411
-	 */
412
-	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
413
-		$displayName2 = strval($displayName2);
414
-		if($displayName2 !== '') {
415
-			$displayName .= ' (' . $displayName2 . ')';
416
-		}
417
-		$this->store('displayName', $displayName);
418
-		return $displayName;
419
-	}
420
-
421
-	/**
422
-	 * Stores the LDAP Username in the Database
423
-	 * @param string $userName
424
-	 */
425
-	public function storeLDAPUserName($userName) {
426
-		$this->store('uid', $userName);
427
-	}
428
-
429
-	/**
430
-	 * @brief checks whether an update method specified by feature was run
431
-	 * already. If not, it will marked like this, because it is expected that
432
-	 * the method will be run, when false is returned.
433
-	 * @param string $feature email | quota | avatar (can be extended)
434
-	 * @return bool
435
-	 */
436
-	private function wasRefreshed($feature) {
437
-		if(isset($this->refreshedFeatures[$feature])) {
438
-			return true;
439
-		}
440
-		$this->refreshedFeatures[$feature] = 1;
441
-		return false;
442
-	}
443
-
444
-	/**
445
-	 * fetches the email from LDAP and stores it as Nextcloud user value
446
-	 * @param string $valueFromLDAP if known, to save an LDAP read request
447
-	 * @return null
448
-	 */
449
-	public function updateEmail($valueFromLDAP = null) {
450
-		if($this->wasRefreshed('email')) {
451
-			return;
452
-		}
453
-		$email = strval($valueFromLDAP);
454
-		if(is_null($valueFromLDAP)) {
455
-			$emailAttribute = $this->connection->ldapEmailAttribute;
456
-			if ($emailAttribute !== '') {
457
-				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
458
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
459
-					$email = strval($aEmail[0]);
460
-				}
461
-			}
462
-		}
463
-		if ($email !== '') {
464
-			$user = $this->userManager->get($this->uid);
465
-			if (!is_null($user)) {
466
-				$currentEmail = strval($user->getEMailAddress());
467
-				if ($currentEmail !== $email) {
468
-					$user->setEMailAddress($email);
469
-				}
470
-			}
471
-		}
472
-	}
473
-
474
-	/**
475
-	 * Overall process goes as follow:
476
-	 * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
477
-	 * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
478
-	 * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
479
-	 * 4. check if the target user exists and set the quota for the user.
480
-	 *
481
-	 * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
482
-	 * parameter can be passed with the value of the attribute. This value will be considered as the
483
-	 * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
484
-	 * fetch all the user's attributes in one call and use the fetched values in this function.
485
-	 * The expected value for that parameter is a string describing the quota for the user. Valid
486
-	 * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
487
-	 * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
488
-	 *
489
-	 * fetches the quota from LDAP and stores it as Nextcloud user value
490
-	 * @param string $valueFromLDAP the quota attribute's value can be passed,
491
-	 * to save the readAttribute request
492
-	 * @return null
493
-	 */
494
-	public function updateQuota($valueFromLDAP = null) {
495
-		if($this->wasRefreshed('quota')) {
496
-			return;
497
-		}
498
-
499
-		$quota = false;
500
-		if(is_null($valueFromLDAP)) {
501
-			$quotaAttribute = $this->connection->ldapQuotaAttribute;
502
-			if ($quotaAttribute !== '') {
503
-				$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
504
-				if($aQuota && (count($aQuota) > 0)) {
505
-					if ($this->verifyQuotaValue($aQuota[0])) {
506
-						$quota = $aQuota[0];
507
-					} else {
508
-						$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
509
-					}
510
-				}
511
-			}
512
-		} else {
513
-			if ($this->verifyQuotaValue($valueFromLDAP)) {
514
-				$quota = $valueFromLDAP;
515
-			} else {
516
-				$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
517
-			}
518
-		}
519
-
520
-		if ($quota === false) {
521
-			// quota not found using the LDAP attribute (or not parseable). Try the default quota
522
-			$defaultQuota = $this->connection->ldapQuotaDefault;
523
-			if ($this->verifyQuotaValue($defaultQuota)) {
524
-				$quota = $defaultQuota;
525
-			}
526
-		}
527
-
528
-		$targetUser = $this->userManager->get($this->uid);
529
-		if ($targetUser) {
530
-			if($quota !== false) {
531
-				$targetUser->setQuota($quota);
532
-			} else {
533
-				$this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
534
-			}
535
-		} else {
536
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
537
-		}
538
-	}
539
-
540
-	private function verifyQuotaValue($quotaValue) {
541
-		return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
542
-	}
543
-
544
-	/**
545
-	 * called by a post_login hook to save the avatar picture
546
-	 *
547
-	 * @param array $params
548
-	 */
549
-	public function updateAvatarPostLogin($params) {
550
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
551
-			$this->updateAvatar();
552
-		}
553
-	}
554
-
555
-	/**
556
-	 * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
557
-	 * @return null
558
-	 */
559
-	public function updateAvatar() {
560
-		if($this->wasRefreshed('avatar')) {
561
-			return;
562
-		}
563
-		$avatarImage = $this->getAvatarImage();
564
-		if($avatarImage === false) {
565
-			//not set, nothing left to do;
566
-			return;
567
-		}
568
-		$this->image->loadFromBase64(base64_encode($avatarImage));
569
-		$this->setOwnCloudAvatar();
570
-	}
571
-
572
-	/**
573
-	 * @brief sets an image as Nextcloud avatar
574
-	 * @return null
575
-	 */
576
-	private function setOwnCloudAvatar() {
577
-		if(!$this->image->valid()) {
578
-			$this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
579
-			return;
580
-		}
581
-		//make sure it is a square and not bigger than 128x128
582
-		$size = min(array($this->image->width(), $this->image->height(), 128));
583
-		if(!$this->image->centerCrop($size)) {
584
-			$this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
585
-			return;
586
-		}
587
-
588
-		if(!$this->fs->isLoaded()) {
589
-			$this->fs->setup($this->uid);
590
-		}
591
-
592
-		try {
593
-			$avatar = $this->avatarManager->getAvatar($this->uid);
594
-			$avatar->set($this->image);
595
-		} catch (\Exception $e) {
596
-			\OC::$server->getLogger()->notice(
597
-				'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
598
-				['app' => 'user_ldap']);
599
-		}
600
-	}
601
-
602
-	/**
603
-	 * called by a post_login hook to handle password expiry
604
-	 *
605
-	 * @param array $params
606
-	 */
607
-	public function handlePasswordExpiry($params) {
608
-		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
609
-		if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
610
-			return;//password expiry handling disabled
611
-		}
612
-		$uid = $params['uid'];
613
-		if(isset($uid) && $uid === $this->getUsername()) {
614
-			//retrieve relevant user attributes
615
-			$result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
124
+        if ($username === null) {
125
+            $log->log("uid for '$dn' must not be null!", Util::ERROR);
126
+            throw new \InvalidArgumentException('uid must not be null!');
127
+        } else if ($username === '') {
128
+            $log->log("uid for '$dn' must not be an empty string", Util::ERROR);
129
+            throw new \InvalidArgumentException('uid must not be an empty string!');
130
+        }
131
+
132
+        $this->access              = $access;
133
+        $this->connection          = $access->getConnection();
134
+        $this->config              = $config;
135
+        $this->fs                  = $fs;
136
+        $this->dn                  = $dn;
137
+        $this->uid                 = $username;
138
+        $this->image               = $image;
139
+        $this->log                 = $log;
140
+        $this->avatarManager       = $avatarManager;
141
+        $this->userManager         = $userManager;
142
+        $this->notificationManager = $notificationManager;
143
+
144
+        \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
145
+    }
146
+
147
+    /**
148
+     * @brief updates properties like email, quota or avatar provided by LDAP
149
+     * @return null
150
+     */
151
+    public function update() {
152
+        if(is_null($this->dn)) {
153
+            return null;
154
+        }
155
+
156
+        $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157
+                self::USER_PREFKEY_FIRSTLOGIN, 0);
158
+
159
+        if($this->needsRefresh()) {
160
+            $this->updateEmail();
161
+            $this->updateQuota();
162
+            if($hasLoggedIn !== 0) {
163
+                //we do not need to try it, when the user has not been logged in
164
+                //before, because the file system will not be ready.
165
+                $this->updateAvatar();
166
+                //in order to get an avatar as soon as possible, mark the user
167
+                //as refreshed only when updating the avatar did happen
168
+                $this->markRefreshTime();
169
+            }
170
+        }
171
+    }
172
+
173
+    /**
174
+     * processes results from LDAP for attributes as returned by getAttributesToRead()
175
+     * @param array $ldapEntry the user entry as retrieved from LDAP
176
+     */
177
+    public function processAttributes($ldapEntry) {
178
+        $this->markRefreshTime();
179
+        //Quota
180
+        $attr = strtolower($this->connection->ldapQuotaAttribute);
181
+        if(isset($ldapEntry[$attr])) {
182
+            $this->updateQuota($ldapEntry[$attr][0]);
183
+        } else {
184
+            if ($this->connection->ldapQuotaDefault !== '') {
185
+                $this->updateQuota();
186
+            }
187
+        }
188
+        unset($attr);
189
+
190
+        //displayName
191
+        $displayName = $displayName2 = '';
192
+        $attr = strtolower($this->connection->ldapUserDisplayName);
193
+        if(isset($ldapEntry[$attr])) {
194
+            $displayName = strval($ldapEntry[$attr][0]);
195
+        }
196
+        $attr = strtolower($this->connection->ldapUserDisplayName2);
197
+        if(isset($ldapEntry[$attr])) {
198
+            $displayName2 = strval($ldapEntry[$attr][0]);
199
+        }
200
+        if ($displayName !== '') {
201
+            $this->composeAndStoreDisplayName($displayName);
202
+            $this->access->cacheUserDisplayName(
203
+                $this->getUsername(),
204
+                $displayName,
205
+                $displayName2
206
+            );
207
+        }
208
+        unset($attr);
209
+
210
+        //Email
211
+        //email must be stored after displayname, because it would cause a user
212
+        //change event that will trigger fetching the display name again
213
+        $attr = strtolower($this->connection->ldapEmailAttribute);
214
+        if(isset($ldapEntry[$attr])) {
215
+            $this->updateEmail($ldapEntry[$attr][0]);
216
+        }
217
+        unset($attr);
218
+
219
+        // LDAP Username, needed for s2s sharing
220
+        if(isset($ldapEntry['uid'])) {
221
+            $this->storeLDAPUserName($ldapEntry['uid'][0]);
222
+        } else if(isset($ldapEntry['samaccountname'])) {
223
+            $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
224
+        }
225
+
226
+        //homePath
227
+        if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
228
+            $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
229
+            if(isset($ldapEntry[$attr])) {
230
+                $this->access->cacheUserHome(
231
+                    $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
232
+            }
233
+        }
234
+
235
+        //memberOf groups
236
+        $cacheKey = 'getMemberOf'.$this->getUsername();
237
+        $groups = false;
238
+        if(isset($ldapEntry['memberof'])) {
239
+            $groups = $ldapEntry['memberof'];
240
+        }
241
+        $this->connection->writeToCache($cacheKey, $groups);
242
+
243
+        //Avatar
244
+        $attrs = array('jpegphoto', 'thumbnailphoto');
245
+        foreach ($attrs as $attr)  {
246
+            if(isset($ldapEntry[$attr])) {
247
+                $this->avatarImage = $ldapEntry[$attr][0];
248
+                // the call to the method that saves the avatar in the file
249
+                // system must be postponed after the login. It is to ensure
250
+                // external mounts are mounted properly (e.g. with login
251
+                // credentials from the session).
252
+                \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
253
+                break;
254
+            }
255
+        }
256
+    }
257
+
258
+    /**
259
+     * @brief returns the LDAP DN of the user
260
+     * @return string
261
+     */
262
+    public function getDN() {
263
+        return $this->dn;
264
+    }
265
+
266
+    /**
267
+     * @brief returns the Nextcloud internal username of the user
268
+     * @return string
269
+     */
270
+    public function getUsername() {
271
+        return $this->uid;
272
+    }
273
+
274
+    /**
275
+     * returns the home directory of the user if specified by LDAP settings
276
+     * @param string $valueFromLDAP
277
+     * @return bool|string
278
+     * @throws \Exception
279
+     */
280
+    public function getHomePath($valueFromLDAP = null) {
281
+        $path = strval($valueFromLDAP);
282
+        $attr = null;
283
+
284
+        if (is_null($valueFromLDAP)
285
+           && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
286
+           && $this->access->connection->homeFolderNamingRule !== 'attr:')
287
+        {
288
+            $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
289
+            $homedir = $this->access->readAttribute(
290
+                $this->access->username2dn($this->getUsername()), $attr);
291
+            if ($homedir && isset($homedir[0])) {
292
+                $path = $homedir[0];
293
+            }
294
+        }
295
+
296
+        if ($path !== '') {
297
+            //if attribute's value is an absolute path take this, otherwise append it to data dir
298
+            //check for / at the beginning or pattern c:\ resp. c:/
299
+            if(   '/' !== $path[0]
300
+               && !(3 < strlen($path) && ctype_alpha($path[0])
301
+                   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
302
+            ) {
303
+                $path = $this->config->getSystemValue('datadirectory',
304
+                        \OC::$SERVERROOT.'/data' ) . '/' . $path;
305
+            }
306
+            //we need it to store it in the DB as well in case a user gets
307
+            //deleted so we can clean up afterwards
308
+            $this->config->setUserValue(
309
+                $this->getUsername(), 'user_ldap', 'homePath', $path
310
+            );
311
+            return $path;
312
+        }
313
+
314
+        if(    !is_null($attr)
315
+            && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
316
+        ) {
317
+            // a naming rule attribute is defined, but it doesn't exist for that LDAP user
318
+            throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
319
+        }
320
+
321
+        //false will apply default behaviour as defined and done by OC_User
322
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
323
+        return false;
324
+    }
325
+
326
+    public function getMemberOfGroups() {
327
+        $cacheKey = 'getMemberOf'.$this->getUsername();
328
+        $memberOfGroups = $this->connection->getFromCache($cacheKey);
329
+        if(!is_null($memberOfGroups)) {
330
+            return $memberOfGroups;
331
+        }
332
+        $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
333
+        $this->connection->writeToCache($cacheKey, $groupDNs);
334
+        return $groupDNs;
335
+    }
336
+
337
+    /**
338
+     * @brief reads the image from LDAP that shall be used as Avatar
339
+     * @return string data (provided by LDAP) | false
340
+     */
341
+    public function getAvatarImage() {
342
+        if(!is_null($this->avatarImage)) {
343
+            return $this->avatarImage;
344
+        }
345
+
346
+        $this->avatarImage = false;
347
+        $attributes = array('jpegPhoto', 'thumbnailPhoto');
348
+        foreach($attributes as $attribute) {
349
+            $result = $this->access->readAttribute($this->dn, $attribute);
350
+            if($result !== false && is_array($result) && isset($result[0])) {
351
+                $this->avatarImage = $result[0];
352
+                break;
353
+            }
354
+        }
355
+
356
+        return $this->avatarImage;
357
+    }
358
+
359
+    /**
360
+     * @brief marks the user as having logged in at least once
361
+     * @return null
362
+     */
363
+    public function markLogin() {
364
+        $this->config->setUserValue(
365
+            $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
366
+    }
367
+
368
+    /**
369
+     * @brief marks the time when user features like email have been updated
370
+     * @return null
371
+     */
372
+    public function markRefreshTime() {
373
+        $this->config->setUserValue(
374
+            $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
375
+    }
376
+
377
+    /**
378
+     * @brief checks whether user features needs to be updated again by
379
+     * comparing the difference of time of the last refresh to now with the
380
+     * desired interval
381
+     * @return bool
382
+     */
383
+    private function needsRefresh() {
384
+        $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
385
+            self::USER_PREFKEY_LASTREFRESH, 0);
386
+
387
+        //TODO make interval configurable
388
+        if((time() - intval($lastChecked)) < 86400 ) {
389
+            return false;
390
+        }
391
+        return  true;
392
+    }
393
+
394
+    /**
395
+     * Stores a key-value pair in relation to this user
396
+     *
397
+     * @param string $key
398
+     * @param string $value
399
+     */
400
+    private function store($key, $value) {
401
+        $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
402
+    }
403
+
404
+    /**
405
+     * Composes the display name and stores it in the database. The final
406
+     * display name is returned.
407
+     *
408
+     * @param string $displayName
409
+     * @param string $displayName2
410
+     * @returns string the effective display name
411
+     */
412
+    public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
413
+        $displayName2 = strval($displayName2);
414
+        if($displayName2 !== '') {
415
+            $displayName .= ' (' . $displayName2 . ')';
416
+        }
417
+        $this->store('displayName', $displayName);
418
+        return $displayName;
419
+    }
420
+
421
+    /**
422
+     * Stores the LDAP Username in the Database
423
+     * @param string $userName
424
+     */
425
+    public function storeLDAPUserName($userName) {
426
+        $this->store('uid', $userName);
427
+    }
428
+
429
+    /**
430
+     * @brief checks whether an update method specified by feature was run
431
+     * already. If not, it will marked like this, because it is expected that
432
+     * the method will be run, when false is returned.
433
+     * @param string $feature email | quota | avatar (can be extended)
434
+     * @return bool
435
+     */
436
+    private function wasRefreshed($feature) {
437
+        if(isset($this->refreshedFeatures[$feature])) {
438
+            return true;
439
+        }
440
+        $this->refreshedFeatures[$feature] = 1;
441
+        return false;
442
+    }
443
+
444
+    /**
445
+     * fetches the email from LDAP and stores it as Nextcloud user value
446
+     * @param string $valueFromLDAP if known, to save an LDAP read request
447
+     * @return null
448
+     */
449
+    public function updateEmail($valueFromLDAP = null) {
450
+        if($this->wasRefreshed('email')) {
451
+            return;
452
+        }
453
+        $email = strval($valueFromLDAP);
454
+        if(is_null($valueFromLDAP)) {
455
+            $emailAttribute = $this->connection->ldapEmailAttribute;
456
+            if ($emailAttribute !== '') {
457
+                $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
458
+                if(is_array($aEmail) && (count($aEmail) > 0)) {
459
+                    $email = strval($aEmail[0]);
460
+                }
461
+            }
462
+        }
463
+        if ($email !== '') {
464
+            $user = $this->userManager->get($this->uid);
465
+            if (!is_null($user)) {
466
+                $currentEmail = strval($user->getEMailAddress());
467
+                if ($currentEmail !== $email) {
468
+                    $user->setEMailAddress($email);
469
+                }
470
+            }
471
+        }
472
+    }
473
+
474
+    /**
475
+     * Overall process goes as follow:
476
+     * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
477
+     * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
478
+     * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
479
+     * 4. check if the target user exists and set the quota for the user.
480
+     *
481
+     * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
482
+     * parameter can be passed with the value of the attribute. This value will be considered as the
483
+     * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
484
+     * fetch all the user's attributes in one call and use the fetched values in this function.
485
+     * The expected value for that parameter is a string describing the quota for the user. Valid
486
+     * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
487
+     * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
488
+     *
489
+     * fetches the quota from LDAP and stores it as Nextcloud user value
490
+     * @param string $valueFromLDAP the quota attribute's value can be passed,
491
+     * to save the readAttribute request
492
+     * @return null
493
+     */
494
+    public function updateQuota($valueFromLDAP = null) {
495
+        if($this->wasRefreshed('quota')) {
496
+            return;
497
+        }
498
+
499
+        $quota = false;
500
+        if(is_null($valueFromLDAP)) {
501
+            $quotaAttribute = $this->connection->ldapQuotaAttribute;
502
+            if ($quotaAttribute !== '') {
503
+                $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
504
+                if($aQuota && (count($aQuota) > 0)) {
505
+                    if ($this->verifyQuotaValue($aQuota[0])) {
506
+                        $quota = $aQuota[0];
507
+                    } else {
508
+                        $this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
509
+                    }
510
+                }
511
+            }
512
+        } else {
513
+            if ($this->verifyQuotaValue($valueFromLDAP)) {
514
+                $quota = $valueFromLDAP;
515
+            } else {
516
+                $this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
517
+            }
518
+        }
519
+
520
+        if ($quota === false) {
521
+            // quota not found using the LDAP attribute (or not parseable). Try the default quota
522
+            $defaultQuota = $this->connection->ldapQuotaDefault;
523
+            if ($this->verifyQuotaValue($defaultQuota)) {
524
+                $quota = $defaultQuota;
525
+            }
526
+        }
527
+
528
+        $targetUser = $this->userManager->get($this->uid);
529
+        if ($targetUser) {
530
+            if($quota !== false) {
531
+                $targetUser->setQuota($quota);
532
+            } else {
533
+                $this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
534
+            }
535
+        } else {
536
+            $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
537
+        }
538
+    }
539
+
540
+    private function verifyQuotaValue($quotaValue) {
541
+        return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
542
+    }
543
+
544
+    /**
545
+     * called by a post_login hook to save the avatar picture
546
+     *
547
+     * @param array $params
548
+     */
549
+    public function updateAvatarPostLogin($params) {
550
+        if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
551
+            $this->updateAvatar();
552
+        }
553
+    }
554
+
555
+    /**
556
+     * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
557
+     * @return null
558
+     */
559
+    public function updateAvatar() {
560
+        if($this->wasRefreshed('avatar')) {
561
+            return;
562
+        }
563
+        $avatarImage = $this->getAvatarImage();
564
+        if($avatarImage === false) {
565
+            //not set, nothing left to do;
566
+            return;
567
+        }
568
+        $this->image->loadFromBase64(base64_encode($avatarImage));
569
+        $this->setOwnCloudAvatar();
570
+    }
571
+
572
+    /**
573
+     * @brief sets an image as Nextcloud avatar
574
+     * @return null
575
+     */
576
+    private function setOwnCloudAvatar() {
577
+        if(!$this->image->valid()) {
578
+            $this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
579
+            return;
580
+        }
581
+        //make sure it is a square and not bigger than 128x128
582
+        $size = min(array($this->image->width(), $this->image->height(), 128));
583
+        if(!$this->image->centerCrop($size)) {
584
+            $this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
585
+            return;
586
+        }
587
+
588
+        if(!$this->fs->isLoaded()) {
589
+            $this->fs->setup($this->uid);
590
+        }
591
+
592
+        try {
593
+            $avatar = $this->avatarManager->getAvatar($this->uid);
594
+            $avatar->set($this->image);
595
+        } catch (\Exception $e) {
596
+            \OC::$server->getLogger()->notice(
597
+                'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
598
+                ['app' => 'user_ldap']);
599
+        }
600
+    }
601
+
602
+    /**
603
+     * called by a post_login hook to handle password expiry
604
+     *
605
+     * @param array $params
606
+     */
607
+    public function handlePasswordExpiry($params) {
608
+        $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
609
+        if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
610
+            return;//password expiry handling disabled
611
+        }
612
+        $uid = $params['uid'];
613
+        if(isset($uid) && $uid === $this->getUsername()) {
614
+            //retrieve relevant user attributes
615
+            $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
616 616
 			
617
-			if(array_key_exists('pwdpolicysubentry', $result[0])) {
618
-				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
619
-				if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
620
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
621
-				}
622
-			}
617
+            if(array_key_exists('pwdpolicysubentry', $result[0])) {
618
+                $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
619
+                if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
620
+                    $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
621
+                }
622
+            }
623 623
 			
624
-			$pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : null;
625
-			$pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : null;
626
-			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
624
+            $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : null;
625
+            $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : null;
626
+            $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
627 627
 			
628
-			//retrieve relevant password policy attributes
629
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
630
-			$result = $this->connection->getFromCache($cacheKey);
631
-			if(is_null($result)) {
632
-				$result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
633
-				$this->connection->writeToCache($cacheKey, $result);
634
-			}
628
+            //retrieve relevant password policy attributes
629
+            $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
630
+            $result = $this->connection->getFromCache($cacheKey);
631
+            if(is_null($result)) {
632
+                $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
633
+                $this->connection->writeToCache($cacheKey, $result);
634
+            }
635 635
 			
636
-			$pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : null;
637
-			$pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : null;
638
-			$pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : null;
636
+            $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : null;
637
+            $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : null;
638
+            $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : null;
639 639
 			
640
-			//handle grace login
641
-			$pwdGraceUseTimeCount = count($pwdGraceUseTime);
642
-			if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
643
-				if($pwdGraceAuthNLimit 
644
-					&& (count($pwdGraceAuthNLimit) > 0)
645
-					&&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
646
-					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
647
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
648
-					'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
649
-				} else { //no more grace login available
650
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
651
-					'user_ldap.renewPassword.showLoginFormInvalidPassword', array('user' => $uid)));
652
-				}
653
-				exit();
654
-			}
655
-			//handle pwdReset attribute
656
-			if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
657
-				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
658
-				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
659
-				'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
660
-				exit();
661
-			}
662
-			//handle password expiry warning
663
-			if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
664
-				if($pwdMaxAge && (count($pwdMaxAge) > 0)
665
-					&& $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
666
-					$pwdMaxAgeInt = intval($pwdMaxAge[0]);
667
-					$pwdExpireWarningInt = intval($pwdExpireWarning[0]);
668
-					if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
669
-						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
670
-						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
671
-						$currentDateTime = new \DateTime();
672
-						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
673
-						if($secondsToExpiry <= $pwdExpireWarningInt) {
674
-							//remove last password expiry warning if any
675
-							$notification = $this->notificationManager->createNotification();
676
-							$notification->setApp('user_ldap')
677
-								->setUser($uid)
678
-								->setObject('pwd_exp_warn', $uid)
679
-							;
680
-							$this->notificationManager->markProcessed($notification);
681
-							//create new password expiry warning
682
-							$notification = $this->notificationManager->createNotification();
683
-							$notification->setApp('user_ldap')
684
-								->setUser($uid)
685
-								->setDateTime($currentDateTime)
686
-								->setObject('pwd_exp_warn', $uid) 
687
-								->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
688
-							;
689
-							$this->notificationManager->notify($notification);
690
-						}
691
-					}
692
-				}
693
-			}
694
-		}
695
-	}
640
+            //handle grace login
641
+            $pwdGraceUseTimeCount = count($pwdGraceUseTime);
642
+            if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
643
+                if($pwdGraceAuthNLimit 
644
+                    && (count($pwdGraceAuthNLimit) > 0)
645
+                    &&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
646
+                    $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
647
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
648
+                    'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
649
+                } else { //no more grace login available
650
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
651
+                    'user_ldap.renewPassword.showLoginFormInvalidPassword', array('user' => $uid)));
652
+                }
653
+                exit();
654
+            }
655
+            //handle pwdReset attribute
656
+            if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
657
+                $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
658
+                header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
659
+                'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
660
+                exit();
661
+            }
662
+            //handle password expiry warning
663
+            if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
664
+                if($pwdMaxAge && (count($pwdMaxAge) > 0)
665
+                    && $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
666
+                    $pwdMaxAgeInt = intval($pwdMaxAge[0]);
667
+                    $pwdExpireWarningInt = intval($pwdExpireWarning[0]);
668
+                    if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
669
+                        $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
670
+                        $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
671
+                        $currentDateTime = new \DateTime();
672
+                        $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
673
+                        if($secondsToExpiry <= $pwdExpireWarningInt) {
674
+                            //remove last password expiry warning if any
675
+                            $notification = $this->notificationManager->createNotification();
676
+                            $notification->setApp('user_ldap')
677
+                                ->setUser($uid)
678
+                                ->setObject('pwd_exp_warn', $uid)
679
+                            ;
680
+                            $this->notificationManager->markProcessed($notification);
681
+                            //create new password expiry warning
682
+                            $notification = $this->notificationManager->createNotification();
683
+                            $notification->setApp('user_ldap')
684
+                                ->setUser($uid)
685
+                                ->setDateTime($currentDateTime)
686
+                                ->setObject('pwd_exp_warn', $uid) 
687
+                                ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
688
+                            ;
689
+                            $this->notificationManager->notify($notification);
690
+                        }
691
+                    }
692
+                }
693
+            }
694
+        }
695
+    }
696 696
 }
Please login to merge, or discard this patch.
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -149,17 +149,17 @@  discard block
 block discarded – undo
149 149
 	 * @return null
150 150
 	 */
151 151
 	public function update() {
152
-		if(is_null($this->dn)) {
152
+		if (is_null($this->dn)) {
153 153
 			return null;
154 154
 		}
155 155
 
156 156
 		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157 157
 				self::USER_PREFKEY_FIRSTLOGIN, 0);
158 158
 
159
-		if($this->needsRefresh()) {
159
+		if ($this->needsRefresh()) {
160 160
 			$this->updateEmail();
161 161
 			$this->updateQuota();
162
-			if($hasLoggedIn !== 0) {
162
+			if ($hasLoggedIn !== 0) {
163 163
 				//we do not need to try it, when the user has not been logged in
164 164
 				//before, because the file system will not be ready.
165 165
 				$this->updateAvatar();
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 		$this->markRefreshTime();
179 179
 		//Quota
180 180
 		$attr = strtolower($this->connection->ldapQuotaAttribute);
181
-		if(isset($ldapEntry[$attr])) {
181
+		if (isset($ldapEntry[$attr])) {
182 182
 			$this->updateQuota($ldapEntry[$attr][0]);
183 183
 		} else {
184 184
 			if ($this->connection->ldapQuotaDefault !== '') {
@@ -190,11 +190,11 @@  discard block
 block discarded – undo
190 190
 		//displayName
191 191
 		$displayName = $displayName2 = '';
192 192
 		$attr = strtolower($this->connection->ldapUserDisplayName);
193
-		if(isset($ldapEntry[$attr])) {
193
+		if (isset($ldapEntry[$attr])) {
194 194
 			$displayName = strval($ldapEntry[$attr][0]);
195 195
 		}
196 196
 		$attr = strtolower($this->connection->ldapUserDisplayName2);
197
-		if(isset($ldapEntry[$attr])) {
197
+		if (isset($ldapEntry[$attr])) {
198 198
 			$displayName2 = strval($ldapEntry[$attr][0]);
199 199
 		}
200 200
 		if ($displayName !== '') {
@@ -211,22 +211,22 @@  discard block
 block discarded – undo
211 211
 		//email must be stored after displayname, because it would cause a user
212 212
 		//change event that will trigger fetching the display name again
213 213
 		$attr = strtolower($this->connection->ldapEmailAttribute);
214
-		if(isset($ldapEntry[$attr])) {
214
+		if (isset($ldapEntry[$attr])) {
215 215
 			$this->updateEmail($ldapEntry[$attr][0]);
216 216
 		}
217 217
 		unset($attr);
218 218
 
219 219
 		// LDAP Username, needed for s2s sharing
220
-		if(isset($ldapEntry['uid'])) {
220
+		if (isset($ldapEntry['uid'])) {
221 221
 			$this->storeLDAPUserName($ldapEntry['uid'][0]);
222
-		} else if(isset($ldapEntry['samaccountname'])) {
222
+		} else if (isset($ldapEntry['samaccountname'])) {
223 223
 			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
224 224
 		}
225 225
 
226 226
 		//homePath
227
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
227
+		if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
228 228
 			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
229
-			if(isset($ldapEntry[$attr])) {
229
+			if (isset($ldapEntry[$attr])) {
230 230
 				$this->access->cacheUserHome(
231 231
 					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
232 232
 			}
@@ -235,15 +235,15 @@  discard block
 block discarded – undo
235 235
 		//memberOf groups
236 236
 		$cacheKey = 'getMemberOf'.$this->getUsername();
237 237
 		$groups = false;
238
-		if(isset($ldapEntry['memberof'])) {
238
+		if (isset($ldapEntry['memberof'])) {
239 239
 			$groups = $ldapEntry['memberof'];
240 240
 		}
241 241
 		$this->connection->writeToCache($cacheKey, $groups);
242 242
 
243 243
 		//Avatar
244 244
 		$attrs = array('jpegphoto', 'thumbnailphoto');
245
-		foreach ($attrs as $attr)  {
246
-			if(isset($ldapEntry[$attr])) {
245
+		foreach ($attrs as $attr) {
246
+			if (isset($ldapEntry[$attr])) {
247 247
 				$this->avatarImage = $ldapEntry[$attr][0];
248 248
 				// the call to the method that saves the avatar in the file
249 249
 				// system must be postponed after the login. It is to ensure
@@ -296,12 +296,12 @@  discard block
 block discarded – undo
296 296
 		if ($path !== '') {
297 297
 			//if attribute's value is an absolute path take this, otherwise append it to data dir
298 298
 			//check for / at the beginning or pattern c:\ resp. c:/
299
-			if(   '/' !== $path[0]
299
+			if ('/' !== $path[0]
300 300
 			   && !(3 < strlen($path) && ctype_alpha($path[0])
301 301
 			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
302 302
 			) {
303 303
 				$path = $this->config->getSystemValue('datadirectory',
304
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
304
+						\OC::$SERVERROOT.'/data').'/'.$path;
305 305
 			}
306 306
 			//we need it to store it in the DB as well in case a user gets
307 307
 			//deleted so we can clean up afterwards
@@ -311,11 +311,11 @@  discard block
 block discarded – undo
311 311
 			return $path;
312 312
 		}
313 313
 
314
-		if(    !is_null($attr)
314
+		if (!is_null($attr)
315 315
 			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
316 316
 		) {
317 317
 			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
318
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
318
+			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: '.$this->getUsername());
319 319
 		}
320 320
 
321 321
 		//false will apply default behaviour as defined and done by OC_User
@@ -326,7 +326,7 @@  discard block
 block discarded – undo
326 326
 	public function getMemberOfGroups() {
327 327
 		$cacheKey = 'getMemberOf'.$this->getUsername();
328 328
 		$memberOfGroups = $this->connection->getFromCache($cacheKey);
329
-		if(!is_null($memberOfGroups)) {
329
+		if (!is_null($memberOfGroups)) {
330 330
 			return $memberOfGroups;
331 331
 		}
332 332
 		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
@@ -339,15 +339,15 @@  discard block
 block discarded – undo
339 339
 	 * @return string data (provided by LDAP) | false
340 340
 	 */
341 341
 	public function getAvatarImage() {
342
-		if(!is_null($this->avatarImage)) {
342
+		if (!is_null($this->avatarImage)) {
343 343
 			return $this->avatarImage;
344 344
 		}
345 345
 
346 346
 		$this->avatarImage = false;
347 347
 		$attributes = array('jpegPhoto', 'thumbnailPhoto');
348
-		foreach($attributes as $attribute) {
348
+		foreach ($attributes as $attribute) {
349 349
 			$result = $this->access->readAttribute($this->dn, $attribute);
350
-			if($result !== false && is_array($result) && isset($result[0])) {
350
+			if ($result !== false && is_array($result) && isset($result[0])) {
351 351
 				$this->avatarImage = $result[0];
352 352
 				break;
353 353
 			}
@@ -385,7 +385,7 @@  discard block
 block discarded – undo
385 385
 			self::USER_PREFKEY_LASTREFRESH, 0);
386 386
 
387 387
 		//TODO make interval configurable
388
-		if((time() - intval($lastChecked)) < 86400 ) {
388
+		if ((time() - intval($lastChecked)) < 86400) {
389 389
 			return false;
390 390
 		}
391 391
 		return  true;
@@ -411,8 +411,8 @@  discard block
 block discarded – undo
411 411
 	 */
412 412
 	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
413 413
 		$displayName2 = strval($displayName2);
414
-		if($displayName2 !== '') {
415
-			$displayName .= ' (' . $displayName2 . ')';
414
+		if ($displayName2 !== '') {
415
+			$displayName .= ' ('.$displayName2.')';
416 416
 		}
417 417
 		$this->store('displayName', $displayName);
418 418
 		return $displayName;
@@ -434,7 +434,7 @@  discard block
 block discarded – undo
434 434
 	 * @return bool
435 435
 	 */
436 436
 	private function wasRefreshed($feature) {
437
-		if(isset($this->refreshedFeatures[$feature])) {
437
+		if (isset($this->refreshedFeatures[$feature])) {
438 438
 			return true;
439 439
 		}
440 440
 		$this->refreshedFeatures[$feature] = 1;
@@ -447,15 +447,15 @@  discard block
 block discarded – undo
447 447
 	 * @return null
448 448
 	 */
449 449
 	public function updateEmail($valueFromLDAP = null) {
450
-		if($this->wasRefreshed('email')) {
450
+		if ($this->wasRefreshed('email')) {
451 451
 			return;
452 452
 		}
453 453
 		$email = strval($valueFromLDAP);
454
-		if(is_null($valueFromLDAP)) {
454
+		if (is_null($valueFromLDAP)) {
455 455
 			$emailAttribute = $this->connection->ldapEmailAttribute;
456 456
 			if ($emailAttribute !== '') {
457 457
 				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
458
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
458
+				if (is_array($aEmail) && (count($aEmail) > 0)) {
459 459
 					$email = strval($aEmail[0]);
460 460
 				}
461 461
 			}
@@ -492,20 +492,20 @@  discard block
 block discarded – undo
492 492
 	 * @return null
493 493
 	 */
494 494
 	public function updateQuota($valueFromLDAP = null) {
495
-		if($this->wasRefreshed('quota')) {
495
+		if ($this->wasRefreshed('quota')) {
496 496
 			return;
497 497
 		}
498 498
 
499 499
 		$quota = false;
500
-		if(is_null($valueFromLDAP)) {
500
+		if (is_null($valueFromLDAP)) {
501 501
 			$quotaAttribute = $this->connection->ldapQuotaAttribute;
502 502
 			if ($quotaAttribute !== '') {
503 503
 				$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
504
-				if($aQuota && (count($aQuota) > 0)) {
504
+				if ($aQuota && (count($aQuota) > 0)) {
505 505
 					if ($this->verifyQuotaValue($aQuota[0])) {
506 506
 						$quota = $aQuota[0];
507 507
 					} else {
508
-						$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
508
+						$this->log->log('not suitable LDAP quota found for user '.$this->uid.': ['.$aQuota[0].']', \OCP\Util::WARN);
509 509
 					}
510 510
 				}
511 511
 			}
@@ -513,7 +513,7 @@  discard block
 block discarded – undo
513 513
 			if ($this->verifyQuotaValue($valueFromLDAP)) {
514 514
 				$quota = $valueFromLDAP;
515 515
 			} else {
516
-				$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
516
+				$this->log->log('not suitable LDAP quota found for user '.$this->uid.': ['.$valueFromLDAP.']', \OCP\Util::WARN);
517 517
 			}
518 518
 		}
519 519
 
@@ -527,13 +527,13 @@  discard block
 block discarded – undo
527 527
 
528 528
 		$targetUser = $this->userManager->get($this->uid);
529 529
 		if ($targetUser) {
530
-			if($quota !== false) {
530
+			if ($quota !== false) {
531 531
 				$targetUser->setQuota($quota);
532 532
 			} else {
533
-				$this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
533
+				$this->log->log('not suitable default quota found for user '.$this->uid.': ['.$defaultQuota.']', \OCP\Util::WARN);
534 534
 			}
535 535
 		} else {
536
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
536
+			$this->log->log('trying to set a quota for user '.$this->uid.' but the user is missing', \OCP\Util::ERROR);
537 537
 		}
538 538
 	}
539 539
 
@@ -547,7 +547,7 @@  discard block
 block discarded – undo
547 547
 	 * @param array $params
548 548
 	 */
549 549
 	public function updateAvatarPostLogin($params) {
550
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
550
+		if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
551 551
 			$this->updateAvatar();
552 552
 		}
553 553
 	}
@@ -557,11 +557,11 @@  discard block
 block discarded – undo
557 557
 	 * @return null
558 558
 	 */
559 559
 	public function updateAvatar() {
560
-		if($this->wasRefreshed('avatar')) {
560
+		if ($this->wasRefreshed('avatar')) {
561 561
 			return;
562 562
 		}
563 563
 		$avatarImage = $this->getAvatarImage();
564
-		if($avatarImage === false) {
564
+		if ($avatarImage === false) {
565 565
 			//not set, nothing left to do;
566 566
 			return;
567 567
 		}
@@ -574,18 +574,18 @@  discard block
 block discarded – undo
574 574
 	 * @return null
575 575
 	 */
576 576
 	private function setOwnCloudAvatar() {
577
-		if(!$this->image->valid()) {
577
+		if (!$this->image->valid()) {
578 578
 			$this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
579 579
 			return;
580 580
 		}
581 581
 		//make sure it is a square and not bigger than 128x128
582 582
 		$size = min(array($this->image->width(), $this->image->height(), 128));
583
-		if(!$this->image->centerCrop($size)) {
583
+		if (!$this->image->centerCrop($size)) {
584 584
 			$this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
585 585
 			return;
586 586
 		}
587 587
 
588
-		if(!$this->fs->isLoaded()) {
588
+		if (!$this->fs->isLoaded()) {
589 589
 			$this->fs->setup($this->uid);
590 590
 		}
591 591
 
@@ -594,7 +594,7 @@  discard block
 block discarded – undo
594 594
 			$avatar->set($this->image);
595 595
 		} catch (\Exception $e) {
596 596
 			\OC::$server->getLogger()->notice(
597
-				'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
597
+				'Could not set avatar for '.$this->dn.', because: '.$e->getMessage(),
598 598
 				['app' => 'user_ldap']);
599 599
 		}
600 600
 	}
@@ -607,17 +607,17 @@  discard block
 block discarded – undo
607 607
 	public function handlePasswordExpiry($params) {
608 608
 		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
609 609
 		if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
610
-			return;//password expiry handling disabled
610
+			return; //password expiry handling disabled
611 611
 		}
612 612
 		$uid = $params['uid'];
613
-		if(isset($uid) && $uid === $this->getUsername()) {
613
+		if (isset($uid) && $uid === $this->getUsername()) {
614 614
 			//retrieve relevant user attributes
615 615
 			$result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
616 616
 			
617
-			if(array_key_exists('pwdpolicysubentry', $result[0])) {
617
+			if (array_key_exists('pwdpolicysubentry', $result[0])) {
618 618
 				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
619
-				if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
620
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
619
+				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
620
+					$ppolicyDN = $pwdPolicySubentry[0]; //custom ppolicy DN
621 621
 				}
622 622
 			}
623 623
 			
@@ -626,9 +626,9 @@  discard block
 block discarded – undo
626 626
 			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
627 627
 			
628 628
 			//retrieve relevant password policy attributes
629
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
629
+			$cacheKey = 'ppolicyAttributes'.$ppolicyDN;
630 630
 			$result = $this->connection->getFromCache($cacheKey);
631
-			if(is_null($result)) {
631
+			if (is_null($result)) {
632 632
 				$result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
633 633
 				$this->connection->writeToCache($cacheKey, $result);
634 634
 			}
@@ -639,8 +639,8 @@  discard block
 block discarded – undo
639 639
 			
640 640
 			//handle grace login
641 641
 			$pwdGraceUseTimeCount = count($pwdGraceUseTime);
642
-			if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
643
-				if($pwdGraceAuthNLimit 
642
+			if ($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
643
+				if ($pwdGraceAuthNLimit 
644 644
 					&& (count($pwdGraceAuthNLimit) > 0)
645 645
 					&&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
646 646
 					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
@@ -653,24 +653,24 @@  discard block
 block discarded – undo
653 653
 				exit();
654 654
 			}
655 655
 			//handle pwdReset attribute
656
-			if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
656
+			if ($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
657 657
 				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
658 658
 				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
659 659
 				'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
660 660
 				exit();
661 661
 			}
662 662
 			//handle password expiry warning
663
-			if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
664
-				if($pwdMaxAge && (count($pwdMaxAge) > 0)
663
+			if ($pwdChangedTime && (count($pwdChangedTime) > 0)) {
664
+				if ($pwdMaxAge && (count($pwdMaxAge) > 0)
665 665
 					&& $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
666 666
 					$pwdMaxAgeInt = intval($pwdMaxAge[0]);
667 667
 					$pwdExpireWarningInt = intval($pwdExpireWarning[0]);
668
-					if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
668
+					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
669 669
 						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
670 670
 						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
671 671
 						$currentDateTime = new \DateTime();
672 672
 						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
673
-						if($secondsToExpiry <= $pwdExpireWarningInt) {
673
+						if ($secondsToExpiry <= $pwdExpireWarningInt) {
674 674
 							//remove last password expiry warning if any
675 675
 							$notification = $this->notificationManager->createNotification();
676 676
 							$notification->setApp('user_ldap')
Please login to merge, or discard this patch.
apps/user_ldap/lib/Mapping/AbstractMapping.php 2 patches
Indentation   +214 added lines, -214 removed lines patch added patch discarded remove patch
@@ -29,267 +29,267 @@
 block discarded – undo
29 29
 * @package OCA\User_LDAP\Mapping
30 30
 */
31 31
 abstract class AbstractMapping {
32
-	/**
33
-	 * @var \OCP\IDBConnection $dbc
34
-	 */
35
-	protected $dbc;
32
+    /**
33
+     * @var \OCP\IDBConnection $dbc
34
+     */
35
+    protected $dbc;
36 36
 
37
-	/**
38
-	 * returns the DB table name which holds the mappings
39
-	 * @return string
40
-	 */
41
-	abstract protected function getTableName();
37
+    /**
38
+     * returns the DB table name which holds the mappings
39
+     * @return string
40
+     */
41
+    abstract protected function getTableName();
42 42
 
43
-	/**
44
-	 * @param \OCP\IDBConnection $dbc
45
-	 */
46
-	public function __construct(\OCP\IDBConnection $dbc) {
47
-		$this->dbc = $dbc;
48
-	}
43
+    /**
44
+     * @param \OCP\IDBConnection $dbc
45
+     */
46
+    public function __construct(\OCP\IDBConnection $dbc) {
47
+        $this->dbc = $dbc;
48
+    }
49 49
 
50
-	/**
51
-	 * checks whether a provided string represents an existing table col
52
-	 * @param string $col
53
-	 * @return bool
54
-	 */
55
-	public function isColNameValid($col) {
56
-		switch($col) {
57
-			case 'ldap_dn':
58
-			case 'owncloud_name':
59
-			case 'directory_uuid':
60
-				return true;
61
-			default:
62
-				return false;
63
-		}
64
-	}
50
+    /**
51
+     * checks whether a provided string represents an existing table col
52
+     * @param string $col
53
+     * @return bool
54
+     */
55
+    public function isColNameValid($col) {
56
+        switch($col) {
57
+            case 'ldap_dn':
58
+            case 'owncloud_name':
59
+            case 'directory_uuid':
60
+                return true;
61
+            default:
62
+                return false;
63
+        }
64
+    }
65 65
 
66
-	/**
67
-	 * Gets the value of one column based on a provided value of another column
68
-	 * @param string $fetchCol
69
-	 * @param string $compareCol
70
-	 * @param string $search
71
-	 * @throws \Exception
72
-	 * @return string|false
73
-	 */
74
-	protected function getXbyY($fetchCol, $compareCol, $search) {
75
-		if(!$this->isColNameValid($fetchCol)) {
76
-			//this is used internally only, but we don't want to risk
77
-			//having SQL injection at all.
78
-			throw new \Exception('Invalid Column Name');
79
-		}
80
-		$query = $this->dbc->prepare('
66
+    /**
67
+     * Gets the value of one column based on a provided value of another column
68
+     * @param string $fetchCol
69
+     * @param string $compareCol
70
+     * @param string $search
71
+     * @throws \Exception
72
+     * @return string|false
73
+     */
74
+    protected function getXbyY($fetchCol, $compareCol, $search) {
75
+        if(!$this->isColNameValid($fetchCol)) {
76
+            //this is used internally only, but we don't want to risk
77
+            //having SQL injection at all.
78
+            throw new \Exception('Invalid Column Name');
79
+        }
80
+        $query = $this->dbc->prepare('
81 81
 			SELECT `' . $fetchCol . '`
82 82
 			FROM `'. $this->getTableName() .'`
83 83
 			WHERE `' . $compareCol . '` = ?
84 84
 		');
85 85
 
86
-		$res = $query->execute(array($search));
87
-		if($res !== false) {
88
-			return $query->fetchColumn();
89
-		}
86
+        $res = $query->execute(array($search));
87
+        if($res !== false) {
88
+            return $query->fetchColumn();
89
+        }
90 90
 
91
-		return false;
92
-	}
91
+        return false;
92
+    }
93 93
 
94
-	/**
95
-	 * Performs a DELETE or UPDATE query to the database.
96
-	 * @param \Doctrine\DBAL\Driver\Statement $query
97
-	 * @param array $parameters
98
-	 * @return bool true if at least one row was modified, false otherwise
99
-	 */
100
-	protected function modify($query, $parameters) {
101
-		$result = $query->execute($parameters);
102
-		return ($result === true && $query->rowCount() > 0);
103
-	}
94
+    /**
95
+     * Performs a DELETE or UPDATE query to the database.
96
+     * @param \Doctrine\DBAL\Driver\Statement $query
97
+     * @param array $parameters
98
+     * @return bool true if at least one row was modified, false otherwise
99
+     */
100
+    protected function modify($query, $parameters) {
101
+        $result = $query->execute($parameters);
102
+        return ($result === true && $query->rowCount() > 0);
103
+    }
104 104
 
105
-	/**
106
-	 * Gets the LDAP DN based on the provided name.
107
-	 * Replaces Access::ocname2dn
108
-	 * @param string $name
109
-	 * @return string|false
110
-	 */
111
-	public function getDNByName($name) {
112
-		return $this->getXbyY('ldap_dn', 'owncloud_name', $name);
113
-	}
105
+    /**
106
+     * Gets the LDAP DN based on the provided name.
107
+     * Replaces Access::ocname2dn
108
+     * @param string $name
109
+     * @return string|false
110
+     */
111
+    public function getDNByName($name) {
112
+        return $this->getXbyY('ldap_dn', 'owncloud_name', $name);
113
+    }
114 114
 
115
-	/**
116
-	 * Updates the DN based on the given UUID
117
-	 * @param string $fdn
118
-	 * @param string $uuid
119
-	 * @return bool
120
-	 */
121
-	public function setDNbyUUID($fdn, $uuid) {
122
-		$query = $this->dbc->prepare('
115
+    /**
116
+     * Updates the DN based on the given UUID
117
+     * @param string $fdn
118
+     * @param string $uuid
119
+     * @return bool
120
+     */
121
+    public function setDNbyUUID($fdn, $uuid) {
122
+        $query = $this->dbc->prepare('
123 123
 			UPDATE `' . $this->getTableName() . '`
124 124
 			SET `ldap_dn` = ?
125 125
 			WHERE `directory_uuid` = ?
126 126
 		');
127 127
 
128
-		return $this->modify($query, array($fdn, $uuid));
129
-	}
128
+        return $this->modify($query, array($fdn, $uuid));
129
+    }
130 130
 
131
-	/**
132
-	 * Updates the UUID based on the given DN
133
-	 *
134
-	 * required by Migration/UUIDFix
135
-	 *
136
-	 * @param $uuid
137
-	 * @param $fdn
138
-	 * @return bool
139
-	 */
140
-	public function setUUIDbyDN($uuid, $fdn) {
141
-		$query = $this->dbc->prepare('
131
+    /**
132
+     * Updates the UUID based on the given DN
133
+     *
134
+     * required by Migration/UUIDFix
135
+     *
136
+     * @param $uuid
137
+     * @param $fdn
138
+     * @return bool
139
+     */
140
+    public function setUUIDbyDN($uuid, $fdn) {
141
+        $query = $this->dbc->prepare('
142 142
 			UPDATE `' . $this->getTableName() . '`
143 143
 			SET `directory_uuid` = ?
144 144
 			WHERE `ldap_dn` = ?
145 145
 		');
146 146
 
147
-		return $this->modify($query, [$uuid, $fdn]);
148
-	}
147
+        return $this->modify($query, [$uuid, $fdn]);
148
+    }
149 149
 
150
-	/**
151
-	 * Gets the name based on the provided LDAP DN.
152
-	 * @param string $fdn
153
-	 * @return string|false
154
-	 */
155
-	public function getNameByDN($fdn) {
156
-		return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn);
157
-	}
150
+    /**
151
+     * Gets the name based on the provided LDAP DN.
152
+     * @param string $fdn
153
+     * @return string|false
154
+     */
155
+    public function getNameByDN($fdn) {
156
+        return $this->getXbyY('owncloud_name', 'ldap_dn', $fdn);
157
+    }
158 158
 
159
-	/**
160
-	 * Searches mapped names by the giving string in the name column
161
-	 * @param string $search
162
-	 * @param string $prefixMatch
163
-	 * @param string $postfixMatch
164
-	 * @return string[]
165
-	 */
166
-	public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
167
-		$query = $this->dbc->prepare('
159
+    /**
160
+     * Searches mapped names by the giving string in the name column
161
+     * @param string $search
162
+     * @param string $prefixMatch
163
+     * @param string $postfixMatch
164
+     * @return string[]
165
+     */
166
+    public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
167
+        $query = $this->dbc->prepare('
168 168
 			SELECT `owncloud_name`
169 169
 			FROM `'. $this->getTableName() .'`
170 170
 			WHERE `owncloud_name` LIKE ?
171 171
 		');
172 172
 
173
-		$res = $query->execute(array($prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch));
174
-		$names = array();
175
-		if($res !== false) {
176
-			while($row = $query->fetch()) {
177
-				$names[] = $row['owncloud_name'];
178
-			}
179
-		}
180
-		return $names;
181
-	}
173
+        $res = $query->execute(array($prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch));
174
+        $names = array();
175
+        if($res !== false) {
176
+            while($row = $query->fetch()) {
177
+                $names[] = $row['owncloud_name'];
178
+            }
179
+        }
180
+        return $names;
181
+    }
182 182
 
183
-	/**
184
-	 * Gets the name based on the provided LDAP UUID.
185
-	 * @param string $uuid
186
-	 * @return string|false
187
-	 */
188
-	public function getNameByUUID($uuid) {
189
-		return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
190
-	}
183
+    /**
184
+     * Gets the name based on the provided LDAP UUID.
185
+     * @param string $uuid
186
+     * @return string|false
187
+     */
188
+    public function getNameByUUID($uuid) {
189
+        return $this->getXbyY('owncloud_name', 'directory_uuid', $uuid);
190
+    }
191 191
 
192
-	/**
193
-	 * Gets the UUID based on the provided LDAP DN
194
-	 * @param string $dn
195
-	 * @return false|string
196
-	 * @throws \Exception
197
-	 */
198
-	public function getUUIDByDN($dn) {
199
-		return $this->getXbyY('directory_uuid', 'ldap_dn', $dn);
200
-	}
192
+    /**
193
+     * Gets the UUID based on the provided LDAP DN
194
+     * @param string $dn
195
+     * @return false|string
196
+     * @throws \Exception
197
+     */
198
+    public function getUUIDByDN($dn) {
199
+        return $this->getXbyY('directory_uuid', 'ldap_dn', $dn);
200
+    }
201 201
 
202
-	/**
203
-	 * gets a piece of the mapping list
204
-	 * @param int $offset
205
-	 * @param int $limit
206
-	 * @return array
207
-	 */
208
-	public function getList($offset = null, $limit = null) {
209
-		$query = $this->dbc->prepare('
202
+    /**
203
+     * gets a piece of the mapping list
204
+     * @param int $offset
205
+     * @param int $limit
206
+     * @return array
207
+     */
208
+    public function getList($offset = null, $limit = null) {
209
+        $query = $this->dbc->prepare('
210 210
 			SELECT
211 211
 				`ldap_dn` AS `dn`,
212 212
 				`owncloud_name` AS `name`,
213 213
 				`directory_uuid` AS `uuid`
214 214
 			FROM `' . $this->getTableName() . '`',
215
-			$limit,
216
-			$offset
217
-		);
215
+            $limit,
216
+            $offset
217
+        );
218 218
 
219
-		$query->execute();
220
-		return $query->fetchAll();
221
-	}
219
+        $query->execute();
220
+        return $query->fetchAll();
221
+    }
222 222
 
223
-	/**
224
-	 * attempts to map the given entry
225
-	 * @param string $fdn fully distinguished name (from LDAP)
226
-	 * @param string $name
227
-	 * @param string $uuid a unique identifier as used in LDAP
228
-	 * @return bool
229
-	 */
230
-	public function map($fdn, $name, $uuid) {
231
-		if(mb_strlen($fdn) > 255) {
232
-			\OC::$server->getLogger()->error(
233
-				'Cannot map, because the DN exceeds 255 characters: {dn}',
234
-				[
235
-					'app' => 'user_ldap',
236
-					'dn' => $fdn,
237
-				]
238
-			);
239
-			return false;
240
-		}
223
+    /**
224
+     * attempts to map the given entry
225
+     * @param string $fdn fully distinguished name (from LDAP)
226
+     * @param string $name
227
+     * @param string $uuid a unique identifier as used in LDAP
228
+     * @return bool
229
+     */
230
+    public function map($fdn, $name, $uuid) {
231
+        if(mb_strlen($fdn) > 255) {
232
+            \OC::$server->getLogger()->error(
233
+                'Cannot map, because the DN exceeds 255 characters: {dn}',
234
+                [
235
+                    'app' => 'user_ldap',
236
+                    'dn' => $fdn,
237
+                ]
238
+            );
239
+            return false;
240
+        }
241 241
 
242
-		$row = array(
243
-			'ldap_dn'        => $fdn,
244
-			'owncloud_name'  => $name,
245
-			'directory_uuid' => $uuid
246
-		);
242
+        $row = array(
243
+            'ldap_dn'        => $fdn,
244
+            'owncloud_name'  => $name,
245
+            'directory_uuid' => $uuid
246
+        );
247 247
 
248
-		try {
249
-			$result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
250
-			// insertIfNotExist returns values as int
251
-			return (bool)$result;
252
-		} catch (\Exception $e) {
253
-			return false;
254
-		}
255
-	}
248
+        try {
249
+            $result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
250
+            // insertIfNotExist returns values as int
251
+            return (bool)$result;
252
+        } catch (\Exception $e) {
253
+            return false;
254
+        }
255
+    }
256 256
 
257
-	/**
258
-	 * removes a mapping based on the owncloud_name of the entry
259
-	 * @param string $name
260
-	 * @return bool
261
-	 */
262
-	public function unmap($name) {
263
-		$query = $this->dbc->prepare('
257
+    /**
258
+     * removes a mapping based on the owncloud_name of the entry
259
+     * @param string $name
260
+     * @return bool
261
+     */
262
+    public function unmap($name) {
263
+        $query = $this->dbc->prepare('
264 264
 			DELETE FROM `'. $this->getTableName() .'`
265 265
 			WHERE `owncloud_name` = ?');
266 266
 
267
-		return $this->modify($query, array($name));
268
-	}
267
+        return $this->modify($query, array($name));
268
+    }
269 269
 
270
-	/**
271
-	 * Truncate's the mapping table
272
-	 * @return bool
273
-	 */
274
-	public function clear() {
275
-		$sql = $this->dbc
276
-			->getDatabasePlatform()
277
-			->getTruncateTableSQL('`' . $this->getTableName() . '`');
278
-		return $this->dbc->prepare($sql)->execute();
279
-	}
270
+    /**
271
+     * Truncate's the mapping table
272
+     * @return bool
273
+     */
274
+    public function clear() {
275
+        $sql = $this->dbc
276
+            ->getDatabasePlatform()
277
+            ->getTruncateTableSQL('`' . $this->getTableName() . '`');
278
+        return $this->dbc->prepare($sql)->execute();
279
+    }
280 280
 
281
-	/**
282
-	 * returns the number of entries in the mappings table
283
-	 *
284
-	 * @return int
285
-	 */
286
-	public function count() {
287
-		$qb = $this->dbc->getQueryBuilder();
288
-		$query = $qb->select($qb->createFunction('COUNT(`ldap_dn`)'))
289
-			->from($this->getTableName());
290
-		$res = $query->execute();
291
-		$count = $res->fetchColumn();
292
-		$res->closeCursor();
293
-		return (int)$count;
294
-	}
281
+    /**
282
+     * returns the number of entries in the mappings table
283
+     *
284
+     * @return int
285
+     */
286
+    public function count() {
287
+        $qb = $this->dbc->getQueryBuilder();
288
+        $query = $qb->select($qb->createFunction('COUNT(`ldap_dn`)'))
289
+            ->from($this->getTableName());
290
+        $res = $query->execute();
291
+        $count = $res->fetchColumn();
292
+        $res->closeCursor();
293
+        return (int)$count;
294
+    }
295 295
 }
Please login to merge, or discard this patch.
Spacing   +17 added lines, -17 removed lines patch added patch discarded remove patch
@@ -53,7 +53,7 @@  discard block
 block discarded – undo
53 53
 	 * @return bool
54 54
 	 */
55 55
 	public function isColNameValid($col) {
56
-		switch($col) {
56
+		switch ($col) {
57 57
 			case 'ldap_dn':
58 58
 			case 'owncloud_name':
59 59
 			case 'directory_uuid':
@@ -72,19 +72,19 @@  discard block
 block discarded – undo
72 72
 	 * @return string|false
73 73
 	 */
74 74
 	protected function getXbyY($fetchCol, $compareCol, $search) {
75
-		if(!$this->isColNameValid($fetchCol)) {
75
+		if (!$this->isColNameValid($fetchCol)) {
76 76
 			//this is used internally only, but we don't want to risk
77 77
 			//having SQL injection at all.
78 78
 			throw new \Exception('Invalid Column Name');
79 79
 		}
80 80
 		$query = $this->dbc->prepare('
81
-			SELECT `' . $fetchCol . '`
82
-			FROM `'. $this->getTableName() .'`
83
-			WHERE `' . $compareCol . '` = ?
81
+			SELECT `' . $fetchCol.'`
82
+			FROM `'. $this->getTableName().'`
83
+			WHERE `' . $compareCol.'` = ?
84 84
 		');
85 85
 
86 86
 		$res = $query->execute(array($search));
87
-		if($res !== false) {
87
+		if ($res !== false) {
88 88
 			return $query->fetchColumn();
89 89
 		}
90 90
 
@@ -120,7 +120,7 @@  discard block
 block discarded – undo
120 120
 	 */
121 121
 	public function setDNbyUUID($fdn, $uuid) {
122 122
 		$query = $this->dbc->prepare('
123
-			UPDATE `' . $this->getTableName() . '`
123
+			UPDATE `' . $this->getTableName().'`
124 124
 			SET `ldap_dn` = ?
125 125
 			WHERE `directory_uuid` = ?
126 126
 		');
@@ -139,7 +139,7 @@  discard block
 block discarded – undo
139 139
 	 */
140 140
 	public function setUUIDbyDN($uuid, $fdn) {
141 141
 		$query = $this->dbc->prepare('
142
-			UPDATE `' . $this->getTableName() . '`
142
+			UPDATE `' . $this->getTableName().'`
143 143
 			SET `directory_uuid` = ?
144 144
 			WHERE `ldap_dn` = ?
145 145
 		');
@@ -166,14 +166,14 @@  discard block
 block discarded – undo
166 166
 	public function getNamesBySearch($search, $prefixMatch = "", $postfixMatch = "") {
167 167
 		$query = $this->dbc->prepare('
168 168
 			SELECT `owncloud_name`
169
-			FROM `'. $this->getTableName() .'`
169
+			FROM `'. $this->getTableName().'`
170 170
 			WHERE `owncloud_name` LIKE ?
171 171
 		');
172 172
 
173 173
 		$res = $query->execute(array($prefixMatch.$this->dbc->escapeLikeParameter($search).$postfixMatch));
174 174
 		$names = array();
175
-		if($res !== false) {
176
-			while($row = $query->fetch()) {
175
+		if ($res !== false) {
176
+			while ($row = $query->fetch()) {
177 177
 				$names[] = $row['owncloud_name'];
178 178
 			}
179 179
 		}
@@ -211,7 +211,7 @@  discard block
 block discarded – undo
211 211
 				`ldap_dn` AS `dn`,
212 212
 				`owncloud_name` AS `name`,
213 213
 				`directory_uuid` AS `uuid`
214
-			FROM `' . $this->getTableName() . '`',
214
+			FROM `' . $this->getTableName().'`',
215 215
 			$limit,
216 216
 			$offset
217 217
 		);
@@ -228,7 +228,7 @@  discard block
 block discarded – undo
228 228
 	 * @return bool
229 229
 	 */
230 230
 	public function map($fdn, $name, $uuid) {
231
-		if(mb_strlen($fdn) > 255) {
231
+		if (mb_strlen($fdn) > 255) {
232 232
 			\OC::$server->getLogger()->error(
233 233
 				'Cannot map, because the DN exceeds 255 characters: {dn}',
234 234
 				[
@@ -248,7 +248,7 @@  discard block
 block discarded – undo
248 248
 		try {
249 249
 			$result = $this->dbc->insertIfNotExist($this->getTableName(), $row);
250 250
 			// insertIfNotExist returns values as int
251
-			return (bool)$result;
251
+			return (bool) $result;
252 252
 		} catch (\Exception $e) {
253 253
 			return false;
254 254
 		}
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	public function unmap($name) {
263 263
 		$query = $this->dbc->prepare('
264
-			DELETE FROM `'. $this->getTableName() .'`
264
+			DELETE FROM `'. $this->getTableName().'`
265 265
 			WHERE `owncloud_name` = ?');
266 266
 
267 267
 		return $this->modify($query, array($name));
@@ -274,7 +274,7 @@  discard block
 block discarded – undo
274 274
 	public function clear() {
275 275
 		$sql = $this->dbc
276 276
 			->getDatabasePlatform()
277
-			->getTruncateTableSQL('`' . $this->getTableName() . '`');
277
+			->getTruncateTableSQL('`'.$this->getTableName().'`');
278 278
 		return $this->dbc->prepare($sql)->execute();
279 279
 	}
280 280
 
@@ -290,6 +290,6 @@  discard block
 block discarded – undo
290 290
 		$res = $query->execute();
291 291
 		$count = $res->fetchColumn();
292 292
 		$res->closeCursor();
293
-		return (int)$count;
293
+		return (int) $count;
294 294
 	}
295 295
 }
Please login to merge, or discard this patch.
apps/user_ldap/composer/composer/autoload_classmap.php 1 patch
Spacing   +56 added lines, -56 removed lines patch added patch discarded remove patch
@@ -6,60 +6,60 @@
 block discarded – undo
6 6
 $baseDir = $vendorDir;
7 7
 
8 8
 return array(
9
-    'OCA\\User_LDAP\\Access' => $baseDir . '/../lib/Access.php',
10
-    'OCA\\User_LDAP\\AppInfo\\Application' => $baseDir . '/../lib/AppInfo/Application.php',
11
-    'OCA\\User_LDAP\\BackendUtility' => $baseDir . '/../lib/BackendUtility.php',
12
-    'OCA\\User_LDAP\\Command\\CheckUser' => $baseDir . '/../lib/Command/CheckUser.php',
13
-    'OCA\\User_LDAP\\Command\\CreateEmptyConfig' => $baseDir . '/../lib/Command/CreateEmptyConfig.php',
14
-    'OCA\\User_LDAP\\Command\\DeleteConfig' => $baseDir . '/../lib/Command/DeleteConfig.php',
15
-    'OCA\\User_LDAP\\Command\\Search' => $baseDir . '/../lib/Command/Search.php',
16
-    'OCA\\User_LDAP\\Command\\SetConfig' => $baseDir . '/../lib/Command/SetConfig.php',
17
-    'OCA\\User_LDAP\\Command\\ShowConfig' => $baseDir . '/../lib/Command/ShowConfig.php',
18
-    'OCA\\User_LDAP\\Command\\ShowRemnants' => $baseDir . '/../lib/Command/ShowRemnants.php',
19
-    'OCA\\User_LDAP\\Command\\TestConfig' => $baseDir . '/../lib/Command/TestConfig.php',
20
-    'OCA\\User_LDAP\\Configuration' => $baseDir . '/../lib/Configuration.php',
21
-    'OCA\\User_LDAP\\Connection' => $baseDir . '/../lib/Connection.php',
22
-    'OCA\\User_LDAP\\Controller\\ConfigAPIController' => $baseDir . '/../lib/Controller/ConfigAPIController.php',
23
-    'OCA\\User_LDAP\\Controller\\RenewPasswordController' => $baseDir . '/../lib/Controller/RenewPasswordController.php',
24
-    'OCA\\User_LDAP\\Exceptions\\ConstraintViolationException' => $baseDir . '/../lib/Exceptions/ConstraintViolationException.php',
25
-    'OCA\\User_LDAP\\Exceptions\\NotOnLDAP' => $baseDir . '/../lib/Exceptions/NotOnLDAP.php',
26
-    'OCA\\User_LDAP\\FilesystemHelper' => $baseDir . '/../lib/FilesystemHelper.php',
27
-    'OCA\\User_LDAP\\GroupPluginManager' => $baseDir . '/../lib/GroupPluginManager.php',
28
-    'OCA\\User_LDAP\\Group_LDAP' => $baseDir . '/../lib/Group_LDAP.php',
29
-    'OCA\\User_LDAP\\Group_Proxy' => $baseDir . '/../lib/Group_Proxy.php',
30
-    'OCA\\User_LDAP\\Helper' => $baseDir . '/../lib/Helper.php',
31
-    'OCA\\User_LDAP\\IGroupLDAP' => $baseDir . '/../lib/IGroupLDAP.php',
32
-    'OCA\\User_LDAP\\ILDAPGroupPlugin' => $baseDir . '/../lib/ILDAPGroupPlugin.php',
33
-    'OCA\\User_LDAP\\ILDAPUserPlugin' => $baseDir . '/../lib/ILDAPUserPlugin.php',
34
-    'OCA\\User_LDAP\\ILDAPWrapper' => $baseDir . '/../lib/ILDAPWrapper.php',
35
-    'OCA\\User_LDAP\\IUserLDAP' => $baseDir . '/../lib/IUserLDAP.php',
36
-    'OCA\\User_LDAP\\Jobs\\CleanUp' => $baseDir . '/../lib/Jobs/CleanUp.php',
37
-    'OCA\\User_LDAP\\Jobs\\Sync' => $baseDir . '/../lib/Jobs/Sync.php',
38
-    'OCA\\User_LDAP\\Jobs\\UpdateGroups' => $baseDir . '/../lib/Jobs/UpdateGroups.php',
39
-    'OCA\\User_LDAP\\LDAP' => $baseDir . '/../lib/LDAP.php',
40
-    'OCA\\User_LDAP\\LDAPProvider' => $baseDir . '/../lib/LDAPProvider.php',
41
-    'OCA\\User_LDAP\\LDAPProviderFactory' => $baseDir . '/../lib/LDAPProviderFactory.php',
42
-    'OCA\\User_LDAP\\LDAPUtility' => $baseDir . '/../lib/LDAPUtility.php',
43
-    'OCA\\User_LDAP\\LogWrapper' => $baseDir . '/../lib/LogWrapper.php',
44
-    'OCA\\User_LDAP\\Mapping\\AbstractMapping' => $baseDir . '/../lib/Mapping/AbstractMapping.php',
45
-    'OCA\\User_LDAP\\Mapping\\GroupMapping' => $baseDir . '/../lib/Mapping/GroupMapping.php',
46
-    'OCA\\User_LDAP\\Mapping\\UserMapping' => $baseDir . '/../lib/Mapping/UserMapping.php',
47
-    'OCA\\User_LDAP\\Migration\\UUIDFix' => $baseDir . '/../lib/Migration/UUIDFix.php',
48
-    'OCA\\User_LDAP\\Migration\\UUIDFixGroup' => $baseDir . '/../lib/Migration/UUIDFixGroup.php',
49
-    'OCA\\User_LDAP\\Migration\\UUIDFixInsert' => $baseDir . '/../lib/Migration/UUIDFixInsert.php',
50
-    'OCA\\User_LDAP\\Migration\\UUIDFixUser' => $baseDir . '/../lib/Migration/UUIDFixUser.php',
51
-    'OCA\\User_LDAP\\Notification\\Notifier' => $baseDir . '/../lib/Notification/Notifier.php',
52
-    'OCA\\User_LDAP\\Proxy' => $baseDir . '/../lib/Proxy.php',
53
-    'OCA\\User_LDAP\\Settings\\Admin' => $baseDir . '/../lib/Settings/Admin.php',
54
-    'OCA\\User_LDAP\\Settings\\Section' => $baseDir . '/../lib/Settings/Section.php',
55
-    'OCA\\User_LDAP\\UserPluginManager' => $baseDir . '/../lib/UserPluginManager.php',
56
-    'OCA\\User_LDAP\\User\\DeletedUsersIndex' => $baseDir . '/../lib/User/DeletedUsersIndex.php',
57
-    'OCA\\User_LDAP\\User\\IUserTools' => $baseDir . '/../lib/User/IUserTools.php',
58
-    'OCA\\User_LDAP\\User\\Manager' => $baseDir . '/../lib/User/Manager.php',
59
-    'OCA\\User_LDAP\\User\\OfflineUser' => $baseDir . '/../lib/User/OfflineUser.php',
60
-    'OCA\\User_LDAP\\User\\User' => $baseDir . '/../lib/User/User.php',
61
-    'OCA\\User_LDAP\\User_LDAP' => $baseDir . '/../lib/User_LDAP.php',
62
-    'OCA\\User_LDAP\\User_Proxy' => $baseDir . '/../lib/User_Proxy.php',
63
-    'OCA\\User_LDAP\\Wizard' => $baseDir . '/../lib/Wizard.php',
64
-    'OCA\\User_LDAP\\WizardResult' => $baseDir . '/../lib/WizardResult.php',
9
+    'OCA\\User_LDAP\\Access' => $baseDir.'/../lib/Access.php',
10
+    'OCA\\User_LDAP\\AppInfo\\Application' => $baseDir.'/../lib/AppInfo/Application.php',
11
+    'OCA\\User_LDAP\\BackendUtility' => $baseDir.'/../lib/BackendUtility.php',
12
+    'OCA\\User_LDAP\\Command\\CheckUser' => $baseDir.'/../lib/Command/CheckUser.php',
13
+    'OCA\\User_LDAP\\Command\\CreateEmptyConfig' => $baseDir.'/../lib/Command/CreateEmptyConfig.php',
14
+    'OCA\\User_LDAP\\Command\\DeleteConfig' => $baseDir.'/../lib/Command/DeleteConfig.php',
15
+    'OCA\\User_LDAP\\Command\\Search' => $baseDir.'/../lib/Command/Search.php',
16
+    'OCA\\User_LDAP\\Command\\SetConfig' => $baseDir.'/../lib/Command/SetConfig.php',
17
+    'OCA\\User_LDAP\\Command\\ShowConfig' => $baseDir.'/../lib/Command/ShowConfig.php',
18
+    'OCA\\User_LDAP\\Command\\ShowRemnants' => $baseDir.'/../lib/Command/ShowRemnants.php',
19
+    'OCA\\User_LDAP\\Command\\TestConfig' => $baseDir.'/../lib/Command/TestConfig.php',
20
+    'OCA\\User_LDAP\\Configuration' => $baseDir.'/../lib/Configuration.php',
21
+    'OCA\\User_LDAP\\Connection' => $baseDir.'/../lib/Connection.php',
22
+    'OCA\\User_LDAP\\Controller\\ConfigAPIController' => $baseDir.'/../lib/Controller/ConfigAPIController.php',
23
+    'OCA\\User_LDAP\\Controller\\RenewPasswordController' => $baseDir.'/../lib/Controller/RenewPasswordController.php',
24
+    'OCA\\User_LDAP\\Exceptions\\ConstraintViolationException' => $baseDir.'/../lib/Exceptions/ConstraintViolationException.php',
25
+    'OCA\\User_LDAP\\Exceptions\\NotOnLDAP' => $baseDir.'/../lib/Exceptions/NotOnLDAP.php',
26
+    'OCA\\User_LDAP\\FilesystemHelper' => $baseDir.'/../lib/FilesystemHelper.php',
27
+    'OCA\\User_LDAP\\GroupPluginManager' => $baseDir.'/../lib/GroupPluginManager.php',
28
+    'OCA\\User_LDAP\\Group_LDAP' => $baseDir.'/../lib/Group_LDAP.php',
29
+    'OCA\\User_LDAP\\Group_Proxy' => $baseDir.'/../lib/Group_Proxy.php',
30
+    'OCA\\User_LDAP\\Helper' => $baseDir.'/../lib/Helper.php',
31
+    'OCA\\User_LDAP\\IGroupLDAP' => $baseDir.'/../lib/IGroupLDAP.php',
32
+    'OCA\\User_LDAP\\ILDAPGroupPlugin' => $baseDir.'/../lib/ILDAPGroupPlugin.php',
33
+    'OCA\\User_LDAP\\ILDAPUserPlugin' => $baseDir.'/../lib/ILDAPUserPlugin.php',
34
+    'OCA\\User_LDAP\\ILDAPWrapper' => $baseDir.'/../lib/ILDAPWrapper.php',
35
+    'OCA\\User_LDAP\\IUserLDAP' => $baseDir.'/../lib/IUserLDAP.php',
36
+    'OCA\\User_LDAP\\Jobs\\CleanUp' => $baseDir.'/../lib/Jobs/CleanUp.php',
37
+    'OCA\\User_LDAP\\Jobs\\Sync' => $baseDir.'/../lib/Jobs/Sync.php',
38
+    'OCA\\User_LDAP\\Jobs\\UpdateGroups' => $baseDir.'/../lib/Jobs/UpdateGroups.php',
39
+    'OCA\\User_LDAP\\LDAP' => $baseDir.'/../lib/LDAP.php',
40
+    'OCA\\User_LDAP\\LDAPProvider' => $baseDir.'/../lib/LDAPProvider.php',
41
+    'OCA\\User_LDAP\\LDAPProviderFactory' => $baseDir.'/../lib/LDAPProviderFactory.php',
42
+    'OCA\\User_LDAP\\LDAPUtility' => $baseDir.'/../lib/LDAPUtility.php',
43
+    'OCA\\User_LDAP\\LogWrapper' => $baseDir.'/../lib/LogWrapper.php',
44
+    'OCA\\User_LDAP\\Mapping\\AbstractMapping' => $baseDir.'/../lib/Mapping/AbstractMapping.php',
45
+    'OCA\\User_LDAP\\Mapping\\GroupMapping' => $baseDir.'/../lib/Mapping/GroupMapping.php',
46
+    'OCA\\User_LDAP\\Mapping\\UserMapping' => $baseDir.'/../lib/Mapping/UserMapping.php',
47
+    'OCA\\User_LDAP\\Migration\\UUIDFix' => $baseDir.'/../lib/Migration/UUIDFix.php',
48
+    'OCA\\User_LDAP\\Migration\\UUIDFixGroup' => $baseDir.'/../lib/Migration/UUIDFixGroup.php',
49
+    'OCA\\User_LDAP\\Migration\\UUIDFixInsert' => $baseDir.'/../lib/Migration/UUIDFixInsert.php',
50
+    'OCA\\User_LDAP\\Migration\\UUIDFixUser' => $baseDir.'/../lib/Migration/UUIDFixUser.php',
51
+    'OCA\\User_LDAP\\Notification\\Notifier' => $baseDir.'/../lib/Notification/Notifier.php',
52
+    'OCA\\User_LDAP\\Proxy' => $baseDir.'/../lib/Proxy.php',
53
+    'OCA\\User_LDAP\\Settings\\Admin' => $baseDir.'/../lib/Settings/Admin.php',
54
+    'OCA\\User_LDAP\\Settings\\Section' => $baseDir.'/../lib/Settings/Section.php',
55
+    'OCA\\User_LDAP\\UserPluginManager' => $baseDir.'/../lib/UserPluginManager.php',
56
+    'OCA\\User_LDAP\\User\\DeletedUsersIndex' => $baseDir.'/../lib/User/DeletedUsersIndex.php',
57
+    'OCA\\User_LDAP\\User\\IUserTools' => $baseDir.'/../lib/User/IUserTools.php',
58
+    'OCA\\User_LDAP\\User\\Manager' => $baseDir.'/../lib/User/Manager.php',
59
+    'OCA\\User_LDAP\\User\\OfflineUser' => $baseDir.'/../lib/User/OfflineUser.php',
60
+    'OCA\\User_LDAP\\User\\User' => $baseDir.'/../lib/User/User.php',
61
+    'OCA\\User_LDAP\\User_LDAP' => $baseDir.'/../lib/User_LDAP.php',
62
+    'OCA\\User_LDAP\\User_Proxy' => $baseDir.'/../lib/User_Proxy.php',
63
+    'OCA\\User_LDAP\\Wizard' => $baseDir.'/../lib/Wizard.php',
64
+    'OCA\\User_LDAP\\WizardResult' => $baseDir.'/../lib/WizardResult.php',
65 65
 );
Please login to merge, or discard this patch.
apps/user_ldap/composer/composer/autoload_static.php 1 patch
Spacing   +63 added lines, -63 removed lines patch added patch discarded remove patch
@@ -6,82 +6,82 @@
 block discarded – undo
6 6
 
7 7
 class ComposerStaticInitUser_LDAP
8 8
 {
9
-    public static $prefixLengthsPsr4 = array (
9
+    public static $prefixLengthsPsr4 = array(
10 10
         'O' => 
11
-        array (
11
+        array(
12 12
             'OCA\\User_LDAP\\' => 14,
13 13
         ),
14 14
     );
15 15
 
16
-    public static $prefixDirsPsr4 = array (
16
+    public static $prefixDirsPsr4 = array(
17 17
         'OCA\\User_LDAP\\' => 
18
-        array (
19
-            0 => __DIR__ . '/..' . '/../lib',
18
+        array(
19
+            0 => __DIR__.'/..'.'/../lib',
20 20
         ),
21 21
     );
22 22
 
23
-    public static $classMap = array (
24
-        'OCA\\User_LDAP\\Access' => __DIR__ . '/..' . '/../lib/Access.php',
25
-        'OCA\\User_LDAP\\AppInfo\\Application' => __DIR__ . '/..' . '/../lib/AppInfo/Application.php',
26
-        'OCA\\User_LDAP\\BackendUtility' => __DIR__ . '/..' . '/../lib/BackendUtility.php',
27
-        'OCA\\User_LDAP\\Command\\CheckUser' => __DIR__ . '/..' . '/../lib/Command/CheckUser.php',
28
-        'OCA\\User_LDAP\\Command\\CreateEmptyConfig' => __DIR__ . '/..' . '/../lib/Command/CreateEmptyConfig.php',
29
-        'OCA\\User_LDAP\\Command\\DeleteConfig' => __DIR__ . '/..' . '/../lib/Command/DeleteConfig.php',
30
-        'OCA\\User_LDAP\\Command\\Search' => __DIR__ . '/..' . '/../lib/Command/Search.php',
31
-        'OCA\\User_LDAP\\Command\\SetConfig' => __DIR__ . '/..' . '/../lib/Command/SetConfig.php',
32
-        'OCA\\User_LDAP\\Command\\ShowConfig' => __DIR__ . '/..' . '/../lib/Command/ShowConfig.php',
33
-        'OCA\\User_LDAP\\Command\\ShowRemnants' => __DIR__ . '/..' . '/../lib/Command/ShowRemnants.php',
34
-        'OCA\\User_LDAP\\Command\\TestConfig' => __DIR__ . '/..' . '/../lib/Command/TestConfig.php',
35
-        'OCA\\User_LDAP\\Configuration' => __DIR__ . '/..' . '/../lib/Configuration.php',
36
-        'OCA\\User_LDAP\\Connection' => __DIR__ . '/..' . '/../lib/Connection.php',
37
-        'OCA\\User_LDAP\\Controller\\ConfigAPIController' => __DIR__ . '/..' . '/../lib/Controller/ConfigAPIController.php',
38
-        'OCA\\User_LDAP\\Controller\\RenewPasswordController' => __DIR__ . '/..' . '/../lib/Controller/RenewPasswordController.php',
39
-        'OCA\\User_LDAP\\Exceptions\\ConstraintViolationException' => __DIR__ . '/..' . '/../lib/Exceptions/ConstraintViolationException.php',
40
-        'OCA\\User_LDAP\\Exceptions\\NotOnLDAP' => __DIR__ . '/..' . '/../lib/Exceptions/NotOnLDAP.php',
41
-        'OCA\\User_LDAP\\FilesystemHelper' => __DIR__ . '/..' . '/../lib/FilesystemHelper.php',
42
-        'OCA\\User_LDAP\\GroupPluginManager' => __DIR__ . '/..' . '/../lib/GroupPluginManager.php',
43
-        'OCA\\User_LDAP\\Group_LDAP' => __DIR__ . '/..' . '/../lib/Group_LDAP.php',
44
-        'OCA\\User_LDAP\\Group_Proxy' => __DIR__ . '/..' . '/../lib/Group_Proxy.php',
45
-        'OCA\\User_LDAP\\Helper' => __DIR__ . '/..' . '/../lib/Helper.php',
46
-        'OCA\\User_LDAP\\IGroupLDAP' => __DIR__ . '/..' . '/../lib/IGroupLDAP.php',
47
-        'OCA\\User_LDAP\\ILDAPGroupPlugin' => __DIR__ . '/..' . '/../lib/ILDAPGroupPlugin.php',
48
-        'OCA\\User_LDAP\\ILDAPUserPlugin' => __DIR__ . '/..' . '/../lib/ILDAPUserPlugin.php',
49
-        'OCA\\User_LDAP\\ILDAPWrapper' => __DIR__ . '/..' . '/../lib/ILDAPWrapper.php',
50
-        'OCA\\User_LDAP\\IUserLDAP' => __DIR__ . '/..' . '/../lib/IUserLDAP.php',
51
-        'OCA\\User_LDAP\\Jobs\\CleanUp' => __DIR__ . '/..' . '/../lib/Jobs/CleanUp.php',
52
-        'OCA\\User_LDAP\\Jobs\\Sync' => __DIR__ . '/..' . '/../lib/Jobs/Sync.php',
53
-        'OCA\\User_LDAP\\Jobs\\UpdateGroups' => __DIR__ . '/..' . '/../lib/Jobs/UpdateGroups.php',
54
-        'OCA\\User_LDAP\\LDAP' => __DIR__ . '/..' . '/../lib/LDAP.php',
55
-        'OCA\\User_LDAP\\LDAPProvider' => __DIR__ . '/..' . '/../lib/LDAPProvider.php',
56
-        'OCA\\User_LDAP\\LDAPProviderFactory' => __DIR__ . '/..' . '/../lib/LDAPProviderFactory.php',
57
-        'OCA\\User_LDAP\\LDAPUtility' => __DIR__ . '/..' . '/../lib/LDAPUtility.php',
58
-        'OCA\\User_LDAP\\LogWrapper' => __DIR__ . '/..' . '/../lib/LogWrapper.php',
59
-        'OCA\\User_LDAP\\Mapping\\AbstractMapping' => __DIR__ . '/..' . '/../lib/Mapping/AbstractMapping.php',
60
-        'OCA\\User_LDAP\\Mapping\\GroupMapping' => __DIR__ . '/..' . '/../lib/Mapping/GroupMapping.php',
61
-        'OCA\\User_LDAP\\Mapping\\UserMapping' => __DIR__ . '/..' . '/../lib/Mapping/UserMapping.php',
62
-        'OCA\\User_LDAP\\Migration\\UUIDFix' => __DIR__ . '/..' . '/../lib/Migration/UUIDFix.php',
63
-        'OCA\\User_LDAP\\Migration\\UUIDFixGroup' => __DIR__ . '/..' . '/../lib/Migration/UUIDFixGroup.php',
64
-        'OCA\\User_LDAP\\Migration\\UUIDFixInsert' => __DIR__ . '/..' . '/../lib/Migration/UUIDFixInsert.php',
65
-        'OCA\\User_LDAP\\Migration\\UUIDFixUser' => __DIR__ . '/..' . '/../lib/Migration/UUIDFixUser.php',
66
-        'OCA\\User_LDAP\\Notification\\Notifier' => __DIR__ . '/..' . '/../lib/Notification/Notifier.php',
67
-        'OCA\\User_LDAP\\Proxy' => __DIR__ . '/..' . '/../lib/Proxy.php',
68
-        'OCA\\User_LDAP\\Settings\\Admin' => __DIR__ . '/..' . '/../lib/Settings/Admin.php',
69
-        'OCA\\User_LDAP\\Settings\\Section' => __DIR__ . '/..' . '/../lib/Settings/Section.php',
70
-        'OCA\\User_LDAP\\UserPluginManager' => __DIR__ . '/..' . '/../lib/UserPluginManager.php',
71
-        'OCA\\User_LDAP\\User\\DeletedUsersIndex' => __DIR__ . '/..' . '/../lib/User/DeletedUsersIndex.php',
72
-        'OCA\\User_LDAP\\User\\IUserTools' => __DIR__ . '/..' . '/../lib/User/IUserTools.php',
73
-        'OCA\\User_LDAP\\User\\Manager' => __DIR__ . '/..' . '/../lib/User/Manager.php',
74
-        'OCA\\User_LDAP\\User\\OfflineUser' => __DIR__ . '/..' . '/../lib/User/OfflineUser.php',
75
-        'OCA\\User_LDAP\\User\\User' => __DIR__ . '/..' . '/../lib/User/User.php',
76
-        'OCA\\User_LDAP\\User_LDAP' => __DIR__ . '/..' . '/../lib/User_LDAP.php',
77
-        'OCA\\User_LDAP\\User_Proxy' => __DIR__ . '/..' . '/../lib/User_Proxy.php',
78
-        'OCA\\User_LDAP\\Wizard' => __DIR__ . '/..' . '/../lib/Wizard.php',
79
-        'OCA\\User_LDAP\\WizardResult' => __DIR__ . '/..' . '/../lib/WizardResult.php',
23
+    public static $classMap = array(
24
+        'OCA\\User_LDAP\\Access' => __DIR__.'/..'.'/../lib/Access.php',
25
+        'OCA\\User_LDAP\\AppInfo\\Application' => __DIR__.'/..'.'/../lib/AppInfo/Application.php',
26
+        'OCA\\User_LDAP\\BackendUtility' => __DIR__.'/..'.'/../lib/BackendUtility.php',
27
+        'OCA\\User_LDAP\\Command\\CheckUser' => __DIR__.'/..'.'/../lib/Command/CheckUser.php',
28
+        'OCA\\User_LDAP\\Command\\CreateEmptyConfig' => __DIR__.'/..'.'/../lib/Command/CreateEmptyConfig.php',
29
+        'OCA\\User_LDAP\\Command\\DeleteConfig' => __DIR__.'/..'.'/../lib/Command/DeleteConfig.php',
30
+        'OCA\\User_LDAP\\Command\\Search' => __DIR__.'/..'.'/../lib/Command/Search.php',
31
+        'OCA\\User_LDAP\\Command\\SetConfig' => __DIR__.'/..'.'/../lib/Command/SetConfig.php',
32
+        'OCA\\User_LDAP\\Command\\ShowConfig' => __DIR__.'/..'.'/../lib/Command/ShowConfig.php',
33
+        'OCA\\User_LDAP\\Command\\ShowRemnants' => __DIR__.'/..'.'/../lib/Command/ShowRemnants.php',
34
+        'OCA\\User_LDAP\\Command\\TestConfig' => __DIR__.'/..'.'/../lib/Command/TestConfig.php',
35
+        'OCA\\User_LDAP\\Configuration' => __DIR__.'/..'.'/../lib/Configuration.php',
36
+        'OCA\\User_LDAP\\Connection' => __DIR__.'/..'.'/../lib/Connection.php',
37
+        'OCA\\User_LDAP\\Controller\\ConfigAPIController' => __DIR__.'/..'.'/../lib/Controller/ConfigAPIController.php',
38
+        'OCA\\User_LDAP\\Controller\\RenewPasswordController' => __DIR__.'/..'.'/../lib/Controller/RenewPasswordController.php',
39
+        'OCA\\User_LDAP\\Exceptions\\ConstraintViolationException' => __DIR__.'/..'.'/../lib/Exceptions/ConstraintViolationException.php',
40
+        'OCA\\User_LDAP\\Exceptions\\NotOnLDAP' => __DIR__.'/..'.'/../lib/Exceptions/NotOnLDAP.php',
41
+        'OCA\\User_LDAP\\FilesystemHelper' => __DIR__.'/..'.'/../lib/FilesystemHelper.php',
42
+        'OCA\\User_LDAP\\GroupPluginManager' => __DIR__.'/..'.'/../lib/GroupPluginManager.php',
43
+        'OCA\\User_LDAP\\Group_LDAP' => __DIR__.'/..'.'/../lib/Group_LDAP.php',
44
+        'OCA\\User_LDAP\\Group_Proxy' => __DIR__.'/..'.'/../lib/Group_Proxy.php',
45
+        'OCA\\User_LDAP\\Helper' => __DIR__.'/..'.'/../lib/Helper.php',
46
+        'OCA\\User_LDAP\\IGroupLDAP' => __DIR__.'/..'.'/../lib/IGroupLDAP.php',
47
+        'OCA\\User_LDAP\\ILDAPGroupPlugin' => __DIR__.'/..'.'/../lib/ILDAPGroupPlugin.php',
48
+        'OCA\\User_LDAP\\ILDAPUserPlugin' => __DIR__.'/..'.'/../lib/ILDAPUserPlugin.php',
49
+        'OCA\\User_LDAP\\ILDAPWrapper' => __DIR__.'/..'.'/../lib/ILDAPWrapper.php',
50
+        'OCA\\User_LDAP\\IUserLDAP' => __DIR__.'/..'.'/../lib/IUserLDAP.php',
51
+        'OCA\\User_LDAP\\Jobs\\CleanUp' => __DIR__.'/..'.'/../lib/Jobs/CleanUp.php',
52
+        'OCA\\User_LDAP\\Jobs\\Sync' => __DIR__.'/..'.'/../lib/Jobs/Sync.php',
53
+        'OCA\\User_LDAP\\Jobs\\UpdateGroups' => __DIR__.'/..'.'/../lib/Jobs/UpdateGroups.php',
54
+        'OCA\\User_LDAP\\LDAP' => __DIR__.'/..'.'/../lib/LDAP.php',
55
+        'OCA\\User_LDAP\\LDAPProvider' => __DIR__.'/..'.'/../lib/LDAPProvider.php',
56
+        'OCA\\User_LDAP\\LDAPProviderFactory' => __DIR__.'/..'.'/../lib/LDAPProviderFactory.php',
57
+        'OCA\\User_LDAP\\LDAPUtility' => __DIR__.'/..'.'/../lib/LDAPUtility.php',
58
+        'OCA\\User_LDAP\\LogWrapper' => __DIR__.'/..'.'/../lib/LogWrapper.php',
59
+        'OCA\\User_LDAP\\Mapping\\AbstractMapping' => __DIR__.'/..'.'/../lib/Mapping/AbstractMapping.php',
60
+        'OCA\\User_LDAP\\Mapping\\GroupMapping' => __DIR__.'/..'.'/../lib/Mapping/GroupMapping.php',
61
+        'OCA\\User_LDAP\\Mapping\\UserMapping' => __DIR__.'/..'.'/../lib/Mapping/UserMapping.php',
62
+        'OCA\\User_LDAP\\Migration\\UUIDFix' => __DIR__.'/..'.'/../lib/Migration/UUIDFix.php',
63
+        'OCA\\User_LDAP\\Migration\\UUIDFixGroup' => __DIR__.'/..'.'/../lib/Migration/UUIDFixGroup.php',
64
+        'OCA\\User_LDAP\\Migration\\UUIDFixInsert' => __DIR__.'/..'.'/../lib/Migration/UUIDFixInsert.php',
65
+        'OCA\\User_LDAP\\Migration\\UUIDFixUser' => __DIR__.'/..'.'/../lib/Migration/UUIDFixUser.php',
66
+        'OCA\\User_LDAP\\Notification\\Notifier' => __DIR__.'/..'.'/../lib/Notification/Notifier.php',
67
+        'OCA\\User_LDAP\\Proxy' => __DIR__.'/..'.'/../lib/Proxy.php',
68
+        'OCA\\User_LDAP\\Settings\\Admin' => __DIR__.'/..'.'/../lib/Settings/Admin.php',
69
+        'OCA\\User_LDAP\\Settings\\Section' => __DIR__.'/..'.'/../lib/Settings/Section.php',
70
+        'OCA\\User_LDAP\\UserPluginManager' => __DIR__.'/..'.'/../lib/UserPluginManager.php',
71
+        'OCA\\User_LDAP\\User\\DeletedUsersIndex' => __DIR__.'/..'.'/../lib/User/DeletedUsersIndex.php',
72
+        'OCA\\User_LDAP\\User\\IUserTools' => __DIR__.'/..'.'/../lib/User/IUserTools.php',
73
+        'OCA\\User_LDAP\\User\\Manager' => __DIR__.'/..'.'/../lib/User/Manager.php',
74
+        'OCA\\User_LDAP\\User\\OfflineUser' => __DIR__.'/..'.'/../lib/User/OfflineUser.php',
75
+        'OCA\\User_LDAP\\User\\User' => __DIR__.'/..'.'/../lib/User/User.php',
76
+        'OCA\\User_LDAP\\User_LDAP' => __DIR__.'/..'.'/../lib/User_LDAP.php',
77
+        'OCA\\User_LDAP\\User_Proxy' => __DIR__.'/..'.'/../lib/User_Proxy.php',
78
+        'OCA\\User_LDAP\\Wizard' => __DIR__.'/..'.'/../lib/Wizard.php',
79
+        'OCA\\User_LDAP\\WizardResult' => __DIR__.'/..'.'/../lib/WizardResult.php',
80 80
     );
81 81
 
82 82
     public static function getInitializer(ClassLoader $loader)
83 83
     {
84
-        return \Closure::bind(function () use ($loader) {
84
+        return \Closure::bind(function() use ($loader) {
85 85
             $loader->prefixLengthsPsr4 = ComposerStaticInitUser_LDAP::$prefixLengthsPsr4;
86 86
             $loader->prefixDirsPsr4 = ComposerStaticInitUser_LDAP::$prefixDirsPsr4;
87 87
             $loader->classMap = ComposerStaticInitUser_LDAP::$classMap;
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_LDAP.php 1 patch
Indentation   +566 added lines, -566 removed lines patch added patch discarded remove patch
@@ -50,574 +50,574 @@
 block discarded – undo
50 50
 use OCP\Util;
51 51
 
52 52
 class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
53
-	/** @var \OCP\IConfig */
54
-	protected $ocConfig;
55
-
56
-	/** @var INotificationManager */
57
-	protected $notificationManager;
58
-
59
-	/** @var string */
60
-	protected $currentUserInDeletionProcess;
61
-
62
-	/** @var UserPluginManager */
63
-	protected $userPluginManager;
64
-
65
-	/**
66
-	 * @param Access $access
67
-	 * @param \OCP\IConfig $ocConfig
68
-	 * @param \OCP\Notification\IManager $notificationManager
69
-	 * @param IUserSession $userSession
70
-	 */
71
-	public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
72
-		parent::__construct($access);
73
-		$this->ocConfig = $ocConfig;
74
-		$this->notificationManager = $notificationManager;
75
-		$this->userPluginManager = $userPluginManager;
76
-		$this->registerHooks($userSession);
77
-	}
78
-
79
-	protected function registerHooks(IUserSession $userSession) {
80
-		$userSession->listen('\OC\User', 'preDelete', [$this, 'preDeleteUser']);
81
-		$userSession->listen('\OC\User', 'postDelete', [$this, 'postDeleteUser']);
82
-	}
83
-
84
-	public function preDeleteUser(IUser $user) {
85
-		$this->currentUserInDeletionProcess = $user->getUID();
86
-	}
87
-
88
-	public function postDeleteUser() {
89
-		$this->currentUserInDeletionProcess = null;
90
-	}
91
-
92
-	/**
93
-	 * checks whether the user is allowed to change his avatar in Nextcloud
94
-	 * @param string $uid the Nextcloud user name
95
-	 * @return boolean either the user can or cannot
96
-	 */
97
-	public function canChangeAvatar($uid) {
98
-		if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
99
-			return $this->userPluginManager->canChangeAvatar($uid);
100
-		}
101
-
102
-		$user = $this->access->userManager->get($uid);
103
-		if(!$user instanceof User) {
104
-			return false;
105
-		}
106
-		if($user->getAvatarImage() === false) {
107
-			return true;
108
-		}
109
-
110
-		return false;
111
-	}
112
-
113
-	/**
114
-	 * returns the username for the given login name, if available
115
-	 *
116
-	 * @param string $loginName
117
-	 * @return string|false
118
-	 */
119
-	public function loginName2UserName($loginName) {
120
-		$cacheKey = 'loginName2UserName-'.$loginName;
121
-		$username = $this->access->connection->getFromCache($cacheKey);
122
-		if(!is_null($username)) {
123
-			return $username;
124
-		}
125
-
126
-		try {
127
-			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
128
-			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
129
-			if($user instanceof OfflineUser) {
130
-				// this path is not really possible, however get() is documented
131
-				// to return User or OfflineUser so we are very defensive here.
132
-				$this->access->connection->writeToCache($cacheKey, false);
133
-				return false;
134
-			}
135
-			$username = $user->getUsername();
136
-			$this->access->connection->writeToCache($cacheKey, $username);
137
-			return $username;
138
-		} catch (NotOnLDAP $e) {
139
-			$this->access->connection->writeToCache($cacheKey, false);
140
-			return false;
141
-		}
142
-	}
53
+    /** @var \OCP\IConfig */
54
+    protected $ocConfig;
55
+
56
+    /** @var INotificationManager */
57
+    protected $notificationManager;
58
+
59
+    /** @var string */
60
+    protected $currentUserInDeletionProcess;
61
+
62
+    /** @var UserPluginManager */
63
+    protected $userPluginManager;
64
+
65
+    /**
66
+     * @param Access $access
67
+     * @param \OCP\IConfig $ocConfig
68
+     * @param \OCP\Notification\IManager $notificationManager
69
+     * @param IUserSession $userSession
70
+     */
71
+    public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
72
+        parent::__construct($access);
73
+        $this->ocConfig = $ocConfig;
74
+        $this->notificationManager = $notificationManager;
75
+        $this->userPluginManager = $userPluginManager;
76
+        $this->registerHooks($userSession);
77
+    }
78
+
79
+    protected function registerHooks(IUserSession $userSession) {
80
+        $userSession->listen('\OC\User', 'preDelete', [$this, 'preDeleteUser']);
81
+        $userSession->listen('\OC\User', 'postDelete', [$this, 'postDeleteUser']);
82
+    }
83
+
84
+    public function preDeleteUser(IUser $user) {
85
+        $this->currentUserInDeletionProcess = $user->getUID();
86
+    }
87
+
88
+    public function postDeleteUser() {
89
+        $this->currentUserInDeletionProcess = null;
90
+    }
91
+
92
+    /**
93
+     * checks whether the user is allowed to change his avatar in Nextcloud
94
+     * @param string $uid the Nextcloud user name
95
+     * @return boolean either the user can or cannot
96
+     */
97
+    public function canChangeAvatar($uid) {
98
+        if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
99
+            return $this->userPluginManager->canChangeAvatar($uid);
100
+        }
101
+
102
+        $user = $this->access->userManager->get($uid);
103
+        if(!$user instanceof User) {
104
+            return false;
105
+        }
106
+        if($user->getAvatarImage() === false) {
107
+            return true;
108
+        }
109
+
110
+        return false;
111
+    }
112
+
113
+    /**
114
+     * returns the username for the given login name, if available
115
+     *
116
+     * @param string $loginName
117
+     * @return string|false
118
+     */
119
+    public function loginName2UserName($loginName) {
120
+        $cacheKey = 'loginName2UserName-'.$loginName;
121
+        $username = $this->access->connection->getFromCache($cacheKey);
122
+        if(!is_null($username)) {
123
+            return $username;
124
+        }
125
+
126
+        try {
127
+            $ldapRecord = $this->getLDAPUserByLoginName($loginName);
128
+            $user = $this->access->userManager->get($ldapRecord['dn'][0]);
129
+            if($user instanceof OfflineUser) {
130
+                // this path is not really possible, however get() is documented
131
+                // to return User or OfflineUser so we are very defensive here.
132
+                $this->access->connection->writeToCache($cacheKey, false);
133
+                return false;
134
+            }
135
+            $username = $user->getUsername();
136
+            $this->access->connection->writeToCache($cacheKey, $username);
137
+            return $username;
138
+        } catch (NotOnLDAP $e) {
139
+            $this->access->connection->writeToCache($cacheKey, false);
140
+            return false;
141
+        }
142
+    }
143 143
 	
144
-	/**
145
-	 * returns the username for the given LDAP DN, if available
146
-	 *
147
-	 * @param string $dn
148
-	 * @return string|false with the username
149
-	 */
150
-	public function dn2UserName($dn) {
151
-		return $this->access->dn2username($dn);
152
-	}
153
-
154
-	/**
155
-	 * returns an LDAP record based on a given login name
156
-	 *
157
-	 * @param string $loginName
158
-	 * @return array
159
-	 * @throws NotOnLDAP
160
-	 */
161
-	public function getLDAPUserByLoginName($loginName) {
162
-		//find out dn of the user name
163
-		$attrs = $this->access->userManager->getAttributes();
164
-		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
165
-		if(count($users) < 1) {
166
-			throw new NotOnLDAP('No user available for the given login name on ' .
167
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
168
-		}
169
-		return $users[0];
170
-	}
171
-
172
-	/**
173
-	 * Check if the password is correct without logging in the user
174
-	 *
175
-	 * @param string $uid The username
176
-	 * @param string $password The password
177
-	 * @return false|string
178
-	 */
179
-	public function checkPassword($uid, $password) {
180
-		try {
181
-			$ldapRecord = $this->getLDAPUserByLoginName($uid);
182
-		} catch(NotOnLDAP $e) {
183
-			if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
184
-				\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
185
-			}
186
-			return false;
187
-		}
188
-		$dn = $ldapRecord['dn'][0];
189
-		$user = $this->access->userManager->get($dn);
190
-
191
-		if(!$user instanceof User) {
192
-			Util::writeLog('user_ldap',
193
-				'LDAP Login: Could not get user object for DN ' . $dn .
194
-				'. Maybe the LDAP entry has no set display name attribute?',
195
-				Util::WARN);
196
-			return false;
197
-		}
198
-		if($user->getUsername() !== false) {
199
-			//are the credentials OK?
200
-			if(!$this->access->areCredentialsValid($dn, $password)) {
201
-				return false;
202
-			}
203
-
204
-			$this->access->cacheUserExists($user->getUsername());
205
-			$user->processAttributes($ldapRecord);
206
-			$user->markLogin();
207
-
208
-			return $user->getUsername();
209
-		}
210
-
211
-		return false;
212
-	}
213
-
214
-	/**
215
-	 * Set password
216
-	 * @param string $uid The username
217
-	 * @param string $password The new password
218
-	 * @return bool
219
-	 */
220
-	public function setPassword($uid, $password) {
221
-		if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
222
-			return $this->userPluginManager->setPassword($uid, $password);
223
-		}
224
-
225
-		$user = $this->access->userManager->get($uid);
226
-
227
-		if(!$user instanceof User) {
228
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
229
-				'. Maybe the LDAP entry has no set display name attribute?');
230
-		}
231
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
232
-			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
233
-			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
234
-			if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
235
-				//remove last password expiry warning if any
236
-				$notification = $this->notificationManager->createNotification();
237
-				$notification->setApp('user_ldap')
238
-					->setUser($uid)
239
-					->setObject('pwd_exp_warn', $uid)
240
-				;
241
-				$this->notificationManager->markProcessed($notification);
242
-			}
243
-			return true;
244
-		}
245
-
246
-		return false;
247
-	}
248
-
249
-	/**
250
-	 * Get a list of all users
251
-	 *
252
-	 * @param string $search
253
-	 * @param integer $limit
254
-	 * @param integer $offset
255
-	 * @return string[] an array of all uids
256
-	 */
257
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
258
-		$search = $this->access->escapeFilterPart($search, true);
259
-		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
260
-
261
-		//check if users are cached, if so return
262
-		$ldap_users = $this->access->connection->getFromCache($cachekey);
263
-		if(!is_null($ldap_users)) {
264
-			return $ldap_users;
265
-		}
266
-
267
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
268
-		// error. With a limit of 0, we get 0 results. So we pass null.
269
-		if($limit <= 0) {
270
-			$limit = null;
271
-		}
272
-		$filter = $this->access->combineFilterWithAnd(array(
273
-			$this->access->connection->ldapUserFilter,
274
-			$this->access->connection->ldapUserDisplayName . '=*',
275
-			$this->access->getFilterPartForUserSearch($search)
276
-		));
277
-
278
-		Util::writeLog('user_ldap',
279
-			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
280
-			Util::DEBUG);
281
-		//do the search and translate results to Nextcloud names
282
-		$ldap_users = $this->access->fetchListOfUsers(
283
-			$filter,
284
-			$this->access->userManager->getAttributes(true),
285
-			$limit, $offset);
286
-		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
287
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
288
-
289
-		$this->access->connection->writeToCache($cachekey, $ldap_users);
290
-		return $ldap_users;
291
-	}
292
-
293
-	/**
294
-	 * checks whether a user is still available on LDAP
295
-	 *
296
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
297
-	 * name or an instance of that user
298
-	 * @return bool
299
-	 * @throws \Exception
300
-	 * @throws \OC\ServerNotAvailableException
301
-	 */
302
-	public function userExistsOnLDAP($user) {
303
-		if(is_string($user)) {
304
-			$user = $this->access->userManager->get($user);
305
-		}
306
-		if(is_null($user)) {
307
-			return false;
308
-		}
309
-
310
-		$dn = $user->getDN();
311
-		//check if user really still exists by reading its entry
312
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
313
-			$lcr = $this->access->connection->getConnectionResource();
314
-			if(is_null($lcr)) {
315
-				throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
316
-			}
317
-
318
-			try {
319
-				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
320
-				if(!$uuid) {
321
-					return false;
322
-				}
323
-				$newDn = $this->access->getUserDnByUuid($uuid);
324
-				//check if renamed user is still valid by reapplying the ldap filter
325
-				if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
326
-					return false;
327
-				}
328
-				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
329
-				return true;
330
-			} catch (\Exception $e) {
331
-				return false;
332
-			}
333
-		}
334
-
335
-		if($user instanceof OfflineUser) {
336
-			$user->unmark();
337
-		}
338
-
339
-		return true;
340
-	}
341
-
342
-	/**
343
-	 * check if a user exists
344
-	 * @param string $uid the username
345
-	 * @return boolean
346
-	 * @throws \Exception when connection could not be established
347
-	 */
348
-	public function userExists($uid) {
349
-		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
-		if(!is_null($userExists)) {
351
-			return (bool)$userExists;
352
-		}
353
-		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354
-		$user = $this->access->userManager->get($uid);
355
-
356
-		if(is_null($user)) {
357
-			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358
-				$this->access->connection->ldapHost, Util::DEBUG);
359
-			$this->access->connection->writeToCache('userExists'.$uid, false);
360
-			return false;
361
-		} else if($user instanceof OfflineUser) {
362
-			//express check for users marked as deleted. Returning true is
363
-			//necessary for cleanup
364
-			return true;
365
-		}
366
-
367
-		$result = $this->userExistsOnLDAP($user);
368
-		$this->access->connection->writeToCache('userExists'.$uid, $result);
369
-		if($result === true) {
370
-			$user->update();
371
-		}
372
-		return $result;
373
-	}
374
-
375
-	/**
376
-	* returns whether a user was deleted in LDAP
377
-	*
378
-	* @param string $uid The username of the user to delete
379
-	* @return bool
380
-	*/
381
-	public function deleteUser($uid) {
382
-		if ($this->userPluginManager->canDeleteUser()) {
383
-			return $this->userPluginManager->deleteUser($uid);
384
-		}
385
-
386
-		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
387
-		if(intval($marked) === 0) {
388
-			\OC::$server->getLogger()->notice(
389
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
390
-				array('app' => 'user_ldap'));
391
-			return false;
392
-		}
393
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
394
-			array('app' => 'user_ldap'));
395
-
396
-		$this->access->getUserMapper()->unmap($uid);
397
-		$this->access->userManager->invalidate($uid);
398
-		return true;
399
-	}
400
-
401
-	/**
402
-	 * get the user's home directory
403
-	 *
404
-	 * @param string $uid the username
405
-	 * @return bool|string
406
-	 * @throws NoUserException
407
-	 * @throws \Exception
408
-	 */
409
-	public function getHome($uid) {
410
-		// user Exists check required as it is not done in user proxy!
411
-		if(!$this->userExists($uid)) {
412
-			return false;
413
-		}
414
-
415
-		if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
416
-			return $this->userPluginManager->getHome($uid);
417
-		}
418
-
419
-		$cacheKey = 'getHome'.$uid;
420
-		$path = $this->access->connection->getFromCache($cacheKey);
421
-		if(!is_null($path)) {
422
-			return $path;
423
-		}
424
-
425
-		// early return path if it is a deleted user
426
-		$user = $this->access->userManager->get($uid);
427
-		if($user instanceof OfflineUser) {
428
-			if($this->currentUserInDeletionProcess !== null
429
-				&& $this->currentUserInDeletionProcess === $user->getOCName()
430
-			) {
431
-				return $user->getHomePath();
432
-			} else {
433
-				throw new NoUserException($uid . ' is not a valid user anymore');
434
-			}
435
-		} else if ($user === null) {
436
-			throw new NoUserException($uid . ' is not a valid user anymore');
437
-		}
438
-
439
-		$path = $user->getHomePath();
440
-		$this->access->cacheUserHome($uid, $path);
441
-
442
-		return $path;
443
-	}
444
-
445
-	/**
446
-	 * get display name of the user
447
-	 * @param string $uid user ID of the user
448
-	 * @return string|false display name
449
-	 */
450
-	public function getDisplayName($uid) {
451
-		if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
452
-			return $this->userPluginManager->getDisplayName($uid);
453
-		}
454
-
455
-		if(!$this->userExists($uid)) {
456
-			return false;
457
-		}
458
-
459
-		$cacheKey = 'getDisplayName'.$uid;
460
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
461
-			return $displayName;
462
-		}
463
-
464
-		//Check whether the display name is configured to have a 2nd feature
465
-		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
466
-		$displayName2 = '';
467
-		if ($additionalAttribute !== '') {
468
-			$displayName2 = $this->access->readAttribute(
469
-				$this->access->username2dn($uid),
470
-				$additionalAttribute);
471
-		}
472
-
473
-		$displayName = $this->access->readAttribute(
474
-			$this->access->username2dn($uid),
475
-			$this->access->connection->ldapUserDisplayName);
476
-
477
-		if($displayName && (count($displayName) > 0)) {
478
-			$displayName = $displayName[0];
479
-
480
-			if (is_array($displayName2)){
481
-				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
482
-			}
483
-
484
-			$user = $this->access->userManager->get($uid);
485
-			if ($user instanceof User) {
486
-				$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
487
-				$this->access->connection->writeToCache($cacheKey, $displayName);
488
-			}
489
-			if ($user instanceof OfflineUser) {
490
-				/** @var OfflineUser $user*/
491
-				$displayName = $user->getDisplayName();
492
-			}
493
-			return $displayName;
494
-		}
495
-
496
-		return null;
497
-	}
498
-
499
-	/**
500
-	 * set display name of the user
501
-	 * @param string $uid user ID of the user
502
-	 * @param string $displayName new display name of the user
503
-	 * @return string|false display name
504
-	 */
505
-	public function setDisplayName($uid, $displayName) {
506
-		if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
507
-			return $this->userPluginManager->setDisplayName($uid, $displayName);
508
-		}
509
-		return false;
510
-	}
511
-
512
-	/**
513
-	 * Get a list of all display names
514
-	 *
515
-	 * @param string $search
516
-	 * @param string|null $limit
517
-	 * @param string|null $offset
518
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
519
-	 */
520
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
521
-		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
522
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
523
-			return $displayNames;
524
-		}
525
-
526
-		$displayNames = array();
527
-		$users = $this->getUsers($search, $limit, $offset);
528
-		foreach ($users as $user) {
529
-			$displayNames[$user] = $this->getDisplayName($user);
530
-		}
531
-		$this->access->connection->writeToCache($cacheKey, $displayNames);
532
-		return $displayNames;
533
-	}
534
-
535
-	/**
536
-	* Check if backend implements actions
537
-	* @param int $actions bitwise-or'ed actions
538
-	* @return boolean
539
-	*
540
-	* Returns the supported actions as int to be
541
-	* compared with \OC\User\Backend::CREATE_USER etc.
542
-	*/
543
-	public function implementsActions($actions) {
544
-		return (bool)((Backend::CHECK_PASSWORD
545
-			| Backend::GET_HOME
546
-			| Backend::GET_DISPLAYNAME
547
-			| Backend::PROVIDE_AVATAR
548
-			| Backend::COUNT_USERS
549
-			| ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0)
550
-			| $this->userPluginManager->getImplementedActions())
551
-			& $actions);
552
-	}
553
-
554
-	/**
555
-	 * @return bool
556
-	 */
557
-	public function hasUserListings() {
558
-		return true;
559
-	}
560
-
561
-	/**
562
-	 * counts the users in LDAP
563
-	 *
564
-	 * @return int|bool
565
-	 */
566
-	public function countUsers() {
567
-		if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
568
-			return $this->userPluginManager->countUsers();
569
-		}
570
-
571
-		$filter = $this->access->getFilterForUserCount();
572
-		$cacheKey = 'countUsers-'.$filter;
573
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
574
-			return $entries;
575
-		}
576
-		$entries = $this->access->countUsers($filter);
577
-		$this->access->connection->writeToCache($cacheKey, $entries);
578
-		return $entries;
579
-	}
580
-
581
-	/**
582
-	 * Backend name to be shown in user management
583
-	 * @return string the name of the backend to be shown
584
-	 */
585
-	public function getBackendName(){
586
-		return 'LDAP';
587
-	}
144
+    /**
145
+     * returns the username for the given LDAP DN, if available
146
+     *
147
+     * @param string $dn
148
+     * @return string|false with the username
149
+     */
150
+    public function dn2UserName($dn) {
151
+        return $this->access->dn2username($dn);
152
+    }
153
+
154
+    /**
155
+     * returns an LDAP record based on a given login name
156
+     *
157
+     * @param string $loginName
158
+     * @return array
159
+     * @throws NotOnLDAP
160
+     */
161
+    public function getLDAPUserByLoginName($loginName) {
162
+        //find out dn of the user name
163
+        $attrs = $this->access->userManager->getAttributes();
164
+        $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
165
+        if(count($users) < 1) {
166
+            throw new NotOnLDAP('No user available for the given login name on ' .
167
+                $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
168
+        }
169
+        return $users[0];
170
+    }
171
+
172
+    /**
173
+     * Check if the password is correct without logging in the user
174
+     *
175
+     * @param string $uid The username
176
+     * @param string $password The password
177
+     * @return false|string
178
+     */
179
+    public function checkPassword($uid, $password) {
180
+        try {
181
+            $ldapRecord = $this->getLDAPUserByLoginName($uid);
182
+        } catch(NotOnLDAP $e) {
183
+            if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
184
+                \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
185
+            }
186
+            return false;
187
+        }
188
+        $dn = $ldapRecord['dn'][0];
189
+        $user = $this->access->userManager->get($dn);
190
+
191
+        if(!$user instanceof User) {
192
+            Util::writeLog('user_ldap',
193
+                'LDAP Login: Could not get user object for DN ' . $dn .
194
+                '. Maybe the LDAP entry has no set display name attribute?',
195
+                Util::WARN);
196
+            return false;
197
+        }
198
+        if($user->getUsername() !== false) {
199
+            //are the credentials OK?
200
+            if(!$this->access->areCredentialsValid($dn, $password)) {
201
+                return false;
202
+            }
203
+
204
+            $this->access->cacheUserExists($user->getUsername());
205
+            $user->processAttributes($ldapRecord);
206
+            $user->markLogin();
207
+
208
+            return $user->getUsername();
209
+        }
210
+
211
+        return false;
212
+    }
213
+
214
+    /**
215
+     * Set password
216
+     * @param string $uid The username
217
+     * @param string $password The new password
218
+     * @return bool
219
+     */
220
+    public function setPassword($uid, $password) {
221
+        if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
222
+            return $this->userPluginManager->setPassword($uid, $password);
223
+        }
224
+
225
+        $user = $this->access->userManager->get($uid);
226
+
227
+        if(!$user instanceof User) {
228
+            throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
229
+                '. Maybe the LDAP entry has no set display name attribute?');
230
+        }
231
+        if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
232
+            $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
233
+            $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
234
+            if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
235
+                //remove last password expiry warning if any
236
+                $notification = $this->notificationManager->createNotification();
237
+                $notification->setApp('user_ldap')
238
+                    ->setUser($uid)
239
+                    ->setObject('pwd_exp_warn', $uid)
240
+                ;
241
+                $this->notificationManager->markProcessed($notification);
242
+            }
243
+            return true;
244
+        }
245
+
246
+        return false;
247
+    }
248
+
249
+    /**
250
+     * Get a list of all users
251
+     *
252
+     * @param string $search
253
+     * @param integer $limit
254
+     * @param integer $offset
255
+     * @return string[] an array of all uids
256
+     */
257
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
258
+        $search = $this->access->escapeFilterPart($search, true);
259
+        $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
260
+
261
+        //check if users are cached, if so return
262
+        $ldap_users = $this->access->connection->getFromCache($cachekey);
263
+        if(!is_null($ldap_users)) {
264
+            return $ldap_users;
265
+        }
266
+
267
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
268
+        // error. With a limit of 0, we get 0 results. So we pass null.
269
+        if($limit <= 0) {
270
+            $limit = null;
271
+        }
272
+        $filter = $this->access->combineFilterWithAnd(array(
273
+            $this->access->connection->ldapUserFilter,
274
+            $this->access->connection->ldapUserDisplayName . '=*',
275
+            $this->access->getFilterPartForUserSearch($search)
276
+        ));
277
+
278
+        Util::writeLog('user_ldap',
279
+            'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
280
+            Util::DEBUG);
281
+        //do the search and translate results to Nextcloud names
282
+        $ldap_users = $this->access->fetchListOfUsers(
283
+            $filter,
284
+            $this->access->userManager->getAttributes(true),
285
+            $limit, $offset);
286
+        $ldap_users = $this->access->nextcloudUserNames($ldap_users);
287
+        Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
288
+
289
+        $this->access->connection->writeToCache($cachekey, $ldap_users);
290
+        return $ldap_users;
291
+    }
292
+
293
+    /**
294
+     * checks whether a user is still available on LDAP
295
+     *
296
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
297
+     * name or an instance of that user
298
+     * @return bool
299
+     * @throws \Exception
300
+     * @throws \OC\ServerNotAvailableException
301
+     */
302
+    public function userExistsOnLDAP($user) {
303
+        if(is_string($user)) {
304
+            $user = $this->access->userManager->get($user);
305
+        }
306
+        if(is_null($user)) {
307
+            return false;
308
+        }
309
+
310
+        $dn = $user->getDN();
311
+        //check if user really still exists by reading its entry
312
+        if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
313
+            $lcr = $this->access->connection->getConnectionResource();
314
+            if(is_null($lcr)) {
315
+                throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
316
+            }
317
+
318
+            try {
319
+                $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
320
+                if(!$uuid) {
321
+                    return false;
322
+                }
323
+                $newDn = $this->access->getUserDnByUuid($uuid);
324
+                //check if renamed user is still valid by reapplying the ldap filter
325
+                if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
326
+                    return false;
327
+                }
328
+                $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
329
+                return true;
330
+            } catch (\Exception $e) {
331
+                return false;
332
+            }
333
+        }
334
+
335
+        if($user instanceof OfflineUser) {
336
+            $user->unmark();
337
+        }
338
+
339
+        return true;
340
+    }
341
+
342
+    /**
343
+     * check if a user exists
344
+     * @param string $uid the username
345
+     * @return boolean
346
+     * @throws \Exception when connection could not be established
347
+     */
348
+    public function userExists($uid) {
349
+        $userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
+        if(!is_null($userExists)) {
351
+            return (bool)$userExists;
352
+        }
353
+        //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354
+        $user = $this->access->userManager->get($uid);
355
+
356
+        if(is_null($user)) {
357
+            Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358
+                $this->access->connection->ldapHost, Util::DEBUG);
359
+            $this->access->connection->writeToCache('userExists'.$uid, false);
360
+            return false;
361
+        } else if($user instanceof OfflineUser) {
362
+            //express check for users marked as deleted. Returning true is
363
+            //necessary for cleanup
364
+            return true;
365
+        }
366
+
367
+        $result = $this->userExistsOnLDAP($user);
368
+        $this->access->connection->writeToCache('userExists'.$uid, $result);
369
+        if($result === true) {
370
+            $user->update();
371
+        }
372
+        return $result;
373
+    }
374
+
375
+    /**
376
+     * returns whether a user was deleted in LDAP
377
+     *
378
+     * @param string $uid The username of the user to delete
379
+     * @return bool
380
+     */
381
+    public function deleteUser($uid) {
382
+        if ($this->userPluginManager->canDeleteUser()) {
383
+            return $this->userPluginManager->deleteUser($uid);
384
+        }
385
+
386
+        $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
387
+        if(intval($marked) === 0) {
388
+            \OC::$server->getLogger()->notice(
389
+                'User '.$uid . ' is not marked as deleted, not cleaning up.',
390
+                array('app' => 'user_ldap'));
391
+            return false;
392
+        }
393
+        \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
394
+            array('app' => 'user_ldap'));
395
+
396
+        $this->access->getUserMapper()->unmap($uid);
397
+        $this->access->userManager->invalidate($uid);
398
+        return true;
399
+    }
400
+
401
+    /**
402
+     * get the user's home directory
403
+     *
404
+     * @param string $uid the username
405
+     * @return bool|string
406
+     * @throws NoUserException
407
+     * @throws \Exception
408
+     */
409
+    public function getHome($uid) {
410
+        // user Exists check required as it is not done in user proxy!
411
+        if(!$this->userExists($uid)) {
412
+            return false;
413
+        }
414
+
415
+        if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
416
+            return $this->userPluginManager->getHome($uid);
417
+        }
418
+
419
+        $cacheKey = 'getHome'.$uid;
420
+        $path = $this->access->connection->getFromCache($cacheKey);
421
+        if(!is_null($path)) {
422
+            return $path;
423
+        }
424
+
425
+        // early return path if it is a deleted user
426
+        $user = $this->access->userManager->get($uid);
427
+        if($user instanceof OfflineUser) {
428
+            if($this->currentUserInDeletionProcess !== null
429
+                && $this->currentUserInDeletionProcess === $user->getOCName()
430
+            ) {
431
+                return $user->getHomePath();
432
+            } else {
433
+                throw new NoUserException($uid . ' is not a valid user anymore');
434
+            }
435
+        } else if ($user === null) {
436
+            throw new NoUserException($uid . ' is not a valid user anymore');
437
+        }
438
+
439
+        $path = $user->getHomePath();
440
+        $this->access->cacheUserHome($uid, $path);
441
+
442
+        return $path;
443
+    }
444
+
445
+    /**
446
+     * get display name of the user
447
+     * @param string $uid user ID of the user
448
+     * @return string|false display name
449
+     */
450
+    public function getDisplayName($uid) {
451
+        if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
452
+            return $this->userPluginManager->getDisplayName($uid);
453
+        }
454
+
455
+        if(!$this->userExists($uid)) {
456
+            return false;
457
+        }
458
+
459
+        $cacheKey = 'getDisplayName'.$uid;
460
+        if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
461
+            return $displayName;
462
+        }
463
+
464
+        //Check whether the display name is configured to have a 2nd feature
465
+        $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
466
+        $displayName2 = '';
467
+        if ($additionalAttribute !== '') {
468
+            $displayName2 = $this->access->readAttribute(
469
+                $this->access->username2dn($uid),
470
+                $additionalAttribute);
471
+        }
472
+
473
+        $displayName = $this->access->readAttribute(
474
+            $this->access->username2dn($uid),
475
+            $this->access->connection->ldapUserDisplayName);
476
+
477
+        if($displayName && (count($displayName) > 0)) {
478
+            $displayName = $displayName[0];
479
+
480
+            if (is_array($displayName2)){
481
+                $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
482
+            }
483
+
484
+            $user = $this->access->userManager->get($uid);
485
+            if ($user instanceof User) {
486
+                $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
487
+                $this->access->connection->writeToCache($cacheKey, $displayName);
488
+            }
489
+            if ($user instanceof OfflineUser) {
490
+                /** @var OfflineUser $user*/
491
+                $displayName = $user->getDisplayName();
492
+            }
493
+            return $displayName;
494
+        }
495
+
496
+        return null;
497
+    }
498
+
499
+    /**
500
+     * set display name of the user
501
+     * @param string $uid user ID of the user
502
+     * @param string $displayName new display name of the user
503
+     * @return string|false display name
504
+     */
505
+    public function setDisplayName($uid, $displayName) {
506
+        if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
507
+            return $this->userPluginManager->setDisplayName($uid, $displayName);
508
+        }
509
+        return false;
510
+    }
511
+
512
+    /**
513
+     * Get a list of all display names
514
+     *
515
+     * @param string $search
516
+     * @param string|null $limit
517
+     * @param string|null $offset
518
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
519
+     */
520
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
521
+        $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
522
+        if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
523
+            return $displayNames;
524
+        }
525
+
526
+        $displayNames = array();
527
+        $users = $this->getUsers($search, $limit, $offset);
528
+        foreach ($users as $user) {
529
+            $displayNames[$user] = $this->getDisplayName($user);
530
+        }
531
+        $this->access->connection->writeToCache($cacheKey, $displayNames);
532
+        return $displayNames;
533
+    }
534
+
535
+    /**
536
+     * Check if backend implements actions
537
+     * @param int $actions bitwise-or'ed actions
538
+     * @return boolean
539
+     *
540
+     * Returns the supported actions as int to be
541
+     * compared with \OC\User\Backend::CREATE_USER etc.
542
+     */
543
+    public function implementsActions($actions) {
544
+        return (bool)((Backend::CHECK_PASSWORD
545
+            | Backend::GET_HOME
546
+            | Backend::GET_DISPLAYNAME
547
+            | Backend::PROVIDE_AVATAR
548
+            | Backend::COUNT_USERS
549
+            | ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0)
550
+            | $this->userPluginManager->getImplementedActions())
551
+            & $actions);
552
+    }
553
+
554
+    /**
555
+     * @return bool
556
+     */
557
+    public function hasUserListings() {
558
+        return true;
559
+    }
560
+
561
+    /**
562
+     * counts the users in LDAP
563
+     *
564
+     * @return int|bool
565
+     */
566
+    public function countUsers() {
567
+        if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
568
+            return $this->userPluginManager->countUsers();
569
+        }
570
+
571
+        $filter = $this->access->getFilterForUserCount();
572
+        $cacheKey = 'countUsers-'.$filter;
573
+        if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
574
+            return $entries;
575
+        }
576
+        $entries = $this->access->countUsers($filter);
577
+        $this->access->connection->writeToCache($cacheKey, $entries);
578
+        return $entries;
579
+    }
580
+
581
+    /**
582
+     * Backend name to be shown in user management
583
+     * @return string the name of the backend to be shown
584
+     */
585
+    public function getBackendName(){
586
+        return 'LDAP';
587
+    }
588 588
 	
589
-	/**
590
-	 * Return access for LDAP interaction.
591
-	 * @param string $uid
592
-	 * @return Access instance of Access for LDAP interaction
593
-	 */
594
-	public function getLDAPAccess($uid) {
595
-		return $this->access;
596
-	}
589
+    /**
590
+     * Return access for LDAP interaction.
591
+     * @param string $uid
592
+     * @return Access instance of Access for LDAP interaction
593
+     */
594
+    public function getLDAPAccess($uid) {
595
+        return $this->access;
596
+    }
597 597
 	
598
-	/**
599
-	 * Return LDAP connection resource from a cloned connection.
600
-	 * The cloned connection needs to be closed manually.
601
-	 * of the current access.
602
-	 * @param string $uid
603
-	 * @return resource of the LDAP connection
604
-	 */
605
-	public function getNewLDAPConnection($uid) {
606
-		$connection = clone $this->access->getConnection();
607
-		return $connection->getConnectionResource();
608
-	}
609
-
610
-	/**
611
-	 * create new user
612
-	 * @param string $username username of the new user
613
-	 * @param string $password password of the new user
614
-	 * @return bool was the user created?
615
-	 */
616
-	public function createUser($username, $password) {
617
-		if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
618
-			return $this->userPluginManager->createUser($username, $password);
619
-		}
620
-		return false;
621
-	}
598
+    /**
599
+     * Return LDAP connection resource from a cloned connection.
600
+     * The cloned connection needs to be closed manually.
601
+     * of the current access.
602
+     * @param string $uid
603
+     * @return resource of the LDAP connection
604
+     */
605
+    public function getNewLDAPConnection($uid) {
606
+        $connection = clone $this->access->getConnection();
607
+        return $connection->getConnectionResource();
608
+    }
609
+
610
+    /**
611
+     * create new user
612
+     * @param string $username username of the new user
613
+     * @param string $password password of the new user
614
+     * @return bool was the user created?
615
+     */
616
+    public function createUser($username, $password) {
617
+        if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
618
+            return $this->userPluginManager->createUser($username, $password);
619
+        }
620
+        return false;
621
+    }
622 622
 
623 623
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -45,183 +45,183 @@
 block discarded – undo
45 45
 use OCA\User_LDAP\User\Manager;
46 46
 
47 47
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
48
-	static private $groupsFromDB;
49
-
50
-	static private $groupBE;
51
-
52
-	public function __construct(){
53
-		$this->interval = self::getRefreshInterval();
54
-	}
55
-
56
-	/**
57
-	 * @param mixed $argument
58
-	 */
59
-	public function run($argument){
60
-		self::updateGroups();
61
-	}
62
-
63
-	static public function updateGroups() {
64
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
65
-
66
-		$knownGroups = array_keys(self::getKnownGroups());
67
-		$actualGroups = self::getGroupBE()->getGroups();
68
-
69
-		if(empty($actualGroups) && empty($knownGroups)) {
70
-			\OCP\Util::writeLog('user_ldap',
71
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
-				\OCP\Util::INFO);
73
-			return;
74
-		}
75
-
76
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
-
80
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
81
-	}
82
-
83
-	/**
84
-	 * @return int
85
-	 */
86
-	static private function getRefreshInterval() {
87
-		//defaults to every hour
88
-		return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
-	}
90
-
91
-	/**
92
-	 * @param string[] $groups
93
-	 */
94
-	static private function handleKnownGroups($groups) {
95
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
96
-		$query = \OCP\DB::prepare('
48
+    static private $groupsFromDB;
49
+
50
+    static private $groupBE;
51
+
52
+    public function __construct(){
53
+        $this->interval = self::getRefreshInterval();
54
+    }
55
+
56
+    /**
57
+     * @param mixed $argument
58
+     */
59
+    public function run($argument){
60
+        self::updateGroups();
61
+    }
62
+
63
+    static public function updateGroups() {
64
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
65
+
66
+        $knownGroups = array_keys(self::getKnownGroups());
67
+        $actualGroups = self::getGroupBE()->getGroups();
68
+
69
+        if(empty($actualGroups) && empty($knownGroups)) {
70
+            \OCP\Util::writeLog('user_ldap',
71
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
+                \OCP\Util::INFO);
73
+            return;
74
+        }
75
+
76
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
+
80
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
81
+    }
82
+
83
+    /**
84
+     * @return int
85
+     */
86
+    static private function getRefreshInterval() {
87
+        //defaults to every hour
88
+        return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
+    }
90
+
91
+    /**
92
+     * @param string[] $groups
93
+     */
94
+    static private function handleKnownGroups($groups) {
95
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
96
+        $query = \OCP\DB::prepare('
97 97
 			UPDATE `*PREFIX*ldap_group_members`
98 98
 			SET `owncloudusers` = ?
99 99
 			WHERE `owncloudname` = ?
100 100
 		');
101
-		foreach($groups as $group) {
102
-			//we assume, that self::$groupsFromDB has been retrieved already
103
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
105
-			$hasChanged = false;
106
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
108
-				\OCP\Util::writeLog('user_ldap',
109
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
-				\OCP\Util::INFO);
111
-				$hasChanged = true;
112
-			}
113
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
115
-				\OCP\Util::writeLog('user_ldap',
116
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
-				\OCP\Util::INFO);
118
-				$hasChanged = true;
119
-			}
120
-			if($hasChanged) {
121
-				$query->execute(array(serialize($actualUsers), $group));
122
-			}
123
-		}
124
-		\OCP\Util::writeLog('user_ldap',
125
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
-			\OCP\Util::DEBUG);
127
-	}
128
-
129
-	/**
130
-	 * @param string[] $createdGroups
131
-	 */
132
-	static private function handleCreatedGroups($createdGroups) {
133
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
134
-		$query = \OCP\DB::prepare('
101
+        foreach($groups as $group) {
102
+            //we assume, that self::$groupsFromDB has been retrieved already
103
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
105
+            $hasChanged = false;
106
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
108
+                \OCP\Util::writeLog('user_ldap',
109
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
+                \OCP\Util::INFO);
111
+                $hasChanged = true;
112
+            }
113
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
115
+                \OCP\Util::writeLog('user_ldap',
116
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
+                \OCP\Util::INFO);
118
+                $hasChanged = true;
119
+            }
120
+            if($hasChanged) {
121
+                $query->execute(array(serialize($actualUsers), $group));
122
+            }
123
+        }
124
+        \OCP\Util::writeLog('user_ldap',
125
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
+            \OCP\Util::DEBUG);
127
+    }
128
+
129
+    /**
130
+     * @param string[] $createdGroups
131
+     */
132
+    static private function handleCreatedGroups($createdGroups) {
133
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
134
+        $query = \OCP\DB::prepare('
135 135
 			INSERT
136 136
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
137 137
 			VALUES (?, ?)
138 138
 		');
139
-		foreach($createdGroups as $createdGroup) {
140
-			\OCP\Util::writeLog('user_ldap',
141
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
-				\OCP\Util::INFO);
143
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
-			$query->execute(array($createdGroup, $users));
145
-		}
146
-		\OCP\Util::writeLog('user_ldap',
147
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
-			\OCP\Util::DEBUG);
149
-	}
150
-
151
-	/**
152
-	 * @param string[] $removedGroups
153
-	 */
154
-	static private function handleRemovedGroups($removedGroups) {
155
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
156
-		$query = \OCP\DB::prepare('
139
+        foreach($createdGroups as $createdGroup) {
140
+            \OCP\Util::writeLog('user_ldap',
141
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
+                \OCP\Util::INFO);
143
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
+            $query->execute(array($createdGroup, $users));
145
+        }
146
+        \OCP\Util::writeLog('user_ldap',
147
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
+            \OCP\Util::DEBUG);
149
+    }
150
+
151
+    /**
152
+     * @param string[] $removedGroups
153
+     */
154
+    static private function handleRemovedGroups($removedGroups) {
155
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
156
+        $query = \OCP\DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*ldap_group_members`
159 159
 			WHERE `owncloudname` = ?
160 160
 		');
161
-		foreach($removedGroups as $removedGroup) {
162
-			\OCP\Util::writeLog('user_ldap',
163
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
-				\OCP\Util::INFO);
165
-			$query->execute(array($removedGroup));
166
-		}
167
-		\OCP\Util::writeLog('user_ldap',
168
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
-			\OCP\Util::DEBUG);
170
-	}
171
-
172
-	/**
173
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
-	 */
175
-	static private function getGroupBE() {
176
-		if(!is_null(self::$groupBE)) {
177
-			return self::$groupBE;
178
-		}
179
-		$helper = new Helper(\OC::$server->getConfig());
180
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
-		$ldapWrapper = new LDAP();
182
-		if(count($configPrefixes) === 1) {
183
-			//avoid the proxy when there is only one LDAP server configured
184
-			$dbc = \OC::$server->getDatabaseConnection();
185
-			$userManager = new Manager(
186
-				\OC::$server->getConfig(),
187
-				new FilesystemHelper(),
188
-				new LogWrapper(),
189
-				\OC::$server->getAvatarManager(),
190
-				new \OCP\Image(),
191
-				$dbc,
192
-				\OC::$server->getUserManager(),
193
-				\OC::$server->getNotificationManager());
194
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig());
196
-			$groupMapper = new GroupMapping($dbc);
197
-			$userMapper  = new UserMapping($dbc);
198
-			$ldapAccess->setGroupMapper($groupMapper);
199
-			$ldapAccess->setUserMapper($userMapper);
200
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
-		} else {
202
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
-		}
204
-
205
-		return self::$groupBE;
206
-	}
207
-
208
-	/**
209
-	 * @return array
210
-	 */
211
-	static private function getKnownGroups() {
212
-		if(is_array(self::$groupsFromDB)) {
213
-			return self::$groupsFromDB;
214
-		}
215
-		$query = \OCP\DB::prepare('
161
+        foreach($removedGroups as $removedGroup) {
162
+            \OCP\Util::writeLog('user_ldap',
163
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
+                \OCP\Util::INFO);
165
+            $query->execute(array($removedGroup));
166
+        }
167
+        \OCP\Util::writeLog('user_ldap',
168
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
+            \OCP\Util::DEBUG);
170
+    }
171
+
172
+    /**
173
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
+     */
175
+    static private function getGroupBE() {
176
+        if(!is_null(self::$groupBE)) {
177
+            return self::$groupBE;
178
+        }
179
+        $helper = new Helper(\OC::$server->getConfig());
180
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
+        $ldapWrapper = new LDAP();
182
+        if(count($configPrefixes) === 1) {
183
+            //avoid the proxy when there is only one LDAP server configured
184
+            $dbc = \OC::$server->getDatabaseConnection();
185
+            $userManager = new Manager(
186
+                \OC::$server->getConfig(),
187
+                new FilesystemHelper(),
188
+                new LogWrapper(),
189
+                \OC::$server->getAvatarManager(),
190
+                new \OCP\Image(),
191
+                $dbc,
192
+                \OC::$server->getUserManager(),
193
+                \OC::$server->getNotificationManager());
194
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig());
196
+            $groupMapper = new GroupMapping($dbc);
197
+            $userMapper  = new UserMapping($dbc);
198
+            $ldapAccess->setGroupMapper($groupMapper);
199
+            $ldapAccess->setUserMapper($userMapper);
200
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
+        } else {
202
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
+        }
204
+
205
+        return self::$groupBE;
206
+    }
207
+
208
+    /**
209
+     * @return array
210
+     */
211
+    static private function getKnownGroups() {
212
+        if(is_array(self::$groupsFromDB)) {
213
+            return self::$groupsFromDB;
214
+        }
215
+        $query = \OCP\DB::prepare('
216 216
 			SELECT `owncloudname`, `owncloudusers`
217 217
 			FROM `*PREFIX*ldap_group_members`
218 218
 		');
219
-		$result = $query->execute()->fetchAll();
220
-		self::$groupsFromDB = array();
221
-		foreach($result as $dataset) {
222
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
-		}
224
-
225
-		return self::$groupsFromDB;
226
-	}
219
+        $result = $query->execute()->fetchAll();
220
+        self::$groupsFromDB = array();
221
+        foreach($result as $dataset) {
222
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
+        }
224
+
225
+        return self::$groupsFromDB;
226
+    }
227 227
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/Sync.php 2 patches
Indentation   +317 added lines, -317 removed lines patch added patch discarded remove patch
@@ -42,321 +42,321 @@
 block discarded – undo
42 42
 use OCP\Notification\IManager;
43 43
 
44 44
 class Sync extends TimedJob {
45
-	const MAX_INTERVAL = 12 * 60 * 60; // 12h
46
-	const MIN_INTERVAL = 30 * 60; // 30min
47
-	/** @var  Helper */
48
-	protected $ldapHelper;
49
-	/** @var  LDAP */
50
-	protected $ldap;
51
-	/** @var  Manager */
52
-	protected $userManager;
53
-	/** @var UserMapping */
54
-	protected $mapper;
55
-	/** @var  IConfig */
56
-	protected $config;
57
-	/** @var  IAvatarManager */
58
-	protected $avatarManager;
59
-	/** @var  IDBConnection */
60
-	protected $dbc;
61
-	/** @var  IUserManager */
62
-	protected $ncUserManager;
63
-	/** @var  IManager */
64
-	protected $notificationManager;
65
-
66
-	public function __construct() {
67
-		$this->setInterval(
68
-			\OC::$server->getConfig()->getAppValue(
69
-				'user_ldap',
70
-				'background_sync_interval',
71
-				self::MIN_INTERVAL
72
-			)
73
-		);
74
-	}
75
-
76
-	/**
77
-	 * updates the interval
78
-	 *
79
-	 * the idea is to adjust the interval depending on the amount of known users
80
-	 * and the attempt to update each user one day. At most it would run every
81
-	 * 30 minutes, and at least every 12 hours.
82
-	 */
83
-	public function updateInterval() {
84
-		$minPagingSize = $this->getMinPagingSize();
85
-		$mappedUsers = $this->mapper->count();
86
-
87
-		$runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
88
-			: $mappedUsers / $minPagingSize;
89
-		$interval = floor(24 * 60 * 60 / $runsPerDay);
90
-		$interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
91
-
92
-		$this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
93
-	}
94
-
95
-	/**
96
-	 * returns the smallest configured paging size
97
-	 * @return int
98
-	 */
99
-	protected function getMinPagingSize() {
100
-		$configKeys = $this->config->getAppKeys('user_ldap');
101
-		$configKeys = array_filter($configKeys, function($key) {
102
-			return strpos($key, 'ldap_paging_size') !== false;
103
-		});
104
-		$minPagingSize = null;
105
-		foreach ($configKeys as $configKey) {
106
-			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
107
-			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
108
-		}
109
-		return (int)$minPagingSize;
110
-	}
111
-
112
-	/**
113
-	 * @param array $argument
114
-	 */
115
-	protected function run($argument) {
116
-		$this->setArgument($argument);
117
-
118
-		$isBackgroundJobModeAjax = $this->config
119
-				->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
120
-		if($isBackgroundJobModeAjax) {
121
-			return;
122
-		}
123
-
124
-		$cycleData = $this->getCycle();
125
-		if($cycleData === null) {
126
-			$cycleData = $this->determineNextCycle();
127
-			if($cycleData === null) {
128
-				$this->updateInterval();
129
-				return;
130
-			}
131
-		}
132
-
133
-		if(!$this->qualifiesToRun($cycleData)) {
134
-			$this->updateInterval();
135
-			return;
136
-		}
137
-
138
-		try {
139
-			$expectMoreResults = $this->runCycle($cycleData);
140
-			if ($expectMoreResults) {
141
-				$this->increaseOffset($cycleData);
142
-			} else {
143
-				$this->determineNextCycle();
144
-			}
145
-			$this->updateInterval();
146
-		} catch (ServerNotAvailableException $e) {
147
-			$this->determineNextCycle();
148
-		}
149
-	}
150
-
151
-	/**
152
-	 * @param array $cycleData
153
-	 * @return bool whether more results are expected from the same configuration
154
-	 */
155
-	public function runCycle($cycleData) {
156
-		$connection = new Connection($this->ldap, $cycleData['prefix']);
157
-		$access = new Access($connection, $this->ldap, $this->userManager, $this->ldapHelper, $this->config);
158
-		$access->setUserMapper($this->mapper);
159
-
160
-		$filter = $access->combineFilterWithAnd(array(
161
-			$access->connection->ldapUserFilter,
162
-			$access->connection->ldapUserDisplayName . '=*',
163
-			$access->getFilterPartForUserSearch('')
164
-		));
165
-		$results = $access->fetchListOfUsers(
166
-			$filter,
167
-			$access->userManager->getAttributes(),
168
-			$connection->ldapPagingSize,
169
-			$cycleData['offset'],
170
-			true
171
-		);
172
-
173
-		if($connection->ldapPagingSize === 0) {
174
-			return true;
175
-		}
176
-		return count($results) !== $connection->ldapPagingSize;
177
-	}
178
-
179
-	/**
180
-	 * returns the info about the current cycle that should be run, if any,
181
-	 * otherwise null
182
-	 *
183
-	 * @return array|null
184
-	 */
185
-	public function getCycle() {
186
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
187
-		if(count($prefixes) === 0) {
188
-			return null;
189
-		}
190
-
191
-		$cycleData = [
192
-			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
193
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
194
-		];
195
-
196
-		if(
197
-			$cycleData['prefix'] !== null
198
-			&& in_array($cycleData['prefix'], $prefixes)
199
-		) {
200
-			return $cycleData;
201
-		}
202
-
203
-		return null;
204
-	}
205
-
206
-	/**
207
-	 * Save the provided cycle information in the DB
208
-	 *
209
-	 * @param array $cycleData
210
-	 */
211
-	public function setCycle(array $cycleData) {
212
-		$this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
213
-		$this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
214
-	}
215
-
216
-	/**
217
-	 * returns data about the next cycle that should run, if any, otherwise
218
-	 * null. It also always goes for the next LDAP configuration!
219
-	 *
220
-	 * @param array|null $cycleData the old cycle
221
-	 * @return array|null
222
-	 */
223
-	public function determineNextCycle(array $cycleData = null) {
224
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
225
-		if(count($prefixes) === 0) {
226
-			return null;
227
-		}
228
-
229
-		// get the next prefix in line and remember it
230
-		$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
231
-		$prefix = $this->getNextPrefix($oldPrefix);
232
-		if($prefix === null) {
233
-			return null;
234
-		}
235
-		$cycleData['prefix'] = $prefix;
236
-		$cycleData['offset'] = 0;
237
-		$this->setCycle(['prefix' => $prefix, 'offset' => 0]);
238
-
239
-		return $cycleData;
240
-	}
241
-
242
-	/**
243
-	 * Checks whether the provided cycle should be run. Currently only the
244
-	 * last configuration change goes into account (at least one hour).
245
-	 *
246
-	 * @param $cycleData
247
-	 * @return bool
248
-	 */
249
-	protected function qualifiesToRun($cycleData) {
250
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
251
-		if((time() - $lastChange) > 60 * 30) {
252
-			return true;
253
-		}
254
-		return false;
255
-	}
256
-
257
-	/**
258
-	 * increases the offset of the current cycle for the next run
259
-	 *
260
-	 * @param $cycleData
261
-	 */
262
-	protected function increaseOffset($cycleData) {
263
-		$ldapConfig = new Configuration($cycleData['prefix']);
264
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
265
-		$this->setCycle($cycleData);
266
-	}
267
-
268
-	/**
269
-	 * determines the next configuration prefix based on the last one (if any)
270
-	 *
271
-	 * @param string|null $lastPrefix
272
-	 * @return string|null
273
-	 */
274
-	protected function getNextPrefix($lastPrefix) {
275
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
276
-		$noOfPrefixes = count($prefixes);
277
-		if($noOfPrefixes === 0) {
278
-			return null;
279
-		}
280
-		$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
281
-		if($i === false) {
282
-			$i = -1;
283
-		} else {
284
-			$i++;
285
-		}
286
-
287
-		if(!isset($prefixes[$i])) {
288
-			$i = 0;
289
-		}
290
-		return $prefixes[$i];
291
-	}
292
-
293
-	/**
294
-	 * "fixes" DI
295
-	 *
296
-	 * @param array $argument
297
-	 */
298
-	public function setArgument($argument) {
299
-		if(isset($argument['config'])) {
300
-			$this->config = $argument['config'];
301
-		} else {
302
-			$this->config = \OC::$server->getConfig();
303
-		}
304
-
305
-		if(isset($argument['helper'])) {
306
-			$this->ldapHelper = $argument['helper'];
307
-		} else {
308
-			$this->ldapHelper = new Helper($this->config);
309
-		}
310
-
311
-		if(isset($argument['ldapWrapper'])) {
312
-			$this->ldap = $argument['ldapWrapper'];
313
-		} else {
314
-			$this->ldap = new LDAP();
315
-		}
316
-
317
-		if(isset($argument['avatarManager'])) {
318
-			$this->avatarManager = $argument['avatarManager'];
319
-		} else {
320
-			$this->avatarManager = \OC::$server->getAvatarManager();
321
-		}
322
-
323
-		if(isset($argument['dbc'])) {
324
-			$this->dbc = $argument['dbc'];
325
-		} else {
326
-			$this->dbc = \OC::$server->getDatabaseConnection();
327
-		}
328
-
329
-		if(isset($argument['ncUserManager'])) {
330
-			$this->ncUserManager = $argument['ncUserManager'];
331
-		} else {
332
-			$this->ncUserManager = \OC::$server->getUserManager();
333
-		}
334
-
335
-		if(isset($argument['notificationManager'])) {
336
-			$this->notificationManager = $argument['notificationManager'];
337
-		} else {
338
-			$this->notificationManager = \OC::$server->getNotificationManager();
339
-		}
340
-
341
-		if(isset($argument['userManager'])) {
342
-			$this->userManager = $argument['userManager'];
343
-		} else {
344
-			$this->userManager = new Manager(
345
-				$this->config,
346
-				new FilesystemHelper(),
347
-				new LogWrapper(),
348
-				$this->avatarManager,
349
-				new Image(),
350
-				$this->dbc,
351
-				$this->ncUserManager,
352
-				$this->notificationManager
353
-			);
354
-		}
355
-
356
-		if(isset($argument['mapper'])) {
357
-			$this->mapper = $argument['mapper'];
358
-		} else {
359
-			$this->mapper = new UserMapping($this->dbc);
360
-		}
361
-	}
45
+    const MAX_INTERVAL = 12 * 60 * 60; // 12h
46
+    const MIN_INTERVAL = 30 * 60; // 30min
47
+    /** @var  Helper */
48
+    protected $ldapHelper;
49
+    /** @var  LDAP */
50
+    protected $ldap;
51
+    /** @var  Manager */
52
+    protected $userManager;
53
+    /** @var UserMapping */
54
+    protected $mapper;
55
+    /** @var  IConfig */
56
+    protected $config;
57
+    /** @var  IAvatarManager */
58
+    protected $avatarManager;
59
+    /** @var  IDBConnection */
60
+    protected $dbc;
61
+    /** @var  IUserManager */
62
+    protected $ncUserManager;
63
+    /** @var  IManager */
64
+    protected $notificationManager;
65
+
66
+    public function __construct() {
67
+        $this->setInterval(
68
+            \OC::$server->getConfig()->getAppValue(
69
+                'user_ldap',
70
+                'background_sync_interval',
71
+                self::MIN_INTERVAL
72
+            )
73
+        );
74
+    }
75
+
76
+    /**
77
+     * updates the interval
78
+     *
79
+     * the idea is to adjust the interval depending on the amount of known users
80
+     * and the attempt to update each user one day. At most it would run every
81
+     * 30 minutes, and at least every 12 hours.
82
+     */
83
+    public function updateInterval() {
84
+        $minPagingSize = $this->getMinPagingSize();
85
+        $mappedUsers = $this->mapper->count();
86
+
87
+        $runsPerDay = ($minPagingSize === 0 || $mappedUsers === 0) ? self::MAX_INTERVAL
88
+            : $mappedUsers / $minPagingSize;
89
+        $interval = floor(24 * 60 * 60 / $runsPerDay);
90
+        $interval = min(max($interval, self::MIN_INTERVAL), self::MAX_INTERVAL);
91
+
92
+        $this->config->setAppValue('user_ldap', 'background_sync_interval', $interval);
93
+    }
94
+
95
+    /**
96
+     * returns the smallest configured paging size
97
+     * @return int
98
+     */
99
+    protected function getMinPagingSize() {
100
+        $configKeys = $this->config->getAppKeys('user_ldap');
101
+        $configKeys = array_filter($configKeys, function($key) {
102
+            return strpos($key, 'ldap_paging_size') !== false;
103
+        });
104
+        $minPagingSize = null;
105
+        foreach ($configKeys as $configKey) {
106
+            $pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
107
+            $minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
108
+        }
109
+        return (int)$minPagingSize;
110
+    }
111
+
112
+    /**
113
+     * @param array $argument
114
+     */
115
+    protected function run($argument) {
116
+        $this->setArgument($argument);
117
+
118
+        $isBackgroundJobModeAjax = $this->config
119
+                ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
120
+        if($isBackgroundJobModeAjax) {
121
+            return;
122
+        }
123
+
124
+        $cycleData = $this->getCycle();
125
+        if($cycleData === null) {
126
+            $cycleData = $this->determineNextCycle();
127
+            if($cycleData === null) {
128
+                $this->updateInterval();
129
+                return;
130
+            }
131
+        }
132
+
133
+        if(!$this->qualifiesToRun($cycleData)) {
134
+            $this->updateInterval();
135
+            return;
136
+        }
137
+
138
+        try {
139
+            $expectMoreResults = $this->runCycle($cycleData);
140
+            if ($expectMoreResults) {
141
+                $this->increaseOffset($cycleData);
142
+            } else {
143
+                $this->determineNextCycle();
144
+            }
145
+            $this->updateInterval();
146
+        } catch (ServerNotAvailableException $e) {
147
+            $this->determineNextCycle();
148
+        }
149
+    }
150
+
151
+    /**
152
+     * @param array $cycleData
153
+     * @return bool whether more results are expected from the same configuration
154
+     */
155
+    public function runCycle($cycleData) {
156
+        $connection = new Connection($this->ldap, $cycleData['prefix']);
157
+        $access = new Access($connection, $this->ldap, $this->userManager, $this->ldapHelper, $this->config);
158
+        $access->setUserMapper($this->mapper);
159
+
160
+        $filter = $access->combineFilterWithAnd(array(
161
+            $access->connection->ldapUserFilter,
162
+            $access->connection->ldapUserDisplayName . '=*',
163
+            $access->getFilterPartForUserSearch('')
164
+        ));
165
+        $results = $access->fetchListOfUsers(
166
+            $filter,
167
+            $access->userManager->getAttributes(),
168
+            $connection->ldapPagingSize,
169
+            $cycleData['offset'],
170
+            true
171
+        );
172
+
173
+        if($connection->ldapPagingSize === 0) {
174
+            return true;
175
+        }
176
+        return count($results) !== $connection->ldapPagingSize;
177
+    }
178
+
179
+    /**
180
+     * returns the info about the current cycle that should be run, if any,
181
+     * otherwise null
182
+     *
183
+     * @return array|null
184
+     */
185
+    public function getCycle() {
186
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
187
+        if(count($prefixes) === 0) {
188
+            return null;
189
+        }
190
+
191
+        $cycleData = [
192
+            'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
193
+            'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
194
+        ];
195
+
196
+        if(
197
+            $cycleData['prefix'] !== null
198
+            && in_array($cycleData['prefix'], $prefixes)
199
+        ) {
200
+            return $cycleData;
201
+        }
202
+
203
+        return null;
204
+    }
205
+
206
+    /**
207
+     * Save the provided cycle information in the DB
208
+     *
209
+     * @param array $cycleData
210
+     */
211
+    public function setCycle(array $cycleData) {
212
+        $this->config->setAppValue('user_ldap', 'background_sync_prefix', $cycleData['prefix']);
213
+        $this->config->setAppValue('user_ldap', 'background_sync_offset', $cycleData['offset']);
214
+    }
215
+
216
+    /**
217
+     * returns data about the next cycle that should run, if any, otherwise
218
+     * null. It also always goes for the next LDAP configuration!
219
+     *
220
+     * @param array|null $cycleData the old cycle
221
+     * @return array|null
222
+     */
223
+    public function determineNextCycle(array $cycleData = null) {
224
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
225
+        if(count($prefixes) === 0) {
226
+            return null;
227
+        }
228
+
229
+        // get the next prefix in line and remember it
230
+        $oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
231
+        $prefix = $this->getNextPrefix($oldPrefix);
232
+        if($prefix === null) {
233
+            return null;
234
+        }
235
+        $cycleData['prefix'] = $prefix;
236
+        $cycleData['offset'] = 0;
237
+        $this->setCycle(['prefix' => $prefix, 'offset' => 0]);
238
+
239
+        return $cycleData;
240
+    }
241
+
242
+    /**
243
+     * Checks whether the provided cycle should be run. Currently only the
244
+     * last configuration change goes into account (at least one hour).
245
+     *
246
+     * @param $cycleData
247
+     * @return bool
248
+     */
249
+    protected function qualifiesToRun($cycleData) {
250
+        $lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
251
+        if((time() - $lastChange) > 60 * 30) {
252
+            return true;
253
+        }
254
+        return false;
255
+    }
256
+
257
+    /**
258
+     * increases the offset of the current cycle for the next run
259
+     *
260
+     * @param $cycleData
261
+     */
262
+    protected function increaseOffset($cycleData) {
263
+        $ldapConfig = new Configuration($cycleData['prefix']);
264
+        $cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
265
+        $this->setCycle($cycleData);
266
+    }
267
+
268
+    /**
269
+     * determines the next configuration prefix based on the last one (if any)
270
+     *
271
+     * @param string|null $lastPrefix
272
+     * @return string|null
273
+     */
274
+    protected function getNextPrefix($lastPrefix) {
275
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
276
+        $noOfPrefixes = count($prefixes);
277
+        if($noOfPrefixes === 0) {
278
+            return null;
279
+        }
280
+        $i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
281
+        if($i === false) {
282
+            $i = -1;
283
+        } else {
284
+            $i++;
285
+        }
286
+
287
+        if(!isset($prefixes[$i])) {
288
+            $i = 0;
289
+        }
290
+        return $prefixes[$i];
291
+    }
292
+
293
+    /**
294
+     * "fixes" DI
295
+     *
296
+     * @param array $argument
297
+     */
298
+    public function setArgument($argument) {
299
+        if(isset($argument['config'])) {
300
+            $this->config = $argument['config'];
301
+        } else {
302
+            $this->config = \OC::$server->getConfig();
303
+        }
304
+
305
+        if(isset($argument['helper'])) {
306
+            $this->ldapHelper = $argument['helper'];
307
+        } else {
308
+            $this->ldapHelper = new Helper($this->config);
309
+        }
310
+
311
+        if(isset($argument['ldapWrapper'])) {
312
+            $this->ldap = $argument['ldapWrapper'];
313
+        } else {
314
+            $this->ldap = new LDAP();
315
+        }
316
+
317
+        if(isset($argument['avatarManager'])) {
318
+            $this->avatarManager = $argument['avatarManager'];
319
+        } else {
320
+            $this->avatarManager = \OC::$server->getAvatarManager();
321
+        }
322
+
323
+        if(isset($argument['dbc'])) {
324
+            $this->dbc = $argument['dbc'];
325
+        } else {
326
+            $this->dbc = \OC::$server->getDatabaseConnection();
327
+        }
328
+
329
+        if(isset($argument['ncUserManager'])) {
330
+            $this->ncUserManager = $argument['ncUserManager'];
331
+        } else {
332
+            $this->ncUserManager = \OC::$server->getUserManager();
333
+        }
334
+
335
+        if(isset($argument['notificationManager'])) {
336
+            $this->notificationManager = $argument['notificationManager'];
337
+        } else {
338
+            $this->notificationManager = \OC::$server->getNotificationManager();
339
+        }
340
+
341
+        if(isset($argument['userManager'])) {
342
+            $this->userManager = $argument['userManager'];
343
+        } else {
344
+            $this->userManager = new Manager(
345
+                $this->config,
346
+                new FilesystemHelper(),
347
+                new LogWrapper(),
348
+                $this->avatarManager,
349
+                new Image(),
350
+                $this->dbc,
351
+                $this->ncUserManager,
352
+                $this->notificationManager
353
+            );
354
+        }
355
+
356
+        if(isset($argument['mapper'])) {
357
+            $this->mapper = $argument['mapper'];
358
+        } else {
359
+            $this->mapper = new UserMapping($this->dbc);
360
+        }
361
+    }
362 362
 }
Please login to merge, or discard this patch.
Spacing   +27 added lines, -27 removed lines patch added patch discarded remove patch
@@ -106,7 +106,7 @@  discard block
 block discarded – undo
106 106
 			$pagingSize = $this->config->getAppValue('user_ldap', $configKey, $minPagingSize);
107 107
 			$minPagingSize = $minPagingSize === null ? $pagingSize : min($minPagingSize, $pagingSize);
108 108
 		}
109
-		return (int)$minPagingSize;
109
+		return (int) $minPagingSize;
110 110
 	}
111 111
 
112 112
 	/**
@@ -117,20 +117,20 @@  discard block
 block discarded – undo
117 117
 
118 118
 		$isBackgroundJobModeAjax = $this->config
119 119
 				->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
120
-		if($isBackgroundJobModeAjax) {
120
+		if ($isBackgroundJobModeAjax) {
121 121
 			return;
122 122
 		}
123 123
 
124 124
 		$cycleData = $this->getCycle();
125
-		if($cycleData === null) {
125
+		if ($cycleData === null) {
126 126
 			$cycleData = $this->determineNextCycle();
127
-			if($cycleData === null) {
127
+			if ($cycleData === null) {
128 128
 				$this->updateInterval();
129 129
 				return;
130 130
 			}
131 131
 		}
132 132
 
133
-		if(!$this->qualifiesToRun($cycleData)) {
133
+		if (!$this->qualifiesToRun($cycleData)) {
134 134
 			$this->updateInterval();
135 135
 			return;
136 136
 		}
@@ -159,7 +159,7 @@  discard block
 block discarded – undo
159 159
 
160 160
 		$filter = $access->combineFilterWithAnd(array(
161 161
 			$access->connection->ldapUserFilter,
162
-			$access->connection->ldapUserDisplayName . '=*',
162
+			$access->connection->ldapUserDisplayName.'=*',
163 163
 			$access->getFilterPartForUserSearch('')
164 164
 		));
165 165
 		$results = $access->fetchListOfUsers(
@@ -170,7 +170,7 @@  discard block
 block discarded – undo
170 170
 			true
171 171
 		);
172 172
 
173
-		if($connection->ldapPagingSize === 0) {
173
+		if ($connection->ldapPagingSize === 0) {
174 174
 			return true;
175 175
 		}
176 176
 		return count($results) !== $connection->ldapPagingSize;
@@ -184,16 +184,16 @@  discard block
 block discarded – undo
184 184
 	 */
185 185
 	public function getCycle() {
186 186
 		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
187
-		if(count($prefixes) === 0) {
187
+		if (count($prefixes) === 0) {
188 188
 			return null;
189 189
 		}
190 190
 
191 191
 		$cycleData = [
192 192
 			'prefix' => $this->config->getAppValue('user_ldap', 'background_sync_prefix', null),
193
-			'offset' => (int)$this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
193
+			'offset' => (int) $this->config->getAppValue('user_ldap', 'background_sync_offset', 0),
194 194
 		];
195 195
 
196
-		if(
196
+		if (
197 197
 			$cycleData['prefix'] !== null
198 198
 			&& in_array($cycleData['prefix'], $prefixes)
199 199
 		) {
@@ -222,14 +222,14 @@  discard block
 block discarded – undo
222 222
 	 */
223 223
 	public function determineNextCycle(array $cycleData = null) {
224 224
 		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
225
-		if(count($prefixes) === 0) {
225
+		if (count($prefixes) === 0) {
226 226
 			return null;
227 227
 		}
228 228
 
229 229
 		// get the next prefix in line and remember it
230 230
 		$oldPrefix = $cycleData === null ? null : $cycleData['prefix'];
231 231
 		$prefix = $this->getNextPrefix($oldPrefix);
232
-		if($prefix === null) {
232
+		if ($prefix === null) {
233 233
 			return null;
234 234
 		}
235 235
 		$cycleData['prefix'] = $prefix;
@@ -247,8 +247,8 @@  discard block
 block discarded – undo
247 247
 	 * @return bool
248 248
 	 */
249 249
 	protected function qualifiesToRun($cycleData) {
250
-		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'] . '_lastChange', 0);
251
-		if((time() - $lastChange) > 60 * 30) {
250
+		$lastChange = $this->config->getAppValue('user_ldap', $cycleData['prefix'].'_lastChange', 0);
251
+		if ((time() - $lastChange) > 60 * 30) {
252 252
 			return true;
253 253
 		}
254 254
 		return false;
@@ -261,7 +261,7 @@  discard block
 block discarded – undo
261 261
 	 */
262 262
 	protected function increaseOffset($cycleData) {
263 263
 		$ldapConfig = new Configuration($cycleData['prefix']);
264
-		$cycleData['offset'] += (int)$ldapConfig->ldapPagingSize;
264
+		$cycleData['offset'] += (int) $ldapConfig->ldapPagingSize;
265 265
 		$this->setCycle($cycleData);
266 266
 	}
267 267
 
@@ -274,17 +274,17 @@  discard block
 block discarded – undo
274 274
 	protected function getNextPrefix($lastPrefix) {
275 275
 		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes(true);
276 276
 		$noOfPrefixes = count($prefixes);
277
-		if($noOfPrefixes === 0) {
277
+		if ($noOfPrefixes === 0) {
278 278
 			return null;
279 279
 		}
280 280
 		$i = $lastPrefix === null ? false : array_search($lastPrefix, $prefixes, true);
281
-		if($i === false) {
281
+		if ($i === false) {
282 282
 			$i = -1;
283 283
 		} else {
284 284
 			$i++;
285 285
 		}
286 286
 
287
-		if(!isset($prefixes[$i])) {
287
+		if (!isset($prefixes[$i])) {
288 288
 			$i = 0;
289 289
 		}
290 290
 		return $prefixes[$i];
@@ -296,49 +296,49 @@  discard block
 block discarded – undo
296 296
 	 * @param array $argument
297 297
 	 */
298 298
 	public function setArgument($argument) {
299
-		if(isset($argument['config'])) {
299
+		if (isset($argument['config'])) {
300 300
 			$this->config = $argument['config'];
301 301
 		} else {
302 302
 			$this->config = \OC::$server->getConfig();
303 303
 		}
304 304
 
305
-		if(isset($argument['helper'])) {
305
+		if (isset($argument['helper'])) {
306 306
 			$this->ldapHelper = $argument['helper'];
307 307
 		} else {
308 308
 			$this->ldapHelper = new Helper($this->config);
309 309
 		}
310 310
 
311
-		if(isset($argument['ldapWrapper'])) {
311
+		if (isset($argument['ldapWrapper'])) {
312 312
 			$this->ldap = $argument['ldapWrapper'];
313 313
 		} else {
314 314
 			$this->ldap = new LDAP();
315 315
 		}
316 316
 
317
-		if(isset($argument['avatarManager'])) {
317
+		if (isset($argument['avatarManager'])) {
318 318
 			$this->avatarManager = $argument['avatarManager'];
319 319
 		} else {
320 320
 			$this->avatarManager = \OC::$server->getAvatarManager();
321 321
 		}
322 322
 
323
-		if(isset($argument['dbc'])) {
323
+		if (isset($argument['dbc'])) {
324 324
 			$this->dbc = $argument['dbc'];
325 325
 		} else {
326 326
 			$this->dbc = \OC::$server->getDatabaseConnection();
327 327
 		}
328 328
 
329
-		if(isset($argument['ncUserManager'])) {
329
+		if (isset($argument['ncUserManager'])) {
330 330
 			$this->ncUserManager = $argument['ncUserManager'];
331 331
 		} else {
332 332
 			$this->ncUserManager = \OC::$server->getUserManager();
333 333
 		}
334 334
 
335
-		if(isset($argument['notificationManager'])) {
335
+		if (isset($argument['notificationManager'])) {
336 336
 			$this->notificationManager = $argument['notificationManager'];
337 337
 		} else {
338 338
 			$this->notificationManager = \OC::$server->getNotificationManager();
339 339
 		}
340 340
 
341
-		if(isset($argument['userManager'])) {
341
+		if (isset($argument['userManager'])) {
342 342
 			$this->userManager = $argument['userManager'];
343 343
 		} else {
344 344
 			$this->userManager = new Manager(
@@ -353,7 +353,7 @@  discard block
 block discarded – undo
353 353
 			);
354 354
 		}
355 355
 
356
-		if(isset($argument['mapper'])) {
356
+		if (isset($argument['mapper'])) {
357 357
 			$this->mapper = $argument['mapper'];
358 358
 		} else {
359 359
 			$this->mapper = new UserMapping($this->dbc);
Please login to merge, or discard this patch.