Passed
Push — master ( 62403d...0c3e2f )
by Joas
14:50 queued 14s
created
apps/user_ldap/ajax/clearMappings.php 1 patch
Indentation   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -35,26 +35,26 @@
 block discarded – undo
35 35
 $subject = (string)$_POST['ldap_clear_mapping'];
36 36
 $mapping = null;
37 37
 try {
38
-	if($subject === 'user') {
39
-		$mapping = new UserMapping(\OC::$server->getDatabaseConnection());
40
-		$result = $mapping->clearCb(
41
-			function ($uid) {
42
-				\OC::$server->getUserManager()->emit('\OC\User', 'preUnassignedUserId', [$uid]);
43
-			},
44
-			function ($uid) {
45
-				\OC::$server->getUserManager()->emit('\OC\User', 'postUnassignedUserId', [$uid]);
46
-			}
47
-		);
48
-	} else if($subject === 'group') {
49
-		$mapping = new GroupMapping(\OC::$server->getDatabaseConnection());
50
-		$result = $mapping->clear();
51
-	}
38
+    if($subject === 'user') {
39
+        $mapping = new UserMapping(\OC::$server->getDatabaseConnection());
40
+        $result = $mapping->clearCb(
41
+            function ($uid) {
42
+                \OC::$server->getUserManager()->emit('\OC\User', 'preUnassignedUserId', [$uid]);
43
+            },
44
+            function ($uid) {
45
+                \OC::$server->getUserManager()->emit('\OC\User', 'postUnassignedUserId', [$uid]);
46
+            }
47
+        );
48
+    } else if($subject === 'group') {
49
+        $mapping = new GroupMapping(\OC::$server->getDatabaseConnection());
50
+        $result = $mapping->clear();
51
+    }
52 52
 
53
-	if($mapping === null || !$result) {
54
-		$l = \OC::$server->getL10N('user_ldap');
55
-		throw new \Exception($l->t('Failed to clear the mappings.'));
56
-	}
57
-	\OC_JSON::success();
53
+    if($mapping === null || !$result) {
54
+        $l = \OC::$server->getL10N('user_ldap');
55
+        throw new \Exception($l->t('Failed to clear the mappings.'));
56
+    }
57
+    \OC_JSON::success();
58 58
 } catch (\Exception $e) {
59
-	\OC_JSON::error(['message' => $e->getMessage()]);
59
+    \OC_JSON::error(['message' => $e->getMessage()]);
60 60
 }
Please login to merge, or discard this patch.
apps/user_ldap/ajax/getNewServerConfigPrefix.php 1 patch
Spacing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -32,13 +32,13 @@
 block discarded – undo
32 32
 $serverConnections = $helper->getServerConfigurationPrefixes();
33 33
 sort($serverConnections);
34 34
 $lk = array_pop($serverConnections);
35
-$ln = (int)str_replace('s', '', $lk);
36
-$nk = 's'.str_pad($ln+1, 2, '0', STR_PAD_LEFT);
35
+$ln = (int) str_replace('s', '', $lk);
36
+$nk = 's'.str_pad($ln + 1, 2, '0', STR_PAD_LEFT);
37 37
 
38 38
 $resultData = ['configPrefix' => $nk];
39 39
 
40 40
 $newConfig = new \OCA\User_LDAP\Configuration($nk, false);
41
-if(isset($_POST['copyConfig'])) {
41
+if (isset($_POST['copyConfig'])) {
42 42
 	$originalConfig = new \OCA\User_LDAP\Configuration($_POST['copyConfig']);
43 43
 	$newConfig->setConfiguration($originalConfig->getConfiguration());
44 44
 } else {
Please login to merge, or discard this patch.
apps/user_ldap/templates/part.wizard-server.php 2 patches
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -2,14 +2,14 @@
 block discarded – undo
2 2
 		<p>
3 3
 		<select id="ldap_serverconfig_chooser" name="ldap_serverconfig_chooser">
4 4
 		<?php
5
-		$i = 1;
6
-		$sel = ' selected';
7
-		foreach($_['serverConfigurationPrefixes'] as $prefix) {
8
-			?>
5
+        $i = 1;
6
+        $sel = ' selected';
7
+        foreach($_['serverConfigurationPrefixes'] as $prefix) {
8
+            ?>
9 9
 			<option value="<?php p($prefix); ?>"<?php p($sel); $sel = ''; ?>><?php p($l->t('%s. Server:', [$i++]));?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
10 10
 			<?php
11
-		}
12
-		?>
11
+        }
12
+        ?>
13 13
 		</select>
14 14
 		<button type="button" id="ldap_action_add_configuration"
15 15
 			name="ldap_action_add_configuration" class="icon-add icon-default-style"
Please login to merge, or discard this patch.
Spacing   +20 added lines, -20 removed lines patch added patch discarded remove patch
@@ -4,23 +4,23 @@  discard block
 block discarded – undo
4 4
 		<?php
5 5
 		$i = 1;
6 6
 		$sel = ' selected';
7
-		foreach($_['serverConfigurationPrefixes'] as $prefix) {
7
+		foreach ($_['serverConfigurationPrefixes'] as $prefix) {
8 8
 			?>
9
-			<option value="<?php p($prefix); ?>"<?php p($sel); $sel = ''; ?>><?php p($l->t('%s. Server:', [$i++]));?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
9
+			<option value="<?php p($prefix); ?>"<?php p($sel); $sel = ''; ?>><?php p($l->t('%s. Server:', [$i++])); ?> <?php p(' '.$_['serverConfigurationHosts'][$prefix]); ?></option>
10 10
 			<?php
11 11
 		}
12 12
 		?>
13 13
 		</select>
14 14
 		<button type="button" id="ldap_action_add_configuration"
15 15
 			name="ldap_action_add_configuration" class="icon-add icon-default-style"
16
-			title="<?php p($l->t('Add a new configuration'));?>">&nbsp;</button>
16
+			title="<?php p($l->t('Add a new configuration')); ?>">&nbsp;</button>
17 17
 		<button type="button" id="ldap_action_copy_configuration"
18 18
 			name="ldap_action_copy_configuration"
19 19
 			class="ldapIconCopy icon-default-style"
20
-			title="<?php p($l->t('Copy current configuration into new directory binding'));?>">&nbsp;</button>
20
+			title="<?php p($l->t('Copy current configuration into new directory binding')); ?>">&nbsp;</button>
21 21
 		<button type="button" id="ldap_action_delete_configuration"
22 22
 			name="ldap_action_delete_configuration" class="icon-delete icon-default-style"
23
-			title="<?php p($l->t('Delete the current configuration'));?>">&nbsp;</button>
23
+			title="<?php p($l->t('Delete the current configuration')); ?>">&nbsp;</button>
24 24
 		</p>
25 25
 
26 26
 		<div class="hostPortCombinator">
@@ -29,14 +29,14 @@  discard block
 block discarded – undo
29 29
 					<div class="table">
30 30
 						<input type="text" class="host" id="ldap_host"
31 31
 							name="ldap_host"
32
-							placeholder="<?php p($l->t('Host'));?>"
33
-							title="<?php p($l->t('You can omit the protocol, unless you require SSL. If so, start with ldaps://'));?>"
32
+							placeholder="<?php p($l->t('Host')); ?>"
33
+							title="<?php p($l->t('You can omit the protocol, unless you require SSL. If so, start with ldaps://')); ?>"
34 34
 							/>
35 35
 						<span class="hostPortCombinatorSpan">
36 36
 							<input type="number" id="ldap_port" name="ldap_port"
37
-								placeholder="<?php p($l->t('Port'));?>" />
37
+								placeholder="<?php p($l->t('Port')); ?>" />
38 38
 							<button class="ldapDetectPort" name="ldapDetectPort" type="button">
39
-								<?php p($l->t('Detect Port'));?>
39
+								<?php p($l->t('Detect Port')); ?>
40 40
 							</button>
41 41
 						</span>
42 42
 					</div>
@@ -46,19 +46,19 @@  discard block
 block discarded – undo
46 46
 			<div class="tablerow">
47 47
 				<input type="text" id="ldap_dn" name="ldap_dn"
48 48
 				class="tablecell"
49
-				placeholder="<?php p($l->t('User DN'));?>" autocomplete="off"
50
-				title="<?php p($l->t('The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty.'));?>"
49
+				placeholder="<?php p($l->t('User DN')); ?>" autocomplete="off"
50
+				title="<?php p($l->t('The DN of the client user with which the bind shall be done, e.g. uid=agent,dc=example,dc=com. For anonymous access, leave DN and Password empty.')); ?>"
51 51
 				/>
52 52
 			</div>
53 53
 
54 54
 			<div class="tablerow">
55 55
 				<input type="password" id="ldap_agent_password"
56 56
 				class="tablecell" name="ldap_agent_password"
57
-				placeholder="<?php p($l->t('Password'));?>" autocomplete="off"
58
-				title="<?php p($l->t('For anonymous access, leave DN and Password empty.'));?>"
57
+				placeholder="<?php p($l->t('Password')); ?>" autocomplete="off"
58
+				title="<?php p($l->t('For anonymous access, leave DN and Password empty.')); ?>"
59 59
 				/>
60 60
 				<button class="ldapSaveAgentCredentials" name="ldapSaveAgentCredentials" type="button">
61
-					<?php p($l->t('Save Credentials'));?>
61
+					<?php p($l->t('Save Credentials')); ?>
62 62
 				</button>
63 63
 			</div>
64 64
 			<div class="tablerow">&nbsp;</div>
@@ -66,24 +66,24 @@  discard block
 block discarded – undo
66 66
 			<div class="tablerow">
67 67
 				<textarea id="ldap_base" name="ldap_base"
68 68
 					class="tablecell"
69
-					placeholder="<?php p($l->t('One Base DN per line'));?>"
70
-					title="<?php p($l->t('You can specify Base DN for users and groups in the Advanced tab'));?>">
69
+					placeholder="<?php p($l->t('One Base DN per line')); ?>"
70
+					title="<?php p($l->t('You can specify Base DN for users and groups in the Advanced tab')); ?>">
71 71
 				</textarea>
72 72
 				<button class="ldapDetectBase" name="ldapDetectBase" type="button">
73
-					<?php p($l->t('Detect Base DN'));?>
73
+					<?php p($l->t('Detect Base DN')); ?>
74 74
 				</button>
75 75
 				<button class="ldapTestBase" name="ldapTestBase" type="button">
76
-					<?php p($l->t('Test Base DN'));?>
76
+					<?php p($l->t('Test Base DN')); ?>
77 77
 				</button>
78 78
 			</div>
79 79
 
80 80
 			<div class="tablerow left">
81 81
 				<input type="checkbox" id="ldap_experienced_admin" value="1"
82 82
 					name="ldap_experienced_admin" class="tablecell"
83
-					title="<?php p($l->t('Avoids automatic LDAP requests. Better for bigger setups, but requires some LDAP knowledge.'));?>"
83
+					title="<?php p($l->t('Avoids automatic LDAP requests. Better for bigger setups, but requires some LDAP knowledge.')); ?>"
84 84
 					/>
85 85
 				<label for="ldap_experienced_admin" class="tablecell">
86
-					<?php p($l->t('Manually enter LDAP filters (recommended for large directories)'));?>
86
+					<?php p($l->t('Manually enter LDAP filters (recommended for large directories)')); ?>
87 87
 				</label>
88 88
 			</div>
89 89
 
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_Proxy.php 2 patches
Indentation   +223 added lines, -223 removed lines patch added patch discarded remove patch
@@ -30,251 +30,251 @@
 block discarded – undo
30 30
 use OCP\Group\Backend\IGetDisplayNameBackend;
31 31
 
32 32
 class Group_Proxy extends Proxy implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend {
33
-	private $backends = [];
34
-	private $refBackend = null;
33
+    private $backends = [];
34
+    private $refBackend = null;
35 35
 
36
-	/**
37
-	 * Constructor
38
-	 * @param string[] $serverConfigPrefixes array containing the config Prefixes
39
-	 */
40
-	public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
41
-		parent::__construct($ldap);
42
-		foreach($serverConfigPrefixes as $configPrefix) {
43
-			$this->backends[$configPrefix] =
44
-				new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
45
-			if(is_null($this->refBackend)) {
46
-				$this->refBackend = &$this->backends[$configPrefix];
47
-			}
48
-		}
49
-	}
36
+    /**
37
+     * Constructor
38
+     * @param string[] $serverConfigPrefixes array containing the config Prefixes
39
+     */
40
+    public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
41
+        parent::__construct($ldap);
42
+        foreach($serverConfigPrefixes as $configPrefix) {
43
+            $this->backends[$configPrefix] =
44
+                new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
45
+            if(is_null($this->refBackend)) {
46
+                $this->refBackend = &$this->backends[$configPrefix];
47
+            }
48
+        }
49
+    }
50 50
 
51
-	/**
52
-	 * Tries the backends one after the other until a positive result is returned from the specified method
53
-	 * @param string $gid the gid connected to the request
54
-	 * @param string $method the method of the group backend that shall be called
55
-	 * @param array $parameters an array of parameters to be passed
56
-	 * @return mixed, the result of the method or false
57
-	 */
58
-	protected function walkBackends($gid, $method, $parameters) {
59
-		$cacheKey = $this->getGroupCacheKey($gid);
60
-		foreach($this->backends as $configPrefix => $backend) {
61
-			if($result = call_user_func_array([$backend, $method], $parameters)) {
62
-				$this->writeToCache($cacheKey, $configPrefix);
63
-				return $result;
64
-			}
65
-		}
66
-		return false;
67
-	}
51
+    /**
52
+     * Tries the backends one after the other until a positive result is returned from the specified method
53
+     * @param string $gid the gid connected to the request
54
+     * @param string $method the method of the group backend that shall be called
55
+     * @param array $parameters an array of parameters to be passed
56
+     * @return mixed, the result of the method or false
57
+     */
58
+    protected function walkBackends($gid, $method, $parameters) {
59
+        $cacheKey = $this->getGroupCacheKey($gid);
60
+        foreach($this->backends as $configPrefix => $backend) {
61
+            if($result = call_user_func_array([$backend, $method], $parameters)) {
62
+                $this->writeToCache($cacheKey, $configPrefix);
63
+                return $result;
64
+            }
65
+        }
66
+        return false;
67
+    }
68 68
 
69
-	/**
70
-	 * Asks the backend connected to the server that supposely takes care of the gid from the request.
71
-	 * @param string $gid the gid connected to the request
72
-	 * @param string $method the method of the group backend that shall be called
73
-	 * @param array $parameters an array of parameters to be passed
74
-	 * @param mixed $passOnWhen the result matches this variable
75
-	 * @return mixed, the result of the method or false
76
-	 */
77
-	protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) {
78
-		$cacheKey = $this->getGroupCacheKey($gid);
79
-		$prefix = $this->getFromCache($cacheKey);
80
-		//in case the uid has been found in the past, try this stored connection first
81
-		if(!is_null($prefix)) {
82
-			if(isset($this->backends[$prefix])) {
83
-				$result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
84
-				if($result === $passOnWhen) {
85
-					//not found here, reset cache to null if group vanished
86
-					//because sometimes methods return false with a reason
87
-					$groupExists = call_user_func_array(
88
-						[$this->backends[$prefix], 'groupExists'],
89
-						[$gid]
90
-					);
91
-					if(!$groupExists) {
92
-						$this->writeToCache($cacheKey, null);
93
-					}
94
-				}
95
-				return $result;
96
-			}
97
-		}
98
-		return false;
99
-	}
69
+    /**
70
+     * Asks the backend connected to the server that supposely takes care of the gid from the request.
71
+     * @param string $gid the gid connected to the request
72
+     * @param string $method the method of the group backend that shall be called
73
+     * @param array $parameters an array of parameters to be passed
74
+     * @param mixed $passOnWhen the result matches this variable
75
+     * @return mixed, the result of the method or false
76
+     */
77
+    protected function callOnLastSeenOn($gid, $method, $parameters, $passOnWhen) {
78
+        $cacheKey = $this->getGroupCacheKey($gid);
79
+        $prefix = $this->getFromCache($cacheKey);
80
+        //in case the uid has been found in the past, try this stored connection first
81
+        if(!is_null($prefix)) {
82
+            if(isset($this->backends[$prefix])) {
83
+                $result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
84
+                if($result === $passOnWhen) {
85
+                    //not found here, reset cache to null if group vanished
86
+                    //because sometimes methods return false with a reason
87
+                    $groupExists = call_user_func_array(
88
+                        [$this->backends[$prefix], 'groupExists'],
89
+                        [$gid]
90
+                    );
91
+                    if(!$groupExists) {
92
+                        $this->writeToCache($cacheKey, null);
93
+                    }
94
+                }
95
+                return $result;
96
+            }
97
+        }
98
+        return false;
99
+    }
100 100
 
101
-	/**
102
-	 * is user in group?
103
-	 * @param string $uid uid of the user
104
-	 * @param string $gid gid of the group
105
-	 * @return bool
106
-	 *
107
-	 * Checks whether the user is member of a group or not.
108
-	 */
109
-	public function inGroup($uid, $gid) {
110
-		return $this->handleRequest($gid, 'inGroup', [$uid, $gid]);
111
-	}
101
+    /**
102
+     * is user in group?
103
+     * @param string $uid uid of the user
104
+     * @param string $gid gid of the group
105
+     * @return bool
106
+     *
107
+     * Checks whether the user is member of a group or not.
108
+     */
109
+    public function inGroup($uid, $gid) {
110
+        return $this->handleRequest($gid, 'inGroup', [$uid, $gid]);
111
+    }
112 112
 
113
-	/**
114
-	 * Get all groups a user belongs to
115
-	 * @param string $uid Name of the user
116
-	 * @return string[] with group names
117
-	 *
118
-	 * This function fetches all groups a user belongs to. It does not check
119
-	 * if the user exists at all.
120
-	 */
121
-	public function getUserGroups($uid) {
122
-		$groups = [];
113
+    /**
114
+     * Get all groups a user belongs to
115
+     * @param string $uid Name of the user
116
+     * @return string[] with group names
117
+     *
118
+     * This function fetches all groups a user belongs to. It does not check
119
+     * if the user exists at all.
120
+     */
121
+    public function getUserGroups($uid) {
122
+        $groups = [];
123 123
 
124
-		foreach($this->backends as $backend) {
125
-			$backendGroups = $backend->getUserGroups($uid);
126
-			if (is_array($backendGroups)) {
127
-				$groups = array_merge($groups, $backendGroups);
128
-			}
129
-		}
124
+        foreach($this->backends as $backend) {
125
+            $backendGroups = $backend->getUserGroups($uid);
126
+            if (is_array($backendGroups)) {
127
+                $groups = array_merge($groups, $backendGroups);
128
+            }
129
+        }
130 130
 
131
-		return $groups;
132
-	}
131
+        return $groups;
132
+    }
133 133
 
134
-	/**
135
-	 * get a list of all users in a group
136
-	 * @return string[] with user ids
137
-	 */
138
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
139
-		$users = [];
134
+    /**
135
+     * get a list of all users in a group
136
+     * @return string[] with user ids
137
+     */
138
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
139
+        $users = [];
140 140
 
141
-		foreach($this->backends as $backend) {
142
-			$backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
143
-			if (is_array($backendUsers)) {
144
-				$users = array_merge($users, $backendUsers);
145
-			}
146
-		}
141
+        foreach($this->backends as $backend) {
142
+            $backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
143
+            if (is_array($backendUsers)) {
144
+                $users = array_merge($users, $backendUsers);
145
+            }
146
+        }
147 147
 
148
-		return $users;
149
-	}
148
+        return $users;
149
+    }
150 150
 
151
-	/**
152
-	 * @param string $gid
153
-	 * @return bool
154
-	 */
155
-	public function createGroup($gid) {
156
-		return $this->handleRequest(
157
-			$gid, 'createGroup', [$gid]);
158
-	}
151
+    /**
152
+     * @param string $gid
153
+     * @return bool
154
+     */
155
+    public function createGroup($gid) {
156
+        return $this->handleRequest(
157
+            $gid, 'createGroup', [$gid]);
158
+    }
159 159
 
160
-	/**
161
-	 * delete a group
162
-	 * @param string $gid gid of the group to delete
163
-	 * @return bool
164
-	 */
165
-	public function deleteGroup($gid) {
166
-		return $this->handleRequest(
167
-			$gid, 'deleteGroup', [$gid]);
168
-	}
160
+    /**
161
+     * delete a group
162
+     * @param string $gid gid of the group to delete
163
+     * @return bool
164
+     */
165
+    public function deleteGroup($gid) {
166
+        return $this->handleRequest(
167
+            $gid, 'deleteGroup', [$gid]);
168
+    }
169 169
 
170
-	/**
171
-	 * Add a user to a group
172
-	 * @param string $uid Name of the user to add to group
173
-	 * @param string $gid Name of the group in which add the user
174
-	 * @return bool
175
-	 *
176
-	 * Adds a user to a group.
177
-	 */
178
-	public function addToGroup($uid, $gid) {
179
-		return $this->handleRequest(
180
-			$gid, 'addToGroup', [$uid, $gid]);
181
-	}
170
+    /**
171
+     * Add a user to a group
172
+     * @param string $uid Name of the user to add to group
173
+     * @param string $gid Name of the group in which add the user
174
+     * @return bool
175
+     *
176
+     * Adds a user to a group.
177
+     */
178
+    public function addToGroup($uid, $gid) {
179
+        return $this->handleRequest(
180
+            $gid, 'addToGroup', [$uid, $gid]);
181
+    }
182 182
 
183
-	/**
184
-	 * Removes a user from a group
185
-	 * @param string $uid Name of the user to remove from group
186
-	 * @param string $gid Name of the group from which remove the user
187
-	 * @return bool
188
-	 *
189
-	 * removes the user from a group.
190
-	 */
191
-	public function removeFromGroup($uid, $gid) {
192
-		return $this->handleRequest(
193
-			$gid, 'removeFromGroup', [$uid, $gid]);
194
-	}
183
+    /**
184
+     * Removes a user from a group
185
+     * @param string $uid Name of the user to remove from group
186
+     * @param string $gid Name of the group from which remove the user
187
+     * @return bool
188
+     *
189
+     * removes the user from a group.
190
+     */
191
+    public function removeFromGroup($uid, $gid) {
192
+        return $this->handleRequest(
193
+            $gid, 'removeFromGroup', [$uid, $gid]);
194
+    }
195 195
 
196
-	/**
197
-	 * returns the number of users in a group, who match the search term
198
-	 * @param string $gid the internal group name
199
-	 * @param string $search optional, a search string
200
-	 * @return int|bool
201
-	 */
202
-	public function countUsersInGroup($gid, $search = '') {
203
-		return $this->handleRequest(
204
-			$gid, 'countUsersInGroup', [$gid, $search]);
205
-	}
196
+    /**
197
+     * returns the number of users in a group, who match the search term
198
+     * @param string $gid the internal group name
199
+     * @param string $search optional, a search string
200
+     * @return int|bool
201
+     */
202
+    public function countUsersInGroup($gid, $search = '') {
203
+        return $this->handleRequest(
204
+            $gid, 'countUsersInGroup', [$gid, $search]);
205
+    }
206 206
 
207
-	/**
208
-	 * get an array with group details
209
-	 * @param string $gid
210
-	 * @return array|false
211
-	 */
212
-	public function getGroupDetails($gid) {
213
-		return $this->handleRequest(
214
-			$gid, 'getGroupDetails', [$gid]);
215
-	}
207
+    /**
208
+     * get an array with group details
209
+     * @param string $gid
210
+     * @return array|false
211
+     */
212
+    public function getGroupDetails($gid) {
213
+        return $this->handleRequest(
214
+            $gid, 'getGroupDetails', [$gid]);
215
+    }
216 216
 
217
-	/**
218
-	 * get a list of all groups
219
-	 * @return string[] with group names
220
-	 *
221
-	 * Returns a list with all groups
222
-	 */
223
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
224
-		$groups = [];
217
+    /**
218
+     * get a list of all groups
219
+     * @return string[] with group names
220
+     *
221
+     * Returns a list with all groups
222
+     */
223
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
224
+        $groups = [];
225 225
 
226
-		foreach($this->backends as $backend) {
227
-			$backendGroups = $backend->getGroups($search, $limit, $offset);
228
-			if (is_array($backendGroups)) {
229
-				$groups = array_merge($groups, $backendGroups);
230
-			}
231
-		}
226
+        foreach($this->backends as $backend) {
227
+            $backendGroups = $backend->getGroups($search, $limit, $offset);
228
+            if (is_array($backendGroups)) {
229
+                $groups = array_merge($groups, $backendGroups);
230
+            }
231
+        }
232 232
 
233
-		return $groups;
234
-	}
233
+        return $groups;
234
+    }
235 235
 
236
-	/**
237
-	 * check if a group exists
238
-	 * @param string $gid
239
-	 * @return bool
240
-	 */
241
-	public function groupExists($gid) {
242
-		return $this->handleRequest($gid, 'groupExists', [$gid]);
243
-	}
236
+    /**
237
+     * check if a group exists
238
+     * @param string $gid
239
+     * @return bool
240
+     */
241
+    public function groupExists($gid) {
242
+        return $this->handleRequest($gid, 'groupExists', [$gid]);
243
+    }
244 244
 
245
-	/**
246
-	 * Check if backend implements actions
247
-	 * @param int $actions bitwise-or'ed actions
248
-	 * @return boolean
249
-	 *
250
-	 * Returns the supported actions as int to be
251
-	 * compared with \OCP\GroupInterface::CREATE_GROUP etc.
252
-	 */
253
-	public function implementsActions($actions) {
254
-		//it's the same across all our user backends obviously
255
-		return $this->refBackend->implementsActions($actions);
256
-	}
245
+    /**
246
+     * Check if backend implements actions
247
+     * @param int $actions bitwise-or'ed actions
248
+     * @return boolean
249
+     *
250
+     * Returns the supported actions as int to be
251
+     * compared with \OCP\GroupInterface::CREATE_GROUP etc.
252
+     */
253
+    public function implementsActions($actions) {
254
+        //it's the same across all our user backends obviously
255
+        return $this->refBackend->implementsActions($actions);
256
+    }
257 257
 
258
-	/**
259
-	 * Return access for LDAP interaction.
260
-	 * @param string $gid
261
-	 * @return Access instance of Access for LDAP interaction
262
-	 */
263
-	public function getLDAPAccess($gid) {
264
-		return $this->handleRequest($gid, 'getLDAPAccess', [$gid]);
265
-	}
258
+    /**
259
+     * Return access for LDAP interaction.
260
+     * @param string $gid
261
+     * @return Access instance of Access for LDAP interaction
262
+     */
263
+    public function getLDAPAccess($gid) {
264
+        return $this->handleRequest($gid, 'getLDAPAccess', [$gid]);
265
+    }
266 266
 
267
-	/**
268
-	 * Return a new LDAP connection for the specified group.
269
-	 * The connection needs to be closed manually.
270
-	 * @param string $gid
271
-	 * @return resource of the LDAP connection
272
-	 */
273
-	public function getNewLDAPConnection($gid) {
274
-		return $this->handleRequest($gid, 'getNewLDAPConnection', [$gid]);
275
-	}
267
+    /**
268
+     * Return a new LDAP connection for the specified group.
269
+     * The connection needs to be closed manually.
270
+     * @param string $gid
271
+     * @return resource of the LDAP connection
272
+     */
273
+    public function getNewLDAPConnection($gid) {
274
+        return $this->handleRequest($gid, 'getNewLDAPConnection', [$gid]);
275
+    }
276 276
 
277
-	public function getDisplayName(string $gid): string {
278
-		return $this->handleRequest($gid, 'getDisplayName', [$gid]);
279
-	}
277
+    public function getDisplayName(string $gid): string {
278
+        return $this->handleRequest($gid, 'getDisplayName', [$gid]);
279
+    }
280 280
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -39,10 +39,10 @@  discard block
 block discarded – undo
39 39
 	 */
40 40
 	public function __construct($serverConfigPrefixes, ILDAPWrapper $ldap, GroupPluginManager $groupPluginManager) {
41 41
 		parent::__construct($ldap);
42
-		foreach($serverConfigPrefixes as $configPrefix) {
42
+		foreach ($serverConfigPrefixes as $configPrefix) {
43 43
 			$this->backends[$configPrefix] =
44 44
 				new \OCA\User_LDAP\Group_LDAP($this->getAccess($configPrefix), $groupPluginManager);
45
-			if(is_null($this->refBackend)) {
45
+			if (is_null($this->refBackend)) {
46 46
 				$this->refBackend = &$this->backends[$configPrefix];
47 47
 			}
48 48
 		}
@@ -57,8 +57,8 @@  discard block
 block discarded – undo
57 57
 	 */
58 58
 	protected function walkBackends($gid, $method, $parameters) {
59 59
 		$cacheKey = $this->getGroupCacheKey($gid);
60
-		foreach($this->backends as $configPrefix => $backend) {
61
-			if($result = call_user_func_array([$backend, $method], $parameters)) {
60
+		foreach ($this->backends as $configPrefix => $backend) {
61
+			if ($result = call_user_func_array([$backend, $method], $parameters)) {
62 62
 				$this->writeToCache($cacheKey, $configPrefix);
63 63
 				return $result;
64 64
 			}
@@ -78,17 +78,17 @@  discard block
 block discarded – undo
78 78
 		$cacheKey = $this->getGroupCacheKey($gid);
79 79
 		$prefix = $this->getFromCache($cacheKey);
80 80
 		//in case the uid has been found in the past, try this stored connection first
81
-		if(!is_null($prefix)) {
82
-			if(isset($this->backends[$prefix])) {
81
+		if (!is_null($prefix)) {
82
+			if (isset($this->backends[$prefix])) {
83 83
 				$result = call_user_func_array([$this->backends[$prefix], $method], $parameters);
84
-				if($result === $passOnWhen) {
84
+				if ($result === $passOnWhen) {
85 85
 					//not found here, reset cache to null if group vanished
86 86
 					//because sometimes methods return false with a reason
87 87
 					$groupExists = call_user_func_array(
88 88
 						[$this->backends[$prefix], 'groupExists'],
89 89
 						[$gid]
90 90
 					);
91
-					if(!$groupExists) {
91
+					if (!$groupExists) {
92 92
 						$this->writeToCache($cacheKey, null);
93 93
 					}
94 94
 				}
@@ -121,7 +121,7 @@  discard block
 block discarded – undo
121 121
 	public function getUserGroups($uid) {
122 122
 		$groups = [];
123 123
 
124
-		foreach($this->backends as $backend) {
124
+		foreach ($this->backends as $backend) {
125 125
 			$backendGroups = $backend->getUserGroups($uid);
126 126
 			if (is_array($backendGroups)) {
127 127
 				$groups = array_merge($groups, $backendGroups);
@@ -138,7 +138,7 @@  discard block
 block discarded – undo
138 138
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
139 139
 		$users = [];
140 140
 
141
-		foreach($this->backends as $backend) {
141
+		foreach ($this->backends as $backend) {
142 142
 			$backendUsers = $backend->usersInGroup($gid, $search, $limit, $offset);
143 143
 			if (is_array($backendUsers)) {
144 144
 				$users = array_merge($users, $backendUsers);
@@ -223,7 +223,7 @@  discard block
 block discarded – undo
223 223
 	public function getGroups($search = '', $limit = -1, $offset = 0) {
224 224
 		$groups = [];
225 225
 
226
-		foreach($this->backends as $backend) {
226
+		foreach ($this->backends as $backend) {
227 227
 			$backendGroups = $backend->getGroups($search, $limit, $offset);
228 228
 			if (is_array($backendGroups)) {
229 229
 				$groups = array_merge($groups, $backendGroups);
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/ShowConfig.php 2 patches
Indentation   +67 added lines, -67 removed lines patch added patch discarded remove patch
@@ -36,77 +36,77 @@
 block discarded – undo
36 36
 use Symfony\Component\Console\Output\OutputInterface;
37 37
 
38 38
 class ShowConfig extends Command {
39
-	/** @var \OCA\User_LDAP\Helper */
40
-	protected $helper;
39
+    /** @var \OCA\User_LDAP\Helper */
40
+    protected $helper;
41 41
 
42
-	/**
43
-	 * @param Helper $helper
44
-	 */
45
-	public function __construct(Helper $helper) {
46
-		$this->helper = $helper;
47
-		parent::__construct();
48
-	}
42
+    /**
43
+     * @param Helper $helper
44
+     */
45
+    public function __construct(Helper $helper) {
46
+        $this->helper = $helper;
47
+        parent::__construct();
48
+    }
49 49
 
50
-	protected function configure() {
51
-		$this
52
-			->setName('ldap:show-config')
53
-			->setDescription('shows the LDAP configuration')
54
-			->addArgument(
55
-					'configID',
56
-					InputArgument::OPTIONAL,
57
-					'will show the configuration of the specified id'
58
-				     )
59
-			->addOption(
60
-					'show-password',
61
-					null,
62
-					InputOption::VALUE_NONE,
63
-					'show ldap bind password'
64
-				     )
65
-		;
66
-	}
50
+    protected function configure() {
51
+        $this
52
+            ->setName('ldap:show-config')
53
+            ->setDescription('shows the LDAP configuration')
54
+            ->addArgument(
55
+                    'configID',
56
+                    InputArgument::OPTIONAL,
57
+                    'will show the configuration of the specified id'
58
+                        )
59
+            ->addOption(
60
+                    'show-password',
61
+                    null,
62
+                    InputOption::VALUE_NONE,
63
+                    'show ldap bind password'
64
+                        )
65
+        ;
66
+    }
67 67
 
68
-	protected function execute(InputInterface $input, OutputInterface $output) {
69
-		$availableConfigs = $this->helper->getServerConfigurationPrefixes();
70
-		$configID = $input->getArgument('configID');
71
-		if(!is_null($configID)) {
72
-			$configIDs[] = $configID;
73
-			if(!in_array($configIDs[0], $availableConfigs)) {
74
-				$output->writeln("Invalid configID");
75
-				return;
76
-			}
77
-		} else {
78
-			$configIDs = $availableConfigs;
79
-		}
68
+    protected function execute(InputInterface $input, OutputInterface $output) {
69
+        $availableConfigs = $this->helper->getServerConfigurationPrefixes();
70
+        $configID = $input->getArgument('configID');
71
+        if(!is_null($configID)) {
72
+            $configIDs[] = $configID;
73
+            if(!in_array($configIDs[0], $availableConfigs)) {
74
+                $output->writeln("Invalid configID");
75
+                return;
76
+            }
77
+        } else {
78
+            $configIDs = $availableConfigs;
79
+        }
80 80
 
81
-		$this->renderConfigs($configIDs, $output, $input->getOption('show-password'));
82
-	}
81
+        $this->renderConfigs($configIDs, $output, $input->getOption('show-password'));
82
+    }
83 83
 
84
-	/**
85
-	 * prints the LDAP configuration(s)
86
-	 * @param string[] configID(s)
87
-	 * @param OutputInterface $output
88
-	 * @param bool $withPassword      Set to TRUE to show plaintext passwords in output
89
-	 */
90
-	protected function renderConfigs($configIDs, $output, $withPassword) {
91
-		foreach($configIDs as $id) {
92
-			$configHolder = new Configuration($id);
93
-			$configuration = $configHolder->getConfiguration();
94
-			ksort($configuration);
84
+    /**
85
+     * prints the LDAP configuration(s)
86
+     * @param string[] configID(s)
87
+     * @param OutputInterface $output
88
+     * @param bool $withPassword      Set to TRUE to show plaintext passwords in output
89
+     */
90
+    protected function renderConfigs($configIDs, $output, $withPassword) {
91
+        foreach($configIDs as $id) {
92
+            $configHolder = new Configuration($id);
93
+            $configuration = $configHolder->getConfiguration();
94
+            ksort($configuration);
95 95
 
96
-			$table = new Table($output);
97
-			$table->setHeaders(['Configuration', $id]);
98
-			$rows = [];
99
-			foreach($configuration as $key => $value) {
100
-				if($key === 'ldapAgentPassword' && !$withPassword) {
101
-					$value = '***';
102
-				}
103
-				if(is_array($value)) {
104
-					$value = implode(';', $value);
105
-				}
106
-				$rows[] = [$key, $value];
107
-			}
108
-			$table->setRows($rows);
109
-			$table->render($output);
110
-		}
111
-	}
96
+            $table = new Table($output);
97
+            $table->setHeaders(['Configuration', $id]);
98
+            $rows = [];
99
+            foreach($configuration as $key => $value) {
100
+                if($key === 'ldapAgentPassword' && !$withPassword) {
101
+                    $value = '***';
102
+                }
103
+                if(is_array($value)) {
104
+                    $value = implode(';', $value);
105
+                }
106
+                $rows[] = [$key, $value];
107
+            }
108
+            $table->setRows($rows);
109
+            $table->render($output);
110
+        }
111
+    }
112 112
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -68,9 +68,9 @@  discard block
 block discarded – undo
68 68
 	protected function execute(InputInterface $input, OutputInterface $output) {
69 69
 		$availableConfigs = $this->helper->getServerConfigurationPrefixes();
70 70
 		$configID = $input->getArgument('configID');
71
-		if(!is_null($configID)) {
71
+		if (!is_null($configID)) {
72 72
 			$configIDs[] = $configID;
73
-			if(!in_array($configIDs[0], $availableConfigs)) {
73
+			if (!in_array($configIDs[0], $availableConfigs)) {
74 74
 				$output->writeln("Invalid configID");
75 75
 				return;
76 76
 			}
@@ -88,7 +88,7 @@  discard block
 block discarded – undo
88 88
 	 * @param bool $withPassword      Set to TRUE to show plaintext passwords in output
89 89
 	 */
90 90
 	protected function renderConfigs($configIDs, $output, $withPassword) {
91
-		foreach($configIDs as $id) {
91
+		foreach ($configIDs as $id) {
92 92
 			$configHolder = new Configuration($id);
93 93
 			$configuration = $configHolder->getConfiguration();
94 94
 			ksort($configuration);
@@ -96,11 +96,11 @@  discard block
 block discarded – undo
96 96
 			$table = new Table($output);
97 97
 			$table->setHeaders(['Configuration', $id]);
98 98
 			$rows = [];
99
-			foreach($configuration as $key => $value) {
100
-				if($key === 'ldapAgentPassword' && !$withPassword) {
99
+			foreach ($configuration as $key => $value) {
100
+				if ($key === 'ldapAgentPassword' && !$withPassword) {
101 101
 					$value = '***';
102 102
 				}
103
-				if(is_array($value)) {
103
+				if (is_array($value)) {
104 104
 					$value = implode(';', $value);
105 105
 				}
106 106
 				$rows[] = [$key, $value];
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/TestConfig.php 2 patches
Indentation   +50 added lines, -50 removed lines patch added patch discarded remove patch
@@ -35,59 +35,59 @@
 block discarded – undo
35 35
 
36 36
 class TestConfig extends Command {
37 37
 
38
-	protected function configure() {
39
-		$this
40
-			->setName('ldap:test-config')
41
-			->setDescription('tests an LDAP configuration')
42
-			->addArgument(
43
-					'configID',
44
-					InputArgument::REQUIRED,
45
-					'the configuration ID'
46
-				     )
47
-		;
48
-	}
38
+    protected function configure() {
39
+        $this
40
+            ->setName('ldap:test-config')
41
+            ->setDescription('tests an LDAP configuration')
42
+            ->addArgument(
43
+                    'configID',
44
+                    InputArgument::REQUIRED,
45
+                    'the configuration ID'
46
+                        )
47
+        ;
48
+    }
49 49
 
50
-	protected function execute(InputInterface $input, OutputInterface $output) {
51
-		$helper = new Helper(\OC::$server->getConfig());
52
-		$availableConfigs = $helper->getServerConfigurationPrefixes();
53
-		$configID = $input->getArgument('configID');
54
-		if(!in_array($configID, $availableConfigs)) {
55
-			$output->writeln("Invalid configID");
56
-			return;
57
-		}
50
+    protected function execute(InputInterface $input, OutputInterface $output) {
51
+        $helper = new Helper(\OC::$server->getConfig());
52
+        $availableConfigs = $helper->getServerConfigurationPrefixes();
53
+        $configID = $input->getArgument('configID');
54
+        if(!in_array($configID, $availableConfigs)) {
55
+            $output->writeln("Invalid configID");
56
+            return;
57
+        }
58 58
 
59
-		$result = $this->testConfig($configID);
60
-		if($result === 0) {
61
-			$output->writeln('The configuration is valid and the connection could be established!');
62
-		} else if($result === 1) {
63
-			$output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
64
-		} else if($result === 2) {
65
-			$output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.');
66
-		} else {
67
-			$output->writeln('Your LDAP server was kidnapped by aliens.');
68
-		}
69
-	}
59
+        $result = $this->testConfig($configID);
60
+        if($result === 0) {
61
+            $output->writeln('The configuration is valid and the connection could be established!');
62
+        } else if($result === 1) {
63
+            $output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
64
+        } else if($result === 2) {
65
+            $output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.');
66
+        } else {
67
+            $output->writeln('Your LDAP server was kidnapped by aliens.');
68
+        }
69
+    }
70 70
 
71
-	/**
72
-	 * tests the specified connection
73
-	 * @param string $configID
74
-	 * @return int
75
-	 */
76
-	protected function testConfig($configID) {
77
-		$lw = new \OCA\User_LDAP\LDAP();
78
-		$connection = new Connection($lw, $configID);
71
+    /**
72
+     * tests the specified connection
73
+     * @param string $configID
74
+     * @return int
75
+     */
76
+    protected function testConfig($configID) {
77
+        $lw = new \OCA\User_LDAP\LDAP();
78
+        $connection = new Connection($lw, $configID);
79 79
 
80
-		//ensure validation is run before we attempt the bind
81
-		$connection->getConfiguration();
80
+        //ensure validation is run before we attempt the bind
81
+        $connection->getConfiguration();
82 82
 
83
-		if(!$connection->setConfiguration([
84
-			'ldap_configuration_active' => 1,
85
-		])) {
86
-			return 1;
87
-		}
88
-		if($connection->bind()) {
89
-			return 0;
90
-		}
91
-		return 2;
92
-	}
83
+        if(!$connection->setConfiguration([
84
+            'ldap_configuration_active' => 1,
85
+        ])) {
86
+            return 1;
87
+        }
88
+        if($connection->bind()) {
89
+            return 0;
90
+        }
91
+        return 2;
92
+    }
93 93
 }
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -51,17 +51,17 @@  discard block
 block discarded – undo
51 51
 		$helper = new Helper(\OC::$server->getConfig());
52 52
 		$availableConfigs = $helper->getServerConfigurationPrefixes();
53 53
 		$configID = $input->getArgument('configID');
54
-		if(!in_array($configID, $availableConfigs)) {
54
+		if (!in_array($configID, $availableConfigs)) {
55 55
 			$output->writeln("Invalid configID");
56 56
 			return;
57 57
 		}
58 58
 
59 59
 		$result = $this->testConfig($configID);
60
-		if($result === 0) {
60
+		if ($result === 0) {
61 61
 			$output->writeln('The configuration is valid and the connection could be established!');
62
-		} else if($result === 1) {
62
+		} else if ($result === 1) {
63 63
 			$output->writeln('The configuration is invalid. Please have a look at the logs for further details.');
64
-		} else if($result === 2) {
64
+		} else if ($result === 2) {
65 65
 			$output->writeln('The configuration is valid, but the Bind failed. Please check the server settings and credentials.');
66 66
 		} else {
67 67
 			$output->writeln('Your LDAP server was kidnapped by aliens.');
@@ -80,12 +80,12 @@  discard block
 block discarded – undo
80 80
 		//ensure validation is run before we attempt the bind
81 81
 		$connection->getConfiguration();
82 82
 
83
-		if(!$connection->setConfiguration([
83
+		if (!$connection->setConfiguration([
84 84
 			'ldap_configuration_active' => 1,
85 85
 		])) {
86 86
 			return 1;
87 87
 		}
88
-		if($connection->bind()) {
88
+		if ($connection->bind()) {
89 89
 			return 0;
90 90
 		}
91 91
 		return 2;
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/OfflineUser.php 2 patches
Indentation   +207 added lines, -207 removed lines patch added patch discarded remove patch
@@ -29,219 +29,219 @@
 block discarded – undo
29 29
 use OCP\IDBConnection;
30 30
 
31 31
 class OfflineUser {
32
-	/**
33
-	 * @var string $ocName
34
-	 */
35
-	protected $ocName;
36
-	/**
37
-	 * @var string $dn
38
-	 */
39
-	protected $dn;
40
-	/**
41
-	 * @var string $uid the UID as provided by LDAP
42
-	 */
43
-	protected $uid;
44
-	/**
45
-	 * @var string $displayName
46
-	 */
47
-	protected $displayName;
48
-	/**
49
-	 * @var string $homePath
50
-	 */
51
-	protected $homePath;
52
-	/**
53
-	 * @var string $lastLogin the timestamp of the last login
54
-	 */
55
-	protected $lastLogin;
56
-	/**
57
-	 * @var string $foundDeleted the timestamp when the user was detected as unavailable
58
-	 */
59
-	protected $foundDeleted;
60
-	/**
61
-	 * @var string $email
62
-	 */
63
-	protected $email;
64
-	/**
65
-	 * @var bool $hasActiveShares
66
-	 */
67
-	protected $hasActiveShares;
68
-	/**
69
-	 * @var IConfig $config
70
-	 */
71
-	protected $config;
72
-	/**
73
-	 * @var IDBConnection $db
74
-	 */
75
-	protected $db;
76
-	/**
77
-	 * @var \OCA\User_LDAP\Mapping\UserMapping
78
-	 */
79
-	protected $mapping;
80
-
81
-	/**
82
-	 * @param string $ocName
83
-	 * @param IConfig $config
84
-	 * @param IDBConnection $db
85
-	 * @param \OCA\User_LDAP\Mapping\UserMapping $mapping
86
-	 */
87
-	public function __construct($ocName, IConfig $config, IDBConnection $db, UserMapping $mapping) {
88
-		$this->ocName = $ocName;
89
-		$this->config = $config;
90
-		$this->db = $db;
91
-		$this->mapping = $mapping;
92
-		$this->fetchDetails();
93
-	}
94
-
95
-	/**
96
-	 * remove the Delete-flag from the user.
97
-	 */
98
-	public function unmark() {
99
-		$this->config->deleteUserValue($this->ocName, 'user_ldap', 'isDeleted');
100
-		$this->config->deleteUserValue($this->ocName, 'user_ldap', 'foundDeleted');
101
-	}
102
-
103
-	/**
104
-	 * exports the user details in an assoc array
105
-	 * @return array
106
-	 */
107
-	public function export() {
108
-		$data = [];
109
-		$data['ocName'] = $this->getOCName();
110
-		$data['dn'] = $this->getDN();
111
-		$data['uid'] = $this->getUID();
112
-		$data['displayName'] = $this->getDisplayName();
113
-		$data['homePath'] = $this->getHomePath();
114
-		$data['lastLogin'] = $this->getLastLogin();
115
-		$data['email'] = $this->getEmail();
116
-		$data['hasActiveShares'] = $this->getHasActiveShares();
117
-
118
-		return $data;
119
-	}
120
-
121
-	/**
122
-	 * getter for Nextcloud internal name
123
-	 * @return string
124
-	 */
125
-	public function getOCName() {
126
-		return $this->ocName;
127
-	}
128
-
129
-	/**
130
-	 * getter for LDAP uid
131
-	 * @return string
132
-	 */
133
-	public function getUID() {
134
-		return $this->uid;
135
-	}
136
-
137
-	/**
138
-	 * getter for LDAP DN
139
-	 * @return string
140
-	 */
141
-	public function getDN() {
142
-		return $this->dn;
143
-	}
144
-
145
-	/**
146
-	 * getter for display name
147
-	 * @return string
148
-	 */
149
-	public function getDisplayName() {
150
-		return $this->displayName;
151
-	}
152
-
153
-	/**
154
-	 * getter for email
155
-	 * @return string
156
-	 */
157
-	public function getEmail() {
158
-		return $this->email;
159
-	}
160
-
161
-	/**
162
-	 * getter for home directory path
163
-	 * @return string
164
-	 */
165
-	public function getHomePath() {
166
-		return $this->homePath;
167
-	}
168
-
169
-	/**
170
-	 * getter for the last login timestamp
171
-	 * @return int
172
-	 */
173
-	public function getLastLogin() {
174
-		return (int)$this->lastLogin;
175
-	}
176
-
177
-	/**
178
-	 * getter for the detection timestamp
179
-	 * @return int
180
-	 */
181
-	public function getDetectedOn() {
182
-		return (int)$this->foundDeleted;
183
-	}
184
-
185
-	/**
186
-	 * getter for having active shares
187
-	 * @return bool
188
-	 */
189
-	public function getHasActiveShares() {
190
-		return $this->hasActiveShares;
191
-	}
192
-
193
-	/**
194
-	 * reads the user details
195
-	 */
196
-	protected function fetchDetails() {
197
-		$properties = [
198
-			'displayName'  => 'user_ldap',
199
-			'uid'          => 'user_ldap',
200
-			'homePath'     => 'user_ldap',
201
-			'foundDeleted' => 'user_ldap',
202
-			'email'        => 'settings',
203
-			'lastLogin'    => 'login',
204
-		];
205
-		foreach($properties as $property => $app) {
206
-			$this->$property = $this->config->getUserValue($this->ocName, $app, $property, '');
207
-		}
208
-
209
-		$dn = $this->mapping->getDNByName($this->ocName);
210
-		$this->dn = ($dn !== false) ? $dn : '';
211
-
212
-		$this->determineShares();
213
-	}
214
-
215
-
216
-	/**
217
-	 * finds out whether the user has active shares. The result is stored in
218
-	 * $this->hasActiveShares
219
-	 */
220
-	protected function determineShares() {
221
-		$query = $this->db->prepare('
32
+    /**
33
+     * @var string $ocName
34
+     */
35
+    protected $ocName;
36
+    /**
37
+     * @var string $dn
38
+     */
39
+    protected $dn;
40
+    /**
41
+     * @var string $uid the UID as provided by LDAP
42
+     */
43
+    protected $uid;
44
+    /**
45
+     * @var string $displayName
46
+     */
47
+    protected $displayName;
48
+    /**
49
+     * @var string $homePath
50
+     */
51
+    protected $homePath;
52
+    /**
53
+     * @var string $lastLogin the timestamp of the last login
54
+     */
55
+    protected $lastLogin;
56
+    /**
57
+     * @var string $foundDeleted the timestamp when the user was detected as unavailable
58
+     */
59
+    protected $foundDeleted;
60
+    /**
61
+     * @var string $email
62
+     */
63
+    protected $email;
64
+    /**
65
+     * @var bool $hasActiveShares
66
+     */
67
+    protected $hasActiveShares;
68
+    /**
69
+     * @var IConfig $config
70
+     */
71
+    protected $config;
72
+    /**
73
+     * @var IDBConnection $db
74
+     */
75
+    protected $db;
76
+    /**
77
+     * @var \OCA\User_LDAP\Mapping\UserMapping
78
+     */
79
+    protected $mapping;
80
+
81
+    /**
82
+     * @param string $ocName
83
+     * @param IConfig $config
84
+     * @param IDBConnection $db
85
+     * @param \OCA\User_LDAP\Mapping\UserMapping $mapping
86
+     */
87
+    public function __construct($ocName, IConfig $config, IDBConnection $db, UserMapping $mapping) {
88
+        $this->ocName = $ocName;
89
+        $this->config = $config;
90
+        $this->db = $db;
91
+        $this->mapping = $mapping;
92
+        $this->fetchDetails();
93
+    }
94
+
95
+    /**
96
+     * remove the Delete-flag from the user.
97
+     */
98
+    public function unmark() {
99
+        $this->config->deleteUserValue($this->ocName, 'user_ldap', 'isDeleted');
100
+        $this->config->deleteUserValue($this->ocName, 'user_ldap', 'foundDeleted');
101
+    }
102
+
103
+    /**
104
+     * exports the user details in an assoc array
105
+     * @return array
106
+     */
107
+    public function export() {
108
+        $data = [];
109
+        $data['ocName'] = $this->getOCName();
110
+        $data['dn'] = $this->getDN();
111
+        $data['uid'] = $this->getUID();
112
+        $data['displayName'] = $this->getDisplayName();
113
+        $data['homePath'] = $this->getHomePath();
114
+        $data['lastLogin'] = $this->getLastLogin();
115
+        $data['email'] = $this->getEmail();
116
+        $data['hasActiveShares'] = $this->getHasActiveShares();
117
+
118
+        return $data;
119
+    }
120
+
121
+    /**
122
+     * getter for Nextcloud internal name
123
+     * @return string
124
+     */
125
+    public function getOCName() {
126
+        return $this->ocName;
127
+    }
128
+
129
+    /**
130
+     * getter for LDAP uid
131
+     * @return string
132
+     */
133
+    public function getUID() {
134
+        return $this->uid;
135
+    }
136
+
137
+    /**
138
+     * getter for LDAP DN
139
+     * @return string
140
+     */
141
+    public function getDN() {
142
+        return $this->dn;
143
+    }
144
+
145
+    /**
146
+     * getter for display name
147
+     * @return string
148
+     */
149
+    public function getDisplayName() {
150
+        return $this->displayName;
151
+    }
152
+
153
+    /**
154
+     * getter for email
155
+     * @return string
156
+     */
157
+    public function getEmail() {
158
+        return $this->email;
159
+    }
160
+
161
+    /**
162
+     * getter for home directory path
163
+     * @return string
164
+     */
165
+    public function getHomePath() {
166
+        return $this->homePath;
167
+    }
168
+
169
+    /**
170
+     * getter for the last login timestamp
171
+     * @return int
172
+     */
173
+    public function getLastLogin() {
174
+        return (int)$this->lastLogin;
175
+    }
176
+
177
+    /**
178
+     * getter for the detection timestamp
179
+     * @return int
180
+     */
181
+    public function getDetectedOn() {
182
+        return (int)$this->foundDeleted;
183
+    }
184
+
185
+    /**
186
+     * getter for having active shares
187
+     * @return bool
188
+     */
189
+    public function getHasActiveShares() {
190
+        return $this->hasActiveShares;
191
+    }
192
+
193
+    /**
194
+     * reads the user details
195
+     */
196
+    protected function fetchDetails() {
197
+        $properties = [
198
+            'displayName'  => 'user_ldap',
199
+            'uid'          => 'user_ldap',
200
+            'homePath'     => 'user_ldap',
201
+            'foundDeleted' => 'user_ldap',
202
+            'email'        => 'settings',
203
+            'lastLogin'    => 'login',
204
+        ];
205
+        foreach($properties as $property => $app) {
206
+            $this->$property = $this->config->getUserValue($this->ocName, $app, $property, '');
207
+        }
208
+
209
+        $dn = $this->mapping->getDNByName($this->ocName);
210
+        $this->dn = ($dn !== false) ? $dn : '';
211
+
212
+        $this->determineShares();
213
+    }
214
+
215
+
216
+    /**
217
+     * finds out whether the user has active shares. The result is stored in
218
+     * $this->hasActiveShares
219
+     */
220
+    protected function determineShares() {
221
+        $query = $this->db->prepare('
222 222
 			SELECT COUNT(`uid_owner`)
223 223
 			FROM `*PREFIX*share`
224 224
 			WHERE `uid_owner` = ?
225 225
 		', 1);
226
-		$query->execute([$this->ocName]);
227
-		$sResult = $query->fetchColumn(0);
228
-		if((int)$sResult === 1) {
229
-			$this->hasActiveShares = true;
230
-			return;
231
-		}
232
-
233
-		$query = $this->db->prepare('
226
+        $query->execute([$this->ocName]);
227
+        $sResult = $query->fetchColumn(0);
228
+        if((int)$sResult === 1) {
229
+            $this->hasActiveShares = true;
230
+            return;
231
+        }
232
+
233
+        $query = $this->db->prepare('
234 234
 			SELECT COUNT(`owner`)
235 235
 			FROM `*PREFIX*share_external`
236 236
 			WHERE `owner` = ?
237 237
 		', 1);
238
-		$query->execute([$this->ocName]);
239
-		$sResult = $query->fetchColumn(0);
240
-		if((int)$sResult === 1) {
241
-			$this->hasActiveShares = true;
242
-			return;
243
-		}
244
-
245
-		$this->hasActiveShares = false;
246
-	}
238
+        $query->execute([$this->ocName]);
239
+        $sResult = $query->fetchColumn(0);
240
+        if((int)$sResult === 1) {
241
+            $this->hasActiveShares = true;
242
+            return;
243
+        }
244
+
245
+        $this->hasActiveShares = false;
246
+    }
247 247
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
 	 * @return int
172 172
 	 */
173 173
 	public function getLastLogin() {
174
-		return (int)$this->lastLogin;
174
+		return (int) $this->lastLogin;
175 175
 	}
176 176
 
177 177
 	/**
@@ -179,7 +179,7 @@  discard block
 block discarded – undo
179 179
 	 * @return int
180 180
 	 */
181 181
 	public function getDetectedOn() {
182
-		return (int)$this->foundDeleted;
182
+		return (int) $this->foundDeleted;
183 183
 	}
184 184
 
185 185
 	/**
@@ -202,7 +202,7 @@  discard block
 block discarded – undo
202 202
 			'email'        => 'settings',
203 203
 			'lastLogin'    => 'login',
204 204
 		];
205
-		foreach($properties as $property => $app) {
205
+		foreach ($properties as $property => $app) {
206 206
 			$this->$property = $this->config->getUserValue($this->ocName, $app, $property, '');
207 207
 		}
208 208
 
@@ -225,7 +225,7 @@  discard block
 block discarded – undo
225 225
 		', 1);
226 226
 		$query->execute([$this->ocName]);
227 227
 		$sResult = $query->fetchColumn(0);
228
-		if((int)$sResult === 1) {
228
+		if ((int) $sResult === 1) {
229 229
 			$this->hasActiveShares = true;
230 230
 			return;
231 231
 		}
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
 		', 1);
238 238
 		$query->execute([$this->ocName]);
239 239
 		$sResult = $query->fetchColumn(0);
240
-		if((int)$sResult === 1) {
240
+		if ((int) $sResult === 1) {
241 241
 			$this->hasActiveShares = true;
242 242
 			return;
243 243
 		}
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/User.php 2 patches
Indentation   +741 added lines, -741 removed lines patch added patch discarded remove patch
@@ -49,745 +49,745 @@
 block discarded – undo
49 49
  * represents an LDAP user, gets and holds user-specific information from LDAP
50 50
  */
51 51
 class User {
52
-	/**
53
-	 * @var Access
54
-	 */
55
-	protected $access;
56
-	/**
57
-	 * @var Connection
58
-	 */
59
-	protected $connection;
60
-	/**
61
-	 * @var IConfig
62
-	 */
63
-	protected $config;
64
-	/**
65
-	 * @var FilesystemHelper
66
-	 */
67
-	protected $fs;
68
-	/**
69
-	 * @var Image
70
-	 */
71
-	protected $image;
72
-	/**
73
-	 * @var LogWrapper
74
-	 */
75
-	protected $log;
76
-	/**
77
-	 * @var IAvatarManager
78
-	 */
79
-	protected $avatarManager;
80
-	/**
81
-	 * @var IUserManager
82
-	 */
83
-	protected $userManager;
84
-	/**
85
-	 * @var INotificationManager
86
-	 */
87
-	protected $notificationManager;
88
-	/**
89
-	 * @var string
90
-	 */
91
-	protected $dn;
92
-	/**
93
-	 * @var string
94
-	 */
95
-	protected $uid;
96
-	/**
97
-	 * @var string[]
98
-	 */
99
-	protected $refreshedFeatures = [];
100
-	/**
101
-	 * @var string
102
-	 */
103
-	protected $avatarImage;
104
-
105
-	/**
106
-	 * DB config keys for user preferences
107
-	 */
108
-	const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
109
-	const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
110
-
111
-	/**
112
-	 * @brief constructor, make sure the subclasses call this one!
113
-	 * @param string $username the internal username
114
-	 * @param string $dn the LDAP DN
115
-	 * @param Access $access
116
-	 * @param IConfig $config
117
-	 * @param FilesystemHelper $fs
118
-	 * @param Image $image any empty instance
119
-	 * @param LogWrapper $log
120
-	 * @param IAvatarManager $avatarManager
121
-	 * @param IUserManager $userManager
122
-	 * @param INotificationManager $notificationManager
123
-	 */
124
-	public function __construct($username, $dn, Access $access,
125
-		IConfig $config, FilesystemHelper $fs, Image $image,
126
-		LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
127
-		INotificationManager $notificationManager) {
128
-
129
-		if ($username === null) {
130
-			$log->log("uid for '$dn' must not be null!", ILogger::ERROR);
131
-			throw new \InvalidArgumentException('uid must not be null!');
132
-		} else if ($username === '') {
133
-			$log->log("uid for '$dn' must not be an empty string", ILogger::ERROR);
134
-			throw new \InvalidArgumentException('uid must not be an empty string!');
135
-		}
136
-
137
-		$this->access              = $access;
138
-		$this->connection          = $access->getConnection();
139
-		$this->config              = $config;
140
-		$this->fs                  = $fs;
141
-		$this->dn                  = $dn;
142
-		$this->uid                 = $username;
143
-		$this->image               = $image;
144
-		$this->log                 = $log;
145
-		$this->avatarManager       = $avatarManager;
146
-		$this->userManager         = $userManager;
147
-		$this->notificationManager = $notificationManager;
148
-
149
-		\OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
150
-	}
151
-
152
-	/**
153
-	 * @brief updates properties like email, quota or avatar provided by LDAP
154
-	 * @return null
155
-	 */
156
-	public function update() {
157
-		if(is_null($this->dn)) {
158
-			return null;
159
-		}
160
-
161
-		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
162
-				self::USER_PREFKEY_FIRSTLOGIN, 0);
163
-
164
-		if($this->needsRefresh()) {
165
-			$this->updateEmail();
166
-			$this->updateQuota();
167
-			if($hasLoggedIn !== 0) {
168
-				//we do not need to try it, when the user has not been logged in
169
-				//before, because the file system will not be ready.
170
-				$this->updateAvatar();
171
-				//in order to get an avatar as soon as possible, mark the user
172
-				//as refreshed only when updating the avatar did happen
173
-				$this->markRefreshTime();
174
-			}
175
-		}
176
-	}
177
-
178
-	/**
179
-	 * marks a user as deleted
180
-	 *
181
-	 * @throws \OCP\PreConditionNotMetException
182
-	 */
183
-	public function markUser() {
184
-		$curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
185
-		if($curValue === '1') {
186
-			// the user is already marked, do not write to DB again
187
-			return;
188
-		}
189
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
190
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
191
-	}
192
-
193
-	/**
194
-	 * processes results from LDAP for attributes as returned by getAttributesToRead()
195
-	 * @param array $ldapEntry the user entry as retrieved from LDAP
196
-	 */
197
-	public function processAttributes($ldapEntry) {
198
-		$this->markRefreshTime();
199
-		//Quota
200
-		$attr = strtolower($this->connection->ldapQuotaAttribute);
201
-		if(isset($ldapEntry[$attr])) {
202
-			$this->updateQuota($ldapEntry[$attr][0]);
203
-		} else {
204
-			if ($this->connection->ldapQuotaDefault !== '') {
205
-				$this->updateQuota();
206
-			}
207
-		}
208
-		unset($attr);
209
-
210
-		//displayName
211
-		$displayName = $displayName2 = '';
212
-		$attr = strtolower($this->connection->ldapUserDisplayName);
213
-		if(isset($ldapEntry[$attr])) {
214
-			$displayName = (string)$ldapEntry[$attr][0];
215
-		}
216
-		$attr = strtolower($this->connection->ldapUserDisplayName2);
217
-		if(isset($ldapEntry[$attr])) {
218
-			$displayName2 = (string)$ldapEntry[$attr][0];
219
-		}
220
-		if ($displayName !== '') {
221
-			$this->composeAndStoreDisplayName($displayName, $displayName2);
222
-			$this->access->cacheUserDisplayName(
223
-				$this->getUsername(),
224
-				$displayName,
225
-				$displayName2
226
-			);
227
-		}
228
-		unset($attr);
229
-
230
-		//Email
231
-		//email must be stored after displayname, because it would cause a user
232
-		//change event that will trigger fetching the display name again
233
-		$attr = strtolower($this->connection->ldapEmailAttribute);
234
-		if(isset($ldapEntry[$attr])) {
235
-			$this->updateEmail($ldapEntry[$attr][0]);
236
-		}
237
-		unset($attr);
238
-
239
-		// LDAP Username, needed for s2s sharing
240
-		if(isset($ldapEntry['uid'])) {
241
-			$this->storeLDAPUserName($ldapEntry['uid'][0]);
242
-		} else if(isset($ldapEntry['samaccountname'])) {
243
-			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
244
-		}
245
-
246
-		//homePath
247
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
248
-			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
249
-			if(isset($ldapEntry[$attr])) {
250
-				$this->access->cacheUserHome(
251
-					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
252
-			}
253
-		}
254
-
255
-		//memberOf groups
256
-		$cacheKey = 'getMemberOf'.$this->getUsername();
257
-		$groups = false;
258
-		if(isset($ldapEntry['memberof'])) {
259
-			$groups = $ldapEntry['memberof'];
260
-		}
261
-		$this->connection->writeToCache($cacheKey, $groups);
262
-
263
-		//external storage var
264
-		$attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
265
-		if(isset($ldapEntry[$attr])) {
266
-			$this->updateExtStorageHome($ldapEntry[$attr][0]);
267
-		}
268
-		unset($attr);
269
-
270
-		//Avatar
271
-		/** @var Connection $connection */
272
-		$connection = $this->access->getConnection();
273
-		$attributes = $connection->resolveRule('avatar');
274
-		foreach ($attributes as $attribute)  {
275
-			if(isset($ldapEntry[$attribute])) {
276
-				$this->avatarImage = $ldapEntry[$attribute][0];
277
-				// the call to the method that saves the avatar in the file
278
-				// system must be postponed after the login. It is to ensure
279
-				// external mounts are mounted properly (e.g. with login
280
-				// credentials from the session).
281
-				\OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
282
-				break;
283
-			}
284
-		}
285
-	}
286
-
287
-	/**
288
-	 * @brief returns the LDAP DN of the user
289
-	 * @return string
290
-	 */
291
-	public function getDN() {
292
-		return $this->dn;
293
-	}
294
-
295
-	/**
296
-	 * @brief returns the Nextcloud internal username of the user
297
-	 * @return string
298
-	 */
299
-	public function getUsername() {
300
-		return $this->uid;
301
-	}
302
-
303
-	/**
304
-	 * returns the home directory of the user if specified by LDAP settings
305
-	 * @param string $valueFromLDAP
306
-	 * @return bool|string
307
-	 * @throws \Exception
308
-	 */
309
-	public function getHomePath($valueFromLDAP = null) {
310
-		$path = (string)$valueFromLDAP;
311
-		$attr = null;
312
-
313
-		if (is_null($valueFromLDAP)
314
-		   && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
315
-		   && $this->access->connection->homeFolderNamingRule !== 'attr:')
316
-		{
317
-			$attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
318
-			$homedir = $this->access->readAttribute(
319
-				$this->access->username2dn($this->getUsername()), $attr);
320
-			if ($homedir && isset($homedir[0])) {
321
-				$path = $homedir[0];
322
-			}
323
-		}
324
-
325
-		if ($path !== '') {
326
-			//if attribute's value is an absolute path take this, otherwise append it to data dir
327
-			//check for / at the beginning or pattern c:\ resp. c:/
328
-			if(   '/' !== $path[0]
329
-			   && !(3 < strlen($path) && ctype_alpha($path[0])
330
-			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
331
-			) {
332
-				$path = $this->config->getSystemValue('datadirectory',
333
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
334
-			}
335
-			//we need it to store it in the DB as well in case a user gets
336
-			//deleted so we can clean up afterwards
337
-			$this->config->setUserValue(
338
-				$this->getUsername(), 'user_ldap', 'homePath', $path
339
-			);
340
-			return $path;
341
-		}
342
-
343
-		if(    !is_null($attr)
344
-			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
345
-		) {
346
-			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
347
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
348
-		}
349
-
350
-		//false will apply default behaviour as defined and done by OC_User
351
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
352
-		return false;
353
-	}
354
-
355
-	public function getMemberOfGroups() {
356
-		$cacheKey = 'getMemberOf'.$this->getUsername();
357
-		$memberOfGroups = $this->connection->getFromCache($cacheKey);
358
-		if(!is_null($memberOfGroups)) {
359
-			return $memberOfGroups;
360
-		}
361
-		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
362
-		$this->connection->writeToCache($cacheKey, $groupDNs);
363
-		return $groupDNs;
364
-	}
365
-
366
-	/**
367
-	 * @brief reads the image from LDAP that shall be used as Avatar
368
-	 * @return string data (provided by LDAP) | false
369
-	 */
370
-	public function getAvatarImage() {
371
-		if(!is_null($this->avatarImage)) {
372
-			return $this->avatarImage;
373
-		}
374
-
375
-		$this->avatarImage = false;
376
-		/** @var Connection $connection */
377
-		$connection = $this->access->getConnection();
378
-		$attributes = $connection->resolveRule('avatar');
379
-		foreach($attributes as $attribute) {
380
-			$result = $this->access->readAttribute($this->dn, $attribute);
381
-			if($result !== false && is_array($result) && isset($result[0])) {
382
-				$this->avatarImage = $result[0];
383
-				break;
384
-			}
385
-		}
386
-
387
-		return $this->avatarImage;
388
-	}
389
-
390
-	/**
391
-	 * @brief marks the user as having logged in at least once
392
-	 * @return null
393
-	 */
394
-	public function markLogin() {
395
-		$this->config->setUserValue(
396
-			$this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
397
-	}
398
-
399
-	/**
400
-	 * @brief marks the time when user features like email have been updated
401
-	 * @return null
402
-	 */
403
-	public function markRefreshTime() {
404
-		$this->config->setUserValue(
405
-			$this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
406
-	}
407
-
408
-	/**
409
-	 * @brief checks whether user features needs to be updated again by
410
-	 * comparing the difference of time of the last refresh to now with the
411
-	 * desired interval
412
-	 * @return bool
413
-	 */
414
-	private function needsRefresh() {
415
-		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
416
-			self::USER_PREFKEY_LASTREFRESH, 0);
417
-
418
-		if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
419
-			return false;
420
-		}
421
-		return  true;
422
-	}
423
-
424
-	/**
425
-	 * Stores a key-value pair in relation to this user
426
-	 *
427
-	 * @param string $key
428
-	 * @param string $value
429
-	 */
430
-	private function store($key, $value) {
431
-		$this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
432
-	}
433
-
434
-	/**
435
-	 * Composes the display name and stores it in the database. The final
436
-	 * display name is returned.
437
-	 *
438
-	 * @param string $displayName
439
-	 * @param string $displayName2
440
-	 * @return string the effective display name
441
-	 */
442
-	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
443
-		$displayName2 = (string)$displayName2;
444
-		if($displayName2 !== '') {
445
-			$displayName .= ' (' . $displayName2 . ')';
446
-		}
447
-		$oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
448
-		if ($oldName !== $displayName)  {
449
-			$this->store('displayName', $displayName);
450
-			$user = $this->userManager->get($this->getUsername());
451
-			if (!empty($oldName) && $user instanceof \OC\User\User) {
452
-				// if it was empty, it would be a new record, not a change emitting the trigger could
453
-				// potentially cause a UniqueConstraintViolationException, depending on some factors.
454
-				$user->triggerChange('displayName', $displayName, $oldName);
455
-			}
456
-		}
457
-		return $displayName;
458
-	}
459
-
460
-	/**
461
-	 * Stores the LDAP Username in the Database
462
-	 * @param string $userName
463
-	 */
464
-	public function storeLDAPUserName($userName) {
465
-		$this->store('uid', $userName);
466
-	}
467
-
468
-	/**
469
-	 * @brief checks whether an update method specified by feature was run
470
-	 * already. If not, it will marked like this, because it is expected that
471
-	 * the method will be run, when false is returned.
472
-	 * @param string $feature email | quota | avatar (can be extended)
473
-	 * @return bool
474
-	 */
475
-	private function wasRefreshed($feature) {
476
-		if(isset($this->refreshedFeatures[$feature])) {
477
-			return true;
478
-		}
479
-		$this->refreshedFeatures[$feature] = 1;
480
-		return false;
481
-	}
482
-
483
-	/**
484
-	 * fetches the email from LDAP and stores it as Nextcloud user value
485
-	 * @param string $valueFromLDAP if known, to save an LDAP read request
486
-	 * @return null
487
-	 */
488
-	public function updateEmail($valueFromLDAP = null) {
489
-		if($this->wasRefreshed('email')) {
490
-			return;
491
-		}
492
-		$email = (string)$valueFromLDAP;
493
-		if(is_null($valueFromLDAP)) {
494
-			$emailAttribute = $this->connection->ldapEmailAttribute;
495
-			if ($emailAttribute !== '') {
496
-				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
497
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
498
-					$email = (string)$aEmail[0];
499
-				}
500
-			}
501
-		}
502
-		if ($email !== '') {
503
-			$user = $this->userManager->get($this->uid);
504
-			if (!is_null($user)) {
505
-				$currentEmail = (string)$user->getEMailAddress();
506
-				if ($currentEmail !== $email) {
507
-					$user->setEMailAddress($email);
508
-				}
509
-			}
510
-		}
511
-	}
512
-
513
-	/**
514
-	 * Overall process goes as follow:
515
-	 * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
516
-	 * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
517
-	 * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
518
-	 * 4. check if the target user exists and set the quota for the user.
519
-	 *
520
-	 * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
521
-	 * parameter can be passed with the value of the attribute. This value will be considered as the
522
-	 * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
523
-	 * fetch all the user's attributes in one call and use the fetched values in this function.
524
-	 * The expected value for that parameter is a string describing the quota for the user. Valid
525
-	 * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
526
-	 * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
527
-	 *
528
-	 * fetches the quota from LDAP and stores it as Nextcloud user value
529
-	 * @param string $valueFromLDAP the quota attribute's value can be passed,
530
-	 * to save the readAttribute request
531
-	 * @return null
532
-	 */
533
-	public function updateQuota($valueFromLDAP = null) {
534
-		if($this->wasRefreshed('quota')) {
535
-			return;
536
-		}
537
-
538
-		$quotaAttribute = $this->connection->ldapQuotaAttribute;
539
-		$defaultQuota = $this->connection->ldapQuotaDefault;
540
-		if($quotaAttribute === '' && $defaultQuota === '') {
541
-			return;
542
-		}
543
-
544
-		$quota = false;
545
-		if(is_null($valueFromLDAP) && $quotaAttribute !== '') {
546
-			$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
547
-			if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
548
-				$quota = $aQuota[0];
549
-			} else if(is_array($aQuota) && isset($aQuota[0])) {
550
-				$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG);
551
-			}
552
-		} else if ($this->verifyQuotaValue($valueFromLDAP)) {
553
-			$quota = $valueFromLDAP;
554
-		} else {
555
-			$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG);
556
-		}
557
-
558
-		if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
559
-			// quota not found using the LDAP attribute (or not parseable). Try the default quota
560
-			$quota = $defaultQuota;
561
-		} else if($quota === false) {
562
-			$this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG);
563
-			return;
564
-		}
565
-
566
-		$targetUser = $this->userManager->get($this->uid);
567
-		if ($targetUser instanceof IUser) {
568
-			$targetUser->setQuota($quota);
569
-		} else {
570
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO);
571
-		}
572
-	}
573
-
574
-	private function verifyQuotaValue($quotaValue) {
575
-		return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
576
-	}
577
-
578
-	/**
579
-	 * called by a post_login hook to save the avatar picture
580
-	 *
581
-	 * @param array $params
582
-	 */
583
-	public function updateAvatarPostLogin($params) {
584
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
585
-			$this->updateAvatar();
586
-		}
587
-	}
588
-
589
-	/**
590
-	 * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
591
-	 * @return bool
592
-	 */
593
-	public function updateAvatar($force = false) {
594
-		if(!$force && $this->wasRefreshed('avatar')) {
595
-			return false;
596
-		}
597
-		$avatarImage = $this->getAvatarImage();
598
-		if($avatarImage === false) {
599
-			//not set, nothing left to do;
600
-			return false;
601
-		}
602
-
603
-		if(!$this->image->loadFromBase64(base64_encode($avatarImage))) {
604
-			return false;
605
-		}
606
-
607
-		// use the checksum before modifications
608
-		$checksum = md5($this->image->data());
609
-
610
-		if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
611
-			return true;
612
-		}
613
-
614
-		$isSet = $this->setOwnCloudAvatar();
615
-
616
-		if($isSet) {
617
-			// save checksum only after successful setting
618
-			$this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
619
-		}
620
-
621
-		return $isSet;
622
-	}
623
-
624
-	/**
625
-	 * @brief sets an image as Nextcloud avatar
626
-	 * @return bool
627
-	 */
628
-	private function setOwnCloudAvatar() {
629
-		if(!$this->image->valid()) {
630
-			$this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR);
631
-			return false;
632
-		}
633
-
634
-
635
-		//make sure it is a square and not bigger than 128x128
636
-		$size = min([$this->image->width(), $this->image->height(), 128]);
637
-		if(!$this->image->centerCrop($size)) {
638
-			$this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR);
639
-			return false;
640
-		}
641
-
642
-		if(!$this->fs->isLoaded()) {
643
-			$this->fs->setup($this->uid);
644
-		}
645
-
646
-		try {
647
-			$avatar = $this->avatarManager->getAvatar($this->uid);
648
-			$avatar->set($this->image);
649
-			return true;
650
-		} catch (\Exception $e) {
651
-			\OC::$server->getLogger()->logException($e, [
652
-				'message' => 'Could not set avatar for ' . $this->dn,
653
-				'level' => ILogger::INFO,
654
-				'app' => 'user_ldap',
655
-			]);
656
-		}
657
-		return false;
658
-	}
659
-
660
-	/**
661
-	 * @throws AttributeNotSet
662
-	 * @throws \OC\ServerNotAvailableException
663
-	 * @throws \OCP\PreConditionNotMetException
664
-	 */
665
-	public function getExtStorageHome():string {
666
-		$value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
667
-		if ($value !== '') {
668
-			return $value;
669
-		}
670
-
671
-		$value = $this->updateExtStorageHome();
672
-		if ($value !== '') {
673
-			return $value;
674
-		}
675
-
676
-		throw new AttributeNotSet(sprintf(
677
-			'external home storage attribute yield no value for %s', $this->getUsername()
678
-		));
679
-	}
680
-
681
-	/**
682
-	 * @throws \OCP\PreConditionNotMetException
683
-	 * @throws \OC\ServerNotAvailableException
684
-	 */
685
-	public function updateExtStorageHome(string $valueFromLDAP = null):string {
686
-		if ($valueFromLDAP === null) {
687
-			$extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
688
-		} else {
689
-			$extHomeValues = [$valueFromLDAP];
690
-		}
691
-		if ($extHomeValues && isset($extHomeValues[0])) {
692
-			$extHome = $extHomeValues[0];
693
-			$this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
694
-			return $extHome;
695
-		} else {
696
-			$this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
697
-			return '';
698
-		}
699
-	}
700
-
701
-	/**
702
-	 * called by a post_login hook to handle password expiry
703
-	 *
704
-	 * @param array $params
705
-	 */
706
-	public function handlePasswordExpiry($params) {
707
-		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
708
-		if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
709
-			return;//password expiry handling disabled
710
-		}
711
-		$uid = $params['uid'];
712
-		if (isset($uid) && $uid === $this->getUsername()) {
713
-			//retrieve relevant user attributes
714
-			$result = $this->access->search('objectclass=*', [$this->dn], ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
715
-
716
-			if (array_key_exists('pwdpolicysubentry', $result[0])) {
717
-				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
718
-				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
719
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
720
-				}
721
-			}
722
-
723
-			$pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
724
-			$pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
725
-			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
726
-
727
-			//retrieve relevant password policy attributes
728
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
729
-			$result = $this->connection->getFromCache($cacheKey);
730
-			if(is_null($result)) {
731
-				$result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
732
-				$this->connection->writeToCache($cacheKey, $result);
733
-			}
734
-
735
-			$pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
736
-			$pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
737
-			$pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
738
-
739
-			//handle grace login
740
-			if (!empty($pwdGraceUseTime)) { //was this a grace login?
741
-				if (!empty($pwdGraceAuthNLimit)
742
-					&& count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
743
-					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
744
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
745
-					'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
746
-				} else { //no more grace login available
747
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
748
-					'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
749
-				}
750
-				exit();
751
-			}
752
-			//handle pwdReset attribute
753
-			if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
754
-				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
755
-				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
756
-				'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
757
-				exit();
758
-			}
759
-			//handle password expiry warning
760
-			if (!empty($pwdChangedTime)) {
761
-				if (!empty($pwdMaxAge)
762
-					&& !empty($pwdExpireWarning)) {
763
-					$pwdMaxAgeInt = (int)$pwdMaxAge[0];
764
-					$pwdExpireWarningInt = (int)$pwdExpireWarning[0];
765
-					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
766
-						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
767
-						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
768
-						$currentDateTime = new \DateTime();
769
-						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
770
-						if ($secondsToExpiry <= $pwdExpireWarningInt) {
771
-							//remove last password expiry warning if any
772
-							$notification = $this->notificationManager->createNotification();
773
-							$notification->setApp('user_ldap')
774
-								->setUser($uid)
775
-								->setObject('pwd_exp_warn', $uid)
776
-							;
777
-							$this->notificationManager->markProcessed($notification);
778
-							//create new password expiry warning
779
-							$notification = $this->notificationManager->createNotification();
780
-							$notification->setApp('user_ldap')
781
-								->setUser($uid)
782
-								->setDateTime($currentDateTime)
783
-								->setObject('pwd_exp_warn', $uid)
784
-								->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
785
-							;
786
-							$this->notificationManager->notify($notification);
787
-						}
788
-					}
789
-				}
790
-			}
791
-		}
792
-	}
52
+    /**
53
+     * @var Access
54
+     */
55
+    protected $access;
56
+    /**
57
+     * @var Connection
58
+     */
59
+    protected $connection;
60
+    /**
61
+     * @var IConfig
62
+     */
63
+    protected $config;
64
+    /**
65
+     * @var FilesystemHelper
66
+     */
67
+    protected $fs;
68
+    /**
69
+     * @var Image
70
+     */
71
+    protected $image;
72
+    /**
73
+     * @var LogWrapper
74
+     */
75
+    protected $log;
76
+    /**
77
+     * @var IAvatarManager
78
+     */
79
+    protected $avatarManager;
80
+    /**
81
+     * @var IUserManager
82
+     */
83
+    protected $userManager;
84
+    /**
85
+     * @var INotificationManager
86
+     */
87
+    protected $notificationManager;
88
+    /**
89
+     * @var string
90
+     */
91
+    protected $dn;
92
+    /**
93
+     * @var string
94
+     */
95
+    protected $uid;
96
+    /**
97
+     * @var string[]
98
+     */
99
+    protected $refreshedFeatures = [];
100
+    /**
101
+     * @var string
102
+     */
103
+    protected $avatarImage;
104
+
105
+    /**
106
+     * DB config keys for user preferences
107
+     */
108
+    const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
109
+    const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
110
+
111
+    /**
112
+     * @brief constructor, make sure the subclasses call this one!
113
+     * @param string $username the internal username
114
+     * @param string $dn the LDAP DN
115
+     * @param Access $access
116
+     * @param IConfig $config
117
+     * @param FilesystemHelper $fs
118
+     * @param Image $image any empty instance
119
+     * @param LogWrapper $log
120
+     * @param IAvatarManager $avatarManager
121
+     * @param IUserManager $userManager
122
+     * @param INotificationManager $notificationManager
123
+     */
124
+    public function __construct($username, $dn, Access $access,
125
+        IConfig $config, FilesystemHelper $fs, Image $image,
126
+        LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
127
+        INotificationManager $notificationManager) {
128
+
129
+        if ($username === null) {
130
+            $log->log("uid for '$dn' must not be null!", ILogger::ERROR);
131
+            throw new \InvalidArgumentException('uid must not be null!');
132
+        } else if ($username === '') {
133
+            $log->log("uid for '$dn' must not be an empty string", ILogger::ERROR);
134
+            throw new \InvalidArgumentException('uid must not be an empty string!');
135
+        }
136
+
137
+        $this->access              = $access;
138
+        $this->connection          = $access->getConnection();
139
+        $this->config              = $config;
140
+        $this->fs                  = $fs;
141
+        $this->dn                  = $dn;
142
+        $this->uid                 = $username;
143
+        $this->image               = $image;
144
+        $this->log                 = $log;
145
+        $this->avatarManager       = $avatarManager;
146
+        $this->userManager         = $userManager;
147
+        $this->notificationManager = $notificationManager;
148
+
149
+        \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
150
+    }
151
+
152
+    /**
153
+     * @brief updates properties like email, quota or avatar provided by LDAP
154
+     * @return null
155
+     */
156
+    public function update() {
157
+        if(is_null($this->dn)) {
158
+            return null;
159
+        }
160
+
161
+        $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
162
+                self::USER_PREFKEY_FIRSTLOGIN, 0);
163
+
164
+        if($this->needsRefresh()) {
165
+            $this->updateEmail();
166
+            $this->updateQuota();
167
+            if($hasLoggedIn !== 0) {
168
+                //we do not need to try it, when the user has not been logged in
169
+                //before, because the file system will not be ready.
170
+                $this->updateAvatar();
171
+                //in order to get an avatar as soon as possible, mark the user
172
+                //as refreshed only when updating the avatar did happen
173
+                $this->markRefreshTime();
174
+            }
175
+        }
176
+    }
177
+
178
+    /**
179
+     * marks a user as deleted
180
+     *
181
+     * @throws \OCP\PreConditionNotMetException
182
+     */
183
+    public function markUser() {
184
+        $curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
185
+        if($curValue === '1') {
186
+            // the user is already marked, do not write to DB again
187
+            return;
188
+        }
189
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
190
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
191
+    }
192
+
193
+    /**
194
+     * processes results from LDAP for attributes as returned by getAttributesToRead()
195
+     * @param array $ldapEntry the user entry as retrieved from LDAP
196
+     */
197
+    public function processAttributes($ldapEntry) {
198
+        $this->markRefreshTime();
199
+        //Quota
200
+        $attr = strtolower($this->connection->ldapQuotaAttribute);
201
+        if(isset($ldapEntry[$attr])) {
202
+            $this->updateQuota($ldapEntry[$attr][0]);
203
+        } else {
204
+            if ($this->connection->ldapQuotaDefault !== '') {
205
+                $this->updateQuota();
206
+            }
207
+        }
208
+        unset($attr);
209
+
210
+        //displayName
211
+        $displayName = $displayName2 = '';
212
+        $attr = strtolower($this->connection->ldapUserDisplayName);
213
+        if(isset($ldapEntry[$attr])) {
214
+            $displayName = (string)$ldapEntry[$attr][0];
215
+        }
216
+        $attr = strtolower($this->connection->ldapUserDisplayName2);
217
+        if(isset($ldapEntry[$attr])) {
218
+            $displayName2 = (string)$ldapEntry[$attr][0];
219
+        }
220
+        if ($displayName !== '') {
221
+            $this->composeAndStoreDisplayName($displayName, $displayName2);
222
+            $this->access->cacheUserDisplayName(
223
+                $this->getUsername(),
224
+                $displayName,
225
+                $displayName2
226
+            );
227
+        }
228
+        unset($attr);
229
+
230
+        //Email
231
+        //email must be stored after displayname, because it would cause a user
232
+        //change event that will trigger fetching the display name again
233
+        $attr = strtolower($this->connection->ldapEmailAttribute);
234
+        if(isset($ldapEntry[$attr])) {
235
+            $this->updateEmail($ldapEntry[$attr][0]);
236
+        }
237
+        unset($attr);
238
+
239
+        // LDAP Username, needed for s2s sharing
240
+        if(isset($ldapEntry['uid'])) {
241
+            $this->storeLDAPUserName($ldapEntry['uid'][0]);
242
+        } else if(isset($ldapEntry['samaccountname'])) {
243
+            $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
244
+        }
245
+
246
+        //homePath
247
+        if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
248
+            $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
249
+            if(isset($ldapEntry[$attr])) {
250
+                $this->access->cacheUserHome(
251
+                    $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
252
+            }
253
+        }
254
+
255
+        //memberOf groups
256
+        $cacheKey = 'getMemberOf'.$this->getUsername();
257
+        $groups = false;
258
+        if(isset($ldapEntry['memberof'])) {
259
+            $groups = $ldapEntry['memberof'];
260
+        }
261
+        $this->connection->writeToCache($cacheKey, $groups);
262
+
263
+        //external storage var
264
+        $attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
265
+        if(isset($ldapEntry[$attr])) {
266
+            $this->updateExtStorageHome($ldapEntry[$attr][0]);
267
+        }
268
+        unset($attr);
269
+
270
+        //Avatar
271
+        /** @var Connection $connection */
272
+        $connection = $this->access->getConnection();
273
+        $attributes = $connection->resolveRule('avatar');
274
+        foreach ($attributes as $attribute)  {
275
+            if(isset($ldapEntry[$attribute])) {
276
+                $this->avatarImage = $ldapEntry[$attribute][0];
277
+                // the call to the method that saves the avatar in the file
278
+                // system must be postponed after the login. It is to ensure
279
+                // external mounts are mounted properly (e.g. with login
280
+                // credentials from the session).
281
+                \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
282
+                break;
283
+            }
284
+        }
285
+    }
286
+
287
+    /**
288
+     * @brief returns the LDAP DN of the user
289
+     * @return string
290
+     */
291
+    public function getDN() {
292
+        return $this->dn;
293
+    }
294
+
295
+    /**
296
+     * @brief returns the Nextcloud internal username of the user
297
+     * @return string
298
+     */
299
+    public function getUsername() {
300
+        return $this->uid;
301
+    }
302
+
303
+    /**
304
+     * returns the home directory of the user if specified by LDAP settings
305
+     * @param string $valueFromLDAP
306
+     * @return bool|string
307
+     * @throws \Exception
308
+     */
309
+    public function getHomePath($valueFromLDAP = null) {
310
+        $path = (string)$valueFromLDAP;
311
+        $attr = null;
312
+
313
+        if (is_null($valueFromLDAP)
314
+           && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
315
+           && $this->access->connection->homeFolderNamingRule !== 'attr:')
316
+        {
317
+            $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
318
+            $homedir = $this->access->readAttribute(
319
+                $this->access->username2dn($this->getUsername()), $attr);
320
+            if ($homedir && isset($homedir[0])) {
321
+                $path = $homedir[0];
322
+            }
323
+        }
324
+
325
+        if ($path !== '') {
326
+            //if attribute's value is an absolute path take this, otherwise append it to data dir
327
+            //check for / at the beginning or pattern c:\ resp. c:/
328
+            if(   '/' !== $path[0]
329
+               && !(3 < strlen($path) && ctype_alpha($path[0])
330
+                   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
331
+            ) {
332
+                $path = $this->config->getSystemValue('datadirectory',
333
+                        \OC::$SERVERROOT.'/data' ) . '/' . $path;
334
+            }
335
+            //we need it to store it in the DB as well in case a user gets
336
+            //deleted so we can clean up afterwards
337
+            $this->config->setUserValue(
338
+                $this->getUsername(), 'user_ldap', 'homePath', $path
339
+            );
340
+            return $path;
341
+        }
342
+
343
+        if(    !is_null($attr)
344
+            && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
345
+        ) {
346
+            // a naming rule attribute is defined, but it doesn't exist for that LDAP user
347
+            throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
348
+        }
349
+
350
+        //false will apply default behaviour as defined and done by OC_User
351
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
352
+        return false;
353
+    }
354
+
355
+    public function getMemberOfGroups() {
356
+        $cacheKey = 'getMemberOf'.$this->getUsername();
357
+        $memberOfGroups = $this->connection->getFromCache($cacheKey);
358
+        if(!is_null($memberOfGroups)) {
359
+            return $memberOfGroups;
360
+        }
361
+        $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
362
+        $this->connection->writeToCache($cacheKey, $groupDNs);
363
+        return $groupDNs;
364
+    }
365
+
366
+    /**
367
+     * @brief reads the image from LDAP that shall be used as Avatar
368
+     * @return string data (provided by LDAP) | false
369
+     */
370
+    public function getAvatarImage() {
371
+        if(!is_null($this->avatarImage)) {
372
+            return $this->avatarImage;
373
+        }
374
+
375
+        $this->avatarImage = false;
376
+        /** @var Connection $connection */
377
+        $connection = $this->access->getConnection();
378
+        $attributes = $connection->resolveRule('avatar');
379
+        foreach($attributes as $attribute) {
380
+            $result = $this->access->readAttribute($this->dn, $attribute);
381
+            if($result !== false && is_array($result) && isset($result[0])) {
382
+                $this->avatarImage = $result[0];
383
+                break;
384
+            }
385
+        }
386
+
387
+        return $this->avatarImage;
388
+    }
389
+
390
+    /**
391
+     * @brief marks the user as having logged in at least once
392
+     * @return null
393
+     */
394
+    public function markLogin() {
395
+        $this->config->setUserValue(
396
+            $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
397
+    }
398
+
399
+    /**
400
+     * @brief marks the time when user features like email have been updated
401
+     * @return null
402
+     */
403
+    public function markRefreshTime() {
404
+        $this->config->setUserValue(
405
+            $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
406
+    }
407
+
408
+    /**
409
+     * @brief checks whether user features needs to be updated again by
410
+     * comparing the difference of time of the last refresh to now with the
411
+     * desired interval
412
+     * @return bool
413
+     */
414
+    private function needsRefresh() {
415
+        $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
416
+            self::USER_PREFKEY_LASTREFRESH, 0);
417
+
418
+        if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
419
+            return false;
420
+        }
421
+        return  true;
422
+    }
423
+
424
+    /**
425
+     * Stores a key-value pair in relation to this user
426
+     *
427
+     * @param string $key
428
+     * @param string $value
429
+     */
430
+    private function store($key, $value) {
431
+        $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
432
+    }
433
+
434
+    /**
435
+     * Composes the display name and stores it in the database. The final
436
+     * display name is returned.
437
+     *
438
+     * @param string $displayName
439
+     * @param string $displayName2
440
+     * @return string the effective display name
441
+     */
442
+    public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
443
+        $displayName2 = (string)$displayName2;
444
+        if($displayName2 !== '') {
445
+            $displayName .= ' (' . $displayName2 . ')';
446
+        }
447
+        $oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
448
+        if ($oldName !== $displayName)  {
449
+            $this->store('displayName', $displayName);
450
+            $user = $this->userManager->get($this->getUsername());
451
+            if (!empty($oldName) && $user instanceof \OC\User\User) {
452
+                // if it was empty, it would be a new record, not a change emitting the trigger could
453
+                // potentially cause a UniqueConstraintViolationException, depending on some factors.
454
+                $user->triggerChange('displayName', $displayName, $oldName);
455
+            }
456
+        }
457
+        return $displayName;
458
+    }
459
+
460
+    /**
461
+     * Stores the LDAP Username in the Database
462
+     * @param string $userName
463
+     */
464
+    public function storeLDAPUserName($userName) {
465
+        $this->store('uid', $userName);
466
+    }
467
+
468
+    /**
469
+     * @brief checks whether an update method specified by feature was run
470
+     * already. If not, it will marked like this, because it is expected that
471
+     * the method will be run, when false is returned.
472
+     * @param string $feature email | quota | avatar (can be extended)
473
+     * @return bool
474
+     */
475
+    private function wasRefreshed($feature) {
476
+        if(isset($this->refreshedFeatures[$feature])) {
477
+            return true;
478
+        }
479
+        $this->refreshedFeatures[$feature] = 1;
480
+        return false;
481
+    }
482
+
483
+    /**
484
+     * fetches the email from LDAP and stores it as Nextcloud user value
485
+     * @param string $valueFromLDAP if known, to save an LDAP read request
486
+     * @return null
487
+     */
488
+    public function updateEmail($valueFromLDAP = null) {
489
+        if($this->wasRefreshed('email')) {
490
+            return;
491
+        }
492
+        $email = (string)$valueFromLDAP;
493
+        if(is_null($valueFromLDAP)) {
494
+            $emailAttribute = $this->connection->ldapEmailAttribute;
495
+            if ($emailAttribute !== '') {
496
+                $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
497
+                if(is_array($aEmail) && (count($aEmail) > 0)) {
498
+                    $email = (string)$aEmail[0];
499
+                }
500
+            }
501
+        }
502
+        if ($email !== '') {
503
+            $user = $this->userManager->get($this->uid);
504
+            if (!is_null($user)) {
505
+                $currentEmail = (string)$user->getEMailAddress();
506
+                if ($currentEmail !== $email) {
507
+                    $user->setEMailAddress($email);
508
+                }
509
+            }
510
+        }
511
+    }
512
+
513
+    /**
514
+     * Overall process goes as follow:
515
+     * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
516
+     * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
517
+     * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
518
+     * 4. check if the target user exists and set the quota for the user.
519
+     *
520
+     * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
521
+     * parameter can be passed with the value of the attribute. This value will be considered as the
522
+     * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
523
+     * fetch all the user's attributes in one call and use the fetched values in this function.
524
+     * The expected value for that parameter is a string describing the quota for the user. Valid
525
+     * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
526
+     * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
527
+     *
528
+     * fetches the quota from LDAP and stores it as Nextcloud user value
529
+     * @param string $valueFromLDAP the quota attribute's value can be passed,
530
+     * to save the readAttribute request
531
+     * @return null
532
+     */
533
+    public function updateQuota($valueFromLDAP = null) {
534
+        if($this->wasRefreshed('quota')) {
535
+            return;
536
+        }
537
+
538
+        $quotaAttribute = $this->connection->ldapQuotaAttribute;
539
+        $defaultQuota = $this->connection->ldapQuotaDefault;
540
+        if($quotaAttribute === '' && $defaultQuota === '') {
541
+            return;
542
+        }
543
+
544
+        $quota = false;
545
+        if(is_null($valueFromLDAP) && $quotaAttribute !== '') {
546
+            $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
547
+            if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
548
+                $quota = $aQuota[0];
549
+            } else if(is_array($aQuota) && isset($aQuota[0])) {
550
+                $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG);
551
+            }
552
+        } else if ($this->verifyQuotaValue($valueFromLDAP)) {
553
+            $quota = $valueFromLDAP;
554
+        } else {
555
+            $this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG);
556
+        }
557
+
558
+        if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
559
+            // quota not found using the LDAP attribute (or not parseable). Try the default quota
560
+            $quota = $defaultQuota;
561
+        } else if($quota === false) {
562
+            $this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG);
563
+            return;
564
+        }
565
+
566
+        $targetUser = $this->userManager->get($this->uid);
567
+        if ($targetUser instanceof IUser) {
568
+            $targetUser->setQuota($quota);
569
+        } else {
570
+            $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO);
571
+        }
572
+    }
573
+
574
+    private function verifyQuotaValue($quotaValue) {
575
+        return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
576
+    }
577
+
578
+    /**
579
+     * called by a post_login hook to save the avatar picture
580
+     *
581
+     * @param array $params
582
+     */
583
+    public function updateAvatarPostLogin($params) {
584
+        if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
585
+            $this->updateAvatar();
586
+        }
587
+    }
588
+
589
+    /**
590
+     * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
591
+     * @return bool
592
+     */
593
+    public function updateAvatar($force = false) {
594
+        if(!$force && $this->wasRefreshed('avatar')) {
595
+            return false;
596
+        }
597
+        $avatarImage = $this->getAvatarImage();
598
+        if($avatarImage === false) {
599
+            //not set, nothing left to do;
600
+            return false;
601
+        }
602
+
603
+        if(!$this->image->loadFromBase64(base64_encode($avatarImage))) {
604
+            return false;
605
+        }
606
+
607
+        // use the checksum before modifications
608
+        $checksum = md5($this->image->data());
609
+
610
+        if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
611
+            return true;
612
+        }
613
+
614
+        $isSet = $this->setOwnCloudAvatar();
615
+
616
+        if($isSet) {
617
+            // save checksum only after successful setting
618
+            $this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
619
+        }
620
+
621
+        return $isSet;
622
+    }
623
+
624
+    /**
625
+     * @brief sets an image as Nextcloud avatar
626
+     * @return bool
627
+     */
628
+    private function setOwnCloudAvatar() {
629
+        if(!$this->image->valid()) {
630
+            $this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR);
631
+            return false;
632
+        }
633
+
634
+
635
+        //make sure it is a square and not bigger than 128x128
636
+        $size = min([$this->image->width(), $this->image->height(), 128]);
637
+        if(!$this->image->centerCrop($size)) {
638
+            $this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR);
639
+            return false;
640
+        }
641
+
642
+        if(!$this->fs->isLoaded()) {
643
+            $this->fs->setup($this->uid);
644
+        }
645
+
646
+        try {
647
+            $avatar = $this->avatarManager->getAvatar($this->uid);
648
+            $avatar->set($this->image);
649
+            return true;
650
+        } catch (\Exception $e) {
651
+            \OC::$server->getLogger()->logException($e, [
652
+                'message' => 'Could not set avatar for ' . $this->dn,
653
+                'level' => ILogger::INFO,
654
+                'app' => 'user_ldap',
655
+            ]);
656
+        }
657
+        return false;
658
+    }
659
+
660
+    /**
661
+     * @throws AttributeNotSet
662
+     * @throws \OC\ServerNotAvailableException
663
+     * @throws \OCP\PreConditionNotMetException
664
+     */
665
+    public function getExtStorageHome():string {
666
+        $value = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', '');
667
+        if ($value !== '') {
668
+            return $value;
669
+        }
670
+
671
+        $value = $this->updateExtStorageHome();
672
+        if ($value !== '') {
673
+            return $value;
674
+        }
675
+
676
+        throw new AttributeNotSet(sprintf(
677
+            'external home storage attribute yield no value for %s', $this->getUsername()
678
+        ));
679
+    }
680
+
681
+    /**
682
+     * @throws \OCP\PreConditionNotMetException
683
+     * @throws \OC\ServerNotAvailableException
684
+     */
685
+    public function updateExtStorageHome(string $valueFromLDAP = null):string {
686
+        if ($valueFromLDAP === null) {
687
+            $extHomeValues = $this->access->readAttribute($this->getDN(), $this->connection->ldapExtStorageHomeAttribute);
688
+        } else {
689
+            $extHomeValues = [$valueFromLDAP];
690
+        }
691
+        if ($extHomeValues && isset($extHomeValues[0])) {
692
+            $extHome = $extHomeValues[0];
693
+            $this->config->setUserValue($this->getUsername(), 'user_ldap', 'extStorageHome', $extHome);
694
+            return $extHome;
695
+        } else {
696
+            $this->config->deleteUserValue($this->getUsername(), 'user_ldap', 'extStorageHome');
697
+            return '';
698
+        }
699
+    }
700
+
701
+    /**
702
+     * called by a post_login hook to handle password expiry
703
+     *
704
+     * @param array $params
705
+     */
706
+    public function handlePasswordExpiry($params) {
707
+        $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
708
+        if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
709
+            return;//password expiry handling disabled
710
+        }
711
+        $uid = $params['uid'];
712
+        if (isset($uid) && $uid === $this->getUsername()) {
713
+            //retrieve relevant user attributes
714
+            $result = $this->access->search('objectclass=*', [$this->dn], ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
715
+
716
+            if (array_key_exists('pwdpolicysubentry', $result[0])) {
717
+                $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
718
+                if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
719
+                    $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
720
+                }
721
+            }
722
+
723
+            $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : [];
724
+            $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : [];
725
+            $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
726
+
727
+            //retrieve relevant password policy attributes
728
+            $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
729
+            $result = $this->connection->getFromCache($cacheKey);
730
+            if(is_null($result)) {
731
+                $result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
732
+                $this->connection->writeToCache($cacheKey, $result);
733
+            }
734
+
735
+            $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : [];
736
+            $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : [];
737
+            $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : [];
738
+
739
+            //handle grace login
740
+            if (!empty($pwdGraceUseTime)) { //was this a grace login?
741
+                if (!empty($pwdGraceAuthNLimit)
742
+                    && count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
743
+                    $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
744
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
745
+                    'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
746
+                } else { //no more grace login available
747
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
748
+                    'user_ldap.renewPassword.showLoginFormInvalidPassword', ['user' => $uid]));
749
+                }
750
+                exit();
751
+            }
752
+            //handle pwdReset attribute
753
+            if (!empty($pwdReset) && $pwdReset[0] === 'TRUE') { //user must change his password
754
+                $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
755
+                header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
756
+                'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
757
+                exit();
758
+            }
759
+            //handle password expiry warning
760
+            if (!empty($pwdChangedTime)) {
761
+                if (!empty($pwdMaxAge)
762
+                    && !empty($pwdExpireWarning)) {
763
+                    $pwdMaxAgeInt = (int)$pwdMaxAge[0];
764
+                    $pwdExpireWarningInt = (int)$pwdExpireWarning[0];
765
+                    if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
766
+                        $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
767
+                        $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
768
+                        $currentDateTime = new \DateTime();
769
+                        $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
770
+                        if ($secondsToExpiry <= $pwdExpireWarningInt) {
771
+                            //remove last password expiry warning if any
772
+                            $notification = $this->notificationManager->createNotification();
773
+                            $notification->setApp('user_ldap')
774
+                                ->setUser($uid)
775
+                                ->setObject('pwd_exp_warn', $uid)
776
+                            ;
777
+                            $this->notificationManager->markProcessed($notification);
778
+                            //create new password expiry warning
779
+                            $notification = $this->notificationManager->createNotification();
780
+                            $notification->setApp('user_ldap')
781
+                                ->setUser($uid)
782
+                                ->setDateTime($currentDateTime)
783
+                                ->setObject('pwd_exp_warn', $uid)
784
+                                ->setSubject('pwd_exp_warn_days', [(int) ceil($secondsToExpiry / 60 / 60 / 24)])
785
+                            ;
786
+                            $this->notificationManager->notify($notification);
787
+                        }
788
+                    }
789
+                }
790
+            }
791
+        }
792
+    }
793 793
 }
Please login to merge, or discard this patch.
Spacing   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -154,17 +154,17 @@  discard block
 block discarded – undo
154 154
 	 * @return null
155 155
 	 */
156 156
 	public function update() {
157
-		if(is_null($this->dn)) {
157
+		if (is_null($this->dn)) {
158 158
 			return null;
159 159
 		}
160 160
 
161 161
 		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
162 162
 				self::USER_PREFKEY_FIRSTLOGIN, 0);
163 163
 
164
-		if($this->needsRefresh()) {
164
+		if ($this->needsRefresh()) {
165 165
 			$this->updateEmail();
166 166
 			$this->updateQuota();
167
-			if($hasLoggedIn !== 0) {
167
+			if ($hasLoggedIn !== 0) {
168 168
 				//we do not need to try it, when the user has not been logged in
169 169
 				//before, because the file system will not be ready.
170 170
 				$this->updateAvatar();
@@ -182,12 +182,12 @@  discard block
 block discarded – undo
182 182
 	 */
183 183
 	public function markUser() {
184 184
 		$curValue = $this->config->getUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '0');
185
-		if($curValue === '1') {
185
+		if ($curValue === '1') {
186 186
 			// the user is already marked, do not write to DB again
187 187
 			return;
188 188
 		}
189 189
 		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'isDeleted', '1');
190
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string)time());
190
+		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'foundDeleted', (string) time());
191 191
 	}
192 192
 
193 193
 	/**
@@ -198,7 +198,7 @@  discard block
 block discarded – undo
198 198
 		$this->markRefreshTime();
199 199
 		//Quota
200 200
 		$attr = strtolower($this->connection->ldapQuotaAttribute);
201
-		if(isset($ldapEntry[$attr])) {
201
+		if (isset($ldapEntry[$attr])) {
202 202
 			$this->updateQuota($ldapEntry[$attr][0]);
203 203
 		} else {
204 204
 			if ($this->connection->ldapQuotaDefault !== '') {
@@ -210,12 +210,12 @@  discard block
 block discarded – undo
210 210
 		//displayName
211 211
 		$displayName = $displayName2 = '';
212 212
 		$attr = strtolower($this->connection->ldapUserDisplayName);
213
-		if(isset($ldapEntry[$attr])) {
214
-			$displayName = (string)$ldapEntry[$attr][0];
213
+		if (isset($ldapEntry[$attr])) {
214
+			$displayName = (string) $ldapEntry[$attr][0];
215 215
 		}
216 216
 		$attr = strtolower($this->connection->ldapUserDisplayName2);
217
-		if(isset($ldapEntry[$attr])) {
218
-			$displayName2 = (string)$ldapEntry[$attr][0];
217
+		if (isset($ldapEntry[$attr])) {
218
+			$displayName2 = (string) $ldapEntry[$attr][0];
219 219
 		}
220 220
 		if ($displayName !== '') {
221 221
 			$this->composeAndStoreDisplayName($displayName, $displayName2);
@@ -231,22 +231,22 @@  discard block
 block discarded – undo
231 231
 		//email must be stored after displayname, because it would cause a user
232 232
 		//change event that will trigger fetching the display name again
233 233
 		$attr = strtolower($this->connection->ldapEmailAttribute);
234
-		if(isset($ldapEntry[$attr])) {
234
+		if (isset($ldapEntry[$attr])) {
235 235
 			$this->updateEmail($ldapEntry[$attr][0]);
236 236
 		}
237 237
 		unset($attr);
238 238
 
239 239
 		// LDAP Username, needed for s2s sharing
240
-		if(isset($ldapEntry['uid'])) {
240
+		if (isset($ldapEntry['uid'])) {
241 241
 			$this->storeLDAPUserName($ldapEntry['uid'][0]);
242
-		} else if(isset($ldapEntry['samaccountname'])) {
242
+		} else if (isset($ldapEntry['samaccountname'])) {
243 243
 			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
244 244
 		}
245 245
 
246 246
 		//homePath
247
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
247
+		if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
248 248
 			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
249
-			if(isset($ldapEntry[$attr])) {
249
+			if (isset($ldapEntry[$attr])) {
250 250
 				$this->access->cacheUserHome(
251 251
 					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
252 252
 			}
@@ -255,14 +255,14 @@  discard block
 block discarded – undo
255 255
 		//memberOf groups
256 256
 		$cacheKey = 'getMemberOf'.$this->getUsername();
257 257
 		$groups = false;
258
-		if(isset($ldapEntry['memberof'])) {
258
+		if (isset($ldapEntry['memberof'])) {
259 259
 			$groups = $ldapEntry['memberof'];
260 260
 		}
261 261
 		$this->connection->writeToCache($cacheKey, $groups);
262 262
 
263 263
 		//external storage var
264 264
 		$attr = strtolower($this->connection->ldapExtStorageHomeAttribute);
265
-		if(isset($ldapEntry[$attr])) {
265
+		if (isset($ldapEntry[$attr])) {
266 266
 			$this->updateExtStorageHome($ldapEntry[$attr][0]);
267 267
 		}
268 268
 		unset($attr);
@@ -271,8 +271,8 @@  discard block
 block discarded – undo
271 271
 		/** @var Connection $connection */
272 272
 		$connection = $this->access->getConnection();
273 273
 		$attributes = $connection->resolveRule('avatar');
274
-		foreach ($attributes as $attribute)  {
275
-			if(isset($ldapEntry[$attribute])) {
274
+		foreach ($attributes as $attribute) {
275
+			if (isset($ldapEntry[$attribute])) {
276 276
 				$this->avatarImage = $ldapEntry[$attribute][0];
277 277
 				// the call to the method that saves the avatar in the file
278 278
 				// system must be postponed after the login. It is to ensure
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 	 * @throws \Exception
308 308
 	 */
309 309
 	public function getHomePath($valueFromLDAP = null) {
310
-		$path = (string)$valueFromLDAP;
310
+		$path = (string) $valueFromLDAP;
311 311
 		$attr = null;
312 312
 
313 313
 		if (is_null($valueFromLDAP)
@@ -325,12 +325,12 @@  discard block
 block discarded – undo
325 325
 		if ($path !== '') {
326 326
 			//if attribute's value is an absolute path take this, otherwise append it to data dir
327 327
 			//check for / at the beginning or pattern c:\ resp. c:/
328
-			if(   '/' !== $path[0]
328
+			if ('/' !== $path[0]
329 329
 			   && !(3 < strlen($path) && ctype_alpha($path[0])
330 330
 			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
331 331
 			) {
332 332
 				$path = $this->config->getSystemValue('datadirectory',
333
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
333
+						\OC::$SERVERROOT.'/data').'/'.$path;
334 334
 			}
335 335
 			//we need it to store it in the DB as well in case a user gets
336 336
 			//deleted so we can clean up afterwards
@@ -340,11 +340,11 @@  discard block
 block discarded – undo
340 340
 			return $path;
341 341
 		}
342 342
 
343
-		if(    !is_null($attr)
343
+		if (!is_null($attr)
344 344
 			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
345 345
 		) {
346 346
 			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
347
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
347
+			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: '.$this->getUsername());
348 348
 		}
349 349
 
350 350
 		//false will apply default behaviour as defined and done by OC_User
@@ -355,7 +355,7 @@  discard block
 block discarded – undo
355 355
 	public function getMemberOfGroups() {
356 356
 		$cacheKey = 'getMemberOf'.$this->getUsername();
357 357
 		$memberOfGroups = $this->connection->getFromCache($cacheKey);
358
-		if(!is_null($memberOfGroups)) {
358
+		if (!is_null($memberOfGroups)) {
359 359
 			return $memberOfGroups;
360 360
 		}
361 361
 		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
@@ -368,7 +368,7 @@  discard block
 block discarded – undo
368 368
 	 * @return string data (provided by LDAP) | false
369 369
 	 */
370 370
 	public function getAvatarImage() {
371
-		if(!is_null($this->avatarImage)) {
371
+		if (!is_null($this->avatarImage)) {
372 372
 			return $this->avatarImage;
373 373
 		}
374 374
 
@@ -376,9 +376,9 @@  discard block
 block discarded – undo
376 376
 		/** @var Connection $connection */
377 377
 		$connection = $this->access->getConnection();
378 378
 		$attributes = $connection->resolveRule('avatar');
379
-		foreach($attributes as $attribute) {
379
+		foreach ($attributes as $attribute) {
380 380
 			$result = $this->access->readAttribute($this->dn, $attribute);
381
-			if($result !== false && is_array($result) && isset($result[0])) {
381
+			if ($result !== false && is_array($result) && isset($result[0])) {
382 382
 				$this->avatarImage = $result[0];
383 383
 				break;
384 384
 			}
@@ -415,7 +415,7 @@  discard block
 block discarded – undo
415 415
 		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
416 416
 			self::USER_PREFKEY_LASTREFRESH, 0);
417 417
 
418
-		if((time() - (int)$lastChecked) < (int)$this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
418
+		if ((time() - (int) $lastChecked) < (int) $this->config->getAppValue('user_ldap', 'updateAttributesInterval', 86400)) {
419 419
 			return false;
420 420
 		}
421 421
 		return  true;
@@ -440,12 +440,12 @@  discard block
 block discarded – undo
440 440
 	 * @return string the effective display name
441 441
 	 */
442 442
 	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
443
-		$displayName2 = (string)$displayName2;
444
-		if($displayName2 !== '') {
445
-			$displayName .= ' (' . $displayName2 . ')';
443
+		$displayName2 = (string) $displayName2;
444
+		if ($displayName2 !== '') {
445
+			$displayName .= ' ('.$displayName2.')';
446 446
 		}
447 447
 		$oldName = $this->config->getUserValue($this->uid, 'user_ldap', 'displayName', null);
448
-		if ($oldName !== $displayName)  {
448
+		if ($oldName !== $displayName) {
449 449
 			$this->store('displayName', $displayName);
450 450
 			$user = $this->userManager->get($this->getUsername());
451 451
 			if (!empty($oldName) && $user instanceof \OC\User\User) {
@@ -473,7 +473,7 @@  discard block
 block discarded – undo
473 473
 	 * @return bool
474 474
 	 */
475 475
 	private function wasRefreshed($feature) {
476
-		if(isset($this->refreshedFeatures[$feature])) {
476
+		if (isset($this->refreshedFeatures[$feature])) {
477 477
 			return true;
478 478
 		}
479 479
 		$this->refreshedFeatures[$feature] = 1;
@@ -486,23 +486,23 @@  discard block
 block discarded – undo
486 486
 	 * @return null
487 487
 	 */
488 488
 	public function updateEmail($valueFromLDAP = null) {
489
-		if($this->wasRefreshed('email')) {
489
+		if ($this->wasRefreshed('email')) {
490 490
 			return;
491 491
 		}
492
-		$email = (string)$valueFromLDAP;
493
-		if(is_null($valueFromLDAP)) {
492
+		$email = (string) $valueFromLDAP;
493
+		if (is_null($valueFromLDAP)) {
494 494
 			$emailAttribute = $this->connection->ldapEmailAttribute;
495 495
 			if ($emailAttribute !== '') {
496 496
 				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
497
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
498
-					$email = (string)$aEmail[0];
497
+				if (is_array($aEmail) && (count($aEmail) > 0)) {
498
+					$email = (string) $aEmail[0];
499 499
 				}
500 500
 			}
501 501
 		}
502 502
 		if ($email !== '') {
503 503
 			$user = $this->userManager->get($this->uid);
504 504
 			if (!is_null($user)) {
505
-				$currentEmail = (string)$user->getEMailAddress();
505
+				$currentEmail = (string) $user->getEMailAddress();
506 506
 				if ($currentEmail !== $email) {
507 507
 					$user->setEMailAddress($email);
508 508
 				}
@@ -531,35 +531,35 @@  discard block
 block discarded – undo
531 531
 	 * @return null
532 532
 	 */
533 533
 	public function updateQuota($valueFromLDAP = null) {
534
-		if($this->wasRefreshed('quota')) {
534
+		if ($this->wasRefreshed('quota')) {
535 535
 			return;
536 536
 		}
537 537
 
538 538
 		$quotaAttribute = $this->connection->ldapQuotaAttribute;
539 539
 		$defaultQuota = $this->connection->ldapQuotaDefault;
540
-		if($quotaAttribute === '' && $defaultQuota === '') {
540
+		if ($quotaAttribute === '' && $defaultQuota === '') {
541 541
 			return;
542 542
 		}
543 543
 
544 544
 		$quota = false;
545
-		if(is_null($valueFromLDAP) && $quotaAttribute !== '') {
545
+		if (is_null($valueFromLDAP) && $quotaAttribute !== '') {
546 546
 			$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
547
-			if($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
547
+			if ($aQuota && (count($aQuota) > 0) && $this->verifyQuotaValue($aQuota[0])) {
548 548
 				$quota = $aQuota[0];
549
-			} else if(is_array($aQuota) && isset($aQuota[0])) {
550
-				$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', ILogger::DEBUG);
549
+			} else if (is_array($aQuota) && isset($aQuota[0])) {
550
+				$this->log->log('no suitable LDAP quota found for user '.$this->uid.': ['.$aQuota[0].']', ILogger::DEBUG);
551 551
 			}
552 552
 		} else if ($this->verifyQuotaValue($valueFromLDAP)) {
553 553
 			$quota = $valueFromLDAP;
554 554
 		} else {
555
-			$this->log->log('no suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', ILogger::DEBUG);
555
+			$this->log->log('no suitable LDAP quota found for user '.$this->uid.': ['.$valueFromLDAP.']', ILogger::DEBUG);
556 556
 		}
557 557
 
558 558
 		if ($quota === false && $this->verifyQuotaValue($defaultQuota)) {
559 559
 			// quota not found using the LDAP attribute (or not parseable). Try the default quota
560 560
 			$quota = $defaultQuota;
561
-		} else if($quota === false) {
562
-			$this->log->log('no suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', ILogger::DEBUG);
561
+		} else if ($quota === false) {
562
+			$this->log->log('no suitable default quota found for user '.$this->uid.': ['.$defaultQuota.']', ILogger::DEBUG);
563 563
 			return;
564 564
 		}
565 565
 
@@ -567,7 +567,7 @@  discard block
 block discarded – undo
567 567
 		if ($targetUser instanceof IUser) {
568 568
 			$targetUser->setQuota($quota);
569 569
 		} else {
570
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', ILogger::INFO);
570
+			$this->log->log('trying to set a quota for user '.$this->uid.' but the user is missing', ILogger::INFO);
571 571
 		}
572 572
 	}
573 573
 
@@ -581,7 +581,7 @@  discard block
 block discarded – undo
581 581
 	 * @param array $params
582 582
 	 */
583 583
 	public function updateAvatarPostLogin($params) {
584
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
584
+		if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
585 585
 			$this->updateAvatar();
586 586
 		}
587 587
 	}
@@ -591,29 +591,29 @@  discard block
 block discarded – undo
591 591
 	 * @return bool
592 592
 	 */
593 593
 	public function updateAvatar($force = false) {
594
-		if(!$force && $this->wasRefreshed('avatar')) {
594
+		if (!$force && $this->wasRefreshed('avatar')) {
595 595
 			return false;
596 596
 		}
597 597
 		$avatarImage = $this->getAvatarImage();
598
-		if($avatarImage === false) {
598
+		if ($avatarImage === false) {
599 599
 			//not set, nothing left to do;
600 600
 			return false;
601 601
 		}
602 602
 
603
-		if(!$this->image->loadFromBase64(base64_encode($avatarImage))) {
603
+		if (!$this->image->loadFromBase64(base64_encode($avatarImage))) {
604 604
 			return false;
605 605
 		}
606 606
 
607 607
 		// use the checksum before modifications
608 608
 		$checksum = md5($this->image->data());
609 609
 
610
-		if($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
610
+		if ($checksum === $this->config->getUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', '')) {
611 611
 			return true;
612 612
 		}
613 613
 
614 614
 		$isSet = $this->setOwnCloudAvatar();
615 615
 
616
-		if($isSet) {
616
+		if ($isSet) {
617 617
 			// save checksum only after successful setting
618 618
 			$this->config->setUserValue($this->uid, 'user_ldap', 'lastAvatarChecksum', $checksum);
619 619
 		}
@@ -626,7 +626,7 @@  discard block
 block discarded – undo
626 626
 	 * @return bool
627 627
 	 */
628 628
 	private function setOwnCloudAvatar() {
629
-		if(!$this->image->valid()) {
629
+		if (!$this->image->valid()) {
630 630
 			$this->log->log('avatar image data from LDAP invalid for '.$this->dn, ILogger::ERROR);
631 631
 			return false;
632 632
 		}
@@ -634,12 +634,12 @@  discard block
 block discarded – undo
634 634
 
635 635
 		//make sure it is a square and not bigger than 128x128
636 636
 		$size = min([$this->image->width(), $this->image->height(), 128]);
637
-		if(!$this->image->centerCrop($size)) {
637
+		if (!$this->image->centerCrop($size)) {
638 638
 			$this->log->log('croping image for avatar failed for '.$this->dn, ILogger::ERROR);
639 639
 			return false;
640 640
 		}
641 641
 
642
-		if(!$this->fs->isLoaded()) {
642
+		if (!$this->fs->isLoaded()) {
643 643
 			$this->fs->setup($this->uid);
644 644
 		}
645 645
 
@@ -649,7 +649,7 @@  discard block
 block discarded – undo
649 649
 			return true;
650 650
 		} catch (\Exception $e) {
651 651
 			\OC::$server->getLogger()->logException($e, [
652
-				'message' => 'Could not set avatar for ' . $this->dn,
652
+				'message' => 'Could not set avatar for '.$this->dn,
653 653
 				'level' => ILogger::INFO,
654 654
 				'app' => 'user_ldap',
655 655
 			]);
@@ -705,8 +705,8 @@  discard block
 block discarded – undo
705 705
 	 */
706 706
 	public function handlePasswordExpiry($params) {
707 707
 		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
708
-		if (empty($ppolicyDN) || ((int)$this->connection->turnOnPasswordChange !== 1)) {
709
-			return;//password expiry handling disabled
708
+		if (empty($ppolicyDN) || ((int) $this->connection->turnOnPasswordChange !== 1)) {
709
+			return; //password expiry handling disabled
710 710
 		}
711 711
 		$uid = $params['uid'];
712 712
 		if (isset($uid) && $uid === $this->getUsername()) {
@@ -715,8 +715,8 @@  discard block
 block discarded – undo
715 715
 
716 716
 			if (array_key_exists('pwdpolicysubentry', $result[0])) {
717 717
 				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
718
-				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
719
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
718
+				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
719
+					$ppolicyDN = $pwdPolicySubentry[0]; //custom ppolicy DN
720 720
 				}
721 721
 			}
722 722
 
@@ -725,9 +725,9 @@  discard block
 block discarded – undo
725 725
 			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : [];
726 726
 
727 727
 			//retrieve relevant password policy attributes
728
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
728
+			$cacheKey = 'ppolicyAttributes'.$ppolicyDN;
729 729
 			$result = $this->connection->getFromCache($cacheKey);
730
-			if(is_null($result)) {
730
+			if (is_null($result)) {
731 731
 				$result = $this->access->search('objectclass=*', [$ppolicyDN], ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
732 732
 				$this->connection->writeToCache($cacheKey, $result);
733 733
 			}
@@ -739,7 +739,7 @@  discard block
 block discarded – undo
739 739
 			//handle grace login
740 740
 			if (!empty($pwdGraceUseTime)) { //was this a grace login?
741 741
 				if (!empty($pwdGraceAuthNLimit)
742
-					&& count($pwdGraceUseTime) < (int)$pwdGraceAuthNLimit[0]) { //at least one more grace login available?
742
+					&& count($pwdGraceUseTime) < (int) $pwdGraceAuthNLimit[0]) { //at least one more grace login available?
743 743
 					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
744 744
 					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
745 745
 					'user_ldap.renewPassword.showRenewPasswordForm', ['user' => $uid]));
@@ -760,9 +760,9 @@  discard block
 block discarded – undo
760 760
 			if (!empty($pwdChangedTime)) {
761 761
 				if (!empty($pwdMaxAge)
762 762
 					&& !empty($pwdExpireWarning)) {
763
-					$pwdMaxAgeInt = (int)$pwdMaxAge[0];
764
-					$pwdExpireWarningInt = (int)$pwdExpireWarning[0];
765
-					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
763
+					$pwdMaxAgeInt = (int) $pwdMaxAge[0];
764
+					$pwdExpireWarningInt = (int) $pwdExpireWarning[0];
765
+					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
766 766
 						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
767 767
 						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
768 768
 						$currentDateTime = new \DateTime();
Please login to merge, or discard this patch.
apps/user_ldap/lib/Group_LDAP.php 2 patches
Indentation   +1231 added lines, -1231 removed lines patch added patch discarded remove patch
@@ -48,1235 +48,1235 @@
 block discarded – undo
48 48
 use OCP\ILogger;
49 49
 
50 50
 class Group_LDAP extends BackendUtility implements \OCP\GroupInterface, IGroupLDAP, IGetDisplayNameBackend {
51
-	protected $enabled = false;
52
-
53
-	/**
54
-	 * @var string[] $cachedGroupMembers array of users with gid as key
55
-	 */
56
-	protected $cachedGroupMembers;
57
-
58
-	/**
59
-	 * @var string[] $cachedGroupsByMember array of groups with uid as key
60
-	 */
61
-	protected $cachedGroupsByMember;
62
-
63
-	/**
64
-	 * @var string[] $cachedNestedGroups array of groups with gid (DN) as key
65
-	 */
66
-	protected $cachedNestedGroups;
67
-
68
-	/** @var GroupPluginManager */
69
-	protected $groupPluginManager;
70
-
71
-	public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
72
-		parent::__construct($access);
73
-		$filter = $this->access->connection->ldapGroupFilter;
74
-		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
75
-		if(!empty($filter) && !empty($gassoc)) {
76
-			$this->enabled = true;
77
-		}
78
-
79
-		$this->cachedGroupMembers = new CappedMemoryCache();
80
-		$this->cachedGroupsByMember = new CappedMemoryCache();
81
-		$this->cachedNestedGroups = new CappedMemoryCache();
82
-		$this->groupPluginManager = $groupPluginManager;
83
-	}
84
-
85
-	/**
86
-	 * is user in group?
87
-	 * @param string $uid uid of the user
88
-	 * @param string $gid gid of the group
89
-	 * @return bool
90
-	 *
91
-	 * Checks whether the user is member of a group or not.
92
-	 */
93
-	public function inGroup($uid, $gid) {
94
-		if(!$this->enabled) {
95
-			return false;
96
-		}
97
-		$cacheKey = 'inGroup'.$uid.':'.$gid;
98
-		$inGroup = $this->access->connection->getFromCache($cacheKey);
99
-		if(!is_null($inGroup)) {
100
-			return (bool)$inGroup;
101
-		}
102
-
103
-		$userDN = $this->access->username2dn($uid);
104
-
105
-		if(isset($this->cachedGroupMembers[$gid])) {
106
-			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
107
-			return $isInGroup;
108
-		}
109
-
110
-		$cacheKeyMembers = 'inGroup-members:'.$gid;
111
-		$members = $this->access->connection->getFromCache($cacheKeyMembers);
112
-		if(!is_null($members)) {
113
-			$this->cachedGroupMembers[$gid] = $members;
114
-			$isInGroup = in_array($userDN, $members, true);
115
-			$this->access->connection->writeToCache($cacheKey, $isInGroup);
116
-			return $isInGroup;
117
-		}
118
-
119
-		$groupDN = $this->access->groupname2dn($gid);
120
-		// just in case
121
-		if(!$groupDN || !$userDN) {
122
-			$this->access->connection->writeToCache($cacheKey, false);
123
-			return false;
124
-		}
125
-
126
-		//check primary group first
127
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
128
-			$this->access->connection->writeToCache($cacheKey, true);
129
-			return true;
130
-		}
131
-
132
-		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
133
-		$members = $this->_groupMembers($groupDN);
134
-		if(!is_array($members) || count($members) === 0) {
135
-			$this->access->connection->writeToCache($cacheKey, false);
136
-			return false;
137
-		}
138
-
139
-		//extra work if we don't get back user DNs
140
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
141
-			$dns = [];
142
-			$filterParts = [];
143
-			$bytes = 0;
144
-			foreach($members as $mid) {
145
-				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
146
-				$filterParts[] = $filter;
147
-				$bytes += strlen($filter);
148
-				if($bytes >= 9000000) {
149
-					// AD has a default input buffer of 10 MB, we do not want
150
-					// to take even the chance to exceed it
151
-					$filter = $this->access->combineFilterWithOr($filterParts);
152
-					$bytes = 0;
153
-					$filterParts = [];
154
-					$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
155
-					$dns = array_merge($dns, $users);
156
-				}
157
-			}
158
-			if(count($filterParts) > 0) {
159
-				$filter = $this->access->combineFilterWithOr($filterParts);
160
-				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
161
-				$dns = array_merge($dns, $users);
162
-			}
163
-			$members = $dns;
164
-		}
165
-
166
-		$isInGroup = in_array($userDN, $members);
167
-		$this->access->connection->writeToCache($cacheKey, $isInGroup);
168
-		$this->access->connection->writeToCache($cacheKeyMembers, $members);
169
-		$this->cachedGroupMembers[$gid] = $members;
170
-
171
-		return $isInGroup;
172
-	}
173
-
174
-	/**
175
-	 * @param string $dnGroup
176
-	 * @return array
177
-	 *
178
-	 * For a group that has user membership defined by an LDAP search url attribute returns the users
179
-	 * that match the search url otherwise returns an empty array.
180
-	 */
181
-	public function getDynamicGroupMembers($dnGroup) {
182
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
183
-
184
-		if (empty($dynamicGroupMemberURL)) {
185
-			return [];
186
-		}
187
-
188
-		$dynamicMembers = [];
189
-		$memberURLs = $this->access->readAttribute(
190
-			$dnGroup,
191
-			$dynamicGroupMemberURL,
192
-			$this->access->connection->ldapGroupFilter
193
-		);
194
-		if ($memberURLs !== false) {
195
-			// this group has the 'memberURL' attribute so this is a dynamic group
196
-			// example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
197
-			// example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
198
-			$pos = strpos($memberURLs[0], '(');
199
-			if ($pos !== false) {
200
-				$memberUrlFilter = substr($memberURLs[0], $pos);
201
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
202
-				$dynamicMembers = [];
203
-				foreach($foundMembers as $value) {
204
-					$dynamicMembers[$value['dn'][0]] = 1;
205
-				}
206
-			} else {
207
-				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
208
-					'of group ' . $dnGroup, ILogger::DEBUG);
209
-			}
210
-		}
211
-		return $dynamicMembers;
212
-	}
213
-
214
-	/**
215
-	 * @param string $dnGroup
216
-	 * @param array|null &$seen
217
-	 * @return array|mixed|null
218
-	 * @throws \OC\ServerNotAvailableException
219
-	 */
220
-	private function _groupMembers($dnGroup, &$seen = null) {
221
-		if ($seen === null) {
222
-			$seen = [];
223
-		}
224
-		$allMembers = [];
225
-		if (array_key_exists($dnGroup, $seen)) {
226
-			// avoid loops
227
-			return [];
228
-		}
229
-		// used extensively in cron job, caching makes sense for nested groups
230
-		$cacheKey = '_groupMembers'.$dnGroup;
231
-		$groupMembers = $this->access->connection->getFromCache($cacheKey);
232
-		if($groupMembers !== null) {
233
-			return $groupMembers;
234
-		}
235
-		$seen[$dnGroup] = 1;
236
-		$members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
237
-		if (is_array($members)) {
238
-			$fetcher = function($memberDN, &$seen) {
239
-				return $this->_groupMembers($memberDN, $seen);
240
-			};
241
-			$allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
242
-		}
243
-
244
-		$allMembers += $this->getDynamicGroupMembers($dnGroup);
245
-
246
-		$this->access->connection->writeToCache($cacheKey, $allMembers);
247
-		return $allMembers;
248
-	}
249
-
250
-	/**
251
-	 * @param string $DN
252
-	 * @param array|null &$seen
253
-	 * @return array
254
-	 * @throws \OC\ServerNotAvailableException
255
-	 */
256
-	private function _getGroupDNsFromMemberOf($DN) {
257
-		$groups = $this->access->readAttribute($DN, 'memberOf');
258
-		if (!is_array($groups)) {
259
-			return [];
260
-		}
261
-
262
-		$fetcher = function($groupDN) {
263
-			if (isset($this->cachedNestedGroups[$groupDN])) {
264
-				$nestedGroups = $this->cachedNestedGroups[$groupDN];
265
-			} else {
266
-				$nestedGroups = $this->access->readAttribute($groupDN, 'memberOf');
267
-				if (!is_array($nestedGroups)) {
268
-					$nestedGroups = [];
269
-				}
270
-				$this->cachedNestedGroups[$groupDN] = $nestedGroups;
271
-			}
272
-			return $nestedGroups;
273
-		};
274
-
275
-		$groups = $this->walkNestedGroups($DN, $fetcher, $groups);
276
-		return $this->access->groupsMatchFilter($groups);
277
-	}
278
-
279
-	/**
280
-	 * @param string $dn
281
-	 * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns
282
-	 * @param array $list
283
-	 * @return array
284
-	 */
285
-	private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array {
286
-		$nesting = (int) $this->access->connection->ldapNestedGroups;
287
-		// depending on the input, we either have a list of DNs or a list of LDAP records
288
-		// also, the output expects either DNs or records. Testing the first element should suffice.
289
-		$recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
290
-
291
-		if ($nesting !== 1) {
292
-			if($recordMode) {
293
-				// the keys are numeric, but should hold the DN
294
-				return array_reduce($list, function ($transformed, $record) use ($dn) {
295
-					if($record['dn'][0] != $dn) {
296
-						$transformed[$record['dn'][0]] = $record;
297
-					}
298
-					return $transformed;
299
-				}, []);
300
-			}
301
-			return $list;
302
-		}
303
-
304
-		$seen = [];
305
-		while ($record = array_pop($list)) {
306
-			$recordDN = $recordMode ? $record['dn'][0] : $record;
307
-			if ($recordDN === $dn || array_key_exists($recordDN, $seen)) {
308
-				// Prevent loops
309
-				continue;
310
-			}
311
-			$fetched = $fetcher($record, $seen);
312
-			$list = array_merge($list, $fetched);
313
-			$seen[$recordDN] = $record;
314
-		}
315
-
316
-		return $recordMode ? $seen : array_keys($seen);
317
-	}
318
-
319
-	/**
320
-	 * translates a gidNumber into an ownCloud internal name
321
-	 * @param string $gid as given by gidNumber on POSIX LDAP
322
-	 * @param string $dn a DN that belongs to the same domain as the group
323
-	 * @return string|bool
324
-	 */
325
-	public function gidNumber2Name($gid, $dn) {
326
-		$cacheKey = 'gidNumberToName' . $gid;
327
-		$groupName = $this->access->connection->getFromCache($cacheKey);
328
-		if(!is_null($groupName) && isset($groupName)) {
329
-			return $groupName;
330
-		}
331
-
332
-		//we need to get the DN from LDAP
333
-		$filter = $this->access->combineFilterWithAnd([
334
-			$this->access->connection->ldapGroupFilter,
335
-			'objectClass=posixGroup',
336
-			$this->access->connection->ldapGidNumber . '=' . $gid
337
-		]);
338
-		$result = $this->access->searchGroups($filter, ['dn'], 1);
339
-		if(empty($result)) {
340
-			return false;
341
-		}
342
-		$dn = $result[0]['dn'][0];
343
-
344
-		//and now the group name
345
-		//NOTE once we have separate ownCloud group IDs and group names we can
346
-		//directly read the display name attribute instead of the DN
347
-		$name = $this->access->dn2groupname($dn);
348
-
349
-		$this->access->connection->writeToCache($cacheKey, $name);
350
-
351
-		return $name;
352
-	}
353
-
354
-	/**
355
-	 * returns the entry's gidNumber
356
-	 * @param string $dn
357
-	 * @param string $attribute
358
-	 * @return string|bool
359
-	 */
360
-	private function getEntryGidNumber($dn, $attribute) {
361
-		$value = $this->access->readAttribute($dn, $attribute);
362
-		if(is_array($value) && !empty($value)) {
363
-			return $value[0];
364
-		}
365
-		return false;
366
-	}
367
-
368
-	/**
369
-	 * returns the group's primary ID
370
-	 * @param string $dn
371
-	 * @return string|bool
372
-	 */
373
-	public function getGroupGidNumber($dn) {
374
-		return $this->getEntryGidNumber($dn, 'gidNumber');
375
-	}
376
-
377
-	/**
378
-	 * returns the user's gidNumber
379
-	 * @param string $dn
380
-	 * @return string|bool
381
-	 */
382
-	public function getUserGidNumber($dn) {
383
-		$gidNumber = false;
384
-		if($this->access->connection->hasGidNumber) {
385
-			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
386
-			if($gidNumber === false) {
387
-				$this->access->connection->hasGidNumber = false;
388
-			}
389
-		}
390
-		return $gidNumber;
391
-	}
392
-
393
-	/**
394
-	 * returns a filter for a "users has specific gid" search or count operation
395
-	 *
396
-	 * @param string $groupDN
397
-	 * @param string $search
398
-	 * @return string
399
-	 * @throws \Exception
400
-	 */
401
-	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
402
-		$groupID = $this->getGroupGidNumber($groupDN);
403
-		if($groupID === false) {
404
-			throw new \Exception('Not a valid group');
405
-		}
406
-
407
-		$filterParts = [];
408
-		$filterParts[] = $this->access->getFilterForUserCount();
409
-		if ($search !== '') {
410
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
411
-		}
412
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
413
-
414
-		return $this->access->combineFilterWithAnd($filterParts);
415
-	}
416
-
417
-	/**
418
-	 * returns a list of users that have the given group as gid number
419
-	 *
420
-	 * @param string $groupDN
421
-	 * @param string $search
422
-	 * @param int $limit
423
-	 * @param int $offset
424
-	 * @return string[]
425
-	 */
426
-	public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
427
-		try {
428
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
429
-			$users = $this->access->fetchListOfUsers(
430
-				$filter,
431
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
432
-				$limit,
433
-				$offset
434
-			);
435
-			return $this->access->nextcloudUserNames($users);
436
-		} catch (\Exception $e) {
437
-			return [];
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * returns the number of users that have the given group as gid number
443
-	 *
444
-	 * @param string $groupDN
445
-	 * @param string $search
446
-	 * @param int $limit
447
-	 * @param int $offset
448
-	 * @return int
449
-	 */
450
-	public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
451
-		try {
452
-			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
453
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
454
-			return (int)$users;
455
-		} catch (\Exception $e) {
456
-			return 0;
457
-		}
458
-	}
459
-
460
-	/**
461
-	 * gets the gidNumber of a user
462
-	 * @param string $dn
463
-	 * @return string
464
-	 */
465
-	public function getUserGroupByGid($dn) {
466
-		$groupID = $this->getUserGidNumber($dn);
467
-		if($groupID !== false) {
468
-			$groupName = $this->gidNumber2Name($groupID, $dn);
469
-			if($groupName !== false) {
470
-				return $groupName;
471
-			}
472
-		}
473
-
474
-		return false;
475
-	}
476
-
477
-	/**
478
-	 * translates a primary group ID into an Nextcloud internal name
479
-	 * @param string $gid as given by primaryGroupID on AD
480
-	 * @param string $dn a DN that belongs to the same domain as the group
481
-	 * @return string|bool
482
-	 */
483
-	public function primaryGroupID2Name($gid, $dn) {
484
-		$cacheKey = 'primaryGroupIDtoName';
485
-		$groupNames = $this->access->connection->getFromCache($cacheKey);
486
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
487
-			return $groupNames[$gid];
488
-		}
489
-
490
-		$domainObjectSid = $this->access->getSID($dn);
491
-		if($domainObjectSid === false) {
492
-			return false;
493
-		}
494
-
495
-		//we need to get the DN from LDAP
496
-		$filter = $this->access->combineFilterWithAnd([
497
-			$this->access->connection->ldapGroupFilter,
498
-			'objectsid=' . $domainObjectSid . '-' . $gid
499
-		]);
500
-		$result = $this->access->searchGroups($filter, ['dn'], 1);
501
-		if(empty($result)) {
502
-			return false;
503
-		}
504
-		$dn = $result[0]['dn'][0];
505
-
506
-		//and now the group name
507
-		//NOTE once we have separate Nextcloud group IDs and group names we can
508
-		//directly read the display name attribute instead of the DN
509
-		$name = $this->access->dn2groupname($dn);
510
-
511
-		$this->access->connection->writeToCache($cacheKey, $name);
512
-
513
-		return $name;
514
-	}
515
-
516
-	/**
517
-	 * returns the entry's primary group ID
518
-	 * @param string $dn
519
-	 * @param string $attribute
520
-	 * @return string|bool
521
-	 */
522
-	private function getEntryGroupID($dn, $attribute) {
523
-		$value = $this->access->readAttribute($dn, $attribute);
524
-		if(is_array($value) && !empty($value)) {
525
-			return $value[0];
526
-		}
527
-		return false;
528
-	}
529
-
530
-	/**
531
-	 * returns the group's primary ID
532
-	 * @param string $dn
533
-	 * @return string|bool
534
-	 */
535
-	public function getGroupPrimaryGroupID($dn) {
536
-		return $this->getEntryGroupID($dn, 'primaryGroupToken');
537
-	}
538
-
539
-	/**
540
-	 * returns the user's primary group ID
541
-	 * @param string $dn
542
-	 * @return string|bool
543
-	 */
544
-	public function getUserPrimaryGroupIDs($dn) {
545
-		$primaryGroupID = false;
546
-		if($this->access->connection->hasPrimaryGroups) {
547
-			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
548
-			if($primaryGroupID === false) {
549
-				$this->access->connection->hasPrimaryGroups = false;
550
-			}
551
-		}
552
-		return $primaryGroupID;
553
-	}
554
-
555
-	/**
556
-	 * returns a filter for a "users in primary group" search or count operation
557
-	 *
558
-	 * @param string $groupDN
559
-	 * @param string $search
560
-	 * @return string
561
-	 * @throws \Exception
562
-	 */
563
-	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
564
-		$groupID = $this->getGroupPrimaryGroupID($groupDN);
565
-		if($groupID === false) {
566
-			throw new \Exception('Not a valid group');
567
-		}
568
-
569
-		$filterParts = [];
570
-		$filterParts[] = $this->access->getFilterForUserCount();
571
-		if ($search !== '') {
572
-			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
573
-		}
574
-		$filterParts[] = 'primaryGroupID=' . $groupID;
575
-
576
-		return $this->access->combineFilterWithAnd($filterParts);
577
-	}
578
-
579
-	/**
580
-	 * returns a list of users that have the given group as primary group
581
-	 *
582
-	 * @param string $groupDN
583
-	 * @param string $search
584
-	 * @param int $limit
585
-	 * @param int $offset
586
-	 * @return string[]
587
-	 */
588
-	public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
589
-		try {
590
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
591
-			$users = $this->access->fetchListOfUsers(
592
-				$filter,
593
-				[$this->access->connection->ldapUserDisplayName, 'dn'],
594
-				$limit,
595
-				$offset
596
-			);
597
-			return $this->access->nextcloudUserNames($users);
598
-		} catch (\Exception $e) {
599
-			return [];
600
-		}
601
-	}
602
-
603
-	/**
604
-	 * returns the number of users that have the given group as primary group
605
-	 *
606
-	 * @param string $groupDN
607
-	 * @param string $search
608
-	 * @param int $limit
609
-	 * @param int $offset
610
-	 * @return int
611
-	 */
612
-	public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
613
-		try {
614
-			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
615
-			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
616
-			return (int)$users;
617
-		} catch (\Exception $e) {
618
-			return 0;
619
-		}
620
-	}
621
-
622
-	/**
623
-	 * gets the primary group of a user
624
-	 * @param string $dn
625
-	 * @return string
626
-	 */
627
-	public function getUserPrimaryGroup($dn) {
628
-		$groupID = $this->getUserPrimaryGroupIDs($dn);
629
-		if($groupID !== false) {
630
-			$groupName = $this->primaryGroupID2Name($groupID, $dn);
631
-			if($groupName !== false) {
632
-				return $groupName;
633
-			}
634
-		}
635
-
636
-		return false;
637
-	}
638
-
639
-	/**
640
-	 * Get all groups a user belongs to
641
-	 * @param string $uid Name of the user
642
-	 * @return array with group names
643
-	 *
644
-	 * This function fetches all groups a user belongs to. It does not check
645
-	 * if the user exists at all.
646
-	 *
647
-	 * This function includes groups based on dynamic group membership.
648
-	 */
649
-	public function getUserGroups($uid) {
650
-		if(!$this->enabled) {
651
-			return [];
652
-		}
653
-		$cacheKey = 'getUserGroups'.$uid;
654
-		$userGroups = $this->access->connection->getFromCache($cacheKey);
655
-		if(!is_null($userGroups)) {
656
-			return $userGroups;
657
-		}
658
-		$userDN = $this->access->username2dn($uid);
659
-		if(!$userDN) {
660
-			$this->access->connection->writeToCache($cacheKey, []);
661
-			return [];
662
-		}
663
-
664
-		$groups = [];
665
-		$primaryGroup = $this->getUserPrimaryGroup($userDN);
666
-		$gidGroupName = $this->getUserGroupByGid($userDN);
667
-
668
-		$dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
669
-
670
-		if (!empty($dynamicGroupMemberURL)) {
671
-			// look through dynamic groups to add them to the result array if needed
672
-			$groupsToMatch = $this->access->fetchListOfGroups(
673
-				$this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
674
-			foreach($groupsToMatch as $dynamicGroup) {
675
-				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
676
-					continue;
677
-				}
678
-				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
679
-				if ($pos !== false) {
680
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
681
-					// apply filter via ldap search to see if this user is in this
682
-					// dynamic group
683
-					$userMatch = $this->access->readAttribute(
684
-						$userDN,
685
-						$this->access->connection->ldapUserDisplayName,
686
-						$memberUrlFilter
687
-					);
688
-					if ($userMatch !== false) {
689
-						// match found so this user is in this group
690
-						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
691
-						if(is_string($groupName)) {
692
-							// be sure to never return false if the dn could not be
693
-							// resolved to a name, for whatever reason.
694
-							$groups[] = $groupName;
695
-						}
696
-					}
697
-				} else {
698
-					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
699
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
700
-				}
701
-			}
702
-		}
703
-
704
-		// if possible, read out membership via memberOf. It's far faster than
705
-		// performing a search, which still is a fallback later.
706
-		// memberof doesn't support memberuid, so skip it here.
707
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
708
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
709
-		    && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
710
-		    ) {
711
-			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
712
-			if (is_array($groupDNs)) {
713
-				foreach ($groupDNs as $dn) {
714
-					$groupName = $this->access->dn2groupname($dn);
715
-					if(is_string($groupName)) {
716
-						// be sure to never return false if the dn could not be
717
-						// resolved to a name, for whatever reason.
718
-						$groups[] = $groupName;
719
-					}
720
-				}
721
-			}
722
-
723
-			if($primaryGroup !== false) {
724
-				$groups[] = $primaryGroup;
725
-			}
726
-			if($gidGroupName !== false) {
727
-				$groups[] = $gidGroupName;
728
-			}
729
-			$this->access->connection->writeToCache($cacheKey, $groups);
730
-			return $groups;
731
-		}
732
-
733
-		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
734
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
735
-			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
736
-		) {
737
-			$uid = $userDN;
738
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
739
-			$result = $this->access->readAttribute($userDN, 'uid');
740
-			if ($result === false) {
741
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
742
-					$this->access->connection->ldapHost, ILogger::DEBUG);
743
-				$uid = false;
744
-			} else {
745
-				$uid = $result[0];
746
-			}
747
-		} else {
748
-			// just in case
749
-			$uid = $userDN;
750
-		}
751
-
752
-		if($uid !== false) {
753
-			if (isset($this->cachedGroupsByMember[$uid])) {
754
-				$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
755
-			} else {
756
-				$groupsByMember = array_values($this->getGroupsByMember($uid));
757
-				$groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
758
-				$this->cachedGroupsByMember[$uid] = $groupsByMember;
759
-				$groups = array_merge($groups, $groupsByMember);
760
-			}
761
-		}
762
-
763
-		if($primaryGroup !== false) {
764
-			$groups[] = $primaryGroup;
765
-		}
766
-		if($gidGroupName !== false) {
767
-			$groups[] = $gidGroupName;
768
-		}
769
-
770
-		$groups = array_unique($groups, SORT_LOCALE_STRING);
771
-		$this->access->connection->writeToCache($cacheKey, $groups);
772
-
773
-		return $groups;
774
-	}
775
-
776
-	/**
777
-	 * @param string $dn
778
-	 * @param array|null &$seen
779
-	 * @return array
780
-	 */
781
-	private function getGroupsByMember($dn, &$seen = null) {
782
-		if ($seen === null) {
783
-			$seen = [];
784
-		}
785
-		if (array_key_exists($dn, $seen)) {
786
-			// avoid loops
787
-			return [];
788
-		}
789
-		$allGroups = [];
790
-		$seen[$dn] = true;
791
-		$filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn;
792
-		$groups = $this->access->fetchListOfGroups($filter,
793
-			[$this->access->connection->ldapGroupDisplayName, 'dn']);
794
-		if (is_array($groups)) {
795
-			$fetcher = function ($dn, &$seen) {
796
-				if(is_array($dn) && isset($dn['dn'][0])) {
797
-					$dn = $dn['dn'][0];
798
-				}
799
-				return $this->getGroupsByMember($dn, $seen);
800
-			};
801
-			$allGroups = $this->walkNestedGroups($dn, $fetcher, $groups);
802
-		}
803
-		$visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups));
804
-		return array_intersect_key($allGroups, array_flip($visibleGroups));
805
-	}
806
-
807
-	/**
808
-	 * get a list of all users in a group
809
-	 *
810
-	 * @param string $gid
811
-	 * @param string $search
812
-	 * @param int $limit
813
-	 * @param int $offset
814
-	 * @return array with user ids
815
-	 * @throws \Exception
816
-	 */
817
-	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
818
-		if(!$this->enabled) {
819
-			return [];
820
-		}
821
-		if(!$this->groupExists($gid)) {
822
-			return [];
823
-		}
824
-		$search = $this->access->escapeFilterPart($search, true);
825
-		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
826
-		// check for cache of the exact query
827
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
828
-		if(!is_null($groupUsers)) {
829
-			return $groupUsers;
830
-		}
831
-
832
-		// check for cache of the query without limit and offset
833
-		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
834
-		if(!is_null($groupUsers)) {
835
-			$groupUsers = array_slice($groupUsers, $offset, $limit);
836
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
837
-			return $groupUsers;
838
-		}
839
-
840
-		if($limit === -1) {
841
-			$limit = null;
842
-		}
843
-		$groupDN = $this->access->groupname2dn($gid);
844
-		if(!$groupDN) {
845
-			// group couldn't be found, return empty resultset
846
-			$this->access->connection->writeToCache($cacheKey, []);
847
-			return [];
848
-		}
849
-
850
-		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
851
-		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
852
-		$members = $this->_groupMembers($groupDN);
853
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
854
-			//in case users could not be retrieved, return empty result set
855
-			$this->access->connection->writeToCache($cacheKey, []);
856
-			return [];
857
-		}
858
-
859
-		$groupUsers = [];
860
-		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
861
-		$attrs = $this->access->userManager->getAttributes(true);
862
-		foreach($members as $member) {
863
-			if($isMemberUid) {
864
-				//we got uids, need to get their DNs to 'translate' them to user names
865
-				$filter = $this->access->combineFilterWithAnd([
866
-					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
867
-					$this->access->combineFilterWithAnd([
868
-						$this->access->getFilterPartForUserSearch($search),
869
-						$this->access->connection->ldapUserFilter
870
-					])
871
-				]);
872
-				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
873
-				if(count($ldap_users) < 1) {
874
-					continue;
875
-				}
876
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
877
-			} else {
878
-				//we got DNs, check if we need to filter by search or we can give back all of them
879
-				$uid = $this->access->dn2username($member);
880
-				if(!$uid) {
881
-					continue;
882
-				}
883
-
884
-				$cacheKey = 'userExistsOnLDAP' . $uid;
885
-				$userExists = $this->access->connection->getFromCache($cacheKey);
886
-				if($userExists === false) {
887
-					continue;
888
-				}
889
-				if($userExists === null || $search !== '') {
890
-					if (!$this->access->readAttribute($member,
891
-						$this->access->connection->ldapUserDisplayName,
892
-						$this->access->combineFilterWithAnd([
893
-							$this->access->getFilterPartForUserSearch($search),
894
-							$this->access->connection->ldapUserFilter
895
-						])))
896
-					{
897
-						if($search === '') {
898
-							$this->access->connection->writeToCache($cacheKey, false);
899
-						}
900
-						continue;
901
-					}
902
-					$this->access->connection->writeToCache($cacheKey, true);
903
-				}
904
-				$groupUsers[] = $uid;
905
-			}
906
-		}
907
-
908
-		$groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
909
-		natsort($groupUsers);
910
-		$this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
911
-		$groupUsers = array_slice($groupUsers, $offset, $limit);
912
-
913
-		$this->access->connection->writeToCache($cacheKey, $groupUsers);
914
-
915
-		return $groupUsers;
916
-	}
917
-
918
-	/**
919
-	 * returns the number of users in a group, who match the search term
920
-	 * @param string $gid the internal group name
921
-	 * @param string $search optional, a search string
922
-	 * @return int|bool
923
-	 */
924
-	public function countUsersInGroup($gid, $search = '') {
925
-		if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
926
-			return $this->groupPluginManager->countUsersInGroup($gid, $search);
927
-		}
928
-
929
-		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
930
-		if(!$this->enabled || !$this->groupExists($gid)) {
931
-			return false;
932
-		}
933
-		$groupUsers = $this->access->connection->getFromCache($cacheKey);
934
-		if(!is_null($groupUsers)) {
935
-			return $groupUsers;
936
-		}
937
-
938
-		$groupDN = $this->access->groupname2dn($gid);
939
-		if(!$groupDN) {
940
-			// group couldn't be found, return empty result set
941
-			$this->access->connection->writeToCache($cacheKey, false);
942
-			return false;
943
-		}
944
-
945
-		$members = $this->_groupMembers($groupDN);
946
-		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
947
-		if(!$members && $primaryUserCount === 0) {
948
-			//in case users could not be retrieved, return empty result set
949
-			$this->access->connection->writeToCache($cacheKey, false);
950
-			return false;
951
-		}
952
-
953
-		if ($search === '') {
954
-			$groupUsers = count($members) + $primaryUserCount;
955
-			$this->access->connection->writeToCache($cacheKey, $groupUsers);
956
-			return $groupUsers;
957
-		}
958
-		$search = $this->access->escapeFilterPart($search, true);
959
-		$isMemberUid =
960
-			(strtolower($this->access->connection->ldapGroupMemberAssocAttr)
961
-			=== 'memberuid');
962
-
963
-		//we need to apply the search filter
964
-		//alternatives that need to be checked:
965
-		//a) get all users by search filter and array_intersect them
966
-		//b) a, but only when less than 1k 10k ?k users like it is
967
-		//c) put all DNs|uids in a LDAP filter, combine with the search string
968
-		//   and let it count.
969
-		//For now this is not important, because the only use of this method
970
-		//does not supply a search string
971
-		$groupUsers = [];
972
-		foreach($members as $member) {
973
-			if($isMemberUid) {
974
-				//we got uids, need to get their DNs to 'translate' them to user names
975
-				$filter = $this->access->combineFilterWithAnd([
976
-					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
977
-					$this->access->getFilterPartForUserSearch($search)
978
-				]);
979
-				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
980
-				if(count($ldap_users) < 1) {
981
-					continue;
982
-				}
983
-				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
984
-			} else {
985
-				//we need to apply the search filter now
986
-				if(!$this->access->readAttribute($member,
987
-					$this->access->connection->ldapUserDisplayName,
988
-					$this->access->getFilterPartForUserSearch($search))) {
989
-					continue;
990
-				}
991
-				// dn2username will also check if the users belong to the allowed base
992
-				if($ocname = $this->access->dn2username($member)) {
993
-					$groupUsers[] = $ocname;
994
-				}
995
-			}
996
-		}
997
-
998
-		//and get users that have the group as primary
999
-		$primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
1000
-
1001
-		return count($groupUsers) + $primaryUsers;
1002
-	}
1003
-
1004
-	/**
1005
-	 * get a list of all groups
1006
-	 *
1007
-	 * @param string $search
1008
-	 * @param $limit
1009
-	 * @param int $offset
1010
-	 * @return array with group names
1011
-	 *
1012
-	 * Returns a list with all groups (used by getGroups)
1013
-	 */
1014
-	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1015
-		if(!$this->enabled) {
1016
-			return [];
1017
-		}
1018
-		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
1019
-
1020
-		//Check cache before driving unnecessary searches
1021
-		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1022
-		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
1023
-		if(!is_null($ldap_groups)) {
1024
-			return $ldap_groups;
1025
-		}
1026
-
1027
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
1028
-		// error. With a limit of 0, we get 0 results. So we pass null.
1029
-		if($limit <= 0) {
1030
-			$limit = null;
1031
-		}
1032
-		$filter = $this->access->combineFilterWithAnd([
1033
-			$this->access->connection->ldapGroupFilter,
1034
-			$this->access->getFilterPartForGroupSearch($search)
1035
-		]);
1036
-		\OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
1037
-		$ldap_groups = $this->access->fetchListOfGroups($filter,
1038
-				[$this->access->connection->ldapGroupDisplayName, 'dn'],
1039
-				$limit,
1040
-				$offset);
1041
-		$ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
1042
-
1043
-		$this->access->connection->writeToCache($cacheKey, $ldap_groups);
1044
-		return $ldap_groups;
1045
-	}
1046
-
1047
-	/**
1048
-	 * get a list of all groups using a paged search
1049
-	 *
1050
-	 * @param string $search
1051
-	 * @param int $limit
1052
-	 * @param int $offset
1053
-	 * @return array with group names
1054
-	 *
1055
-	 * Returns a list with all groups
1056
-	 * Uses a paged search if available to override a
1057
-	 * server side search limit.
1058
-	 * (active directory has a limit of 1000 by default)
1059
-	 */
1060
-	public function getGroups($search = '', $limit = -1, $offset = 0) {
1061
-		if(!$this->enabled) {
1062
-			return [];
1063
-		}
1064
-		$search = $this->access->escapeFilterPart($search, true);
1065
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1066
-		if ($pagingSize <= 0) {
1067
-			return $this->getGroupsChunk($search, $limit, $offset);
1068
-		}
1069
-		$maxGroups = 100000; // limit max results (just for safety reasons)
1070
-		if ($limit > -1) {
1071
-		   $overallLimit = min($limit + $offset, $maxGroups);
1072
-		} else {
1073
-		   $overallLimit = $maxGroups;
1074
-		}
1075
-		$chunkOffset = $offset;
1076
-		$allGroups = [];
1077
-		while ($chunkOffset < $overallLimit) {
1078
-			$chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1079
-			$ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1080
-			$nread = count($ldapGroups);
1081
-			\OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1082
-			if ($nread) {
1083
-				$allGroups = array_merge($allGroups, $ldapGroups);
1084
-				$chunkOffset += $nread;
1085
-			}
1086
-			if ($nread < $chunkLimit) {
1087
-				break;
1088
-			}
1089
-		}
1090
-		return $allGroups;
1091
-	}
1092
-
1093
-	/**
1094
-	 * @param string $group
1095
-	 * @return bool
1096
-	 */
1097
-	public function groupMatchesFilter($group) {
1098
-		return (strripos($group, $this->groupSearch) !== false);
1099
-	}
1100
-
1101
-	/**
1102
-	 * check if a group exists
1103
-	 * @param string $gid
1104
-	 * @return bool
1105
-	 */
1106
-	public function groupExists($gid) {
1107
-		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1108
-		if(!is_null($groupExists)) {
1109
-			return (bool)$groupExists;
1110
-		}
1111
-
1112
-		//getting dn, if false the group does not exist. If dn, it may be mapped
1113
-		//only, requires more checking.
1114
-		$dn = $this->access->groupname2dn($gid);
1115
-		if(!$dn) {
1116
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1117
-			return false;
1118
-		}
1119
-
1120
-		//if group really still exists, we will be able to read its objectclass
1121
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1122
-			$this->access->connection->writeToCache('groupExists'.$gid, false);
1123
-			return false;
1124
-		}
1125
-
1126
-		$this->access->connection->writeToCache('groupExists'.$gid, true);
1127
-		return true;
1128
-	}
1129
-
1130
-	/**
1131
-	* Check if backend implements actions
1132
-	* @param int $actions bitwise-or'ed actions
1133
-	* @return boolean
1134
-	*
1135
-	* Returns the supported actions as int to be
1136
-	* compared with GroupInterface::CREATE_GROUP etc.
1137
-	*/
1138
-	public function implementsActions($actions) {
1139
-		return (bool)((GroupInterface::COUNT_USERS |
1140
-				$this->groupPluginManager->getImplementedActions()) & $actions);
1141
-	}
1142
-
1143
-	/**
1144
-	 * Return access for LDAP interaction.
1145
-	 * @return Access instance of Access for LDAP interaction
1146
-	 */
1147
-	public function getLDAPAccess($gid) {
1148
-		return $this->access;
1149
-	}
1150
-
1151
-	/**
1152
-	 * create a group
1153
-	 * @param string $gid
1154
-	 * @return bool
1155
-	 * @throws \Exception
1156
-	 */
1157
-	public function createGroup($gid) {
1158
-		if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1159
-			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1160
-				//updates group mapping
1161
-				$uuid = $this->access->getUUID($dn, false);
1162
-				if(is_string($uuid)) {
1163
-					$this->access->mapAndAnnounceIfApplicable(
1164
-						$this->access->getGroupMapper(),
1165
-						$dn,
1166
-						$gid,
1167
-						$uuid,
1168
-						false
1169
-					);
1170
-					$this->access->cacheGroupExists($gid);
1171
-				}
1172
-			}
1173
-			return $dn != null;
1174
-		}
1175
-		throw new \Exception('Could not create group in LDAP backend.');
1176
-	}
1177
-
1178
-	/**
1179
-	 * delete a group
1180
-	 * @param string $gid gid of the group to delete
1181
-	 * @return bool
1182
-	 * @throws \Exception
1183
-	 */
1184
-	public function deleteGroup($gid) {
1185
-		if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1186
-			if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1187
-				#delete group in nextcloud internal db
1188
-				$this->access->getGroupMapper()->unmap($gid);
1189
-				$this->access->connection->writeToCache("groupExists".$gid, false);
1190
-			}
1191
-			return $ret;
1192
-		}
1193
-		throw new \Exception('Could not delete group in LDAP backend.');
1194
-	}
1195
-
1196
-	/**
1197
-	 * Add a user to a group
1198
-	 * @param string $uid Name of the user to add to group
1199
-	 * @param string $gid Name of the group in which add the user
1200
-	 * @return bool
1201
-	 * @throws \Exception
1202
-	 */
1203
-	public function addToGroup($uid, $gid) {
1204
-		if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1205
-			if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1206
-				$this->access->connection->clearCache();
1207
-				unset($this->cachedGroupMembers[$gid]);
1208
-			}
1209
-			return $ret;
1210
-		}
1211
-		throw new \Exception('Could not add user to group in LDAP backend.');
1212
-	}
1213
-
1214
-	/**
1215
-	 * Removes a user from a group
1216
-	 * @param string $uid Name of the user to remove from group
1217
-	 * @param string $gid Name of the group from which remove the user
1218
-	 * @return bool
1219
-	 * @throws \Exception
1220
-	 */
1221
-	public function removeFromGroup($uid, $gid) {
1222
-		if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1223
-			if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1224
-				$this->access->connection->clearCache();
1225
-				unset($this->cachedGroupMembers[$gid]);
1226
-			}
1227
-			return $ret;
1228
-		}
1229
-		throw new \Exception('Could not remove user from group in LDAP backend.');
1230
-	}
1231
-
1232
-	/**
1233
-	 * Gets group details
1234
-	 * @param string $gid Name of the group
1235
-	 * @return array | false
1236
-	 * @throws \Exception
1237
-	 */
1238
-	public function getGroupDetails($gid) {
1239
-		if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1240
-			return $this->groupPluginManager->getGroupDetails($gid);
1241
-		}
1242
-		throw new \Exception('Could not get group details in LDAP backend.');
1243
-	}
1244
-
1245
-	/**
1246
-	 * Return LDAP connection resource from a cloned connection.
1247
-	 * The cloned connection needs to be closed manually.
1248
-	 * of the current access.
1249
-	 * @param string $gid
1250
-	 * @return resource of the LDAP connection
1251
-	 */
1252
-	public function getNewLDAPConnection($gid) {
1253
-		$connection = clone $this->access->getConnection();
1254
-		return $connection->getConnectionResource();
1255
-	}
1256
-
1257
-	/**
1258
-	 * @throws \OC\ServerNotAvailableException
1259
-	 */
1260
-	public function getDisplayName(string $gid): string {
1261
-		if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
1262
-			return $this->groupPluginManager->getDisplayName($gid);
1263
-		}
1264
-
1265
-		$cacheKey = 'group_getDisplayName' . $gid;
1266
-		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1267
-			return $displayName;
1268
-		}
1269
-
1270
-		$displayName = $this->access->readAttribute(
1271
-			$this->access->groupname2dn($gid),
1272
-			$this->access->connection->ldapGroupDisplayName);
1273
-
1274
-		if ($displayName && (count($displayName) > 0)) {
1275
-			$displayName = $displayName[0];
1276
-			$this->access->connection->writeToCache($cacheKey, $displayName);
1277
-			return $displayName;
1278
-		}
1279
-
1280
-		return '';
1281
-	}
51
+    protected $enabled = false;
52
+
53
+    /**
54
+     * @var string[] $cachedGroupMembers array of users with gid as key
55
+     */
56
+    protected $cachedGroupMembers;
57
+
58
+    /**
59
+     * @var string[] $cachedGroupsByMember array of groups with uid as key
60
+     */
61
+    protected $cachedGroupsByMember;
62
+
63
+    /**
64
+     * @var string[] $cachedNestedGroups array of groups with gid (DN) as key
65
+     */
66
+    protected $cachedNestedGroups;
67
+
68
+    /** @var GroupPluginManager */
69
+    protected $groupPluginManager;
70
+
71
+    public function __construct(Access $access, GroupPluginManager $groupPluginManager) {
72
+        parent::__construct($access);
73
+        $filter = $this->access->connection->ldapGroupFilter;
74
+        $gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
75
+        if(!empty($filter) && !empty($gassoc)) {
76
+            $this->enabled = true;
77
+        }
78
+
79
+        $this->cachedGroupMembers = new CappedMemoryCache();
80
+        $this->cachedGroupsByMember = new CappedMemoryCache();
81
+        $this->cachedNestedGroups = new CappedMemoryCache();
82
+        $this->groupPluginManager = $groupPluginManager;
83
+    }
84
+
85
+    /**
86
+     * is user in group?
87
+     * @param string $uid uid of the user
88
+     * @param string $gid gid of the group
89
+     * @return bool
90
+     *
91
+     * Checks whether the user is member of a group or not.
92
+     */
93
+    public function inGroup($uid, $gid) {
94
+        if(!$this->enabled) {
95
+            return false;
96
+        }
97
+        $cacheKey = 'inGroup'.$uid.':'.$gid;
98
+        $inGroup = $this->access->connection->getFromCache($cacheKey);
99
+        if(!is_null($inGroup)) {
100
+            return (bool)$inGroup;
101
+        }
102
+
103
+        $userDN = $this->access->username2dn($uid);
104
+
105
+        if(isset($this->cachedGroupMembers[$gid])) {
106
+            $isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
107
+            return $isInGroup;
108
+        }
109
+
110
+        $cacheKeyMembers = 'inGroup-members:'.$gid;
111
+        $members = $this->access->connection->getFromCache($cacheKeyMembers);
112
+        if(!is_null($members)) {
113
+            $this->cachedGroupMembers[$gid] = $members;
114
+            $isInGroup = in_array($userDN, $members, true);
115
+            $this->access->connection->writeToCache($cacheKey, $isInGroup);
116
+            return $isInGroup;
117
+        }
118
+
119
+        $groupDN = $this->access->groupname2dn($gid);
120
+        // just in case
121
+        if(!$groupDN || !$userDN) {
122
+            $this->access->connection->writeToCache($cacheKey, false);
123
+            return false;
124
+        }
125
+
126
+        //check primary group first
127
+        if($gid === $this->getUserPrimaryGroup($userDN)) {
128
+            $this->access->connection->writeToCache($cacheKey, true);
129
+            return true;
130
+        }
131
+
132
+        //usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
133
+        $members = $this->_groupMembers($groupDN);
134
+        if(!is_array($members) || count($members) === 0) {
135
+            $this->access->connection->writeToCache($cacheKey, false);
136
+            return false;
137
+        }
138
+
139
+        //extra work if we don't get back user DNs
140
+        if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
141
+            $dns = [];
142
+            $filterParts = [];
143
+            $bytes = 0;
144
+            foreach($members as $mid) {
145
+                $filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
146
+                $filterParts[] = $filter;
147
+                $bytes += strlen($filter);
148
+                if($bytes >= 9000000) {
149
+                    // AD has a default input buffer of 10 MB, we do not want
150
+                    // to take even the chance to exceed it
151
+                    $filter = $this->access->combineFilterWithOr($filterParts);
152
+                    $bytes = 0;
153
+                    $filterParts = [];
154
+                    $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
155
+                    $dns = array_merge($dns, $users);
156
+                }
157
+            }
158
+            if(count($filterParts) > 0) {
159
+                $filter = $this->access->combineFilterWithOr($filterParts);
160
+                $users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
161
+                $dns = array_merge($dns, $users);
162
+            }
163
+            $members = $dns;
164
+        }
165
+
166
+        $isInGroup = in_array($userDN, $members);
167
+        $this->access->connection->writeToCache($cacheKey, $isInGroup);
168
+        $this->access->connection->writeToCache($cacheKeyMembers, $members);
169
+        $this->cachedGroupMembers[$gid] = $members;
170
+
171
+        return $isInGroup;
172
+    }
173
+
174
+    /**
175
+     * @param string $dnGroup
176
+     * @return array
177
+     *
178
+     * For a group that has user membership defined by an LDAP search url attribute returns the users
179
+     * that match the search url otherwise returns an empty array.
180
+     */
181
+    public function getDynamicGroupMembers($dnGroup) {
182
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
183
+
184
+        if (empty($dynamicGroupMemberURL)) {
185
+            return [];
186
+        }
187
+
188
+        $dynamicMembers = [];
189
+        $memberURLs = $this->access->readAttribute(
190
+            $dnGroup,
191
+            $dynamicGroupMemberURL,
192
+            $this->access->connection->ldapGroupFilter
193
+        );
194
+        if ($memberURLs !== false) {
195
+            // this group has the 'memberURL' attribute so this is a dynamic group
196
+            // example 1: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(o=HeadOffice)
197
+            // example 2: ldap:///cn=users,cn=accounts,dc=dcsubbase,dc=dcbase??one?(&(o=HeadOffice)(uidNumber>=500))
198
+            $pos = strpos($memberURLs[0], '(');
199
+            if ($pos !== false) {
200
+                $memberUrlFilter = substr($memberURLs[0], $pos);
201
+                $foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
202
+                $dynamicMembers = [];
203
+                foreach($foundMembers as $value) {
204
+                    $dynamicMembers[$value['dn'][0]] = 1;
205
+                }
206
+            } else {
207
+                \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
208
+                    'of group ' . $dnGroup, ILogger::DEBUG);
209
+            }
210
+        }
211
+        return $dynamicMembers;
212
+    }
213
+
214
+    /**
215
+     * @param string $dnGroup
216
+     * @param array|null &$seen
217
+     * @return array|mixed|null
218
+     * @throws \OC\ServerNotAvailableException
219
+     */
220
+    private function _groupMembers($dnGroup, &$seen = null) {
221
+        if ($seen === null) {
222
+            $seen = [];
223
+        }
224
+        $allMembers = [];
225
+        if (array_key_exists($dnGroup, $seen)) {
226
+            // avoid loops
227
+            return [];
228
+        }
229
+        // used extensively in cron job, caching makes sense for nested groups
230
+        $cacheKey = '_groupMembers'.$dnGroup;
231
+        $groupMembers = $this->access->connection->getFromCache($cacheKey);
232
+        if($groupMembers !== null) {
233
+            return $groupMembers;
234
+        }
235
+        $seen[$dnGroup] = 1;
236
+        $members = $this->access->readAttribute($dnGroup, $this->access->connection->ldapGroupMemberAssocAttr);
237
+        if (is_array($members)) {
238
+            $fetcher = function($memberDN, &$seen) {
239
+                return $this->_groupMembers($memberDN, $seen);
240
+            };
241
+            $allMembers = $this->walkNestedGroups($dnGroup, $fetcher, $members);
242
+        }
243
+
244
+        $allMembers += $this->getDynamicGroupMembers($dnGroup);
245
+
246
+        $this->access->connection->writeToCache($cacheKey, $allMembers);
247
+        return $allMembers;
248
+    }
249
+
250
+    /**
251
+     * @param string $DN
252
+     * @param array|null &$seen
253
+     * @return array
254
+     * @throws \OC\ServerNotAvailableException
255
+     */
256
+    private function _getGroupDNsFromMemberOf($DN) {
257
+        $groups = $this->access->readAttribute($DN, 'memberOf');
258
+        if (!is_array($groups)) {
259
+            return [];
260
+        }
261
+
262
+        $fetcher = function($groupDN) {
263
+            if (isset($this->cachedNestedGroups[$groupDN])) {
264
+                $nestedGroups = $this->cachedNestedGroups[$groupDN];
265
+            } else {
266
+                $nestedGroups = $this->access->readAttribute($groupDN, 'memberOf');
267
+                if (!is_array($nestedGroups)) {
268
+                    $nestedGroups = [];
269
+                }
270
+                $this->cachedNestedGroups[$groupDN] = $nestedGroups;
271
+            }
272
+            return $nestedGroups;
273
+        };
274
+
275
+        $groups = $this->walkNestedGroups($DN, $fetcher, $groups);
276
+        return $this->access->groupsMatchFilter($groups);
277
+    }
278
+
279
+    /**
280
+     * @param string $dn
281
+     * @param \Closure $fetcher args: string $dn, array $seen, returns: string[] of dns
282
+     * @param array $list
283
+     * @return array
284
+     */
285
+    private function walkNestedGroups(string $dn, \Closure $fetcher, array $list): array {
286
+        $nesting = (int) $this->access->connection->ldapNestedGroups;
287
+        // depending on the input, we either have a list of DNs or a list of LDAP records
288
+        // also, the output expects either DNs or records. Testing the first element should suffice.
289
+        $recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
290
+
291
+        if ($nesting !== 1) {
292
+            if($recordMode) {
293
+                // the keys are numeric, but should hold the DN
294
+                return array_reduce($list, function ($transformed, $record) use ($dn) {
295
+                    if($record['dn'][0] != $dn) {
296
+                        $transformed[$record['dn'][0]] = $record;
297
+                    }
298
+                    return $transformed;
299
+                }, []);
300
+            }
301
+            return $list;
302
+        }
303
+
304
+        $seen = [];
305
+        while ($record = array_pop($list)) {
306
+            $recordDN = $recordMode ? $record['dn'][0] : $record;
307
+            if ($recordDN === $dn || array_key_exists($recordDN, $seen)) {
308
+                // Prevent loops
309
+                continue;
310
+            }
311
+            $fetched = $fetcher($record, $seen);
312
+            $list = array_merge($list, $fetched);
313
+            $seen[$recordDN] = $record;
314
+        }
315
+
316
+        return $recordMode ? $seen : array_keys($seen);
317
+    }
318
+
319
+    /**
320
+     * translates a gidNumber into an ownCloud internal name
321
+     * @param string $gid as given by gidNumber on POSIX LDAP
322
+     * @param string $dn a DN that belongs to the same domain as the group
323
+     * @return string|bool
324
+     */
325
+    public function gidNumber2Name($gid, $dn) {
326
+        $cacheKey = 'gidNumberToName' . $gid;
327
+        $groupName = $this->access->connection->getFromCache($cacheKey);
328
+        if(!is_null($groupName) && isset($groupName)) {
329
+            return $groupName;
330
+        }
331
+
332
+        //we need to get the DN from LDAP
333
+        $filter = $this->access->combineFilterWithAnd([
334
+            $this->access->connection->ldapGroupFilter,
335
+            'objectClass=posixGroup',
336
+            $this->access->connection->ldapGidNumber . '=' . $gid
337
+        ]);
338
+        $result = $this->access->searchGroups($filter, ['dn'], 1);
339
+        if(empty($result)) {
340
+            return false;
341
+        }
342
+        $dn = $result[0]['dn'][0];
343
+
344
+        //and now the group name
345
+        //NOTE once we have separate ownCloud group IDs and group names we can
346
+        //directly read the display name attribute instead of the DN
347
+        $name = $this->access->dn2groupname($dn);
348
+
349
+        $this->access->connection->writeToCache($cacheKey, $name);
350
+
351
+        return $name;
352
+    }
353
+
354
+    /**
355
+     * returns the entry's gidNumber
356
+     * @param string $dn
357
+     * @param string $attribute
358
+     * @return string|bool
359
+     */
360
+    private function getEntryGidNumber($dn, $attribute) {
361
+        $value = $this->access->readAttribute($dn, $attribute);
362
+        if(is_array($value) && !empty($value)) {
363
+            return $value[0];
364
+        }
365
+        return false;
366
+    }
367
+
368
+    /**
369
+     * returns the group's primary ID
370
+     * @param string $dn
371
+     * @return string|bool
372
+     */
373
+    public function getGroupGidNumber($dn) {
374
+        return $this->getEntryGidNumber($dn, 'gidNumber');
375
+    }
376
+
377
+    /**
378
+     * returns the user's gidNumber
379
+     * @param string $dn
380
+     * @return string|bool
381
+     */
382
+    public function getUserGidNumber($dn) {
383
+        $gidNumber = false;
384
+        if($this->access->connection->hasGidNumber) {
385
+            $gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
386
+            if($gidNumber === false) {
387
+                $this->access->connection->hasGidNumber = false;
388
+            }
389
+        }
390
+        return $gidNumber;
391
+    }
392
+
393
+    /**
394
+     * returns a filter for a "users has specific gid" search or count operation
395
+     *
396
+     * @param string $groupDN
397
+     * @param string $search
398
+     * @return string
399
+     * @throws \Exception
400
+     */
401
+    private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
402
+        $groupID = $this->getGroupGidNumber($groupDN);
403
+        if($groupID === false) {
404
+            throw new \Exception('Not a valid group');
405
+        }
406
+
407
+        $filterParts = [];
408
+        $filterParts[] = $this->access->getFilterForUserCount();
409
+        if ($search !== '') {
410
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
411
+        }
412
+        $filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
413
+
414
+        return $this->access->combineFilterWithAnd($filterParts);
415
+    }
416
+
417
+    /**
418
+     * returns a list of users that have the given group as gid number
419
+     *
420
+     * @param string $groupDN
421
+     * @param string $search
422
+     * @param int $limit
423
+     * @param int $offset
424
+     * @return string[]
425
+     */
426
+    public function getUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
427
+        try {
428
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
429
+            $users = $this->access->fetchListOfUsers(
430
+                $filter,
431
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
432
+                $limit,
433
+                $offset
434
+            );
435
+            return $this->access->nextcloudUserNames($users);
436
+        } catch (\Exception $e) {
437
+            return [];
438
+        }
439
+    }
440
+
441
+    /**
442
+     * returns the number of users that have the given group as gid number
443
+     *
444
+     * @param string $groupDN
445
+     * @param string $search
446
+     * @param int $limit
447
+     * @param int $offset
448
+     * @return int
449
+     */
450
+    public function countUsersInGidNumber($groupDN, $search = '', $limit = -1, $offset = 0) {
451
+        try {
452
+            $filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
453
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
454
+            return (int)$users;
455
+        } catch (\Exception $e) {
456
+            return 0;
457
+        }
458
+    }
459
+
460
+    /**
461
+     * gets the gidNumber of a user
462
+     * @param string $dn
463
+     * @return string
464
+     */
465
+    public function getUserGroupByGid($dn) {
466
+        $groupID = $this->getUserGidNumber($dn);
467
+        if($groupID !== false) {
468
+            $groupName = $this->gidNumber2Name($groupID, $dn);
469
+            if($groupName !== false) {
470
+                return $groupName;
471
+            }
472
+        }
473
+
474
+        return false;
475
+    }
476
+
477
+    /**
478
+     * translates a primary group ID into an Nextcloud internal name
479
+     * @param string $gid as given by primaryGroupID on AD
480
+     * @param string $dn a DN that belongs to the same domain as the group
481
+     * @return string|bool
482
+     */
483
+    public function primaryGroupID2Name($gid, $dn) {
484
+        $cacheKey = 'primaryGroupIDtoName';
485
+        $groupNames = $this->access->connection->getFromCache($cacheKey);
486
+        if(!is_null($groupNames) && isset($groupNames[$gid])) {
487
+            return $groupNames[$gid];
488
+        }
489
+
490
+        $domainObjectSid = $this->access->getSID($dn);
491
+        if($domainObjectSid === false) {
492
+            return false;
493
+        }
494
+
495
+        //we need to get the DN from LDAP
496
+        $filter = $this->access->combineFilterWithAnd([
497
+            $this->access->connection->ldapGroupFilter,
498
+            'objectsid=' . $domainObjectSid . '-' . $gid
499
+        ]);
500
+        $result = $this->access->searchGroups($filter, ['dn'], 1);
501
+        if(empty($result)) {
502
+            return false;
503
+        }
504
+        $dn = $result[0]['dn'][0];
505
+
506
+        //and now the group name
507
+        //NOTE once we have separate Nextcloud group IDs and group names we can
508
+        //directly read the display name attribute instead of the DN
509
+        $name = $this->access->dn2groupname($dn);
510
+
511
+        $this->access->connection->writeToCache($cacheKey, $name);
512
+
513
+        return $name;
514
+    }
515
+
516
+    /**
517
+     * returns the entry's primary group ID
518
+     * @param string $dn
519
+     * @param string $attribute
520
+     * @return string|bool
521
+     */
522
+    private function getEntryGroupID($dn, $attribute) {
523
+        $value = $this->access->readAttribute($dn, $attribute);
524
+        if(is_array($value) && !empty($value)) {
525
+            return $value[0];
526
+        }
527
+        return false;
528
+    }
529
+
530
+    /**
531
+     * returns the group's primary ID
532
+     * @param string $dn
533
+     * @return string|bool
534
+     */
535
+    public function getGroupPrimaryGroupID($dn) {
536
+        return $this->getEntryGroupID($dn, 'primaryGroupToken');
537
+    }
538
+
539
+    /**
540
+     * returns the user's primary group ID
541
+     * @param string $dn
542
+     * @return string|bool
543
+     */
544
+    public function getUserPrimaryGroupIDs($dn) {
545
+        $primaryGroupID = false;
546
+        if($this->access->connection->hasPrimaryGroups) {
547
+            $primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
548
+            if($primaryGroupID === false) {
549
+                $this->access->connection->hasPrimaryGroups = false;
550
+            }
551
+        }
552
+        return $primaryGroupID;
553
+    }
554
+
555
+    /**
556
+     * returns a filter for a "users in primary group" search or count operation
557
+     *
558
+     * @param string $groupDN
559
+     * @param string $search
560
+     * @return string
561
+     * @throws \Exception
562
+     */
563
+    private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
564
+        $groupID = $this->getGroupPrimaryGroupID($groupDN);
565
+        if($groupID === false) {
566
+            throw new \Exception('Not a valid group');
567
+        }
568
+
569
+        $filterParts = [];
570
+        $filterParts[] = $this->access->getFilterForUserCount();
571
+        if ($search !== '') {
572
+            $filterParts[] = $this->access->getFilterPartForUserSearch($search);
573
+        }
574
+        $filterParts[] = 'primaryGroupID=' . $groupID;
575
+
576
+        return $this->access->combineFilterWithAnd($filterParts);
577
+    }
578
+
579
+    /**
580
+     * returns a list of users that have the given group as primary group
581
+     *
582
+     * @param string $groupDN
583
+     * @param string $search
584
+     * @param int $limit
585
+     * @param int $offset
586
+     * @return string[]
587
+     */
588
+    public function getUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
589
+        try {
590
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
591
+            $users = $this->access->fetchListOfUsers(
592
+                $filter,
593
+                [$this->access->connection->ldapUserDisplayName, 'dn'],
594
+                $limit,
595
+                $offset
596
+            );
597
+            return $this->access->nextcloudUserNames($users);
598
+        } catch (\Exception $e) {
599
+            return [];
600
+        }
601
+    }
602
+
603
+    /**
604
+     * returns the number of users that have the given group as primary group
605
+     *
606
+     * @param string $groupDN
607
+     * @param string $search
608
+     * @param int $limit
609
+     * @param int $offset
610
+     * @return int
611
+     */
612
+    public function countUsersInPrimaryGroup($groupDN, $search = '', $limit = -1, $offset = 0) {
613
+        try {
614
+            $filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
615
+            $users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
616
+            return (int)$users;
617
+        } catch (\Exception $e) {
618
+            return 0;
619
+        }
620
+    }
621
+
622
+    /**
623
+     * gets the primary group of a user
624
+     * @param string $dn
625
+     * @return string
626
+     */
627
+    public function getUserPrimaryGroup($dn) {
628
+        $groupID = $this->getUserPrimaryGroupIDs($dn);
629
+        if($groupID !== false) {
630
+            $groupName = $this->primaryGroupID2Name($groupID, $dn);
631
+            if($groupName !== false) {
632
+                return $groupName;
633
+            }
634
+        }
635
+
636
+        return false;
637
+    }
638
+
639
+    /**
640
+     * Get all groups a user belongs to
641
+     * @param string $uid Name of the user
642
+     * @return array with group names
643
+     *
644
+     * This function fetches all groups a user belongs to. It does not check
645
+     * if the user exists at all.
646
+     *
647
+     * This function includes groups based on dynamic group membership.
648
+     */
649
+    public function getUserGroups($uid) {
650
+        if(!$this->enabled) {
651
+            return [];
652
+        }
653
+        $cacheKey = 'getUserGroups'.$uid;
654
+        $userGroups = $this->access->connection->getFromCache($cacheKey);
655
+        if(!is_null($userGroups)) {
656
+            return $userGroups;
657
+        }
658
+        $userDN = $this->access->username2dn($uid);
659
+        if(!$userDN) {
660
+            $this->access->connection->writeToCache($cacheKey, []);
661
+            return [];
662
+        }
663
+
664
+        $groups = [];
665
+        $primaryGroup = $this->getUserPrimaryGroup($userDN);
666
+        $gidGroupName = $this->getUserGroupByGid($userDN);
667
+
668
+        $dynamicGroupMemberURL = strtolower($this->access->connection->ldapDynamicGroupMemberURL);
669
+
670
+        if (!empty($dynamicGroupMemberURL)) {
671
+            // look through dynamic groups to add them to the result array if needed
672
+            $groupsToMatch = $this->access->fetchListOfGroups(
673
+                $this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
674
+            foreach($groupsToMatch as $dynamicGroup) {
675
+                if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
676
+                    continue;
677
+                }
678
+                $pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
679
+                if ($pos !== false) {
680
+                    $memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
681
+                    // apply filter via ldap search to see if this user is in this
682
+                    // dynamic group
683
+                    $userMatch = $this->access->readAttribute(
684
+                        $userDN,
685
+                        $this->access->connection->ldapUserDisplayName,
686
+                        $memberUrlFilter
687
+                    );
688
+                    if ($userMatch !== false) {
689
+                        // match found so this user is in this group
690
+                        $groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
691
+                        if(is_string($groupName)) {
692
+                            // be sure to never return false if the dn could not be
693
+                            // resolved to a name, for whatever reason.
694
+                            $groups[] = $groupName;
695
+                        }
696
+                    }
697
+                } else {
698
+                    \OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
699
+                        'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
700
+                }
701
+            }
702
+        }
703
+
704
+        // if possible, read out membership via memberOf. It's far faster than
705
+        // performing a search, which still is a fallback later.
706
+        // memberof doesn't support memberuid, so skip it here.
707
+        if((int)$this->access->connection->hasMemberOfFilterSupport === 1
708
+            && (int)$this->access->connection->useMemberOfToDetectMembership === 1
709
+            && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
710
+            ) {
711
+            $groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
712
+            if (is_array($groupDNs)) {
713
+                foreach ($groupDNs as $dn) {
714
+                    $groupName = $this->access->dn2groupname($dn);
715
+                    if(is_string($groupName)) {
716
+                        // be sure to never return false if the dn could not be
717
+                        // resolved to a name, for whatever reason.
718
+                        $groups[] = $groupName;
719
+                    }
720
+                }
721
+            }
722
+
723
+            if($primaryGroup !== false) {
724
+                $groups[] = $primaryGroup;
725
+            }
726
+            if($gidGroupName !== false) {
727
+                $groups[] = $gidGroupName;
728
+            }
729
+            $this->access->connection->writeToCache($cacheKey, $groups);
730
+            return $groups;
731
+        }
732
+
733
+        //uniqueMember takes DN, memberuid the uid, so we need to distinguish
734
+        if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
735
+            || (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
736
+        ) {
737
+            $uid = $userDN;
738
+        } else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
739
+            $result = $this->access->readAttribute($userDN, 'uid');
740
+            if ($result === false) {
741
+                \OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
742
+                    $this->access->connection->ldapHost, ILogger::DEBUG);
743
+                $uid = false;
744
+            } else {
745
+                $uid = $result[0];
746
+            }
747
+        } else {
748
+            // just in case
749
+            $uid = $userDN;
750
+        }
751
+
752
+        if($uid !== false) {
753
+            if (isset($this->cachedGroupsByMember[$uid])) {
754
+                $groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
755
+            } else {
756
+                $groupsByMember = array_values($this->getGroupsByMember($uid));
757
+                $groupsByMember = $this->access->nextcloudGroupNames($groupsByMember);
758
+                $this->cachedGroupsByMember[$uid] = $groupsByMember;
759
+                $groups = array_merge($groups, $groupsByMember);
760
+            }
761
+        }
762
+
763
+        if($primaryGroup !== false) {
764
+            $groups[] = $primaryGroup;
765
+        }
766
+        if($gidGroupName !== false) {
767
+            $groups[] = $gidGroupName;
768
+        }
769
+
770
+        $groups = array_unique($groups, SORT_LOCALE_STRING);
771
+        $this->access->connection->writeToCache($cacheKey, $groups);
772
+
773
+        return $groups;
774
+    }
775
+
776
+    /**
777
+     * @param string $dn
778
+     * @param array|null &$seen
779
+     * @return array
780
+     */
781
+    private function getGroupsByMember($dn, &$seen = null) {
782
+        if ($seen === null) {
783
+            $seen = [];
784
+        }
785
+        if (array_key_exists($dn, $seen)) {
786
+            // avoid loops
787
+            return [];
788
+        }
789
+        $allGroups = [];
790
+        $seen[$dn] = true;
791
+        $filter = $this->access->connection->ldapGroupMemberAssocAttr.'='.$dn;
792
+        $groups = $this->access->fetchListOfGroups($filter,
793
+            [$this->access->connection->ldapGroupDisplayName, 'dn']);
794
+        if (is_array($groups)) {
795
+            $fetcher = function ($dn, &$seen) {
796
+                if(is_array($dn) && isset($dn['dn'][0])) {
797
+                    $dn = $dn['dn'][0];
798
+                }
799
+                return $this->getGroupsByMember($dn, $seen);
800
+            };
801
+            $allGroups = $this->walkNestedGroups($dn, $fetcher, $groups);
802
+        }
803
+        $visibleGroups = $this->access->groupsMatchFilter(array_keys($allGroups));
804
+        return array_intersect_key($allGroups, array_flip($visibleGroups));
805
+    }
806
+
807
+    /**
808
+     * get a list of all users in a group
809
+     *
810
+     * @param string $gid
811
+     * @param string $search
812
+     * @param int $limit
813
+     * @param int $offset
814
+     * @return array with user ids
815
+     * @throws \Exception
816
+     */
817
+    public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
818
+        if(!$this->enabled) {
819
+            return [];
820
+        }
821
+        if(!$this->groupExists($gid)) {
822
+            return [];
823
+        }
824
+        $search = $this->access->escapeFilterPart($search, true);
825
+        $cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
826
+        // check for cache of the exact query
827
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
828
+        if(!is_null($groupUsers)) {
829
+            return $groupUsers;
830
+        }
831
+
832
+        // check for cache of the query without limit and offset
833
+        $groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
834
+        if(!is_null($groupUsers)) {
835
+            $groupUsers = array_slice($groupUsers, $offset, $limit);
836
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
837
+            return $groupUsers;
838
+        }
839
+
840
+        if($limit === -1) {
841
+            $limit = null;
842
+        }
843
+        $groupDN = $this->access->groupname2dn($gid);
844
+        if(!$groupDN) {
845
+            // group couldn't be found, return empty resultset
846
+            $this->access->connection->writeToCache($cacheKey, []);
847
+            return [];
848
+        }
849
+
850
+        $primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
851
+        $posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
852
+        $members = $this->_groupMembers($groupDN);
853
+        if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
854
+            //in case users could not be retrieved, return empty result set
855
+            $this->access->connection->writeToCache($cacheKey, []);
856
+            return [];
857
+        }
858
+
859
+        $groupUsers = [];
860
+        $isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
861
+        $attrs = $this->access->userManager->getAttributes(true);
862
+        foreach($members as $member) {
863
+            if($isMemberUid) {
864
+                //we got uids, need to get their DNs to 'translate' them to user names
865
+                $filter = $this->access->combineFilterWithAnd([
866
+                    str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
867
+                    $this->access->combineFilterWithAnd([
868
+                        $this->access->getFilterPartForUserSearch($search),
869
+                        $this->access->connection->ldapUserFilter
870
+                    ])
871
+                ]);
872
+                $ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
873
+                if(count($ldap_users) < 1) {
874
+                    continue;
875
+                }
876
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
877
+            } else {
878
+                //we got DNs, check if we need to filter by search or we can give back all of them
879
+                $uid = $this->access->dn2username($member);
880
+                if(!$uid) {
881
+                    continue;
882
+                }
883
+
884
+                $cacheKey = 'userExistsOnLDAP' . $uid;
885
+                $userExists = $this->access->connection->getFromCache($cacheKey);
886
+                if($userExists === false) {
887
+                    continue;
888
+                }
889
+                if($userExists === null || $search !== '') {
890
+                    if (!$this->access->readAttribute($member,
891
+                        $this->access->connection->ldapUserDisplayName,
892
+                        $this->access->combineFilterWithAnd([
893
+                            $this->access->getFilterPartForUserSearch($search),
894
+                            $this->access->connection->ldapUserFilter
895
+                        ])))
896
+                    {
897
+                        if($search === '') {
898
+                            $this->access->connection->writeToCache($cacheKey, false);
899
+                        }
900
+                        continue;
901
+                    }
902
+                    $this->access->connection->writeToCache($cacheKey, true);
903
+                }
904
+                $groupUsers[] = $uid;
905
+            }
906
+        }
907
+
908
+        $groupUsers = array_unique(array_merge($groupUsers, $primaryUsers, $posixGroupUsers));
909
+        natsort($groupUsers);
910
+        $this->access->connection->writeToCache('usersInGroup-'.$gid.'-'.$search, $groupUsers);
911
+        $groupUsers = array_slice($groupUsers, $offset, $limit);
912
+
913
+        $this->access->connection->writeToCache($cacheKey, $groupUsers);
914
+
915
+        return $groupUsers;
916
+    }
917
+
918
+    /**
919
+     * returns the number of users in a group, who match the search term
920
+     * @param string $gid the internal group name
921
+     * @param string $search optional, a search string
922
+     * @return int|bool
923
+     */
924
+    public function countUsersInGroup($gid, $search = '') {
925
+        if ($this->groupPluginManager->implementsActions(GroupInterface::COUNT_USERS)) {
926
+            return $this->groupPluginManager->countUsersInGroup($gid, $search);
927
+        }
928
+
929
+        $cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
930
+        if(!$this->enabled || !$this->groupExists($gid)) {
931
+            return false;
932
+        }
933
+        $groupUsers = $this->access->connection->getFromCache($cacheKey);
934
+        if(!is_null($groupUsers)) {
935
+            return $groupUsers;
936
+        }
937
+
938
+        $groupDN = $this->access->groupname2dn($gid);
939
+        if(!$groupDN) {
940
+            // group couldn't be found, return empty result set
941
+            $this->access->connection->writeToCache($cacheKey, false);
942
+            return false;
943
+        }
944
+
945
+        $members = $this->_groupMembers($groupDN);
946
+        $primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
947
+        if(!$members && $primaryUserCount === 0) {
948
+            //in case users could not be retrieved, return empty result set
949
+            $this->access->connection->writeToCache($cacheKey, false);
950
+            return false;
951
+        }
952
+
953
+        if ($search === '') {
954
+            $groupUsers = count($members) + $primaryUserCount;
955
+            $this->access->connection->writeToCache($cacheKey, $groupUsers);
956
+            return $groupUsers;
957
+        }
958
+        $search = $this->access->escapeFilterPart($search, true);
959
+        $isMemberUid =
960
+            (strtolower($this->access->connection->ldapGroupMemberAssocAttr)
961
+            === 'memberuid');
962
+
963
+        //we need to apply the search filter
964
+        //alternatives that need to be checked:
965
+        //a) get all users by search filter and array_intersect them
966
+        //b) a, but only when less than 1k 10k ?k users like it is
967
+        //c) put all DNs|uids in a LDAP filter, combine with the search string
968
+        //   and let it count.
969
+        //For now this is not important, because the only use of this method
970
+        //does not supply a search string
971
+        $groupUsers = [];
972
+        foreach($members as $member) {
973
+            if($isMemberUid) {
974
+                //we got uids, need to get their DNs to 'translate' them to user names
975
+                $filter = $this->access->combineFilterWithAnd([
976
+                    str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
977
+                    $this->access->getFilterPartForUserSearch($search)
978
+                ]);
979
+                $ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
980
+                if(count($ldap_users) < 1) {
981
+                    continue;
982
+                }
983
+                $groupUsers[] = $this->access->dn2username($ldap_users[0]);
984
+            } else {
985
+                //we need to apply the search filter now
986
+                if(!$this->access->readAttribute($member,
987
+                    $this->access->connection->ldapUserDisplayName,
988
+                    $this->access->getFilterPartForUserSearch($search))) {
989
+                    continue;
990
+                }
991
+                // dn2username will also check if the users belong to the allowed base
992
+                if($ocname = $this->access->dn2username($member)) {
993
+                    $groupUsers[] = $ocname;
994
+                }
995
+            }
996
+        }
997
+
998
+        //and get users that have the group as primary
999
+        $primaryUsers = $this->countUsersInPrimaryGroup($groupDN, $search);
1000
+
1001
+        return count($groupUsers) + $primaryUsers;
1002
+    }
1003
+
1004
+    /**
1005
+     * get a list of all groups
1006
+     *
1007
+     * @param string $search
1008
+     * @param $limit
1009
+     * @param int $offset
1010
+     * @return array with group names
1011
+     *
1012
+     * Returns a list with all groups (used by getGroups)
1013
+     */
1014
+    protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1015
+        if(!$this->enabled) {
1016
+            return [];
1017
+        }
1018
+        $cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
1019
+
1020
+        //Check cache before driving unnecessary searches
1021
+        \OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1022
+        $ldap_groups = $this->access->connection->getFromCache($cacheKey);
1023
+        if(!is_null($ldap_groups)) {
1024
+            return $ldap_groups;
1025
+        }
1026
+
1027
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
1028
+        // error. With a limit of 0, we get 0 results. So we pass null.
1029
+        if($limit <= 0) {
1030
+            $limit = null;
1031
+        }
1032
+        $filter = $this->access->combineFilterWithAnd([
1033
+            $this->access->connection->ldapGroupFilter,
1034
+            $this->access->getFilterPartForGroupSearch($search)
1035
+        ]);
1036
+        \OCP\Util::writeLog('user_ldap', 'getGroups Filter '.$filter, ILogger::DEBUG);
1037
+        $ldap_groups = $this->access->fetchListOfGroups($filter,
1038
+                [$this->access->connection->ldapGroupDisplayName, 'dn'],
1039
+                $limit,
1040
+                $offset);
1041
+        $ldap_groups = $this->access->nextcloudGroupNames($ldap_groups);
1042
+
1043
+        $this->access->connection->writeToCache($cacheKey, $ldap_groups);
1044
+        return $ldap_groups;
1045
+    }
1046
+
1047
+    /**
1048
+     * get a list of all groups using a paged search
1049
+     *
1050
+     * @param string $search
1051
+     * @param int $limit
1052
+     * @param int $offset
1053
+     * @return array with group names
1054
+     *
1055
+     * Returns a list with all groups
1056
+     * Uses a paged search if available to override a
1057
+     * server side search limit.
1058
+     * (active directory has a limit of 1000 by default)
1059
+     */
1060
+    public function getGroups($search = '', $limit = -1, $offset = 0) {
1061
+        if(!$this->enabled) {
1062
+            return [];
1063
+        }
1064
+        $search = $this->access->escapeFilterPart($search, true);
1065
+        $pagingSize = (int)$this->access->connection->ldapPagingSize;
1066
+        if ($pagingSize <= 0) {
1067
+            return $this->getGroupsChunk($search, $limit, $offset);
1068
+        }
1069
+        $maxGroups = 100000; // limit max results (just for safety reasons)
1070
+        if ($limit > -1) {
1071
+            $overallLimit = min($limit + $offset, $maxGroups);
1072
+        } else {
1073
+            $overallLimit = $maxGroups;
1074
+        }
1075
+        $chunkOffset = $offset;
1076
+        $allGroups = [];
1077
+        while ($chunkOffset < $overallLimit) {
1078
+            $chunkLimit = min($pagingSize, $overallLimit - $chunkOffset);
1079
+            $ldapGroups = $this->getGroupsChunk($search, $chunkLimit, $chunkOffset);
1080
+            $nread = count($ldapGroups);
1081
+            \OCP\Util::writeLog('user_ldap', 'getGroups('.$search.'): read '.$nread.' at offset '.$chunkOffset.' (limit: '.$chunkLimit.')', ILogger::DEBUG);
1082
+            if ($nread) {
1083
+                $allGroups = array_merge($allGroups, $ldapGroups);
1084
+                $chunkOffset += $nread;
1085
+            }
1086
+            if ($nread < $chunkLimit) {
1087
+                break;
1088
+            }
1089
+        }
1090
+        return $allGroups;
1091
+    }
1092
+
1093
+    /**
1094
+     * @param string $group
1095
+     * @return bool
1096
+     */
1097
+    public function groupMatchesFilter($group) {
1098
+        return (strripos($group, $this->groupSearch) !== false);
1099
+    }
1100
+
1101
+    /**
1102
+     * check if a group exists
1103
+     * @param string $gid
1104
+     * @return bool
1105
+     */
1106
+    public function groupExists($gid) {
1107
+        $groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1108
+        if(!is_null($groupExists)) {
1109
+            return (bool)$groupExists;
1110
+        }
1111
+
1112
+        //getting dn, if false the group does not exist. If dn, it may be mapped
1113
+        //only, requires more checking.
1114
+        $dn = $this->access->groupname2dn($gid);
1115
+        if(!$dn) {
1116
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1117
+            return false;
1118
+        }
1119
+
1120
+        //if group really still exists, we will be able to read its objectclass
1121
+        if(!is_array($this->access->readAttribute($dn, ''))) {
1122
+            $this->access->connection->writeToCache('groupExists'.$gid, false);
1123
+            return false;
1124
+        }
1125
+
1126
+        $this->access->connection->writeToCache('groupExists'.$gid, true);
1127
+        return true;
1128
+    }
1129
+
1130
+    /**
1131
+     * Check if backend implements actions
1132
+     * @param int $actions bitwise-or'ed actions
1133
+     * @return boolean
1134
+     *
1135
+     * Returns the supported actions as int to be
1136
+     * compared with GroupInterface::CREATE_GROUP etc.
1137
+     */
1138
+    public function implementsActions($actions) {
1139
+        return (bool)((GroupInterface::COUNT_USERS |
1140
+                $this->groupPluginManager->getImplementedActions()) & $actions);
1141
+    }
1142
+
1143
+    /**
1144
+     * Return access for LDAP interaction.
1145
+     * @return Access instance of Access for LDAP interaction
1146
+     */
1147
+    public function getLDAPAccess($gid) {
1148
+        return $this->access;
1149
+    }
1150
+
1151
+    /**
1152
+     * create a group
1153
+     * @param string $gid
1154
+     * @return bool
1155
+     * @throws \Exception
1156
+     */
1157
+    public function createGroup($gid) {
1158
+        if ($this->groupPluginManager->implementsActions(GroupInterface::CREATE_GROUP)) {
1159
+            if ($dn = $this->groupPluginManager->createGroup($gid)) {
1160
+                //updates group mapping
1161
+                $uuid = $this->access->getUUID($dn, false);
1162
+                if(is_string($uuid)) {
1163
+                    $this->access->mapAndAnnounceIfApplicable(
1164
+                        $this->access->getGroupMapper(),
1165
+                        $dn,
1166
+                        $gid,
1167
+                        $uuid,
1168
+                        false
1169
+                    );
1170
+                    $this->access->cacheGroupExists($gid);
1171
+                }
1172
+            }
1173
+            return $dn != null;
1174
+        }
1175
+        throw new \Exception('Could not create group in LDAP backend.');
1176
+    }
1177
+
1178
+    /**
1179
+     * delete a group
1180
+     * @param string $gid gid of the group to delete
1181
+     * @return bool
1182
+     * @throws \Exception
1183
+     */
1184
+    public function deleteGroup($gid) {
1185
+        if ($this->groupPluginManager->implementsActions(GroupInterface::DELETE_GROUP)) {
1186
+            if ($ret = $this->groupPluginManager->deleteGroup($gid)) {
1187
+                #delete group in nextcloud internal db
1188
+                $this->access->getGroupMapper()->unmap($gid);
1189
+                $this->access->connection->writeToCache("groupExists".$gid, false);
1190
+            }
1191
+            return $ret;
1192
+        }
1193
+        throw new \Exception('Could not delete group in LDAP backend.');
1194
+    }
1195
+
1196
+    /**
1197
+     * Add a user to a group
1198
+     * @param string $uid Name of the user to add to group
1199
+     * @param string $gid Name of the group in which add the user
1200
+     * @return bool
1201
+     * @throws \Exception
1202
+     */
1203
+    public function addToGroup($uid, $gid) {
1204
+        if ($this->groupPluginManager->implementsActions(GroupInterface::ADD_TO_GROUP)) {
1205
+            if ($ret = $this->groupPluginManager->addToGroup($uid, $gid)) {
1206
+                $this->access->connection->clearCache();
1207
+                unset($this->cachedGroupMembers[$gid]);
1208
+            }
1209
+            return $ret;
1210
+        }
1211
+        throw new \Exception('Could not add user to group in LDAP backend.');
1212
+    }
1213
+
1214
+    /**
1215
+     * Removes a user from a group
1216
+     * @param string $uid Name of the user to remove from group
1217
+     * @param string $gid Name of the group from which remove the user
1218
+     * @return bool
1219
+     * @throws \Exception
1220
+     */
1221
+    public function removeFromGroup($uid, $gid) {
1222
+        if ($this->groupPluginManager->implementsActions(GroupInterface::REMOVE_FROM_GROUP)) {
1223
+            if ($ret = $this->groupPluginManager->removeFromGroup($uid, $gid)) {
1224
+                $this->access->connection->clearCache();
1225
+                unset($this->cachedGroupMembers[$gid]);
1226
+            }
1227
+            return $ret;
1228
+        }
1229
+        throw new \Exception('Could not remove user from group in LDAP backend.');
1230
+    }
1231
+
1232
+    /**
1233
+     * Gets group details
1234
+     * @param string $gid Name of the group
1235
+     * @return array | false
1236
+     * @throws \Exception
1237
+     */
1238
+    public function getGroupDetails($gid) {
1239
+        if ($this->groupPluginManager->implementsActions(GroupInterface::GROUP_DETAILS)) {
1240
+            return $this->groupPluginManager->getGroupDetails($gid);
1241
+        }
1242
+        throw new \Exception('Could not get group details in LDAP backend.');
1243
+    }
1244
+
1245
+    /**
1246
+     * Return LDAP connection resource from a cloned connection.
1247
+     * The cloned connection needs to be closed manually.
1248
+     * of the current access.
1249
+     * @param string $gid
1250
+     * @return resource of the LDAP connection
1251
+     */
1252
+    public function getNewLDAPConnection($gid) {
1253
+        $connection = clone $this->access->getConnection();
1254
+        return $connection->getConnectionResource();
1255
+    }
1256
+
1257
+    /**
1258
+     * @throws \OC\ServerNotAvailableException
1259
+     */
1260
+    public function getDisplayName(string $gid): string {
1261
+        if ($this->groupPluginManager instanceof IGetDisplayNameBackend) {
1262
+            return $this->groupPluginManager->getDisplayName($gid);
1263
+        }
1264
+
1265
+        $cacheKey = 'group_getDisplayName' . $gid;
1266
+        if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1267
+            return $displayName;
1268
+        }
1269
+
1270
+        $displayName = $this->access->readAttribute(
1271
+            $this->access->groupname2dn($gid),
1272
+            $this->access->connection->ldapGroupDisplayName);
1273
+
1274
+        if ($displayName && (count($displayName) > 0)) {
1275
+            $displayName = $displayName[0];
1276
+            $this->access->connection->writeToCache($cacheKey, $displayName);
1277
+            return $displayName;
1278
+        }
1279
+
1280
+        return '';
1281
+    }
1282 1282
 }
Please login to merge, or discard this patch.
Spacing   +101 added lines, -101 removed lines patch added patch discarded remove patch
@@ -72,7 +72,7 @@  discard block
 block discarded – undo
72 72
 		parent::__construct($access);
73 73
 		$filter = $this->access->connection->ldapGroupFilter;
74 74
 		$gassoc = $this->access->connection->ldapGroupMemberAssocAttr;
75
-		if(!empty($filter) && !empty($gassoc)) {
75
+		if (!empty($filter) && !empty($gassoc)) {
76 76
 			$this->enabled = true;
77 77
 		}
78 78
 
@@ -91,25 +91,25 @@  discard block
 block discarded – undo
91 91
 	 * Checks whether the user is member of a group or not.
92 92
 	 */
93 93
 	public function inGroup($uid, $gid) {
94
-		if(!$this->enabled) {
94
+		if (!$this->enabled) {
95 95
 			return false;
96 96
 		}
97 97
 		$cacheKey = 'inGroup'.$uid.':'.$gid;
98 98
 		$inGroup = $this->access->connection->getFromCache($cacheKey);
99
-		if(!is_null($inGroup)) {
100
-			return (bool)$inGroup;
99
+		if (!is_null($inGroup)) {
100
+			return (bool) $inGroup;
101 101
 		}
102 102
 
103 103
 		$userDN = $this->access->username2dn($uid);
104 104
 
105
-		if(isset($this->cachedGroupMembers[$gid])) {
105
+		if (isset($this->cachedGroupMembers[$gid])) {
106 106
 			$isInGroup = in_array($userDN, $this->cachedGroupMembers[$gid]);
107 107
 			return $isInGroup;
108 108
 		}
109 109
 
110 110
 		$cacheKeyMembers = 'inGroup-members:'.$gid;
111 111
 		$members = $this->access->connection->getFromCache($cacheKeyMembers);
112
-		if(!is_null($members)) {
112
+		if (!is_null($members)) {
113 113
 			$this->cachedGroupMembers[$gid] = $members;
114 114
 			$isInGroup = in_array($userDN, $members, true);
115 115
 			$this->access->connection->writeToCache($cacheKey, $isInGroup);
@@ -118,34 +118,34 @@  discard block
 block discarded – undo
118 118
 
119 119
 		$groupDN = $this->access->groupname2dn($gid);
120 120
 		// just in case
121
-		if(!$groupDN || !$userDN) {
121
+		if (!$groupDN || !$userDN) {
122 122
 			$this->access->connection->writeToCache($cacheKey, false);
123 123
 			return false;
124 124
 		}
125 125
 
126 126
 		//check primary group first
127
-		if($gid === $this->getUserPrimaryGroup($userDN)) {
127
+		if ($gid === $this->getUserPrimaryGroup($userDN)) {
128 128
 			$this->access->connection->writeToCache($cacheKey, true);
129 129
 			return true;
130 130
 		}
131 131
 
132 132
 		//usually, LDAP attributes are said to be case insensitive. But there are exceptions of course.
133 133
 		$members = $this->_groupMembers($groupDN);
134
-		if(!is_array($members) || count($members) === 0) {
134
+		if (!is_array($members) || count($members) === 0) {
135 135
 			$this->access->connection->writeToCache($cacheKey, false);
136 136
 			return false;
137 137
 		}
138 138
 
139 139
 		//extra work if we don't get back user DNs
140
-		if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
140
+		if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
141 141
 			$dns = [];
142 142
 			$filterParts = [];
143 143
 			$bytes = 0;
144
-			foreach($members as $mid) {
144
+			foreach ($members as $mid) {
145 145
 				$filter = str_replace('%uid', $mid, $this->access->connection->ldapLoginFilter);
146 146
 				$filterParts[] = $filter;
147 147
 				$bytes += strlen($filter);
148
-				if($bytes >= 9000000) {
148
+				if ($bytes >= 9000000) {
149 149
 					// AD has a default input buffer of 10 MB, we do not want
150 150
 					// to take even the chance to exceed it
151 151
 					$filter = $this->access->combineFilterWithOr($filterParts);
@@ -155,7 +155,7 @@  discard block
 block discarded – undo
155 155
 					$dns = array_merge($dns, $users);
156 156
 				}
157 157
 			}
158
-			if(count($filterParts) > 0) {
158
+			if (count($filterParts) > 0) {
159 159
 				$filter = $this->access->combineFilterWithOr($filterParts);
160 160
 				$users = $this->access->fetchListOfUsers($filter, 'dn', count($filterParts));
161 161
 				$dns = array_merge($dns, $users);
@@ -198,14 +198,14 @@  discard block
 block discarded – undo
198 198
 			$pos = strpos($memberURLs[0], '(');
199 199
 			if ($pos !== false) {
200 200
 				$memberUrlFilter = substr($memberURLs[0], $pos);
201
-				$foundMembers = $this->access->searchUsers($memberUrlFilter,'dn');
201
+				$foundMembers = $this->access->searchUsers($memberUrlFilter, 'dn');
202 202
 				$dynamicMembers = [];
203
-				foreach($foundMembers as $value) {
203
+				foreach ($foundMembers as $value) {
204 204
 					$dynamicMembers[$value['dn'][0]] = 1;
205 205
 				}
206 206
 			} else {
207 207
 				\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
208
-					'of group ' . $dnGroup, ILogger::DEBUG);
208
+					'of group '.$dnGroup, ILogger::DEBUG);
209 209
 			}
210 210
 		}
211 211
 		return $dynamicMembers;
@@ -229,7 +229,7 @@  discard block
 block discarded – undo
229 229
 		// used extensively in cron job, caching makes sense for nested groups
230 230
 		$cacheKey = '_groupMembers'.$dnGroup;
231 231
 		$groupMembers = $this->access->connection->getFromCache($cacheKey);
232
-		if($groupMembers !== null) {
232
+		if ($groupMembers !== null) {
233 233
 			return $groupMembers;
234 234
 		}
235 235
 		$seen[$dnGroup] = 1;
@@ -289,10 +289,10 @@  discard block
 block discarded – undo
289 289
 		$recordMode = is_array($list) && isset($list[0]) && is_array($list[0]) && isset($list[0]['dn'][0]);
290 290
 
291 291
 		if ($nesting !== 1) {
292
-			if($recordMode) {
292
+			if ($recordMode) {
293 293
 				// the keys are numeric, but should hold the DN
294
-				return array_reduce($list, function ($transformed, $record) use ($dn) {
295
-					if($record['dn'][0] != $dn) {
294
+				return array_reduce($list, function($transformed, $record) use ($dn) {
295
+					if ($record['dn'][0] != $dn) {
296 296
 						$transformed[$record['dn'][0]] = $record;
297 297
 					}
298 298
 					return $transformed;
@@ -323,9 +323,9 @@  discard block
 block discarded – undo
323 323
 	 * @return string|bool
324 324
 	 */
325 325
 	public function gidNumber2Name($gid, $dn) {
326
-		$cacheKey = 'gidNumberToName' . $gid;
326
+		$cacheKey = 'gidNumberToName'.$gid;
327 327
 		$groupName = $this->access->connection->getFromCache($cacheKey);
328
-		if(!is_null($groupName) && isset($groupName)) {
328
+		if (!is_null($groupName) && isset($groupName)) {
329 329
 			return $groupName;
330 330
 		}
331 331
 
@@ -333,10 +333,10 @@  discard block
 block discarded – undo
333 333
 		$filter = $this->access->combineFilterWithAnd([
334 334
 			$this->access->connection->ldapGroupFilter,
335 335
 			'objectClass=posixGroup',
336
-			$this->access->connection->ldapGidNumber . '=' . $gid
336
+			$this->access->connection->ldapGidNumber.'='.$gid
337 337
 		]);
338 338
 		$result = $this->access->searchGroups($filter, ['dn'], 1);
339
-		if(empty($result)) {
339
+		if (empty($result)) {
340 340
 			return false;
341 341
 		}
342 342
 		$dn = $result[0]['dn'][0];
@@ -359,7 +359,7 @@  discard block
 block discarded – undo
359 359
 	 */
360 360
 	private function getEntryGidNumber($dn, $attribute) {
361 361
 		$value = $this->access->readAttribute($dn, $attribute);
362
-		if(is_array($value) && !empty($value)) {
362
+		if (is_array($value) && !empty($value)) {
363 363
 			return $value[0];
364 364
 		}
365 365
 		return false;
@@ -381,9 +381,9 @@  discard block
 block discarded – undo
381 381
 	 */
382 382
 	public function getUserGidNumber($dn) {
383 383
 		$gidNumber = false;
384
-		if($this->access->connection->hasGidNumber) {
384
+		if ($this->access->connection->hasGidNumber) {
385 385
 			$gidNumber = $this->getEntryGidNumber($dn, $this->access->connection->ldapGidNumber);
386
-			if($gidNumber === false) {
386
+			if ($gidNumber === false) {
387 387
 				$this->access->connection->hasGidNumber = false;
388 388
 			}
389 389
 		}
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
 	 */
401 401
 	private function prepareFilterForUsersHasGidNumber($groupDN, $search = '') {
402 402
 		$groupID = $this->getGroupGidNumber($groupDN);
403
-		if($groupID === false) {
403
+		if ($groupID === false) {
404 404
 			throw new \Exception('Not a valid group');
405 405
 		}
406 406
 
@@ -409,7 +409,7 @@  discard block
 block discarded – undo
409 409
 		if ($search !== '') {
410 410
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
411 411
 		}
412
-		$filterParts[] = $this->access->connection->ldapGidNumber .'=' . $groupID;
412
+		$filterParts[] = $this->access->connection->ldapGidNumber.'='.$groupID;
413 413
 
414 414
 		return $this->access->combineFilterWithAnd($filterParts);
415 415
 	}
@@ -451,7 +451,7 @@  discard block
 block discarded – undo
451 451
 		try {
452 452
 			$filter = $this->prepareFilterForUsersHasGidNumber($groupDN, $search);
453 453
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
454
-			return (int)$users;
454
+			return (int) $users;
455 455
 		} catch (\Exception $e) {
456 456
 			return 0;
457 457
 		}
@@ -464,9 +464,9 @@  discard block
 block discarded – undo
464 464
 	 */
465 465
 	public function getUserGroupByGid($dn) {
466 466
 		$groupID = $this->getUserGidNumber($dn);
467
-		if($groupID !== false) {
467
+		if ($groupID !== false) {
468 468
 			$groupName = $this->gidNumber2Name($groupID, $dn);
469
-			if($groupName !== false) {
469
+			if ($groupName !== false) {
470 470
 				return $groupName;
471 471
 			}
472 472
 		}
@@ -483,22 +483,22 @@  discard block
 block discarded – undo
483 483
 	public function primaryGroupID2Name($gid, $dn) {
484 484
 		$cacheKey = 'primaryGroupIDtoName';
485 485
 		$groupNames = $this->access->connection->getFromCache($cacheKey);
486
-		if(!is_null($groupNames) && isset($groupNames[$gid])) {
486
+		if (!is_null($groupNames) && isset($groupNames[$gid])) {
487 487
 			return $groupNames[$gid];
488 488
 		}
489 489
 
490 490
 		$domainObjectSid = $this->access->getSID($dn);
491
-		if($domainObjectSid === false) {
491
+		if ($domainObjectSid === false) {
492 492
 			return false;
493 493
 		}
494 494
 
495 495
 		//we need to get the DN from LDAP
496 496
 		$filter = $this->access->combineFilterWithAnd([
497 497
 			$this->access->connection->ldapGroupFilter,
498
-			'objectsid=' . $domainObjectSid . '-' . $gid
498
+			'objectsid='.$domainObjectSid.'-'.$gid
499 499
 		]);
500 500
 		$result = $this->access->searchGroups($filter, ['dn'], 1);
501
-		if(empty($result)) {
501
+		if (empty($result)) {
502 502
 			return false;
503 503
 		}
504 504
 		$dn = $result[0]['dn'][0];
@@ -521,7 +521,7 @@  discard block
 block discarded – undo
521 521
 	 */
522 522
 	private function getEntryGroupID($dn, $attribute) {
523 523
 		$value = $this->access->readAttribute($dn, $attribute);
524
-		if(is_array($value) && !empty($value)) {
524
+		if (is_array($value) && !empty($value)) {
525 525
 			return $value[0];
526 526
 		}
527 527
 		return false;
@@ -543,9 +543,9 @@  discard block
 block discarded – undo
543 543
 	 */
544 544
 	public function getUserPrimaryGroupIDs($dn) {
545 545
 		$primaryGroupID = false;
546
-		if($this->access->connection->hasPrimaryGroups) {
546
+		if ($this->access->connection->hasPrimaryGroups) {
547 547
 			$primaryGroupID = $this->getEntryGroupID($dn, 'primaryGroupID');
548
-			if($primaryGroupID === false) {
548
+			if ($primaryGroupID === false) {
549 549
 				$this->access->connection->hasPrimaryGroups = false;
550 550
 			}
551 551
 		}
@@ -562,7 +562,7 @@  discard block
 block discarded – undo
562 562
 	 */
563 563
 	private function prepareFilterForUsersInPrimaryGroup($groupDN, $search = '') {
564 564
 		$groupID = $this->getGroupPrimaryGroupID($groupDN);
565
-		if($groupID === false) {
565
+		if ($groupID === false) {
566 566
 			throw new \Exception('Not a valid group');
567 567
 		}
568 568
 
@@ -571,7 +571,7 @@  discard block
 block discarded – undo
571 571
 		if ($search !== '') {
572 572
 			$filterParts[] = $this->access->getFilterPartForUserSearch($search);
573 573
 		}
574
-		$filterParts[] = 'primaryGroupID=' . $groupID;
574
+		$filterParts[] = 'primaryGroupID='.$groupID;
575 575
 
576 576
 		return $this->access->combineFilterWithAnd($filterParts);
577 577
 	}
@@ -613,7 +613,7 @@  discard block
 block discarded – undo
613 613
 		try {
614 614
 			$filter = $this->prepareFilterForUsersInPrimaryGroup($groupDN, $search);
615 615
 			$users = $this->access->countUsers($filter, ['dn'], $limit, $offset);
616
-			return (int)$users;
616
+			return (int) $users;
617 617
 		} catch (\Exception $e) {
618 618
 			return 0;
619 619
 		}
@@ -626,9 +626,9 @@  discard block
 block discarded – undo
626 626
 	 */
627 627
 	public function getUserPrimaryGroup($dn) {
628 628
 		$groupID = $this->getUserPrimaryGroupIDs($dn);
629
-		if($groupID !== false) {
629
+		if ($groupID !== false) {
630 630
 			$groupName = $this->primaryGroupID2Name($groupID, $dn);
631
-			if($groupName !== false) {
631
+			if ($groupName !== false) {
632 632
 				return $groupName;
633 633
 			}
634 634
 		}
@@ -647,16 +647,16 @@  discard block
 block discarded – undo
647 647
 	 * This function includes groups based on dynamic group membership.
648 648
 	 */
649 649
 	public function getUserGroups($uid) {
650
-		if(!$this->enabled) {
650
+		if (!$this->enabled) {
651 651
 			return [];
652 652
 		}
653 653
 		$cacheKey = 'getUserGroups'.$uid;
654 654
 		$userGroups = $this->access->connection->getFromCache($cacheKey);
655
-		if(!is_null($userGroups)) {
655
+		if (!is_null($userGroups)) {
656 656
 			return $userGroups;
657 657
 		}
658 658
 		$userDN = $this->access->username2dn($uid);
659
-		if(!$userDN) {
659
+		if (!$userDN) {
660 660
 			$this->access->connection->writeToCache($cacheKey, []);
661 661
 			return [];
662 662
 		}
@@ -670,14 +670,14 @@  discard block
 block discarded – undo
670 670
 		if (!empty($dynamicGroupMemberURL)) {
671 671
 			// look through dynamic groups to add them to the result array if needed
672 672
 			$groupsToMatch = $this->access->fetchListOfGroups(
673
-				$this->access->connection->ldapGroupFilter,['dn',$dynamicGroupMemberURL]);
674
-			foreach($groupsToMatch as $dynamicGroup) {
673
+				$this->access->connection->ldapGroupFilter, ['dn', $dynamicGroupMemberURL]);
674
+			foreach ($groupsToMatch as $dynamicGroup) {
675 675
 				if (!array_key_exists($dynamicGroupMemberURL, $dynamicGroup)) {
676 676
 					continue;
677 677
 				}
678 678
 				$pos = strpos($dynamicGroup[$dynamicGroupMemberURL][0], '(');
679 679
 				if ($pos !== false) {
680
-					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0],$pos);
680
+					$memberUrlFilter = substr($dynamicGroup[$dynamicGroupMemberURL][0], $pos);
681 681
 					// apply filter via ldap search to see if this user is in this
682 682
 					// dynamic group
683 683
 					$userMatch = $this->access->readAttribute(
@@ -688,7 +688,7 @@  discard block
 block discarded – undo
688 688
 					if ($userMatch !== false) {
689 689
 						// match found so this user is in this group
690 690
 						$groupName = $this->access->dn2groupname($dynamicGroup['dn'][0]);
691
-						if(is_string($groupName)) {
691
+						if (is_string($groupName)) {
692 692
 							// be sure to never return false if the dn could not be
693 693
 							// resolved to a name, for whatever reason.
694 694
 							$groups[] = $groupName;
@@ -696,7 +696,7 @@  discard block
 block discarded – undo
696 696
 					}
697 697
 				} else {
698 698
 					\OCP\Util::writeLog('user_ldap', 'No search filter found on member url '.
699
-						'of group ' . print_r($dynamicGroup, true), ILogger::DEBUG);
699
+						'of group '.print_r($dynamicGroup, true), ILogger::DEBUG);
700 700
 				}
701 701
 			}
702 702
 		}
@@ -704,15 +704,15 @@  discard block
 block discarded – undo
704 704
 		// if possible, read out membership via memberOf. It's far faster than
705 705
 		// performing a search, which still is a fallback later.
706 706
 		// memberof doesn't support memberuid, so skip it here.
707
-		if((int)$this->access->connection->hasMemberOfFilterSupport === 1
708
-			&& (int)$this->access->connection->useMemberOfToDetectMembership === 1
707
+		if ((int) $this->access->connection->hasMemberOfFilterSupport === 1
708
+			&& (int) $this->access->connection->useMemberOfToDetectMembership === 1
709 709
 		    && strtolower($this->access->connection->ldapGroupMemberAssocAttr) !== 'memberuid'
710 710
 		    ) {
711 711
 			$groupDNs = $this->_getGroupDNsFromMemberOf($userDN);
712 712
 			if (is_array($groupDNs)) {
713 713
 				foreach ($groupDNs as $dn) {
714 714
 					$groupName = $this->access->dn2groupname($dn);
715
-					if(is_string($groupName)) {
715
+					if (is_string($groupName)) {
716 716
 						// be sure to never return false if the dn could not be
717 717
 						// resolved to a name, for whatever reason.
718 718
 						$groups[] = $groupName;
@@ -720,10 +720,10 @@  discard block
 block discarded – undo
720 720
 				}
721 721
 			}
722 722
 
723
-			if($primaryGroup !== false) {
723
+			if ($primaryGroup !== false) {
724 724
 				$groups[] = $primaryGroup;
725 725
 			}
726
-			if($gidGroupName !== false) {
726
+			if ($gidGroupName !== false) {
727 727
 				$groups[] = $gidGroupName;
728 728
 			}
729 729
 			$this->access->connection->writeToCache($cacheKey, $groups);
@@ -731,14 +731,14 @@  discard block
 block discarded – undo
731 731
 		}
732 732
 
733 733
 		//uniqueMember takes DN, memberuid the uid, so we need to distinguish
734
-		if((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
734
+		if ((strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'uniquemember')
735 735
 			|| (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'member')
736 736
 		) {
737 737
 			$uid = $userDN;
738
-		} else if(strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
738
+		} else if (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid') {
739 739
 			$result = $this->access->readAttribute($userDN, 'uid');
740 740
 			if ($result === false) {
741
-				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN ' . $userDN . ' on '.
741
+				\OCP\Util::writeLog('user_ldap', 'No uid attribute found for DN '.$userDN.' on '.
742 742
 					$this->access->connection->ldapHost, ILogger::DEBUG);
743 743
 				$uid = false;
744 744
 			} else {
@@ -749,7 +749,7 @@  discard block
 block discarded – undo
749 749
 			$uid = $userDN;
750 750
 		}
751 751
 
752
-		if($uid !== false) {
752
+		if ($uid !== false) {
753 753
 			if (isset($this->cachedGroupsByMember[$uid])) {
754 754
 				$groups = array_merge($groups, $this->cachedGroupsByMember[$uid]);
755 755
 			} else {
@@ -760,10 +760,10 @@  discard block
 block discarded – undo
760 760
 			}
761 761
 		}
762 762
 
763
-		if($primaryGroup !== false) {
763
+		if ($primaryGroup !== false) {
764 764
 			$groups[] = $primaryGroup;
765 765
 		}
766
-		if($gidGroupName !== false) {
766
+		if ($gidGroupName !== false) {
767 767
 			$groups[] = $gidGroupName;
768 768
 		}
769 769
 
@@ -792,8 +792,8 @@  discard block
 block discarded – undo
792 792
 		$groups = $this->access->fetchListOfGroups($filter,
793 793
 			[$this->access->connection->ldapGroupDisplayName, 'dn']);
794 794
 		if (is_array($groups)) {
795
-			$fetcher = function ($dn, &$seen) {
796
-				if(is_array($dn) && isset($dn['dn'][0])) {
795
+			$fetcher = function($dn, &$seen) {
796
+				if (is_array($dn) && isset($dn['dn'][0])) {
797 797
 					$dn = $dn['dn'][0];
798 798
 				}
799 799
 				return $this->getGroupsByMember($dn, $seen);
@@ -815,33 +815,33 @@  discard block
 block discarded – undo
815 815
 	 * @throws \Exception
816 816
 	 */
817 817
 	public function usersInGroup($gid, $search = '', $limit = -1, $offset = 0) {
818
-		if(!$this->enabled) {
818
+		if (!$this->enabled) {
819 819
 			return [];
820 820
 		}
821
-		if(!$this->groupExists($gid)) {
821
+		if (!$this->groupExists($gid)) {
822 822
 			return [];
823 823
 		}
824 824
 		$search = $this->access->escapeFilterPart($search, true);
825 825
 		$cacheKey = 'usersInGroup-'.$gid.'-'.$search.'-'.$limit.'-'.$offset;
826 826
 		// check for cache of the exact query
827 827
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
828
-		if(!is_null($groupUsers)) {
828
+		if (!is_null($groupUsers)) {
829 829
 			return $groupUsers;
830 830
 		}
831 831
 
832 832
 		// check for cache of the query without limit and offset
833 833
 		$groupUsers = $this->access->connection->getFromCache('usersInGroup-'.$gid.'-'.$search);
834
-		if(!is_null($groupUsers)) {
834
+		if (!is_null($groupUsers)) {
835 835
 			$groupUsers = array_slice($groupUsers, $offset, $limit);
836 836
 			$this->access->connection->writeToCache($cacheKey, $groupUsers);
837 837
 			return $groupUsers;
838 838
 		}
839 839
 
840
-		if($limit === -1) {
840
+		if ($limit === -1) {
841 841
 			$limit = null;
842 842
 		}
843 843
 		$groupDN = $this->access->groupname2dn($gid);
844
-		if(!$groupDN) {
844
+		if (!$groupDN) {
845 845
 			// group couldn't be found, return empty resultset
846 846
 			$this->access->connection->writeToCache($cacheKey, []);
847 847
 			return [];
@@ -850,7 +850,7 @@  discard block
 block discarded – undo
850 850
 		$primaryUsers = $this->getUsersInPrimaryGroup($groupDN, $search, $limit, $offset);
851 851
 		$posixGroupUsers = $this->getUsersInGidNumber($groupDN, $search, $limit, $offset);
852 852
 		$members = $this->_groupMembers($groupDN);
853
-		if(!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
853
+		if (!$members && empty($posixGroupUsers) && empty($primaryUsers)) {
854 854
 			//in case users could not be retrieved, return empty result set
855 855
 			$this->access->connection->writeToCache($cacheKey, []);
856 856
 			return [];
@@ -859,8 +859,8 @@  discard block
 block discarded – undo
859 859
 		$groupUsers = [];
860 860
 		$isMemberUid = (strtolower($this->access->connection->ldapGroupMemberAssocAttr) === 'memberuid');
861 861
 		$attrs = $this->access->userManager->getAttributes(true);
862
-		foreach($members as $member) {
863
-			if($isMemberUid) {
862
+		foreach ($members as $member) {
863
+			if ($isMemberUid) {
864 864
 				//we got uids, need to get their DNs to 'translate' them to user names
865 865
 				$filter = $this->access->combineFilterWithAnd([
866 866
 					str_replace('%uid', trim($member), $this->access->connection->ldapLoginFilter),
@@ -870,23 +870,23 @@  discard block
 block discarded – undo
870 870
 					])
871 871
 				]);
872 872
 				$ldap_users = $this->access->fetchListOfUsers($filter, $attrs, 1);
873
-				if(count($ldap_users) < 1) {
873
+				if (count($ldap_users) < 1) {
874 874
 					continue;
875 875
 				}
876 876
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]['dn'][0]);
877 877
 			} else {
878 878
 				//we got DNs, check if we need to filter by search or we can give back all of them
879 879
 				$uid = $this->access->dn2username($member);
880
-				if(!$uid) {
880
+				if (!$uid) {
881 881
 					continue;
882 882
 				}
883 883
 
884
-				$cacheKey = 'userExistsOnLDAP' . $uid;
884
+				$cacheKey = 'userExistsOnLDAP'.$uid;
885 885
 				$userExists = $this->access->connection->getFromCache($cacheKey);
886
-				if($userExists === false) {
886
+				if ($userExists === false) {
887 887
 					continue;
888 888
 				}
889
-				if($userExists === null || $search !== '') {
889
+				if ($userExists === null || $search !== '') {
890 890
 					if (!$this->access->readAttribute($member,
891 891
 						$this->access->connection->ldapUserDisplayName,
892 892
 						$this->access->combineFilterWithAnd([
@@ -894,7 +894,7 @@  discard block
 block discarded – undo
894 894
 							$this->access->connection->ldapUserFilter
895 895
 						])))
896 896
 					{
897
-						if($search === '') {
897
+						if ($search === '') {
898 898
 							$this->access->connection->writeToCache($cacheKey, false);
899 899
 						}
900 900
 						continue;
@@ -927,16 +927,16 @@  discard block
 block discarded – undo
927 927
 		}
928 928
 
929 929
 		$cacheKey = 'countUsersInGroup-'.$gid.'-'.$search;
930
-		if(!$this->enabled || !$this->groupExists($gid)) {
930
+		if (!$this->enabled || !$this->groupExists($gid)) {
931 931
 			return false;
932 932
 		}
933 933
 		$groupUsers = $this->access->connection->getFromCache($cacheKey);
934
-		if(!is_null($groupUsers)) {
934
+		if (!is_null($groupUsers)) {
935 935
 			return $groupUsers;
936 936
 		}
937 937
 
938 938
 		$groupDN = $this->access->groupname2dn($gid);
939
-		if(!$groupDN) {
939
+		if (!$groupDN) {
940 940
 			// group couldn't be found, return empty result set
941 941
 			$this->access->connection->writeToCache($cacheKey, false);
942 942
 			return false;
@@ -944,7 +944,7 @@  discard block
 block discarded – undo
944 944
 
945 945
 		$members = $this->_groupMembers($groupDN);
946 946
 		$primaryUserCount = $this->countUsersInPrimaryGroup($groupDN, '');
947
-		if(!$members && $primaryUserCount === 0) {
947
+		if (!$members && $primaryUserCount === 0) {
948 948
 			//in case users could not be retrieved, return empty result set
949 949
 			$this->access->connection->writeToCache($cacheKey, false);
950 950
 			return false;
@@ -969,27 +969,27 @@  discard block
 block discarded – undo
969 969
 		//For now this is not important, because the only use of this method
970 970
 		//does not supply a search string
971 971
 		$groupUsers = [];
972
-		foreach($members as $member) {
973
-			if($isMemberUid) {
972
+		foreach ($members as $member) {
973
+			if ($isMemberUid) {
974 974
 				//we got uids, need to get their DNs to 'translate' them to user names
975 975
 				$filter = $this->access->combineFilterWithAnd([
976 976
 					str_replace('%uid', $member, $this->access->connection->ldapLoginFilter),
977 977
 					$this->access->getFilterPartForUserSearch($search)
978 978
 				]);
979 979
 				$ldap_users = $this->access->fetchListOfUsers($filter, 'dn', 1);
980
-				if(count($ldap_users) < 1) {
980
+				if (count($ldap_users) < 1) {
981 981
 					continue;
982 982
 				}
983 983
 				$groupUsers[] = $this->access->dn2username($ldap_users[0]);
984 984
 			} else {
985 985
 				//we need to apply the search filter now
986
-				if(!$this->access->readAttribute($member,
986
+				if (!$this->access->readAttribute($member,
987 987
 					$this->access->connection->ldapUserDisplayName,
988 988
 					$this->access->getFilterPartForUserSearch($search))) {
989 989
 					continue;
990 990
 				}
991 991
 				// dn2username will also check if the users belong to the allowed base
992
-				if($ocname = $this->access->dn2username($member)) {
992
+				if ($ocname = $this->access->dn2username($member)) {
993 993
 					$groupUsers[] = $ocname;
994 994
 				}
995 995
 			}
@@ -1012,7 +1012,7 @@  discard block
 block discarded – undo
1012 1012
 	 * Returns a list with all groups (used by getGroups)
1013 1013
 	 */
1014 1014
 	protected function getGroupsChunk($search = '', $limit = -1, $offset = 0) {
1015
-		if(!$this->enabled) {
1015
+		if (!$this->enabled) {
1016 1016
 			return [];
1017 1017
 		}
1018 1018
 		$cacheKey = 'getGroups-'.$search.'-'.$limit.'-'.$offset;
@@ -1020,13 +1020,13 @@  discard block
 block discarded – undo
1020 1020
 		//Check cache before driving unnecessary searches
1021 1021
 		\OCP\Util::writeLog('user_ldap', 'getGroups '.$cacheKey, ILogger::DEBUG);
1022 1022
 		$ldap_groups = $this->access->connection->getFromCache($cacheKey);
1023
-		if(!is_null($ldap_groups)) {
1023
+		if (!is_null($ldap_groups)) {
1024 1024
 			return $ldap_groups;
1025 1025
 		}
1026 1026
 
1027 1027
 		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
1028 1028
 		// error. With a limit of 0, we get 0 results. So we pass null.
1029
-		if($limit <= 0) {
1029
+		if ($limit <= 0) {
1030 1030
 			$limit = null;
1031 1031
 		}
1032 1032
 		$filter = $this->access->combineFilterWithAnd([
@@ -1058,11 +1058,11 @@  discard block
 block discarded – undo
1058 1058
 	 * (active directory has a limit of 1000 by default)
1059 1059
 	 */
1060 1060
 	public function getGroups($search = '', $limit = -1, $offset = 0) {
1061
-		if(!$this->enabled) {
1061
+		if (!$this->enabled) {
1062 1062
 			return [];
1063 1063
 		}
1064 1064
 		$search = $this->access->escapeFilterPart($search, true);
1065
-		$pagingSize = (int)$this->access->connection->ldapPagingSize;
1065
+		$pagingSize = (int) $this->access->connection->ldapPagingSize;
1066 1066
 		if ($pagingSize <= 0) {
1067 1067
 			return $this->getGroupsChunk($search, $limit, $offset);
1068 1068
 		}
@@ -1105,20 +1105,20 @@  discard block
 block discarded – undo
1105 1105
 	 */
1106 1106
 	public function groupExists($gid) {
1107 1107
 		$groupExists = $this->access->connection->getFromCache('groupExists'.$gid);
1108
-		if(!is_null($groupExists)) {
1109
-			return (bool)$groupExists;
1108
+		if (!is_null($groupExists)) {
1109
+			return (bool) $groupExists;
1110 1110
 		}
1111 1111
 
1112 1112
 		//getting dn, if false the group does not exist. If dn, it may be mapped
1113 1113
 		//only, requires more checking.
1114 1114
 		$dn = $this->access->groupname2dn($gid);
1115
-		if(!$dn) {
1115
+		if (!$dn) {
1116 1116
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1117 1117
 			return false;
1118 1118
 		}
1119 1119
 
1120 1120
 		//if group really still exists, we will be able to read its objectclass
1121
-		if(!is_array($this->access->readAttribute($dn, ''))) {
1121
+		if (!is_array($this->access->readAttribute($dn, ''))) {
1122 1122
 			$this->access->connection->writeToCache('groupExists'.$gid, false);
1123 1123
 			return false;
1124 1124
 		}
@@ -1136,7 +1136,7 @@  discard block
 block discarded – undo
1136 1136
 	* compared with GroupInterface::CREATE_GROUP etc.
1137 1137
 	*/
1138 1138
 	public function implementsActions($actions) {
1139
-		return (bool)((GroupInterface::COUNT_USERS |
1139
+		return (bool) ((GroupInterface::COUNT_USERS |
1140 1140
 				$this->groupPluginManager->getImplementedActions()) & $actions);
1141 1141
 	}
1142 1142
 
@@ -1159,7 +1159,7 @@  discard block
 block discarded – undo
1159 1159
 			if ($dn = $this->groupPluginManager->createGroup($gid)) {
1160 1160
 				//updates group mapping
1161 1161
 				$uuid = $this->access->getUUID($dn, false);
1162
-				if(is_string($uuid)) {
1162
+				if (is_string($uuid)) {
1163 1163
 					$this->access->mapAndAnnounceIfApplicable(
1164 1164
 						$this->access->getGroupMapper(),
1165 1165
 						$dn,
@@ -1262,7 +1262,7 @@  discard block
 block discarded – undo
1262 1262
 			return $this->groupPluginManager->getDisplayName($gid);
1263 1263
 		}
1264 1264
 
1265
-		$cacheKey = 'group_getDisplayName' . $gid;
1265
+		$cacheKey = 'group_getDisplayName'.$gid;
1266 1266
 		if (!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
1267 1267
 			return $displayName;
1268 1268
 		}
Please login to merge, or discard this patch.