Passed
Push — master ( 645109...008e6d )
by Christoph
12:14 queued 12s
created
apps/user_ldap/lib/LDAPProvider.php 1 patch
Indentation   +250 added lines, -250 removed lines patch added patch discarded remove patch
@@ -38,274 +38,274 @@
 block discarded – undo
38 38
  */
39 39
 class LDAPProvider implements ILDAPProvider, IDeletionFlagSupport {
40 40
 
41
-	private $userBackend;
42
-	private $groupBackend;
43
-	private $logger;
44
-	private $helper;
45
-	private $deletedUsersIndex;
41
+    private $userBackend;
42
+    private $groupBackend;
43
+    private $logger;
44
+    private $helper;
45
+    private $deletedUsersIndex;
46 46
 	
47
-	/**
48
-	 * Create new LDAPProvider
49
-	 * @param \OCP\IServerContainer $serverContainer
50
-	 * @param Helper $helper
51
-	 * @param DeletedUsersIndex $deletedUsersIndex
52
-	 * @throws \Exception if user_ldap app was not enabled
53
-	 */
54
-	public function __construct(IServerContainer $serverContainer, Helper $helper, DeletedUsersIndex $deletedUsersIndex) {
55
-		$this->logger = $serverContainer->getLogger();
56
-		$this->helper = $helper;
57
-		$this->deletedUsersIndex = $deletedUsersIndex;
58
-		$userBackendFound = false;
59
-		$groupBackendFound = false;
60
-		foreach ($serverContainer->getUserManager()->getBackends() as $backend){
61
-			$this->logger->debug('instance '.get_class($backend).' user backend.', ['app' => 'user_ldap']);
62
-			if ($backend instanceof IUserLDAP) {
63
-				$this->userBackend = $backend;
64
-				$userBackendFound = true;
65
-				break;
66
-			}
67
-		}
68
-		foreach ($serverContainer->getGroupManager()->getBackends() as $backend){
69
-			$this->logger->debug('instance '.get_class($backend).' group backend.', ['app' => 'user_ldap']);
70
-			if ($backend instanceof IGroupLDAP) {
71
-				$this->groupBackend = $backend;
72
-				$groupBackendFound = true;
73
-				break;
74
-			}
75
-		}
47
+    /**
48
+     * Create new LDAPProvider
49
+     * @param \OCP\IServerContainer $serverContainer
50
+     * @param Helper $helper
51
+     * @param DeletedUsersIndex $deletedUsersIndex
52
+     * @throws \Exception if user_ldap app was not enabled
53
+     */
54
+    public function __construct(IServerContainer $serverContainer, Helper $helper, DeletedUsersIndex $deletedUsersIndex) {
55
+        $this->logger = $serverContainer->getLogger();
56
+        $this->helper = $helper;
57
+        $this->deletedUsersIndex = $deletedUsersIndex;
58
+        $userBackendFound = false;
59
+        $groupBackendFound = false;
60
+        foreach ($serverContainer->getUserManager()->getBackends() as $backend){
61
+            $this->logger->debug('instance '.get_class($backend).' user backend.', ['app' => 'user_ldap']);
62
+            if ($backend instanceof IUserLDAP) {
63
+                $this->userBackend = $backend;
64
+                $userBackendFound = true;
65
+                break;
66
+            }
67
+        }
68
+        foreach ($serverContainer->getGroupManager()->getBackends() as $backend){
69
+            $this->logger->debug('instance '.get_class($backend).' group backend.', ['app' => 'user_ldap']);
70
+            if ($backend instanceof IGroupLDAP) {
71
+                $this->groupBackend = $backend;
72
+                $groupBackendFound = true;
73
+                break;
74
+            }
75
+        }
76 76
 
77
-		if (!$userBackendFound or !$groupBackendFound) {
78
-			throw new \Exception('To use the LDAPProvider, user_ldap app must be enabled');
79
-		}
80
-	}
77
+        if (!$userBackendFound or !$groupBackendFound) {
78
+            throw new \Exception('To use the LDAPProvider, user_ldap app must be enabled');
79
+        }
80
+    }
81 81
 	
82
-	/**
83
-	 * Translate an user id to LDAP DN
84
-	 * @param string $uid user id
85
-	 * @return string with the LDAP DN
86
-	 * @throws \Exception if translation was unsuccessful
87
-	 */
88
-	public function getUserDN($uid) {
89
-		if(!$this->userBackend->userExists($uid)){
90
-			throw new \Exception('User id not found in LDAP');
91
-		}
92
-		$result = $this->userBackend->getLDAPAccess($uid)->username2dn($uid);
93
-		if(!$result){
94
-			throw new \Exception('Translation to LDAP DN unsuccessful');
95
-		}
96
-		return $result;
97
-	}
82
+    /**
83
+     * Translate an user id to LDAP DN
84
+     * @param string $uid user id
85
+     * @return string with the LDAP DN
86
+     * @throws \Exception if translation was unsuccessful
87
+     */
88
+    public function getUserDN($uid) {
89
+        if(!$this->userBackend->userExists($uid)){
90
+            throw new \Exception('User id not found in LDAP');
91
+        }
92
+        $result = $this->userBackend->getLDAPAccess($uid)->username2dn($uid);
93
+        if(!$result){
94
+            throw new \Exception('Translation to LDAP DN unsuccessful');
95
+        }
96
+        return $result;
97
+    }
98 98
 
99
-	/**
100
-	 * Translate a group id to LDAP DN.
101
-	 * @param string $gid group id
102
-	 * @return string
103
-	 * @throws \Exception
104
-	 */
105
-	public function getGroupDN($gid) {
106
-		if(!$this->groupBackend->groupExists($gid)){
107
-			throw new \Exception('Group id not found in LDAP');
108
-		}
109
-		$result = $this->groupBackend->getLDAPAccess($gid)->groupname2dn($gid);
110
-		if(!$result){
111
-			throw new \Exception('Translation to LDAP DN unsuccessful');
112
-		}
113
-		return $result;
114
-	}
99
+    /**
100
+     * Translate a group id to LDAP DN.
101
+     * @param string $gid group id
102
+     * @return string
103
+     * @throws \Exception
104
+     */
105
+    public function getGroupDN($gid) {
106
+        if(!$this->groupBackend->groupExists($gid)){
107
+            throw new \Exception('Group id not found in LDAP');
108
+        }
109
+        $result = $this->groupBackend->getLDAPAccess($gid)->groupname2dn($gid);
110
+        if(!$result){
111
+            throw new \Exception('Translation to LDAP DN unsuccessful');
112
+        }
113
+        return $result;
114
+    }
115 115
 
116
-	/**
117
-	 * Translate a LDAP DN to an internal user name. If there is no mapping between
118
-	 * the DN and the user name, a new one will be created.
119
-	 * @param string $dn LDAP DN
120
-	 * @return string with the internal user name
121
-	 * @throws \Exception if translation was unsuccessful
122
-	 */
123
-	public function getUserName($dn) {
124
-		$result = $this->userBackend->dn2UserName($dn);
125
-		if(!$result){
126
-			throw new \Exception('Translation to internal user name unsuccessful');
127
-		}
128
-		return $result;
129
-	}
116
+    /**
117
+     * Translate a LDAP DN to an internal user name. If there is no mapping between
118
+     * the DN and the user name, a new one will be created.
119
+     * @param string $dn LDAP DN
120
+     * @return string with the internal user name
121
+     * @throws \Exception if translation was unsuccessful
122
+     */
123
+    public function getUserName($dn) {
124
+        $result = $this->userBackend->dn2UserName($dn);
125
+        if(!$result){
126
+            throw new \Exception('Translation to internal user name unsuccessful');
127
+        }
128
+        return $result;
129
+    }
130 130
 	
131
-	/**
132
-	 * Convert a stored DN so it can be used as base parameter for LDAP queries.
133
-	 * @param string $dn the DN in question
134
-	 * @return string
135
-	 */
136
-	public function DNasBaseParameter($dn) {
137
-		return $this->helper->DNasBaseParameter($dn);
138
-	}
131
+    /**
132
+     * Convert a stored DN so it can be used as base parameter for LDAP queries.
133
+     * @param string $dn the DN in question
134
+     * @return string
135
+     */
136
+    public function DNasBaseParameter($dn) {
137
+        return $this->helper->DNasBaseParameter($dn);
138
+    }
139 139
 	
140
-	/**
141
-	 * Sanitize a DN received from the LDAP server.
142
-	 * @param array $dn the DN in question
143
-	 * @return array the sanitized DN
144
-	 */
145
-	public function sanitizeDN($dn) {
146
-		return $this->helper->sanitizeDN($dn);
147
-	}
140
+    /**
141
+     * Sanitize a DN received from the LDAP server.
142
+     * @param array $dn the DN in question
143
+     * @return array the sanitized DN
144
+     */
145
+    public function sanitizeDN($dn) {
146
+        return $this->helper->sanitizeDN($dn);
147
+    }
148 148
 	
149
-	/**
150
-	 * Return a new LDAP connection resource for the specified user.
151
-	 * The connection must be closed manually.
152
-	 * @param string $uid user id
153
-	 * @return resource of the LDAP connection
154
-	 * @throws \Exception if user id was not found in LDAP
155
-	 */
156
-	public function getLDAPConnection($uid) {
157
-		if(!$this->userBackend->userExists($uid)){
158
-			throw new \Exception('User id not found in LDAP');
159
-		}
160
-		return $this->userBackend->getNewLDAPConnection($uid);
161
-	}
149
+    /**
150
+     * Return a new LDAP connection resource for the specified user.
151
+     * The connection must be closed manually.
152
+     * @param string $uid user id
153
+     * @return resource of the LDAP connection
154
+     * @throws \Exception if user id was not found in LDAP
155
+     */
156
+    public function getLDAPConnection($uid) {
157
+        if(!$this->userBackend->userExists($uid)){
158
+            throw new \Exception('User id not found in LDAP');
159
+        }
160
+        return $this->userBackend->getNewLDAPConnection($uid);
161
+    }
162 162
 
163
-	/**
164
-	 * Return a new LDAP connection resource for the specified user.
165
-	 * The connection must be closed manually.
166
-	 * @param string $gid group id
167
-	 * @return resource of the LDAP connection
168
-	 * @throws \Exception if group id was not found in LDAP
169
-	 */
170
-	public function getGroupLDAPConnection($gid) {
171
-		if(!$this->groupBackend->groupExists($gid)){
172
-			throw new \Exception('Group id not found in LDAP');
173
-		}
174
-		return $this->groupBackend->getNewLDAPConnection($gid);
175
-	}
163
+    /**
164
+     * Return a new LDAP connection resource for the specified user.
165
+     * The connection must be closed manually.
166
+     * @param string $gid group id
167
+     * @return resource of the LDAP connection
168
+     * @throws \Exception if group id was not found in LDAP
169
+     */
170
+    public function getGroupLDAPConnection($gid) {
171
+        if(!$this->groupBackend->groupExists($gid)){
172
+            throw new \Exception('Group id not found in LDAP');
173
+        }
174
+        return $this->groupBackend->getNewLDAPConnection($gid);
175
+    }
176 176
 	
177
-	/**
178
-	 * Get the LDAP base for users.
179
-	 * @param string $uid user id
180
-	 * @return string the base for users
181
-	 * @throws \Exception if user id was not found in LDAP
182
-	 */
183
-	public function getLDAPBaseUsers($uid) {
184
-		if(!$this->userBackend->userExists($uid)){
185
-			throw new \Exception('User id not found in LDAP');
186
-		}
187
-		$access = $this->userBackend->getLDAPAccess($uid);
188
-		$bases = $access->getConnection()->ldapBaseUsers;
189
-		$dn = $this->getUserDN($uid);
190
-		foreach ($bases as $base) {
191
-			if($access->isDNPartOfBase($dn, [$base])) {
192
-				return $base;
193
-			}
194
-		}
195
-		// should not occur, because the user does not qualify to use NC in this case
196
-		$this->logger->info(
197
-			'No matching user base found for user {dn}, available: {bases}.',
198
-			[
199
-				'app' => 'user_ldap',
200
-				'dn' => $dn,
201
-				'bases' => $bases,
202
-			]
203
-		);
204
-		return array_shift($bases);
205
-	}
177
+    /**
178
+     * Get the LDAP base for users.
179
+     * @param string $uid user id
180
+     * @return string the base for users
181
+     * @throws \Exception if user id was not found in LDAP
182
+     */
183
+    public function getLDAPBaseUsers($uid) {
184
+        if(!$this->userBackend->userExists($uid)){
185
+            throw new \Exception('User id not found in LDAP');
186
+        }
187
+        $access = $this->userBackend->getLDAPAccess($uid);
188
+        $bases = $access->getConnection()->ldapBaseUsers;
189
+        $dn = $this->getUserDN($uid);
190
+        foreach ($bases as $base) {
191
+            if($access->isDNPartOfBase($dn, [$base])) {
192
+                return $base;
193
+            }
194
+        }
195
+        // should not occur, because the user does not qualify to use NC in this case
196
+        $this->logger->info(
197
+            'No matching user base found for user {dn}, available: {bases}.',
198
+            [
199
+                'app' => 'user_ldap',
200
+                'dn' => $dn,
201
+                'bases' => $bases,
202
+            ]
203
+        );
204
+        return array_shift($bases);
205
+    }
206 206
 	
207
-	/**
208
-	 * Get the LDAP base for groups.
209
-	 * @param string $uid user id
210
-	 * @return string the base for groups
211
-	 * @throws \Exception if user id was not found in LDAP
212
-	 */
213
-	public function getLDAPBaseGroups($uid) {
214
-		if(!$this->userBackend->userExists($uid)){
215
-			throw new \Exception('User id not found in LDAP');
216
-		}
217
-		$bases = $this->userBackend->getLDAPAccess($uid)->getConnection()->ldapBaseGroups;
218
-		return array_shift($bases);
219
-	}
207
+    /**
208
+     * Get the LDAP base for groups.
209
+     * @param string $uid user id
210
+     * @return string the base for groups
211
+     * @throws \Exception if user id was not found in LDAP
212
+     */
213
+    public function getLDAPBaseGroups($uid) {
214
+        if(!$this->userBackend->userExists($uid)){
215
+            throw new \Exception('User id not found in LDAP');
216
+        }
217
+        $bases = $this->userBackend->getLDAPAccess($uid)->getConnection()->ldapBaseGroups;
218
+        return array_shift($bases);
219
+    }
220 220
 	
221
-	/**
222
-	 * Clear the cache if a cache is used, otherwise do nothing.
223
-	 * @param string $uid user id
224
-	 * @throws \Exception if user id was not found in LDAP
225
-	 */
226
-	public function clearCache($uid) {
227
-		if(!$this->userBackend->userExists($uid)){
228
-			throw new \Exception('User id not found in LDAP');
229
-		}
230
-		$this->userBackend->getLDAPAccess($uid)->getConnection()->clearCache();
231
-	}
221
+    /**
222
+     * Clear the cache if a cache is used, otherwise do nothing.
223
+     * @param string $uid user id
224
+     * @throws \Exception if user id was not found in LDAP
225
+     */
226
+    public function clearCache($uid) {
227
+        if(!$this->userBackend->userExists($uid)){
228
+            throw new \Exception('User id not found in LDAP');
229
+        }
230
+        $this->userBackend->getLDAPAccess($uid)->getConnection()->clearCache();
231
+    }
232 232
 
233
-	/**
234
-	 * Clear the cache if a cache is used, otherwise do nothing.
235
-	 * Acts on the LDAP connection of a group
236
-	 * @param string $gid group id
237
-	 * @throws \Exception if user id was not found in LDAP
238
-	 */
239
-	public function clearGroupCache($gid) {
240
-		if(!$this->groupBackend->groupExists($gid)){
241
-			throw new \Exception('Group id not found in LDAP');
242
-		}
243
-		$this->groupBackend->getLDAPAccess($gid)->getConnection()->clearCache();
244
-	}
233
+    /**
234
+     * Clear the cache if a cache is used, otherwise do nothing.
235
+     * Acts on the LDAP connection of a group
236
+     * @param string $gid group id
237
+     * @throws \Exception if user id was not found in LDAP
238
+     */
239
+    public function clearGroupCache($gid) {
240
+        if(!$this->groupBackend->groupExists($gid)){
241
+            throw new \Exception('Group id not found in LDAP');
242
+        }
243
+        $this->groupBackend->getLDAPAccess($gid)->getConnection()->clearCache();
244
+    }
245 245
 	
246
-	/**
247
-	 * Check whether a LDAP DN exists
248
-	 * @param string $dn LDAP DN
249
-	 * @return bool whether the DN exists
250
-	 */
251
-	public function dnExists($dn) {
252
-		$result = $this->userBackend->dn2UserName($dn);
253
-		return !$result ? false : true;
254
-	}
246
+    /**
247
+     * Check whether a LDAP DN exists
248
+     * @param string $dn LDAP DN
249
+     * @return bool whether the DN exists
250
+     */
251
+    public function dnExists($dn) {
252
+        $result = $this->userBackend->dn2UserName($dn);
253
+        return !$result ? false : true;
254
+    }
255 255
 	
256
-	/**
257
-	 * Flag record for deletion.
258
-	 * @param string $uid user id
259
-	 */
260
-	public function flagRecord($uid) {
261
-		$this->deletedUsersIndex->markUser($uid);
262
-	}
256
+    /**
257
+     * Flag record for deletion.
258
+     * @param string $uid user id
259
+     */
260
+    public function flagRecord($uid) {
261
+        $this->deletedUsersIndex->markUser($uid);
262
+    }
263 263
 	
264
-	/**
265
-	 * Unflag record for deletion.
266
-	 * @param string $uid user id
267
-	 */
268
-	public function unflagRecord($uid) {
269
-		//do nothing
270
-	}
264
+    /**
265
+     * Unflag record for deletion.
266
+     * @param string $uid user id
267
+     */
268
+    public function unflagRecord($uid) {
269
+        //do nothing
270
+    }
271 271
 
272
-	/**
273
-	 * Get the LDAP attribute name for the user's display name
274
-	 * @param string $uid user id
275
-	 * @return string the display name field
276
-	 * @throws \Exception if user id was not found in LDAP
277
-	 */
278
-	public function getLDAPDisplayNameField($uid) {
279
-		if(!$this->userBackend->userExists($uid)){
280
-			throw new \Exception('User id not found in LDAP');
281
-		}
282
-		return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_display_name'];
283
-	}
272
+    /**
273
+     * Get the LDAP attribute name for the user's display name
274
+     * @param string $uid user id
275
+     * @return string the display name field
276
+     * @throws \Exception if user id was not found in LDAP
277
+     */
278
+    public function getLDAPDisplayNameField($uid) {
279
+        if(!$this->userBackend->userExists($uid)){
280
+            throw new \Exception('User id not found in LDAP');
281
+        }
282
+        return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_display_name'];
283
+    }
284 284
 
285
-	/**
286
-	 * Get the LDAP attribute name for the email
287
-	 * @param string $uid user id
288
-	 * @return string the email field
289
-	 * @throws \Exception if user id was not found in LDAP
290
-	 */
291
-	public function getLDAPEmailField($uid) {
292
-		if(!$this->userBackend->userExists($uid)){
293
-			throw new \Exception('User id not found in LDAP');
294
-		}
295
-		return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_email_attr'];
296
-	}
285
+    /**
286
+     * Get the LDAP attribute name for the email
287
+     * @param string $uid user id
288
+     * @return string the email field
289
+     * @throws \Exception if user id was not found in LDAP
290
+     */
291
+    public function getLDAPEmailField($uid) {
292
+        if(!$this->userBackend->userExists($uid)){
293
+            throw new \Exception('User id not found in LDAP');
294
+        }
295
+        return $this->userBackend->getLDAPAccess($uid)->getConnection()->getConfiguration()['ldap_email_attr'];
296
+    }
297 297
 
298
-	/**
299
-	 * Get the LDAP type of association between users and groups
300
-	 * @param string $gid group id
301
-	 * @return string the configuration, one of: 'memberUid', 'uniqueMember', 'member', 'gidNumber', ''
302
-	 * @throws \Exception if group id was not found in LDAP
303
-	 */
304
-	public function getLDAPGroupMemberAssoc($gid) {
305
-		if(!$this->groupBackend->groupExists($gid)){
306
-			throw new \Exception('Group id not found in LDAP');
307
-		}
308
-		return $this->groupBackend->getLDAPAccess($gid)->getConnection()->getConfiguration()['ldap_group_member_assoc_attribute'];
309
-	}
298
+    /**
299
+     * Get the LDAP type of association between users and groups
300
+     * @param string $gid group id
301
+     * @return string the configuration, one of: 'memberUid', 'uniqueMember', 'member', 'gidNumber', ''
302
+     * @throws \Exception if group id was not found in LDAP
303
+     */
304
+    public function getLDAPGroupMemberAssoc($gid) {
305
+        if(!$this->groupBackend->groupExists($gid)){
306
+            throw new \Exception('Group id not found in LDAP');
307
+        }
308
+        return $this->groupBackend->getLDAPAccess($gid)->getConnection()->getConfiguration()['ldap_group_member_assoc_attribute'];
309
+    }
310 310
 
311 311
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Controller/RenewPasswordController.php 1 patch
Indentation   +129 added lines, -129 removed lines patch added patch discarded remove patch
@@ -36,144 +36,144 @@
 block discarded – undo
36 36
 use OCP\IUserManager;
37 37
 
38 38
 class RenewPasswordController extends Controller {
39
-	/** @var IUserManager */
40
-	private $userManager;
41
-	/** @var IConfig */
42
-	private $config;
43
-	/** @var IL10N */
44
-	protected $l10n;
45
-	/** @var ISession */
46
-	private $session;
47
-	/** @var IURLGenerator */
48
-	private $urlGenerator;
39
+    /** @var IUserManager */
40
+    private $userManager;
41
+    /** @var IConfig */
42
+    private $config;
43
+    /** @var IL10N */
44
+    protected $l10n;
45
+    /** @var ISession */
46
+    private $session;
47
+    /** @var IURLGenerator */
48
+    private $urlGenerator;
49 49
 
50
-	/**
51
-	 * @param string $appName
52
-	 * @param IRequest $request
53
-	 * @param IUserManager $userManager
54
-	 * @param IConfig $config
55
-	 * @param IURLGenerator $urlGenerator
56
-	 */
57
-	function __construct($appName, IRequest $request, IUserManager $userManager,
58
-		IConfig $config, IL10N $l10n, ISession $session, IURLGenerator $urlGenerator) {
59
-		parent::__construct($appName, $request);
60
-		$this->userManager = $userManager;
61
-		$this->config = $config;
62
-		$this->l10n = $l10n;
63
-		$this->session = $session;
64
-		$this->urlGenerator = $urlGenerator;
65
-	}
50
+    /**
51
+     * @param string $appName
52
+     * @param IRequest $request
53
+     * @param IUserManager $userManager
54
+     * @param IConfig $config
55
+     * @param IURLGenerator $urlGenerator
56
+     */
57
+    function __construct($appName, IRequest $request, IUserManager $userManager,
58
+        IConfig $config, IL10N $l10n, ISession $session, IURLGenerator $urlGenerator) {
59
+        parent::__construct($appName, $request);
60
+        $this->userManager = $userManager;
61
+        $this->config = $config;
62
+        $this->l10n = $l10n;
63
+        $this->session = $session;
64
+        $this->urlGenerator = $urlGenerator;
65
+    }
66 66
 
67
-	/**
68
-	 * @PublicPage
69
-	 * @NoCSRFRequired
70
-	 *
71
-	 * @return RedirectResponse
72
-	 */
73
-	public function cancel() {
74
-		return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
75
-	}
67
+    /**
68
+     * @PublicPage
69
+     * @NoCSRFRequired
70
+     *
71
+     * @return RedirectResponse
72
+     */
73
+    public function cancel() {
74
+        return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
75
+    }
76 76
 
77
-	/**
78
-	 * @PublicPage
79
-	 * @NoCSRFRequired
80
-	 * @UseSession
81
-	 *
82
-	 * @param string $user
83
-	 *
84
-	 * @return TemplateResponse|RedirectResponse
85
-	 */
86
-	public function showRenewPasswordForm($user) {
87
-		if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
88
-			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
89
-		}
90
-		$parameters = [];
91
-		$renewPasswordMessages = $this->session->get('renewPasswordMessages');
92
-		$errors = [];
93
-		$messages = [];
94
-		if (is_array($renewPasswordMessages)) {
95
-			list($errors, $messages) = $renewPasswordMessages;
96
-		}
97
-		$this->session->remove('renewPasswordMessages');
98
-		foreach ($errors as $value) {
99
-			$parameters[$value] = true;
100
-		}
77
+    /**
78
+     * @PublicPage
79
+     * @NoCSRFRequired
80
+     * @UseSession
81
+     *
82
+     * @param string $user
83
+     *
84
+     * @return TemplateResponse|RedirectResponse
85
+     */
86
+    public function showRenewPasswordForm($user) {
87
+        if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
88
+            return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
89
+        }
90
+        $parameters = [];
91
+        $renewPasswordMessages = $this->session->get('renewPasswordMessages');
92
+        $errors = [];
93
+        $messages = [];
94
+        if (is_array($renewPasswordMessages)) {
95
+            list($errors, $messages) = $renewPasswordMessages;
96
+        }
97
+        $this->session->remove('renewPasswordMessages');
98
+        foreach ($errors as $value) {
99
+            $parameters[$value] = true;
100
+        }
101 101
 
102
-		$parameters['messages'] = $messages;
103
-		$parameters['user'] = $user;
102
+        $parameters['messages'] = $messages;
103
+        $parameters['user'] = $user;
104 104
 
105
-		$parameters['canResetPassword'] = true;
106
-		$parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
107
-		if (!$parameters['resetPasswordLink']) {
108
-			$userObj = $this->userManager->get($user);
109
-			if ($userObj instanceof IUser) {
110
-				$parameters['canResetPassword'] = $userObj->canChangePassword();
111
-			}
112
-		}
113
-		$parameters['cancelLink'] = $this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm');
105
+        $parameters['canResetPassword'] = true;
106
+        $parameters['resetPasswordLink'] = $this->config->getSystemValue('lost_password_link', '');
107
+        if (!$parameters['resetPasswordLink']) {
108
+            $userObj = $this->userManager->get($user);
109
+            if ($userObj instanceof IUser) {
110
+                $parameters['canResetPassword'] = $userObj->canChangePassword();
111
+            }
112
+        }
113
+        $parameters['cancelLink'] = $this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm');
114 114
 
115
-		return new TemplateResponse(
116
-			$this->appName, 'renewpassword', $parameters, 'guest'
117
-		);
118
-	}
115
+        return new TemplateResponse(
116
+            $this->appName, 'renewpassword', $parameters, 'guest'
117
+        );
118
+    }
119 119
 
120
-	/**
121
-	 * @PublicPage
122
-	 * @UseSession
123
-	 *
124
-	 * @param string $user
125
-	 * @param string $oldPassword
126
-	 * @param string $newPassword
127
-	 *
128
-	 * @return RedirectResponse
129
-	 */
130
-	public function tryRenewPassword($user, $oldPassword, $newPassword) {
131
-		if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
132
-			return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
133
-		}
134
-		$args = !is_null($user) ? ['user' => $user] : [];
135
-		$loginResult = $this->userManager->checkPassword($user, $oldPassword);
136
-		if ($loginResult === false) {
137
-			$this->session->set('renewPasswordMessages', [
138
-				['invalidpassword'], []
139
-			]);
140
-			return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
141
-		}
120
+    /**
121
+     * @PublicPage
122
+     * @UseSession
123
+     *
124
+     * @param string $user
125
+     * @param string $oldPassword
126
+     * @param string $newPassword
127
+     *
128
+     * @return RedirectResponse
129
+     */
130
+    public function tryRenewPassword($user, $oldPassword, $newPassword) {
131
+        if($this->config->getUserValue($user, 'user_ldap', 'needsPasswordReset') !== 'true') {
132
+            return new RedirectResponse($this->urlGenerator->linkToRouteAbsolute('core.login.showLoginForm'));
133
+        }
134
+        $args = !is_null($user) ? ['user' => $user] : [];
135
+        $loginResult = $this->userManager->checkPassword($user, $oldPassword);
136
+        if ($loginResult === false) {
137
+            $this->session->set('renewPasswordMessages', [
138
+                ['invalidpassword'], []
139
+            ]);
140
+            return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
141
+        }
142 142
 		
143
-		try {
144
-			if (!is_null($newPassword) && \OC_User::setPassword($user, $newPassword)) {
145
-				$this->session->set('loginMessages', [
146
-					[], [$this->l10n->t("Please login with the new password")]
147
-				]);
148
-				$this->config->setUserValue($user, 'user_ldap', 'needsPasswordReset', 'false');
149
-				return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
150
-			} else {
151
-				$this->session->set('renewPasswordMessages', [
152
-					['internalexception'], []
153
-				]);
154
-			}
155
-		} catch (HintException $e) {
156
-			$this->session->set('renewPasswordMessages', [
157
-				[], [$e->getHint()]
158
-			]);
159
-		}
143
+        try {
144
+            if (!is_null($newPassword) && \OC_User::setPassword($user, $newPassword)) {
145
+                $this->session->set('loginMessages', [
146
+                    [], [$this->l10n->t("Please login with the new password")]
147
+                ]);
148
+                $this->config->setUserValue($user, 'user_ldap', 'needsPasswordReset', 'false');
149
+                return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
150
+            } else {
151
+                $this->session->set('renewPasswordMessages', [
152
+                    ['internalexception'], []
153
+                ]);
154
+            }
155
+        } catch (HintException $e) {
156
+            $this->session->set('renewPasswordMessages', [
157
+                [], [$e->getHint()]
158
+            ]);
159
+        }
160 160
 
161
-		return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
162
-	}
161
+        return new RedirectResponse($this->urlGenerator->linkToRoute('user_ldap.renewPassword.showRenewPasswordForm', $args));
162
+    }
163 163
 
164
-	/**
165
-	 * @PublicPage
166
-	 * @NoCSRFRequired
167
-	 * @UseSession
168
-	 *
169
-	 * @return RedirectResponse
170
-	 */
171
-	public function showLoginFormInvalidPassword($user) {
172
-		$args = !is_null($user) ? ['user' => $user] : [];
173
-		$this->session->set('loginMessages', [
174
-			['invalidpassword'], []
175
-		]);
176
-		return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
177
-	}
164
+    /**
165
+     * @PublicPage
166
+     * @NoCSRFRequired
167
+     * @UseSession
168
+     *
169
+     * @return RedirectResponse
170
+     */
171
+    public function showLoginFormInvalidPassword($user) {
172
+        $args = !is_null($user) ? ['user' => $user] : [];
173
+        $this->session->set('loginMessages', [
174
+            ['invalidpassword'], []
175
+        ]);
176
+        return new RedirectResponse($this->urlGenerator->linkToRoute('core.login.showLoginForm', $args));
177
+    }
178 178
 
179 179
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Configuration.php 1 patch
Indentation   +510 added lines, -510 removed lines patch added patch discarded remove patch
@@ -41,543 +41,543 @@
 block discarded – undo
41 41
  * @property string ldapUserAvatarRule
42 42
  */
43 43
 class Configuration {
44
-	const AVATAR_PREFIX_DEFAULT = 'default';
45
-	const AVATAR_PREFIX_NONE = 'none';
46
-	const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
44
+    const AVATAR_PREFIX_DEFAULT = 'default';
45
+    const AVATAR_PREFIX_NONE = 'none';
46
+    const AVATAR_PREFIX_DATA_ATTRIBUTE = 'data:';
47 47
 
48
-	protected $configPrefix = null;
49
-	protected $configRead = false;
50
-	/**
51
-	 * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
52
-	 *               the config ID is registered
53
-	 */
54
-	protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
48
+    protected $configPrefix = null;
49
+    protected $configRead = false;
50
+    /**
51
+     * @var string[] pre-filled with one reference key so that at least one entry is written on save request and
52
+     *               the config ID is registered
53
+     */
54
+    protected $unsavedChanges = ['ldapConfigurationActive' => 'ldapConfigurationActive'];
55 55
 
56
-	//settings
57
-	protected $config = [
58
-		'ldapHost' => null,
59
-		'ldapPort' => null,
60
-		'ldapBackupHost' => null,
61
-		'ldapBackupPort' => null,
62
-		'ldapBase' => null,
63
-		'ldapBaseUsers' => null,
64
-		'ldapBaseGroups' => null,
65
-		'ldapAgentName' => null,
66
-		'ldapAgentPassword' => null,
67
-		'ldapTLS' => null,
68
-		'turnOffCertCheck' => null,
69
-		'ldapIgnoreNamingRules' => null,
70
-		'ldapUserDisplayName' => null,
71
-		'ldapUserDisplayName2' => null,
72
-		'ldapUserAvatarRule' => null,
73
-		'ldapGidNumber' => null,
74
-		'ldapUserFilterObjectclass' => null,
75
-		'ldapUserFilterGroups' => null,
76
-		'ldapUserFilter' => null,
77
-		'ldapUserFilterMode' => null,
78
-		'ldapGroupFilter' => null,
79
-		'ldapGroupFilterMode' => null,
80
-		'ldapGroupFilterObjectclass' => null,
81
-		'ldapGroupFilterGroups' => null,
82
-		'ldapGroupDisplayName' => null,
83
-		'ldapGroupMemberAssocAttr' => null,
84
-		'ldapLoginFilter' => null,
85
-		'ldapLoginFilterMode' => null,
86
-		'ldapLoginFilterEmail' => null,
87
-		'ldapLoginFilterUsername' => null,
88
-		'ldapLoginFilterAttributes' => null,
89
-		'ldapQuotaAttribute' => null,
90
-		'ldapQuotaDefault' => null,
91
-		'ldapEmailAttribute' => null,
92
-		'ldapCacheTTL' => null,
93
-		'ldapUuidUserAttribute' => 'auto',
94
-		'ldapUuidGroupAttribute' => 'auto',
95
-		'ldapOverrideMainServer' => false,
96
-		'ldapConfigurationActive' => false,
97
-		'ldapAttributesForUserSearch' => null,
98
-		'ldapAttributesForGroupSearch' => null,
99
-		'ldapExperiencedAdmin' => false,
100
-		'homeFolderNamingRule' => null,
101
-		'hasMemberOfFilterSupport' => false,
102
-		'useMemberOfToDetectMembership' => true,
103
-		'ldapExpertUsernameAttr' => null,
104
-		'ldapExpertUUIDUserAttr' => null,
105
-		'ldapExpertUUIDGroupAttr' => null,
106
-		'lastJpegPhotoLookup' => null,
107
-		'ldapNestedGroups' => false,
108
-		'ldapPagingSize' => null,
109
-		'turnOnPasswordChange' => false,
110
-		'ldapDynamicGroupMemberURL' => null,
111
-		'ldapDefaultPPolicyDN' => null,
112
-		'ldapExtStorageHomeAttribute' => null,
113
-	];
56
+    //settings
57
+    protected $config = [
58
+        'ldapHost' => null,
59
+        'ldapPort' => null,
60
+        'ldapBackupHost' => null,
61
+        'ldapBackupPort' => null,
62
+        'ldapBase' => null,
63
+        'ldapBaseUsers' => null,
64
+        'ldapBaseGroups' => null,
65
+        'ldapAgentName' => null,
66
+        'ldapAgentPassword' => null,
67
+        'ldapTLS' => null,
68
+        'turnOffCertCheck' => null,
69
+        'ldapIgnoreNamingRules' => null,
70
+        'ldapUserDisplayName' => null,
71
+        'ldapUserDisplayName2' => null,
72
+        'ldapUserAvatarRule' => null,
73
+        'ldapGidNumber' => null,
74
+        'ldapUserFilterObjectclass' => null,
75
+        'ldapUserFilterGroups' => null,
76
+        'ldapUserFilter' => null,
77
+        'ldapUserFilterMode' => null,
78
+        'ldapGroupFilter' => null,
79
+        'ldapGroupFilterMode' => null,
80
+        'ldapGroupFilterObjectclass' => null,
81
+        'ldapGroupFilterGroups' => null,
82
+        'ldapGroupDisplayName' => null,
83
+        'ldapGroupMemberAssocAttr' => null,
84
+        'ldapLoginFilter' => null,
85
+        'ldapLoginFilterMode' => null,
86
+        'ldapLoginFilterEmail' => null,
87
+        'ldapLoginFilterUsername' => null,
88
+        'ldapLoginFilterAttributes' => null,
89
+        'ldapQuotaAttribute' => null,
90
+        'ldapQuotaDefault' => null,
91
+        'ldapEmailAttribute' => null,
92
+        'ldapCacheTTL' => null,
93
+        'ldapUuidUserAttribute' => 'auto',
94
+        'ldapUuidGroupAttribute' => 'auto',
95
+        'ldapOverrideMainServer' => false,
96
+        'ldapConfigurationActive' => false,
97
+        'ldapAttributesForUserSearch' => null,
98
+        'ldapAttributesForGroupSearch' => null,
99
+        'ldapExperiencedAdmin' => false,
100
+        'homeFolderNamingRule' => null,
101
+        'hasMemberOfFilterSupport' => false,
102
+        'useMemberOfToDetectMembership' => true,
103
+        'ldapExpertUsernameAttr' => null,
104
+        'ldapExpertUUIDUserAttr' => null,
105
+        'ldapExpertUUIDGroupAttr' => null,
106
+        'lastJpegPhotoLookup' => null,
107
+        'ldapNestedGroups' => false,
108
+        'ldapPagingSize' => null,
109
+        'turnOnPasswordChange' => false,
110
+        'ldapDynamicGroupMemberURL' => null,
111
+        'ldapDefaultPPolicyDN' => null,
112
+        'ldapExtStorageHomeAttribute' => null,
113
+    ];
114 114
 
115
-	/**
116
-	 * @param string $configPrefix
117
-	 * @param bool $autoRead
118
-	 */
119
-	public function __construct($configPrefix, $autoRead = true) {
120
-		$this->configPrefix = $configPrefix;
121
-		if($autoRead) {
122
-			$this->readConfiguration();
123
-		}
124
-	}
115
+    /**
116
+     * @param string $configPrefix
117
+     * @param bool $autoRead
118
+     */
119
+    public function __construct($configPrefix, $autoRead = true) {
120
+        $this->configPrefix = $configPrefix;
121
+        if($autoRead) {
122
+            $this->readConfiguration();
123
+        }
124
+    }
125 125
 
126
-	/**
127
-	 * @param string $name
128
-	 * @return mixed|null
129
-	 */
130
-	public function __get($name) {
131
-		if(isset($this->config[$name])) {
132
-			return $this->config[$name];
133
-		}
134
-		return null;
135
-	}
126
+    /**
127
+     * @param string $name
128
+     * @return mixed|null
129
+     */
130
+    public function __get($name) {
131
+        if(isset($this->config[$name])) {
132
+            return $this->config[$name];
133
+        }
134
+        return null;
135
+    }
136 136
 
137
-	/**
138
-	 * @param string $name
139
-	 * @param mixed $value
140
-	 */
141
-	public function __set($name, $value) {
142
-		$this->setConfiguration([$name => $value]);
143
-	}
137
+    /**
138
+     * @param string $name
139
+     * @param mixed $value
140
+     */
141
+    public function __set($name, $value) {
142
+        $this->setConfiguration([$name => $value]);
143
+    }
144 144
 
145
-	/**
146
-	 * @return array
147
-	 */
148
-	public function getConfiguration() {
149
-		return $this->config;
150
-	}
145
+    /**
146
+     * @return array
147
+     */
148
+    public function getConfiguration() {
149
+        return $this->config;
150
+    }
151 151
 
152
-	/**
153
-	 * set LDAP configuration with values delivered by an array, not read
154
-	 * from configuration. It does not save the configuration! To do so, you
155
-	 * must call saveConfiguration afterwards.
156
-	 * @param array $config array that holds the config parameters in an associated
157
-	 * array
158
-	 * @param array &$applied optional; array where the set fields will be given to
159
-	 * @return false|null
160
-	 */
161
-	public function setConfiguration($config, &$applied = null) {
162
-		if(!is_array($config)) {
163
-			return false;
164
-		}
152
+    /**
153
+     * set LDAP configuration with values delivered by an array, not read
154
+     * from configuration. It does not save the configuration! To do so, you
155
+     * must call saveConfiguration afterwards.
156
+     * @param array $config array that holds the config parameters in an associated
157
+     * array
158
+     * @param array &$applied optional; array where the set fields will be given to
159
+     * @return false|null
160
+     */
161
+    public function setConfiguration($config, &$applied = null) {
162
+        if(!is_array($config)) {
163
+            return false;
164
+        }
165 165
 
166
-		$cta = $this->getConfigTranslationArray();
167
-		foreach($config as $inputKey => $val) {
168
-			if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
169
-				$key = $cta[$inputKey];
170
-			} elseif(array_key_exists($inputKey, $this->config)) {
171
-				$key = $inputKey;
172
-			} else {
173
-				continue;
174
-			}
166
+        $cta = $this->getConfigTranslationArray();
167
+        foreach($config as $inputKey => $val) {
168
+            if(strpos($inputKey, '_') !== false && array_key_exists($inputKey, $cta)) {
169
+                $key = $cta[$inputKey];
170
+            } elseif(array_key_exists($inputKey, $this->config)) {
171
+                $key = $inputKey;
172
+            } else {
173
+                continue;
174
+            }
175 175
 
176
-			$setMethod = 'setValue';
177
-			switch($key) {
178
-				case 'ldapAgentPassword':
179
-					$setMethod = 'setRawValue';
180
-					break;
181
-				case 'homeFolderNamingRule':
182
-					$trimmedVal = trim($val);
183
-					if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
184
-						$val = 'attr:'.$trimmedVal;
185
-					}
186
-					break;
187
-				case 'ldapBase':
188
-				case 'ldapBaseUsers':
189
-				case 'ldapBaseGroups':
190
-				case 'ldapAttributesForUserSearch':
191
-				case 'ldapAttributesForGroupSearch':
192
-				case 'ldapUserFilterObjectclass':
193
-				case 'ldapUserFilterGroups':
194
-				case 'ldapGroupFilterObjectclass':
195
-				case 'ldapGroupFilterGroups':
196
-				case 'ldapLoginFilterAttributes':
197
-					$setMethod = 'setMultiLine';
198
-					break;
199
-			}
200
-			$this->$setMethod($key, $val);
201
-			if(is_array($applied)) {
202
-				$applied[] = $inputKey;
203
-				// storing key as index avoids duplication, and as value for simplicity
204
-			}
205
-			$this->unsavedChanges[$key] = $key;
206
-		}
207
-		return null;
208
-	}
176
+            $setMethod = 'setValue';
177
+            switch($key) {
178
+                case 'ldapAgentPassword':
179
+                    $setMethod = 'setRawValue';
180
+                    break;
181
+                case 'homeFolderNamingRule':
182
+                    $trimmedVal = trim($val);
183
+                    if ($trimmedVal !== '' && strpos($val, 'attr:') === false) {
184
+                        $val = 'attr:'.$trimmedVal;
185
+                    }
186
+                    break;
187
+                case 'ldapBase':
188
+                case 'ldapBaseUsers':
189
+                case 'ldapBaseGroups':
190
+                case 'ldapAttributesForUserSearch':
191
+                case 'ldapAttributesForGroupSearch':
192
+                case 'ldapUserFilterObjectclass':
193
+                case 'ldapUserFilterGroups':
194
+                case 'ldapGroupFilterObjectclass':
195
+                case 'ldapGroupFilterGroups':
196
+                case 'ldapLoginFilterAttributes':
197
+                    $setMethod = 'setMultiLine';
198
+                    break;
199
+            }
200
+            $this->$setMethod($key, $val);
201
+            if(is_array($applied)) {
202
+                $applied[] = $inputKey;
203
+                // storing key as index avoids duplication, and as value for simplicity
204
+            }
205
+            $this->unsavedChanges[$key] = $key;
206
+        }
207
+        return null;
208
+    }
209 209
 
210
-	public function readConfiguration() {
211
-		if(!$this->configRead && !is_null($this->configPrefix)) {
212
-			$cta = array_flip($this->getConfigTranslationArray());
213
-			foreach($this->config as $key => $val) {
214
-				if(!isset($cta[$key])) {
215
-					//some are determined
216
-					continue;
217
-				}
218
-				$dbKey = $cta[$key];
219
-				switch($key) {
220
-					case 'ldapBase':
221
-					case 'ldapBaseUsers':
222
-					case 'ldapBaseGroups':
223
-					case 'ldapAttributesForUserSearch':
224
-					case 'ldapAttributesForGroupSearch':
225
-					case 'ldapUserFilterObjectclass':
226
-					case 'ldapUserFilterGroups':
227
-					case 'ldapGroupFilterObjectclass':
228
-					case 'ldapGroupFilterGroups':
229
-					case 'ldapLoginFilterAttributes':
230
-						$readMethod = 'getMultiLine';
231
-						break;
232
-					case 'ldapIgnoreNamingRules':
233
-						$readMethod = 'getSystemValue';
234
-						$dbKey = $key;
235
-						break;
236
-					case 'ldapAgentPassword':
237
-						$readMethod = 'getPwd';
238
-						break;
239
-					case 'ldapUserDisplayName2':
240
-					case 'ldapGroupDisplayName':
241
-						$readMethod = 'getLcValue';
242
-						break;
243
-					case 'ldapUserDisplayName':
244
-					default:
245
-						// user display name does not lower case because
246
-						// we rely on an upper case N as indicator whether to
247
-						// auto-detect it or not. FIXME
248
-						$readMethod = 'getValue';
249
-						break;
250
-				}
251
-				$this->config[$key] = $this->$readMethod($dbKey);
252
-			}
253
-			$this->configRead = true;
254
-		}
255
-	}
210
+    public function readConfiguration() {
211
+        if(!$this->configRead && !is_null($this->configPrefix)) {
212
+            $cta = array_flip($this->getConfigTranslationArray());
213
+            foreach($this->config as $key => $val) {
214
+                if(!isset($cta[$key])) {
215
+                    //some are determined
216
+                    continue;
217
+                }
218
+                $dbKey = $cta[$key];
219
+                switch($key) {
220
+                    case 'ldapBase':
221
+                    case 'ldapBaseUsers':
222
+                    case 'ldapBaseGroups':
223
+                    case 'ldapAttributesForUserSearch':
224
+                    case 'ldapAttributesForGroupSearch':
225
+                    case 'ldapUserFilterObjectclass':
226
+                    case 'ldapUserFilterGroups':
227
+                    case 'ldapGroupFilterObjectclass':
228
+                    case 'ldapGroupFilterGroups':
229
+                    case 'ldapLoginFilterAttributes':
230
+                        $readMethod = 'getMultiLine';
231
+                        break;
232
+                    case 'ldapIgnoreNamingRules':
233
+                        $readMethod = 'getSystemValue';
234
+                        $dbKey = $key;
235
+                        break;
236
+                    case 'ldapAgentPassword':
237
+                        $readMethod = 'getPwd';
238
+                        break;
239
+                    case 'ldapUserDisplayName2':
240
+                    case 'ldapGroupDisplayName':
241
+                        $readMethod = 'getLcValue';
242
+                        break;
243
+                    case 'ldapUserDisplayName':
244
+                    default:
245
+                        // user display name does not lower case because
246
+                        // we rely on an upper case N as indicator whether to
247
+                        // auto-detect it or not. FIXME
248
+                        $readMethod = 'getValue';
249
+                        break;
250
+                }
251
+                $this->config[$key] = $this->$readMethod($dbKey);
252
+            }
253
+            $this->configRead = true;
254
+        }
255
+    }
256 256
 
257
-	/**
258
-	 * saves the current config changes in the database
259
-	 */
260
-	public function saveConfiguration() {
261
-		$cta = array_flip($this->getConfigTranslationArray());
262
-		foreach($this->unsavedChanges as $key) {
263
-			$value = $this->config[$key];
264
-			switch ($key) {
265
-				case 'ldapAgentPassword':
266
-					$value = base64_encode($value);
267
-					break;
268
-				case 'ldapBase':
269
-				case 'ldapBaseUsers':
270
-				case 'ldapBaseGroups':
271
-				case 'ldapAttributesForUserSearch':
272
-				case 'ldapAttributesForGroupSearch':
273
-				case 'ldapUserFilterObjectclass':
274
-				case 'ldapUserFilterGroups':
275
-				case 'ldapGroupFilterObjectclass':
276
-				case 'ldapGroupFilterGroups':
277
-				case 'ldapLoginFilterAttributes':
278
-					if(is_array($value)) {
279
-						$value = implode("\n", $value);
280
-					}
281
-					break;
282
-				//following options are not stored but detected, skip them
283
-				case 'ldapIgnoreNamingRules':
284
-				case 'ldapUuidUserAttribute':
285
-				case 'ldapUuidGroupAttribute':
286
-					continue 2;
287
-			}
288
-			if(is_null($value)) {
289
-				$value = '';
290
-			}
291
-			$this->saveValue($cta[$key], $value);
292
-		}
293
-		$this->saveValue('_lastChange', time());
294
-		$this->unsavedChanges = [];
295
-	}
257
+    /**
258
+     * saves the current config changes in the database
259
+     */
260
+    public function saveConfiguration() {
261
+        $cta = array_flip($this->getConfigTranslationArray());
262
+        foreach($this->unsavedChanges as $key) {
263
+            $value = $this->config[$key];
264
+            switch ($key) {
265
+                case 'ldapAgentPassword':
266
+                    $value = base64_encode($value);
267
+                    break;
268
+                case 'ldapBase':
269
+                case 'ldapBaseUsers':
270
+                case 'ldapBaseGroups':
271
+                case 'ldapAttributesForUserSearch':
272
+                case 'ldapAttributesForGroupSearch':
273
+                case 'ldapUserFilterObjectclass':
274
+                case 'ldapUserFilterGroups':
275
+                case 'ldapGroupFilterObjectclass':
276
+                case 'ldapGroupFilterGroups':
277
+                case 'ldapLoginFilterAttributes':
278
+                    if(is_array($value)) {
279
+                        $value = implode("\n", $value);
280
+                    }
281
+                    break;
282
+                //following options are not stored but detected, skip them
283
+                case 'ldapIgnoreNamingRules':
284
+                case 'ldapUuidUserAttribute':
285
+                case 'ldapUuidGroupAttribute':
286
+                    continue 2;
287
+            }
288
+            if(is_null($value)) {
289
+                $value = '';
290
+            }
291
+            $this->saveValue($cta[$key], $value);
292
+        }
293
+        $this->saveValue('_lastChange', time());
294
+        $this->unsavedChanges = [];
295
+    }
296 296
 
297
-	/**
298
-	 * @param string $varName
299
-	 * @return array|string
300
-	 */
301
-	protected function getMultiLine($varName) {
302
-		$value = $this->getValue($varName);
303
-		if(empty($value)) {
304
-			$value = '';
305
-		} else {
306
-			$value = preg_split('/\r\n|\r|\n/', $value);
307
-		}
297
+    /**
298
+     * @param string $varName
299
+     * @return array|string
300
+     */
301
+    protected function getMultiLine($varName) {
302
+        $value = $this->getValue($varName);
303
+        if(empty($value)) {
304
+            $value = '';
305
+        } else {
306
+            $value = preg_split('/\r\n|\r|\n/', $value);
307
+        }
308 308
 
309
-		return $value;
310
-	}
309
+        return $value;
310
+    }
311 311
 
312
-	/**
313
-	 * Sets multi-line values as arrays
314
-	 *
315
-	 * @param string $varName name of config-key
316
-	 * @param array|string $value to set
317
-	 */
318
-	protected function setMultiLine($varName, $value) {
319
-		if(empty($value)) {
320
-			$value = '';
321
-		} else if (!is_array($value)) {
322
-			$value = preg_split('/\r\n|\r|\n|;/', $value);
323
-			if($value === false) {
324
-				$value = '';
325
-			}
326
-		}
312
+    /**
313
+     * Sets multi-line values as arrays
314
+     *
315
+     * @param string $varName name of config-key
316
+     * @param array|string $value to set
317
+     */
318
+    protected function setMultiLine($varName, $value) {
319
+        if(empty($value)) {
320
+            $value = '';
321
+        } else if (!is_array($value)) {
322
+            $value = preg_split('/\r\n|\r|\n|;/', $value);
323
+            if($value === false) {
324
+                $value = '';
325
+            }
326
+        }
327 327
 
328
-		if(!is_array($value)) {
329
-			$finalValue = trim($value);
330
-		} else {
331
-			$finalValue = [];
332
-			foreach($value as $key => $val) {
333
-				if(is_string($val)) {
334
-					$val = trim($val);
335
-					if ($val !== '') {
336
-						//accidental line breaks are not wanted and can cause
337
-						// odd behaviour. Thus, away with them.
338
-						$finalValue[] = $val;
339
-					}
340
-				} else {
341
-					$finalValue[] = $val;
342
-				}
343
-			}
344
-		}
328
+        if(!is_array($value)) {
329
+            $finalValue = trim($value);
330
+        } else {
331
+            $finalValue = [];
332
+            foreach($value as $key => $val) {
333
+                if(is_string($val)) {
334
+                    $val = trim($val);
335
+                    if ($val !== '') {
336
+                        //accidental line breaks are not wanted and can cause
337
+                        // odd behaviour. Thus, away with them.
338
+                        $finalValue[] = $val;
339
+                    }
340
+                } else {
341
+                    $finalValue[] = $val;
342
+                }
343
+            }
344
+        }
345 345
 
346
-		$this->setRawValue($varName, $finalValue);
347
-	}
346
+        $this->setRawValue($varName, $finalValue);
347
+    }
348 348
 
349
-	/**
350
-	 * @param string $varName
351
-	 * @return string
352
-	 */
353
-	protected function getPwd($varName) {
354
-		return base64_decode($this->getValue($varName));
355
-	}
349
+    /**
350
+     * @param string $varName
351
+     * @return string
352
+     */
353
+    protected function getPwd($varName) {
354
+        return base64_decode($this->getValue($varName));
355
+    }
356 356
 
357
-	/**
358
-	 * @param string $varName
359
-	 * @return string
360
-	 */
361
-	protected function getLcValue($varName) {
362
-		return mb_strtolower($this->getValue($varName), 'UTF-8');
363
-	}
357
+    /**
358
+     * @param string $varName
359
+     * @return string
360
+     */
361
+    protected function getLcValue($varName) {
362
+        return mb_strtolower($this->getValue($varName), 'UTF-8');
363
+    }
364 364
 
365
-	/**
366
-	 * @param string $varName
367
-	 * @return string
368
-	 */
369
-	protected function getSystemValue($varName) {
370
-		//FIXME: if another system value is added, softcode the default value
371
-		return \OC::$server->getConfig()->getSystemValue($varName, false);
372
-	}
365
+    /**
366
+     * @param string $varName
367
+     * @return string
368
+     */
369
+    protected function getSystemValue($varName) {
370
+        //FIXME: if another system value is added, softcode the default value
371
+        return \OC::$server->getConfig()->getSystemValue($varName, false);
372
+    }
373 373
 
374
-	/**
375
-	 * @param string $varName
376
-	 * @return string
377
-	 */
378
-	protected function getValue($varName) {
379
-		static $defaults;
380
-		if(is_null($defaults)) {
381
-			$defaults = $this->getDefaults();
382
-		}
383
-		return \OC::$server->getConfig()->getAppValue('user_ldap',
384
-										$this->configPrefix.$varName,
385
-										$defaults[$varName]);
386
-	}
374
+    /**
375
+     * @param string $varName
376
+     * @return string
377
+     */
378
+    protected function getValue($varName) {
379
+        static $defaults;
380
+        if(is_null($defaults)) {
381
+            $defaults = $this->getDefaults();
382
+        }
383
+        return \OC::$server->getConfig()->getAppValue('user_ldap',
384
+                                        $this->configPrefix.$varName,
385
+                                        $defaults[$varName]);
386
+    }
387 387
 
388
-	/**
389
-	 * Sets a scalar value.
390
-	 *
391
-	 * @param string $varName name of config key
392
-	 * @param mixed $value to set
393
-	 */
394
-	protected function setValue($varName, $value) {
395
-		if(is_string($value)) {
396
-			$value = trim($value);
397
-		}
398
-		$this->config[$varName] = $value;
399
-	}
388
+    /**
389
+     * Sets a scalar value.
390
+     *
391
+     * @param string $varName name of config key
392
+     * @param mixed $value to set
393
+     */
394
+    protected function setValue($varName, $value) {
395
+        if(is_string($value)) {
396
+            $value = trim($value);
397
+        }
398
+        $this->config[$varName] = $value;
399
+    }
400 400
 
401
-	/**
402
-	 * Sets a scalar value without trimming.
403
-	 *
404
-	 * @param string $varName name of config key
405
-	 * @param mixed $value to set
406
-	 */
407
-	protected function setRawValue($varName, $value) {
408
-		$this->config[$varName] = $value;
409
-	}
401
+    /**
402
+     * Sets a scalar value without trimming.
403
+     *
404
+     * @param string $varName name of config key
405
+     * @param mixed $value to set
406
+     */
407
+    protected function setRawValue($varName, $value) {
408
+        $this->config[$varName] = $value;
409
+    }
410 410
 
411
-	/**
412
-	 * @param string $varName
413
-	 * @param string $value
414
-	 * @return bool
415
-	 */
416
-	protected function saveValue($varName, $value) {
417
-		\OC::$server->getConfig()->setAppValue(
418
-			'user_ldap',
419
-			$this->configPrefix.$varName,
420
-			$value
421
-		);
422
-		return true;
423
-	}
411
+    /**
412
+     * @param string $varName
413
+     * @param string $value
414
+     * @return bool
415
+     */
416
+    protected function saveValue($varName, $value) {
417
+        \OC::$server->getConfig()->setAppValue(
418
+            'user_ldap',
419
+            $this->configPrefix.$varName,
420
+            $value
421
+        );
422
+        return true;
423
+    }
424 424
 
425
-	/**
426
-	 * @return array an associative array with the default values. Keys are correspond
427
-	 * to config-value entries in the database table
428
-	 */
429
-	public function getDefaults() {
430
-		return [
431
-			'ldap_host'                         => '',
432
-			'ldap_port'                         => '',
433
-			'ldap_backup_host'                  => '',
434
-			'ldap_backup_port'                  => '',
435
-			'ldap_override_main_server'         => '',
436
-			'ldap_dn'                           => '',
437
-			'ldap_agent_password'               => '',
438
-			'ldap_base'                         => '',
439
-			'ldap_base_users'                   => '',
440
-			'ldap_base_groups'                  => '',
441
-			'ldap_userlist_filter'              => '',
442
-			'ldap_user_filter_mode'             => 0,
443
-			'ldap_userfilter_objectclass'       => '',
444
-			'ldap_userfilter_groups'            => '',
445
-			'ldap_login_filter'                 => '',
446
-			'ldap_login_filter_mode'            => 0,
447
-			'ldap_loginfilter_email'            => 0,
448
-			'ldap_loginfilter_username'         => 1,
449
-			'ldap_loginfilter_attributes'       => '',
450
-			'ldap_group_filter'                 => '',
451
-			'ldap_group_filter_mode'            => 0,
452
-			'ldap_groupfilter_objectclass'      => '',
453
-			'ldap_groupfilter_groups'           => '',
454
-			'ldap_gid_number'                   => 'gidNumber',
455
-			'ldap_display_name'                 => 'displayName',
456
-			'ldap_user_display_name_2'			=> '',
457
-			'ldap_group_display_name'           => 'cn',
458
-			'ldap_tls'                          => 0,
459
-			'ldap_quota_def'                    => '',
460
-			'ldap_quota_attr'                   => '',
461
-			'ldap_email_attr'                   => '',
462
-			'ldap_group_member_assoc_attribute' => '',
463
-			'ldap_cache_ttl'                    => 600,
464
-			'ldap_uuid_user_attribute'          => 'auto',
465
-			'ldap_uuid_group_attribute'         => 'auto',
466
-			'home_folder_naming_rule'           => '',
467
-			'ldap_turn_off_cert_check'          => 0,
468
-			'ldap_configuration_active'         => 0,
469
-			'ldap_attributes_for_user_search'   => '',
470
-			'ldap_attributes_for_group_search'  => '',
471
-			'ldap_expert_username_attr'         => '',
472
-			'ldap_expert_uuid_user_attr'        => '',
473
-			'ldap_expert_uuid_group_attr'       => '',
474
-			'has_memberof_filter_support'       => 0,
475
-			'use_memberof_to_detect_membership' => 1,
476
-			'last_jpegPhoto_lookup'             => 0,
477
-			'ldap_nested_groups'                => 0,
478
-			'ldap_paging_size'                  => 500,
479
-			'ldap_turn_on_pwd_change'           => 0,
480
-			'ldap_experienced_admin'            => 0,
481
-			'ldap_dynamic_group_member_url'     => '',
482
-			'ldap_default_ppolicy_dn'           => '',
483
-			'ldap_user_avatar_rule'             => 'default',
484
-			'ldap_ext_storage_home_attribute'   => '',
485
-		];
486
-	}
425
+    /**
426
+     * @return array an associative array with the default values. Keys are correspond
427
+     * to config-value entries in the database table
428
+     */
429
+    public function getDefaults() {
430
+        return [
431
+            'ldap_host'                         => '',
432
+            'ldap_port'                         => '',
433
+            'ldap_backup_host'                  => '',
434
+            'ldap_backup_port'                  => '',
435
+            'ldap_override_main_server'         => '',
436
+            'ldap_dn'                           => '',
437
+            'ldap_agent_password'               => '',
438
+            'ldap_base'                         => '',
439
+            'ldap_base_users'                   => '',
440
+            'ldap_base_groups'                  => '',
441
+            'ldap_userlist_filter'              => '',
442
+            'ldap_user_filter_mode'             => 0,
443
+            'ldap_userfilter_objectclass'       => '',
444
+            'ldap_userfilter_groups'            => '',
445
+            'ldap_login_filter'                 => '',
446
+            'ldap_login_filter_mode'            => 0,
447
+            'ldap_loginfilter_email'            => 0,
448
+            'ldap_loginfilter_username'         => 1,
449
+            'ldap_loginfilter_attributes'       => '',
450
+            'ldap_group_filter'                 => '',
451
+            'ldap_group_filter_mode'            => 0,
452
+            'ldap_groupfilter_objectclass'      => '',
453
+            'ldap_groupfilter_groups'           => '',
454
+            'ldap_gid_number'                   => 'gidNumber',
455
+            'ldap_display_name'                 => 'displayName',
456
+            'ldap_user_display_name_2'			=> '',
457
+            'ldap_group_display_name'           => 'cn',
458
+            'ldap_tls'                          => 0,
459
+            'ldap_quota_def'                    => '',
460
+            'ldap_quota_attr'                   => '',
461
+            'ldap_email_attr'                   => '',
462
+            'ldap_group_member_assoc_attribute' => '',
463
+            'ldap_cache_ttl'                    => 600,
464
+            'ldap_uuid_user_attribute'          => 'auto',
465
+            'ldap_uuid_group_attribute'         => 'auto',
466
+            'home_folder_naming_rule'           => '',
467
+            'ldap_turn_off_cert_check'          => 0,
468
+            'ldap_configuration_active'         => 0,
469
+            'ldap_attributes_for_user_search'   => '',
470
+            'ldap_attributes_for_group_search'  => '',
471
+            'ldap_expert_username_attr'         => '',
472
+            'ldap_expert_uuid_user_attr'        => '',
473
+            'ldap_expert_uuid_group_attr'       => '',
474
+            'has_memberof_filter_support'       => 0,
475
+            'use_memberof_to_detect_membership' => 1,
476
+            'last_jpegPhoto_lookup'             => 0,
477
+            'ldap_nested_groups'                => 0,
478
+            'ldap_paging_size'                  => 500,
479
+            'ldap_turn_on_pwd_change'           => 0,
480
+            'ldap_experienced_admin'            => 0,
481
+            'ldap_dynamic_group_member_url'     => '',
482
+            'ldap_default_ppolicy_dn'           => '',
483
+            'ldap_user_avatar_rule'             => 'default',
484
+            'ldap_ext_storage_home_attribute'   => '',
485
+        ];
486
+    }
487 487
 
488
-	/**
489
-	 * @return array that maps internal variable names to database fields
490
-	 */
491
-	public function getConfigTranslationArray() {
492
-		//TODO: merge them into one representation
493
-		static $array = [
494
-			'ldap_host'                         => 'ldapHost',
495
-			'ldap_port'                         => 'ldapPort',
496
-			'ldap_backup_host'                  => 'ldapBackupHost',
497
-			'ldap_backup_port'                  => 'ldapBackupPort',
498
-			'ldap_override_main_server'         => 'ldapOverrideMainServer',
499
-			'ldap_dn'                           => 'ldapAgentName',
500
-			'ldap_agent_password'               => 'ldapAgentPassword',
501
-			'ldap_base'                         => 'ldapBase',
502
-			'ldap_base_users'                   => 'ldapBaseUsers',
503
-			'ldap_base_groups'                  => 'ldapBaseGroups',
504
-			'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
505
-			'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
506
-			'ldap_userlist_filter'              => 'ldapUserFilter',
507
-			'ldap_user_filter_mode'             => 'ldapUserFilterMode',
508
-			'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
509
-			'ldap_login_filter'                 => 'ldapLoginFilter',
510
-			'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
511
-			'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
512
-			'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
513
-			'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
514
-			'ldap_group_filter'                 => 'ldapGroupFilter',
515
-			'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
516
-			'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
517
-			'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
518
-			'ldap_gid_number'                   => 'ldapGidNumber',
519
-			'ldap_display_name'                 => 'ldapUserDisplayName',
520
-			'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
521
-			'ldap_group_display_name'           => 'ldapGroupDisplayName',
522
-			'ldap_tls'                          => 'ldapTLS',
523
-			'ldap_quota_def'                    => 'ldapQuotaDefault',
524
-			'ldap_quota_attr'                   => 'ldapQuotaAttribute',
525
-			'ldap_email_attr'                   => 'ldapEmailAttribute',
526
-			'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
527
-			'ldap_cache_ttl'                    => 'ldapCacheTTL',
528
-			'home_folder_naming_rule'           => 'homeFolderNamingRule',
529
-			'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
530
-			'ldap_configuration_active'         => 'ldapConfigurationActive',
531
-			'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
532
-			'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
533
-			'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
534
-			'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
535
-			'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
536
-			'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
537
-			'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
538
-			'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
539
-			'ldap_nested_groups'                => 'ldapNestedGroups',
540
-			'ldap_paging_size'                  => 'ldapPagingSize',
541
-			'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
542
-			'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
543
-			'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
544
-			'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
545
-			'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
546
-			'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
547
-		];
548
-		return $array;
549
-	}
488
+    /**
489
+     * @return array that maps internal variable names to database fields
490
+     */
491
+    public function getConfigTranslationArray() {
492
+        //TODO: merge them into one representation
493
+        static $array = [
494
+            'ldap_host'                         => 'ldapHost',
495
+            'ldap_port'                         => 'ldapPort',
496
+            'ldap_backup_host'                  => 'ldapBackupHost',
497
+            'ldap_backup_port'                  => 'ldapBackupPort',
498
+            'ldap_override_main_server'         => 'ldapOverrideMainServer',
499
+            'ldap_dn'                           => 'ldapAgentName',
500
+            'ldap_agent_password'               => 'ldapAgentPassword',
501
+            'ldap_base'                         => 'ldapBase',
502
+            'ldap_base_users'                   => 'ldapBaseUsers',
503
+            'ldap_base_groups'                  => 'ldapBaseGroups',
504
+            'ldap_userfilter_objectclass'       => 'ldapUserFilterObjectclass',
505
+            'ldap_userfilter_groups'            => 'ldapUserFilterGroups',
506
+            'ldap_userlist_filter'              => 'ldapUserFilter',
507
+            'ldap_user_filter_mode'             => 'ldapUserFilterMode',
508
+            'ldap_user_avatar_rule'             => 'ldapUserAvatarRule',
509
+            'ldap_login_filter'                 => 'ldapLoginFilter',
510
+            'ldap_login_filter_mode'            => 'ldapLoginFilterMode',
511
+            'ldap_loginfilter_email'            => 'ldapLoginFilterEmail',
512
+            'ldap_loginfilter_username'         => 'ldapLoginFilterUsername',
513
+            'ldap_loginfilter_attributes'       => 'ldapLoginFilterAttributes',
514
+            'ldap_group_filter'                 => 'ldapGroupFilter',
515
+            'ldap_group_filter_mode'            => 'ldapGroupFilterMode',
516
+            'ldap_groupfilter_objectclass'      => 'ldapGroupFilterObjectclass',
517
+            'ldap_groupfilter_groups'           => 'ldapGroupFilterGroups',
518
+            'ldap_gid_number'                   => 'ldapGidNumber',
519
+            'ldap_display_name'                 => 'ldapUserDisplayName',
520
+            'ldap_user_display_name_2'			=> 'ldapUserDisplayName2',
521
+            'ldap_group_display_name'           => 'ldapGroupDisplayName',
522
+            'ldap_tls'                          => 'ldapTLS',
523
+            'ldap_quota_def'                    => 'ldapQuotaDefault',
524
+            'ldap_quota_attr'                   => 'ldapQuotaAttribute',
525
+            'ldap_email_attr'                   => 'ldapEmailAttribute',
526
+            'ldap_group_member_assoc_attribute' => 'ldapGroupMemberAssocAttr',
527
+            'ldap_cache_ttl'                    => 'ldapCacheTTL',
528
+            'home_folder_naming_rule'           => 'homeFolderNamingRule',
529
+            'ldap_turn_off_cert_check'          => 'turnOffCertCheck',
530
+            'ldap_configuration_active'         => 'ldapConfigurationActive',
531
+            'ldap_attributes_for_user_search'   => 'ldapAttributesForUserSearch',
532
+            'ldap_attributes_for_group_search'  => 'ldapAttributesForGroupSearch',
533
+            'ldap_expert_username_attr'         => 'ldapExpertUsernameAttr',
534
+            'ldap_expert_uuid_user_attr'        => 'ldapExpertUUIDUserAttr',
535
+            'ldap_expert_uuid_group_attr'       => 'ldapExpertUUIDGroupAttr',
536
+            'has_memberof_filter_support'       => 'hasMemberOfFilterSupport',
537
+            'use_memberof_to_detect_membership' => 'useMemberOfToDetectMembership',
538
+            'last_jpegPhoto_lookup'             => 'lastJpegPhotoLookup',
539
+            'ldap_nested_groups'                => 'ldapNestedGroups',
540
+            'ldap_paging_size'                  => 'ldapPagingSize',
541
+            'ldap_turn_on_pwd_change'           => 'turnOnPasswordChange',
542
+            'ldap_experienced_admin'            => 'ldapExperiencedAdmin',
543
+            'ldap_dynamic_group_member_url'     => 'ldapDynamicGroupMemberURL',
544
+            'ldap_default_ppolicy_dn'           => 'ldapDefaultPPolicyDN',
545
+            'ldap_ext_storage_home_attribute'   => 'ldapExtStorageHomeAttribute',
546
+            'ldapIgnoreNamingRules'             => 'ldapIgnoreNamingRules',	// sysconfig
547
+        ];
548
+        return $array;
549
+    }
550 550
 
551
-	/**
552
-	 * @param string $rule
553
-	 * @return array
554
-	 * @throws \RuntimeException
555
-	 */
556
-	public function resolveRule($rule) {
557
-		if($rule === 'avatar') {
558
-			return $this->getAvatarAttributes();
559
-		}
560
-		throw new \RuntimeException('Invalid rule');
561
-	}
551
+    /**
552
+     * @param string $rule
553
+     * @return array
554
+     * @throws \RuntimeException
555
+     */
556
+    public function resolveRule($rule) {
557
+        if($rule === 'avatar') {
558
+            return $this->getAvatarAttributes();
559
+        }
560
+        throw new \RuntimeException('Invalid rule');
561
+    }
562 562
 
563
-	public function getAvatarAttributes() {
564
-		$value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
565
-		$defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
563
+    public function getAvatarAttributes() {
564
+        $value = $this->ldapUserAvatarRule ?: self::AVATAR_PREFIX_DEFAULT;
565
+        $defaultAttributes = ['jpegphoto', 'thumbnailphoto'];
566 566
 
567
-		if($value === self::AVATAR_PREFIX_NONE) {
568
-			return [];
569
-		}
570
-		if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
571
-			$attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
572
-			if($attribute === '') {
573
-				return $defaultAttributes;
574
-			}
575
-			return [strtolower($attribute)];
576
-		}
577
-		if($value !== self::AVATAR_PREFIX_DEFAULT) {
578
-			\OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
579
-		}
580
-		return $defaultAttributes;
581
-	}
567
+        if($value === self::AVATAR_PREFIX_NONE) {
568
+            return [];
569
+        }
570
+        if(strpos($value, self::AVATAR_PREFIX_DATA_ATTRIBUTE) === 0) {
571
+            $attribute = trim(substr($value, strlen(self::AVATAR_PREFIX_DATA_ATTRIBUTE)));
572
+            if($attribute === '') {
573
+                return $defaultAttributes;
574
+            }
575
+            return [strtolower($attribute)];
576
+        }
577
+        if($value !== self::AVATAR_PREFIX_DEFAULT) {
578
+            \OC::$server->getLogger()->warning('Invalid config value to ldapUserAvatarRule; falling back to default.');
579
+        }
580
+        return $defaultAttributes;
581
+    }
582 582
 
583 583
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Access.php 1 patch
Indentation   +2028 added lines, -2028 removed lines patch added patch discarded remove patch
@@ -64,1779 +64,1779 @@  discard block
 block discarded – undo
64 64
  * @package OCA\User_LDAP
65 65
  */
66 66
 class Access extends LDAPUtility {
67
-	const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
68
-
69
-	/** @var \OCA\User_LDAP\Connection */
70
-	public $connection;
71
-	/** @var Manager */
72
-	public $userManager;
73
-	//never ever check this var directly, always use getPagedSearchResultState
74
-	protected $pagedSearchedSuccessful;
75
-
76
-	/**
77
-	 * @var string[] $cookies an array of returned Paged Result cookies
78
-	 */
79
-	protected $cookies = [];
80
-
81
-	/**
82
-	 * @var string $lastCookie the last cookie returned from a Paged Results
83
-	 * operation, defaults to an empty string
84
-	 */
85
-	protected $lastCookie = '';
86
-
87
-	/**
88
-	 * @var AbstractMapping $userMapper
89
-	 */
90
-	protected $userMapper;
91
-
92
-	/**
93
-	 * @var AbstractMapping $userMapper
94
-	 */
95
-	protected $groupMapper;
96
-
97
-	/**
98
-	 * @var \OCA\User_LDAP\Helper
99
-	 */
100
-	private $helper;
101
-	/** @var IConfig */
102
-	private $config;
103
-	/** @var IUserManager */
104
-	private $ncUserManager;
105
-
106
-	public function __construct(
107
-		Connection $connection,
108
-		ILDAPWrapper $ldap,
109
-		Manager $userManager,
110
-		Helper $helper,
111
-		IConfig $config,
112
-		IUserManager $ncUserManager
113
-	) {
114
-		parent::__construct($ldap);
115
-		$this->connection = $connection;
116
-		$this->userManager = $userManager;
117
-		$this->userManager->setLdapAccess($this);
118
-		$this->helper = $helper;
119
-		$this->config = $config;
120
-		$this->ncUserManager = $ncUserManager;
121
-	}
122
-
123
-	/**
124
-	 * sets the User Mapper
125
-	 * @param AbstractMapping $mapper
126
-	 */
127
-	public function setUserMapper(AbstractMapping $mapper) {
128
-		$this->userMapper = $mapper;
129
-	}
130
-
131
-	/**
132
-	 * returns the User Mapper
133
-	 * @throws \Exception
134
-	 * @return AbstractMapping
135
-	 */
136
-	public function getUserMapper() {
137
-		if(is_null($this->userMapper)) {
138
-			throw new \Exception('UserMapper was not assigned to this Access instance.');
139
-		}
140
-		return $this->userMapper;
141
-	}
142
-
143
-	/**
144
-	 * sets the Group Mapper
145
-	 * @param AbstractMapping $mapper
146
-	 */
147
-	public function setGroupMapper(AbstractMapping $mapper) {
148
-		$this->groupMapper = $mapper;
149
-	}
150
-
151
-	/**
152
-	 * returns the Group Mapper
153
-	 * @throws \Exception
154
-	 * @return AbstractMapping
155
-	 */
156
-	public function getGroupMapper() {
157
-		if(is_null($this->groupMapper)) {
158
-			throw new \Exception('GroupMapper was not assigned to this Access instance.');
159
-		}
160
-		return $this->groupMapper;
161
-	}
162
-
163
-	/**
164
-	 * @return bool
165
-	 */
166
-	private function checkConnection() {
167
-		return ($this->connection instanceof Connection);
168
-	}
169
-
170
-	/**
171
-	 * returns the Connection instance
172
-	 * @return \OCA\User_LDAP\Connection
173
-	 */
174
-	public function getConnection() {
175
-		return $this->connection;
176
-	}
177
-
178
-	/**
179
-	 * reads a given attribute for an LDAP record identified by a DN
180
-	 *
181
-	 * @param string $dn the record in question
182
-	 * @param string $attr the attribute that shall be retrieved
183
-	 *        if empty, just check the record's existence
184
-	 * @param string $filter
185
-	 * @return array|false an array of values on success or an empty
186
-	 *          array if $attr is empty, false otherwise
187
-	 * @throws ServerNotAvailableException
188
-	 */
189
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
190
-		if(!$this->checkConnection()) {
191
-			\OCP\Util::writeLog('user_ldap',
192
-				'No LDAP Connector assigned, access impossible for readAttribute.',
193
-				ILogger::WARN);
194
-			return false;
195
-		}
196
-		$cr = $this->connection->getConnectionResource();
197
-		if(!$this->ldap->isResource($cr)) {
198
-			//LDAP not available
199
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
200
-			return false;
201
-		}
202
-		//Cancel possibly running Paged Results operation, otherwise we run in
203
-		//LDAP protocol errors
204
-		$this->abandonPagedSearch();
205
-		// openLDAP requires that we init a new Paged Search. Not needed by AD,
206
-		// but does not hurt either.
207
-		$pagingSize = (int)$this->connection->ldapPagingSize;
208
-		// 0 won't result in replies, small numbers may leave out groups
209
-		// (cf. #12306), 500 is default for paging and should work everywhere.
210
-		$maxResults = $pagingSize > 20 ? $pagingSize : 500;
211
-		$attr = mb_strtolower($attr, 'UTF-8');
212
-		// the actual read attribute later may contain parameters on a ranged
213
-		// request, e.g. member;range=99-199. Depends on server reply.
214
-		$attrToRead = $attr;
215
-
216
-		$values = [];
217
-		$isRangeRequest = false;
218
-		do {
219
-			$result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
220
-			if(is_bool($result)) {
221
-				// when an exists request was run and it was successful, an empty
222
-				// array must be returned
223
-				return $result ? [] : false;
224
-			}
225
-
226
-			if (!$isRangeRequest) {
227
-				$values = $this->extractAttributeValuesFromResult($result, $attr);
228
-				if (!empty($values)) {
229
-					return $values;
230
-				}
231
-			}
232
-
233
-			$isRangeRequest = false;
234
-			$result = $this->extractRangeData($result, $attr);
235
-			if (!empty($result)) {
236
-				$normalizedResult = $this->extractAttributeValuesFromResult(
237
-					[ $attr => $result['values'] ],
238
-					$attr
239
-				);
240
-				$values = array_merge($values, $normalizedResult);
241
-
242
-				if($result['rangeHigh'] === '*') {
243
-					// when server replies with * as high range value, there are
244
-					// no more results left
245
-					return $values;
246
-				} else {
247
-					$low  = $result['rangeHigh'] + 1;
248
-					$attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
249
-					$isRangeRequest = true;
250
-				}
251
-			}
252
-		} while($isRangeRequest);
253
-
254
-		\OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
255
-		return false;
256
-	}
257
-
258
-	/**
259
-	 * Runs an read operation against LDAP
260
-	 *
261
-	 * @param resource $cr the LDAP connection
262
-	 * @param string $dn
263
-	 * @param string $attribute
264
-	 * @param string $filter
265
-	 * @param int $maxResults
266
-	 * @return array|bool false if there was any error, true if an exists check
267
-	 *                    was performed and the requested DN found, array with the
268
-	 *                    returned data on a successful usual operation
269
-	 * @throws ServerNotAvailableException
270
-	 */
271
-	public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
272
-		$this->initPagedSearch($filter, [$dn], [$attribute], $maxResults, 0);
273
-		$dn = $this->helper->DNasBaseParameter($dn);
274
-		$rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
275
-		if (!$this->ldap->isResource($rr)) {
276
-			if ($attribute !== '') {
277
-				//do not throw this message on userExists check, irritates
278
-				\OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
279
-			}
280
-			//in case an error occurs , e.g. object does not exist
281
-			return false;
282
-		}
283
-		if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
284
-			\OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
285
-			return true;
286
-		}
287
-		$er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
288
-		if (!$this->ldap->isResource($er)) {
289
-			//did not match the filter, return false
290
-			return false;
291
-		}
292
-		//LDAP attributes are not case sensitive
293
-		$result = \OCP\Util::mb_array_change_key_case(
294
-			$this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
295
-
296
-		return $result;
297
-	}
298
-
299
-	/**
300
-	 * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
301
-	 * data if present.
302
-	 *
303
-	 * @param array $result from ILDAPWrapper::getAttributes()
304
-	 * @param string $attribute the attribute name that was read
305
-	 * @return string[]
306
-	 */
307
-	public function extractAttributeValuesFromResult($result, $attribute) {
308
-		$values = [];
309
-		if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
310
-			$lowercaseAttribute = strtolower($attribute);
311
-			for($i=0;$i<$result[$attribute]['count'];$i++) {
312
-				if($this->resemblesDN($attribute)) {
313
-					$values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
314
-				} elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
315
-					$values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
316
-				} else {
317
-					$values[] = $result[$attribute][$i];
318
-				}
319
-			}
320
-		}
321
-		return $values;
322
-	}
323
-
324
-	/**
325
-	 * Attempts to find ranged data in a getAttribute results and extracts the
326
-	 * returned values as well as information on the range and full attribute
327
-	 * name for further processing.
328
-	 *
329
-	 * @param array $result from ILDAPWrapper::getAttributes()
330
-	 * @param string $attribute the attribute name that was read. Without ";range=…"
331
-	 * @return array If a range was detected with keys 'values', 'attributeName',
332
-	 *               'attributeFull' and 'rangeHigh', otherwise empty.
333
-	 */
334
-	public function extractRangeData($result, $attribute) {
335
-		$keys = array_keys($result);
336
-		foreach($keys as $key) {
337
-			if($key !== $attribute && strpos($key, $attribute) === 0) {
338
-				$queryData = explode(';', $key);
339
-				if(strpos($queryData[1], 'range=') === 0) {
340
-					$high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
341
-					$data = [
342
-						'values' => $result[$key],
343
-						'attributeName' => $queryData[0],
344
-						'attributeFull' => $key,
345
-						'rangeHigh' => $high,
346
-					];
347
-					return $data;
348
-				}
349
-			}
350
-		}
351
-		return [];
352
-	}
353
-
354
-	/**
355
-	 * Set password for an LDAP user identified by a DN
356
-	 *
357
-	 * @param string $userDN the user in question
358
-	 * @param string $password the new password
359
-	 * @return bool
360
-	 * @throws HintException
361
-	 * @throws \Exception
362
-	 */
363
-	public function setPassword($userDN, $password) {
364
-		if((int)$this->connection->turnOnPasswordChange !== 1) {
365
-			throw new \Exception('LDAP password changes are disabled.');
366
-		}
367
-		$cr = $this->connection->getConnectionResource();
368
-		if(!$this->ldap->isResource($cr)) {
369
-			//LDAP not available
370
-			\OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
371
-			return false;
372
-		}
373
-		try {
374
-			// try PASSWD extended operation first
375
-			return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
376
-						@$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
377
-		} catch(ConstraintViolationException $e) {
378
-			throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
379
-		}
380
-	}
381
-
382
-	/**
383
-	 * checks whether the given attributes value is probably a DN
384
-	 * @param string $attr the attribute in question
385
-	 * @return boolean if so true, otherwise false
386
-	 */
387
-	private function resemblesDN($attr) {
388
-		$resemblingAttributes = [
389
-			'dn',
390
-			'uniquemember',
391
-			'member',
392
-			// memberOf is an "operational" attribute, without a definition in any RFC
393
-			'memberof'
394
-		];
395
-		return in_array($attr, $resemblingAttributes);
396
-	}
397
-
398
-	/**
399
-	 * checks whether the given string is probably a DN
400
-	 * @param string $string
401
-	 * @return boolean
402
-	 */
403
-	public function stringResemblesDN($string) {
404
-		$r = $this->ldap->explodeDN($string, 0);
405
-		// if exploding a DN succeeds and does not end up in
406
-		// an empty array except for $r[count] being 0.
407
-		return (is_array($r) && count($r) > 1);
408
-	}
409
-
410
-	/**
411
-	 * returns a DN-string that is cleaned from not domain parts, e.g.
412
-	 * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
413
-	 * becomes dc=foobar,dc=server,dc=org
414
-	 * @param string $dn
415
-	 * @return string
416
-	 */
417
-	public function getDomainDNFromDN($dn) {
418
-		$allParts = $this->ldap->explodeDN($dn, 0);
419
-		if($allParts === false) {
420
-			//not a valid DN
421
-			return '';
422
-		}
423
-		$domainParts = [];
424
-		$dcFound = false;
425
-		foreach($allParts as $part) {
426
-			if(!$dcFound && strpos($part, 'dc=') === 0) {
427
-				$dcFound = true;
428
-			}
429
-			if($dcFound) {
430
-				$domainParts[] = $part;
431
-			}
432
-		}
433
-		return implode(',', $domainParts);
434
-	}
435
-
436
-	/**
437
-	 * returns the LDAP DN for the given internal Nextcloud name of the group
438
-	 * @param string $name the Nextcloud name in question
439
-	 * @return string|false LDAP DN on success, otherwise false
440
-	 */
441
-	public function groupname2dn($name) {
442
-		return $this->groupMapper->getDNByName($name);
443
-	}
444
-
445
-	/**
446
-	 * returns the LDAP DN for the given internal Nextcloud name of the user
447
-	 * @param string $name the Nextcloud name in question
448
-	 * @return string|false with the LDAP DN on success, otherwise false
449
-	 */
450
-	public function username2dn($name) {
451
-		$fdn = $this->userMapper->getDNByName($name);
452
-
453
-		//Check whether the DN belongs to the Base, to avoid issues on multi-
454
-		//server setups
455
-		if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
456
-			return $fdn;
457
-		}
458
-
459
-		return false;
460
-	}
461
-
462
-	/**
463
-	 * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
464
-	 *
465
-	 * @param string $fdn the dn of the group object
466
-	 * @param string $ldapName optional, the display name of the object
467
-	 * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
468
-	 * @throws \Exception
469
-	 */
470
-	public function dn2groupname($fdn, $ldapName = null) {
471
-		//To avoid bypassing the base DN settings under certain circumstances
472
-		//with the group support, check whether the provided DN matches one of
473
-		//the given Bases
474
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
475
-			return false;
476
-		}
477
-
478
-		return $this->dn2ocname($fdn, $ldapName, false);
479
-	}
480
-
481
-	/**
482
-	 * accepts an array of group DNs and tests whether they match the user
483
-	 * filter by doing read operations against the group entries. Returns an
484
-	 * array of DNs that match the filter.
485
-	 *
486
-	 * @param string[] $groupDNs
487
-	 * @return string[]
488
-	 * @throws ServerNotAvailableException
489
-	 */
490
-	public function groupsMatchFilter($groupDNs) {
491
-		$validGroupDNs = [];
492
-		foreach($groupDNs as $dn) {
493
-			$cacheKey = 'groupsMatchFilter-'.$dn;
494
-			$groupMatchFilter = $this->connection->getFromCache($cacheKey);
495
-			if(!is_null($groupMatchFilter)) {
496
-				if($groupMatchFilter) {
497
-					$validGroupDNs[] = $dn;
498
-				}
499
-				continue;
500
-			}
501
-
502
-			// Check the base DN first. If this is not met already, we don't
503
-			// need to ask the server at all.
504
-			if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
505
-				$this->connection->writeToCache($cacheKey, false);
506
-				continue;
507
-			}
508
-
509
-			$result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
510
-			if(is_array($result)) {
511
-				$this->connection->writeToCache($cacheKey, true);
512
-				$validGroupDNs[] = $dn;
513
-			} else {
514
-				$this->connection->writeToCache($cacheKey, false);
515
-			}
516
-
517
-		}
518
-		return $validGroupDNs;
519
-	}
520
-
521
-	/**
522
-	 * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
523
-	 *
524
-	 * @param string $dn the dn of the user object
525
-	 * @param string $ldapName optional, the display name of the object
526
-	 * @return string|false with with the name to use in Nextcloud
527
-	 * @throws \Exception
528
-	 */
529
-	public function dn2username($fdn, $ldapName = null) {
530
-		//To avoid bypassing the base DN settings under certain circumstances
531
-		//with the group support, check whether the provided DN matches one of
532
-		//the given Bases
533
-		if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
534
-			return false;
535
-		}
536
-
537
-		return $this->dn2ocname($fdn, $ldapName, true);
538
-	}
539
-
540
-	/**
541
-	 * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
542
-	 *
543
-	 * @param string $fdn the dn of the user object
544
-	 * @param string|null $ldapName optional, the display name of the object
545
-	 * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
546
-	 * @param bool|null $newlyMapped
547
-	 * @param array|null $record
548
-	 * @return false|string with with the name to use in Nextcloud
549
-	 * @throws \Exception
550
-	 */
551
-	public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
552
-		$newlyMapped = false;
553
-		if($isUser) {
554
-			$mapper = $this->getUserMapper();
555
-			$nameAttribute = $this->connection->ldapUserDisplayName;
556
-			$filter = $this->connection->ldapUserFilter;
557
-		} else {
558
-			$mapper = $this->getGroupMapper();
559
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
560
-			$filter = $this->connection->ldapGroupFilter;
561
-		}
562
-
563
-		//let's try to retrieve the Nextcloud name from the mappings table
564
-		$ncName = $mapper->getNameByDN($fdn);
565
-		if(is_string($ncName)) {
566
-			return $ncName;
567
-		}
568
-
569
-		//second try: get the UUID and check if it is known. Then, update the DN and return the name.
570
-		$uuid = $this->getUUID($fdn, $isUser, $record);
571
-		if(is_string($uuid)) {
572
-			$ncName = $mapper->getNameByUUID($uuid);
573
-			if(is_string($ncName)) {
574
-				$mapper->setDNbyUUID($fdn, $uuid);
575
-				return $ncName;
576
-			}
577
-		} else {
578
-			//If the UUID can't be detected something is foul.
579
-			\OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
580
-			return false;
581
-		}
582
-
583
-		if(is_null($ldapName)) {
584
-			$ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
585
-			if(!isset($ldapName[0]) && empty($ldapName[0])) {
586
-				\OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
587
-				return false;
588
-			}
589
-			$ldapName = $ldapName[0];
590
-		}
591
-
592
-		if($isUser) {
593
-			$usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
594
-			if ($usernameAttribute !== '') {
595
-				$username = $this->readAttribute($fdn, $usernameAttribute);
596
-				$username = $username[0];
597
-			} else {
598
-				$username = $uuid;
599
-			}
600
-			try {
601
-				$intName = $this->sanitizeUsername($username);
602
-			} catch (\InvalidArgumentException $e) {
603
-				\OC::$server->getLogger()->logException($e, [
604
-					'app' => 'user_ldap',
605
-					'level' => ILogger::WARN,
606
-				]);
607
-				// we don't attempt to set a username here. We can go for
608
-				// for an alternative 4 digit random number as we would append
609
-				// otherwise, however it's likely not enough space in bigger
610
-				// setups, and most importantly: this is not intended.
611
-				return false;
612
-			}
613
-		} else {
614
-			$intName = $ldapName;
615
-		}
616
-
617
-		//a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
618
-		//disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
619
-		//NOTE: mind, disabling cache affects only this instance! Using it
620
-		// outside of core user management will still cache the user as non-existing.
621
-		$originalTTL = $this->connection->ldapCacheTTL;
622
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
623
-		if($intName !== ''
624
-			&& (($isUser && !$this->ncUserManager->userExists($intName))
625
-				|| (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
626
-			)
627
-		) {
628
-			$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
629
-			$newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
630
-			if($newlyMapped) {
631
-				return $intName;
632
-			}
633
-		}
634
-
635
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
636
-		$altName = $this->createAltInternalOwnCloudName($intName, $isUser);
637
-		if (is_string($altName)) {
638
-			if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
639
-				$newlyMapped = true;
640
-				return $altName;
641
-			}
642
-		}
643
-
644
-		//if everything else did not help..
645
-		\OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
646
-		return false;
647
-	}
648
-
649
-	public function mapAndAnnounceIfApplicable(
650
-		AbstractMapping $mapper,
651
-		string $fdn,
652
-		string $name,
653
-		string $uuid,
654
-		bool $isUser
655
-	) :bool {
656
-		if($mapper->map($fdn, $name, $uuid)) {
657
-			if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
658
-				$this->cacheUserExists($name);
659
-				$this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
660
-			} elseif (!$isUser) {
661
-				$this->cacheGroupExists($name);
662
-			}
663
-			return true;
664
-		}
665
-		return false;
666
-	}
667
-
668
-	/**
669
-	 * gives back the user names as they are used ownClod internally
670
-	 *
671
-	 * @param array $ldapUsers as returned by fetchList()
672
-	 * @return array an array with the user names to use in Nextcloud
673
-	 *
674
-	 * gives back the user names as they are used ownClod internally
675
-	 * @throws \Exception
676
-	 */
677
-	public function nextcloudUserNames($ldapUsers) {
678
-		return $this->ldap2NextcloudNames($ldapUsers, true);
679
-	}
680
-
681
-	/**
682
-	 * gives back the group names as they are used ownClod internally
683
-	 *
684
-	 * @param array $ldapGroups as returned by fetchList()
685
-	 * @return array an array with the group names to use in Nextcloud
686
-	 *
687
-	 * gives back the group names as they are used ownClod internally
688
-	 * @throws \Exception
689
-	 */
690
-	public function nextcloudGroupNames($ldapGroups) {
691
-		return $this->ldap2NextcloudNames($ldapGroups, false);
692
-	}
693
-
694
-	/**
695
-	 * @param array $ldapObjects as returned by fetchList()
696
-	 * @param bool $isUsers
697
-	 * @return array
698
-	 * @throws \Exception
699
-	 */
700
-	private function ldap2NextcloudNames($ldapObjects, $isUsers) {
701
-		if($isUsers) {
702
-			$nameAttribute = $this->connection->ldapUserDisplayName;
703
-			$sndAttribute  = $this->connection->ldapUserDisplayName2;
704
-		} else {
705
-			$nameAttribute = $this->connection->ldapGroupDisplayName;
706
-		}
707
-		$nextcloudNames = [];
708
-
709
-		foreach($ldapObjects as $ldapObject) {
710
-			$nameByLDAP = null;
711
-			if(isset($ldapObject[$nameAttribute])
712
-				&& is_array($ldapObject[$nameAttribute])
713
-				&& isset($ldapObject[$nameAttribute][0])
714
-			) {
715
-				// might be set, but not necessarily. if so, we use it.
716
-				$nameByLDAP = $ldapObject[$nameAttribute][0];
717
-			}
718
-
719
-			$ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
720
-			if($ncName) {
721
-				$nextcloudNames[] = $ncName;
722
-				if($isUsers) {
723
-					$this->updateUserState($ncName);
724
-					//cache the user names so it does not need to be retrieved
725
-					//again later (e.g. sharing dialogue).
726
-					if(is_null($nameByLDAP)) {
727
-						continue;
728
-					}
729
-					$sndName = isset($ldapObject[$sndAttribute][0])
730
-						? $ldapObject[$sndAttribute][0] : '';
731
-					$this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
732
-				} else if($nameByLDAP !== null) {
733
-					$this->cacheGroupDisplayName($ncName, $nameByLDAP);
734
-				}
735
-			}
736
-		}
737
-		return $nextcloudNames;
738
-	}
739
-
740
-	/**
741
-	 * removes the deleted-flag of a user if it was set
742
-	 *
743
-	 * @param string $ncname
744
-	 * @throws \Exception
745
-	 */
746
-	public function updateUserState($ncname) {
747
-		$user = $this->userManager->get($ncname);
748
-		if($user instanceof OfflineUser) {
749
-			$user->unmark();
750
-		}
751
-	}
752
-
753
-	/**
754
-	 * caches the user display name
755
-	 * @param string $ocName the internal Nextcloud username
756
-	 * @param string|false $home the home directory path
757
-	 */
758
-	public function cacheUserHome($ocName, $home) {
759
-		$cacheKey = 'getHome'.$ocName;
760
-		$this->connection->writeToCache($cacheKey, $home);
761
-	}
762
-
763
-	/**
764
-	 * caches a user as existing
765
-	 * @param string $ocName the internal Nextcloud username
766
-	 */
767
-	public function cacheUserExists($ocName) {
768
-		$this->connection->writeToCache('userExists'.$ocName, true);
769
-	}
770
-
771
-	/**
772
-	 * caches a group as existing
773
-	 */
774
-	public function cacheGroupExists(string $gid): void {
775
-		$this->connection->writeToCache('groupExists'.$gid, true);
776
-	}
777
-
778
-	/**
779
-	 * caches the user display name
780
-	 *
781
-	 * @param string $ocName the internal Nextcloud username
782
-	 * @param string $displayName the display name
783
-	 * @param string $displayName2 the second display name
784
-	 * @throws \Exception
785
-	 */
786
-	public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
787
-		$user = $this->userManager->get($ocName);
788
-		if($user === null) {
789
-			return;
790
-		}
791
-		$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
792
-		$cacheKeyTrunk = 'getDisplayName';
793
-		$this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
794
-	}
795
-
796
-	public function cacheGroupDisplayName(string $ncName, string $displayName): void {
797
-		$cacheKey = 'group_getDisplayName' . $ncName;
798
-		$this->connection->writeToCache($cacheKey, $displayName);
799
-	}
800
-
801
-	/**
802
-	 * creates a unique name for internal Nextcloud use for users. Don't call it directly.
803
-	 * @param string $name the display name of the object
804
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
805
-	 *
806
-	 * Instead of using this method directly, call
807
-	 * createAltInternalOwnCloudName($name, true)
808
-	 */
809
-	private function _createAltInternalOwnCloudNameForUsers($name) {
810
-		$attempts = 0;
811
-		//while loop is just a precaution. If a name is not generated within
812
-		//20 attempts, something else is very wrong. Avoids infinite loop.
813
-		while($attempts < 20){
814
-			$altName = $name . '_' . rand(1000,9999);
815
-			if(!$this->ncUserManager->userExists($altName)) {
816
-				return $altName;
817
-			}
818
-			$attempts++;
819
-		}
820
-		return false;
821
-	}
822
-
823
-	/**
824
-	 * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
825
-	 * @param string $name the display name of the object
826
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
827
-	 *
828
-	 * Instead of using this method directly, call
829
-	 * createAltInternalOwnCloudName($name, false)
830
-	 *
831
-	 * Group names are also used as display names, so we do a sequential
832
-	 * numbering, e.g. Developers_42 when there are 41 other groups called
833
-	 * "Developers"
834
-	 */
835
-	private function _createAltInternalOwnCloudNameForGroups($name) {
836
-		$usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
837
-		if(!$usedNames || count($usedNames) === 0) {
838
-			$lastNo = 1; //will become name_2
839
-		} else {
840
-			natsort($usedNames);
841
-			$lastName = array_pop($usedNames);
842
-			$lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
843
-		}
844
-		$altName = $name.'_'. (string)($lastNo+1);
845
-		unset($usedNames);
846
-
847
-		$attempts = 1;
848
-		while($attempts < 21){
849
-			// Check to be really sure it is unique
850
-			// while loop is just a precaution. If a name is not generated within
851
-			// 20 attempts, something else is very wrong. Avoids infinite loop.
852
-			if(!\OC::$server->getGroupManager()->groupExists($altName)) {
853
-				return $altName;
854
-			}
855
-			$altName = $name . '_' . ($lastNo + $attempts);
856
-			$attempts++;
857
-		}
858
-		return false;
859
-	}
860
-
861
-	/**
862
-	 * creates a unique name for internal Nextcloud use.
863
-	 * @param string $name the display name of the object
864
-	 * @param boolean $isUser whether name should be created for a user (true) or a group (false)
865
-	 * @return string|false with with the name to use in Nextcloud or false if unsuccessful
866
-	 */
867
-	private function createAltInternalOwnCloudName($name, $isUser) {
868
-		$originalTTL = $this->connection->ldapCacheTTL;
869
-		$this->connection->setConfiguration(['ldapCacheTTL' => 0]);
870
-		if($isUser) {
871
-			$altName = $this->_createAltInternalOwnCloudNameForUsers($name);
872
-		} else {
873
-			$altName = $this->_createAltInternalOwnCloudNameForGroups($name);
874
-		}
875
-		$this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
876
-
877
-		return $altName;
878
-	}
879
-
880
-	/**
881
-	 * fetches a list of users according to a provided loginName and utilizing
882
-	 * the login filter.
883
-	 *
884
-	 * @param string $loginName
885
-	 * @param array $attributes optional, list of attributes to read
886
-	 * @return array
887
-	 */
888
-	public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
889
-		$loginName = $this->escapeFilterPart($loginName);
890
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
891
-		return $this->fetchListOfUsers($filter, $attributes);
892
-	}
893
-
894
-	/**
895
-	 * counts the number of users according to a provided loginName and
896
-	 * utilizing the login filter.
897
-	 *
898
-	 * @param string $loginName
899
-	 * @return int
900
-	 */
901
-	public function countUsersByLoginName($loginName) {
902
-		$loginName = $this->escapeFilterPart($loginName);
903
-		$filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
904
-		return $this->countUsers($filter);
905
-	}
906
-
907
-	/**
908
-	 * @param string $filter
909
-	 * @param string|string[] $attr
910
-	 * @param int $limit
911
-	 * @param int $offset
912
-	 * @param bool $forceApplyAttributes
913
-	 * @return array
914
-	 * @throws \Exception
915
-	 */
916
-	public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
917
-		$ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
918
-		$recordsToUpdate = $ldapRecords;
919
-		if(!$forceApplyAttributes) {
920
-			$isBackgroundJobModeAjax = $this->config
921
-					->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
922
-			$recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) {
923
-				$newlyMapped = false;
924
-				$uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
925
-				if(is_string($uid)) {
926
-					$this->cacheUserExists($uid);
927
-				}
928
-				return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
929
-			});
930
-		}
931
-		$this->batchApplyUserAttributes($recordsToUpdate);
932
-		return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
933
-	}
934
-
935
-	/**
936
-	 * provided with an array of LDAP user records the method will fetch the
937
-	 * user object and requests it to process the freshly fetched attributes and
938
-	 * and their values
939
-	 *
940
-	 * @param array $ldapRecords
941
-	 * @throws \Exception
942
-	 */
943
-	public function batchApplyUserAttributes(array $ldapRecords) {
944
-		$displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
945
-		foreach($ldapRecords as $userRecord) {
946
-			if(!isset($userRecord[$displayNameAttribute])) {
947
-				// displayName is obligatory
948
-				continue;
949
-			}
950
-			$ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
951
-			if($ocName === false) {
952
-				continue;
953
-			}
954
-			$this->updateUserState($ocName);
955
-			$user = $this->userManager->get($ocName);
956
-			if ($user !== null) {
957
-				$user->processAttributes($userRecord);
958
-			} else {
959
-				\OC::$server->getLogger()->debug(
960
-					"The ldap user manager returned null for $ocName",
961
-					['app'=>'user_ldap']
962
-				);
963
-			}
964
-		}
965
-	}
966
-
967
-	/**
968
-	 * @param string $filter
969
-	 * @param string|string[] $attr
970
-	 * @param int $limit
971
-	 * @param int $offset
972
-	 * @return array
973
-	 */
974
-	public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
975
-		$groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
976
-		array_walk($groupRecords, function ($record) {
977
-			$newlyMapped = false;
978
-			$gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
979
-			if(!$newlyMapped && is_string($gid)) {
980
-				$this->cacheGroupExists($gid);
981
-			}
982
-		});
983
-		return $this->fetchList($groupRecords, $this->manyAttributes($attr));
984
-	}
985
-
986
-	/**
987
-	 * @param array $list
988
-	 * @param bool $manyAttributes
989
-	 * @return array
990
-	 */
991
-	private function fetchList($list, $manyAttributes) {
992
-		if(is_array($list)) {
993
-			if($manyAttributes) {
994
-				return $list;
995
-			} else {
996
-				$list = array_reduce($list, function ($carry, $item) {
997
-					$attribute = array_keys($item)[0];
998
-					$carry[] = $item[$attribute][0];
999
-					return $carry;
1000
-				}, []);
1001
-				return array_unique($list, SORT_LOCALE_STRING);
1002
-			}
1003
-		}
1004
-
1005
-		//error cause actually, maybe throw an exception in future.
1006
-		return [];
1007
-	}
1008
-
1009
-	/**
1010
-	 * executes an LDAP search, optimized for Users
1011
-	 *
1012
-	 * @param string $filter the LDAP filter for the search
1013
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1014
-	 * @param integer $limit
1015
-	 * @param integer $offset
1016
-	 * @return array with the search result
1017
-	 *
1018
-	 * Executes an LDAP search
1019
-	 * @throws ServerNotAvailableException
1020
-	 */
1021
-	public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1022
-		$result = [];
1023
-		foreach($this->connection->ldapBaseUsers as $base) {
1024
-			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1025
-		}
1026
-		return $result;
1027
-	}
1028
-
1029
-	/**
1030
-	 * @param string $filter
1031
-	 * @param string|string[] $attr
1032
-	 * @param int $limit
1033
-	 * @param int $offset
1034
-	 * @return false|int
1035
-	 * @throws ServerNotAvailableException
1036
-	 */
1037
-	public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1038
-		$result = false;
1039
-		foreach($this->connection->ldapBaseUsers as $base) {
1040
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1041
-			$result = is_int($count) ? (int)$result + $count : $result;
1042
-		}
1043
-		return $result;
1044
-	}
1045
-
1046
-	/**
1047
-	 * executes an LDAP search, optimized for Groups
1048
-	 *
1049
-	 * @param string $filter the LDAP filter for the search
1050
-	 * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1051
-	 * @param integer $limit
1052
-	 * @param integer $offset
1053
-	 * @return array with the search result
1054
-	 *
1055
-	 * Executes an LDAP search
1056
-	 * @throws ServerNotAvailableException
1057
-	 */
1058
-	public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1059
-		$result = [];
1060
-		foreach($this->connection->ldapBaseGroups as $base) {
1061
-			$result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1062
-		}
1063
-		return $result;
1064
-	}
1065
-
1066
-	/**
1067
-	 * returns the number of available groups
1068
-	 *
1069
-	 * @param string $filter the LDAP search filter
1070
-	 * @param string[] $attr optional
1071
-	 * @param int|null $limit
1072
-	 * @param int|null $offset
1073
-	 * @return int|bool
1074
-	 * @throws ServerNotAvailableException
1075
-	 */
1076
-	public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1077
-		$result = false;
1078
-		foreach($this->connection->ldapBaseGroups as $base) {
1079
-			$count = $this->count($filter, [$base], $attr, $limit, $offset);
1080
-			$result = is_int($count) ? (int)$result + $count : $result;
1081
-		}
1082
-		return $result;
1083
-	}
1084
-
1085
-	/**
1086
-	 * returns the number of available objects on the base DN
1087
-	 *
1088
-	 * @param int|null $limit
1089
-	 * @param int|null $offset
1090
-	 * @return int|bool
1091
-	 * @throws ServerNotAvailableException
1092
-	 */
1093
-	public function countObjects($limit = null, $offset = null) {
1094
-		$result = false;
1095
-		foreach($this->connection->ldapBase as $base) {
1096
-			$count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1097
-			$result = is_int($count) ? (int)$result + $count : $result;
1098
-		}
1099
-		return $result;
1100
-	}
1101
-
1102
-	/**
1103
-	 * Returns the LDAP handler
1104
-	 * @throws \OC\ServerNotAvailableException
1105
-	 */
1106
-
1107
-	/**
1108
-	 * @return mixed
1109
-	 * @throws \OC\ServerNotAvailableException
1110
-	 */
1111
-	private function invokeLDAPMethod() {
1112
-		$arguments = func_get_args();
1113
-		$command = array_shift($arguments);
1114
-		$cr = array_shift($arguments);
1115
-		if (!method_exists($this->ldap, $command)) {
1116
-			return null;
1117
-		}
1118
-		array_unshift($arguments, $cr);
1119
-		// php no longer supports call-time pass-by-reference
1120
-		// thus cannot support controlPagedResultResponse as the third argument
1121
-		// is a reference
1122
-		$doMethod = function () use ($command, &$arguments) {
1123
-			if ($command == 'controlPagedResultResponse') {
1124
-				throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1125
-			} else {
1126
-				return call_user_func_array([$this->ldap, $command], $arguments);
1127
-			}
1128
-		};
1129
-		try {
1130
-			$ret = $doMethod();
1131
-		} catch (ServerNotAvailableException $e) {
1132
-			/* Server connection lost, attempt to reestablish it
67
+    const UUID_ATTRIBUTES = ['entryuuid', 'nsuniqueid', 'objectguid', 'guid', 'ipauniqueid'];
68
+
69
+    /** @var \OCA\User_LDAP\Connection */
70
+    public $connection;
71
+    /** @var Manager */
72
+    public $userManager;
73
+    //never ever check this var directly, always use getPagedSearchResultState
74
+    protected $pagedSearchedSuccessful;
75
+
76
+    /**
77
+     * @var string[] $cookies an array of returned Paged Result cookies
78
+     */
79
+    protected $cookies = [];
80
+
81
+    /**
82
+     * @var string $lastCookie the last cookie returned from a Paged Results
83
+     * operation, defaults to an empty string
84
+     */
85
+    protected $lastCookie = '';
86
+
87
+    /**
88
+     * @var AbstractMapping $userMapper
89
+     */
90
+    protected $userMapper;
91
+
92
+    /**
93
+     * @var AbstractMapping $userMapper
94
+     */
95
+    protected $groupMapper;
96
+
97
+    /**
98
+     * @var \OCA\User_LDAP\Helper
99
+     */
100
+    private $helper;
101
+    /** @var IConfig */
102
+    private $config;
103
+    /** @var IUserManager */
104
+    private $ncUserManager;
105
+
106
+    public function __construct(
107
+        Connection $connection,
108
+        ILDAPWrapper $ldap,
109
+        Manager $userManager,
110
+        Helper $helper,
111
+        IConfig $config,
112
+        IUserManager $ncUserManager
113
+    ) {
114
+        parent::__construct($ldap);
115
+        $this->connection = $connection;
116
+        $this->userManager = $userManager;
117
+        $this->userManager->setLdapAccess($this);
118
+        $this->helper = $helper;
119
+        $this->config = $config;
120
+        $this->ncUserManager = $ncUserManager;
121
+    }
122
+
123
+    /**
124
+     * sets the User Mapper
125
+     * @param AbstractMapping $mapper
126
+     */
127
+    public function setUserMapper(AbstractMapping $mapper) {
128
+        $this->userMapper = $mapper;
129
+    }
130
+
131
+    /**
132
+     * returns the User Mapper
133
+     * @throws \Exception
134
+     * @return AbstractMapping
135
+     */
136
+    public function getUserMapper() {
137
+        if(is_null($this->userMapper)) {
138
+            throw new \Exception('UserMapper was not assigned to this Access instance.');
139
+        }
140
+        return $this->userMapper;
141
+    }
142
+
143
+    /**
144
+     * sets the Group Mapper
145
+     * @param AbstractMapping $mapper
146
+     */
147
+    public function setGroupMapper(AbstractMapping $mapper) {
148
+        $this->groupMapper = $mapper;
149
+    }
150
+
151
+    /**
152
+     * returns the Group Mapper
153
+     * @throws \Exception
154
+     * @return AbstractMapping
155
+     */
156
+    public function getGroupMapper() {
157
+        if(is_null($this->groupMapper)) {
158
+            throw new \Exception('GroupMapper was not assigned to this Access instance.');
159
+        }
160
+        return $this->groupMapper;
161
+    }
162
+
163
+    /**
164
+     * @return bool
165
+     */
166
+    private function checkConnection() {
167
+        return ($this->connection instanceof Connection);
168
+    }
169
+
170
+    /**
171
+     * returns the Connection instance
172
+     * @return \OCA\User_LDAP\Connection
173
+     */
174
+    public function getConnection() {
175
+        return $this->connection;
176
+    }
177
+
178
+    /**
179
+     * reads a given attribute for an LDAP record identified by a DN
180
+     *
181
+     * @param string $dn the record in question
182
+     * @param string $attr the attribute that shall be retrieved
183
+     *        if empty, just check the record's existence
184
+     * @param string $filter
185
+     * @return array|false an array of values on success or an empty
186
+     *          array if $attr is empty, false otherwise
187
+     * @throws ServerNotAvailableException
188
+     */
189
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*') {
190
+        if(!$this->checkConnection()) {
191
+            \OCP\Util::writeLog('user_ldap',
192
+                'No LDAP Connector assigned, access impossible for readAttribute.',
193
+                ILogger::WARN);
194
+            return false;
195
+        }
196
+        $cr = $this->connection->getConnectionResource();
197
+        if(!$this->ldap->isResource($cr)) {
198
+            //LDAP not available
199
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
200
+            return false;
201
+        }
202
+        //Cancel possibly running Paged Results operation, otherwise we run in
203
+        //LDAP protocol errors
204
+        $this->abandonPagedSearch();
205
+        // openLDAP requires that we init a new Paged Search. Not needed by AD,
206
+        // but does not hurt either.
207
+        $pagingSize = (int)$this->connection->ldapPagingSize;
208
+        // 0 won't result in replies, small numbers may leave out groups
209
+        // (cf. #12306), 500 is default for paging and should work everywhere.
210
+        $maxResults = $pagingSize > 20 ? $pagingSize : 500;
211
+        $attr = mb_strtolower($attr, 'UTF-8');
212
+        // the actual read attribute later may contain parameters on a ranged
213
+        // request, e.g. member;range=99-199. Depends on server reply.
214
+        $attrToRead = $attr;
215
+
216
+        $values = [];
217
+        $isRangeRequest = false;
218
+        do {
219
+            $result = $this->executeRead($cr, $dn, $attrToRead, $filter, $maxResults);
220
+            if(is_bool($result)) {
221
+                // when an exists request was run and it was successful, an empty
222
+                // array must be returned
223
+                return $result ? [] : false;
224
+            }
225
+
226
+            if (!$isRangeRequest) {
227
+                $values = $this->extractAttributeValuesFromResult($result, $attr);
228
+                if (!empty($values)) {
229
+                    return $values;
230
+                }
231
+            }
232
+
233
+            $isRangeRequest = false;
234
+            $result = $this->extractRangeData($result, $attr);
235
+            if (!empty($result)) {
236
+                $normalizedResult = $this->extractAttributeValuesFromResult(
237
+                    [ $attr => $result['values'] ],
238
+                    $attr
239
+                );
240
+                $values = array_merge($values, $normalizedResult);
241
+
242
+                if($result['rangeHigh'] === '*') {
243
+                    // when server replies with * as high range value, there are
244
+                    // no more results left
245
+                    return $values;
246
+                } else {
247
+                    $low  = $result['rangeHigh'] + 1;
248
+                    $attrToRead = $result['attributeName'] . ';range=' . $low . '-*';
249
+                    $isRangeRequest = true;
250
+                }
251
+            }
252
+        } while($isRangeRequest);
253
+
254
+        \OCP\Util::writeLog('user_ldap', 'Requested attribute '.$attr.' not found for '.$dn, ILogger::DEBUG);
255
+        return false;
256
+    }
257
+
258
+    /**
259
+     * Runs an read operation against LDAP
260
+     *
261
+     * @param resource $cr the LDAP connection
262
+     * @param string $dn
263
+     * @param string $attribute
264
+     * @param string $filter
265
+     * @param int $maxResults
266
+     * @return array|bool false if there was any error, true if an exists check
267
+     *                    was performed and the requested DN found, array with the
268
+     *                    returned data on a successful usual operation
269
+     * @throws ServerNotAvailableException
270
+     */
271
+    public function executeRead($cr, $dn, $attribute, $filter, $maxResults) {
272
+        $this->initPagedSearch($filter, [$dn], [$attribute], $maxResults, 0);
273
+        $dn = $this->helper->DNasBaseParameter($dn);
274
+        $rr = @$this->invokeLDAPMethod('read', $cr, $dn, $filter, [$attribute]);
275
+        if (!$this->ldap->isResource($rr)) {
276
+            if ($attribute !== '') {
277
+                //do not throw this message on userExists check, irritates
278
+                \OCP\Util::writeLog('user_ldap', 'readAttribute failed for DN ' . $dn, ILogger::DEBUG);
279
+            }
280
+            //in case an error occurs , e.g. object does not exist
281
+            return false;
282
+        }
283
+        if ($attribute === '' && ($filter === 'objectclass=*' || $this->invokeLDAPMethod('countEntries', $cr, $rr) === 1)) {
284
+            \OCP\Util::writeLog('user_ldap', 'readAttribute: ' . $dn . ' found', ILogger::DEBUG);
285
+            return true;
286
+        }
287
+        $er = $this->invokeLDAPMethod('firstEntry', $cr, $rr);
288
+        if (!$this->ldap->isResource($er)) {
289
+            //did not match the filter, return false
290
+            return false;
291
+        }
292
+        //LDAP attributes are not case sensitive
293
+        $result = \OCP\Util::mb_array_change_key_case(
294
+            $this->invokeLDAPMethod('getAttributes', $cr, $er), MB_CASE_LOWER, 'UTF-8');
295
+
296
+        return $result;
297
+    }
298
+
299
+    /**
300
+     * Normalizes a result grom getAttributes(), i.e. handles DNs and binary
301
+     * data if present.
302
+     *
303
+     * @param array $result from ILDAPWrapper::getAttributes()
304
+     * @param string $attribute the attribute name that was read
305
+     * @return string[]
306
+     */
307
+    public function extractAttributeValuesFromResult($result, $attribute) {
308
+        $values = [];
309
+        if(isset($result[$attribute]) && $result[$attribute]['count'] > 0) {
310
+            $lowercaseAttribute = strtolower($attribute);
311
+            for($i=0;$i<$result[$attribute]['count'];$i++) {
312
+                if($this->resemblesDN($attribute)) {
313
+                    $values[] = $this->helper->sanitizeDN($result[$attribute][$i]);
314
+                } elseif($lowercaseAttribute === 'objectguid' || $lowercaseAttribute === 'guid') {
315
+                    $values[] = $this->convertObjectGUID2Str($result[$attribute][$i]);
316
+                } else {
317
+                    $values[] = $result[$attribute][$i];
318
+                }
319
+            }
320
+        }
321
+        return $values;
322
+    }
323
+
324
+    /**
325
+     * Attempts to find ranged data in a getAttribute results and extracts the
326
+     * returned values as well as information on the range and full attribute
327
+     * name for further processing.
328
+     *
329
+     * @param array $result from ILDAPWrapper::getAttributes()
330
+     * @param string $attribute the attribute name that was read. Without ";range=…"
331
+     * @return array If a range was detected with keys 'values', 'attributeName',
332
+     *               'attributeFull' and 'rangeHigh', otherwise empty.
333
+     */
334
+    public function extractRangeData($result, $attribute) {
335
+        $keys = array_keys($result);
336
+        foreach($keys as $key) {
337
+            if($key !== $attribute && strpos($key, $attribute) === 0) {
338
+                $queryData = explode(';', $key);
339
+                if(strpos($queryData[1], 'range=') === 0) {
340
+                    $high = substr($queryData[1], 1 + strpos($queryData[1], '-'));
341
+                    $data = [
342
+                        'values' => $result[$key],
343
+                        'attributeName' => $queryData[0],
344
+                        'attributeFull' => $key,
345
+                        'rangeHigh' => $high,
346
+                    ];
347
+                    return $data;
348
+                }
349
+            }
350
+        }
351
+        return [];
352
+    }
353
+
354
+    /**
355
+     * Set password for an LDAP user identified by a DN
356
+     *
357
+     * @param string $userDN the user in question
358
+     * @param string $password the new password
359
+     * @return bool
360
+     * @throws HintException
361
+     * @throws \Exception
362
+     */
363
+    public function setPassword($userDN, $password) {
364
+        if((int)$this->connection->turnOnPasswordChange !== 1) {
365
+            throw new \Exception('LDAP password changes are disabled.');
366
+        }
367
+        $cr = $this->connection->getConnectionResource();
368
+        if(!$this->ldap->isResource($cr)) {
369
+            //LDAP not available
370
+            \OCP\Util::writeLog('user_ldap', 'LDAP resource not available.', ILogger::DEBUG);
371
+            return false;
372
+        }
373
+        try {
374
+            // try PASSWD extended operation first
375
+            return @$this->invokeLDAPMethod('exopPasswd', $cr, $userDN, '', $password) ||
376
+                        @$this->invokeLDAPMethod('modReplace', $cr, $userDN, $password);
377
+        } catch(ConstraintViolationException $e) {
378
+            throw new HintException('Password change rejected.', \OC::$server->getL10N('user_ldap')->t('Password change rejected. Hint: ').$e->getMessage(), $e->getCode());
379
+        }
380
+    }
381
+
382
+    /**
383
+     * checks whether the given attributes value is probably a DN
384
+     * @param string $attr the attribute in question
385
+     * @return boolean if so true, otherwise false
386
+     */
387
+    private function resemblesDN($attr) {
388
+        $resemblingAttributes = [
389
+            'dn',
390
+            'uniquemember',
391
+            'member',
392
+            // memberOf is an "operational" attribute, without a definition in any RFC
393
+            'memberof'
394
+        ];
395
+        return in_array($attr, $resemblingAttributes);
396
+    }
397
+
398
+    /**
399
+     * checks whether the given string is probably a DN
400
+     * @param string $string
401
+     * @return boolean
402
+     */
403
+    public function stringResemblesDN($string) {
404
+        $r = $this->ldap->explodeDN($string, 0);
405
+        // if exploding a DN succeeds and does not end up in
406
+        // an empty array except for $r[count] being 0.
407
+        return (is_array($r) && count($r) > 1);
408
+    }
409
+
410
+    /**
411
+     * returns a DN-string that is cleaned from not domain parts, e.g.
412
+     * cn=foo,cn=bar,dc=foobar,dc=server,dc=org
413
+     * becomes dc=foobar,dc=server,dc=org
414
+     * @param string $dn
415
+     * @return string
416
+     */
417
+    public function getDomainDNFromDN($dn) {
418
+        $allParts = $this->ldap->explodeDN($dn, 0);
419
+        if($allParts === false) {
420
+            //not a valid DN
421
+            return '';
422
+        }
423
+        $domainParts = [];
424
+        $dcFound = false;
425
+        foreach($allParts as $part) {
426
+            if(!$dcFound && strpos($part, 'dc=') === 0) {
427
+                $dcFound = true;
428
+            }
429
+            if($dcFound) {
430
+                $domainParts[] = $part;
431
+            }
432
+        }
433
+        return implode(',', $domainParts);
434
+    }
435
+
436
+    /**
437
+     * returns the LDAP DN for the given internal Nextcloud name of the group
438
+     * @param string $name the Nextcloud name in question
439
+     * @return string|false LDAP DN on success, otherwise false
440
+     */
441
+    public function groupname2dn($name) {
442
+        return $this->groupMapper->getDNByName($name);
443
+    }
444
+
445
+    /**
446
+     * returns the LDAP DN for the given internal Nextcloud name of the user
447
+     * @param string $name the Nextcloud name in question
448
+     * @return string|false with the LDAP DN on success, otherwise false
449
+     */
450
+    public function username2dn($name) {
451
+        $fdn = $this->userMapper->getDNByName($name);
452
+
453
+        //Check whether the DN belongs to the Base, to avoid issues on multi-
454
+        //server setups
455
+        if(is_string($fdn) && $this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
456
+            return $fdn;
457
+        }
458
+
459
+        return false;
460
+    }
461
+
462
+    /**
463
+     * returns the internal Nextcloud name for the given LDAP DN of the group, false on DN outside of search DN or failure
464
+     *
465
+     * @param string $fdn the dn of the group object
466
+     * @param string $ldapName optional, the display name of the object
467
+     * @return string|false with the name to use in Nextcloud, false on DN outside of search DN
468
+     * @throws \Exception
469
+     */
470
+    public function dn2groupname($fdn, $ldapName = null) {
471
+        //To avoid bypassing the base DN settings under certain circumstances
472
+        //with the group support, check whether the provided DN matches one of
473
+        //the given Bases
474
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseGroups)) {
475
+            return false;
476
+        }
477
+
478
+        return $this->dn2ocname($fdn, $ldapName, false);
479
+    }
480
+
481
+    /**
482
+     * accepts an array of group DNs and tests whether they match the user
483
+     * filter by doing read operations against the group entries. Returns an
484
+     * array of DNs that match the filter.
485
+     *
486
+     * @param string[] $groupDNs
487
+     * @return string[]
488
+     * @throws ServerNotAvailableException
489
+     */
490
+    public function groupsMatchFilter($groupDNs) {
491
+        $validGroupDNs = [];
492
+        foreach($groupDNs as $dn) {
493
+            $cacheKey = 'groupsMatchFilter-'.$dn;
494
+            $groupMatchFilter = $this->connection->getFromCache($cacheKey);
495
+            if(!is_null($groupMatchFilter)) {
496
+                if($groupMatchFilter) {
497
+                    $validGroupDNs[] = $dn;
498
+                }
499
+                continue;
500
+            }
501
+
502
+            // Check the base DN first. If this is not met already, we don't
503
+            // need to ask the server at all.
504
+            if(!$this->isDNPartOfBase($dn, $this->connection->ldapBaseGroups)) {
505
+                $this->connection->writeToCache($cacheKey, false);
506
+                continue;
507
+            }
508
+
509
+            $result = $this->readAttribute($dn, '', $this->connection->ldapGroupFilter);
510
+            if(is_array($result)) {
511
+                $this->connection->writeToCache($cacheKey, true);
512
+                $validGroupDNs[] = $dn;
513
+            } else {
514
+                $this->connection->writeToCache($cacheKey, false);
515
+            }
516
+
517
+        }
518
+        return $validGroupDNs;
519
+    }
520
+
521
+    /**
522
+     * returns the internal Nextcloud name for the given LDAP DN of the user, false on DN outside of search DN or failure
523
+     *
524
+     * @param string $dn the dn of the user object
525
+     * @param string $ldapName optional, the display name of the object
526
+     * @return string|false with with the name to use in Nextcloud
527
+     * @throws \Exception
528
+     */
529
+    public function dn2username($fdn, $ldapName = null) {
530
+        //To avoid bypassing the base DN settings under certain circumstances
531
+        //with the group support, check whether the provided DN matches one of
532
+        //the given Bases
533
+        if(!$this->isDNPartOfBase($fdn, $this->connection->ldapBaseUsers)) {
534
+            return false;
535
+        }
536
+
537
+        return $this->dn2ocname($fdn, $ldapName, true);
538
+    }
539
+
540
+    /**
541
+     * returns an internal Nextcloud name for the given LDAP DN, false on DN outside of search DN
542
+     *
543
+     * @param string $fdn the dn of the user object
544
+     * @param string|null $ldapName optional, the display name of the object
545
+     * @param bool $isUser optional, whether it is a user object (otherwise group assumed)
546
+     * @param bool|null $newlyMapped
547
+     * @param array|null $record
548
+     * @return false|string with with the name to use in Nextcloud
549
+     * @throws \Exception
550
+     */
551
+    public function dn2ocname($fdn, $ldapName = null, $isUser = true, &$newlyMapped = null, array $record = null) {
552
+        $newlyMapped = false;
553
+        if($isUser) {
554
+            $mapper = $this->getUserMapper();
555
+            $nameAttribute = $this->connection->ldapUserDisplayName;
556
+            $filter = $this->connection->ldapUserFilter;
557
+        } else {
558
+            $mapper = $this->getGroupMapper();
559
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
560
+            $filter = $this->connection->ldapGroupFilter;
561
+        }
562
+
563
+        //let's try to retrieve the Nextcloud name from the mappings table
564
+        $ncName = $mapper->getNameByDN($fdn);
565
+        if(is_string($ncName)) {
566
+            return $ncName;
567
+        }
568
+
569
+        //second try: get the UUID and check if it is known. Then, update the DN and return the name.
570
+        $uuid = $this->getUUID($fdn, $isUser, $record);
571
+        if(is_string($uuid)) {
572
+            $ncName = $mapper->getNameByUUID($uuid);
573
+            if(is_string($ncName)) {
574
+                $mapper->setDNbyUUID($fdn, $uuid);
575
+                return $ncName;
576
+            }
577
+        } else {
578
+            //If the UUID can't be detected something is foul.
579
+            \OCP\Util::writeLog('user_ldap', 'Cannot determine UUID for '.$fdn.'. Skipping.', ILogger::INFO);
580
+            return false;
581
+        }
582
+
583
+        if(is_null($ldapName)) {
584
+            $ldapName = $this->readAttribute($fdn, $nameAttribute, $filter);
585
+            if(!isset($ldapName[0]) && empty($ldapName[0])) {
586
+                \OCP\Util::writeLog('user_ldap', 'No or empty name for '.$fdn.' with filter '.$filter.'.', ILogger::INFO);
587
+                return false;
588
+            }
589
+            $ldapName = $ldapName[0];
590
+        }
591
+
592
+        if($isUser) {
593
+            $usernameAttribute = (string)$this->connection->ldapExpertUsernameAttr;
594
+            if ($usernameAttribute !== '') {
595
+                $username = $this->readAttribute($fdn, $usernameAttribute);
596
+                $username = $username[0];
597
+            } else {
598
+                $username = $uuid;
599
+            }
600
+            try {
601
+                $intName = $this->sanitizeUsername($username);
602
+            } catch (\InvalidArgumentException $e) {
603
+                \OC::$server->getLogger()->logException($e, [
604
+                    'app' => 'user_ldap',
605
+                    'level' => ILogger::WARN,
606
+                ]);
607
+                // we don't attempt to set a username here. We can go for
608
+                // for an alternative 4 digit random number as we would append
609
+                // otherwise, however it's likely not enough space in bigger
610
+                // setups, and most importantly: this is not intended.
611
+                return false;
612
+            }
613
+        } else {
614
+            $intName = $ldapName;
615
+        }
616
+
617
+        //a new user/group! Add it only if it doesn't conflict with other backend's users or existing groups
618
+        //disabling Cache is required to avoid that the new user is cached as not-existing in fooExists check
619
+        //NOTE: mind, disabling cache affects only this instance! Using it
620
+        // outside of core user management will still cache the user as non-existing.
621
+        $originalTTL = $this->connection->ldapCacheTTL;
622
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
623
+        if($intName !== ''
624
+            && (($isUser && !$this->ncUserManager->userExists($intName))
625
+                || (!$isUser && !\OC::$server->getGroupManager()->groupExists($intName))
626
+            )
627
+        ) {
628
+            $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
629
+            $newlyMapped = $this->mapAndAnnounceIfApplicable($mapper, $fdn, $intName, $uuid, $isUser);
630
+            if($newlyMapped) {
631
+                return $intName;
632
+            }
633
+        }
634
+
635
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
636
+        $altName = $this->createAltInternalOwnCloudName($intName, $isUser);
637
+        if (is_string($altName)) {
638
+            if($this->mapAndAnnounceIfApplicable($mapper, $fdn, $altName, $uuid, $isUser)) {
639
+                $newlyMapped = true;
640
+                return $altName;
641
+            }
642
+        }
643
+
644
+        //if everything else did not help..
645
+        \OCP\Util::writeLog('user_ldap', 'Could not create unique name for '.$fdn.'.', ILogger::INFO);
646
+        return false;
647
+    }
648
+
649
+    public function mapAndAnnounceIfApplicable(
650
+        AbstractMapping $mapper,
651
+        string $fdn,
652
+        string $name,
653
+        string $uuid,
654
+        bool $isUser
655
+    ) :bool {
656
+        if($mapper->map($fdn, $name, $uuid)) {
657
+            if ($this->ncUserManager instanceof PublicEmitter && $isUser) {
658
+                $this->cacheUserExists($name);
659
+                $this->ncUserManager->emit('\OC\User', 'assignedUserId', [$name]);
660
+            } elseif (!$isUser) {
661
+                $this->cacheGroupExists($name);
662
+            }
663
+            return true;
664
+        }
665
+        return false;
666
+    }
667
+
668
+    /**
669
+     * gives back the user names as they are used ownClod internally
670
+     *
671
+     * @param array $ldapUsers as returned by fetchList()
672
+     * @return array an array with the user names to use in Nextcloud
673
+     *
674
+     * gives back the user names as they are used ownClod internally
675
+     * @throws \Exception
676
+     */
677
+    public function nextcloudUserNames($ldapUsers) {
678
+        return $this->ldap2NextcloudNames($ldapUsers, true);
679
+    }
680
+
681
+    /**
682
+     * gives back the group names as they are used ownClod internally
683
+     *
684
+     * @param array $ldapGroups as returned by fetchList()
685
+     * @return array an array with the group names to use in Nextcloud
686
+     *
687
+     * gives back the group names as they are used ownClod internally
688
+     * @throws \Exception
689
+     */
690
+    public function nextcloudGroupNames($ldapGroups) {
691
+        return $this->ldap2NextcloudNames($ldapGroups, false);
692
+    }
693
+
694
+    /**
695
+     * @param array $ldapObjects as returned by fetchList()
696
+     * @param bool $isUsers
697
+     * @return array
698
+     * @throws \Exception
699
+     */
700
+    private function ldap2NextcloudNames($ldapObjects, $isUsers) {
701
+        if($isUsers) {
702
+            $nameAttribute = $this->connection->ldapUserDisplayName;
703
+            $sndAttribute  = $this->connection->ldapUserDisplayName2;
704
+        } else {
705
+            $nameAttribute = $this->connection->ldapGroupDisplayName;
706
+        }
707
+        $nextcloudNames = [];
708
+
709
+        foreach($ldapObjects as $ldapObject) {
710
+            $nameByLDAP = null;
711
+            if(isset($ldapObject[$nameAttribute])
712
+                && is_array($ldapObject[$nameAttribute])
713
+                && isset($ldapObject[$nameAttribute][0])
714
+            ) {
715
+                // might be set, but not necessarily. if so, we use it.
716
+                $nameByLDAP = $ldapObject[$nameAttribute][0];
717
+            }
718
+
719
+            $ncName = $this->dn2ocname($ldapObject['dn'][0], $nameByLDAP, $isUsers);
720
+            if($ncName) {
721
+                $nextcloudNames[] = $ncName;
722
+                if($isUsers) {
723
+                    $this->updateUserState($ncName);
724
+                    //cache the user names so it does not need to be retrieved
725
+                    //again later (e.g. sharing dialogue).
726
+                    if(is_null($nameByLDAP)) {
727
+                        continue;
728
+                    }
729
+                    $sndName = isset($ldapObject[$sndAttribute][0])
730
+                        ? $ldapObject[$sndAttribute][0] : '';
731
+                    $this->cacheUserDisplayName($ncName, $nameByLDAP, $sndName);
732
+                } else if($nameByLDAP !== null) {
733
+                    $this->cacheGroupDisplayName($ncName, $nameByLDAP);
734
+                }
735
+            }
736
+        }
737
+        return $nextcloudNames;
738
+    }
739
+
740
+    /**
741
+     * removes the deleted-flag of a user if it was set
742
+     *
743
+     * @param string $ncname
744
+     * @throws \Exception
745
+     */
746
+    public function updateUserState($ncname) {
747
+        $user = $this->userManager->get($ncname);
748
+        if($user instanceof OfflineUser) {
749
+            $user->unmark();
750
+        }
751
+    }
752
+
753
+    /**
754
+     * caches the user display name
755
+     * @param string $ocName the internal Nextcloud username
756
+     * @param string|false $home the home directory path
757
+     */
758
+    public function cacheUserHome($ocName, $home) {
759
+        $cacheKey = 'getHome'.$ocName;
760
+        $this->connection->writeToCache($cacheKey, $home);
761
+    }
762
+
763
+    /**
764
+     * caches a user as existing
765
+     * @param string $ocName the internal Nextcloud username
766
+     */
767
+    public function cacheUserExists($ocName) {
768
+        $this->connection->writeToCache('userExists'.$ocName, true);
769
+    }
770
+
771
+    /**
772
+     * caches a group as existing
773
+     */
774
+    public function cacheGroupExists(string $gid): void {
775
+        $this->connection->writeToCache('groupExists'.$gid, true);
776
+    }
777
+
778
+    /**
779
+     * caches the user display name
780
+     *
781
+     * @param string $ocName the internal Nextcloud username
782
+     * @param string $displayName the display name
783
+     * @param string $displayName2 the second display name
784
+     * @throws \Exception
785
+     */
786
+    public function cacheUserDisplayName($ocName, $displayName, $displayName2 = '') {
787
+        $user = $this->userManager->get($ocName);
788
+        if($user === null) {
789
+            return;
790
+        }
791
+        $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
792
+        $cacheKeyTrunk = 'getDisplayName';
793
+        $this->connection->writeToCache($cacheKeyTrunk.$ocName, $displayName);
794
+    }
795
+
796
+    public function cacheGroupDisplayName(string $ncName, string $displayName): void {
797
+        $cacheKey = 'group_getDisplayName' . $ncName;
798
+        $this->connection->writeToCache($cacheKey, $displayName);
799
+    }
800
+
801
+    /**
802
+     * creates a unique name for internal Nextcloud use for users. Don't call it directly.
803
+     * @param string $name the display name of the object
804
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
805
+     *
806
+     * Instead of using this method directly, call
807
+     * createAltInternalOwnCloudName($name, true)
808
+     */
809
+    private function _createAltInternalOwnCloudNameForUsers($name) {
810
+        $attempts = 0;
811
+        //while loop is just a precaution. If a name is not generated within
812
+        //20 attempts, something else is very wrong. Avoids infinite loop.
813
+        while($attempts < 20){
814
+            $altName = $name . '_' . rand(1000,9999);
815
+            if(!$this->ncUserManager->userExists($altName)) {
816
+                return $altName;
817
+            }
818
+            $attempts++;
819
+        }
820
+        return false;
821
+    }
822
+
823
+    /**
824
+     * creates a unique name for internal Nextcloud use for groups. Don't call it directly.
825
+     * @param string $name the display name of the object
826
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful.
827
+     *
828
+     * Instead of using this method directly, call
829
+     * createAltInternalOwnCloudName($name, false)
830
+     *
831
+     * Group names are also used as display names, so we do a sequential
832
+     * numbering, e.g. Developers_42 when there are 41 other groups called
833
+     * "Developers"
834
+     */
835
+    private function _createAltInternalOwnCloudNameForGroups($name) {
836
+        $usedNames = $this->groupMapper->getNamesBySearch($name, "", '_%');
837
+        if(!$usedNames || count($usedNames) === 0) {
838
+            $lastNo = 1; //will become name_2
839
+        } else {
840
+            natsort($usedNames);
841
+            $lastName = array_pop($usedNames);
842
+            $lastNo = (int)substr($lastName, strrpos($lastName, '_') + 1);
843
+        }
844
+        $altName = $name.'_'. (string)($lastNo+1);
845
+        unset($usedNames);
846
+
847
+        $attempts = 1;
848
+        while($attempts < 21){
849
+            // Check to be really sure it is unique
850
+            // while loop is just a precaution. If a name is not generated within
851
+            // 20 attempts, something else is very wrong. Avoids infinite loop.
852
+            if(!\OC::$server->getGroupManager()->groupExists($altName)) {
853
+                return $altName;
854
+            }
855
+            $altName = $name . '_' . ($lastNo + $attempts);
856
+            $attempts++;
857
+        }
858
+        return false;
859
+    }
860
+
861
+    /**
862
+     * creates a unique name for internal Nextcloud use.
863
+     * @param string $name the display name of the object
864
+     * @param boolean $isUser whether name should be created for a user (true) or a group (false)
865
+     * @return string|false with with the name to use in Nextcloud or false if unsuccessful
866
+     */
867
+    private function createAltInternalOwnCloudName($name, $isUser) {
868
+        $originalTTL = $this->connection->ldapCacheTTL;
869
+        $this->connection->setConfiguration(['ldapCacheTTL' => 0]);
870
+        if($isUser) {
871
+            $altName = $this->_createAltInternalOwnCloudNameForUsers($name);
872
+        } else {
873
+            $altName = $this->_createAltInternalOwnCloudNameForGroups($name);
874
+        }
875
+        $this->connection->setConfiguration(['ldapCacheTTL' => $originalTTL]);
876
+
877
+        return $altName;
878
+    }
879
+
880
+    /**
881
+     * fetches a list of users according to a provided loginName and utilizing
882
+     * the login filter.
883
+     *
884
+     * @param string $loginName
885
+     * @param array $attributes optional, list of attributes to read
886
+     * @return array
887
+     */
888
+    public function fetchUsersByLoginName($loginName, $attributes = ['dn']) {
889
+        $loginName = $this->escapeFilterPart($loginName);
890
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
891
+        return $this->fetchListOfUsers($filter, $attributes);
892
+    }
893
+
894
+    /**
895
+     * counts the number of users according to a provided loginName and
896
+     * utilizing the login filter.
897
+     *
898
+     * @param string $loginName
899
+     * @return int
900
+     */
901
+    public function countUsersByLoginName($loginName) {
902
+        $loginName = $this->escapeFilterPart($loginName);
903
+        $filter = str_replace('%uid', $loginName, $this->connection->ldapLoginFilter);
904
+        return $this->countUsers($filter);
905
+    }
906
+
907
+    /**
908
+     * @param string $filter
909
+     * @param string|string[] $attr
910
+     * @param int $limit
911
+     * @param int $offset
912
+     * @param bool $forceApplyAttributes
913
+     * @return array
914
+     * @throws \Exception
915
+     */
916
+    public function fetchListOfUsers($filter, $attr, $limit = null, $offset = null, $forceApplyAttributes = false) {
917
+        $ldapRecords = $this->searchUsers($filter, $attr, $limit, $offset);
918
+        $recordsToUpdate = $ldapRecords;
919
+        if(!$forceApplyAttributes) {
920
+            $isBackgroundJobModeAjax = $this->config
921
+                    ->getAppValue('core', 'backgroundjobs_mode', 'ajax') === 'ajax';
922
+            $recordsToUpdate = array_filter($ldapRecords, function ($record) use ($isBackgroundJobModeAjax) {
923
+                $newlyMapped = false;
924
+                $uid = $this->dn2ocname($record['dn'][0], null, true, $newlyMapped, $record);
925
+                if(is_string($uid)) {
926
+                    $this->cacheUserExists($uid);
927
+                }
928
+                return ($uid !== false) && ($newlyMapped || $isBackgroundJobModeAjax);
929
+            });
930
+        }
931
+        $this->batchApplyUserAttributes($recordsToUpdate);
932
+        return $this->fetchList($ldapRecords, $this->manyAttributes($attr));
933
+    }
934
+
935
+    /**
936
+     * provided with an array of LDAP user records the method will fetch the
937
+     * user object and requests it to process the freshly fetched attributes and
938
+     * and their values
939
+     *
940
+     * @param array $ldapRecords
941
+     * @throws \Exception
942
+     */
943
+    public function batchApplyUserAttributes(array $ldapRecords) {
944
+        $displayNameAttribute = strtolower($this->connection->ldapUserDisplayName);
945
+        foreach($ldapRecords as $userRecord) {
946
+            if(!isset($userRecord[$displayNameAttribute])) {
947
+                // displayName is obligatory
948
+                continue;
949
+            }
950
+            $ocName  = $this->dn2ocname($userRecord['dn'][0], null, true);
951
+            if($ocName === false) {
952
+                continue;
953
+            }
954
+            $this->updateUserState($ocName);
955
+            $user = $this->userManager->get($ocName);
956
+            if ($user !== null) {
957
+                $user->processAttributes($userRecord);
958
+            } else {
959
+                \OC::$server->getLogger()->debug(
960
+                    "The ldap user manager returned null for $ocName",
961
+                    ['app'=>'user_ldap']
962
+                );
963
+            }
964
+        }
965
+    }
966
+
967
+    /**
968
+     * @param string $filter
969
+     * @param string|string[] $attr
970
+     * @param int $limit
971
+     * @param int $offset
972
+     * @return array
973
+     */
974
+    public function fetchListOfGroups($filter, $attr, $limit = null, $offset = null) {
975
+        $groupRecords = $this->searchGroups($filter, $attr, $limit, $offset);
976
+        array_walk($groupRecords, function ($record) {
977
+            $newlyMapped = false;
978
+            $gid = $this->dn2ocname($record['dn'][0], null, false, $newlyMapped, $record);
979
+            if(!$newlyMapped && is_string($gid)) {
980
+                $this->cacheGroupExists($gid);
981
+            }
982
+        });
983
+        return $this->fetchList($groupRecords, $this->manyAttributes($attr));
984
+    }
985
+
986
+    /**
987
+     * @param array $list
988
+     * @param bool $manyAttributes
989
+     * @return array
990
+     */
991
+    private function fetchList($list, $manyAttributes) {
992
+        if(is_array($list)) {
993
+            if($manyAttributes) {
994
+                return $list;
995
+            } else {
996
+                $list = array_reduce($list, function ($carry, $item) {
997
+                    $attribute = array_keys($item)[0];
998
+                    $carry[] = $item[$attribute][0];
999
+                    return $carry;
1000
+                }, []);
1001
+                return array_unique($list, SORT_LOCALE_STRING);
1002
+            }
1003
+        }
1004
+
1005
+        //error cause actually, maybe throw an exception in future.
1006
+        return [];
1007
+    }
1008
+
1009
+    /**
1010
+     * executes an LDAP search, optimized for Users
1011
+     *
1012
+     * @param string $filter the LDAP filter for the search
1013
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1014
+     * @param integer $limit
1015
+     * @param integer $offset
1016
+     * @return array with the search result
1017
+     *
1018
+     * Executes an LDAP search
1019
+     * @throws ServerNotAvailableException
1020
+     */
1021
+    public function searchUsers($filter, $attr = null, $limit = null, $offset = null) {
1022
+        $result = [];
1023
+        foreach($this->connection->ldapBaseUsers as $base) {
1024
+            $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1025
+        }
1026
+        return $result;
1027
+    }
1028
+
1029
+    /**
1030
+     * @param string $filter
1031
+     * @param string|string[] $attr
1032
+     * @param int $limit
1033
+     * @param int $offset
1034
+     * @return false|int
1035
+     * @throws ServerNotAvailableException
1036
+     */
1037
+    public function countUsers($filter, $attr = ['dn'], $limit = null, $offset = null) {
1038
+        $result = false;
1039
+        foreach($this->connection->ldapBaseUsers as $base) {
1040
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1041
+            $result = is_int($count) ? (int)$result + $count : $result;
1042
+        }
1043
+        return $result;
1044
+    }
1045
+
1046
+    /**
1047
+     * executes an LDAP search, optimized for Groups
1048
+     *
1049
+     * @param string $filter the LDAP filter for the search
1050
+     * @param string|string[] $attr optional, when a certain attribute shall be filtered out
1051
+     * @param integer $limit
1052
+     * @param integer $offset
1053
+     * @return array with the search result
1054
+     *
1055
+     * Executes an LDAP search
1056
+     * @throws ServerNotAvailableException
1057
+     */
1058
+    public function searchGroups($filter, $attr = null, $limit = null, $offset = null) {
1059
+        $result = [];
1060
+        foreach($this->connection->ldapBaseGroups as $base) {
1061
+            $result = array_merge($result, $this->search($filter, [$base], $attr, $limit, $offset));
1062
+        }
1063
+        return $result;
1064
+    }
1065
+
1066
+    /**
1067
+     * returns the number of available groups
1068
+     *
1069
+     * @param string $filter the LDAP search filter
1070
+     * @param string[] $attr optional
1071
+     * @param int|null $limit
1072
+     * @param int|null $offset
1073
+     * @return int|bool
1074
+     * @throws ServerNotAvailableException
1075
+     */
1076
+    public function countGroups($filter, $attr = ['dn'], $limit = null, $offset = null) {
1077
+        $result = false;
1078
+        foreach($this->connection->ldapBaseGroups as $base) {
1079
+            $count = $this->count($filter, [$base], $attr, $limit, $offset);
1080
+            $result = is_int($count) ? (int)$result + $count : $result;
1081
+        }
1082
+        return $result;
1083
+    }
1084
+
1085
+    /**
1086
+     * returns the number of available objects on the base DN
1087
+     *
1088
+     * @param int|null $limit
1089
+     * @param int|null $offset
1090
+     * @return int|bool
1091
+     * @throws ServerNotAvailableException
1092
+     */
1093
+    public function countObjects($limit = null, $offset = null) {
1094
+        $result = false;
1095
+        foreach($this->connection->ldapBase as $base) {
1096
+            $count = $this->count('objectclass=*', [$base], ['dn'], $limit, $offset);
1097
+            $result = is_int($count) ? (int)$result + $count : $result;
1098
+        }
1099
+        return $result;
1100
+    }
1101
+
1102
+    /**
1103
+     * Returns the LDAP handler
1104
+     * @throws \OC\ServerNotAvailableException
1105
+     */
1106
+
1107
+    /**
1108
+     * @return mixed
1109
+     * @throws \OC\ServerNotAvailableException
1110
+     */
1111
+    private function invokeLDAPMethod() {
1112
+        $arguments = func_get_args();
1113
+        $command = array_shift($arguments);
1114
+        $cr = array_shift($arguments);
1115
+        if (!method_exists($this->ldap, $command)) {
1116
+            return null;
1117
+        }
1118
+        array_unshift($arguments, $cr);
1119
+        // php no longer supports call-time pass-by-reference
1120
+        // thus cannot support controlPagedResultResponse as the third argument
1121
+        // is a reference
1122
+        $doMethod = function () use ($command, &$arguments) {
1123
+            if ($command == 'controlPagedResultResponse') {
1124
+                throw new \InvalidArgumentException('Invoker does not support controlPagedResultResponse, call LDAP Wrapper directly instead.');
1125
+            } else {
1126
+                return call_user_func_array([$this->ldap, $command], $arguments);
1127
+            }
1128
+        };
1129
+        try {
1130
+            $ret = $doMethod();
1131
+        } catch (ServerNotAvailableException $e) {
1132
+            /* Server connection lost, attempt to reestablish it
1133 1133
 			 * Maybe implement exponential backoff?
1134 1134
 			 * This was enough to get solr indexer working which has large delays between LDAP fetches.
1135 1135
 			 */
1136
-			\OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1137
-			$this->connection->resetConnectionResource();
1138
-			$cr = $this->connection->getConnectionResource();
1139
-
1140
-			if(!$this->ldap->isResource($cr)) {
1141
-				// Seems like we didn't find any resource.
1142
-				\OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1143
-				throw $e;
1144
-			}
1145
-
1146
-			$arguments[0] = array_pad([], count($arguments[0]), $cr);
1147
-			$ret = $doMethod();
1148
-		}
1149
-		return $ret;
1150
-	}
1151
-
1152
-	/**
1153
-	 * retrieved. Results will according to the order in the array.
1154
-	 *
1155
-	 * @param $filter
1156
-	 * @param $base
1157
-	 * @param string[]|string|null $attr
1158
-	 * @param int $limit optional, maximum results to be counted
1159
-	 * @param int $offset optional, a starting point
1160
-	 * @return array|false array with the search result as first value and pagedSearchOK as
1161
-	 * second | false if not successful
1162
-	 * @throws ServerNotAvailableException
1163
-	 */
1164
-	private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1165
-		if(!is_null($attr) && !is_array($attr)) {
1166
-			$attr = [mb_strtolower($attr, 'UTF-8')];
1167
-		}
1168
-
1169
-		// See if we have a resource, in case not cancel with message
1170
-		$cr = $this->connection->getConnectionResource();
1171
-		if(!$this->ldap->isResource($cr)) {
1172
-			// Seems like we didn't find any resource.
1173
-			// Return an empty array just like before.
1174
-			\OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1175
-			return false;
1176
-		}
1177
-
1178
-		//check whether paged search should be attempted
1179
-		$pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1180
-
1181
-		$linkResources = array_pad([], count($base), $cr);
1182
-		$sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1183
-		// cannot use $cr anymore, might have changed in the previous call!
1184
-		$error = $this->ldap->errno($this->connection->getConnectionResource());
1185
-		if(!is_array($sr) || $error !== 0) {
1186
-			\OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1187
-			return false;
1188
-		}
1189
-
1190
-		return [$sr, $pagedSearchOK];
1191
-	}
1192
-
1193
-	/**
1194
-	 * processes an LDAP paged search operation
1195
-	 *
1196
-	 * @param array $sr the array containing the LDAP search resources
1197
-	 * @param string $filter the LDAP filter for the search
1198
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1199
-	 * @param int $iFoundItems number of results in the single search operation
1200
-	 * @param int $limit maximum results to be counted
1201
-	 * @param int $offset a starting point
1202
-	 * @param bool $pagedSearchOK whether a paged search has been executed
1203
-	 * @param bool $skipHandling required for paged search when cookies to
1204
-	 * prior results need to be gained
1205
-	 * @return bool cookie validity, true if we have more pages, false otherwise.
1206
-	 * @throws ServerNotAvailableException
1207
-	 */
1208
-	private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1209
-		$cookie = null;
1210
-		if($pagedSearchOK) {
1211
-			$cr = $this->connection->getConnectionResource();
1212
-			foreach($sr as $key => $res) {
1213
-				if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1214
-					$this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1215
-				}
1216
-			}
1217
-
1218
-			//browsing through prior pages to get the cookie for the new one
1219
-			if($skipHandling) {
1220
-				return false;
1221
-			}
1222
-			// if count is bigger, then the server does not support
1223
-			// paged search. Instead, he did a normal search. We set a
1224
-			// flag here, so the callee knows how to deal with it.
1225
-			if($iFoundItems <= $limit) {
1226
-				$this->pagedSearchedSuccessful = true;
1227
-			}
1228
-		} else {
1229
-			if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1230
-				\OC::$server->getLogger()->debug(
1231
-					'Paged search was not available',
1232
-					[ 'app' => 'user_ldap' ]
1233
-				);
1234
-			}
1235
-		}
1236
-		/* ++ Fixing RHDS searches with pages with zero results ++
1136
+            \OCP\Util::writeLog('user_ldap', "Connection lost on $command, attempting to reestablish.", ILogger::DEBUG);
1137
+            $this->connection->resetConnectionResource();
1138
+            $cr = $this->connection->getConnectionResource();
1139
+
1140
+            if(!$this->ldap->isResource($cr)) {
1141
+                // Seems like we didn't find any resource.
1142
+                \OCP\Util::writeLog('user_ldap', "Could not $command, because resource is missing.", ILogger::DEBUG);
1143
+                throw $e;
1144
+            }
1145
+
1146
+            $arguments[0] = array_pad([], count($arguments[0]), $cr);
1147
+            $ret = $doMethod();
1148
+        }
1149
+        return $ret;
1150
+    }
1151
+
1152
+    /**
1153
+     * retrieved. Results will according to the order in the array.
1154
+     *
1155
+     * @param $filter
1156
+     * @param $base
1157
+     * @param string[]|string|null $attr
1158
+     * @param int $limit optional, maximum results to be counted
1159
+     * @param int $offset optional, a starting point
1160
+     * @return array|false array with the search result as first value and pagedSearchOK as
1161
+     * second | false if not successful
1162
+     * @throws ServerNotAvailableException
1163
+     */
1164
+    private function executeSearch($filter, $base, &$attr = null, $limit = null, $offset = null) {
1165
+        if(!is_null($attr) && !is_array($attr)) {
1166
+            $attr = [mb_strtolower($attr, 'UTF-8')];
1167
+        }
1168
+
1169
+        // See if we have a resource, in case not cancel with message
1170
+        $cr = $this->connection->getConnectionResource();
1171
+        if(!$this->ldap->isResource($cr)) {
1172
+            // Seems like we didn't find any resource.
1173
+            // Return an empty array just like before.
1174
+            \OCP\Util::writeLog('user_ldap', 'Could not search, because resource is missing.', ILogger::DEBUG);
1175
+            return false;
1176
+        }
1177
+
1178
+        //check whether paged search should be attempted
1179
+        $pagedSearchOK = $this->initPagedSearch($filter, $base, $attr, (int)$limit, $offset);
1180
+
1181
+        $linkResources = array_pad([], count($base), $cr);
1182
+        $sr = $this->invokeLDAPMethod('search', $linkResources, $base, $filter, $attr);
1183
+        // cannot use $cr anymore, might have changed in the previous call!
1184
+        $error = $this->ldap->errno($this->connection->getConnectionResource());
1185
+        if(!is_array($sr) || $error !== 0) {
1186
+            \OCP\Util::writeLog('user_ldap', 'Attempt for Paging?  '.print_r($pagedSearchOK, true), ILogger::ERROR);
1187
+            return false;
1188
+        }
1189
+
1190
+        return [$sr, $pagedSearchOK];
1191
+    }
1192
+
1193
+    /**
1194
+     * processes an LDAP paged search operation
1195
+     *
1196
+     * @param array $sr the array containing the LDAP search resources
1197
+     * @param string $filter the LDAP filter for the search
1198
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1199
+     * @param int $iFoundItems number of results in the single search operation
1200
+     * @param int $limit maximum results to be counted
1201
+     * @param int $offset a starting point
1202
+     * @param bool $pagedSearchOK whether a paged search has been executed
1203
+     * @param bool $skipHandling required for paged search when cookies to
1204
+     * prior results need to be gained
1205
+     * @return bool cookie validity, true if we have more pages, false otherwise.
1206
+     * @throws ServerNotAvailableException
1207
+     */
1208
+    private function processPagedSearchStatus($sr, $filter, $base, $iFoundItems, $limit, $offset, $pagedSearchOK, $skipHandling) {
1209
+        $cookie = null;
1210
+        if($pagedSearchOK) {
1211
+            $cr = $this->connection->getConnectionResource();
1212
+            foreach($sr as $key => $res) {
1213
+                if($this->ldap->controlPagedResultResponse($cr, $res, $cookie)) {
1214
+                    $this->setPagedResultCookie($base[$key], $filter, $limit, $offset, $cookie);
1215
+                }
1216
+            }
1217
+
1218
+            //browsing through prior pages to get the cookie for the new one
1219
+            if($skipHandling) {
1220
+                return false;
1221
+            }
1222
+            // if count is bigger, then the server does not support
1223
+            // paged search. Instead, he did a normal search. We set a
1224
+            // flag here, so the callee knows how to deal with it.
1225
+            if($iFoundItems <= $limit) {
1226
+                $this->pagedSearchedSuccessful = true;
1227
+            }
1228
+        } else {
1229
+            if(!is_null($limit) && (int)$this->connection->ldapPagingSize !== 0) {
1230
+                \OC::$server->getLogger()->debug(
1231
+                    'Paged search was not available',
1232
+                    [ 'app' => 'user_ldap' ]
1233
+                );
1234
+            }
1235
+        }
1236
+        /* ++ Fixing RHDS searches with pages with zero results ++
1237 1237
 		 * Return cookie status. If we don't have more pages, with RHDS
1238 1238
 		 * cookie is null, with openldap cookie is an empty string and
1239 1239
 		 * to 386ds '0' is a valid cookie. Even if $iFoundItems == 0
1240 1240
 		 */
1241
-		return !empty($cookie) || $cookie === '0';
1242
-	}
1243
-
1244
-	/**
1245
-	 * executes an LDAP search, but counts the results only
1246
-	 *
1247
-	 * @param string $filter the LDAP filter for the search
1248
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1249
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1250
-	 * retrieved. Results will according to the order in the array.
1251
-	 * @param int $limit optional, maximum results to be counted
1252
-	 * @param int $offset optional, a starting point
1253
-	 * @param bool $skipHandling indicates whether the pages search operation is
1254
-	 * completed
1255
-	 * @return int|false Integer or false if the search could not be initialized
1256
-	 * @throws ServerNotAvailableException
1257
-	 */
1258
-	private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1259
-		\OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1260
-
1261
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1262
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1263
-			$limitPerPage = $limit;
1264
-		}
1265
-
1266
-		$counter = 0;
1267
-		$count = null;
1268
-		$this->connection->getConnectionResource();
1269
-
1270
-		do {
1271
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1272
-			if($search === false) {
1273
-				return $counter > 0 ? $counter : false;
1274
-			}
1275
-			list($sr, $pagedSearchOK) = $search;
1276
-
1277
-			/* ++ Fixing RHDS searches with pages with zero results ++
1241
+        return !empty($cookie) || $cookie === '0';
1242
+    }
1243
+
1244
+    /**
1245
+     * executes an LDAP search, but counts the results only
1246
+     *
1247
+     * @param string $filter the LDAP filter for the search
1248
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1249
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1250
+     * retrieved. Results will according to the order in the array.
1251
+     * @param int $limit optional, maximum results to be counted
1252
+     * @param int $offset optional, a starting point
1253
+     * @param bool $skipHandling indicates whether the pages search operation is
1254
+     * completed
1255
+     * @return int|false Integer or false if the search could not be initialized
1256
+     * @throws ServerNotAvailableException
1257
+     */
1258
+    private function count($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1259
+        \OCP\Util::writeLog('user_ldap', 'Count filter:  '.print_r($filter, true), ILogger::DEBUG);
1260
+
1261
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1262
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1263
+            $limitPerPage = $limit;
1264
+        }
1265
+
1266
+        $counter = 0;
1267
+        $count = null;
1268
+        $this->connection->getConnectionResource();
1269
+
1270
+        do {
1271
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1272
+            if($search === false) {
1273
+                return $counter > 0 ? $counter : false;
1274
+            }
1275
+            list($sr, $pagedSearchOK) = $search;
1276
+
1277
+            /* ++ Fixing RHDS searches with pages with zero results ++
1278 1278
 			 * countEntriesInSearchResults() method signature changed
1279 1279
 			 * by removing $limit and &$hasHitLimit parameters
1280 1280
 			 */
1281
-			$count = $this->countEntriesInSearchResults($sr);
1282
-			$counter += $count;
1281
+            $count = $this->countEntriesInSearchResults($sr);
1282
+            $counter += $count;
1283 1283
 
1284
-			$hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1285
-										$offset, $pagedSearchOK, $skipHandling);
1286
-			$offset += $limitPerPage;
1287
-			/* ++ Fixing RHDS searches with pages with zero results ++
1284
+            $hasMorePages = $this->processPagedSearchStatus($sr, $filter, $base, $count, $limitPerPage,
1285
+                                        $offset, $pagedSearchOK, $skipHandling);
1286
+            $offset += $limitPerPage;
1287
+            /* ++ Fixing RHDS searches with pages with zero results ++
1288 1288
 			 * Continue now depends on $hasMorePages value
1289 1289
 			 */
1290
-			$continue = $pagedSearchOK && $hasMorePages;
1291
-		} while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1292
-
1293
-		return $counter;
1294
-	}
1295
-
1296
-	/**
1297
-	 * @param array $searchResults
1298
-	 * @return int
1299
-	 * @throws ServerNotAvailableException
1300
-	 */
1301
-	private function countEntriesInSearchResults($searchResults) {
1302
-		$counter = 0;
1303
-
1304
-		foreach($searchResults as $res) {
1305
-			$count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1306
-			$counter += $count;
1307
-		}
1308
-
1309
-		return $counter;
1310
-	}
1311
-
1312
-	/**
1313
-	 * Executes an LDAP search
1314
-	 *
1315
-	 * @param string $filter the LDAP filter for the search
1316
-	 * @param array $base an array containing the LDAP subtree(s) that shall be searched
1317
-	 * @param string|string[] $attr optional, array, one or more attributes that shall be
1318
-	 * @param int $limit
1319
-	 * @param int $offset
1320
-	 * @param bool $skipHandling
1321
-	 * @return array with the search result
1322
-	 * @throws ServerNotAvailableException
1323
-	 */
1324
-	public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1325
-		$limitPerPage = (int)$this->connection->ldapPagingSize;
1326
-		if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1327
-			$limitPerPage = $limit;
1328
-		}
1329
-
1330
-		/* ++ Fixing RHDS searches with pages with zero results ++
1290
+            $continue = $pagedSearchOK && $hasMorePages;
1291
+        } while($continue && (is_null($limit) || $limit <= 0 || $limit > $counter));
1292
+
1293
+        return $counter;
1294
+    }
1295
+
1296
+    /**
1297
+     * @param array $searchResults
1298
+     * @return int
1299
+     * @throws ServerNotAvailableException
1300
+     */
1301
+    private function countEntriesInSearchResults($searchResults) {
1302
+        $counter = 0;
1303
+
1304
+        foreach($searchResults as $res) {
1305
+            $count = (int)$this->invokeLDAPMethod('countEntries', $this->connection->getConnectionResource(), $res);
1306
+            $counter += $count;
1307
+        }
1308
+
1309
+        return $counter;
1310
+    }
1311
+
1312
+    /**
1313
+     * Executes an LDAP search
1314
+     *
1315
+     * @param string $filter the LDAP filter for the search
1316
+     * @param array $base an array containing the LDAP subtree(s) that shall be searched
1317
+     * @param string|string[] $attr optional, array, one or more attributes that shall be
1318
+     * @param int $limit
1319
+     * @param int $offset
1320
+     * @param bool $skipHandling
1321
+     * @return array with the search result
1322
+     * @throws ServerNotAvailableException
1323
+     */
1324
+    public function search($filter, $base, $attr = null, $limit = null, $offset = null, $skipHandling = false) {
1325
+        $limitPerPage = (int)$this->connection->ldapPagingSize;
1326
+        if(!is_null($limit) && $limit < $limitPerPage && $limit > 0) {
1327
+            $limitPerPage = $limit;
1328
+        }
1329
+
1330
+        /* ++ Fixing RHDS searches with pages with zero results ++
1331 1331
 		 * As we can have pages with zero results and/or pages with less
1332 1332
 		 * than $limit results but with a still valid server 'cookie',
1333 1333
 		 * loops through until we get $continue equals true and
1334 1334
 		 * $findings['count'] < $limit
1335 1335
 		 */
1336
-		$findings = [];
1337
-		$savedoffset = $offset;
1338
-		do {
1339
-			$search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1340
-			if($search === false) {
1341
-				return [];
1342
-			}
1343
-			list($sr, $pagedSearchOK) = $search;
1344
-			$cr = $this->connection->getConnectionResource();
1345
-
1346
-			if($skipHandling) {
1347
-				//i.e. result do not need to be fetched, we just need the cookie
1348
-				//thus pass 1 or any other value as $iFoundItems because it is not
1349
-				//used
1350
-				$this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1351
-								$offset, $pagedSearchOK,
1352
-								$skipHandling);
1353
-				return [];
1354
-			}
1355
-
1356
-			$iFoundItems = 0;
1357
-			foreach($sr as $res) {
1358
-				$findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1359
-				$iFoundItems = max($iFoundItems, $findings['count']);
1360
-				unset($findings['count']);
1361
-			}
1362
-
1363
-			$continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1364
-				$limitPerPage, $offset, $pagedSearchOK,
1365
-										$skipHandling);
1366
-			$offset += $limitPerPage;
1367
-		} while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1368
-		// reseting offset
1369
-		$offset = $savedoffset;
1370
-
1371
-		// if we're here, probably no connection resource is returned.
1372
-		// to make Nextcloud behave nicely, we simply give back an empty array.
1373
-		if(is_null($findings)) {
1374
-			return [];
1375
-		}
1376
-
1377
-		if(!is_null($attr)) {
1378
-			$selection = [];
1379
-			$i = 0;
1380
-			foreach($findings as $item) {
1381
-				if(!is_array($item)) {
1382
-					continue;
1383
-				}
1384
-				$item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1385
-				foreach($attr as $key) {
1386
-					if(isset($item[$key])) {
1387
-						if(is_array($item[$key]) && isset($item[$key]['count'])) {
1388
-							unset($item[$key]['count']);
1389
-						}
1390
-						if($key !== 'dn') {
1391
-							if($this->resemblesDN($key)) {
1392
-								$selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1393
-							} else if($key === 'objectguid' || $key === 'guid') {
1394
-								$selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1395
-							} else {
1396
-								$selection[$i][$key] = $item[$key];
1397
-							}
1398
-						} else {
1399
-							$selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1400
-						}
1401
-					}
1402
-
1403
-				}
1404
-				$i++;
1405
-			}
1406
-			$findings = $selection;
1407
-		}
1408
-		//we slice the findings, when
1409
-		//a) paged search unsuccessful, though attempted
1410
-		//b) no paged search, but limit set
1411
-		if((!$this->getPagedSearchResultState()
1412
-			&& $pagedSearchOK)
1413
-			|| (
1414
-				!$pagedSearchOK
1415
-				&& !is_null($limit)
1416
-			)
1417
-		) {
1418
-			$findings = array_slice($findings, (int)$offset, $limit);
1419
-		}
1420
-		return $findings;
1421
-	}
1422
-
1423
-	/**
1424
-	 * @param string $name
1425
-	 * @return string
1426
-	 * @throws \InvalidArgumentException
1427
-	 */
1428
-	public function sanitizeUsername($name) {
1429
-		$name = trim($name);
1430
-
1431
-		if($this->connection->ldapIgnoreNamingRules) {
1432
-			return $name;
1433
-		}
1434
-
1435
-		// Transliteration to ASCII
1436
-		$transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1437
-		if($transliterated !== false) {
1438
-			// depending on system config iconv can work or not
1439
-			$name = $transliterated;
1440
-		}
1441
-
1442
-		// Replacements
1443
-		$name = str_replace(' ', '_', $name);
1444
-
1445
-		// Every remaining disallowed characters will be removed
1446
-		$name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1447
-
1448
-		if($name === '') {
1449
-			throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1450
-		}
1451
-
1452
-		return $name;
1453
-	}
1454
-
1455
-	/**
1456
-	 * escapes (user provided) parts for LDAP filter
1457
-	 * @param string $input, the provided value
1458
-	 * @param bool $allowAsterisk whether in * at the beginning should be preserved
1459
-	 * @return string the escaped string
1460
-	 */
1461
-	public function escapeFilterPart($input, $allowAsterisk = false) {
1462
-		$asterisk = '';
1463
-		if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1464
-			$asterisk = '*';
1465
-			$input = mb_substr($input, 1, null, 'UTF-8');
1466
-		}
1467
-		$search  = ['*', '\\', '(', ')'];
1468
-		$replace = ['\\*', '\\\\', '\\(', '\\)'];
1469
-		return $asterisk . str_replace($search, $replace, $input);
1470
-	}
1471
-
1472
-	/**
1473
-	 * combines the input filters with AND
1474
-	 * @param string[] $filters the filters to connect
1475
-	 * @return string the combined filter
1476
-	 */
1477
-	public function combineFilterWithAnd($filters) {
1478
-		return $this->combineFilter($filters, '&');
1479
-	}
1480
-
1481
-	/**
1482
-	 * combines the input filters with OR
1483
-	 * @param string[] $filters the filters to connect
1484
-	 * @return string the combined filter
1485
-	 * Combines Filter arguments with OR
1486
-	 */
1487
-	public function combineFilterWithOr($filters) {
1488
-		return $this->combineFilter($filters, '|');
1489
-	}
1490
-
1491
-	/**
1492
-	 * combines the input filters with given operator
1493
-	 * @param string[] $filters the filters to connect
1494
-	 * @param string $operator either & or |
1495
-	 * @return string the combined filter
1496
-	 */
1497
-	private function combineFilter($filters, $operator) {
1498
-		$combinedFilter = '('.$operator;
1499
-		foreach($filters as $filter) {
1500
-			if ($filter !== '' && $filter[0] !== '(') {
1501
-				$filter = '('.$filter.')';
1502
-			}
1503
-			$combinedFilter.=$filter;
1504
-		}
1505
-		$combinedFilter.=')';
1506
-		return $combinedFilter;
1507
-	}
1508
-
1509
-	/**
1510
-	 * creates a filter part for to perform search for users
1511
-	 * @param string $search the search term
1512
-	 * @return string the final filter part to use in LDAP searches
1513
-	 */
1514
-	public function getFilterPartForUserSearch($search) {
1515
-		return $this->getFilterPartForSearch($search,
1516
-			$this->connection->ldapAttributesForUserSearch,
1517
-			$this->connection->ldapUserDisplayName);
1518
-	}
1519
-
1520
-	/**
1521
-	 * creates a filter part for to perform search for groups
1522
-	 * @param string $search the search term
1523
-	 * @return string the final filter part to use in LDAP searches
1524
-	 */
1525
-	public function getFilterPartForGroupSearch($search) {
1526
-		return $this->getFilterPartForSearch($search,
1527
-			$this->connection->ldapAttributesForGroupSearch,
1528
-			$this->connection->ldapGroupDisplayName);
1529
-	}
1530
-
1531
-	/**
1532
-	 * creates a filter part for searches by splitting up the given search
1533
-	 * string into single words
1534
-	 * @param string $search the search term
1535
-	 * @param string[] $searchAttributes needs to have at least two attributes,
1536
-	 * otherwise it does not make sense :)
1537
-	 * @return string the final filter part to use in LDAP searches
1538
-	 * @throws \Exception
1539
-	 */
1540
-	private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1541
-		if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1542
-			throw new \Exception('searchAttributes must be an array with at least two string');
1543
-		}
1544
-		$searchWords = explode(' ', trim($search));
1545
-		$wordFilters = [];
1546
-		foreach($searchWords as $word) {
1547
-			$word = $this->prepareSearchTerm($word);
1548
-			//every word needs to appear at least once
1549
-			$wordMatchOneAttrFilters = [];
1550
-			foreach($searchAttributes as $attr) {
1551
-				$wordMatchOneAttrFilters[] = $attr . '=' . $word;
1552
-			}
1553
-			$wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1554
-		}
1555
-		return $this->combineFilterWithAnd($wordFilters);
1556
-	}
1557
-
1558
-	/**
1559
-	 * creates a filter part for searches
1560
-	 * @param string $search the search term
1561
-	 * @param string[]|null $searchAttributes
1562
-	 * @param string $fallbackAttribute a fallback attribute in case the user
1563
-	 * did not define search attributes. Typically the display name attribute.
1564
-	 * @return string the final filter part to use in LDAP searches
1565
-	 */
1566
-	private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1567
-		$filter = [];
1568
-		$haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1569
-		if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1570
-			try {
1571
-				return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1572
-			} catch(\Exception $e) {
1573
-				\OCP\Util::writeLog(
1574
-					'user_ldap',
1575
-					'Creating advanced filter for search failed, falling back to simple method.',
1576
-					ILogger::INFO
1577
-				);
1578
-			}
1579
-		}
1580
-
1581
-		$search = $this->prepareSearchTerm($search);
1582
-		if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1583
-			if ($fallbackAttribute === '') {
1584
-				return '';
1585
-			}
1586
-			$filter[] = $fallbackAttribute . '=' . $search;
1587
-		} else {
1588
-			foreach($searchAttributes as $attribute) {
1589
-				$filter[] = $attribute . '=' . $search;
1590
-			}
1591
-		}
1592
-		if(count($filter) === 1) {
1593
-			return '('.$filter[0].')';
1594
-		}
1595
-		return $this->combineFilterWithOr($filter);
1596
-	}
1597
-
1598
-	/**
1599
-	 * returns the search term depending on whether we are allowed
1600
-	 * list users found by ldap with the current input appended by
1601
-	 * a *
1602
-	 * @return string
1603
-	 */
1604
-	private function prepareSearchTerm($term) {
1605
-		$config = \OC::$server->getConfig();
1606
-
1607
-		$allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1608
-
1609
-		$result = $term;
1610
-		if ($term === '') {
1611
-			$result = '*';
1612
-		} else if ($allowEnum !== 'no') {
1613
-			$result = $term . '*';
1614
-		}
1615
-		return $result;
1616
-	}
1617
-
1618
-	/**
1619
-	 * returns the filter used for counting users
1620
-	 * @return string
1621
-	 */
1622
-	public function getFilterForUserCount() {
1623
-		$filter = $this->combineFilterWithAnd([
1624
-			$this->connection->ldapUserFilter,
1625
-			$this->connection->ldapUserDisplayName . '=*'
1626
-		]);
1627
-
1628
-		return $filter;
1629
-	}
1630
-
1631
-	/**
1632
-	 * @param string $name
1633
-	 * @param string $password
1634
-	 * @return bool
1635
-	 */
1636
-	public function areCredentialsValid($name, $password) {
1637
-		$name = $this->helper->DNasBaseParameter($name);
1638
-		$testConnection = clone $this->connection;
1639
-		$credentials = [
1640
-			'ldapAgentName' => $name,
1641
-			'ldapAgentPassword' => $password
1642
-		];
1643
-		if(!$testConnection->setConfiguration($credentials)) {
1644
-			return false;
1645
-		}
1646
-		return $testConnection->bind();
1647
-	}
1648
-
1649
-	/**
1650
-	 * reverse lookup of a DN given a known UUID
1651
-	 *
1652
-	 * @param string $uuid
1653
-	 * @return string
1654
-	 * @throws \Exception
1655
-	 */
1656
-	public function getUserDnByUuid($uuid) {
1657
-		$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1658
-		$filter       = $this->connection->ldapUserFilter;
1659
-		$base         = $this->connection->ldapBaseUsers;
1660
-
1661
-		if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1662
-			// Sacrebleu! The UUID attribute is unknown :( We need first an
1663
-			// existing DN to be able to reliably detect it.
1664
-			$result = $this->search($filter, $base, ['dn'], 1);
1665
-			if(!isset($result[0]) || !isset($result[0]['dn'])) {
1666
-				throw new \Exception('Cannot determine UUID attribute');
1667
-			}
1668
-			$dn = $result[0]['dn'][0];
1669
-			if(!$this->detectUuidAttribute($dn, true)) {
1670
-				throw new \Exception('Cannot determine UUID attribute');
1671
-			}
1672
-		} else {
1673
-			// The UUID attribute is either known or an override is given.
1674
-			// By calling this method we ensure that $this->connection->$uuidAttr
1675
-			// is definitely set
1676
-			if(!$this->detectUuidAttribute('', true)) {
1677
-				throw new \Exception('Cannot determine UUID attribute');
1678
-			}
1679
-		}
1680
-
1681
-		$uuidAttr = $this->connection->ldapUuidUserAttribute;
1682
-		if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1683
-			$uuid = $this->formatGuid2ForFilterUser($uuid);
1684
-		}
1685
-
1686
-		$filter = $uuidAttr . '=' . $uuid;
1687
-		$result = $this->searchUsers($filter, ['dn'], 2);
1688
-		if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1689
-			// we put the count into account to make sure that this is
1690
-			// really unique
1691
-			return $result[0]['dn'][0];
1692
-		}
1693
-
1694
-		throw new \Exception('Cannot determine UUID attribute');
1695
-	}
1696
-
1697
-	/**
1698
-	 * auto-detects the directory's UUID attribute
1699
-	 *
1700
-	 * @param string $dn a known DN used to check against
1701
-	 * @param bool $isUser
1702
-	 * @param bool $force the detection should be run, even if it is not set to auto
1703
-	 * @param array|null $ldapRecord
1704
-	 * @return bool true on success, false otherwise
1705
-	 * @throws ServerNotAvailableException
1706
-	 */
1707
-	private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1708
-		if($isUser) {
1709
-			$uuidAttr     = 'ldapUuidUserAttribute';
1710
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1711
-		} else {
1712
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1713
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1714
-		}
1715
-
1716
-		if(!$force) {
1717
-			if($this->connection->$uuidAttr !== 'auto') {
1718
-				return true;
1719
-			} else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1720
-				$this->connection->$uuidAttr = $uuidOverride;
1721
-				return true;
1722
-			}
1723
-
1724
-			$attribute = $this->connection->getFromCache($uuidAttr);
1725
-			if(!$attribute === null) {
1726
-				$this->connection->$uuidAttr = $attribute;
1727
-				return true;
1728
-			}
1729
-		}
1730
-
1731
-		foreach(self::UUID_ATTRIBUTES as $attribute) {
1732
-			if($ldapRecord !== null) {
1733
-				// we have the info from LDAP already, we don't need to talk to the server again
1734
-				if(isset($ldapRecord[$attribute])) {
1735
-					$this->connection->$uuidAttr = $attribute;
1736
-					return true;
1737
-				}
1738
-			}
1739
-
1740
-			$value = $this->readAttribute($dn, $attribute);
1741
-			if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1742
-				\OC::$server->getLogger()->debug(
1743
-					'Setting {attribute} as {subject}',
1744
-					[
1745
-						'app' => 'user_ldap',
1746
-						'attribute' => $attribute,
1747
-						'subject' => $uuidAttr
1748
-					]
1749
-				);
1750
-				$this->connection->$uuidAttr = $attribute;
1751
-				$this->connection->writeToCache($uuidAttr, $attribute);
1752
-				return true;
1753
-			}
1754
-		}
1755
-		\OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1756
-
1757
-		return false;
1758
-	}
1759
-
1760
-	/**
1761
-	 * @param string $dn
1762
-	 * @param bool $isUser
1763
-	 * @param null $ldapRecord
1764
-	 * @return bool|string
1765
-	 * @throws ServerNotAvailableException
1766
-	 */
1767
-	public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1768
-		if($isUser) {
1769
-			$uuidAttr     = 'ldapUuidUserAttribute';
1770
-			$uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1771
-		} else {
1772
-			$uuidAttr     = 'ldapUuidGroupAttribute';
1773
-			$uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1774
-		}
1775
-
1776
-		$uuid = false;
1777
-		if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1778
-			$attr = $this->connection->$uuidAttr;
1779
-			$uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1780
-			if(!is_array($uuid)
1781
-				&& $uuidOverride !== ''
1782
-				&& $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1783
-			{
1784
-				$uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1785
-					? $ldapRecord[$this->connection->$uuidAttr]
1786
-					: $this->readAttribute($dn, $this->connection->$uuidAttr);
1787
-			}
1788
-			if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1789
-				$uuid = $uuid[0];
1790
-			}
1791
-		}
1792
-
1793
-		return $uuid;
1794
-	}
1795
-
1796
-	/**
1797
-	 * converts a binary ObjectGUID into a string representation
1798
-	 * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1799
-	 * @return string
1800
-	 * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1801
-	 */
1802
-	private function convertObjectGUID2Str($oguid) {
1803
-		$hex_guid = bin2hex($oguid);
1804
-		$hex_guid_to_guid_str = '';
1805
-		for($k = 1; $k <= 4; ++$k) {
1806
-			$hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1807
-		}
1808
-		$hex_guid_to_guid_str .= '-';
1809
-		for($k = 1; $k <= 2; ++$k) {
1810
-			$hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1811
-		}
1812
-		$hex_guid_to_guid_str .= '-';
1813
-		for($k = 1; $k <= 2; ++$k) {
1814
-			$hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1815
-		}
1816
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1817
-		$hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1818
-
1819
-		return strtoupper($hex_guid_to_guid_str);
1820
-	}
1821
-
1822
-	/**
1823
-	 * the first three blocks of the string-converted GUID happen to be in
1824
-	 * reverse order. In order to use it in a filter, this needs to be
1825
-	 * corrected. Furthermore the dashes need to be replaced and \\ preprended
1826
-	 * to every two hax figures.
1827
-	 *
1828
-	 * If an invalid string is passed, it will be returned without change.
1829
-	 *
1830
-	 * @param string $guid
1831
-	 * @return string
1832
-	 */
1833
-	public function formatGuid2ForFilterUser($guid) {
1834
-		if(!is_string($guid)) {
1835
-			throw new \InvalidArgumentException('String expected');
1836
-		}
1837
-		$blocks = explode('-', $guid);
1838
-		if(count($blocks) !== 5) {
1839
-			/*
1336
+        $findings = [];
1337
+        $savedoffset = $offset;
1338
+        do {
1339
+            $search = $this->executeSearch($filter, $base, $attr, $limitPerPage, $offset);
1340
+            if($search === false) {
1341
+                return [];
1342
+            }
1343
+            list($sr, $pagedSearchOK) = $search;
1344
+            $cr = $this->connection->getConnectionResource();
1345
+
1346
+            if($skipHandling) {
1347
+                //i.e. result do not need to be fetched, we just need the cookie
1348
+                //thus pass 1 or any other value as $iFoundItems because it is not
1349
+                //used
1350
+                $this->processPagedSearchStatus($sr, $filter, $base, 1, $limitPerPage,
1351
+                                $offset, $pagedSearchOK,
1352
+                                $skipHandling);
1353
+                return [];
1354
+            }
1355
+
1356
+            $iFoundItems = 0;
1357
+            foreach($sr as $res) {
1358
+                $findings = array_merge($findings, $this->invokeLDAPMethod('getEntries', $cr, $res));
1359
+                $iFoundItems = max($iFoundItems, $findings['count']);
1360
+                unset($findings['count']);
1361
+            }
1362
+
1363
+            $continue = $this->processPagedSearchStatus($sr, $filter, $base, $iFoundItems,
1364
+                $limitPerPage, $offset, $pagedSearchOK,
1365
+                                        $skipHandling);
1366
+            $offset += $limitPerPage;
1367
+        } while ($continue && $pagedSearchOK && ($limit === null || count($findings) < $limit));
1368
+        // reseting offset
1369
+        $offset = $savedoffset;
1370
+
1371
+        // if we're here, probably no connection resource is returned.
1372
+        // to make Nextcloud behave nicely, we simply give back an empty array.
1373
+        if(is_null($findings)) {
1374
+            return [];
1375
+        }
1376
+
1377
+        if(!is_null($attr)) {
1378
+            $selection = [];
1379
+            $i = 0;
1380
+            foreach($findings as $item) {
1381
+                if(!is_array($item)) {
1382
+                    continue;
1383
+                }
1384
+                $item = \OCP\Util::mb_array_change_key_case($item, MB_CASE_LOWER, 'UTF-8');
1385
+                foreach($attr as $key) {
1386
+                    if(isset($item[$key])) {
1387
+                        if(is_array($item[$key]) && isset($item[$key]['count'])) {
1388
+                            unset($item[$key]['count']);
1389
+                        }
1390
+                        if($key !== 'dn') {
1391
+                            if($this->resemblesDN($key)) {
1392
+                                $selection[$i][$key] = $this->helper->sanitizeDN($item[$key]);
1393
+                            } else if($key === 'objectguid' || $key === 'guid') {
1394
+                                $selection[$i][$key] = [$this->convertObjectGUID2Str($item[$key][0])];
1395
+                            } else {
1396
+                                $selection[$i][$key] = $item[$key];
1397
+                            }
1398
+                        } else {
1399
+                            $selection[$i][$key] = [$this->helper->sanitizeDN($item[$key])];
1400
+                        }
1401
+                    }
1402
+
1403
+                }
1404
+                $i++;
1405
+            }
1406
+            $findings = $selection;
1407
+        }
1408
+        //we slice the findings, when
1409
+        //a) paged search unsuccessful, though attempted
1410
+        //b) no paged search, but limit set
1411
+        if((!$this->getPagedSearchResultState()
1412
+            && $pagedSearchOK)
1413
+            || (
1414
+                !$pagedSearchOK
1415
+                && !is_null($limit)
1416
+            )
1417
+        ) {
1418
+            $findings = array_slice($findings, (int)$offset, $limit);
1419
+        }
1420
+        return $findings;
1421
+    }
1422
+
1423
+    /**
1424
+     * @param string $name
1425
+     * @return string
1426
+     * @throws \InvalidArgumentException
1427
+     */
1428
+    public function sanitizeUsername($name) {
1429
+        $name = trim($name);
1430
+
1431
+        if($this->connection->ldapIgnoreNamingRules) {
1432
+            return $name;
1433
+        }
1434
+
1435
+        // Transliteration to ASCII
1436
+        $transliterated = @iconv('UTF-8', 'ASCII//TRANSLIT', $name);
1437
+        if($transliterated !== false) {
1438
+            // depending on system config iconv can work or not
1439
+            $name = $transliterated;
1440
+        }
1441
+
1442
+        // Replacements
1443
+        $name = str_replace(' ', '_', $name);
1444
+
1445
+        // Every remaining disallowed characters will be removed
1446
+        $name = preg_replace('/[^a-zA-Z0-9_.@-]/u', '', $name);
1447
+
1448
+        if($name === '') {
1449
+            throw new \InvalidArgumentException('provided name template for username does not contain any allowed characters');
1450
+        }
1451
+
1452
+        return $name;
1453
+    }
1454
+
1455
+    /**
1456
+     * escapes (user provided) parts for LDAP filter
1457
+     * @param string $input, the provided value
1458
+     * @param bool $allowAsterisk whether in * at the beginning should be preserved
1459
+     * @return string the escaped string
1460
+     */
1461
+    public function escapeFilterPart($input, $allowAsterisk = false) {
1462
+        $asterisk = '';
1463
+        if($allowAsterisk && strlen($input) > 0 && $input[0] === '*') {
1464
+            $asterisk = '*';
1465
+            $input = mb_substr($input, 1, null, 'UTF-8');
1466
+        }
1467
+        $search  = ['*', '\\', '(', ')'];
1468
+        $replace = ['\\*', '\\\\', '\\(', '\\)'];
1469
+        return $asterisk . str_replace($search, $replace, $input);
1470
+    }
1471
+
1472
+    /**
1473
+     * combines the input filters with AND
1474
+     * @param string[] $filters the filters to connect
1475
+     * @return string the combined filter
1476
+     */
1477
+    public function combineFilterWithAnd($filters) {
1478
+        return $this->combineFilter($filters, '&');
1479
+    }
1480
+
1481
+    /**
1482
+     * combines the input filters with OR
1483
+     * @param string[] $filters the filters to connect
1484
+     * @return string the combined filter
1485
+     * Combines Filter arguments with OR
1486
+     */
1487
+    public function combineFilterWithOr($filters) {
1488
+        return $this->combineFilter($filters, '|');
1489
+    }
1490
+
1491
+    /**
1492
+     * combines the input filters with given operator
1493
+     * @param string[] $filters the filters to connect
1494
+     * @param string $operator either & or |
1495
+     * @return string the combined filter
1496
+     */
1497
+    private function combineFilter($filters, $operator) {
1498
+        $combinedFilter = '('.$operator;
1499
+        foreach($filters as $filter) {
1500
+            if ($filter !== '' && $filter[0] !== '(') {
1501
+                $filter = '('.$filter.')';
1502
+            }
1503
+            $combinedFilter.=$filter;
1504
+        }
1505
+        $combinedFilter.=')';
1506
+        return $combinedFilter;
1507
+    }
1508
+
1509
+    /**
1510
+     * creates a filter part for to perform search for users
1511
+     * @param string $search the search term
1512
+     * @return string the final filter part to use in LDAP searches
1513
+     */
1514
+    public function getFilterPartForUserSearch($search) {
1515
+        return $this->getFilterPartForSearch($search,
1516
+            $this->connection->ldapAttributesForUserSearch,
1517
+            $this->connection->ldapUserDisplayName);
1518
+    }
1519
+
1520
+    /**
1521
+     * creates a filter part for to perform search for groups
1522
+     * @param string $search the search term
1523
+     * @return string the final filter part to use in LDAP searches
1524
+     */
1525
+    public function getFilterPartForGroupSearch($search) {
1526
+        return $this->getFilterPartForSearch($search,
1527
+            $this->connection->ldapAttributesForGroupSearch,
1528
+            $this->connection->ldapGroupDisplayName);
1529
+    }
1530
+
1531
+    /**
1532
+     * creates a filter part for searches by splitting up the given search
1533
+     * string into single words
1534
+     * @param string $search the search term
1535
+     * @param string[] $searchAttributes needs to have at least two attributes,
1536
+     * otherwise it does not make sense :)
1537
+     * @return string the final filter part to use in LDAP searches
1538
+     * @throws \Exception
1539
+     */
1540
+    private function getAdvancedFilterPartForSearch($search, $searchAttributes) {
1541
+        if(!is_array($searchAttributes) || count($searchAttributes) < 2) {
1542
+            throw new \Exception('searchAttributes must be an array with at least two string');
1543
+        }
1544
+        $searchWords = explode(' ', trim($search));
1545
+        $wordFilters = [];
1546
+        foreach($searchWords as $word) {
1547
+            $word = $this->prepareSearchTerm($word);
1548
+            //every word needs to appear at least once
1549
+            $wordMatchOneAttrFilters = [];
1550
+            foreach($searchAttributes as $attr) {
1551
+                $wordMatchOneAttrFilters[] = $attr . '=' . $word;
1552
+            }
1553
+            $wordFilters[] = $this->combineFilterWithOr($wordMatchOneAttrFilters);
1554
+        }
1555
+        return $this->combineFilterWithAnd($wordFilters);
1556
+    }
1557
+
1558
+    /**
1559
+     * creates a filter part for searches
1560
+     * @param string $search the search term
1561
+     * @param string[]|null $searchAttributes
1562
+     * @param string $fallbackAttribute a fallback attribute in case the user
1563
+     * did not define search attributes. Typically the display name attribute.
1564
+     * @return string the final filter part to use in LDAP searches
1565
+     */
1566
+    private function getFilterPartForSearch($search, $searchAttributes, $fallbackAttribute) {
1567
+        $filter = [];
1568
+        $haveMultiSearchAttributes = (is_array($searchAttributes) && count($searchAttributes) > 0);
1569
+        if($haveMultiSearchAttributes && strpos(trim($search), ' ') !== false) {
1570
+            try {
1571
+                return $this->getAdvancedFilterPartForSearch($search, $searchAttributes);
1572
+            } catch(\Exception $e) {
1573
+                \OCP\Util::writeLog(
1574
+                    'user_ldap',
1575
+                    'Creating advanced filter for search failed, falling back to simple method.',
1576
+                    ILogger::INFO
1577
+                );
1578
+            }
1579
+        }
1580
+
1581
+        $search = $this->prepareSearchTerm($search);
1582
+        if(!is_array($searchAttributes) || count($searchAttributes) === 0) {
1583
+            if ($fallbackAttribute === '') {
1584
+                return '';
1585
+            }
1586
+            $filter[] = $fallbackAttribute . '=' . $search;
1587
+        } else {
1588
+            foreach($searchAttributes as $attribute) {
1589
+                $filter[] = $attribute . '=' . $search;
1590
+            }
1591
+        }
1592
+        if(count($filter) === 1) {
1593
+            return '('.$filter[0].')';
1594
+        }
1595
+        return $this->combineFilterWithOr($filter);
1596
+    }
1597
+
1598
+    /**
1599
+     * returns the search term depending on whether we are allowed
1600
+     * list users found by ldap with the current input appended by
1601
+     * a *
1602
+     * @return string
1603
+     */
1604
+    private function prepareSearchTerm($term) {
1605
+        $config = \OC::$server->getConfig();
1606
+
1607
+        $allowEnum = $config->getAppValue('core', 'shareapi_allow_share_dialog_user_enumeration', 'yes');
1608
+
1609
+        $result = $term;
1610
+        if ($term === '') {
1611
+            $result = '*';
1612
+        } else if ($allowEnum !== 'no') {
1613
+            $result = $term . '*';
1614
+        }
1615
+        return $result;
1616
+    }
1617
+
1618
+    /**
1619
+     * returns the filter used for counting users
1620
+     * @return string
1621
+     */
1622
+    public function getFilterForUserCount() {
1623
+        $filter = $this->combineFilterWithAnd([
1624
+            $this->connection->ldapUserFilter,
1625
+            $this->connection->ldapUserDisplayName . '=*'
1626
+        ]);
1627
+
1628
+        return $filter;
1629
+    }
1630
+
1631
+    /**
1632
+     * @param string $name
1633
+     * @param string $password
1634
+     * @return bool
1635
+     */
1636
+    public function areCredentialsValid($name, $password) {
1637
+        $name = $this->helper->DNasBaseParameter($name);
1638
+        $testConnection = clone $this->connection;
1639
+        $credentials = [
1640
+            'ldapAgentName' => $name,
1641
+            'ldapAgentPassword' => $password
1642
+        ];
1643
+        if(!$testConnection->setConfiguration($credentials)) {
1644
+            return false;
1645
+        }
1646
+        return $testConnection->bind();
1647
+    }
1648
+
1649
+    /**
1650
+     * reverse lookup of a DN given a known UUID
1651
+     *
1652
+     * @param string $uuid
1653
+     * @return string
1654
+     * @throws \Exception
1655
+     */
1656
+    public function getUserDnByUuid($uuid) {
1657
+        $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1658
+        $filter       = $this->connection->ldapUserFilter;
1659
+        $base         = $this->connection->ldapBaseUsers;
1660
+
1661
+        if ($this->connection->ldapUuidUserAttribute === 'auto' && $uuidOverride === '') {
1662
+            // Sacrebleu! The UUID attribute is unknown :( We need first an
1663
+            // existing DN to be able to reliably detect it.
1664
+            $result = $this->search($filter, $base, ['dn'], 1);
1665
+            if(!isset($result[0]) || !isset($result[0]['dn'])) {
1666
+                throw new \Exception('Cannot determine UUID attribute');
1667
+            }
1668
+            $dn = $result[0]['dn'][0];
1669
+            if(!$this->detectUuidAttribute($dn, true)) {
1670
+                throw new \Exception('Cannot determine UUID attribute');
1671
+            }
1672
+        } else {
1673
+            // The UUID attribute is either known or an override is given.
1674
+            // By calling this method we ensure that $this->connection->$uuidAttr
1675
+            // is definitely set
1676
+            if(!$this->detectUuidAttribute('', true)) {
1677
+                throw new \Exception('Cannot determine UUID attribute');
1678
+            }
1679
+        }
1680
+
1681
+        $uuidAttr = $this->connection->ldapUuidUserAttribute;
1682
+        if($uuidAttr === 'guid' || $uuidAttr === 'objectguid') {
1683
+            $uuid = $this->formatGuid2ForFilterUser($uuid);
1684
+        }
1685
+
1686
+        $filter = $uuidAttr . '=' . $uuid;
1687
+        $result = $this->searchUsers($filter, ['dn'], 2);
1688
+        if(is_array($result) && isset($result[0]) && isset($result[0]['dn']) && count($result) === 1) {
1689
+            // we put the count into account to make sure that this is
1690
+            // really unique
1691
+            return $result[0]['dn'][0];
1692
+        }
1693
+
1694
+        throw new \Exception('Cannot determine UUID attribute');
1695
+    }
1696
+
1697
+    /**
1698
+     * auto-detects the directory's UUID attribute
1699
+     *
1700
+     * @param string $dn a known DN used to check against
1701
+     * @param bool $isUser
1702
+     * @param bool $force the detection should be run, even if it is not set to auto
1703
+     * @param array|null $ldapRecord
1704
+     * @return bool true on success, false otherwise
1705
+     * @throws ServerNotAvailableException
1706
+     */
1707
+    private function detectUuidAttribute($dn, $isUser = true, $force = false, array $ldapRecord = null) {
1708
+        if($isUser) {
1709
+            $uuidAttr     = 'ldapUuidUserAttribute';
1710
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1711
+        } else {
1712
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1713
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1714
+        }
1715
+
1716
+        if(!$force) {
1717
+            if($this->connection->$uuidAttr !== 'auto') {
1718
+                return true;
1719
+            } else if (is_string($uuidOverride) && trim($uuidOverride) !== '') {
1720
+                $this->connection->$uuidAttr = $uuidOverride;
1721
+                return true;
1722
+            }
1723
+
1724
+            $attribute = $this->connection->getFromCache($uuidAttr);
1725
+            if(!$attribute === null) {
1726
+                $this->connection->$uuidAttr = $attribute;
1727
+                return true;
1728
+            }
1729
+        }
1730
+
1731
+        foreach(self::UUID_ATTRIBUTES as $attribute) {
1732
+            if($ldapRecord !== null) {
1733
+                // we have the info from LDAP already, we don't need to talk to the server again
1734
+                if(isset($ldapRecord[$attribute])) {
1735
+                    $this->connection->$uuidAttr = $attribute;
1736
+                    return true;
1737
+                }
1738
+            }
1739
+
1740
+            $value = $this->readAttribute($dn, $attribute);
1741
+            if(is_array($value) && isset($value[0]) && !empty($value[0])) {
1742
+                \OC::$server->getLogger()->debug(
1743
+                    'Setting {attribute} as {subject}',
1744
+                    [
1745
+                        'app' => 'user_ldap',
1746
+                        'attribute' => $attribute,
1747
+                        'subject' => $uuidAttr
1748
+                    ]
1749
+                );
1750
+                $this->connection->$uuidAttr = $attribute;
1751
+                $this->connection->writeToCache($uuidAttr, $attribute);
1752
+                return true;
1753
+            }
1754
+        }
1755
+        \OC::$server->getLogger()->debug('Could not autodetect the UUID attribute', ['app' => 'user_ldap']);
1756
+
1757
+        return false;
1758
+    }
1759
+
1760
+    /**
1761
+     * @param string $dn
1762
+     * @param bool $isUser
1763
+     * @param null $ldapRecord
1764
+     * @return bool|string
1765
+     * @throws ServerNotAvailableException
1766
+     */
1767
+    public function getUUID($dn, $isUser = true, $ldapRecord = null) {
1768
+        if($isUser) {
1769
+            $uuidAttr     = 'ldapUuidUserAttribute';
1770
+            $uuidOverride = $this->connection->ldapExpertUUIDUserAttr;
1771
+        } else {
1772
+            $uuidAttr     = 'ldapUuidGroupAttribute';
1773
+            $uuidOverride = $this->connection->ldapExpertUUIDGroupAttr;
1774
+        }
1775
+
1776
+        $uuid = false;
1777
+        if($this->detectUuidAttribute($dn, $isUser, false, $ldapRecord)) {
1778
+            $attr = $this->connection->$uuidAttr;
1779
+            $uuid = isset($ldapRecord[$attr]) ? $ldapRecord[$attr] : $this->readAttribute($dn, $attr);
1780
+            if(!is_array($uuid)
1781
+                && $uuidOverride !== ''
1782
+                && $this->detectUuidAttribute($dn, $isUser, true, $ldapRecord))
1783
+            {
1784
+                $uuid = isset($ldapRecord[$this->connection->$uuidAttr])
1785
+                    ? $ldapRecord[$this->connection->$uuidAttr]
1786
+                    : $this->readAttribute($dn, $this->connection->$uuidAttr);
1787
+            }
1788
+            if(is_array($uuid) && isset($uuid[0]) && !empty($uuid[0])) {
1789
+                $uuid = $uuid[0];
1790
+            }
1791
+        }
1792
+
1793
+        return $uuid;
1794
+    }
1795
+
1796
+    /**
1797
+     * converts a binary ObjectGUID into a string representation
1798
+     * @param string $oguid the ObjectGUID in it's binary form as retrieved from AD
1799
+     * @return string
1800
+     * @link http://www.php.net/manual/en/function.ldap-get-values-len.php#73198
1801
+     */
1802
+    private function convertObjectGUID2Str($oguid) {
1803
+        $hex_guid = bin2hex($oguid);
1804
+        $hex_guid_to_guid_str = '';
1805
+        for($k = 1; $k <= 4; ++$k) {
1806
+            $hex_guid_to_guid_str .= substr($hex_guid, 8 - 2 * $k, 2);
1807
+        }
1808
+        $hex_guid_to_guid_str .= '-';
1809
+        for($k = 1; $k <= 2; ++$k) {
1810
+            $hex_guid_to_guid_str .= substr($hex_guid, 12 - 2 * $k, 2);
1811
+        }
1812
+        $hex_guid_to_guid_str .= '-';
1813
+        for($k = 1; $k <= 2; ++$k) {
1814
+            $hex_guid_to_guid_str .= substr($hex_guid, 16 - 2 * $k, 2);
1815
+        }
1816
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 16, 4);
1817
+        $hex_guid_to_guid_str .= '-' . substr($hex_guid, 20);
1818
+
1819
+        return strtoupper($hex_guid_to_guid_str);
1820
+    }
1821
+
1822
+    /**
1823
+     * the first three blocks of the string-converted GUID happen to be in
1824
+     * reverse order. In order to use it in a filter, this needs to be
1825
+     * corrected. Furthermore the dashes need to be replaced and \\ preprended
1826
+     * to every two hax figures.
1827
+     *
1828
+     * If an invalid string is passed, it will be returned without change.
1829
+     *
1830
+     * @param string $guid
1831
+     * @return string
1832
+     */
1833
+    public function formatGuid2ForFilterUser($guid) {
1834
+        if(!is_string($guid)) {
1835
+            throw new \InvalidArgumentException('String expected');
1836
+        }
1837
+        $blocks = explode('-', $guid);
1838
+        if(count($blocks) !== 5) {
1839
+            /*
1840 1840
 			 * Why not throw an Exception instead? This method is a utility
1841 1841
 			 * called only when trying to figure out whether a "missing" known
1842 1842
 			 * LDAP user was or was not renamed on the LDAP server. And this
@@ -1847,283 +1847,283 @@  discard block
 block discarded – undo
1847 1847
 			 * an exception here would kill the experience for a valid, acting
1848 1848
 			 * user. Instead we write a log message.
1849 1849
 			 */
1850
-			\OC::$server->getLogger()->info(
1851
-				'Passed string does not resemble a valid GUID. Known UUID ' .
1852
-				'({uuid}) probably does not match UUID configuration.',
1853
-				[ 'app' => 'user_ldap', 'uuid' => $guid ]
1854
-			);
1855
-			return $guid;
1856
-		}
1857
-		for($i=0; $i < 3; $i++) {
1858
-			$pairs = str_split($blocks[$i], 2);
1859
-			$pairs = array_reverse($pairs);
1860
-			$blocks[$i] = implode('', $pairs);
1861
-		}
1862
-		for($i=0; $i < 5; $i++) {
1863
-			$pairs = str_split($blocks[$i], 2);
1864
-			$blocks[$i] = '\\' . implode('\\', $pairs);
1865
-		}
1866
-		return implode('', $blocks);
1867
-	}
1868
-
1869
-	/**
1870
-	 * gets a SID of the domain of the given dn
1871
-	 *
1872
-	 * @param string $dn
1873
-	 * @return string|bool
1874
-	 * @throws ServerNotAvailableException
1875
-	 */
1876
-	public function getSID($dn) {
1877
-		$domainDN = $this->getDomainDNFromDN($dn);
1878
-		$cacheKey = 'getSID-'.$domainDN;
1879
-		$sid = $this->connection->getFromCache($cacheKey);
1880
-		if(!is_null($sid)) {
1881
-			return $sid;
1882
-		}
1883
-
1884
-		$objectSid = $this->readAttribute($domainDN, 'objectsid');
1885
-		if(!is_array($objectSid) || empty($objectSid)) {
1886
-			$this->connection->writeToCache($cacheKey, false);
1887
-			return false;
1888
-		}
1889
-		$domainObjectSid = $this->convertSID2Str($objectSid[0]);
1890
-		$this->connection->writeToCache($cacheKey, $domainObjectSid);
1891
-
1892
-		return $domainObjectSid;
1893
-	}
1894
-
1895
-	/**
1896
-	 * converts a binary SID into a string representation
1897
-	 * @param string $sid
1898
-	 * @return string
1899
-	 */
1900
-	public function convertSID2Str($sid) {
1901
-		// The format of a SID binary string is as follows:
1902
-		// 1 byte for the revision level
1903
-		// 1 byte for the number n of variable sub-ids
1904
-		// 6 bytes for identifier authority value
1905
-		// n*4 bytes for n sub-ids
1906
-		//
1907
-		// Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1908
-		//  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1909
-		$revision = ord($sid[0]);
1910
-		$numberSubID = ord($sid[1]);
1911
-
1912
-		$subIdStart = 8; // 1 + 1 + 6
1913
-		$subIdLength = 4;
1914
-		if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1915
-			// Incorrect number of bytes present.
1916
-			return '';
1917
-		}
1918
-
1919
-		// 6 bytes = 48 bits can be represented using floats without loss of
1920
-		// precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1921
-		$iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1922
-
1923
-		$subIDs = [];
1924
-		for ($i = 0; $i < $numberSubID; $i++) {
1925
-			$subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1926
-			$subIDs[] = sprintf('%u', $subID[1]);
1927
-		}
1928
-
1929
-		// Result for example above: S-1-5-21-249921958-728525901-1594176202
1930
-		return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1931
-	}
1932
-
1933
-	/**
1934
-	 * checks if the given DN is part of the given base DN(s)
1935
-	 * @param string $dn the DN
1936
-	 * @param string[] $bases array containing the allowed base DN or DNs
1937
-	 * @return bool
1938
-	 */
1939
-	public function isDNPartOfBase($dn, $bases) {
1940
-		$belongsToBase = false;
1941
-		$bases = $this->helper->sanitizeDN($bases);
1942
-
1943
-		foreach($bases as $base) {
1944
-			$belongsToBase = true;
1945
-			if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1946
-				$belongsToBase = false;
1947
-			}
1948
-			if($belongsToBase) {
1949
-				break;
1950
-			}
1951
-		}
1952
-		return $belongsToBase;
1953
-	}
1954
-
1955
-	/**
1956
-	 * resets a running Paged Search operation
1957
-	 *
1958
-	 * @throws ServerNotAvailableException
1959
-	 */
1960
-	private function abandonPagedSearch() {
1961
-		$cr = $this->connection->getConnectionResource();
1962
-		$this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1963
-		$this->getPagedSearchResultState();
1964
-		$this->lastCookie = '';
1965
-		$this->cookies = [];
1966
-	}
1967
-
1968
-	/**
1969
-	 * get a cookie for the next LDAP paged search
1970
-	 * @param string $base a string with the base DN for the search
1971
-	 * @param string $filter the search filter to identify the correct search
1972
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1973
-	 * @param int $offset the offset for the new search to identify the correct search really good
1974
-	 * @return string containing the key or empty if none is cached
1975
-	 */
1976
-	private function getPagedResultCookie($base, $filter, $limit, $offset) {
1977
-		if($offset === 0) {
1978
-			return '';
1979
-		}
1980
-		$offset -= $limit;
1981
-		//we work with cache here
1982
-		$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1983
-		$cookie = '';
1984
-		if(isset($this->cookies[$cacheKey])) {
1985
-			$cookie = $this->cookies[$cacheKey];
1986
-			if(is_null($cookie)) {
1987
-				$cookie = '';
1988
-			}
1989
-		}
1990
-		return $cookie;
1991
-	}
1992
-
1993
-	/**
1994
-	 * checks whether an LDAP paged search operation has more pages that can be
1995
-	 * retrieved, typically when offset and limit are provided.
1996
-	 *
1997
-	 * Be very careful to use it: the last cookie value, which is inspected, can
1998
-	 * be reset by other operations. Best, call it immediately after a search(),
1999
-	 * searchUsers() or searchGroups() call. count-methods are probably safe as
2000
-	 * well. Don't rely on it with any fetchList-method.
2001
-	 * @return bool
2002
-	 */
2003
-	public function hasMoreResults() {
2004
-		if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2005
-			// as in RFC 2696, when all results are returned, the cookie will
2006
-			// be empty.
2007
-			return false;
2008
-		}
2009
-
2010
-		return true;
2011
-	}
2012
-
2013
-	/**
2014
-	 * set a cookie for LDAP paged search run
2015
-	 * @param string $base a string with the base DN for the search
2016
-	 * @param string $filter the search filter to identify the correct search
2017
-	 * @param int $limit the limit (or 'pageSize'), to identify the correct search well
2018
-	 * @param int $offset the offset for the run search to identify the correct search really good
2019
-	 * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
2020
-	 * @return void
2021
-	 */
2022
-	private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2023
-		// allow '0' for 389ds
2024
-		if(!empty($cookie) || $cookie === '0') {
2025
-			$cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2026
-			$this->cookies[$cacheKey] = $cookie;
2027
-			$this->lastCookie = $cookie;
2028
-		}
2029
-	}
2030
-
2031
-	/**
2032
-	 * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2033
-	 * @return boolean|null true on success, null or false otherwise
2034
-	 */
2035
-	public function getPagedSearchResultState() {
2036
-		$result = $this->pagedSearchedSuccessful;
2037
-		$this->pagedSearchedSuccessful = null;
2038
-		return $result;
2039
-	}
2040
-
2041
-	/**
2042
-	 * Prepares a paged search, if possible
2043
-	 *
2044
-	 * @param string $filter the LDAP filter for the search
2045
-	 * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2046
-	 * @param string[] $attr optional, when a certain attribute shall be filtered outside
2047
-	 * @param int $limit
2048
-	 * @param int $offset
2049
-	 * @return bool|true
2050
-	 * @throws ServerNotAvailableException
2051
-	 */
2052
-	private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2053
-		$pagedSearchOK = false;
2054
-		if ($limit !== 0) {
2055
-			$offset = (int)$offset; //can be null
2056
-			\OCP\Util::writeLog('user_ldap',
2057
-				'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2058
-				.' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2059
-				ILogger::DEBUG);
2060
-			//get the cookie from the search for the previous search, required by LDAP
2061
-			foreach($bases as $base) {
2062
-
2063
-				$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2064
-				if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2065
-					// no cookie known from a potential previous search. We need
2066
-					// to start from 0 to come to the desired page. cookie value
2067
-					// of '0' is valid, because 389ds
2068
-					$reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2069
-					$this->search($filter, [$base], $attr, $limit, $reOffset, true);
2070
-					$cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2071
-					//still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2072
-					// '0' is valid, because 389ds
2073
-					//TODO: remember this, probably does not change in the next request...
2074
-					if(empty($cookie) && $cookie !== '0') {
2075
-						$cookie = null;
2076
-					}
2077
-				}
2078
-				if(!is_null($cookie)) {
2079
-					//since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2080
-					$this->abandonPagedSearch();
2081
-					$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2082
-						$this->connection->getConnectionResource(), $limit,
2083
-						false, $cookie);
2084
-					if(!$pagedSearchOK) {
2085
-						return false;
2086
-					}
2087
-					\OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
2088
-				} else {
2089
-					$e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
2090
-					\OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
2091
-				}
2092
-
2093
-			}
2094
-		/* ++ Fixing RHDS searches with pages with zero results ++
1850
+            \OC::$server->getLogger()->info(
1851
+                'Passed string does not resemble a valid GUID. Known UUID ' .
1852
+                '({uuid}) probably does not match UUID configuration.',
1853
+                [ 'app' => 'user_ldap', 'uuid' => $guid ]
1854
+            );
1855
+            return $guid;
1856
+        }
1857
+        for($i=0; $i < 3; $i++) {
1858
+            $pairs = str_split($blocks[$i], 2);
1859
+            $pairs = array_reverse($pairs);
1860
+            $blocks[$i] = implode('', $pairs);
1861
+        }
1862
+        for($i=0; $i < 5; $i++) {
1863
+            $pairs = str_split($blocks[$i], 2);
1864
+            $blocks[$i] = '\\' . implode('\\', $pairs);
1865
+        }
1866
+        return implode('', $blocks);
1867
+    }
1868
+
1869
+    /**
1870
+     * gets a SID of the domain of the given dn
1871
+     *
1872
+     * @param string $dn
1873
+     * @return string|bool
1874
+     * @throws ServerNotAvailableException
1875
+     */
1876
+    public function getSID($dn) {
1877
+        $domainDN = $this->getDomainDNFromDN($dn);
1878
+        $cacheKey = 'getSID-'.$domainDN;
1879
+        $sid = $this->connection->getFromCache($cacheKey);
1880
+        if(!is_null($sid)) {
1881
+            return $sid;
1882
+        }
1883
+
1884
+        $objectSid = $this->readAttribute($domainDN, 'objectsid');
1885
+        if(!is_array($objectSid) || empty($objectSid)) {
1886
+            $this->connection->writeToCache($cacheKey, false);
1887
+            return false;
1888
+        }
1889
+        $domainObjectSid = $this->convertSID2Str($objectSid[0]);
1890
+        $this->connection->writeToCache($cacheKey, $domainObjectSid);
1891
+
1892
+        return $domainObjectSid;
1893
+    }
1894
+
1895
+    /**
1896
+     * converts a binary SID into a string representation
1897
+     * @param string $sid
1898
+     * @return string
1899
+     */
1900
+    public function convertSID2Str($sid) {
1901
+        // The format of a SID binary string is as follows:
1902
+        // 1 byte for the revision level
1903
+        // 1 byte for the number n of variable sub-ids
1904
+        // 6 bytes for identifier authority value
1905
+        // n*4 bytes for n sub-ids
1906
+        //
1907
+        // Example: 010400000000000515000000a681e50e4d6c6c2bca32055f
1908
+        //  Legend: RRNNAAAAAAAAAAAA11111111222222223333333344444444
1909
+        $revision = ord($sid[0]);
1910
+        $numberSubID = ord($sid[1]);
1911
+
1912
+        $subIdStart = 8; // 1 + 1 + 6
1913
+        $subIdLength = 4;
1914
+        if (strlen($sid) !== $subIdStart + $subIdLength * $numberSubID) {
1915
+            // Incorrect number of bytes present.
1916
+            return '';
1917
+        }
1918
+
1919
+        // 6 bytes = 48 bits can be represented using floats without loss of
1920
+        // precision (see https://gist.github.com/bantu/886ac680b0aef5812f71)
1921
+        $iav = number_format(hexdec(bin2hex(substr($sid, 2, 6))), 0, '', '');
1922
+
1923
+        $subIDs = [];
1924
+        for ($i = 0; $i < $numberSubID; $i++) {
1925
+            $subID = unpack('V', substr($sid, $subIdStart + $subIdLength * $i, $subIdLength));
1926
+            $subIDs[] = sprintf('%u', $subID[1]);
1927
+        }
1928
+
1929
+        // Result for example above: S-1-5-21-249921958-728525901-1594176202
1930
+        return sprintf('S-%d-%s-%s', $revision, $iav, implode('-', $subIDs));
1931
+    }
1932
+
1933
+    /**
1934
+     * checks if the given DN is part of the given base DN(s)
1935
+     * @param string $dn the DN
1936
+     * @param string[] $bases array containing the allowed base DN or DNs
1937
+     * @return bool
1938
+     */
1939
+    public function isDNPartOfBase($dn, $bases) {
1940
+        $belongsToBase = false;
1941
+        $bases = $this->helper->sanitizeDN($bases);
1942
+
1943
+        foreach($bases as $base) {
1944
+            $belongsToBase = true;
1945
+            if(mb_strripos($dn, $base, 0, 'UTF-8') !== (mb_strlen($dn, 'UTF-8')-mb_strlen($base, 'UTF-8'))) {
1946
+                $belongsToBase = false;
1947
+            }
1948
+            if($belongsToBase) {
1949
+                break;
1950
+            }
1951
+        }
1952
+        return $belongsToBase;
1953
+    }
1954
+
1955
+    /**
1956
+     * resets a running Paged Search operation
1957
+     *
1958
+     * @throws ServerNotAvailableException
1959
+     */
1960
+    private function abandonPagedSearch() {
1961
+        $cr = $this->connection->getConnectionResource();
1962
+        $this->invokeLDAPMethod('controlPagedResult', $cr, 0, false, $this->lastCookie);
1963
+        $this->getPagedSearchResultState();
1964
+        $this->lastCookie = '';
1965
+        $this->cookies = [];
1966
+    }
1967
+
1968
+    /**
1969
+     * get a cookie for the next LDAP paged search
1970
+     * @param string $base a string with the base DN for the search
1971
+     * @param string $filter the search filter to identify the correct search
1972
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
1973
+     * @param int $offset the offset for the new search to identify the correct search really good
1974
+     * @return string containing the key or empty if none is cached
1975
+     */
1976
+    private function getPagedResultCookie($base, $filter, $limit, $offset) {
1977
+        if($offset === 0) {
1978
+            return '';
1979
+        }
1980
+        $offset -= $limit;
1981
+        //we work with cache here
1982
+        $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
1983
+        $cookie = '';
1984
+        if(isset($this->cookies[$cacheKey])) {
1985
+            $cookie = $this->cookies[$cacheKey];
1986
+            if(is_null($cookie)) {
1987
+                $cookie = '';
1988
+            }
1989
+        }
1990
+        return $cookie;
1991
+    }
1992
+
1993
+    /**
1994
+     * checks whether an LDAP paged search operation has more pages that can be
1995
+     * retrieved, typically when offset and limit are provided.
1996
+     *
1997
+     * Be very careful to use it: the last cookie value, which is inspected, can
1998
+     * be reset by other operations. Best, call it immediately after a search(),
1999
+     * searchUsers() or searchGroups() call. count-methods are probably safe as
2000
+     * well. Don't rely on it with any fetchList-method.
2001
+     * @return bool
2002
+     */
2003
+    public function hasMoreResults() {
2004
+        if(empty($this->lastCookie) && $this->lastCookie !== '0') {
2005
+            // as in RFC 2696, when all results are returned, the cookie will
2006
+            // be empty.
2007
+            return false;
2008
+        }
2009
+
2010
+        return true;
2011
+    }
2012
+
2013
+    /**
2014
+     * set a cookie for LDAP paged search run
2015
+     * @param string $base a string with the base DN for the search
2016
+     * @param string $filter the search filter to identify the correct search
2017
+     * @param int $limit the limit (or 'pageSize'), to identify the correct search well
2018
+     * @param int $offset the offset for the run search to identify the correct search really good
2019
+     * @param string $cookie string containing the cookie returned by ldap_control_paged_result_response
2020
+     * @return void
2021
+     */
2022
+    private function setPagedResultCookie($base, $filter, $limit, $offset, $cookie) {
2023
+        // allow '0' for 389ds
2024
+        if(!empty($cookie) || $cookie === '0') {
2025
+            $cacheKey = 'lc' . crc32($base) . '-' . crc32($filter) . '-' . (int)$limit . '-' . (int)$offset;
2026
+            $this->cookies[$cacheKey] = $cookie;
2027
+            $this->lastCookie = $cookie;
2028
+        }
2029
+    }
2030
+
2031
+    /**
2032
+     * Check whether the most recent paged search was successful. It flushed the state var. Use it always after a possible paged search.
2033
+     * @return boolean|null true on success, null or false otherwise
2034
+     */
2035
+    public function getPagedSearchResultState() {
2036
+        $result = $this->pagedSearchedSuccessful;
2037
+        $this->pagedSearchedSuccessful = null;
2038
+        return $result;
2039
+    }
2040
+
2041
+    /**
2042
+     * Prepares a paged search, if possible
2043
+     *
2044
+     * @param string $filter the LDAP filter for the search
2045
+     * @param string[] $bases an array containing the LDAP subtree(s) that shall be searched
2046
+     * @param string[] $attr optional, when a certain attribute shall be filtered outside
2047
+     * @param int $limit
2048
+     * @param int $offset
2049
+     * @return bool|true
2050
+     * @throws ServerNotAvailableException
2051
+     */
2052
+    private function initPagedSearch($filter, $bases, $attr, $limit, $offset) {
2053
+        $pagedSearchOK = false;
2054
+        if ($limit !== 0) {
2055
+            $offset = (int)$offset; //can be null
2056
+            \OCP\Util::writeLog('user_ldap',
2057
+                'initializing paged search for  Filter '.$filter.' base '.print_r($bases, true)
2058
+                .' attr '.print_r($attr, true). ' limit ' .$limit.' offset '.$offset,
2059
+                ILogger::DEBUG);
2060
+            //get the cookie from the search for the previous search, required by LDAP
2061
+            foreach($bases as $base) {
2062
+
2063
+                $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2064
+                if(empty($cookie) && $cookie !== "0" && ($offset > 0)) {
2065
+                    // no cookie known from a potential previous search. We need
2066
+                    // to start from 0 to come to the desired page. cookie value
2067
+                    // of '0' is valid, because 389ds
2068
+                    $reOffset = ($offset - $limit) < 0 ? 0 : $offset - $limit;
2069
+                    $this->search($filter, [$base], $attr, $limit, $reOffset, true);
2070
+                    $cookie = $this->getPagedResultCookie($base, $filter, $limit, $offset);
2071
+                    //still no cookie? obviously, the server does not like us. Let's skip paging efforts.
2072
+                    // '0' is valid, because 389ds
2073
+                    //TODO: remember this, probably does not change in the next request...
2074
+                    if(empty($cookie) && $cookie !== '0') {
2075
+                        $cookie = null;
2076
+                    }
2077
+                }
2078
+                if(!is_null($cookie)) {
2079
+                    //since offset = 0, this is a new search. We abandon other searches that might be ongoing.
2080
+                    $this->abandonPagedSearch();
2081
+                    $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2082
+                        $this->connection->getConnectionResource(), $limit,
2083
+                        false, $cookie);
2084
+                    if(!$pagedSearchOK) {
2085
+                        return false;
2086
+                    }
2087
+                    \OCP\Util::writeLog('user_ldap', 'Ready for a paged search', ILogger::DEBUG);
2088
+                } else {
2089
+                    $e = new \Exception('No paged search possible, Limit '.$limit.' Offset '.$offset);
2090
+                    \OC::$server->getLogger()->logException($e, ['level' => ILogger::DEBUG]);
2091
+                }
2092
+
2093
+            }
2094
+        /* ++ Fixing RHDS searches with pages with zero results ++
2095 2095
 		 * We coudn't get paged searches working with our RHDS for login ($limit = 0),
2096 2096
 		 * due to pages with zero results.
2097 2097
 		 * So we added "&& !empty($this->lastCookie)" to this test to ignore pagination
2098 2098
 		 * if we don't have a previous paged search.
2099 2099
 		 */
2100
-		} else if ($limit === 0 && !empty($this->lastCookie)) {
2101
-			// a search without limit was requested. However, if we do use
2102
-			// Paged Search once, we always must do it. This requires us to
2103
-			// initialize it with the configured page size.
2104
-			$this->abandonPagedSearch();
2105
-			// in case someone set it to 0 … use 500, otherwise no results will
2106
-			// be returned.
2107
-			$pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2108
-			$pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2109
-				$this->connection->getConnectionResource(),
2110
-				$pageSize, false, '');
2111
-		}
2112
-
2113
-		return $pagedSearchOK;
2114
-	}
2115
-
2116
-	/**
2117
-	 * Is more than one $attr used for search?
2118
-	 *
2119
-	 * @param string|string[]|null $attr
2120
-	 * @return bool
2121
-	 */
2122
-	private function manyAttributes($attr): bool {
2123
-		if (\is_array($attr)) {
2124
-			return \count($attr) > 1;
2125
-		}
2126
-		return false;
2127
-	}
2100
+        } else if ($limit === 0 && !empty($this->lastCookie)) {
2101
+            // a search without limit was requested. However, if we do use
2102
+            // Paged Search once, we always must do it. This requires us to
2103
+            // initialize it with the configured page size.
2104
+            $this->abandonPagedSearch();
2105
+            // in case someone set it to 0 … use 500, otherwise no results will
2106
+            // be returned.
2107
+            $pageSize = (int)$this->connection->ldapPagingSize > 0 ? (int)$this->connection->ldapPagingSize : 500;
2108
+            $pagedSearchOK = $this->invokeLDAPMethod('controlPagedResult',
2109
+                $this->connection->getConnectionResource(),
2110
+                $pageSize, false, '');
2111
+        }
2112
+
2113
+        return $pagedSearchOK;
2114
+    }
2115
+
2116
+    /**
2117
+     * Is more than one $attr used for search?
2118
+     *
2119
+     * @param string|string[]|null $attr
2120
+     * @return bool
2121
+     */
2122
+    private function manyAttributes($attr): bool {
2123
+        if (\is_array($attr)) {
2124
+            return \count($attr) > 1;
2125
+        }
2126
+        return false;
2127
+    }
2128 2128
 
2129 2129
 }
Please login to merge, or discard this patch.
apps/encryption/templates/settings-personal.php 1 patch
Indentation   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -1,6 +1,6 @@  discard block
 block discarded – undo
1 1
 <?php
2
-	/** @var array $_ */
3
-	/** @var \OCP\IL10N $l */
2
+    /** @var array $_ */
3
+    /** @var \OCP\IL10N $l */
4 4
 script('encryption', 'settings-personal');
5 5
 ?>
6 6
 <form id="ocDefaultEncryptionModule" class="section">
@@ -19,8 +19,8 @@  discard block
 block discarded – undo
19 19
 			<br />
20 20
 			<?php p($l->t("Set your old private key password to your current log-in password:")); ?>
21 21
 			<?php if ($_["recoveryEnabledForUser"]):
22
-					p($l->t(" If you don't remember your old password you can ask your administrator to recover your files."));
23
-			endif; ?>
22
+                    p($l->t(" If you don't remember your old password you can ask your administrator to recover your files."));
23
+            endif; ?>
24 24
 			<br />
25 25
 			<input
26 26
 				type="password"
Please login to merge, or discard this patch.
apps/encryption/lib/Crypto/EncryptAll.php 1 patch
Indentation   +435 added lines, -435 removed lines patch added patch discarded remove patch
@@ -47,440 +47,440 @@
 block discarded – undo
47 47
 
48 48
 class EncryptAll {
49 49
 
50
-	/** @var Setup */
51
-	protected $userSetup;
52
-
53
-	/** @var IUserManager */
54
-	protected $userManager;
55
-
56
-	/** @var View */
57
-	protected $rootView;
58
-
59
-	/** @var KeyManager */
60
-	protected $keyManager;
61
-
62
-	/** @var Util */
63
-	protected $util;
64
-
65
-	/** @var array  */
66
-	protected $userPasswords;
67
-
68
-	/** @var  IConfig */
69
-	protected $config;
70
-
71
-	/** @var IMailer */
72
-	protected $mailer;
73
-
74
-	/** @var  IL10N */
75
-	protected $l;
76
-
77
-	/** @var  QuestionHelper */
78
-	protected $questionHelper;
79
-
80
-	/** @var  OutputInterface */
81
-	protected $output;
82
-
83
-	/** @var  InputInterface */
84
-	protected $input;
85
-
86
-	/** @var ISecureRandom */
87
-	protected $secureRandom;
88
-
89
-	/**
90
-	 * @param Setup $userSetup
91
-	 * @param IUserManager $userManager
92
-	 * @param View $rootView
93
-	 * @param KeyManager $keyManager
94
-	 * @param Util $util
95
-	 * @param IConfig $config
96
-	 * @param IMailer $mailer
97
-	 * @param IL10N $l
98
-	 * @param QuestionHelper $questionHelper
99
-	 * @param ISecureRandom $secureRandom
100
-	 */
101
-	public function __construct(
102
-		Setup $userSetup,
103
-		IUserManager $userManager,
104
-		View $rootView,
105
-		KeyManager $keyManager,
106
-		Util $util,
107
-		IConfig $config,
108
-		IMailer $mailer,
109
-		IL10N $l,
110
-		QuestionHelper $questionHelper,
111
-		ISecureRandom $secureRandom
112
-	) {
113
-		$this->userSetup = $userSetup;
114
-		$this->userManager = $userManager;
115
-		$this->rootView = $rootView;
116
-		$this->keyManager = $keyManager;
117
-		$this->util = $util;
118
-		$this->config = $config;
119
-		$this->mailer = $mailer;
120
-		$this->l = $l;
121
-		$this->questionHelper = $questionHelper;
122
-		$this->secureRandom = $secureRandom;
123
-		// store one time passwords for the users
124
-		$this->userPasswords = [];
125
-	}
126
-
127
-	/**
128
-	 * start to encrypt all files
129
-	 *
130
-	 * @param InputInterface $input
131
-	 * @param OutputInterface $output
132
-	 */
133
-	public function encryptAll(InputInterface $input, OutputInterface $output) {
134
-
135
-		$this->input = $input;
136
-		$this->output = $output;
137
-
138
-		$headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
139
-		$this->output->writeln("\n");
140
-		$this->output->writeln($headline);
141
-		$this->output->writeln(str_pad('', strlen($headline), '='));
142
-		$this->output->writeln("\n");
143
-
144
-		if ($this->util->isMasterKeyEnabled()) {
145
-			$this->output->writeln('Use master key to encrypt all files.');
146
-			$this->keyManager->validateMasterKey();
147
-		} else {
148
-			//create private/public keys for each user and store the private key password
149
-			$this->output->writeln('Create key-pair for every user');
150
-			$this->output->writeln('------------------------------');
151
-			$this->output->writeln('');
152
-			$this->output->writeln('This module will encrypt all files in the users files folder initially.');
153
-			$this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
154
-			$this->output->writeln('');
155
-			$this->createKeyPairs();
156
-		}
157
-
158
-
159
-		// output generated encryption key passwords
160
-		if ($this->util->isMasterKeyEnabled() === false) {
161
-			//send-out or display password list and write it to a file
162
-			$this->output->writeln("\n");
163
-			$this->output->writeln('Generated encryption key passwords');
164
-			$this->output->writeln('----------------------------------');
165
-			$this->output->writeln('');
166
-			$this->outputPasswords();
167
-		}
168
-
169
-		//setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
170
-		$this->output->writeln("\n");
171
-		$this->output->writeln('Start to encrypt users files');
172
-		$this->output->writeln('----------------------------');
173
-		$this->output->writeln('');
174
-		$this->encryptAllUsersFiles();
175
-		$this->output->writeln("\n");
176
-	}
177
-
178
-	/**
179
-	 * create key-pair for every user
180
-	 */
181
-	protected function createKeyPairs() {
182
-		$this->output->writeln("\n");
183
-		$progress = new ProgressBar($this->output);
184
-		$progress->setFormat(" %message% \n [%bar%]");
185
-		$progress->start();
186
-
187
-		foreach($this->userManager->getBackends() as $backend) {
188
-			$limit = 500;
189
-			$offset = 0;
190
-			do {
191
-				$users = $backend->getUsers('', $limit, $offset);
192
-				foreach ($users as $user) {
193
-					if ($this->keyManager->userHasKeys($user) === false) {
194
-						$progress->setMessage('Create key-pair for ' . $user);
195
-						$progress->advance();
196
-						$this->setupUserFS($user);
197
-						$password = $this->generateOneTimePassword($user);
198
-						$this->userSetup->setupUser($user, $password);
199
-					} else {
200
-						// users which already have a key-pair will be stored with a
201
-						// empty password and filtered out later
202
-						$this->userPasswords[$user] = '';
203
-					}
204
-				}
205
-				$offset += $limit;
206
-			} while(count($users) >= $limit);
207
-		}
208
-
209
-		$progress->setMessage('Key-pair created for all users');
210
-		$progress->finish();
211
-	}
212
-
213
-	/**
214
-	 * iterate over all user and encrypt their files
215
-	 */
216
-	protected function encryptAllUsersFiles() {
217
-		$this->output->writeln("\n");
218
-		$progress = new ProgressBar($this->output);
219
-		$progress->setFormat(" %message% \n [%bar%]");
220
-		$progress->start();
221
-		$numberOfUsers = count($this->userPasswords);
222
-		$userNo = 1;
223
-		if ($this->util->isMasterKeyEnabled()) {
224
-			$this->encryptAllUserFilesWithMasterKey($progress);
225
-		} else {
226
-			foreach ($this->userPasswords as $uid => $password) {
227
-				$userCount = "$uid ($userNo of $numberOfUsers)";
228
-				$this->encryptUsersFiles($uid, $progress, $userCount);
229
-				$userNo++;
230
-			}
231
-		}
232
-		$progress->setMessage("all files encrypted");
233
-		$progress->finish();
234
-
235
-	}
236
-
237
-	/**
238
-	 * encrypt all user files with the master key
239
-	 *
240
-	 * @param ProgressBar $progress
241
-	 */
242
-	protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
243
-		$userNo = 1;
244
-		foreach($this->userManager->getBackends() as $backend) {
245
-			$limit = 500;
246
-			$offset = 0;
247
-			do {
248
-				$users = $backend->getUsers('', $limit, $offset);
249
-				foreach ($users as $user) {
250
-					$userCount = "$user ($userNo)";
251
-					$this->encryptUsersFiles($user, $progress, $userCount);
252
-					$userNo++;
253
-				}
254
-				$offset += $limit;
255
-			} while(count($users) >= $limit);
256
-		}
257
-	}
258
-
259
-	/**
260
-	 * encrypt files from the given user
261
-	 *
262
-	 * @param string $uid
263
-	 * @param ProgressBar $progress
264
-	 * @param string $userCount
265
-	 */
266
-	protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
267
-
268
-		$this->setupUserFS($uid);
269
-		$directories = [];
270
-		$directories[] =  '/' . $uid . '/files';
271
-
272
-		while($root = array_pop($directories)) {
273
-			$content = $this->rootView->getDirectoryContent($root);
274
-			foreach ($content as $file) {
275
-				$path = $root . '/' . $file['name'];
276
-				if ($this->rootView->is_dir($path)) {
277
-					$directories[] = $path;
278
-					continue;
279
-				} else {
280
-					$progress->setMessage("encrypt files for user $userCount: $path");
281
-					$progress->advance();
282
-					if($this->encryptFile($path) === false) {
283
-						$progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
284
-						$progress->advance();
285
-					}
286
-				}
287
-			}
288
-		}
289
-	}
290
-
291
-	/**
292
-	 * encrypt file
293
-	 *
294
-	 * @param string $path
295
-	 * @return bool
296
-	 */
297
-	protected function encryptFile($path) {
298
-
299
-		// skip already encrypted files
300
-		$fileInfo = $this->rootView->getFileInfo($path);
301
-		if ($fileInfo !== false && $fileInfo->isEncrypted()) {
302
-			return true;
303
-		}
304
-
305
-		$source = $path;
306
-		$target = $path . '.encrypted.' . time();
307
-
308
-		try {
309
-			$this->rootView->copy($source, $target);
310
-			$this->rootView->rename($target, $source);
311
-		} catch (DecryptionFailedException $e) {
312
-			if ($this->rootView->file_exists($target)) {
313
-				$this->rootView->unlink($target);
314
-			}
315
-			return false;
316
-		}
317
-
318
-		return true;
319
-	}
320
-
321
-	/**
322
-	 * output one-time encryption passwords
323
-	 */
324
-	protected function outputPasswords() {
325
-		$table = new Table($this->output);
326
-		$table->setHeaders(['Username', 'Private key password']);
327
-
328
-		//create rows
329
-		$newPasswords = [];
330
-		$unchangedPasswords = [];
331
-		foreach ($this->userPasswords as $uid => $password) {
332
-			if (empty($password)) {
333
-				$unchangedPasswords[] = $uid;
334
-			} else {
335
-				$newPasswords[] = [$uid, $password];
336
-			}
337
-		}
338
-
339
-		if (empty($newPasswords)) {
340
-			$this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
341
-			return;
342
-		}
343
-
344
-		$table->setRows($newPasswords);
345
-		$table->render();
346
-
347
-		if (!empty($unchangedPasswords)) {
348
-			$this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
349
-			foreach ($unchangedPasswords as $uid) {
350
-				$this->output->writeln("    $uid");
351
-			}
352
-		}
353
-
354
-		$this->writePasswordsToFile($newPasswords);
355
-
356
-		$this->output->writeln('');
357
-		$question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
358
-		if ($this->questionHelper->ask($this->input, $this->output, $question)) {
359
-			$this->sendPasswordsByMail();
360
-		}
361
-	}
362
-
363
-	/**
364
-	 * write one-time encryption passwords to a csv file
365
-	 *
366
-	 * @param array $passwords
367
-	 */
368
-	protected function writePasswordsToFile(array $passwords) {
369
-		$fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
370
-		foreach ($passwords as $pwd) {
371
-			fputcsv($fp, $pwd);
372
-		}
373
-		fclose($fp);
374
-		$this->output->writeln("\n");
375
-		$this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
376
-		$this->output->writeln('');
377
-		$this->output->writeln('Each of these users need to login to the web interface, go to the');
378
-		$this->output->writeln('personal settings section "basic encryption module" and');
379
-		$this->output->writeln('update the private key password to match the login password again by');
380
-		$this->output->writeln('entering the one-time password into the "old log-in password" field');
381
-		$this->output->writeln('and their current login password');
382
-	}
383
-
384
-	/**
385
-	 * setup user file system
386
-	 *
387
-	 * @param string $uid
388
-	 */
389
-	protected function setupUserFS($uid) {
390
-		\OC_Util::tearDownFS();
391
-		\OC_Util::setupFS($uid);
392
-	}
393
-
394
-	/**
395
-	 * generate one time password for the user and store it in a array
396
-	 *
397
-	 * @param string $uid
398
-	 * @return string password
399
-	 */
400
-	protected function generateOneTimePassword($uid) {
401
-		$password = $this->secureRandom->generate(8);
402
-		$this->userPasswords[$uid] = $password;
403
-		return $password;
404
-	}
405
-
406
-	/**
407
-	 * send encryption key passwords to the users by mail
408
-	 */
409
-	protected function sendPasswordsByMail() {
410
-		$noMail = [];
411
-
412
-		$this->output->writeln('');
413
-		$progress = new ProgressBar($this->output, count($this->userPasswords));
414
-		$progress->start();
415
-
416
-		foreach ($this->userPasswords as $uid => $password) {
417
-			$progress->advance();
418
-			if (!empty($password)) {
419
-				$recipient = $this->userManager->get($uid);
420
-				$recipientDisplayName = $recipient->getDisplayName();
421
-				$to = $recipient->getEMailAddress();
422
-
423
-				if ($to === '') {
424
-					$noMail[] = $uid;
425
-					continue;
426
-				}
427
-
428
-				$subject = (string)$this->l->t('one-time password for server-side-encryption');
429
-				list($htmlBody, $textBody) = $this->createMailBody($password);
430
-
431
-				// send it out now
432
-				try {
433
-					$message = $this->mailer->createMessage();
434
-					$message->setSubject($subject);
435
-					$message->setTo([$to => $recipientDisplayName]);
436
-					$message->setHtmlBody($htmlBody);
437
-					$message->setPlainBody($textBody);
438
-					$message->setFrom([
439
-						\OCP\Util::getDefaultEmailAddress('admin-noreply')
440
-					]);
441
-
442
-					$this->mailer->send($message);
443
-				} catch (\Exception $e) {
444
-					$noMail[] = $uid;
445
-				}
446
-			}
447
-		}
448
-
449
-		$progress->finish();
450
-
451
-		if (empty($noMail)) {
452
-			$this->output->writeln("\n\nPassword successfully send to all users");
453
-		} else {
454
-			$table = new Table($this->output);
455
-			$table->setHeaders(['Username', 'Private key password']);
456
-			$this->output->writeln("\n\nCould not send password to following users:\n");
457
-			$rows = [];
458
-			foreach ($noMail as $uid) {
459
-				$rows[] = [$uid, $this->userPasswords[$uid]];
460
-			}
461
-			$table->setRows($rows);
462
-			$table->render();
463
-		}
464
-
465
-	}
466
-
467
-	/**
468
-	 * create mail body for plain text and html mail
469
-	 *
470
-	 * @param string $password one-time encryption password
471
-	 * @return array an array of the html mail body and the plain text mail body
472
-	 */
473
-	protected function createMailBody($password) {
474
-
475
-		$html = new \OC_Template("encryption", "mail", "");
476
-		$html->assign('password', $password);
477
-		$htmlMail = $html->fetchPage();
478
-
479
-		$plainText = new \OC_Template("encryption", "altmail", "");
480
-		$plainText->assign('password', $password);
481
-		$plainTextMail = $plainText->fetchPage();
482
-
483
-		return [$htmlMail, $plainTextMail];
484
-	}
50
+    /** @var Setup */
51
+    protected $userSetup;
52
+
53
+    /** @var IUserManager */
54
+    protected $userManager;
55
+
56
+    /** @var View */
57
+    protected $rootView;
58
+
59
+    /** @var KeyManager */
60
+    protected $keyManager;
61
+
62
+    /** @var Util */
63
+    protected $util;
64
+
65
+    /** @var array  */
66
+    protected $userPasswords;
67
+
68
+    /** @var  IConfig */
69
+    protected $config;
70
+
71
+    /** @var IMailer */
72
+    protected $mailer;
73
+
74
+    /** @var  IL10N */
75
+    protected $l;
76
+
77
+    /** @var  QuestionHelper */
78
+    protected $questionHelper;
79
+
80
+    /** @var  OutputInterface */
81
+    protected $output;
82
+
83
+    /** @var  InputInterface */
84
+    protected $input;
85
+
86
+    /** @var ISecureRandom */
87
+    protected $secureRandom;
88
+
89
+    /**
90
+     * @param Setup $userSetup
91
+     * @param IUserManager $userManager
92
+     * @param View $rootView
93
+     * @param KeyManager $keyManager
94
+     * @param Util $util
95
+     * @param IConfig $config
96
+     * @param IMailer $mailer
97
+     * @param IL10N $l
98
+     * @param QuestionHelper $questionHelper
99
+     * @param ISecureRandom $secureRandom
100
+     */
101
+    public function __construct(
102
+        Setup $userSetup,
103
+        IUserManager $userManager,
104
+        View $rootView,
105
+        KeyManager $keyManager,
106
+        Util $util,
107
+        IConfig $config,
108
+        IMailer $mailer,
109
+        IL10N $l,
110
+        QuestionHelper $questionHelper,
111
+        ISecureRandom $secureRandom
112
+    ) {
113
+        $this->userSetup = $userSetup;
114
+        $this->userManager = $userManager;
115
+        $this->rootView = $rootView;
116
+        $this->keyManager = $keyManager;
117
+        $this->util = $util;
118
+        $this->config = $config;
119
+        $this->mailer = $mailer;
120
+        $this->l = $l;
121
+        $this->questionHelper = $questionHelper;
122
+        $this->secureRandom = $secureRandom;
123
+        // store one time passwords for the users
124
+        $this->userPasswords = [];
125
+    }
126
+
127
+    /**
128
+     * start to encrypt all files
129
+     *
130
+     * @param InputInterface $input
131
+     * @param OutputInterface $output
132
+     */
133
+    public function encryptAll(InputInterface $input, OutputInterface $output) {
134
+
135
+        $this->input = $input;
136
+        $this->output = $output;
137
+
138
+        $headline = 'Encrypt all files with the ' . Encryption::DISPLAY_NAME;
139
+        $this->output->writeln("\n");
140
+        $this->output->writeln($headline);
141
+        $this->output->writeln(str_pad('', strlen($headline), '='));
142
+        $this->output->writeln("\n");
143
+
144
+        if ($this->util->isMasterKeyEnabled()) {
145
+            $this->output->writeln('Use master key to encrypt all files.');
146
+            $this->keyManager->validateMasterKey();
147
+        } else {
148
+            //create private/public keys for each user and store the private key password
149
+            $this->output->writeln('Create key-pair for every user');
150
+            $this->output->writeln('------------------------------');
151
+            $this->output->writeln('');
152
+            $this->output->writeln('This module will encrypt all files in the users files folder initially.');
153
+            $this->output->writeln('Already existing versions and files in the trash bin will not be encrypted.');
154
+            $this->output->writeln('');
155
+            $this->createKeyPairs();
156
+        }
157
+
158
+
159
+        // output generated encryption key passwords
160
+        if ($this->util->isMasterKeyEnabled() === false) {
161
+            //send-out or display password list and write it to a file
162
+            $this->output->writeln("\n");
163
+            $this->output->writeln('Generated encryption key passwords');
164
+            $this->output->writeln('----------------------------------');
165
+            $this->output->writeln('');
166
+            $this->outputPasswords();
167
+        }
168
+
169
+        //setup users file system and encrypt all files one by one (take should encrypt setting of storage into account)
170
+        $this->output->writeln("\n");
171
+        $this->output->writeln('Start to encrypt users files');
172
+        $this->output->writeln('----------------------------');
173
+        $this->output->writeln('');
174
+        $this->encryptAllUsersFiles();
175
+        $this->output->writeln("\n");
176
+    }
177
+
178
+    /**
179
+     * create key-pair for every user
180
+     */
181
+    protected function createKeyPairs() {
182
+        $this->output->writeln("\n");
183
+        $progress = new ProgressBar($this->output);
184
+        $progress->setFormat(" %message% \n [%bar%]");
185
+        $progress->start();
186
+
187
+        foreach($this->userManager->getBackends() as $backend) {
188
+            $limit = 500;
189
+            $offset = 0;
190
+            do {
191
+                $users = $backend->getUsers('', $limit, $offset);
192
+                foreach ($users as $user) {
193
+                    if ($this->keyManager->userHasKeys($user) === false) {
194
+                        $progress->setMessage('Create key-pair for ' . $user);
195
+                        $progress->advance();
196
+                        $this->setupUserFS($user);
197
+                        $password = $this->generateOneTimePassword($user);
198
+                        $this->userSetup->setupUser($user, $password);
199
+                    } else {
200
+                        // users which already have a key-pair will be stored with a
201
+                        // empty password and filtered out later
202
+                        $this->userPasswords[$user] = '';
203
+                    }
204
+                }
205
+                $offset += $limit;
206
+            } while(count($users) >= $limit);
207
+        }
208
+
209
+        $progress->setMessage('Key-pair created for all users');
210
+        $progress->finish();
211
+    }
212
+
213
+    /**
214
+     * iterate over all user and encrypt their files
215
+     */
216
+    protected function encryptAllUsersFiles() {
217
+        $this->output->writeln("\n");
218
+        $progress = new ProgressBar($this->output);
219
+        $progress->setFormat(" %message% \n [%bar%]");
220
+        $progress->start();
221
+        $numberOfUsers = count($this->userPasswords);
222
+        $userNo = 1;
223
+        if ($this->util->isMasterKeyEnabled()) {
224
+            $this->encryptAllUserFilesWithMasterKey($progress);
225
+        } else {
226
+            foreach ($this->userPasswords as $uid => $password) {
227
+                $userCount = "$uid ($userNo of $numberOfUsers)";
228
+                $this->encryptUsersFiles($uid, $progress, $userCount);
229
+                $userNo++;
230
+            }
231
+        }
232
+        $progress->setMessage("all files encrypted");
233
+        $progress->finish();
234
+
235
+    }
236
+
237
+    /**
238
+     * encrypt all user files with the master key
239
+     *
240
+     * @param ProgressBar $progress
241
+     */
242
+    protected function encryptAllUserFilesWithMasterKey(ProgressBar $progress) {
243
+        $userNo = 1;
244
+        foreach($this->userManager->getBackends() as $backend) {
245
+            $limit = 500;
246
+            $offset = 0;
247
+            do {
248
+                $users = $backend->getUsers('', $limit, $offset);
249
+                foreach ($users as $user) {
250
+                    $userCount = "$user ($userNo)";
251
+                    $this->encryptUsersFiles($user, $progress, $userCount);
252
+                    $userNo++;
253
+                }
254
+                $offset += $limit;
255
+            } while(count($users) >= $limit);
256
+        }
257
+    }
258
+
259
+    /**
260
+     * encrypt files from the given user
261
+     *
262
+     * @param string $uid
263
+     * @param ProgressBar $progress
264
+     * @param string $userCount
265
+     */
266
+    protected function encryptUsersFiles($uid, ProgressBar $progress, $userCount) {
267
+
268
+        $this->setupUserFS($uid);
269
+        $directories = [];
270
+        $directories[] =  '/' . $uid . '/files';
271
+
272
+        while($root = array_pop($directories)) {
273
+            $content = $this->rootView->getDirectoryContent($root);
274
+            foreach ($content as $file) {
275
+                $path = $root . '/' . $file['name'];
276
+                if ($this->rootView->is_dir($path)) {
277
+                    $directories[] = $path;
278
+                    continue;
279
+                } else {
280
+                    $progress->setMessage("encrypt files for user $userCount: $path");
281
+                    $progress->advance();
282
+                    if($this->encryptFile($path) === false) {
283
+                        $progress->setMessage("encrypt files for user $userCount: $path (already encrypted)");
284
+                        $progress->advance();
285
+                    }
286
+                }
287
+            }
288
+        }
289
+    }
290
+
291
+    /**
292
+     * encrypt file
293
+     *
294
+     * @param string $path
295
+     * @return bool
296
+     */
297
+    protected function encryptFile($path) {
298
+
299
+        // skip already encrypted files
300
+        $fileInfo = $this->rootView->getFileInfo($path);
301
+        if ($fileInfo !== false && $fileInfo->isEncrypted()) {
302
+            return true;
303
+        }
304
+
305
+        $source = $path;
306
+        $target = $path . '.encrypted.' . time();
307
+
308
+        try {
309
+            $this->rootView->copy($source, $target);
310
+            $this->rootView->rename($target, $source);
311
+        } catch (DecryptionFailedException $e) {
312
+            if ($this->rootView->file_exists($target)) {
313
+                $this->rootView->unlink($target);
314
+            }
315
+            return false;
316
+        }
317
+
318
+        return true;
319
+    }
320
+
321
+    /**
322
+     * output one-time encryption passwords
323
+     */
324
+    protected function outputPasswords() {
325
+        $table = new Table($this->output);
326
+        $table->setHeaders(['Username', 'Private key password']);
327
+
328
+        //create rows
329
+        $newPasswords = [];
330
+        $unchangedPasswords = [];
331
+        foreach ($this->userPasswords as $uid => $password) {
332
+            if (empty($password)) {
333
+                $unchangedPasswords[] = $uid;
334
+            } else {
335
+                $newPasswords[] = [$uid, $password];
336
+            }
337
+        }
338
+
339
+        if (empty($newPasswords)) {
340
+            $this->output->writeln("\nAll users already had a key-pair, no further action needed.\n");
341
+            return;
342
+        }
343
+
344
+        $table->setRows($newPasswords);
345
+        $table->render();
346
+
347
+        if (!empty($unchangedPasswords)) {
348
+            $this->output->writeln("\nThe following users already had a key-pair which was reused without setting a new password:\n");
349
+            foreach ($unchangedPasswords as $uid) {
350
+                $this->output->writeln("    $uid");
351
+            }
352
+        }
353
+
354
+        $this->writePasswordsToFile($newPasswords);
355
+
356
+        $this->output->writeln('');
357
+        $question = new ConfirmationQuestion('Do you want to send the passwords directly to the users by mail? (y/n) ', false);
358
+        if ($this->questionHelper->ask($this->input, $this->output, $question)) {
359
+            $this->sendPasswordsByMail();
360
+        }
361
+    }
362
+
363
+    /**
364
+     * write one-time encryption passwords to a csv file
365
+     *
366
+     * @param array $passwords
367
+     */
368
+    protected function writePasswordsToFile(array $passwords) {
369
+        $fp = $this->rootView->fopen('oneTimeEncryptionPasswords.csv', 'w');
370
+        foreach ($passwords as $pwd) {
371
+            fputcsv($fp, $pwd);
372
+        }
373
+        fclose($fp);
374
+        $this->output->writeln("\n");
375
+        $this->output->writeln('A list of all newly created passwords was written to data/oneTimeEncryptionPasswords.csv');
376
+        $this->output->writeln('');
377
+        $this->output->writeln('Each of these users need to login to the web interface, go to the');
378
+        $this->output->writeln('personal settings section "basic encryption module" and');
379
+        $this->output->writeln('update the private key password to match the login password again by');
380
+        $this->output->writeln('entering the one-time password into the "old log-in password" field');
381
+        $this->output->writeln('and their current login password');
382
+    }
383
+
384
+    /**
385
+     * setup user file system
386
+     *
387
+     * @param string $uid
388
+     */
389
+    protected function setupUserFS($uid) {
390
+        \OC_Util::tearDownFS();
391
+        \OC_Util::setupFS($uid);
392
+    }
393
+
394
+    /**
395
+     * generate one time password for the user and store it in a array
396
+     *
397
+     * @param string $uid
398
+     * @return string password
399
+     */
400
+    protected function generateOneTimePassword($uid) {
401
+        $password = $this->secureRandom->generate(8);
402
+        $this->userPasswords[$uid] = $password;
403
+        return $password;
404
+    }
405
+
406
+    /**
407
+     * send encryption key passwords to the users by mail
408
+     */
409
+    protected function sendPasswordsByMail() {
410
+        $noMail = [];
411
+
412
+        $this->output->writeln('');
413
+        $progress = new ProgressBar($this->output, count($this->userPasswords));
414
+        $progress->start();
415
+
416
+        foreach ($this->userPasswords as $uid => $password) {
417
+            $progress->advance();
418
+            if (!empty($password)) {
419
+                $recipient = $this->userManager->get($uid);
420
+                $recipientDisplayName = $recipient->getDisplayName();
421
+                $to = $recipient->getEMailAddress();
422
+
423
+                if ($to === '') {
424
+                    $noMail[] = $uid;
425
+                    continue;
426
+                }
427
+
428
+                $subject = (string)$this->l->t('one-time password for server-side-encryption');
429
+                list($htmlBody, $textBody) = $this->createMailBody($password);
430
+
431
+                // send it out now
432
+                try {
433
+                    $message = $this->mailer->createMessage();
434
+                    $message->setSubject($subject);
435
+                    $message->setTo([$to => $recipientDisplayName]);
436
+                    $message->setHtmlBody($htmlBody);
437
+                    $message->setPlainBody($textBody);
438
+                    $message->setFrom([
439
+                        \OCP\Util::getDefaultEmailAddress('admin-noreply')
440
+                    ]);
441
+
442
+                    $this->mailer->send($message);
443
+                } catch (\Exception $e) {
444
+                    $noMail[] = $uid;
445
+                }
446
+            }
447
+        }
448
+
449
+        $progress->finish();
450
+
451
+        if (empty($noMail)) {
452
+            $this->output->writeln("\n\nPassword successfully send to all users");
453
+        } else {
454
+            $table = new Table($this->output);
455
+            $table->setHeaders(['Username', 'Private key password']);
456
+            $this->output->writeln("\n\nCould not send password to following users:\n");
457
+            $rows = [];
458
+            foreach ($noMail as $uid) {
459
+                $rows[] = [$uid, $this->userPasswords[$uid]];
460
+            }
461
+            $table->setRows($rows);
462
+            $table->render();
463
+        }
464
+
465
+    }
466
+
467
+    /**
468
+     * create mail body for plain text and html mail
469
+     *
470
+     * @param string $password one-time encryption password
471
+     * @return array an array of the html mail body and the plain text mail body
472
+     */
473
+    protected function createMailBody($password) {
474
+
475
+        $html = new \OC_Template("encryption", "mail", "");
476
+        $html->assign('password', $password);
477
+        $htmlMail = $html->fetchPage();
478
+
479
+        $plainText = new \OC_Template("encryption", "altmail", "");
480
+        $plainText->assign('password', $password);
481
+        $plainTextMail = $plainText->fetchPage();
482
+
483
+        return [$htmlMail, $plainTextMail];
484
+    }
485 485
 
486 486
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Controller/RecoveryController.php 1 patch
Indentation   +155 added lines, -155 removed lines patch added patch discarded remove patch
@@ -34,160 +34,160 @@
 block discarded – undo
34 34
 use OCP\IRequest;
35 35
 
36 36
 class RecoveryController extends Controller {
37
-	/**
38
-	 * @var IConfig
39
-	 */
40
-	private $config;
41
-	/**
42
-	 * @var IL10N
43
-	 */
44
-	private $l;
45
-	/**
46
-	 * @var Recovery
47
-	 */
48
-	private $recovery;
49
-
50
-	/**
51
-	 * @param string $AppName
52
-	 * @param IRequest $request
53
-	 * @param IConfig $config
54
-	 * @param IL10N $l10n
55
-	 * @param Recovery $recovery
56
-	 */
57
-	public function __construct($AppName,
58
-								IRequest $request,
59
-								IConfig $config,
60
-								IL10N $l10n,
61
-								Recovery $recovery) {
62
-		parent::__construct($AppName, $request);
63
-		$this->config = $config;
64
-		$this->l = $l10n;
65
-		$this->recovery = $recovery;
66
-	}
67
-
68
-	/**
69
-	 * @param string $recoveryPassword
70
-	 * @param string $confirmPassword
71
-	 * @param string $adminEnableRecovery
72
-	 * @return DataResponse
73
-	 */
74
-	public function adminRecovery($recoveryPassword, $confirmPassword, $adminEnableRecovery) {
75
-		// Check if both passwords are the same
76
-		if (empty($recoveryPassword)) {
77
-			$errorMessage = (string)$this->l->t('Missing recovery key password');
78
-			return new DataResponse(['data' => ['message' => $errorMessage]],
79
-				Http::STATUS_BAD_REQUEST);
80
-		}
81
-
82
-		if (empty($confirmPassword)) {
83
-			$errorMessage = (string)$this->l->t('Please repeat the recovery key password');
84
-			return new DataResponse(['data' => ['message' => $errorMessage]],
85
-				Http::STATUS_BAD_REQUEST);
86
-		}
87
-
88
-		if ($recoveryPassword !== $confirmPassword) {
89
-			$errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
90
-			return new DataResponse(['data' => ['message' => $errorMessage]],
91
-				Http::STATUS_BAD_REQUEST);
92
-		}
93
-
94
-		if (isset($adminEnableRecovery) && $adminEnableRecovery === '1') {
95
-			if ($this->recovery->enableAdminRecovery($recoveryPassword)) {
96
-				return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully enabled')]]);
97
-			}
98
-			return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not enable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
99
-		} elseif (isset($adminEnableRecovery) && $adminEnableRecovery === '0') {
100
-			if ($this->recovery->disableAdminRecovery($recoveryPassword)) {
101
-				return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully disabled')]]);
102
-			}
103
-			return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not disable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
104
-		}
105
-		// this response should never be sent but just in case.
106
-		return new DataResponse(['data' => ['message' => (string)$this->l->t('Missing parameters')]], Http::STATUS_BAD_REQUEST);
107
-	}
108
-
109
-	/**
110
-	 * @param string $newPassword
111
-	 * @param string $oldPassword
112
-	 * @param string $confirmPassword
113
-	 * @return DataResponse
114
-	 */
115
-	public function changeRecoveryPassword($newPassword, $oldPassword, $confirmPassword) {
116
-		//check if both passwords are the same
117
-		if (empty($oldPassword)) {
118
-			$errorMessage = (string)$this->l->t('Please provide the old recovery password');
119
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
120
-		}
121
-
122
-		if (empty($newPassword)) {
123
-			$errorMessage = (string)$this->l->t('Please provide a new recovery password');
124
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
125
-		}
126
-
127
-		if (empty($confirmPassword)) {
128
-			$errorMessage = (string)$this->l->t('Please repeat the new recovery password');
129
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
130
-		}
131
-
132
-		if ($newPassword !== $confirmPassword) {
133
-			$errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
134
-			return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
135
-		}
136
-
137
-		$result = $this->recovery->changeRecoveryKeyPassword($newPassword,
138
-			$oldPassword);
139
-
140
-		if ($result) {
141
-			return new DataResponse(
142
-				[
143
-					'data' => [
144
-						'message' => (string)$this->l->t('Password successfully changed.')]
145
-				]
146
-			);
147
-		}
148
-		return new DataResponse(
149
-			[
150
-				'data' => [
151
-					'message' => (string)$this->l->t('Could not change the password. Maybe the old password was not correct.')
152
-				]
153
-			], Http::STATUS_BAD_REQUEST);
154
-	}
155
-
156
-	/**
157
-	 * @NoAdminRequired
158
-	 *
159
-	 * @param string $userEnableRecovery
160
-	 * @return DataResponse
161
-	 */
162
-	public function userSetRecovery($userEnableRecovery) {
163
-		if ($userEnableRecovery === '0' || $userEnableRecovery === '1') {
164
-
165
-			$result = $this->recovery->setRecoveryForUser($userEnableRecovery);
166
-
167
-			if ($result) {
168
-				if ($userEnableRecovery === '0') {
169
-					return new DataResponse(
170
-						[
171
-							'data' => [
172
-								'message' => (string)$this->l->t('Recovery Key disabled')]
173
-						]
174
-					);
175
-				}
176
-				return new DataResponse(
177
-					[
178
-						'data' => [
179
-							'message' => (string)$this->l->t('Recovery Key enabled')]
180
-					]
181
-				);
182
-			}
183
-
184
-		}
185
-		return new DataResponse(
186
-			[
187
-				'data' => [
188
-					'message' => (string)$this->l->t('Could not enable the recovery key, please try again or contact your administrator')
189
-				]
190
-			], Http::STATUS_BAD_REQUEST);
191
-	}
37
+    /**
38
+     * @var IConfig
39
+     */
40
+    private $config;
41
+    /**
42
+     * @var IL10N
43
+     */
44
+    private $l;
45
+    /**
46
+     * @var Recovery
47
+     */
48
+    private $recovery;
49
+
50
+    /**
51
+     * @param string $AppName
52
+     * @param IRequest $request
53
+     * @param IConfig $config
54
+     * @param IL10N $l10n
55
+     * @param Recovery $recovery
56
+     */
57
+    public function __construct($AppName,
58
+                                IRequest $request,
59
+                                IConfig $config,
60
+                                IL10N $l10n,
61
+                                Recovery $recovery) {
62
+        parent::__construct($AppName, $request);
63
+        $this->config = $config;
64
+        $this->l = $l10n;
65
+        $this->recovery = $recovery;
66
+    }
67
+
68
+    /**
69
+     * @param string $recoveryPassword
70
+     * @param string $confirmPassword
71
+     * @param string $adminEnableRecovery
72
+     * @return DataResponse
73
+     */
74
+    public function adminRecovery($recoveryPassword, $confirmPassword, $adminEnableRecovery) {
75
+        // Check if both passwords are the same
76
+        if (empty($recoveryPassword)) {
77
+            $errorMessage = (string)$this->l->t('Missing recovery key password');
78
+            return new DataResponse(['data' => ['message' => $errorMessage]],
79
+                Http::STATUS_BAD_REQUEST);
80
+        }
81
+
82
+        if (empty($confirmPassword)) {
83
+            $errorMessage = (string)$this->l->t('Please repeat the recovery key password');
84
+            return new DataResponse(['data' => ['message' => $errorMessage]],
85
+                Http::STATUS_BAD_REQUEST);
86
+        }
87
+
88
+        if ($recoveryPassword !== $confirmPassword) {
89
+            $errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
90
+            return new DataResponse(['data' => ['message' => $errorMessage]],
91
+                Http::STATUS_BAD_REQUEST);
92
+        }
93
+
94
+        if (isset($adminEnableRecovery) && $adminEnableRecovery === '1') {
95
+            if ($this->recovery->enableAdminRecovery($recoveryPassword)) {
96
+                return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully enabled')]]);
97
+            }
98
+            return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not enable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
99
+        } elseif (isset($adminEnableRecovery) && $adminEnableRecovery === '0') {
100
+            if ($this->recovery->disableAdminRecovery($recoveryPassword)) {
101
+                return new DataResponse(['data' => ['message' => (string)$this->l->t('Recovery key successfully disabled')]]);
102
+            }
103
+            return new DataResponse(['data' => ['message' => (string)$this->l->t('Could not disable recovery key. Please check your recovery key password!')]], Http::STATUS_BAD_REQUEST);
104
+        }
105
+        // this response should never be sent but just in case.
106
+        return new DataResponse(['data' => ['message' => (string)$this->l->t('Missing parameters')]], Http::STATUS_BAD_REQUEST);
107
+    }
108
+
109
+    /**
110
+     * @param string $newPassword
111
+     * @param string $oldPassword
112
+     * @param string $confirmPassword
113
+     * @return DataResponse
114
+     */
115
+    public function changeRecoveryPassword($newPassword, $oldPassword, $confirmPassword) {
116
+        //check if both passwords are the same
117
+        if (empty($oldPassword)) {
118
+            $errorMessage = (string)$this->l->t('Please provide the old recovery password');
119
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
120
+        }
121
+
122
+        if (empty($newPassword)) {
123
+            $errorMessage = (string)$this->l->t('Please provide a new recovery password');
124
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
125
+        }
126
+
127
+        if (empty($confirmPassword)) {
128
+            $errorMessage = (string)$this->l->t('Please repeat the new recovery password');
129
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
130
+        }
131
+
132
+        if ($newPassword !== $confirmPassword) {
133
+            $errorMessage = (string)$this->l->t('Repeated recovery key password does not match the provided recovery key password');
134
+            return new DataResponse(['data' => ['message' => $errorMessage]], Http::STATUS_BAD_REQUEST);
135
+        }
136
+
137
+        $result = $this->recovery->changeRecoveryKeyPassword($newPassword,
138
+            $oldPassword);
139
+
140
+        if ($result) {
141
+            return new DataResponse(
142
+                [
143
+                    'data' => [
144
+                        'message' => (string)$this->l->t('Password successfully changed.')]
145
+                ]
146
+            );
147
+        }
148
+        return new DataResponse(
149
+            [
150
+                'data' => [
151
+                    'message' => (string)$this->l->t('Could not change the password. Maybe the old password was not correct.')
152
+                ]
153
+            ], Http::STATUS_BAD_REQUEST);
154
+    }
155
+
156
+    /**
157
+     * @NoAdminRequired
158
+     *
159
+     * @param string $userEnableRecovery
160
+     * @return DataResponse
161
+     */
162
+    public function userSetRecovery($userEnableRecovery) {
163
+        if ($userEnableRecovery === '0' || $userEnableRecovery === '1') {
164
+
165
+            $result = $this->recovery->setRecoveryForUser($userEnableRecovery);
166
+
167
+            if ($result) {
168
+                if ($userEnableRecovery === '0') {
169
+                    return new DataResponse(
170
+                        [
171
+                            'data' => [
172
+                                'message' => (string)$this->l->t('Recovery Key disabled')]
173
+                        ]
174
+                    );
175
+                }
176
+                return new DataResponse(
177
+                    [
178
+                        'data' => [
179
+                            'message' => (string)$this->l->t('Recovery Key enabled')]
180
+                    ]
181
+                );
182
+            }
183
+
184
+        }
185
+        return new DataResponse(
186
+            [
187
+                'data' => [
188
+                    'message' => (string)$this->l->t('Could not enable the recovery key, please try again or contact your administrator')
189
+                ]
190
+            ], Http::STATUS_BAD_REQUEST);
191
+    }
192 192
 
193 193
 }
Please login to merge, or discard this patch.
apps/encryption/lib/Controller/StatusController.php 1 patch
Indentation   +62 added lines, -62 removed lines patch added patch discarded remove patch
@@ -34,73 +34,73 @@
 block discarded – undo
34 34
 
35 35
 class StatusController extends Controller {
36 36
 
37
-	/** @var IL10N */
38
-	private $l;
37
+    /** @var IL10N */
38
+    private $l;
39 39
 
40
-	/** @var Session */
41
-	private $session;
40
+    /** @var Session */
41
+    private $session;
42 42
 
43
-	/** @var IManager */
44
-	private $encryptionManager;
43
+    /** @var IManager */
44
+    private $encryptionManager;
45 45
 
46
-	/**
47
-	 * @param string $AppName
48
-	 * @param IRequest $request
49
-	 * @param IL10N $l10n
50
-	 * @param Session $session
51
-	 * @param IManager $encryptionManager
52
-	 */
53
-	public function __construct($AppName,
54
-								IRequest $request,
55
-								IL10N $l10n,
56
-								Session $session,
57
-								IManager $encryptionManager
58
-								) {
59
-		parent::__construct($AppName, $request);
60
-		$this->l = $l10n;
61
-		$this->session = $session;
62
-		$this->encryptionManager = $encryptionManager;
63
-	}
46
+    /**
47
+     * @param string $AppName
48
+     * @param IRequest $request
49
+     * @param IL10N $l10n
50
+     * @param Session $session
51
+     * @param IManager $encryptionManager
52
+     */
53
+    public function __construct($AppName,
54
+                                IRequest $request,
55
+                                IL10N $l10n,
56
+                                Session $session,
57
+                                IManager $encryptionManager
58
+                                ) {
59
+        parent::__construct($AppName, $request);
60
+        $this->l = $l10n;
61
+        $this->session = $session;
62
+        $this->encryptionManager = $encryptionManager;
63
+    }
64 64
 
65
-	/**
66
-	 * @NoAdminRequired
67
-	 * @return DataResponse
68
-	 */
69
-	public function getStatus() {
65
+    /**
66
+     * @NoAdminRequired
67
+     * @return DataResponse
68
+     */
69
+    public function getStatus() {
70 70
 
71
-		$status = 'error';
72
-		$message = 'no valid init status';
73
-		switch($this->session->getStatus()) {
74
-			case Session::INIT_EXECUTED:
75
-				$status = 'interactionNeeded';
76
-				$message = (string)$this->l->t(
77
-					'Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files.'
78
-				);
79
-				break;
80
-			case Session::NOT_INITIALIZED:
81
-				$status = 'interactionNeeded';
82
-				if ($this->encryptionManager->isEnabled()) {
83
-					$message = (string)$this->l->t(
84
-						'Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again.'
85
-					);
86
-				} else {
87
-					$message = (string)$this->l->t(
88
-						'Please enable server side encryption in the admin settings in order to use the encryption module.'
89
-					);
90
-				}
91
-				break;
92
-			case Session::INIT_SUCCESSFUL:
93
-				$status = 'success';
94
-				$message = (string)$this->l->t('Encryption app is enabled and ready');
95
-		}
71
+        $status = 'error';
72
+        $message = 'no valid init status';
73
+        switch($this->session->getStatus()) {
74
+            case Session::INIT_EXECUTED:
75
+                $status = 'interactionNeeded';
76
+                $message = (string)$this->l->t(
77
+                    'Invalid private key for encryption app. Please update your private key password in your personal settings to recover access to your encrypted files.'
78
+                );
79
+                break;
80
+            case Session::NOT_INITIALIZED:
81
+                $status = 'interactionNeeded';
82
+                if ($this->encryptionManager->isEnabled()) {
83
+                    $message = (string)$this->l->t(
84
+                        'Encryption App is enabled, but your keys are not initialized. Please log-out and log-in again.'
85
+                    );
86
+                } else {
87
+                    $message = (string)$this->l->t(
88
+                        'Please enable server side encryption in the admin settings in order to use the encryption module.'
89
+                    );
90
+                }
91
+                break;
92
+            case Session::INIT_SUCCESSFUL:
93
+                $status = 'success';
94
+                $message = (string)$this->l->t('Encryption app is enabled and ready');
95
+        }
96 96
 
97
-		return new DataResponse(
98
-			[
99
-				'status' => $status,
100
-				'data' => [
101
-					'message' => $message]
102
-			]
103
-		);
104
-	}
97
+        return new DataResponse(
98
+            [
99
+                'status' => $status,
100
+                'data' => [
101
+                    'message' => $message]
102
+            ]
103
+        );
104
+    }
105 105
 
106 106
 }
Please login to merge, or discard this patch.
apps/comments/lib/Notification/Listener.php 1 patch
Indentation   +78 added lines, -78 removed lines patch added patch discarded remove patch
@@ -29,93 +29,93 @@
 block discarded – undo
29 29
 use OCP\Notification\IManager;
30 30
 
31 31
 class Listener {
32
-	/** @var IManager */
33
-	protected $notificationManager;
32
+    /** @var IManager */
33
+    protected $notificationManager;
34 34
 
35
-	/** @var IUserManager */
36
-	protected $userManager;
35
+    /** @var IUserManager */
36
+    protected $userManager;
37 37
 
38
-	/**
39
-	 * Listener constructor.
40
-	 *
41
-	 * @param IManager $notificationManager
42
-	 * @param IUserManager $userManager
43
-	 */
44
-	public function __construct(
45
-		IManager $notificationManager,
46
-		IUserManager $userManager
47
-	) {
38
+    /**
39
+     * Listener constructor.
40
+     *
41
+     * @param IManager $notificationManager
42
+     * @param IUserManager $userManager
43
+     */
44
+    public function __construct(
45
+        IManager $notificationManager,
46
+        IUserManager $userManager
47
+    ) {
48 48
 
49
-		$this->notificationManager = $notificationManager;
50
-		$this->userManager = $userManager;
51
-	}
49
+        $this->notificationManager = $notificationManager;
50
+        $this->userManager = $userManager;
51
+    }
52 52
 
53
-	/**
54
-	 * @param CommentsEvent $event
55
-	 */
56
-	public function evaluate(CommentsEvent $event) {
57
-		$comment = $event->getComment();
53
+    /**
54
+     * @param CommentsEvent $event
55
+     */
56
+    public function evaluate(CommentsEvent $event) {
57
+        $comment = $event->getComment();
58 58
 
59
-		$mentions = $this->extractMentions($comment->getMentions());
60
-		if(empty($mentions)) {
61
-			// no one to notify
62
-			return;
63
-		}
59
+        $mentions = $this->extractMentions($comment->getMentions());
60
+        if(empty($mentions)) {
61
+            // no one to notify
62
+            return;
63
+        }
64 64
 
65
-		$notification = $this->instantiateNotification($comment);
65
+        $notification = $this->instantiateNotification($comment);
66 66
 
67
-		foreach($mentions as $uid) {
68
-			if(($comment->getActorType() === 'users' && $uid === $comment->getActorId())
69
-				|| !$this->userManager->userExists($uid)
70
-			) {
71
-				// do not notify unknown users or yourself
72
-				continue;
73
-			}
67
+        foreach($mentions as $uid) {
68
+            if(($comment->getActorType() === 'users' && $uid === $comment->getActorId())
69
+                || !$this->userManager->userExists($uid)
70
+            ) {
71
+                // do not notify unknown users or yourself
72
+                continue;
73
+            }
74 74
 
75
-			$notification->setUser($uid);
76
-			if($event->getEvent() === CommentsEvent::EVENT_DELETE
77
-				|| $event->getEvent() === CommentsEvent::EVENT_PRE_UPDATE)
78
-			{
79
-				$this->notificationManager->markProcessed($notification);
80
-			} else {
81
-				$this->notificationManager->notify($notification);
82
-			}
83
-		}
84
-	}
75
+            $notification->setUser($uid);
76
+            if($event->getEvent() === CommentsEvent::EVENT_DELETE
77
+                || $event->getEvent() === CommentsEvent::EVENT_PRE_UPDATE)
78
+            {
79
+                $this->notificationManager->markProcessed($notification);
80
+            } else {
81
+                $this->notificationManager->notify($notification);
82
+            }
83
+        }
84
+    }
85 85
 
86
-	/**
87
-	 * creates a notification instance and fills it with comment data
88
-	 *
89
-	 * @param IComment $comment
90
-	 * @return \OCP\Notification\INotification
91
-	 */
92
-	public function instantiateNotification(IComment $comment) {
93
-		$notification = $this->notificationManager->createNotification();
94
-		$notification
95
-			->setApp('comments')
96
-			->setObject('comment', $comment->getId())
97
-			->setSubject('mention', [ $comment->getObjectType(), $comment->getObjectId() ])
98
-			->setDateTime($comment->getCreationDateTime());
86
+    /**
87
+     * creates a notification instance and fills it with comment data
88
+     *
89
+     * @param IComment $comment
90
+     * @return \OCP\Notification\INotification
91
+     */
92
+    public function instantiateNotification(IComment $comment) {
93
+        $notification = $this->notificationManager->createNotification();
94
+        $notification
95
+            ->setApp('comments')
96
+            ->setObject('comment', $comment->getId())
97
+            ->setSubject('mention', [ $comment->getObjectType(), $comment->getObjectId() ])
98
+            ->setDateTime($comment->getCreationDateTime());
99 99
 
100
-		return $notification;
101
-	}
100
+        return $notification;
101
+    }
102 102
 
103
-	/**
104
-	 * flattens the mention array returned from comments to a list of user ids.
105
-	 *
106
-	 * @param array $mentions
107
-	 * @return string[] containing the mentions, e.g. ['alice', 'bob']
108
-	 */
109
-	public function extractMentions(array $mentions) {
110
-		if(empty($mentions)) {
111
-			return [];
112
-		}
113
-		$uids = [];
114
-		foreach($mentions as $mention) {
115
-			if($mention['type'] === 'user') {
116
-				$uids[] = $mention['id'];
117
-			}
118
-		}
119
-		return $uids;
120
-	}
103
+    /**
104
+     * flattens the mention array returned from comments to a list of user ids.
105
+     *
106
+     * @param array $mentions
107
+     * @return string[] containing the mentions, e.g. ['alice', 'bob']
108
+     */
109
+    public function extractMentions(array $mentions) {
110
+        if(empty($mentions)) {
111
+            return [];
112
+        }
113
+        $uids = [];
114
+        foreach($mentions as $mention) {
115
+            if($mention['type'] === 'user') {
116
+                $uids[] = $mention['id'];
117
+            }
118
+        }
119
+        return $uids;
120
+    }
121 121
 }
Please login to merge, or discard this patch.