Completed
Pull Request — master (#7057)
by Blizzz
14:25
created
apps/user_ldap/lib/Jobs/UpdateGroups.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -45,183 +45,183 @@
 block discarded – undo
45 45
 use OCA\User_LDAP\User\Manager;
46 46
 
47 47
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
48
-	static private $groupsFromDB;
49
-
50
-	static private $groupBE;
51
-
52
-	public function __construct(){
53
-		$this->interval = self::getRefreshInterval();
54
-	}
55
-
56
-	/**
57
-	 * @param mixed $argument
58
-	 */
59
-	public function run($argument){
60
-		self::updateGroups();
61
-	}
62
-
63
-	static public function updateGroups() {
64
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
65
-
66
-		$knownGroups = array_keys(self::getKnownGroups());
67
-		$actualGroups = self::getGroupBE()->getGroups();
68
-
69
-		if(empty($actualGroups) && empty($knownGroups)) {
70
-			\OCP\Util::writeLog('user_ldap',
71
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
-				\OCP\Util::INFO);
73
-			return;
74
-		}
75
-
76
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
-
80
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
81
-	}
82
-
83
-	/**
84
-	 * @return int
85
-	 */
86
-	static private function getRefreshInterval() {
87
-		//defaults to every hour
88
-		return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
-	}
90
-
91
-	/**
92
-	 * @param string[] $groups
93
-	 */
94
-	static private function handleKnownGroups($groups) {
95
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
96
-		$query = \OCP\DB::prepare('
48
+    static private $groupsFromDB;
49
+
50
+    static private $groupBE;
51
+
52
+    public function __construct(){
53
+        $this->interval = self::getRefreshInterval();
54
+    }
55
+
56
+    /**
57
+     * @param mixed $argument
58
+     */
59
+    public function run($argument){
60
+        self::updateGroups();
61
+    }
62
+
63
+    static public function updateGroups() {
64
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
65
+
66
+        $knownGroups = array_keys(self::getKnownGroups());
67
+        $actualGroups = self::getGroupBE()->getGroups();
68
+
69
+        if(empty($actualGroups) && empty($knownGroups)) {
70
+            \OCP\Util::writeLog('user_ldap',
71
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
72
+                \OCP\Util::INFO);
73
+            return;
74
+        }
75
+
76
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
77
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
78
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
79
+
80
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
81
+    }
82
+
83
+    /**
84
+     * @return int
85
+     */
86
+    static private function getRefreshInterval() {
87
+        //defaults to every hour
88
+        return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
89
+    }
90
+
91
+    /**
92
+     * @param string[] $groups
93
+     */
94
+    static private function handleKnownGroups($groups) {
95
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
96
+        $query = \OCP\DB::prepare('
97 97
 			UPDATE `*PREFIX*ldap_group_members`
98 98
 			SET `owncloudusers` = ?
99 99
 			WHERE `owncloudname` = ?
100 100
 		');
101
-		foreach($groups as $group) {
102
-			//we assume, that self::$groupsFromDB has been retrieved already
103
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
105
-			$hasChanged = false;
106
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
108
-				\OCP\Util::writeLog('user_ldap',
109
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
-				\OCP\Util::INFO);
111
-				$hasChanged = true;
112
-			}
113
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
115
-				\OCP\Util::writeLog('user_ldap',
116
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
-				\OCP\Util::INFO);
118
-				$hasChanged = true;
119
-			}
120
-			if($hasChanged) {
121
-				$query->execute(array(serialize($actualUsers), $group));
122
-			}
123
-		}
124
-		\OCP\Util::writeLog('user_ldap',
125
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
-			\OCP\Util::DEBUG);
127
-	}
128
-
129
-	/**
130
-	 * @param string[] $createdGroups
131
-	 */
132
-	static private function handleCreatedGroups($createdGroups) {
133
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
134
-		$query = \OCP\DB::prepare('
101
+        foreach($groups as $group) {
102
+            //we assume, that self::$groupsFromDB has been retrieved already
103
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
104
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
105
+            $hasChanged = false;
106
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
107
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
108
+                \OCP\Util::writeLog('user_ldap',
109
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
110
+                \OCP\Util::INFO);
111
+                $hasChanged = true;
112
+            }
113
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
114
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
115
+                \OCP\Util::writeLog('user_ldap',
116
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
117
+                \OCP\Util::INFO);
118
+                $hasChanged = true;
119
+            }
120
+            if($hasChanged) {
121
+                $query->execute(array(serialize($actualUsers), $group));
122
+            }
123
+        }
124
+        \OCP\Util::writeLog('user_ldap',
125
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
126
+            \OCP\Util::DEBUG);
127
+    }
128
+
129
+    /**
130
+     * @param string[] $createdGroups
131
+     */
132
+    static private function handleCreatedGroups($createdGroups) {
133
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
134
+        $query = \OCP\DB::prepare('
135 135
 			INSERT
136 136
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
137 137
 			VALUES (?, ?)
138 138
 		');
139
-		foreach($createdGroups as $createdGroup) {
140
-			\OCP\Util::writeLog('user_ldap',
141
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
-				\OCP\Util::INFO);
143
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
-			$query->execute(array($createdGroup, $users));
145
-		}
146
-		\OCP\Util::writeLog('user_ldap',
147
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
-			\OCP\Util::DEBUG);
149
-	}
150
-
151
-	/**
152
-	 * @param string[] $removedGroups
153
-	 */
154
-	static private function handleRemovedGroups($removedGroups) {
155
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
156
-		$query = \OCP\DB::prepare('
139
+        foreach($createdGroups as $createdGroup) {
140
+            \OCP\Util::writeLog('user_ldap',
141
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
142
+                \OCP\Util::INFO);
143
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
144
+            $query->execute(array($createdGroup, $users));
145
+        }
146
+        \OCP\Util::writeLog('user_ldap',
147
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
148
+            \OCP\Util::DEBUG);
149
+    }
150
+
151
+    /**
152
+     * @param string[] $removedGroups
153
+     */
154
+    static private function handleRemovedGroups($removedGroups) {
155
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
156
+        $query = \OCP\DB::prepare('
157 157
 			DELETE
158 158
 			FROM `*PREFIX*ldap_group_members`
159 159
 			WHERE `owncloudname` = ?
160 160
 		');
161
-		foreach($removedGroups as $removedGroup) {
162
-			\OCP\Util::writeLog('user_ldap',
163
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
-				\OCP\Util::INFO);
165
-			$query->execute(array($removedGroup));
166
-		}
167
-		\OCP\Util::writeLog('user_ldap',
168
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
-			\OCP\Util::DEBUG);
170
-	}
171
-
172
-	/**
173
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
-	 */
175
-	static private function getGroupBE() {
176
-		if(!is_null(self::$groupBE)) {
177
-			return self::$groupBE;
178
-		}
179
-		$helper = new Helper(\OC::$server->getConfig());
180
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
-		$ldapWrapper = new LDAP();
182
-		if(count($configPrefixes) === 1) {
183
-			//avoid the proxy when there is only one LDAP server configured
184
-			$dbc = \OC::$server->getDatabaseConnection();
185
-			$userManager = new Manager(
186
-				\OC::$server->getConfig(),
187
-				new FilesystemHelper(),
188
-				new LogWrapper(),
189
-				\OC::$server->getAvatarManager(),
190
-				new \OCP\Image(),
191
-				$dbc,
192
-				\OC::$server->getUserManager(),
193
-				\OC::$server->getNotificationManager());
194
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server);
196
-			$groupMapper = new GroupMapping($dbc);
197
-			$userMapper  = new UserMapping($dbc);
198
-			$ldapAccess->setGroupMapper($groupMapper);
199
-			$ldapAccess->setUserMapper($userMapper);
200
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
-		} else {
202
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
-		}
204
-
205
-		return self::$groupBE;
206
-	}
207
-
208
-	/**
209
-	 * @return array
210
-	 */
211
-	static private function getKnownGroups() {
212
-		if(is_array(self::$groupsFromDB)) {
213
-			return self::$groupsFromDB;
214
-		}
215
-		$query = \OCP\DB::prepare('
161
+        foreach($removedGroups as $removedGroup) {
162
+            \OCP\Util::writeLog('user_ldap',
163
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
164
+                \OCP\Util::INFO);
165
+            $query->execute(array($removedGroup));
166
+        }
167
+        \OCP\Util::writeLog('user_ldap',
168
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
169
+            \OCP\Util::DEBUG);
170
+    }
171
+
172
+    /**
173
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
174
+     */
175
+    static private function getGroupBE() {
176
+        if(!is_null(self::$groupBE)) {
177
+            return self::$groupBE;
178
+        }
179
+        $helper = new Helper(\OC::$server->getConfig());
180
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
181
+        $ldapWrapper = new LDAP();
182
+        if(count($configPrefixes) === 1) {
183
+            //avoid the proxy when there is only one LDAP server configured
184
+            $dbc = \OC::$server->getDatabaseConnection();
185
+            $userManager = new Manager(
186
+                \OC::$server->getConfig(),
187
+                new FilesystemHelper(),
188
+                new LogWrapper(),
189
+                \OC::$server->getAvatarManager(),
190
+                new \OCP\Image(),
191
+                $dbc,
192
+                \OC::$server->getUserManager(),
193
+                \OC::$server->getNotificationManager());
194
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
195
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server);
196
+            $groupMapper = new GroupMapping($dbc);
197
+            $userMapper  = new UserMapping($dbc);
198
+            $ldapAccess->setGroupMapper($groupMapper);
199
+            $ldapAccess->setUserMapper($userMapper);
200
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query('LDAPGroupPluginManager'));
201
+        } else {
202
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query('LDAPGroupPluginManager'));
203
+        }
204
+
205
+        return self::$groupBE;
206
+    }
207
+
208
+    /**
209
+     * @return array
210
+     */
211
+    static private function getKnownGroups() {
212
+        if(is_array(self::$groupsFromDB)) {
213
+            return self::$groupsFromDB;
214
+        }
215
+        $query = \OCP\DB::prepare('
216 216
 			SELECT `owncloudname`, `owncloudusers`
217 217
 			FROM `*PREFIX*ldap_group_members`
218 218
 		');
219
-		$result = $query->execute()->fetchAll();
220
-		self::$groupsFromDB = array();
221
-		foreach($result as $dataset) {
222
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
-		}
224
-
225
-		return self::$groupsFromDB;
226
-	}
219
+        $result = $query->execute()->fetchAll();
220
+        self::$groupsFromDB = array();
221
+        foreach($result as $dataset) {
222
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
223
+        }
224
+
225
+        return self::$groupsFromDB;
226
+    }
227 227
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User_LDAP.php 1 patch
Indentation   +566 added lines, -566 removed lines patch added patch discarded remove patch
@@ -50,574 +50,574 @@
 block discarded – undo
50 50
 use OCP\Util;
51 51
 
52 52
 class User_LDAP extends BackendUtility implements \OCP\IUserBackend, \OCP\UserInterface, IUserLDAP {
53
-	/** @var \OCP\IConfig */
54
-	protected $ocConfig;
55
-
56
-	/** @var INotificationManager */
57
-	protected $notificationManager;
58
-
59
-	/** @var string */
60
-	protected $currentUserInDeletionProcess;
61
-
62
-	/** @var UserPluginManager */
63
-	protected $userPluginManager;
64
-
65
-	/**
66
-	 * @param Access $access
67
-	 * @param \OCP\IConfig $ocConfig
68
-	 * @param \OCP\Notification\IManager $notificationManager
69
-	 * @param IUserSession $userSession
70
-	 */
71
-	public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
72
-		parent::__construct($access);
73
-		$this->ocConfig = $ocConfig;
74
-		$this->notificationManager = $notificationManager;
75
-		$this->userPluginManager = $userPluginManager;
76
-		$this->registerHooks($userSession);
77
-	}
78
-
79
-	protected function registerHooks(IUserSession $userSession) {
80
-		$userSession->listen('\OC\User', 'preDelete', [$this, 'preDeleteUser']);
81
-		$userSession->listen('\OC\User', 'postDelete', [$this, 'postDeleteUser']);
82
-	}
83
-
84
-	public function preDeleteUser(IUser $user) {
85
-		$this->currentUserInDeletionProcess = $user->getUID();
86
-	}
87
-
88
-	public function postDeleteUser() {
89
-		$this->currentUserInDeletionProcess = null;
90
-	}
91
-
92
-	/**
93
-	 * checks whether the user is allowed to change his avatar in Nextcloud
94
-	 * @param string $uid the Nextcloud user name
95
-	 * @return boolean either the user can or cannot
96
-	 */
97
-	public function canChangeAvatar($uid) {
98
-		if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
99
-			return $this->userPluginManager->canChangeAvatar($uid);
100
-		}
101
-
102
-		$user = $this->access->userManager->get($uid);
103
-		if(!$user instanceof User) {
104
-			return false;
105
-		}
106
-		if($user->getAvatarImage() === false) {
107
-			return true;
108
-		}
109
-
110
-		return false;
111
-	}
112
-
113
-	/**
114
-	 * returns the username for the given login name, if available
115
-	 *
116
-	 * @param string $loginName
117
-	 * @return string|false
118
-	 */
119
-	public function loginName2UserName($loginName) {
120
-		$cacheKey = 'loginName2UserName-'.$loginName;
121
-		$username = $this->access->connection->getFromCache($cacheKey);
122
-		if(!is_null($username)) {
123
-			return $username;
124
-		}
125
-
126
-		try {
127
-			$ldapRecord = $this->getLDAPUserByLoginName($loginName);
128
-			$user = $this->access->userManager->get($ldapRecord['dn'][0]);
129
-			if($user instanceof OfflineUser) {
130
-				// this path is not really possible, however get() is documented
131
-				// to return User or OfflineUser so we are very defensive here.
132
-				$this->access->connection->writeToCache($cacheKey, false);
133
-				return false;
134
-			}
135
-			$username = $user->getUsername();
136
-			$this->access->connection->writeToCache($cacheKey, $username);
137
-			return $username;
138
-		} catch (NotOnLDAP $e) {
139
-			$this->access->connection->writeToCache($cacheKey, false);
140
-			return false;
141
-		}
142
-	}
53
+    /** @var \OCP\IConfig */
54
+    protected $ocConfig;
55
+
56
+    /** @var INotificationManager */
57
+    protected $notificationManager;
58
+
59
+    /** @var string */
60
+    protected $currentUserInDeletionProcess;
61
+
62
+    /** @var UserPluginManager */
63
+    protected $userPluginManager;
64
+
65
+    /**
66
+     * @param Access $access
67
+     * @param \OCP\IConfig $ocConfig
68
+     * @param \OCP\Notification\IManager $notificationManager
69
+     * @param IUserSession $userSession
70
+     */
71
+    public function __construct(Access $access, IConfig $ocConfig, INotificationManager $notificationManager, IUserSession $userSession, UserPluginManager $userPluginManager) {
72
+        parent::__construct($access);
73
+        $this->ocConfig = $ocConfig;
74
+        $this->notificationManager = $notificationManager;
75
+        $this->userPluginManager = $userPluginManager;
76
+        $this->registerHooks($userSession);
77
+    }
78
+
79
+    protected function registerHooks(IUserSession $userSession) {
80
+        $userSession->listen('\OC\User', 'preDelete', [$this, 'preDeleteUser']);
81
+        $userSession->listen('\OC\User', 'postDelete', [$this, 'postDeleteUser']);
82
+    }
83
+
84
+    public function preDeleteUser(IUser $user) {
85
+        $this->currentUserInDeletionProcess = $user->getUID();
86
+    }
87
+
88
+    public function postDeleteUser() {
89
+        $this->currentUserInDeletionProcess = null;
90
+    }
91
+
92
+    /**
93
+     * checks whether the user is allowed to change his avatar in Nextcloud
94
+     * @param string $uid the Nextcloud user name
95
+     * @return boolean either the user can or cannot
96
+     */
97
+    public function canChangeAvatar($uid) {
98
+        if ($this->userPluginManager->implementsActions(Backend::PROVIDE_AVATAR)) {
99
+            return $this->userPluginManager->canChangeAvatar($uid);
100
+        }
101
+
102
+        $user = $this->access->userManager->get($uid);
103
+        if(!$user instanceof User) {
104
+            return false;
105
+        }
106
+        if($user->getAvatarImage() === false) {
107
+            return true;
108
+        }
109
+
110
+        return false;
111
+    }
112
+
113
+    /**
114
+     * returns the username for the given login name, if available
115
+     *
116
+     * @param string $loginName
117
+     * @return string|false
118
+     */
119
+    public function loginName2UserName($loginName) {
120
+        $cacheKey = 'loginName2UserName-'.$loginName;
121
+        $username = $this->access->connection->getFromCache($cacheKey);
122
+        if(!is_null($username)) {
123
+            return $username;
124
+        }
125
+
126
+        try {
127
+            $ldapRecord = $this->getLDAPUserByLoginName($loginName);
128
+            $user = $this->access->userManager->get($ldapRecord['dn'][0]);
129
+            if($user instanceof OfflineUser) {
130
+                // this path is not really possible, however get() is documented
131
+                // to return User or OfflineUser so we are very defensive here.
132
+                $this->access->connection->writeToCache($cacheKey, false);
133
+                return false;
134
+            }
135
+            $username = $user->getUsername();
136
+            $this->access->connection->writeToCache($cacheKey, $username);
137
+            return $username;
138
+        } catch (NotOnLDAP $e) {
139
+            $this->access->connection->writeToCache($cacheKey, false);
140
+            return false;
141
+        }
142
+    }
143 143
 	
144
-	/**
145
-	 * returns the username for the given LDAP DN, if available
146
-	 *
147
-	 * @param string $dn
148
-	 * @return string|false with the username
149
-	 */
150
-	public function dn2UserName($dn) {
151
-		return $this->access->dn2username($dn);
152
-	}
153
-
154
-	/**
155
-	 * returns an LDAP record based on a given login name
156
-	 *
157
-	 * @param string $loginName
158
-	 * @return array
159
-	 * @throws NotOnLDAP
160
-	 */
161
-	public function getLDAPUserByLoginName($loginName) {
162
-		//find out dn of the user name
163
-		$attrs = $this->access->userManager->getAttributes();
164
-		$users = $this->access->fetchUsersByLoginName($loginName, $attrs);
165
-		if(count($users) < 1) {
166
-			throw new NotOnLDAP('No user available for the given login name on ' .
167
-				$this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
168
-		}
169
-		return $users[0];
170
-	}
171
-
172
-	/**
173
-	 * Check if the password is correct without logging in the user
174
-	 *
175
-	 * @param string $uid The username
176
-	 * @param string $password The password
177
-	 * @return false|string
178
-	 */
179
-	public function checkPassword($uid, $password) {
180
-		try {
181
-			$ldapRecord = $this->getLDAPUserByLoginName($uid);
182
-		} catch(NotOnLDAP $e) {
183
-			if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
184
-				\OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
185
-			}
186
-			return false;
187
-		}
188
-		$dn = $ldapRecord['dn'][0];
189
-		$user = $this->access->userManager->get($dn);
190
-
191
-		if(!$user instanceof User) {
192
-			Util::writeLog('user_ldap',
193
-				'LDAP Login: Could not get user object for DN ' . $dn .
194
-				'. Maybe the LDAP entry has no set display name attribute?',
195
-				Util::WARN);
196
-			return false;
197
-		}
198
-		if($user->getUsername() !== false) {
199
-			//are the credentials OK?
200
-			if(!$this->access->areCredentialsValid($dn, $password)) {
201
-				return false;
202
-			}
203
-
204
-			$this->access->cacheUserExists($user->getUsername());
205
-			$user->processAttributes($ldapRecord);
206
-			$user->markLogin();
207
-
208
-			return $user->getUsername();
209
-		}
210
-
211
-		return false;
212
-	}
213
-
214
-	/**
215
-	 * Set password
216
-	 * @param string $uid The username
217
-	 * @param string $password The new password
218
-	 * @return bool
219
-	 */
220
-	public function setPassword($uid, $password) {
221
-		if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
222
-			return $this->userPluginManager->setPassword($uid, $password);
223
-		}
224
-
225
-		$user = $this->access->userManager->get($uid);
226
-
227
-		if(!$user instanceof User) {
228
-			throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
229
-				'. Maybe the LDAP entry has no set display name attribute?');
230
-		}
231
-		if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
232
-			$ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
233
-			$turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
234
-			if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
235
-				//remove last password expiry warning if any
236
-				$notification = $this->notificationManager->createNotification();
237
-				$notification->setApp('user_ldap')
238
-					->setUser($uid)
239
-					->setObject('pwd_exp_warn', $uid)
240
-				;
241
-				$this->notificationManager->markProcessed($notification);
242
-			}
243
-			return true;
244
-		}
245
-
246
-		return false;
247
-	}
248
-
249
-	/**
250
-	 * Get a list of all users
251
-	 *
252
-	 * @param string $search
253
-	 * @param integer $limit
254
-	 * @param integer $offset
255
-	 * @return string[] an array of all uids
256
-	 */
257
-	public function getUsers($search = '', $limit = 10, $offset = 0) {
258
-		$search = $this->access->escapeFilterPart($search, true);
259
-		$cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
260
-
261
-		//check if users are cached, if so return
262
-		$ldap_users = $this->access->connection->getFromCache($cachekey);
263
-		if(!is_null($ldap_users)) {
264
-			return $ldap_users;
265
-		}
266
-
267
-		// if we'd pass -1 to LDAP search, we'd end up in a Protocol
268
-		// error. With a limit of 0, we get 0 results. So we pass null.
269
-		if($limit <= 0) {
270
-			$limit = null;
271
-		}
272
-		$filter = $this->access->combineFilterWithAnd(array(
273
-			$this->access->connection->ldapUserFilter,
274
-			$this->access->connection->ldapUserDisplayName . '=*',
275
-			$this->access->getFilterPartForUserSearch($search)
276
-		));
277
-
278
-		Util::writeLog('user_ldap',
279
-			'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
280
-			Util::DEBUG);
281
-		//do the search and translate results to Nextcloud names
282
-		$ldap_users = $this->access->fetchListOfUsers(
283
-			$filter,
284
-			$this->access->userManager->getAttributes(true),
285
-			$limit, $offset);
286
-		$ldap_users = $this->access->nextcloudUserNames($ldap_users);
287
-		Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
288
-
289
-		$this->access->connection->writeToCache($cachekey, $ldap_users);
290
-		return $ldap_users;
291
-	}
292
-
293
-	/**
294
-	 * checks whether a user is still available on LDAP
295
-	 *
296
-	 * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
297
-	 * name or an instance of that user
298
-	 * @return bool
299
-	 * @throws \Exception
300
-	 * @throws \OC\ServerNotAvailableException
301
-	 */
302
-	public function userExistsOnLDAP($user) {
303
-		if(is_string($user)) {
304
-			$user = $this->access->userManager->get($user);
305
-		}
306
-		if(is_null($user)) {
307
-			return false;
308
-		}
309
-
310
-		$dn = $user->getDN();
311
-		//check if user really still exists by reading its entry
312
-		if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
313
-			$lcr = $this->access->connection->getConnectionResource();
314
-			if(is_null($lcr)) {
315
-				throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
316
-			}
317
-
318
-			try {
319
-				$uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
320
-				if(!$uuid) {
321
-					return false;
322
-				}
323
-				$newDn = $this->access->getUserDnByUuid($uuid);
324
-				//check if renamed user is still valid by reapplying the ldap filter
325
-				if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
326
-					return false;
327
-				}
328
-				$this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
329
-				return true;
330
-			} catch (\Exception $e) {
331
-				return false;
332
-			}
333
-		}
334
-
335
-		if($user instanceof OfflineUser) {
336
-			$user->unmark();
337
-		}
338
-
339
-		return true;
340
-	}
341
-
342
-	/**
343
-	 * check if a user exists
344
-	 * @param string $uid the username
345
-	 * @return boolean
346
-	 * @throws \Exception when connection could not be established
347
-	 */
348
-	public function userExists($uid) {
349
-		$userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
-		if(!is_null($userExists)) {
351
-			return (bool)$userExists;
352
-		}
353
-		//getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354
-		$user = $this->access->userManager->get($uid);
355
-
356
-		if(is_null($user)) {
357
-			Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358
-				$this->access->connection->ldapHost, Util::DEBUG);
359
-			$this->access->connection->writeToCache('userExists'.$uid, false);
360
-			return false;
361
-		} else if($user instanceof OfflineUser) {
362
-			//express check for users marked as deleted. Returning true is
363
-			//necessary for cleanup
364
-			return true;
365
-		}
366
-
367
-		$result = $this->userExistsOnLDAP($user);
368
-		$this->access->connection->writeToCache('userExists'.$uid, $result);
369
-		if($result === true) {
370
-			$user->update();
371
-		}
372
-		return $result;
373
-	}
374
-
375
-	/**
376
-	* returns whether a user was deleted in LDAP
377
-	*
378
-	* @param string $uid The username of the user to delete
379
-	* @return bool
380
-	*/
381
-	public function deleteUser($uid) {
382
-		if ($this->userPluginManager->canDeleteUser()) {
383
-			return $this->userPluginManager->deleteUser($uid);
384
-		}
385
-
386
-		$marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
387
-		if(intval($marked) === 0) {
388
-			\OC::$server->getLogger()->notice(
389
-				'User '.$uid . ' is not marked as deleted, not cleaning up.',
390
-				array('app' => 'user_ldap'));
391
-			return false;
392
-		}
393
-		\OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
394
-			array('app' => 'user_ldap'));
395
-
396
-		$this->access->getUserMapper()->unmap($uid);
397
-		$this->access->userManager->invalidate($uid);
398
-		return true;
399
-	}
400
-
401
-	/**
402
-	 * get the user's home directory
403
-	 *
404
-	 * @param string $uid the username
405
-	 * @return bool|string
406
-	 * @throws NoUserException
407
-	 * @throws \Exception
408
-	 */
409
-	public function getHome($uid) {
410
-		// user Exists check required as it is not done in user proxy!
411
-		if(!$this->userExists($uid)) {
412
-			return false;
413
-		}
414
-
415
-		if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
416
-			return $this->userPluginManager->getHome($uid);
417
-		}
418
-
419
-		$cacheKey = 'getHome'.$uid;
420
-		$path = $this->access->connection->getFromCache($cacheKey);
421
-		if(!is_null($path)) {
422
-			return $path;
423
-		}
424
-
425
-		// early return path if it is a deleted user
426
-		$user = $this->access->userManager->get($uid);
427
-		if($user instanceof OfflineUser) {
428
-			if($this->currentUserInDeletionProcess !== null
429
-				&& $this->currentUserInDeletionProcess === $user->getOCName()
430
-			) {
431
-				return $user->getHomePath();
432
-			} else {
433
-				throw new NoUserException($uid . ' is not a valid user anymore');
434
-			}
435
-		} else if ($user === null) {
436
-			throw new NoUserException($uid . ' is not a valid user anymore');
437
-		}
438
-
439
-		$path = $user->getHomePath();
440
-		$this->access->cacheUserHome($uid, $path);
441
-
442
-		return $path;
443
-	}
444
-
445
-	/**
446
-	 * get display name of the user
447
-	 * @param string $uid user ID of the user
448
-	 * @return string|false display name
449
-	 */
450
-	public function getDisplayName($uid) {
451
-		if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
452
-			return $this->userPluginManager->getDisplayName($uid);
453
-		}
454
-
455
-		if(!$this->userExists($uid)) {
456
-			return false;
457
-		}
458
-
459
-		$cacheKey = 'getDisplayName'.$uid;
460
-		if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
461
-			return $displayName;
462
-		}
463
-
464
-		//Check whether the display name is configured to have a 2nd feature
465
-		$additionalAttribute = $this->access->connection->ldapUserDisplayName2;
466
-		$displayName2 = '';
467
-		if ($additionalAttribute !== '') {
468
-			$displayName2 = $this->access->readAttribute(
469
-				$this->access->username2dn($uid),
470
-				$additionalAttribute);
471
-		}
472
-
473
-		$displayName = $this->access->readAttribute(
474
-			$this->access->username2dn($uid),
475
-			$this->access->connection->ldapUserDisplayName);
476
-
477
-		if($displayName && (count($displayName) > 0)) {
478
-			$displayName = $displayName[0];
479
-
480
-			if (is_array($displayName2)){
481
-				$displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
482
-			}
483
-
484
-			$user = $this->access->userManager->get($uid);
485
-			if ($user instanceof User) {
486
-				$displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
487
-				$this->access->connection->writeToCache($cacheKey, $displayName);
488
-			}
489
-			if ($user instanceof OfflineUser) {
490
-				/** @var OfflineUser $user*/
491
-				$displayName = $user->getDisplayName();
492
-			}
493
-			return $displayName;
494
-		}
495
-
496
-		return null;
497
-	}
498
-
499
-	/**
500
-	 * set display name of the user
501
-	 * @param string $uid user ID of the user
502
-	 * @param string $displayName new display name of the user
503
-	 * @return string|false display name
504
-	 */
505
-	public function setDisplayName($uid, $displayName) {
506
-		if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
507
-			return $this->userPluginManager->setDisplayName($uid, $displayName);
508
-		}
509
-		return false;
510
-	}
511
-
512
-	/**
513
-	 * Get a list of all display names
514
-	 *
515
-	 * @param string $search
516
-	 * @param string|null $limit
517
-	 * @param string|null $offset
518
-	 * @return array an array of all displayNames (value) and the corresponding uids (key)
519
-	 */
520
-	public function getDisplayNames($search = '', $limit = null, $offset = null) {
521
-		$cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
522
-		if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
523
-			return $displayNames;
524
-		}
525
-
526
-		$displayNames = array();
527
-		$users = $this->getUsers($search, $limit, $offset);
528
-		foreach ($users as $user) {
529
-			$displayNames[$user] = $this->getDisplayName($user);
530
-		}
531
-		$this->access->connection->writeToCache($cacheKey, $displayNames);
532
-		return $displayNames;
533
-	}
534
-
535
-	/**
536
-	* Check if backend implements actions
537
-	* @param int $actions bitwise-or'ed actions
538
-	* @return boolean
539
-	*
540
-	* Returns the supported actions as int to be
541
-	* compared with \OC\User\Backend::CREATE_USER etc.
542
-	*/
543
-	public function implementsActions($actions) {
544
-		return (bool)((Backend::CHECK_PASSWORD
545
-			| Backend::GET_HOME
546
-			| Backend::GET_DISPLAYNAME
547
-			| Backend::PROVIDE_AVATAR
548
-			| Backend::COUNT_USERS
549
-			| ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0)
550
-			| $this->userPluginManager->getImplementedActions())
551
-			& $actions);
552
-	}
553
-
554
-	/**
555
-	 * @return bool
556
-	 */
557
-	public function hasUserListings() {
558
-		return true;
559
-	}
560
-
561
-	/**
562
-	 * counts the users in LDAP
563
-	 *
564
-	 * @return int|bool
565
-	 */
566
-	public function countUsers() {
567
-		if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
568
-			return $this->userPluginManager->countUsers();
569
-		}
570
-
571
-		$filter = $this->access->getFilterForUserCount();
572
-		$cacheKey = 'countUsers-'.$filter;
573
-		if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
574
-			return $entries;
575
-		}
576
-		$entries = $this->access->countUsers($filter);
577
-		$this->access->connection->writeToCache($cacheKey, $entries);
578
-		return $entries;
579
-	}
580
-
581
-	/**
582
-	 * Backend name to be shown in user management
583
-	 * @return string the name of the backend to be shown
584
-	 */
585
-	public function getBackendName(){
586
-		return 'LDAP';
587
-	}
144
+    /**
145
+     * returns the username for the given LDAP DN, if available
146
+     *
147
+     * @param string $dn
148
+     * @return string|false with the username
149
+     */
150
+    public function dn2UserName($dn) {
151
+        return $this->access->dn2username($dn);
152
+    }
153
+
154
+    /**
155
+     * returns an LDAP record based on a given login name
156
+     *
157
+     * @param string $loginName
158
+     * @return array
159
+     * @throws NotOnLDAP
160
+     */
161
+    public function getLDAPUserByLoginName($loginName) {
162
+        //find out dn of the user name
163
+        $attrs = $this->access->userManager->getAttributes();
164
+        $users = $this->access->fetchUsersByLoginName($loginName, $attrs);
165
+        if(count($users) < 1) {
166
+            throw new NotOnLDAP('No user available for the given login name on ' .
167
+                $this->access->connection->ldapHost . ':' . $this->access->connection->ldapPort);
168
+        }
169
+        return $users[0];
170
+    }
171
+
172
+    /**
173
+     * Check if the password is correct without logging in the user
174
+     *
175
+     * @param string $uid The username
176
+     * @param string $password The password
177
+     * @return false|string
178
+     */
179
+    public function checkPassword($uid, $password) {
180
+        try {
181
+            $ldapRecord = $this->getLDAPUserByLoginName($uid);
182
+        } catch(NotOnLDAP $e) {
183
+            if($this->ocConfig->getSystemValue('loglevel', Util::WARN) === Util::DEBUG) {
184
+                \OC::$server->getLogger()->logException($e, ['app' => 'user_ldap']);
185
+            }
186
+            return false;
187
+        }
188
+        $dn = $ldapRecord['dn'][0];
189
+        $user = $this->access->userManager->get($dn);
190
+
191
+        if(!$user instanceof User) {
192
+            Util::writeLog('user_ldap',
193
+                'LDAP Login: Could not get user object for DN ' . $dn .
194
+                '. Maybe the LDAP entry has no set display name attribute?',
195
+                Util::WARN);
196
+            return false;
197
+        }
198
+        if($user->getUsername() !== false) {
199
+            //are the credentials OK?
200
+            if(!$this->access->areCredentialsValid($dn, $password)) {
201
+                return false;
202
+            }
203
+
204
+            $this->access->cacheUserExists($user->getUsername());
205
+            $user->processAttributes($ldapRecord);
206
+            $user->markLogin();
207
+
208
+            return $user->getUsername();
209
+        }
210
+
211
+        return false;
212
+    }
213
+
214
+    /**
215
+     * Set password
216
+     * @param string $uid The username
217
+     * @param string $password The new password
218
+     * @return bool
219
+     */
220
+    public function setPassword($uid, $password) {
221
+        if ($this->userPluginManager->implementsActions(Backend::SET_PASSWORD)) {
222
+            return $this->userPluginManager->setPassword($uid, $password);
223
+        }
224
+
225
+        $user = $this->access->userManager->get($uid);
226
+
227
+        if(!$user instanceof User) {
228
+            throw new \Exception('LDAP setPassword: Could not get user object for uid ' . $uid .
229
+                '. Maybe the LDAP entry has no set display name attribute?');
230
+        }
231
+        if($user->getUsername() !== false && $this->access->setPassword($user->getDN(), $password)) {
232
+            $ldapDefaultPPolicyDN = $this->access->connection->ldapDefaultPPolicyDN;
233
+            $turnOnPasswordChange = $this->access->connection->turnOnPasswordChange;
234
+            if (!empty($ldapDefaultPPolicyDN) && (intval($turnOnPasswordChange) === 1)) {
235
+                //remove last password expiry warning if any
236
+                $notification = $this->notificationManager->createNotification();
237
+                $notification->setApp('user_ldap')
238
+                    ->setUser($uid)
239
+                    ->setObject('pwd_exp_warn', $uid)
240
+                ;
241
+                $this->notificationManager->markProcessed($notification);
242
+            }
243
+            return true;
244
+        }
245
+
246
+        return false;
247
+    }
248
+
249
+    /**
250
+     * Get a list of all users
251
+     *
252
+     * @param string $search
253
+     * @param integer $limit
254
+     * @param integer $offset
255
+     * @return string[] an array of all uids
256
+     */
257
+    public function getUsers($search = '', $limit = 10, $offset = 0) {
258
+        $search = $this->access->escapeFilterPart($search, true);
259
+        $cachekey = 'getUsers-'.$search.'-'.$limit.'-'.$offset;
260
+
261
+        //check if users are cached, if so return
262
+        $ldap_users = $this->access->connection->getFromCache($cachekey);
263
+        if(!is_null($ldap_users)) {
264
+            return $ldap_users;
265
+        }
266
+
267
+        // if we'd pass -1 to LDAP search, we'd end up in a Protocol
268
+        // error. With a limit of 0, we get 0 results. So we pass null.
269
+        if($limit <= 0) {
270
+            $limit = null;
271
+        }
272
+        $filter = $this->access->combineFilterWithAnd(array(
273
+            $this->access->connection->ldapUserFilter,
274
+            $this->access->connection->ldapUserDisplayName . '=*',
275
+            $this->access->getFilterPartForUserSearch($search)
276
+        ));
277
+
278
+        Util::writeLog('user_ldap',
279
+            'getUsers: Options: search '.$search.' limit '.$limit.' offset '.$offset.' Filter: '.$filter,
280
+            Util::DEBUG);
281
+        //do the search and translate results to Nextcloud names
282
+        $ldap_users = $this->access->fetchListOfUsers(
283
+            $filter,
284
+            $this->access->userManager->getAttributes(true),
285
+            $limit, $offset);
286
+        $ldap_users = $this->access->nextcloudUserNames($ldap_users);
287
+        Util::writeLog('user_ldap', 'getUsers: '.count($ldap_users). ' Users found', Util::DEBUG);
288
+
289
+        $this->access->connection->writeToCache($cachekey, $ldap_users);
290
+        return $ldap_users;
291
+    }
292
+
293
+    /**
294
+     * checks whether a user is still available on LDAP
295
+     *
296
+     * @param string|\OCA\User_LDAP\User\User $user either the Nextcloud user
297
+     * name or an instance of that user
298
+     * @return bool
299
+     * @throws \Exception
300
+     * @throws \OC\ServerNotAvailableException
301
+     */
302
+    public function userExistsOnLDAP($user) {
303
+        if(is_string($user)) {
304
+            $user = $this->access->userManager->get($user);
305
+        }
306
+        if(is_null($user)) {
307
+            return false;
308
+        }
309
+
310
+        $dn = $user->getDN();
311
+        //check if user really still exists by reading its entry
312
+        if(!is_array($this->access->readAttribute($dn, '', $this->access->connection->ldapUserFilter))) {
313
+            $lcr = $this->access->connection->getConnectionResource();
314
+            if(is_null($lcr)) {
315
+                throw new \Exception('No LDAP Connection to server ' . $this->access->connection->ldapHost);
316
+            }
317
+
318
+            try {
319
+                $uuid = $this->access->getUserMapper()->getUUIDByDN($dn);
320
+                if(!$uuid) {
321
+                    return false;
322
+                }
323
+                $newDn = $this->access->getUserDnByUuid($uuid);
324
+                //check if renamed user is still valid by reapplying the ldap filter
325
+                if(!is_array($this->access->readAttribute($newDn, '', $this->access->connection->ldapUserFilter))) {
326
+                    return false;
327
+                }
328
+                $this->access->getUserMapper()->setDNbyUUID($newDn, $uuid);
329
+                return true;
330
+            } catch (\Exception $e) {
331
+                return false;
332
+            }
333
+        }
334
+
335
+        if($user instanceof OfflineUser) {
336
+            $user->unmark();
337
+        }
338
+
339
+        return true;
340
+    }
341
+
342
+    /**
343
+     * check if a user exists
344
+     * @param string $uid the username
345
+     * @return boolean
346
+     * @throws \Exception when connection could not be established
347
+     */
348
+    public function userExists($uid) {
349
+        $userExists = $this->access->connection->getFromCache('userExists'.$uid);
350
+        if(!is_null($userExists)) {
351
+            return (bool)$userExists;
352
+        }
353
+        //getting dn, if false the user does not exist. If dn, he may be mapped only, requires more checking.
354
+        $user = $this->access->userManager->get($uid);
355
+
356
+        if(is_null($user)) {
357
+            Util::writeLog('user_ldap', 'No DN found for '.$uid.' on '.
358
+                $this->access->connection->ldapHost, Util::DEBUG);
359
+            $this->access->connection->writeToCache('userExists'.$uid, false);
360
+            return false;
361
+        } else if($user instanceof OfflineUser) {
362
+            //express check for users marked as deleted. Returning true is
363
+            //necessary for cleanup
364
+            return true;
365
+        }
366
+
367
+        $result = $this->userExistsOnLDAP($user);
368
+        $this->access->connection->writeToCache('userExists'.$uid, $result);
369
+        if($result === true) {
370
+            $user->update();
371
+        }
372
+        return $result;
373
+    }
374
+
375
+    /**
376
+     * returns whether a user was deleted in LDAP
377
+     *
378
+     * @param string $uid The username of the user to delete
379
+     * @return bool
380
+     */
381
+    public function deleteUser($uid) {
382
+        if ($this->userPluginManager->canDeleteUser()) {
383
+            return $this->userPluginManager->deleteUser($uid);
384
+        }
385
+
386
+        $marked = $this->ocConfig->getUserValue($uid, 'user_ldap', 'isDeleted', 0);
387
+        if(intval($marked) === 0) {
388
+            \OC::$server->getLogger()->notice(
389
+                'User '.$uid . ' is not marked as deleted, not cleaning up.',
390
+                array('app' => 'user_ldap'));
391
+            return false;
392
+        }
393
+        \OC::$server->getLogger()->info('Cleaning up after user ' . $uid,
394
+            array('app' => 'user_ldap'));
395
+
396
+        $this->access->getUserMapper()->unmap($uid);
397
+        $this->access->userManager->invalidate($uid);
398
+        return true;
399
+    }
400
+
401
+    /**
402
+     * get the user's home directory
403
+     *
404
+     * @param string $uid the username
405
+     * @return bool|string
406
+     * @throws NoUserException
407
+     * @throws \Exception
408
+     */
409
+    public function getHome($uid) {
410
+        // user Exists check required as it is not done in user proxy!
411
+        if(!$this->userExists($uid)) {
412
+            return false;
413
+        }
414
+
415
+        if ($this->userPluginManager->implementsActions(Backend::GET_HOME)) {
416
+            return $this->userPluginManager->getHome($uid);
417
+        }
418
+
419
+        $cacheKey = 'getHome'.$uid;
420
+        $path = $this->access->connection->getFromCache($cacheKey);
421
+        if(!is_null($path)) {
422
+            return $path;
423
+        }
424
+
425
+        // early return path if it is a deleted user
426
+        $user = $this->access->userManager->get($uid);
427
+        if($user instanceof OfflineUser) {
428
+            if($this->currentUserInDeletionProcess !== null
429
+                && $this->currentUserInDeletionProcess === $user->getOCName()
430
+            ) {
431
+                return $user->getHomePath();
432
+            } else {
433
+                throw new NoUserException($uid . ' is not a valid user anymore');
434
+            }
435
+        } else if ($user === null) {
436
+            throw new NoUserException($uid . ' is not a valid user anymore');
437
+        }
438
+
439
+        $path = $user->getHomePath();
440
+        $this->access->cacheUserHome($uid, $path);
441
+
442
+        return $path;
443
+    }
444
+
445
+    /**
446
+     * get display name of the user
447
+     * @param string $uid user ID of the user
448
+     * @return string|false display name
449
+     */
450
+    public function getDisplayName($uid) {
451
+        if ($this->userPluginManager->implementsActions(Backend::GET_DISPLAYNAME)) {
452
+            return $this->userPluginManager->getDisplayName($uid);
453
+        }
454
+
455
+        if(!$this->userExists($uid)) {
456
+            return false;
457
+        }
458
+
459
+        $cacheKey = 'getDisplayName'.$uid;
460
+        if(!is_null($displayName = $this->access->connection->getFromCache($cacheKey))) {
461
+            return $displayName;
462
+        }
463
+
464
+        //Check whether the display name is configured to have a 2nd feature
465
+        $additionalAttribute = $this->access->connection->ldapUserDisplayName2;
466
+        $displayName2 = '';
467
+        if ($additionalAttribute !== '') {
468
+            $displayName2 = $this->access->readAttribute(
469
+                $this->access->username2dn($uid),
470
+                $additionalAttribute);
471
+        }
472
+
473
+        $displayName = $this->access->readAttribute(
474
+            $this->access->username2dn($uid),
475
+            $this->access->connection->ldapUserDisplayName);
476
+
477
+        if($displayName && (count($displayName) > 0)) {
478
+            $displayName = $displayName[0];
479
+
480
+            if (is_array($displayName2)){
481
+                $displayName2 = count($displayName2) > 0 ? $displayName2[0] : '';
482
+            }
483
+
484
+            $user = $this->access->userManager->get($uid);
485
+            if ($user instanceof User) {
486
+                $displayName = $user->composeAndStoreDisplayName($displayName, $displayName2);
487
+                $this->access->connection->writeToCache($cacheKey, $displayName);
488
+            }
489
+            if ($user instanceof OfflineUser) {
490
+                /** @var OfflineUser $user*/
491
+                $displayName = $user->getDisplayName();
492
+            }
493
+            return $displayName;
494
+        }
495
+
496
+        return null;
497
+    }
498
+
499
+    /**
500
+     * set display name of the user
501
+     * @param string $uid user ID of the user
502
+     * @param string $displayName new display name of the user
503
+     * @return string|false display name
504
+     */
505
+    public function setDisplayName($uid, $displayName) {
506
+        if ($this->userPluginManager->implementsActions(Backend::SET_DISPLAYNAME)) {
507
+            return $this->userPluginManager->setDisplayName($uid, $displayName);
508
+        }
509
+        return false;
510
+    }
511
+
512
+    /**
513
+     * Get a list of all display names
514
+     *
515
+     * @param string $search
516
+     * @param string|null $limit
517
+     * @param string|null $offset
518
+     * @return array an array of all displayNames (value) and the corresponding uids (key)
519
+     */
520
+    public function getDisplayNames($search = '', $limit = null, $offset = null) {
521
+        $cacheKey = 'getDisplayNames-'.$search.'-'.$limit.'-'.$offset;
522
+        if(!is_null($displayNames = $this->access->connection->getFromCache($cacheKey))) {
523
+            return $displayNames;
524
+        }
525
+
526
+        $displayNames = array();
527
+        $users = $this->getUsers($search, $limit, $offset);
528
+        foreach ($users as $user) {
529
+            $displayNames[$user] = $this->getDisplayName($user);
530
+        }
531
+        $this->access->connection->writeToCache($cacheKey, $displayNames);
532
+        return $displayNames;
533
+    }
534
+
535
+    /**
536
+     * Check if backend implements actions
537
+     * @param int $actions bitwise-or'ed actions
538
+     * @return boolean
539
+     *
540
+     * Returns the supported actions as int to be
541
+     * compared with \OC\User\Backend::CREATE_USER etc.
542
+     */
543
+    public function implementsActions($actions) {
544
+        return (bool)((Backend::CHECK_PASSWORD
545
+            | Backend::GET_HOME
546
+            | Backend::GET_DISPLAYNAME
547
+            | Backend::PROVIDE_AVATAR
548
+            | Backend::COUNT_USERS
549
+            | ((intval($this->access->connection->turnOnPasswordChange) === 1)?(Backend::SET_PASSWORD):0)
550
+            | $this->userPluginManager->getImplementedActions())
551
+            & $actions);
552
+    }
553
+
554
+    /**
555
+     * @return bool
556
+     */
557
+    public function hasUserListings() {
558
+        return true;
559
+    }
560
+
561
+    /**
562
+     * counts the users in LDAP
563
+     *
564
+     * @return int|bool
565
+     */
566
+    public function countUsers() {
567
+        if ($this->userPluginManager->implementsActions(Backend::COUNT_USERS)) {
568
+            return $this->userPluginManager->countUsers();
569
+        }
570
+
571
+        $filter = $this->access->getFilterForUserCount();
572
+        $cacheKey = 'countUsers-'.$filter;
573
+        if(!is_null($entries = $this->access->connection->getFromCache($cacheKey))) {
574
+            return $entries;
575
+        }
576
+        $entries = $this->access->countUsers($filter);
577
+        $this->access->connection->writeToCache($cacheKey, $entries);
578
+        return $entries;
579
+    }
580
+
581
+    /**
582
+     * Backend name to be shown in user management
583
+     * @return string the name of the backend to be shown
584
+     */
585
+    public function getBackendName(){
586
+        return 'LDAP';
587
+    }
588 588
 	
589
-	/**
590
-	 * Return access for LDAP interaction.
591
-	 * @param string $uid
592
-	 * @return Access instance of Access for LDAP interaction
593
-	 */
594
-	public function getLDAPAccess($uid) {
595
-		return $this->access;
596
-	}
589
+    /**
590
+     * Return access for LDAP interaction.
591
+     * @param string $uid
592
+     * @return Access instance of Access for LDAP interaction
593
+     */
594
+    public function getLDAPAccess($uid) {
595
+        return $this->access;
596
+    }
597 597
 	
598
-	/**
599
-	 * Return LDAP connection resource from a cloned connection.
600
-	 * The cloned connection needs to be closed manually.
601
-	 * of the current access.
602
-	 * @param string $uid
603
-	 * @return resource of the LDAP connection
604
-	 */
605
-	public function getNewLDAPConnection($uid) {
606
-		$connection = clone $this->access->getConnection();
607
-		return $connection->getConnectionResource();
608
-	}
609
-
610
-	/**
611
-	 * create new user
612
-	 * @param string $username username of the new user
613
-	 * @param string $password password of the new user
614
-	 * @return bool was the user created?
615
-	 */
616
-	public function createUser($username, $password) {
617
-		if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
618
-			return $this->userPluginManager->createUser($username, $password);
619
-		}
620
-		return false;
621
-	}
598
+    /**
599
+     * Return LDAP connection resource from a cloned connection.
600
+     * The cloned connection needs to be closed manually.
601
+     * of the current access.
602
+     * @param string $uid
603
+     * @return resource of the LDAP connection
604
+     */
605
+    public function getNewLDAPConnection($uid) {
606
+        $connection = clone $this->access->getConnection();
607
+        return $connection->getConnectionResource();
608
+    }
609
+
610
+    /**
611
+     * create new user
612
+     * @param string $username username of the new user
613
+     * @param string $password password of the new user
614
+     * @return bool was the user created?
615
+     */
616
+    public function createUser($username, $password) {
617
+        if ($this->userPluginManager->implementsActions(Backend::CREATE_USER)) {
618
+            return $this->userPluginManager->createUser($username, $password);
619
+        }
620
+        return false;
621
+    }
622 622
 
623 623
 }
Please login to merge, or discard this patch.