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