Completed
Push — master ( 3d671c...42e805 )
by Blizzz
48:26 queued 33:21
created
apps/user_ldap/appinfo/register_command.php 1 patch
Indentation   +7 added lines, -7 removed lines patch added patch discarded remove patch
@@ -33,13 +33,13 @@  discard block
 block discarded – undo
33 33
 $helper = new Helper(\OC::$server->getConfig());
34 34
 $ocConfig = \OC::$server->getConfig();
35 35
 $uBackend = new User_Proxy(
36
-	$helper->getServerConfigurationPrefixes(true),
37
-	new LDAP(),
38
-	$ocConfig,
39
-	\OC::$server->getNotificationManager()
36
+    $helper->getServerConfigurationPrefixes(true),
37
+    new LDAP(),
38
+    $ocConfig,
39
+    \OC::$server->getNotificationManager()
40 40
 );
41 41
 $deletedUsersIndex = new DeletedUsersIndex(
42
-	$ocConfig, $dbConnection, $userMapping
42
+    $ocConfig, $dbConnection, $userMapping
43 43
 );
44 44
 
45 45
 $application->add(new OCA\User_LDAP\Command\ShowConfig($helper));
@@ -49,8 +49,8 @@  discard block
 block discarded – undo
49 49
 $application->add(new OCA\User_LDAP\Command\DeleteConfig($helper));
50 50
 $application->add(new OCA\User_LDAP\Command\Search($ocConfig));
51 51
 $application->add(new OCA\User_LDAP\Command\ShowRemnants(
52
-	$deletedUsersIndex, \OC::$server->getDateTimeFormatter())
52
+    $deletedUsersIndex, \OC::$server->getDateTimeFormatter())
53 53
 );
54 54
 $application->add(new OCA\User_LDAP\Command\CheckUser(
55
-	$uBackend, $helper, $deletedUsersIndex, $userMapping)
55
+    $uBackend, $helper, $deletedUsersIndex, $userMapping)
56 56
 );
Please login to merge, or discard this patch.
apps/user_ldap/lib/Proxy.php 2 patches
Indentation   +173 added lines, -173 removed lines patch added patch discarded remove patch
@@ -35,177 +35,177 @@
 block discarded – undo
35 35
 use OCA\User_LDAP\User\Manager;
36 36
 
37 37
 abstract class Proxy {
38
-	static private $accesses = array();
39
-	private $ldap = null;
40
-
41
-	/** @var \OCP\ICache|null */
42
-	private $cache;
43
-
44
-	/**
45
-	 * @param ILDAPWrapper $ldap
46
-	 */
47
-	public function __construct(ILDAPWrapper $ldap) {
48
-		$this->ldap = $ldap;
49
-		$memcache = \OC::$server->getMemCacheFactory();
50
-		if($memcache->isAvailable()) {
51
-			$this->cache = $memcache->create();
52
-		}
53
-	}
54
-
55
-	/**
56
-	 * @param string $configPrefix
57
-	 */
58
-	private function addAccess($configPrefix) {
59
-		static $ocConfig;
60
-		static $fs;
61
-		static $log;
62
-		static $avatarM;
63
-		static $userMap;
64
-		static $groupMap;
65
-		static $db;
66
-		static $coreUserManager;
67
-		static $coreNotificationManager;
68
-		if(is_null($fs)) {
69
-			$ocConfig = \OC::$server->getConfig();
70
-			$fs       = new FilesystemHelper();
71
-			$log      = new LogWrapper();
72
-			$avatarM  = \OC::$server->getAvatarManager();
73
-			$db       = \OC::$server->getDatabaseConnection();
74
-			$userMap  = new UserMapping($db);
75
-			$groupMap = new GroupMapping($db);
76
-			$coreUserManager = \OC::$server->getUserManager();
77
-			$coreNotificationManager = \OC::$server->getNotificationManager();
78
-		}
79
-		$userManager =
80
-			new Manager($ocConfig, $fs, $log, $avatarM, new \OCP\Image(), $db,
81
-				$coreUserManager, $coreNotificationManager);
82
-		$connector = new Connection($this->ldap, $configPrefix);
83
-		$access = new Access($connector, $this->ldap, $userManager, new Helper(\OC::$server->getConfig()));
84
-		$access->setUserMapper($userMap);
85
-		$access->setGroupMapper($groupMap);
86
-		self::$accesses[$configPrefix] = $access;
87
-	}
88
-
89
-	/**
90
-	 * @param string $configPrefix
91
-	 * @return mixed
92
-	 */
93
-	protected function getAccess($configPrefix) {
94
-		if(!isset(self::$accesses[$configPrefix])) {
95
-			$this->addAccess($configPrefix);
96
-		}
97
-		return self::$accesses[$configPrefix];
98
-	}
99
-
100
-	/**
101
-	 * @param string $uid
102
-	 * @return string
103
-	 */
104
-	protected function getUserCacheKey($uid) {
105
-		return 'user-'.$uid.'-lastSeenOn';
106
-	}
107
-
108
-	/**
109
-	 * @param string $gid
110
-	 * @return string
111
-	 */
112
-	protected function getGroupCacheKey($gid) {
113
-		return 'group-'.$gid.'-lastSeenOn';
114
-	}
115
-
116
-	/**
117
-	 * @param string $id
118
-	 * @param string $method
119
-	 * @param array $parameters
120
-	 * @param bool $passOnWhen
121
-	 * @return mixed
122
-	 */
123
-	abstract protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen);
124
-
125
-	/**
126
-	 * @param string $id
127
-	 * @param string $method
128
-	 * @param array $parameters
129
-	 * @return mixed
130
-	 */
131
-	abstract protected function walkBackends($id, $method, $parameters);
132
-
133
-	/**
134
-	 * @param string $id
135
-	 * @return Access
136
-	 */
137
-	abstract public function getLDAPAccess($id);
138
-
139
-	/**
140
-	 * Takes care of the request to the User backend
141
-	 * @param string $id
142
-	 * @param string $method string, the method of the user backend that shall be called
143
-	 * @param array $parameters an array of parameters to be passed
144
-	 * @param bool $passOnWhen
145
-	 * @return mixed, the result of the specified method
146
-	 */
147
-	protected function handleRequest($id, $method, $parameters, $passOnWhen = false) {
148
-		$result = $this->callOnLastSeenOn($id,  $method, $parameters, $passOnWhen);
149
-		if($result === $passOnWhen) {
150
-			$result = $this->walkBackends($id, $method, $parameters);
151
-		}
152
-		return $result;
153
-	}
154
-
155
-	/**
156
-	 * @param string|null $key
157
-	 * @return string
158
-	 */
159
-	private function getCacheKey($key) {
160
-		$prefix = 'LDAP-Proxy-';
161
-		if(is_null($key)) {
162
-			return $prefix;
163
-		}
164
-		return $prefix.md5($key);
165
-	}
166
-
167
-	/**
168
-	 * @param string $key
169
-	 * @return mixed|null
170
-	 */
171
-	public function getFromCache($key) {
172
-		if(is_null($this->cache) || !$this->isCached($key)) {
173
-			return null;
174
-		}
175
-		$key = $this->getCacheKey($key);
176
-
177
-		return json_decode(base64_decode($this->cache->get($key)));
178
-	}
179
-
180
-	/**
181
-	 * @param string $key
182
-	 * @return bool
183
-	 */
184
-	public function isCached($key) {
185
-		if(is_null($this->cache)) {
186
-			return false;
187
-		}
188
-		$key = $this->getCacheKey($key);
189
-		return $this->cache->hasKey($key);
190
-	}
191
-
192
-	/**
193
-	 * @param string $key
194
-	 * @param mixed $value
195
-	 */
196
-	public function writeToCache($key, $value) {
197
-		if(is_null($this->cache)) {
198
-			return;
199
-		}
200
-		$key   = $this->getCacheKey($key);
201
-		$value = base64_encode(json_encode($value));
202
-		$this->cache->set($key, $value, '2592000');
203
-	}
204
-
205
-	public function clearCache() {
206
-		if(is_null($this->cache)) {
207
-			return;
208
-		}
209
-		$this->cache->clear($this->getCacheKey(null));
210
-	}
38
+    static private $accesses = array();
39
+    private $ldap = null;
40
+
41
+    /** @var \OCP\ICache|null */
42
+    private $cache;
43
+
44
+    /**
45
+     * @param ILDAPWrapper $ldap
46
+     */
47
+    public function __construct(ILDAPWrapper $ldap) {
48
+        $this->ldap = $ldap;
49
+        $memcache = \OC::$server->getMemCacheFactory();
50
+        if($memcache->isAvailable()) {
51
+            $this->cache = $memcache->create();
52
+        }
53
+    }
54
+
55
+    /**
56
+     * @param string $configPrefix
57
+     */
58
+    private function addAccess($configPrefix) {
59
+        static $ocConfig;
60
+        static $fs;
61
+        static $log;
62
+        static $avatarM;
63
+        static $userMap;
64
+        static $groupMap;
65
+        static $db;
66
+        static $coreUserManager;
67
+        static $coreNotificationManager;
68
+        if(is_null($fs)) {
69
+            $ocConfig = \OC::$server->getConfig();
70
+            $fs       = new FilesystemHelper();
71
+            $log      = new LogWrapper();
72
+            $avatarM  = \OC::$server->getAvatarManager();
73
+            $db       = \OC::$server->getDatabaseConnection();
74
+            $userMap  = new UserMapping($db);
75
+            $groupMap = new GroupMapping($db);
76
+            $coreUserManager = \OC::$server->getUserManager();
77
+            $coreNotificationManager = \OC::$server->getNotificationManager();
78
+        }
79
+        $userManager =
80
+            new Manager($ocConfig, $fs, $log, $avatarM, new \OCP\Image(), $db,
81
+                $coreUserManager, $coreNotificationManager);
82
+        $connector = new Connection($this->ldap, $configPrefix);
83
+        $access = new Access($connector, $this->ldap, $userManager, new Helper(\OC::$server->getConfig()));
84
+        $access->setUserMapper($userMap);
85
+        $access->setGroupMapper($groupMap);
86
+        self::$accesses[$configPrefix] = $access;
87
+    }
88
+
89
+    /**
90
+     * @param string $configPrefix
91
+     * @return mixed
92
+     */
93
+    protected function getAccess($configPrefix) {
94
+        if(!isset(self::$accesses[$configPrefix])) {
95
+            $this->addAccess($configPrefix);
96
+        }
97
+        return self::$accesses[$configPrefix];
98
+    }
99
+
100
+    /**
101
+     * @param string $uid
102
+     * @return string
103
+     */
104
+    protected function getUserCacheKey($uid) {
105
+        return 'user-'.$uid.'-lastSeenOn';
106
+    }
107
+
108
+    /**
109
+     * @param string $gid
110
+     * @return string
111
+     */
112
+    protected function getGroupCacheKey($gid) {
113
+        return 'group-'.$gid.'-lastSeenOn';
114
+    }
115
+
116
+    /**
117
+     * @param string $id
118
+     * @param string $method
119
+     * @param array $parameters
120
+     * @param bool $passOnWhen
121
+     * @return mixed
122
+     */
123
+    abstract protected function callOnLastSeenOn($id, $method, $parameters, $passOnWhen);
124
+
125
+    /**
126
+     * @param string $id
127
+     * @param string $method
128
+     * @param array $parameters
129
+     * @return mixed
130
+     */
131
+    abstract protected function walkBackends($id, $method, $parameters);
132
+
133
+    /**
134
+     * @param string $id
135
+     * @return Access
136
+     */
137
+    abstract public function getLDAPAccess($id);
138
+
139
+    /**
140
+     * Takes care of the request to the User backend
141
+     * @param string $id
142
+     * @param string $method string, the method of the user backend that shall be called
143
+     * @param array $parameters an array of parameters to be passed
144
+     * @param bool $passOnWhen
145
+     * @return mixed, the result of the specified method
146
+     */
147
+    protected function handleRequest($id, $method, $parameters, $passOnWhen = false) {
148
+        $result = $this->callOnLastSeenOn($id,  $method, $parameters, $passOnWhen);
149
+        if($result === $passOnWhen) {
150
+            $result = $this->walkBackends($id, $method, $parameters);
151
+        }
152
+        return $result;
153
+    }
154
+
155
+    /**
156
+     * @param string|null $key
157
+     * @return string
158
+     */
159
+    private function getCacheKey($key) {
160
+        $prefix = 'LDAP-Proxy-';
161
+        if(is_null($key)) {
162
+            return $prefix;
163
+        }
164
+        return $prefix.md5($key);
165
+    }
166
+
167
+    /**
168
+     * @param string $key
169
+     * @return mixed|null
170
+     */
171
+    public function getFromCache($key) {
172
+        if(is_null($this->cache) || !$this->isCached($key)) {
173
+            return null;
174
+        }
175
+        $key = $this->getCacheKey($key);
176
+
177
+        return json_decode(base64_decode($this->cache->get($key)));
178
+    }
179
+
180
+    /**
181
+     * @param string $key
182
+     * @return bool
183
+     */
184
+    public function isCached($key) {
185
+        if(is_null($this->cache)) {
186
+            return false;
187
+        }
188
+        $key = $this->getCacheKey($key);
189
+        return $this->cache->hasKey($key);
190
+    }
191
+
192
+    /**
193
+     * @param string $key
194
+     * @param mixed $value
195
+     */
196
+    public function writeToCache($key, $value) {
197
+        if(is_null($this->cache)) {
198
+            return;
199
+        }
200
+        $key   = $this->getCacheKey($key);
201
+        $value = base64_encode(json_encode($value));
202
+        $this->cache->set($key, $value, '2592000');
203
+    }
204
+
205
+    public function clearCache() {
206
+        if(is_null($this->cache)) {
207
+            return;
208
+        }
209
+        $this->cache->clear($this->getCacheKey(null));
210
+    }
211 211
 }
Please login to merge, or discard this patch.
Spacing   +10 added lines, -10 removed lines patch added patch discarded remove patch
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
 	public function __construct(ILDAPWrapper $ldap) {
48 48
 		$this->ldap = $ldap;
49 49
 		$memcache = \OC::$server->getMemCacheFactory();
50
-		if($memcache->isAvailable()) {
50
+		if ($memcache->isAvailable()) {
51 51
 			$this->cache = $memcache->create();
52 52
 		}
53 53
 	}
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
 		static $db;
66 66
 		static $coreUserManager;
67 67
 		static $coreNotificationManager;
68
-		if(is_null($fs)) {
68
+		if (is_null($fs)) {
69 69
 			$ocConfig = \OC::$server->getConfig();
70 70
 			$fs       = new FilesystemHelper();
71 71
 			$log      = new LogWrapper();
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
 	 * @return mixed
92 92
 	 */
93 93
 	protected function getAccess($configPrefix) {
94
-		if(!isset(self::$accesses[$configPrefix])) {
94
+		if (!isset(self::$accesses[$configPrefix])) {
95 95
 			$this->addAccess($configPrefix);
96 96
 		}
97 97
 		return self::$accesses[$configPrefix];
@@ -145,8 +145,8 @@  discard block
 block discarded – undo
145 145
 	 * @return mixed, the result of the specified method
146 146
 	 */
147 147
 	protected function handleRequest($id, $method, $parameters, $passOnWhen = false) {
148
-		$result = $this->callOnLastSeenOn($id,  $method, $parameters, $passOnWhen);
149
-		if($result === $passOnWhen) {
148
+		$result = $this->callOnLastSeenOn($id, $method, $parameters, $passOnWhen);
149
+		if ($result === $passOnWhen) {
150 150
 			$result = $this->walkBackends($id, $method, $parameters);
151 151
 		}
152 152
 		return $result;
@@ -158,7 +158,7 @@  discard block
 block discarded – undo
158 158
 	 */
159 159
 	private function getCacheKey($key) {
160 160
 		$prefix = 'LDAP-Proxy-';
161
-		if(is_null($key)) {
161
+		if (is_null($key)) {
162 162
 			return $prefix;
163 163
 		}
164 164
 		return $prefix.md5($key);
@@ -169,7 +169,7 @@  discard block
 block discarded – undo
169 169
 	 * @return mixed|null
170 170
 	 */
171 171
 	public function getFromCache($key) {
172
-		if(is_null($this->cache) || !$this->isCached($key)) {
172
+		if (is_null($this->cache) || !$this->isCached($key)) {
173 173
 			return null;
174 174
 		}
175 175
 		$key = $this->getCacheKey($key);
@@ -182,7 +182,7 @@  discard block
 block discarded – undo
182 182
 	 * @return bool
183 183
 	 */
184 184
 	public function isCached($key) {
185
-		if(is_null($this->cache)) {
185
+		if (is_null($this->cache)) {
186 186
 			return false;
187 187
 		}
188 188
 		$key = $this->getCacheKey($key);
@@ -194,7 +194,7 @@  discard block
 block discarded – undo
194 194
 	 * @param mixed $value
195 195
 	 */
196 196
 	public function writeToCache($key, $value) {
197
-		if(is_null($this->cache)) {
197
+		if (is_null($this->cache)) {
198 198
 			return;
199 199
 		}
200 200
 		$key   = $this->getCacheKey($key);
@@ -203,7 +203,7 @@  discard block
 block discarded – undo
203 203
 	}
204 204
 
205 205
 	public function clearCache() {
206
-		if(is_null($this->cache)) {
206
+		if (is_null($this->cache)) {
207 207
 			return;
208 208
 		}
209 209
 		$this->cache->clear($this->getCacheKey(null));
Please login to merge, or discard this patch.
apps/user_ldap/lib/Migration/UUIDFixGroup.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -30,9 +30,9 @@
 block discarded – undo
30 30
 use OCP\IConfig;
31 31
 
32 32
 class UUIDFixGroup extends UUIDFix {
33
-	public function __construct(GroupMapping $mapper, LDAP $ldap, IConfig $config, Helper $helper) {
34
-		$this->mapper = $mapper;
35
-		$this->proxy = new User_Proxy($helper->getServerConfigurationPrefixes(true), $ldap, $config, 
36
-			\OC::$server->getNotificationManager());
37
-	}
33
+    public function __construct(GroupMapping $mapper, LDAP $ldap, IConfig $config, Helper $helper) {
34
+        $this->mapper = $mapper;
35
+        $this->proxy = new User_Proxy($helper->getServerConfigurationPrefixes(true), $ldap, $config, 
36
+            \OC::$server->getNotificationManager());
37
+    }
38 38
 }
Please login to merge, or discard this patch.
apps/user_ldap/appinfo/app.php 2 patches
Indentation   +38 added lines, -38 removed lines patch added patch discarded remove patch
@@ -33,56 +33,56 @@
 block discarded – undo
33 33
 $ocConfig = \OC::$server->getConfig();
34 34
 $notificationManager = \OC::$server->getNotificationManager();
35 35
 $notificationManager->registerNotifier(function() {
36
-	return new \OCA\User_LDAP\Notification\Notifier(
37
-	  \OC::$server->getL10NFactory()
38
-	);
36
+    return new \OCA\User_LDAP\Notification\Notifier(
37
+        \OC::$server->getL10NFactory()
38
+    );
39 39
 }, function() {
40
-		$l = \OC::$server->getL10N('user_ldap');
41
-		return [
42
-			'id' => 'user_ldap',
43
-			'name' => $l->t('LDAP user and group backend'),
44
-		];
40
+        $l = \OC::$server->getL10N('user_ldap');
41
+        return [
42
+            'id' => 'user_ldap',
43
+            'name' => $l->t('LDAP user and group backend'),
44
+        ];
45 45
 });
46 46
 if(count($configPrefixes) === 1) {
47
-	$dbc = \OC::$server->getDatabaseConnection();
48
-	$userManager = new OCA\User_LDAP\User\Manager($ocConfig,
49
-		new OCA\User_LDAP\FilesystemHelper(),
50
-		new OCA\User_LDAP\LogWrapper(),
51
-		\OC::$server->getAvatarManager(),
52
-		new \OCP\Image(),
53
-		$dbc,
54
-		\OC::$server->getUserManager(),
55
-		$notificationManager
56
-	);
57
-	$connector = new OCA\User_LDAP\Connection($ldapWrapper, $configPrefixes[0]);
58
-	$ldapAccess = new OCA\User_LDAP\Access($connector, $ldapWrapper, $userManager, $helper);
47
+    $dbc = \OC::$server->getDatabaseConnection();
48
+    $userManager = new OCA\User_LDAP\User\Manager($ocConfig,
49
+        new OCA\User_LDAP\FilesystemHelper(),
50
+        new OCA\User_LDAP\LogWrapper(),
51
+        \OC::$server->getAvatarManager(),
52
+        new \OCP\Image(),
53
+        $dbc,
54
+        \OC::$server->getUserManager(),
55
+        $notificationManager
56
+    );
57
+    $connector = new OCA\User_LDAP\Connection($ldapWrapper, $configPrefixes[0]);
58
+    $ldapAccess = new OCA\User_LDAP\Access($connector, $ldapWrapper, $userManager, $helper);
59 59
 
60
-	$ldapAccess->setUserMapper(new OCA\User_LDAP\Mapping\UserMapping($dbc));
61
-	$ldapAccess->setGroupMapper(new OCA\User_LDAP\Mapping\GroupMapping($dbc));
62
-	$userBackend  = new OCA\User_LDAP\User_LDAP($ldapAccess, $ocConfig, $notificationManager);
63
-	$groupBackend = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
60
+    $ldapAccess->setUserMapper(new OCA\User_LDAP\Mapping\UserMapping($dbc));
61
+    $ldapAccess->setGroupMapper(new OCA\User_LDAP\Mapping\GroupMapping($dbc));
62
+    $userBackend  = new OCA\User_LDAP\User_LDAP($ldapAccess, $ocConfig, $notificationManager);
63
+    $groupBackend = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
64 64
 } else if(count($configPrefixes) > 1) {
65
-	$userBackend  = new OCA\User_LDAP\User_Proxy(
66
-		$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager
67
-	);
68
-	$groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
65
+    $userBackend  = new OCA\User_LDAP\User_Proxy(
66
+        $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager
67
+    );
68
+    $groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
69 69
 }
70 70
 
71 71
 if(count($configPrefixes) > 0) {
72
-	// register user backend
73
-	OC_User::useBackend($userBackend);
74
-	\OC::$server->getGroupManager()->addBackend($groupBackend);
72
+    // register user backend
73
+    OC_User::useBackend($userBackend);
74
+    \OC::$server->getGroupManager()->addBackend($groupBackend);
75 75
 }
76 76
 
77 77
 \OCP\Util::connectHook(
78
-	'\OCA\Files_Sharing\API\Server2Server',
79
-	'preLoginNameUsedAsUserName',
80
-	'\OCA\User_LDAP\Helper',
81
-	'loginName2UserName'
78
+    '\OCA\Files_Sharing\API\Server2Server',
79
+    'preLoginNameUsedAsUserName',
80
+    '\OCA\User_LDAP\Helper',
81
+    'loginName2UserName'
82 82
 );
83 83
 
84 84
 if(OCP\App::isEnabled('user_webdavauth')) {
85
-	OCP\Util::writeLog('user_ldap',
86
-		'user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour',
87
-		OCP\Util::WARN);
85
+    OCP\Util::writeLog('user_ldap',
86
+        'user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour',
87
+        OCP\Util::WARN);
88 88
 }
Please login to merge, or discard this patch.
Spacing   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 			'name' => $l->t('LDAP user and group backend'),
44 44
 		];
45 45
 });
46
-if(count($configPrefixes) === 1) {
46
+if (count($configPrefixes) === 1) {
47 47
 	$dbc = \OC::$server->getDatabaseConnection();
48 48
 	$userManager = new OCA\User_LDAP\User\Manager($ocConfig,
49 49
 		new OCA\User_LDAP\FilesystemHelper(),
@@ -61,14 +61,14 @@  discard block
 block discarded – undo
61 61
 	$ldapAccess->setGroupMapper(new OCA\User_LDAP\Mapping\GroupMapping($dbc));
62 62
 	$userBackend  = new OCA\User_LDAP\User_LDAP($ldapAccess, $ocConfig, $notificationManager);
63 63
 	$groupBackend = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
64
-} else if(count($configPrefixes) > 1) {
64
+} else if (count($configPrefixes) > 1) {
65 65
 	$userBackend  = new OCA\User_LDAP\User_Proxy(
66 66
 		$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager
67 67
 	);
68
-	$groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
68
+	$groupBackend = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
69 69
 }
70 70
 
71
-if(count($configPrefixes) > 0) {
71
+if (count($configPrefixes) > 0) {
72 72
 	// register user backend
73 73
 	OC_User::useBackend($userBackend);
74 74
 	\OC::$server->getGroupManager()->addBackend($groupBackend);
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
 	'loginName2UserName'
82 82
 );
83 83
 
84
-if(OCP\App::isEnabled('user_webdavauth')) {
84
+if (OCP\App::isEnabled('user_webdavauth')) {
85 85
 	OCP\Util::writeLog('user_ldap',
86 86
 		'user_ldap and user_webdavauth are incompatible. You may experience unexpected behaviour',
87 87
 		OCP\Util::WARN);
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/Search.php 1 patch
Indentation   +87 added lines, -87 removed lines patch added patch discarded remove patch
@@ -37,98 +37,98 @@
 block discarded – undo
37 37
 use OCP\IConfig;
38 38
 
39 39
 class Search extends Command {
40
-	/** @var \OCP\IConfig */
41
-	protected $ocConfig;
40
+    /** @var \OCP\IConfig */
41
+    protected $ocConfig;
42 42
 
43
-	/**
44
-	 * @param \OCP\IConfig $ocConfig
45
-	 */
46
-	public function __construct(IConfig $ocConfig) {
47
-		$this->ocConfig = $ocConfig;
48
-		parent::__construct();
49
-	}
43
+    /**
44
+     * @param \OCP\IConfig $ocConfig
45
+     */
46
+    public function __construct(IConfig $ocConfig) {
47
+        $this->ocConfig = $ocConfig;
48
+        parent::__construct();
49
+    }
50 50
 
51
-	protected function configure() {
52
-		$this
53
-			->setName('ldap:search')
54
-			->setDescription('executes a user or group search')
55
-			->addArgument(
56
-					'search',
57
-					InputArgument::REQUIRED,
58
-					'the search string (can be empty)'
59
-				     )
60
-			->addOption(
61
-					'group',
62
-					null,
63
-					InputOption::VALUE_NONE,
64
-					'searches groups instead of users'
65
-				     )
66
-			->addOption(
67
-					'offset',
68
-					null,
69
-					InputOption::VALUE_REQUIRED,
70
-					'The offset of the result set. Needs to be a multiple of limit. defaults to 0.',
71
-					0
72
-				     )
73
-			->addOption(
74
-					'limit',
75
-					null,
76
-					InputOption::VALUE_REQUIRED,
77
-					'limit the results. 0 means no limit, defaults to 15',
78
-					15
79
-				     )
80
-		;
81
-	}
51
+    protected function configure() {
52
+        $this
53
+            ->setName('ldap:search')
54
+            ->setDescription('executes a user or group search')
55
+            ->addArgument(
56
+                    'search',
57
+                    InputArgument::REQUIRED,
58
+                    'the search string (can be empty)'
59
+                        )
60
+            ->addOption(
61
+                    'group',
62
+                    null,
63
+                    InputOption::VALUE_NONE,
64
+                    'searches groups instead of users'
65
+                        )
66
+            ->addOption(
67
+                    'offset',
68
+                    null,
69
+                    InputOption::VALUE_REQUIRED,
70
+                    'The offset of the result set. Needs to be a multiple of limit. defaults to 0.',
71
+                    0
72
+                        )
73
+            ->addOption(
74
+                    'limit',
75
+                    null,
76
+                    InputOption::VALUE_REQUIRED,
77
+                    'limit the results. 0 means no limit, defaults to 15',
78
+                    15
79
+                        )
80
+        ;
81
+    }
82 82
 
83
-	/**
84
-	 * Tests whether the offset and limit options are valid
85
-	 * @param int $offset
86
-	 * @param int $limit
87
-	 * @throws \InvalidArgumentException
88
-	 */
89
-	protected function validateOffsetAndLimit($offset, $limit) {
90
-		if($limit < 0) {
91
-			throw new \InvalidArgumentException('limit must be  0 or greater');
92
-		}
93
-		if($offset  < 0) {
94
-			throw new \InvalidArgumentException('offset must be 0 or greater');
95
-		}
96
-		if($limit === 0 && $offset !== 0) {
97
-			throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0');
98
-		}
99
-		if($offset > 0 && ($offset % $limit !== 0)) {
100
-			throw new \InvalidArgumentException('offset must be a multiple of limit');
101
-		}
102
-	}
83
+    /**
84
+     * Tests whether the offset and limit options are valid
85
+     * @param int $offset
86
+     * @param int $limit
87
+     * @throws \InvalidArgumentException
88
+     */
89
+    protected function validateOffsetAndLimit($offset, $limit) {
90
+        if($limit < 0) {
91
+            throw new \InvalidArgumentException('limit must be  0 or greater');
92
+        }
93
+        if($offset  < 0) {
94
+            throw new \InvalidArgumentException('offset must be 0 or greater');
95
+        }
96
+        if($limit === 0 && $offset !== 0) {
97
+            throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0');
98
+        }
99
+        if($offset > 0 && ($offset % $limit !== 0)) {
100
+            throw new \InvalidArgumentException('offset must be a multiple of limit');
101
+        }
102
+    }
103 103
 
104
-	protected function execute(InputInterface $input, OutputInterface $output) {
105
-		$helper = new Helper($this->ocConfig);
106
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
107
-		$ldapWrapper = new LDAP();
104
+    protected function execute(InputInterface $input, OutputInterface $output) {
105
+        $helper = new Helper($this->ocConfig);
106
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
107
+        $ldapWrapper = new LDAP();
108 108
 
109
-		$offset = intval($input->getOption('offset'));
110
-		$limit = intval($input->getOption('limit'));
111
-		$this->validateOffsetAndLimit($offset, $limit);
109
+        $offset = intval($input->getOption('offset'));
110
+        $limit = intval($input->getOption('limit'));
111
+        $this->validateOffsetAndLimit($offset, $limit);
112 112
 
113
-		if($input->getOption('group')) {
114
-			$proxy = new Group_Proxy($configPrefixes, $ldapWrapper);
115
-			$getMethod = 'getGroups';
116
-			$printID = false;
117
-			// convert the limit of groups to null. This will show all the groups available instead of
118
-			// nothing, and will match the same behaviour the search for users has.
119
-			if ($limit === 0) {
120
-				$limit = null;
121
-			}
122
-		} else {
123
-			$proxy = new User_Proxy($configPrefixes, $ldapWrapper, $this->ocConfig, \OC::$server->getNotificationManager());
124
-			$getMethod = 'getDisplayNames';
125
-			$printID = true;
126
-		}
113
+        if($input->getOption('group')) {
114
+            $proxy = new Group_Proxy($configPrefixes, $ldapWrapper);
115
+            $getMethod = 'getGroups';
116
+            $printID = false;
117
+            // convert the limit of groups to null. This will show all the groups available instead of
118
+            // nothing, and will match the same behaviour the search for users has.
119
+            if ($limit === 0) {
120
+                $limit = null;
121
+            }
122
+        } else {
123
+            $proxy = new User_Proxy($configPrefixes, $ldapWrapper, $this->ocConfig, \OC::$server->getNotificationManager());
124
+            $getMethod = 'getDisplayNames';
125
+            $printID = true;
126
+        }
127 127
 
128
-		$result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset);
129
-		foreach($result as $id => $name) {
130
-			$line = $name . ($printID ? ' ('.$id.')' : '');
131
-			$output->writeln($line);
132
-		}
133
-	}
128
+        $result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset);
129
+        foreach($result as $id => $name) {
130
+            $line = $name . ($printID ? ' ('.$id.')' : '');
131
+            $output->writeln($line);
132
+        }
133
+    }
134 134
 }
Please login to merge, or discard this patch.
apps/user_ldap/templates/settings.php 1 patch
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -59,73 +59,73 @@
 block discarded – undo
59 59
 
60 60
 	<div id="ldapSettings">
61 61
 	<ul>
62
-		<li id="#ldapWizard1"><a href="#ldapWizard1"><?php p($l->t('Server'));?></a></li>
63
-		<li id="#ldapWizard2"><a href="#ldapWizard2"><?php p($l->t('Users'));?></a></li>
64
-		<li id="#ldapWizard3"><a href="#ldapWizard3"><?php p($l->t('Login Attributes'));?></a></li>
65
-		<li id="#ldapWizard4"><a href="#ldapWizard4"><?php p($l->t('Groups'));?></a></li>
66
-		<li class="ldapSettingsTabs"><a href="#ldapSettings-2"><?php p($l->t('Expert'));?></a></li>
67
-		<li class="ldapSettingsTabs"><a href="#ldapSettings-1"><?php p($l->t('Advanced'));?></a></li>
62
+		<li id="#ldapWizard1"><a href="#ldapWizard1"><?php p($l->t('Server')); ?></a></li>
63
+		<li id="#ldapWizard2"><a href="#ldapWizard2"><?php p($l->t('Users')); ?></a></li>
64
+		<li id="#ldapWizard3"><a href="#ldapWizard3"><?php p($l->t('Login Attributes')); ?></a></li>
65
+		<li id="#ldapWizard4"><a href="#ldapWizard4"><?php p($l->t('Groups')); ?></a></li>
66
+		<li class="ldapSettingsTabs"><a href="#ldapSettings-2"><?php p($l->t('Expert')); ?></a></li>
67
+		<li class="ldapSettingsTabs"><a href="#ldapSettings-1"><?php p($l->t('Advanced')); ?></a></li>
68 68
 	</ul>
69
-	<?php if(OCP\App::isEnabled('user_webdavauth')) {
69
+	<?php if (OCP\App::isEnabled('user_webdavauth')) {
70 70
 		print_unescaped('<p class="ldapwarning">'.$l->t('<b>Warning:</b> Apps user_ldap and user_webdavauth are incompatible. You may experience unexpected behavior. Please ask your system administrator to disable one of them.').'</p>');
71 71
 	}
72
-	if(!function_exists('ldap_connect')) {
72
+	if (!function_exists('ldap_connect')) {
73 73
 		print_unescaped('<p class="ldapwarning">'.$l->t('<b>Warning:</b> The PHP LDAP module is not installed, the backend will not work. Please ask your system administrator to install it.').'</p>');
74 74
 	}
75 75
 	?>
76
-	<?php require_once(__DIR__ . '/part.wizard-server.php'); ?>
77
-	<?php require_once(__DIR__ . '/part.wizard-userfilter.php'); ?>
78
-	<?php require_once(__DIR__ . '/part.wizard-loginfilter.php'); ?>
79
-	<?php require_once(__DIR__ . '/part.wizard-groupfilter.php'); ?>
76
+	<?php require_once(__DIR__.'/part.wizard-server.php'); ?>
77
+	<?php require_once(__DIR__.'/part.wizard-userfilter.php'); ?>
78
+	<?php require_once(__DIR__.'/part.wizard-loginfilter.php'); ?>
79
+	<?php require_once(__DIR__.'/part.wizard-groupfilter.php'); ?>
80 80
 	<fieldset id="ldapSettings-1">
81 81
 		<div id="ldapAdvancedAccordion">
82
-			<h3><?php p($l->t('Connection Settings'));?></h3>
82
+			<h3><?php p($l->t('Connection Settings')); ?></h3>
83 83
 			<div>
84
-				<p><label for="ldap_configuration_active"><?php p($l->t('Configuration Active'));?></label><input type="checkbox" id="ldap_configuration_active" name="ldap_configuration_active" value="1" data-default="<?php p($_['ldap_configuration_active_default']); ?>"  title="<?php p($l->t('When unchecked, this configuration will be skipped.'));?>" /></p>
85
-				<p><label for="ldap_backup_host"><?php p($l->t('Backup (Replica) Host'));?></label><input type="text" id="ldap_backup_host" name="ldap_backup_host" data-default="<?php p($_['ldap_backup_host_default']); ?>" title="<?php p($l->t('Give an optional backup host. It must be a replica of the main LDAP/AD server.'));?>"></p>
86
-				<p><label for="ldap_backup_port"><?php p($l->t('Backup (Replica) Port'));?></label><input type="number" id="ldap_backup_port" name="ldap_backup_port" data-default="<?php p($_['ldap_backup_port_default']); ?>"  /></p>
87
-				<p><label for="ldap_override_main_server"><?php p($l->t('Disable Main Server'));?></label><input type="checkbox" id="ldap_override_main_server" name="ldap_override_main_server" value="1" data-default="<?php p($_['ldap_override_main_server_default']); ?>"  title="<?php p($l->t('Only connect to the replica server.'));?>" /></p>
88
-				<p><label for="ldap_turn_off_cert_check"><?php p($l->t('Turn off SSL certificate validation.'));?></label><input type="checkbox" id="ldap_turn_off_cert_check" name="ldap_turn_off_cert_check" title="<?php p($l->t('Not recommended, use it for testing only! If connection only works with this option, import the LDAP server\'s SSL certificate in your %s server.', $theme->getName() ));?>" data-default="<?php p($_['ldap_turn_off_cert_check_default']); ?>" value="1"><br/></p>
89
-				<p><label for="ldap_cache_ttl"><?php p($l->t('Cache Time-To-Live'));?></label><input type="number" id="ldap_cache_ttl" name="ldap_cache_ttl" title="<?php p($l->t('in seconds. A change empties the cache.'));?>" data-default="<?php p($_['ldap_cache_ttl_default']); ?>" /></p>
84
+				<p><label for="ldap_configuration_active"><?php p($l->t('Configuration Active')); ?></label><input type="checkbox" id="ldap_configuration_active" name="ldap_configuration_active" value="1" data-default="<?php p($_['ldap_configuration_active_default']); ?>"  title="<?php p($l->t('When unchecked, this configuration will be skipped.')); ?>" /></p>
85
+				<p><label for="ldap_backup_host"><?php p($l->t('Backup (Replica) Host')); ?></label><input type="text" id="ldap_backup_host" name="ldap_backup_host" data-default="<?php p($_['ldap_backup_host_default']); ?>" title="<?php p($l->t('Give an optional backup host. It must be a replica of the main LDAP/AD server.')); ?>"></p>
86
+				<p><label for="ldap_backup_port"><?php p($l->t('Backup (Replica) Port')); ?></label><input type="number" id="ldap_backup_port" name="ldap_backup_port" data-default="<?php p($_['ldap_backup_port_default']); ?>"  /></p>
87
+				<p><label for="ldap_override_main_server"><?php p($l->t('Disable Main Server')); ?></label><input type="checkbox" id="ldap_override_main_server" name="ldap_override_main_server" value="1" data-default="<?php p($_['ldap_override_main_server_default']); ?>"  title="<?php p($l->t('Only connect to the replica server.')); ?>" /></p>
88
+				<p><label for="ldap_turn_off_cert_check"><?php p($l->t('Turn off SSL certificate validation.')); ?></label><input type="checkbox" id="ldap_turn_off_cert_check" name="ldap_turn_off_cert_check" title="<?php p($l->t('Not recommended, use it for testing only! If connection only works with this option, import the LDAP server\'s SSL certificate in your %s server.', $theme->getName())); ?>" data-default="<?php p($_['ldap_turn_off_cert_check_default']); ?>" value="1"><br/></p>
89
+				<p><label for="ldap_cache_ttl"><?php p($l->t('Cache Time-To-Live')); ?></label><input type="number" id="ldap_cache_ttl" name="ldap_cache_ttl" title="<?php p($l->t('in seconds. A change empties the cache.')); ?>" data-default="<?php p($_['ldap_cache_ttl_default']); ?>" /></p>
90 90
 			</div>
91
-			<h3><?php p($l->t('Directory Settings'));?></h3>
91
+			<h3><?php p($l->t('Directory Settings')); ?></h3>
92 92
 			<div>
93
-				<p><label for="ldap_display_name"><?php p($l->t('User Display Name Field'));?></label><input type="text" id="ldap_display_name" name="ldap_display_name" data-default="<?php p($_['ldap_display_name_default']); ?>" title="<?php p($l->t('The LDAP attribute to use to generate the user\'s display name.'));?>" /></p>
94
-				<p><label for="ldap_user_display_name_2"><?php p($l->t('2nd User Display Name Field'));?></label><input type="text" id="ldap_user_display_name_2" name="ldap_user_display_name_2" data-default="<?php p($_['ldap_user_display_name_2_default']); ?>" title="<?php p($l->t('Optional. An LDAP attribute to be added to the display name in brackets. Results in e.g. »John Doe ([email protected])«.'));?>" /></p>
95
-				<p><label for="ldap_base_users"><?php p($l->t('Base User Tree'));?></label><textarea id="ldap_base_users" name="ldap_base_users" placeholder="<?php p($l->t('One User Base DN per line'));?>" data-default="<?php p($_['ldap_base_users_default']); ?>" title="<?php p($l->t('Base User Tree'));?>"></textarea></p>
96
-				<p><label for="ldap_attributes_for_user_search"><?php p($l->t('User Search Attributes'));?></label><textarea id="ldap_attributes_for_user_search" name="ldap_attributes_for_user_search" placeholder="<?php p($l->t('Optional; one attribute per line'));?>" data-default="<?php p($_['ldap_attributes_for_user_search_default']); ?>" title="<?php p($l->t('User Search Attributes'));?>"></textarea></p>
97
-				<p><label for="ldap_group_display_name"><?php p($l->t('Group Display Name Field'));?></label><input type="text" id="ldap_group_display_name" name="ldap_group_display_name" data-default="<?php p($_['ldap_group_display_name_default']); ?>" title="<?php p($l->t('The LDAP attribute to use to generate the groups\'s display name.'));?>" /></p>
98
-				<p><label for="ldap_base_groups"><?php p($l->t('Base Group Tree'));?></label><textarea id="ldap_base_groups" name="ldap_base_groups" placeholder="<?php p($l->t('One Group Base DN per line'));?>" data-default="<?php p($_['ldap_base_groups_default']); ?>" title="<?php p($l->t('Base Group Tree'));?>"></textarea></p>
99
-				<p><label for="ldap_attributes_for_group_search"><?php p($l->t('Group Search Attributes'));?></label><textarea id="ldap_attributes_for_group_search" name="ldap_attributes_for_group_search" placeholder="<?php p($l->t('Optional; one attribute per line'));?>" data-default="<?php p($_['ldap_attributes_for_group_search_default']); ?>" title="<?php p($l->t('Group Search Attributes'));?>"></textarea></p>
100
-				<p><label for="ldap_group_member_assoc_attribute"><?php p($l->t('Group-Member association'));?></label><select id="ldap_group_member_assoc_attribute" name="ldap_group_member_assoc_attribute" data-default="<?php p($_['ldap_group_member_assoc_attribute_default']); ?>" ><option value="uniqueMember"<?php if (isset($_['ldap_group_member_assoc_attribute']) && ($_['ldap_group_member_assoc_attribute'] === 'uniqueMember')) p(' selected'); ?>>uniqueMember</option><option value="memberUid"<?php if (isset($_['ldap_group_member_assoc_attribute']) && ($_['ldap_group_member_assoc_attribute'] === 'memberUid')) p(' selected'); ?>>memberUid</option><option value="member"<?php if (isset($_['ldap_group_member_assoc_attribute']) && ($_['ldap_group_member_assoc_attribute'] === 'member')) p(' selected'); ?>>member (AD)</option></select></p>
101
-				<p><label for="ldap_dynamic_group_member_url"><?php p($l->t('Dynamic Group Member URL'));?></label><input type="text" id="ldap_dynamic_group_member_url" name="ldap_dynamic_group_member_url" title="<?php p($l->t('The LDAP attribute that on group objects contains an LDAP search URL that determines what objects belong to the group. (An empty setting disables dynamic group membership functionality.)'));?>" data-default="<?php p($_['ldap_dynamic_group_member_url_default']); ?>" /></p>
102
-				<p><label for="ldap_nested_groups"><?php p($l->t('Nested Groups'));?></label><input type="checkbox" id="ldap_nested_groups" name="ldap_nested_groups" value="1" data-default="<?php p($_['ldap_nested_groups_default']); ?>"  title="<?php p($l->t('When switched on, groups that contain groups are supported. (Only works if the group member attribute contains DNs.)'));?>" /></p>
103
-				<p><label for="ldap_paging_size"><?php p($l->t('Paging chunksize'));?></label><input type="number" id="ldap_paging_size" name="ldap_paging_size" title="<?php p($l->t('Chunksize used for paged LDAP searches that may return bulky results like user or group enumeration. (Setting it 0 disables paged LDAP searches in those situations.)'));?>" data-default="<?php p($_['ldap_paging_size_default']); ?>" /></p>
104
-				<p><label for="ldap_turn_on_pwd_change"><?php p($l->t('Enable LDAP password changes per user'));?></label><span class="inlinetable"><span class="tablerow left"><input type="checkbox" id="ldap_turn_on_pwd_change" name="ldap_turn_on_pwd_change" value="1" data-default="<?php p($_['ldap_turn_on_pwd_change_default']); ?>" title="<?php p($l->t('Allow LDAP users to change their password and allow Super Administrators and Group Administrators to change the password of their LDAP users. Only works when access control policies are configured accordingly on the LDAP server. As passwords are sent in plaintext to the LDAP server, transport encryption must be used and password hashing should be configured on the LDAP server.'));?>" /><span class="tablecell"><?php p($l->t('(New password is sent as plain text to LDAP)'));?></span></span>
93
+				<p><label for="ldap_display_name"><?php p($l->t('User Display Name Field')); ?></label><input type="text" id="ldap_display_name" name="ldap_display_name" data-default="<?php p($_['ldap_display_name_default']); ?>" title="<?php p($l->t('The LDAP attribute to use to generate the user\'s display name.')); ?>" /></p>
94
+				<p><label for="ldap_user_display_name_2"><?php p($l->t('2nd User Display Name Field')); ?></label><input type="text" id="ldap_user_display_name_2" name="ldap_user_display_name_2" data-default="<?php p($_['ldap_user_display_name_2_default']); ?>" title="<?php p($l->t('Optional. An LDAP attribute to be added to the display name in brackets. Results in e.g. »John Doe ([email protected])«.')); ?>" /></p>
95
+				<p><label for="ldap_base_users"><?php p($l->t('Base User Tree')); ?></label><textarea id="ldap_base_users" name="ldap_base_users" placeholder="<?php p($l->t('One User Base DN per line')); ?>" data-default="<?php p($_['ldap_base_users_default']); ?>" title="<?php p($l->t('Base User Tree')); ?>"></textarea></p>
96
+				<p><label for="ldap_attributes_for_user_search"><?php p($l->t('User Search Attributes')); ?></label><textarea id="ldap_attributes_for_user_search" name="ldap_attributes_for_user_search" placeholder="<?php p($l->t('Optional; one attribute per line')); ?>" data-default="<?php p($_['ldap_attributes_for_user_search_default']); ?>" title="<?php p($l->t('User Search Attributes')); ?>"></textarea></p>
97
+				<p><label for="ldap_group_display_name"><?php p($l->t('Group Display Name Field')); ?></label><input type="text" id="ldap_group_display_name" name="ldap_group_display_name" data-default="<?php p($_['ldap_group_display_name_default']); ?>" title="<?php p($l->t('The LDAP attribute to use to generate the groups\'s display name.')); ?>" /></p>
98
+				<p><label for="ldap_base_groups"><?php p($l->t('Base Group Tree')); ?></label><textarea id="ldap_base_groups" name="ldap_base_groups" placeholder="<?php p($l->t('One Group Base DN per line')); ?>" data-default="<?php p($_['ldap_base_groups_default']); ?>" title="<?php p($l->t('Base Group Tree')); ?>"></textarea></p>
99
+				<p><label for="ldap_attributes_for_group_search"><?php p($l->t('Group Search Attributes')); ?></label><textarea id="ldap_attributes_for_group_search" name="ldap_attributes_for_group_search" placeholder="<?php p($l->t('Optional; one attribute per line')); ?>" data-default="<?php p($_['ldap_attributes_for_group_search_default']); ?>" title="<?php p($l->t('Group Search Attributes')); ?>"></textarea></p>
100
+				<p><label for="ldap_group_member_assoc_attribute"><?php p($l->t('Group-Member association')); ?></label><select id="ldap_group_member_assoc_attribute" name="ldap_group_member_assoc_attribute" data-default="<?php p($_['ldap_group_member_assoc_attribute_default']); ?>" ><option value="uniqueMember"<?php if (isset($_['ldap_group_member_assoc_attribute']) && ($_['ldap_group_member_assoc_attribute'] === 'uniqueMember')) p(' selected'); ?>>uniqueMember</option><option value="memberUid"<?php if (isset($_['ldap_group_member_assoc_attribute']) && ($_['ldap_group_member_assoc_attribute'] === 'memberUid')) p(' selected'); ?>>memberUid</option><option value="member"<?php if (isset($_['ldap_group_member_assoc_attribute']) && ($_['ldap_group_member_assoc_attribute'] === 'member')) p(' selected'); ?>>member (AD)</option></select></p>
101
+				<p><label for="ldap_dynamic_group_member_url"><?php p($l->t('Dynamic Group Member URL')); ?></label><input type="text" id="ldap_dynamic_group_member_url" name="ldap_dynamic_group_member_url" title="<?php p($l->t('The LDAP attribute that on group objects contains an LDAP search URL that determines what objects belong to the group. (An empty setting disables dynamic group membership functionality.)')); ?>" data-default="<?php p($_['ldap_dynamic_group_member_url_default']); ?>" /></p>
102
+				<p><label for="ldap_nested_groups"><?php p($l->t('Nested Groups')); ?></label><input type="checkbox" id="ldap_nested_groups" name="ldap_nested_groups" value="1" data-default="<?php p($_['ldap_nested_groups_default']); ?>"  title="<?php p($l->t('When switched on, groups that contain groups are supported. (Only works if the group member attribute contains DNs.)')); ?>" /></p>
103
+				<p><label for="ldap_paging_size"><?php p($l->t('Paging chunksize')); ?></label><input type="number" id="ldap_paging_size" name="ldap_paging_size" title="<?php p($l->t('Chunksize used for paged LDAP searches that may return bulky results like user or group enumeration. (Setting it 0 disables paged LDAP searches in those situations.)')); ?>" data-default="<?php p($_['ldap_paging_size_default']); ?>" /></p>
104
+				<p><label for="ldap_turn_on_pwd_change"><?php p($l->t('Enable LDAP password changes per user')); ?></label><span class="inlinetable"><span class="tablerow left"><input type="checkbox" id="ldap_turn_on_pwd_change" name="ldap_turn_on_pwd_change" value="1" data-default="<?php p($_['ldap_turn_on_pwd_change_default']); ?>" title="<?php p($l->t('Allow LDAP users to change their password and allow Super Administrators and Group Administrators to change the password of their LDAP users. Only works when access control policies are configured accordingly on the LDAP server. As passwords are sent in plaintext to the LDAP server, transport encryption must be used and password hashing should be configured on the LDAP server.')); ?>" /><span class="tablecell"><?php p($l->t('(New password is sent as plain text to LDAP)')); ?></span></span>
105 105
 			</span><br/></p>
106
-				<p><label for="ldap_default_ppolicy_dn"><?php p($l->t('Default password policy DN'));?></label><input type="text" id="ldap_default_ppolicy_dn" name="ldap_default_ppolicy_dn" title="<?php p($l->t('The DN of a default password policy that will be used for password expiry handling. Works only when LDAP password changes per user are enabled and is only supported by OpenLDAP. Leave empty to disable password expiry handling.'));?>" data-default="<?php p($_['ldap_default_ppolicy_dn_default']); ?>" /></p>
106
+				<p><label for="ldap_default_ppolicy_dn"><?php p($l->t('Default password policy DN')); ?></label><input type="text" id="ldap_default_ppolicy_dn" name="ldap_default_ppolicy_dn" title="<?php p($l->t('The DN of a default password policy that will be used for password expiry handling. Works only when LDAP password changes per user are enabled and is only supported by OpenLDAP. Leave empty to disable password expiry handling.')); ?>" data-default="<?php p($_['ldap_default_ppolicy_dn_default']); ?>" /></p>
107 107
 			</div>
108
-			<h3><?php p($l->t('Special Attributes'));?></h3>
108
+			<h3><?php p($l->t('Special Attributes')); ?></h3>
109 109
 			<div>
110
-				<p><label for="ldap_quota_attr"><?php p($l->t('Quota Field'));?></label><input type="text" id="ldap_quota_attr" name="ldap_quota_attr" data-default="<?php p($_['ldap_quota_attr_default']); ?>" title="<?php p($l->t('Leave empty for user\'s default quota. Otherwise, specify an LDAP/AD attribute.'));?>" /></p>
111
-				<p><label for="ldap_quota_def"><?php p($l->t('Quota Default'));?></label><input type="text" id="ldap_quota_def" name="ldap_quota_def" data-default="<?php p($_['ldap_quota_def_default']); ?>" title="<?php p($l->t('Override default quota for LDAP users who do not have a quota set in the Quota Field.'));?>" /></p>
112
-				<p><label for="ldap_email_attr"><?php p($l->t('Email Field'));?></label><input type="text" id="ldap_email_attr" name="ldap_email_attr" data-default="<?php p($_['ldap_email_attr_default']); ?>" title="<?php p($l->t('Set the user\'s email from their LDAP attribute. Leave it empty for default behaviour.'));?>" /></p>
113
-				<p><label for="home_folder_naming_rule"><?php p($l->t('User Home Folder Naming Rule'));?></label><input type="text" id="home_folder_naming_rule" name="home_folder_naming_rule" title="<?php p($l->t('Leave empty for user name (default). Otherwise, specify an LDAP/AD attribute.'));?>" data-default="<?php p($_['home_folder_naming_rule_default']); ?>" /></p>
110
+				<p><label for="ldap_quota_attr"><?php p($l->t('Quota Field')); ?></label><input type="text" id="ldap_quota_attr" name="ldap_quota_attr" data-default="<?php p($_['ldap_quota_attr_default']); ?>" title="<?php p($l->t('Leave empty for user\'s default quota. Otherwise, specify an LDAP/AD attribute.')); ?>" /></p>
111
+				<p><label for="ldap_quota_def"><?php p($l->t('Quota Default')); ?></label><input type="text" id="ldap_quota_def" name="ldap_quota_def" data-default="<?php p($_['ldap_quota_def_default']); ?>" title="<?php p($l->t('Override default quota for LDAP users who do not have a quota set in the Quota Field.')); ?>" /></p>
112
+				<p><label for="ldap_email_attr"><?php p($l->t('Email Field')); ?></label><input type="text" id="ldap_email_attr" name="ldap_email_attr" data-default="<?php p($_['ldap_email_attr_default']); ?>" title="<?php p($l->t('Set the user\'s email from their LDAP attribute. Leave it empty for default behaviour.')); ?>" /></p>
113
+				<p><label for="home_folder_naming_rule"><?php p($l->t('User Home Folder Naming Rule')); ?></label><input type="text" id="home_folder_naming_rule" name="home_folder_naming_rule" title="<?php p($l->t('Leave empty for user name (default). Otherwise, specify an LDAP/AD attribute.')); ?>" data-default="<?php p($_['home_folder_naming_rule_default']); ?>" /></p>
114 114
 			</div>
115 115
 		</div>
116 116
 		<?php print_unescaped($_['settingControls']); ?>
117 117
 	</fieldset>
118 118
 	<fieldset id="ldapSettings-2">
119
-		<p><strong><?php p($l->t('Internal Username'));?></strong></p>
120
-		<p class="ldapIndent"><?php p($l->t('By default the internal username will be created from the UUID attribute. It makes sure that the username is unique and characters do not need to be converted. The internal username has the restriction that only these characters are allowed: [ a-zA-Z0-9_.@- ].  Other characters are replaced with their ASCII correspondence or simply omitted. On collisions a number will be added/increased. The internal username is used to identify a user internally. It is also the default name for the user home folder. It is also a part of remote URLs, for instance for all *DAV services. With this setting, the default behavior can be overridden. Leave it empty for default behavior. Changes will have effect only on newly mapped (added) LDAP users.'));?></p>
121
-		<p class="ldapIndent"><label for="ldap_expert_username_attr"><?php p($l->t('Internal Username Attribute:'));?></label><input type="text" id="ldap_expert_username_attr" name="ldap_expert_username_attr" data-default="<?php p($_['ldap_expert_username_attr_default']); ?>" /></p>
122
-		<p><strong><?php p($l->t('Override UUID detection'));?></strong></p>
123
-		<p class="ldapIndent"><?php p($l->t('By default, the UUID attribute is automatically detected. The UUID attribute is used to doubtlessly identify LDAP users and groups. Also, the internal username will be created based on the UUID, if not specified otherwise above. You can override the setting and pass an attribute of your choice. You must make sure that the attribute of your choice can be fetched for both users and groups and it is unique. Leave it empty for default behavior. Changes will have effect only on newly mapped (added) LDAP users and groups.'));?></p>
124
-		<p class="ldapIndent"><label for="ldap_expert_uuid_user_attr"><?php p($l->t('UUID Attribute for Users:'));?></label><input type="text" id="ldap_expert_uuid_user_attr" name="ldap_expert_uuid_user_attr" data-default="<?php p($_['ldap_expert_uuid_user_attr_default']); ?>" /></p>
125
-		<p class="ldapIndent"><label for="ldap_expert_uuid_group_attr"><?php p($l->t('UUID Attribute for Groups:'));?></label><input type="text" id="ldap_expert_uuid_group_attr" name="ldap_expert_uuid_group_attr" data-default="<?php p($_['ldap_expert_uuid_group_attr_default']); ?>" /></p>
126
-		<p><strong><?php p($l->t('Username-LDAP User Mapping'));?></strong></p>
127
-		<p class="ldapIndent"><?php p($l->t('Usernames are used to store and assign (meta) data. In order to precisely identify and recognize users, each LDAP user will have an internal username. This requires a mapping from username to LDAP user. The created username is mapped to the UUID of the LDAP user. Additionally the DN is cached as well to reduce LDAP interaction, but it is not used for identification. If the DN changes, the changes will be found. The internal username is used all over. Clearing the mappings will have leftovers everywhere. Clearing the mappings is not configuration sensitive, it affects all LDAP configurations! Never clear the mappings in a production environment, only in a testing or experimental stage.'));?></p>
128
-		<p class="ldapIndent"><button type="button" id="ldap_action_clear_user_mappings" name="ldap_action_clear_user_mappings"><?php p($l->t('Clear Username-LDAP User Mapping'));?></button><br/><button type="button" id="ldap_action_clear_group_mappings" name="ldap_action_clear_group_mappings"><?php p($l->t('Clear Groupname-LDAP Group Mapping'));?></button></p>
119
+		<p><strong><?php p($l->t('Internal Username')); ?></strong></p>
120
+		<p class="ldapIndent"><?php p($l->t('By default the internal username will be created from the UUID attribute. It makes sure that the username is unique and characters do not need to be converted. The internal username has the restriction that only these characters are allowed: [ a-zA-Z0-9_.@- ].  Other characters are replaced with their ASCII correspondence or simply omitted. On collisions a number will be added/increased. The internal username is used to identify a user internally. It is also the default name for the user home folder. It is also a part of remote URLs, for instance for all *DAV services. With this setting, the default behavior can be overridden. Leave it empty for default behavior. Changes will have effect only on newly mapped (added) LDAP users.')); ?></p>
121
+		<p class="ldapIndent"><label for="ldap_expert_username_attr"><?php p($l->t('Internal Username Attribute:')); ?></label><input type="text" id="ldap_expert_username_attr" name="ldap_expert_username_attr" data-default="<?php p($_['ldap_expert_username_attr_default']); ?>" /></p>
122
+		<p><strong><?php p($l->t('Override UUID detection')); ?></strong></p>
123
+		<p class="ldapIndent"><?php p($l->t('By default, the UUID attribute is automatically detected. The UUID attribute is used to doubtlessly identify LDAP users and groups. Also, the internal username will be created based on the UUID, if not specified otherwise above. You can override the setting and pass an attribute of your choice. You must make sure that the attribute of your choice can be fetched for both users and groups and it is unique. Leave it empty for default behavior. Changes will have effect only on newly mapped (added) LDAP users and groups.')); ?></p>
124
+		<p class="ldapIndent"><label for="ldap_expert_uuid_user_attr"><?php p($l->t('UUID Attribute for Users:')); ?></label><input type="text" id="ldap_expert_uuid_user_attr" name="ldap_expert_uuid_user_attr" data-default="<?php p($_['ldap_expert_uuid_user_attr_default']); ?>" /></p>
125
+		<p class="ldapIndent"><label for="ldap_expert_uuid_group_attr"><?php p($l->t('UUID Attribute for Groups:')); ?></label><input type="text" id="ldap_expert_uuid_group_attr" name="ldap_expert_uuid_group_attr" data-default="<?php p($_['ldap_expert_uuid_group_attr_default']); ?>" /></p>
126
+		<p><strong><?php p($l->t('Username-LDAP User Mapping')); ?></strong></p>
127
+		<p class="ldapIndent"><?php p($l->t('Usernames are used to store and assign (meta) data. In order to precisely identify and recognize users, each LDAP user will have an internal username. This requires a mapping from username to LDAP user. The created username is mapped to the UUID of the LDAP user. Additionally the DN is cached as well to reduce LDAP interaction, but it is not used for identification. If the DN changes, the changes will be found. The internal username is used all over. Clearing the mappings will have leftovers everywhere. Clearing the mappings is not configuration sensitive, it affects all LDAP configurations! Never clear the mappings in a production environment, only in a testing or experimental stage.')); ?></p>
128
+		<p class="ldapIndent"><button type="button" id="ldap_action_clear_user_mappings" name="ldap_action_clear_user_mappings"><?php p($l->t('Clear Username-LDAP User Mapping')); ?></button><br/><button type="button" id="ldap_action_clear_group_mappings" name="ldap_action_clear_group_mappings"><?php p($l->t('Clear Groupname-LDAP Group Mapping')); ?></button></p>
129 129
 		<?php print_unescaped($_['settingControls']); ?>
130 130
 	</fieldset>
131 131
 	</div>
Please login to merge, or discard this patch.
apps/user_ldap/appinfo/routes.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -23,36 +23,36 @@
 block discarded – undo
23 23
 
24 24
 /** @var $this \OCP\Route\IRouter */
25 25
 $this->create('user_ldap_ajax_clearMappings', 'ajax/clearMappings.php')
26
-	->actionInclude('user_ldap/ajax/clearMappings.php');
26
+    ->actionInclude('user_ldap/ajax/clearMappings.php');
27 27
 $this->create('user_ldap_ajax_deleteConfiguration', 'ajax/deleteConfiguration.php')
28
-	->actionInclude('user_ldap/ajax/deleteConfiguration.php');
28
+    ->actionInclude('user_ldap/ajax/deleteConfiguration.php');
29 29
 $this->create('user_ldap_ajax_getConfiguration', 'ajax/getConfiguration.php')
30
-	->actionInclude('user_ldap/ajax/getConfiguration.php');
30
+    ->actionInclude('user_ldap/ajax/getConfiguration.php');
31 31
 $this->create('user_ldap_ajax_getNewServerConfigPrefix', 'ajax/getNewServerConfigPrefix.php')
32
-	->actionInclude('user_ldap/ajax/getNewServerConfigPrefix.php');
32
+    ->actionInclude('user_ldap/ajax/getNewServerConfigPrefix.php');
33 33
 $this->create('user_ldap_ajax_setConfiguration', 'ajax/setConfiguration.php')
34
-	->actionInclude('user_ldap/ajax/setConfiguration.php');
34
+    ->actionInclude('user_ldap/ajax/setConfiguration.php');
35 35
 $this->create('user_ldap_ajax_testConfiguration', 'ajax/testConfiguration.php')
36
-	->actionInclude('user_ldap/ajax/testConfiguration.php');
36
+    ->actionInclude('user_ldap/ajax/testConfiguration.php');
37 37
 $this->create('user_ldap_ajax_wizard', 'ajax/wizard.php')
38
-	->actionInclude('user_ldap/ajax/wizard.php');
38
+    ->actionInclude('user_ldap/ajax/wizard.php');
39 39
 
40 40
 $application = new \OCP\AppFramework\App('user_ldap');
41 41
 $application->registerRoutes($this, [
42
-	'ocs' => [
43
-		['name' => 'ConfigAPI#create', 'url' => '/api/v1/config', 'verb' => 'POST'],
44
-		['name' => 'ConfigAPI#show',   'url' => '/api/v1/config/{configID}', 'verb' => 'GET'],
45
-		['name' => 'ConfigAPI#modify', 'url' => '/api/v1/config/{configID}', 'verb' => 'PUT'],
46
-		['name' => 'ConfigAPI#delete', 'url' => '/api/v1/config/{configID}', 'verb' => 'DELETE'],
47
-	]
42
+    'ocs' => [
43
+        ['name' => 'ConfigAPI#create', 'url' => '/api/v1/config', 'verb' => 'POST'],
44
+        ['name' => 'ConfigAPI#show',   'url' => '/api/v1/config/{configID}', 'verb' => 'GET'],
45
+        ['name' => 'ConfigAPI#modify', 'url' => '/api/v1/config/{configID}', 'verb' => 'PUT'],
46
+        ['name' => 'ConfigAPI#delete', 'url' => '/api/v1/config/{configID}', 'verb' => 'DELETE'],
47
+    ]
48 48
 ]);
49 49
 
50 50
 $application = new OCA\User_LDAP\AppInfo\Application();
51 51
 $application->registerRoutes($this, [
52
-	'routes' => [
53
-		['name' => 'renewPassword#tryRenewPassword', 'url' => '/renewpassword', 'verb' => 'POST'],
54
-		['name' => 'renewPassword#showRenewPasswordForm', 'url' => '/renewpassword/{user}', 'verb' => 'GET'],
55
-		['name' => 'renewPassword#cancel', 'url' => '/renewpassword/cancel', 'verb' => 'GET'],
56
-		['name' => 'renewPassword#showLoginFormInvalidPassword', 'url' => '/renewpassword/invalidlogin/{user}', 'verb' => 'GET'],
57
-	]
52
+    'routes' => [
53
+        ['name' => 'renewPassword#tryRenewPassword', 'url' => '/renewpassword', 'verb' => 'POST'],
54
+        ['name' => 'renewPassword#showRenewPasswordForm', 'url' => '/renewpassword/{user}', 'verb' => 'GET'],
55
+        ['name' => 'renewPassword#cancel', 'url' => '/renewpassword/cancel', 'verb' => 'GET'],
56
+        ['name' => 'renewPassword#showLoginFormInvalidPassword', 'url' => '/renewpassword/invalidlogin/{user}', 'verb' => 'GET'],
57
+    ]
58 58
 ]);
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/User.php 2 patches
Spacing   +58 added lines, -58 removed lines patch added patch discarded remove patch
@@ -149,17 +149,17 @@  discard block
 block discarded – undo
149 149
 	 * @return null
150 150
 	 */
151 151
 	public function update() {
152
-		if(is_null($this->dn)) {
152
+		if (is_null($this->dn)) {
153 153
 			return null;
154 154
 		}
155 155
 
156 156
 		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157 157
 				self::USER_PREFKEY_FIRSTLOGIN, 0);
158 158
 
159
-		if($this->needsRefresh()) {
159
+		if ($this->needsRefresh()) {
160 160
 			$this->updateEmail();
161 161
 			$this->updateQuota();
162
-			if($hasLoggedIn !== 0) {
162
+			if ($hasLoggedIn !== 0) {
163 163
 				//we do not need to try it, when the user has not been logged in
164 164
 				//before, because the file system will not be ready.
165 165
 				$this->updateAvatar();
@@ -178,7 +178,7 @@  discard block
 block discarded – undo
178 178
 		$this->markRefreshTime();
179 179
 		//Quota
180 180
 		$attr = strtolower($this->connection->ldapQuotaAttribute);
181
-		if(isset($ldapEntry[$attr])) {
181
+		if (isset($ldapEntry[$attr])) {
182 182
 			$this->updateQuota($ldapEntry[$attr][0]);
183 183
 		} else {
184 184
 			if ($this->connection->ldapQuotaDefault !== '') {
@@ -189,7 +189,7 @@  discard block
 block discarded – undo
189 189
 
190 190
 		//Email
191 191
 		$attr = strtolower($this->connection->ldapEmailAttribute);
192
-		if(isset($ldapEntry[$attr])) {
192
+		if (isset($ldapEntry[$attr])) {
193 193
 			$this->updateEmail($ldapEntry[$attr][0]);
194 194
 		}
195 195
 		unset($attr);
@@ -197,11 +197,11 @@  discard block
 block discarded – undo
197 197
 		//displayName
198 198
 		$displayName = $displayName2 = '';
199 199
 		$attr = strtolower($this->connection->ldapUserDisplayName);
200
-		if(isset($ldapEntry[$attr])) {
200
+		if (isset($ldapEntry[$attr])) {
201 201
 			$displayName = strval($ldapEntry[$attr][0]);
202 202
 		}
203 203
 		$attr = strtolower($this->connection->ldapUserDisplayName2);
204
-		if(isset($ldapEntry[$attr])) {
204
+		if (isset($ldapEntry[$attr])) {
205 205
 			$displayName2 = strval($ldapEntry[$attr][0]);
206 206
 		}
207 207
 		if ($displayName !== '') {
@@ -215,16 +215,16 @@  discard block
 block discarded – undo
215 215
 		unset($attr);
216 216
 
217 217
 		// LDAP Username, needed for s2s sharing
218
-		if(isset($ldapEntry['uid'])) {
218
+		if (isset($ldapEntry['uid'])) {
219 219
 			$this->storeLDAPUserName($ldapEntry['uid'][0]);
220
-		} else if(isset($ldapEntry['samaccountname'])) {
220
+		} else if (isset($ldapEntry['samaccountname'])) {
221 221
 			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
222 222
 		}
223 223
 
224 224
 		//homePath
225
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
225
+		if (strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
226 226
 			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
227
-			if(isset($ldapEntry[$attr])) {
227
+			if (isset($ldapEntry[$attr])) {
228 228
 				$this->access->cacheUserHome(
229 229
 					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
230 230
 			}
@@ -233,15 +233,15 @@  discard block
 block discarded – undo
233 233
 		//memberOf groups
234 234
 		$cacheKey = 'getMemberOf'.$this->getUsername();
235 235
 		$groups = false;
236
-		if(isset($ldapEntry['memberof'])) {
236
+		if (isset($ldapEntry['memberof'])) {
237 237
 			$groups = $ldapEntry['memberof'];
238 238
 		}
239 239
 		$this->connection->writeToCache($cacheKey, $groups);
240 240
 
241 241
 		//Avatar
242 242
 		$attrs = array('jpegphoto', 'thumbnailphoto');
243
-		foreach ($attrs as $attr)  {
244
-			if(isset($ldapEntry[$attr])) {
243
+		foreach ($attrs as $attr) {
244
+			if (isset($ldapEntry[$attr])) {
245 245
 				$this->avatarImage = $ldapEntry[$attr][0];
246 246
 				// the call to the method that saves the avatar in the file
247 247
 				// system must be postponed after the login. It is to ensure
@@ -294,12 +294,12 @@  discard block
 block discarded – undo
294 294
 		if ($path !== '') {
295 295
 			//if attribute's value is an absolute path take this, otherwise append it to data dir
296 296
 			//check for / at the beginning or pattern c:\ resp. c:/
297
-			if(   '/' !== $path[0]
297
+			if ('/' !== $path[0]
298 298
 			   && !(3 < strlen($path) && ctype_alpha($path[0])
299 299
 			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
300 300
 			) {
301 301
 				$path = $this->config->getSystemValue('datadirectory',
302
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
302
+						\OC::$SERVERROOT.'/data').'/'.$path;
303 303
 			}
304 304
 			//we need it to store it in the DB as well in case a user gets
305 305
 			//deleted so we can clean up afterwards
@@ -309,11 +309,11 @@  discard block
 block discarded – undo
309 309
 			return $path;
310 310
 		}
311 311
 
312
-		if(    !is_null($attr)
312
+		if (!is_null($attr)
313 313
 			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
314 314
 		) {
315 315
 			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
316
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
316
+			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: '.$this->getUsername());
317 317
 		}
318 318
 
319 319
 		//false will apply default behaviour as defined and done by OC_User
@@ -324,7 +324,7 @@  discard block
 block discarded – undo
324 324
 	public function getMemberOfGroups() {
325 325
 		$cacheKey = 'getMemberOf'.$this->getUsername();
326 326
 		$memberOfGroups = $this->connection->getFromCache($cacheKey);
327
-		if(!is_null($memberOfGroups)) {
327
+		if (!is_null($memberOfGroups)) {
328 328
 			return $memberOfGroups;
329 329
 		}
330 330
 		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
@@ -337,15 +337,15 @@  discard block
 block discarded – undo
337 337
 	 * @return string data (provided by LDAP) | false
338 338
 	 */
339 339
 	public function getAvatarImage() {
340
-		if(!is_null($this->avatarImage)) {
340
+		if (!is_null($this->avatarImage)) {
341 341
 			return $this->avatarImage;
342 342
 		}
343 343
 
344 344
 		$this->avatarImage = false;
345 345
 		$attributes = array('jpegPhoto', 'thumbnailPhoto');
346
-		foreach($attributes as $attribute) {
346
+		foreach ($attributes as $attribute) {
347 347
 			$result = $this->access->readAttribute($this->dn, $attribute);
348
-			if($result !== false && is_array($result) && isset($result[0])) {
348
+			if ($result !== false && is_array($result) && isset($result[0])) {
349 349
 				$this->avatarImage = $result[0];
350 350
 				break;
351 351
 			}
@@ -383,7 +383,7 @@  discard block
 block discarded – undo
383 383
 			self::USER_PREFKEY_LASTREFRESH, 0);
384 384
 
385 385
 		//TODO make interval configurable
386
-		if((time() - intval($lastChecked)) < 86400 ) {
386
+		if ((time() - intval($lastChecked)) < 86400) {
387 387
 			return false;
388 388
 		}
389 389
 		return  true;
@@ -409,8 +409,8 @@  discard block
 block discarded – undo
409 409
 	 */
410 410
 	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
411 411
 		$displayName2 = strval($displayName2);
412
-		if($displayName2 !== '') {
413
-			$displayName .= ' (' . $displayName2 . ')';
412
+		if ($displayName2 !== '') {
413
+			$displayName .= ' ('.$displayName2.')';
414 414
 		}
415 415
 		$this->store('displayName', $displayName);
416 416
 		return $displayName;
@@ -432,7 +432,7 @@  discard block
 block discarded – undo
432 432
 	 * @return bool
433 433
 	 */
434 434
 	private function wasRefreshed($feature) {
435
-		if(isset($this->refreshedFeatures[$feature])) {
435
+		if (isset($this->refreshedFeatures[$feature])) {
436 436
 			return true;
437 437
 		}
438 438
 		$this->refreshedFeatures[$feature] = 1;
@@ -445,15 +445,15 @@  discard block
 block discarded – undo
445 445
 	 * @return null
446 446
 	 */
447 447
 	public function updateEmail($valueFromLDAP = null) {
448
-		if($this->wasRefreshed('email')) {
448
+		if ($this->wasRefreshed('email')) {
449 449
 			return;
450 450
 		}
451 451
 		$email = strval($valueFromLDAP);
452
-		if(is_null($valueFromLDAP)) {
452
+		if (is_null($valueFromLDAP)) {
453 453
 			$emailAttribute = $this->connection->ldapEmailAttribute;
454 454
 			if ($emailAttribute !== '') {
455 455
 				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
456
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
456
+				if (is_array($aEmail) && (count($aEmail) > 0)) {
457 457
 					$email = strval($aEmail[0]);
458 458
 				}
459 459
 			}
@@ -490,20 +490,20 @@  discard block
 block discarded – undo
490 490
 	 * @return null
491 491
 	 */
492 492
 	public function updateQuota($valueFromLDAP = null) {
493
-		if($this->wasRefreshed('quota')) {
493
+		if ($this->wasRefreshed('quota')) {
494 494
 			return;
495 495
 		}
496 496
 
497 497
 		$quota = false;
498
-		if(is_null($valueFromLDAP)) {
498
+		if (is_null($valueFromLDAP)) {
499 499
 			$quotaAttribute = $this->connection->ldapQuotaAttribute;
500 500
 			if ($quotaAttribute !== '') {
501 501
 				$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
502
-				if($aQuota && (count($aQuota) > 0)) {
502
+				if ($aQuota && (count($aQuota) > 0)) {
503 503
 					if ($this->verifyQuotaValue($aQuota[0])) {
504 504
 						$quota = $aQuota[0];
505 505
 					} else {
506
-						$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
506
+						$this->log->log('not suitable LDAP quota found for user '.$this->uid.': ['.$aQuota[0].']', \OCP\Util::WARN);
507 507
 					}
508 508
 				}
509 509
 			}
@@ -511,7 +511,7 @@  discard block
 block discarded – undo
511 511
 			if ($this->verifyQuotaValue($valueFromLDAP)) {
512 512
 				$quota = $valueFromLDAP;
513 513
 			} else {
514
-				$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
514
+				$this->log->log('not suitable LDAP quota found for user '.$this->uid.': ['.$valueFromLDAP.']', \OCP\Util::WARN);
515 515
 			}
516 516
 		}
517 517
 
@@ -525,14 +525,14 @@  discard block
 block discarded – undo
525 525
 
526 526
 		$targetUser = $this->userManager->get($this->uid);
527 527
 		if ($targetUser) {
528
-			if($quota !== false) {
528
+			if ($quota !== false) {
529 529
 				$targetUser->setQuota($quota);
530 530
 			} else {
531
-				$this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
531
+				$this->log->log('not suitable default quota found for user '.$this->uid.': ['.$defaultQuota.']', \OCP\Util::WARN);
532 532
 				$targetUser->setQuota('default');
533 533
 			}
534 534
 		} else {
535
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
535
+			$this->log->log('trying to set a quota for user '.$this->uid.' but the user is missing', \OCP\Util::ERROR);
536 536
 		}
537 537
 	}
538 538
 
@@ -546,7 +546,7 @@  discard block
 block discarded – undo
546 546
 	 * @param array $params
547 547
 	 */
548 548
 	public function updateAvatarPostLogin($params) {
549
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
549
+		if (isset($params['uid']) && $params['uid'] === $this->getUsername()) {
550 550
 			$this->updateAvatar();
551 551
 		}
552 552
 	}
@@ -556,11 +556,11 @@  discard block
 block discarded – undo
556 556
 	 * @return null
557 557
 	 */
558 558
 	public function updateAvatar() {
559
-		if($this->wasRefreshed('avatar')) {
559
+		if ($this->wasRefreshed('avatar')) {
560 560
 			return;
561 561
 		}
562 562
 		$avatarImage = $this->getAvatarImage();
563
-		if($avatarImage === false) {
563
+		if ($avatarImage === false) {
564 564
 			//not set, nothing left to do;
565 565
 			return;
566 566
 		}
@@ -573,18 +573,18 @@  discard block
 block discarded – undo
573 573
 	 * @return null
574 574
 	 */
575 575
 	private function setOwnCloudAvatar() {
576
-		if(!$this->image->valid()) {
576
+		if (!$this->image->valid()) {
577 577
 			$this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
578 578
 			return;
579 579
 		}
580 580
 		//make sure it is a square and not bigger than 128x128
581 581
 		$size = min(array($this->image->width(), $this->image->height(), 128));
582
-		if(!$this->image->centerCrop($size)) {
582
+		if (!$this->image->centerCrop($size)) {
583 583
 			$this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
584 584
 			return;
585 585
 		}
586 586
 
587
-		if(!$this->fs->isLoaded()) {
587
+		if (!$this->fs->isLoaded()) {
588 588
 			$this->fs->setup($this->uid);
589 589
 		}
590 590
 
@@ -593,7 +593,7 @@  discard block
 block discarded – undo
593 593
 			$avatar->set($this->image);
594 594
 		} catch (\Exception $e) {
595 595
 			\OC::$server->getLogger()->notice(
596
-				'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
596
+				'Could not set avatar for '.$this->dn.', because: '.$e->getMessage(),
597 597
 				['app' => 'user_ldap']);
598 598
 		}
599 599
 	}
@@ -606,17 +606,17 @@  discard block
 block discarded – undo
606 606
 	public function handlePasswordExpiry($params) {
607 607
 		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
608 608
 		if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
609
-			return;//password expiry handling disabled
609
+			return; //password expiry handling disabled
610 610
 		}
611 611
 		$uid = $params['uid'];
612
-		if(isset($uid) && $uid === $this->getUsername()) {
612
+		if (isset($uid) && $uid === $this->getUsername()) {
613 613
 			//retrieve relevant user attributes
614 614
 			$result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
615 615
 			
616
-			if(array_key_exists('pwdpolicysubentry', $result[0])) {
616
+			if (array_key_exists('pwdpolicysubentry', $result[0])) {
617 617
 				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
618
-				if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
619
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
618
+				if ($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)) {
619
+					$ppolicyDN = $pwdPolicySubentry[0]; //custom ppolicy DN
620 620
 				}
621 621
 			}
622 622
 			
@@ -625,9 +625,9 @@  discard block
 block discarded – undo
625 625
 			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
626 626
 			
627 627
 			//retrieve relevant password policy attributes
628
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
628
+			$cacheKey = 'ppolicyAttributes'.$ppolicyDN;
629 629
 			$result = $this->connection->getFromCache($cacheKey);
630
-			if(is_null($result)) {
630
+			if (is_null($result)) {
631 631
 				$result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
632 632
 				$this->connection->writeToCache($cacheKey, $result);
633 633
 			}
@@ -638,8 +638,8 @@  discard block
 block discarded – undo
638 638
 			
639 639
 			//handle grace login
640 640
 			$pwdGraceUseTimeCount = count($pwdGraceUseTime);
641
-			if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
642
-				if($pwdGraceAuthNLimit 
641
+			if ($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
642
+				if ($pwdGraceAuthNLimit 
643 643
 					&& (count($pwdGraceAuthNLimit) > 0)
644 644
 					&&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
645 645
 					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
@@ -652,24 +652,24 @@  discard block
 block discarded – undo
652 652
 				exit();
653 653
 			}
654 654
 			//handle pwdReset attribute
655
-			if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
655
+			if ($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
656 656
 				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
657 657
 				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
658 658
 				'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
659 659
 				exit();
660 660
 			}
661 661
 			//handle password expiry warning
662
-			if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
663
-				if($pwdMaxAge && (count($pwdMaxAge) > 0)
662
+			if ($pwdChangedTime && (count($pwdChangedTime) > 0)) {
663
+				if ($pwdMaxAge && (count($pwdMaxAge) > 0)
664 664
 					&& $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
665 665
 					$pwdMaxAgeInt = intval($pwdMaxAge[0]);
666 666
 					$pwdExpireWarningInt = intval($pwdExpireWarning[0]);
667
-					if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
667
+					if ($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0) {
668 668
 						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
669 669
 						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
670 670
 						$currentDateTime = new \DateTime();
671 671
 						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
672
-						if($secondsToExpiry <= $pwdExpireWarningInt) {
672
+						if ($secondsToExpiry <= $pwdExpireWarningInt) {
673 673
 							//remove last password expiry warning if any
674 674
 							$notification = $this->notificationManager->createNotification();
675 675
 							$notification->setApp('user_ldap')
Please login to merge, or discard this patch.
Indentation   +643 added lines, -643 removed lines patch added patch discarded remove patch
@@ -43,653 +43,653 @@
 block discarded – undo
43 43
  * represents an LDAP user, gets and holds user-specific information from LDAP
44 44
  */
45 45
 class User {
46
-	/**
47
-	 * @var IUserTools
48
-	 */
49
-	protected $access;
50
-	/**
51
-	 * @var Connection
52
-	 */
53
-	protected $connection;
54
-	/**
55
-	 * @var IConfig
56
-	 */
57
-	protected $config;
58
-	/**
59
-	 * @var FilesystemHelper
60
-	 */
61
-	protected $fs;
62
-	/**
63
-	 * @var Image
64
-	 */
65
-	protected $image;
66
-	/**
67
-	 * @var LogWrapper
68
-	 */
69
-	protected $log;
70
-	/**
71
-	 * @var IAvatarManager
72
-	 */
73
-	protected $avatarManager;
74
-	/**
75
-	 * @var IUserManager
76
-	 */
77
-	protected $userManager;
78
-	/**
79
-	 * @var INotificationManager
80
-	 */
81
-	protected $notificationManager;
82
-	/**
83
-	 * @var string
84
-	 */
85
-	protected $dn;
86
-	/**
87
-	 * @var string
88
-	 */
89
-	protected $uid;
90
-	/**
91
-	 * @var string[]
92
-	 */
93
-	protected $refreshedFeatures = array();
94
-	/**
95
-	 * @var string
96
-	 */
97
-	protected $avatarImage;
98
-
99
-	/**
100
-	 * DB config keys for user preferences
101
-	 */
102
-	const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
103
-	const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
104
-
105
-	/**
106
-	 * @brief constructor, make sure the subclasses call this one!
107
-	 * @param string $username the internal username
108
-	 * @param string $dn the LDAP DN
109
-	 * @param IUserTools $access an instance that implements IUserTools for
110
-	 * LDAP interaction
111
-	 * @param IConfig $config
112
-	 * @param FilesystemHelper $fs
113
-	 * @param Image $image any empty instance
114
-	 * @param LogWrapper $log
115
-	 * @param IAvatarManager $avatarManager
116
-	 * @param IUserManager $userManager
117
-	 * @param INotificationManager $notificationManager
118
-	 */
119
-	public function __construct($username, $dn, IUserTools $access,
120
-		IConfig $config, FilesystemHelper $fs, Image $image,
121
-		LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
122
-		INotificationManager $notificationManager) {
46
+    /**
47
+     * @var IUserTools
48
+     */
49
+    protected $access;
50
+    /**
51
+     * @var Connection
52
+     */
53
+    protected $connection;
54
+    /**
55
+     * @var IConfig
56
+     */
57
+    protected $config;
58
+    /**
59
+     * @var FilesystemHelper
60
+     */
61
+    protected $fs;
62
+    /**
63
+     * @var Image
64
+     */
65
+    protected $image;
66
+    /**
67
+     * @var LogWrapper
68
+     */
69
+    protected $log;
70
+    /**
71
+     * @var IAvatarManager
72
+     */
73
+    protected $avatarManager;
74
+    /**
75
+     * @var IUserManager
76
+     */
77
+    protected $userManager;
78
+    /**
79
+     * @var INotificationManager
80
+     */
81
+    protected $notificationManager;
82
+    /**
83
+     * @var string
84
+     */
85
+    protected $dn;
86
+    /**
87
+     * @var string
88
+     */
89
+    protected $uid;
90
+    /**
91
+     * @var string[]
92
+     */
93
+    protected $refreshedFeatures = array();
94
+    /**
95
+     * @var string
96
+     */
97
+    protected $avatarImage;
98
+
99
+    /**
100
+     * DB config keys for user preferences
101
+     */
102
+    const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
103
+    const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
104
+
105
+    /**
106
+     * @brief constructor, make sure the subclasses call this one!
107
+     * @param string $username the internal username
108
+     * @param string $dn the LDAP DN
109
+     * @param IUserTools $access an instance that implements IUserTools for
110
+     * LDAP interaction
111
+     * @param IConfig $config
112
+     * @param FilesystemHelper $fs
113
+     * @param Image $image any empty instance
114
+     * @param LogWrapper $log
115
+     * @param IAvatarManager $avatarManager
116
+     * @param IUserManager $userManager
117
+     * @param INotificationManager $notificationManager
118
+     */
119
+    public function __construct($username, $dn, IUserTools $access,
120
+        IConfig $config, FilesystemHelper $fs, Image $image,
121
+        LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager,
122
+        INotificationManager $notificationManager) {
123 123
 	
124
-		if ($username === null) {
125
-			$log->log("uid for '$dn' must not be null!", Util::ERROR);
126
-			throw new \InvalidArgumentException('uid must not be null!');
127
-		} else if ($username === '') {
128
-			$log->log("uid for '$dn' must not be an empty string", Util::ERROR);
129
-			throw new \InvalidArgumentException('uid must not be an empty string!');
130
-		}
131
-
132
-		$this->access              = $access;
133
-		$this->connection          = $access->getConnection();
134
-		$this->config              = $config;
135
-		$this->fs                  = $fs;
136
-		$this->dn                  = $dn;
137
-		$this->uid                 = $username;
138
-		$this->image               = $image;
139
-		$this->log                 = $log;
140
-		$this->avatarManager       = $avatarManager;
141
-		$this->userManager         = $userManager;
142
-		$this->notificationManager = $notificationManager;
143
-
144
-		\OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
145
-	}
146
-
147
-	/**
148
-	 * @brief updates properties like email, quota or avatar provided by LDAP
149
-	 * @return null
150
-	 */
151
-	public function update() {
152
-		if(is_null($this->dn)) {
153
-			return null;
154
-		}
155
-
156
-		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157
-				self::USER_PREFKEY_FIRSTLOGIN, 0);
158
-
159
-		if($this->needsRefresh()) {
160
-			$this->updateEmail();
161
-			$this->updateQuota();
162
-			if($hasLoggedIn !== 0) {
163
-				//we do not need to try it, when the user has not been logged in
164
-				//before, because the file system will not be ready.
165
-				$this->updateAvatar();
166
-				//in order to get an avatar as soon as possible, mark the user
167
-				//as refreshed only when updating the avatar did happen
168
-				$this->markRefreshTime();
169
-			}
170
-		}
171
-	}
172
-
173
-	/**
174
-	 * processes results from LDAP for attributes as returned by getAttributesToRead()
175
-	 * @param array $ldapEntry the user entry as retrieved from LDAP
176
-	 */
177
-	public function processAttributes($ldapEntry) {
178
-		$this->markRefreshTime();
179
-		//Quota
180
-		$attr = strtolower($this->connection->ldapQuotaAttribute);
181
-		if(isset($ldapEntry[$attr])) {
182
-			$this->updateQuota($ldapEntry[$attr][0]);
183
-		} else {
184
-			if ($this->connection->ldapQuotaDefault !== '') {
185
-				$this->updateQuota();
186
-			}
187
-		}
188
-		unset($attr);
189
-
190
-		//Email
191
-		$attr = strtolower($this->connection->ldapEmailAttribute);
192
-		if(isset($ldapEntry[$attr])) {
193
-			$this->updateEmail($ldapEntry[$attr][0]);
194
-		}
195
-		unset($attr);
196
-
197
-		//displayName
198
-		$displayName = $displayName2 = '';
199
-		$attr = strtolower($this->connection->ldapUserDisplayName);
200
-		if(isset($ldapEntry[$attr])) {
201
-			$displayName = strval($ldapEntry[$attr][0]);
202
-		}
203
-		$attr = strtolower($this->connection->ldapUserDisplayName2);
204
-		if(isset($ldapEntry[$attr])) {
205
-			$displayName2 = strval($ldapEntry[$attr][0]);
206
-		}
207
-		if ($displayName !== '') {
208
-			$this->composeAndStoreDisplayName($displayName);
209
-			$this->access->cacheUserDisplayName(
210
-				$this->getUsername(),
211
-				$displayName,
212
-				$displayName2
213
-			);
214
-		}
215
-		unset($attr);
216
-
217
-		// LDAP Username, needed for s2s sharing
218
-		if(isset($ldapEntry['uid'])) {
219
-			$this->storeLDAPUserName($ldapEntry['uid'][0]);
220
-		} else if(isset($ldapEntry['samaccountname'])) {
221
-			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
222
-		}
223
-
224
-		//homePath
225
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
226
-			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
227
-			if(isset($ldapEntry[$attr])) {
228
-				$this->access->cacheUserHome(
229
-					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
230
-			}
231
-		}
232
-
233
-		//memberOf groups
234
-		$cacheKey = 'getMemberOf'.$this->getUsername();
235
-		$groups = false;
236
-		if(isset($ldapEntry['memberof'])) {
237
-			$groups = $ldapEntry['memberof'];
238
-		}
239
-		$this->connection->writeToCache($cacheKey, $groups);
240
-
241
-		//Avatar
242
-		$attrs = array('jpegphoto', 'thumbnailphoto');
243
-		foreach ($attrs as $attr)  {
244
-			if(isset($ldapEntry[$attr])) {
245
-				$this->avatarImage = $ldapEntry[$attr][0];
246
-				// the call to the method that saves the avatar in the file
247
-				// system must be postponed after the login. It is to ensure
248
-				// external mounts are mounted properly (e.g. with login
249
-				// credentials from the session).
250
-				\OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
251
-				break;
252
-			}
253
-		}
254
-	}
255
-
256
-	/**
257
-	 * @brief returns the LDAP DN of the user
258
-	 * @return string
259
-	 */
260
-	public function getDN() {
261
-		return $this->dn;
262
-	}
263
-
264
-	/**
265
-	 * @brief returns the Nextcloud internal username of the user
266
-	 * @return string
267
-	 */
268
-	public function getUsername() {
269
-		return $this->uid;
270
-	}
271
-
272
-	/**
273
-	 * returns the home directory of the user if specified by LDAP settings
274
-	 * @param string $valueFromLDAP
275
-	 * @return bool|string
276
-	 * @throws \Exception
277
-	 */
278
-	public function getHomePath($valueFromLDAP = null) {
279
-		$path = strval($valueFromLDAP);
280
-		$attr = null;
281
-
282
-		if (is_null($valueFromLDAP)
283
-		   && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
284
-		   && $this->access->connection->homeFolderNamingRule !== 'attr:')
285
-		{
286
-			$attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
287
-			$homedir = $this->access->readAttribute(
288
-				$this->access->username2dn($this->getUsername()), $attr);
289
-			if ($homedir && isset($homedir[0])) {
290
-				$path = $homedir[0];
291
-			}
292
-		}
293
-
294
-		if ($path !== '') {
295
-			//if attribute's value is an absolute path take this, otherwise append it to data dir
296
-			//check for / at the beginning or pattern c:\ resp. c:/
297
-			if(   '/' !== $path[0]
298
-			   && !(3 < strlen($path) && ctype_alpha($path[0])
299
-			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
300
-			) {
301
-				$path = $this->config->getSystemValue('datadirectory',
302
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
303
-			}
304
-			//we need it to store it in the DB as well in case a user gets
305
-			//deleted so we can clean up afterwards
306
-			$this->config->setUserValue(
307
-				$this->getUsername(), 'user_ldap', 'homePath', $path
308
-			);
309
-			return $path;
310
-		}
311
-
312
-		if(    !is_null($attr)
313
-			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
314
-		) {
315
-			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
316
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
317
-		}
318
-
319
-		//false will apply default behaviour as defined and done by OC_User
320
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
321
-		return false;
322
-	}
323
-
324
-	public function getMemberOfGroups() {
325
-		$cacheKey = 'getMemberOf'.$this->getUsername();
326
-		$memberOfGroups = $this->connection->getFromCache($cacheKey);
327
-		if(!is_null($memberOfGroups)) {
328
-			return $memberOfGroups;
329
-		}
330
-		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
331
-		$this->connection->writeToCache($cacheKey, $groupDNs);
332
-		return $groupDNs;
333
-	}
334
-
335
-	/**
336
-	 * @brief reads the image from LDAP that shall be used as Avatar
337
-	 * @return string data (provided by LDAP) | false
338
-	 */
339
-	public function getAvatarImage() {
340
-		if(!is_null($this->avatarImage)) {
341
-			return $this->avatarImage;
342
-		}
343
-
344
-		$this->avatarImage = false;
345
-		$attributes = array('jpegPhoto', 'thumbnailPhoto');
346
-		foreach($attributes as $attribute) {
347
-			$result = $this->access->readAttribute($this->dn, $attribute);
348
-			if($result !== false && is_array($result) && isset($result[0])) {
349
-				$this->avatarImage = $result[0];
350
-				break;
351
-			}
352
-		}
353
-
354
-		return $this->avatarImage;
355
-	}
356
-
357
-	/**
358
-	 * @brief marks the user as having logged in at least once
359
-	 * @return null
360
-	 */
361
-	public function markLogin() {
362
-		$this->config->setUserValue(
363
-			$this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
364
-	}
365
-
366
-	/**
367
-	 * @brief marks the time when user features like email have been updated
368
-	 * @return null
369
-	 */
370
-	public function markRefreshTime() {
371
-		$this->config->setUserValue(
372
-			$this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
373
-	}
374
-
375
-	/**
376
-	 * @brief checks whether user features needs to be updated again by
377
-	 * comparing the difference of time of the last refresh to now with the
378
-	 * desired interval
379
-	 * @return bool
380
-	 */
381
-	private function needsRefresh() {
382
-		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
383
-			self::USER_PREFKEY_LASTREFRESH, 0);
384
-
385
-		//TODO make interval configurable
386
-		if((time() - intval($lastChecked)) < 86400 ) {
387
-			return false;
388
-		}
389
-		return  true;
390
-	}
391
-
392
-	/**
393
-	 * Stores a key-value pair in relation to this user
394
-	 *
395
-	 * @param string $key
396
-	 * @param string $value
397
-	 */
398
-	private function store($key, $value) {
399
-		$this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
400
-	}
401
-
402
-	/**
403
-	 * Composes the display name and stores it in the database. The final
404
-	 * display name is returned.
405
-	 *
406
-	 * @param string $displayName
407
-	 * @param string $displayName2
408
-	 * @returns string the effective display name
409
-	 */
410
-	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
411
-		$displayName2 = strval($displayName2);
412
-		if($displayName2 !== '') {
413
-			$displayName .= ' (' . $displayName2 . ')';
414
-		}
415
-		$this->store('displayName', $displayName);
416
-		return $displayName;
417
-	}
418
-
419
-	/**
420
-	 * Stores the LDAP Username in the Database
421
-	 * @param string $userName
422
-	 */
423
-	public function storeLDAPUserName($userName) {
424
-		$this->store('uid', $userName);
425
-	}
426
-
427
-	/**
428
-	 * @brief checks whether an update method specified by feature was run
429
-	 * already. If not, it will marked like this, because it is expected that
430
-	 * the method will be run, when false is returned.
431
-	 * @param string $feature email | quota | avatar (can be extended)
432
-	 * @return bool
433
-	 */
434
-	private function wasRefreshed($feature) {
435
-		if(isset($this->refreshedFeatures[$feature])) {
436
-			return true;
437
-		}
438
-		$this->refreshedFeatures[$feature] = 1;
439
-		return false;
440
-	}
441
-
442
-	/**
443
-	 * fetches the email from LDAP and stores it as Nextcloud user value
444
-	 * @param string $valueFromLDAP if known, to save an LDAP read request
445
-	 * @return null
446
-	 */
447
-	public function updateEmail($valueFromLDAP = null) {
448
-		if($this->wasRefreshed('email')) {
449
-			return;
450
-		}
451
-		$email = strval($valueFromLDAP);
452
-		if(is_null($valueFromLDAP)) {
453
-			$emailAttribute = $this->connection->ldapEmailAttribute;
454
-			if ($emailAttribute !== '') {
455
-				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
456
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
457
-					$email = strval($aEmail[0]);
458
-				}
459
-			}
460
-		}
461
-		if ($email !== '') {
462
-			$user = $this->userManager->get($this->uid);
463
-			if (!is_null($user)) {
464
-				$currentEmail = strval($user->getEMailAddress());
465
-				if ($currentEmail !== $email) {
466
-					$user->setEMailAddress($email);
467
-				}
468
-			}
469
-		}
470
-	}
471
-
472
-	/**
473
-	 * Overall process goes as follow:
474
-	 * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
475
-	 * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
476
-	 * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
477
-	 * 4. check if the target user exists and set the quota for the user.
478
-	 *
479
-	 * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
480
-	 * parameter can be passed with the value of the attribute. This value will be considered as the
481
-	 * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
482
-	 * fetch all the user's attributes in one call and use the fetched values in this function.
483
-	 * The expected value for that parameter is a string describing the quota for the user. Valid
484
-	 * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
485
-	 * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
486
-	 *
487
-	 * fetches the quota from LDAP and stores it as Nextcloud user value
488
-	 * @param string $valueFromLDAP the quota attribute's value can be passed,
489
-	 * to save the readAttribute request
490
-	 * @return null
491
-	 */
492
-	public function updateQuota($valueFromLDAP = null) {
493
-		if($this->wasRefreshed('quota')) {
494
-			return;
495
-		}
496
-
497
-		$quota = false;
498
-		if(is_null($valueFromLDAP)) {
499
-			$quotaAttribute = $this->connection->ldapQuotaAttribute;
500
-			if ($quotaAttribute !== '') {
501
-				$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
502
-				if($aQuota && (count($aQuota) > 0)) {
503
-					if ($this->verifyQuotaValue($aQuota[0])) {
504
-						$quota = $aQuota[0];
505
-					} else {
506
-						$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
507
-					}
508
-				}
509
-			}
510
-		} else {
511
-			if ($this->verifyQuotaValue($valueFromLDAP)) {
512
-				$quota = $valueFromLDAP;
513
-			} else {
514
-				$this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
515
-			}
516
-		}
517
-
518
-		if ($quota === false) {
519
-			// quota not found using the LDAP attribute (or not parseable). Try the default quota
520
-			$defaultQuota = $this->connection->ldapQuotaDefault;
521
-			if ($this->verifyQuotaValue($defaultQuota)) {
522
-				$quota = $defaultQuota;
523
-			}
524
-		}
525
-
526
-		$targetUser = $this->userManager->get($this->uid);
527
-		if ($targetUser) {
528
-			if($quota !== false) {
529
-				$targetUser->setQuota($quota);
530
-			} else {
531
-				$this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
532
-				$targetUser->setQuota('default');
533
-			}
534
-		} else {
535
-			$this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
536
-		}
537
-	}
538
-
539
-	private function verifyQuotaValue($quotaValue) {
540
-		return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
541
-	}
542
-
543
-	/**
544
-	 * called by a post_login hook to save the avatar picture
545
-	 *
546
-	 * @param array $params
547
-	 */
548
-	public function updateAvatarPostLogin($params) {
549
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
550
-			$this->updateAvatar();
551
-		}
552
-	}
553
-
554
-	/**
555
-	 * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
556
-	 * @return null
557
-	 */
558
-	public function updateAvatar() {
559
-		if($this->wasRefreshed('avatar')) {
560
-			return;
561
-		}
562
-		$avatarImage = $this->getAvatarImage();
563
-		if($avatarImage === false) {
564
-			//not set, nothing left to do;
565
-			return;
566
-		}
567
-		$this->image->loadFromBase64(base64_encode($avatarImage));
568
-		$this->setOwnCloudAvatar();
569
-	}
570
-
571
-	/**
572
-	 * @brief sets an image as Nextcloud avatar
573
-	 * @return null
574
-	 */
575
-	private function setOwnCloudAvatar() {
576
-		if(!$this->image->valid()) {
577
-			$this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
578
-			return;
579
-		}
580
-		//make sure it is a square and not bigger than 128x128
581
-		$size = min(array($this->image->width(), $this->image->height(), 128));
582
-		if(!$this->image->centerCrop($size)) {
583
-			$this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
584
-			return;
585
-		}
586
-
587
-		if(!$this->fs->isLoaded()) {
588
-			$this->fs->setup($this->uid);
589
-		}
590
-
591
-		try {
592
-			$avatar = $this->avatarManager->getAvatar($this->uid);
593
-			$avatar->set($this->image);
594
-		} catch (\Exception $e) {
595
-			\OC::$server->getLogger()->notice(
596
-				'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
597
-				['app' => 'user_ldap']);
598
-		}
599
-	}
600
-
601
-	/**
602
-	 * called by a post_login hook to handle password expiry
603
-	 *
604
-	 * @param array $params
605
-	 */
606
-	public function handlePasswordExpiry($params) {
607
-		$ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
608
-		if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
609
-			return;//password expiry handling disabled
610
-		}
611
-		$uid = $params['uid'];
612
-		if(isset($uid) && $uid === $this->getUsername()) {
613
-			//retrieve relevant user attributes
614
-			$result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
124
+        if ($username === null) {
125
+            $log->log("uid for '$dn' must not be null!", Util::ERROR);
126
+            throw new \InvalidArgumentException('uid must not be null!');
127
+        } else if ($username === '') {
128
+            $log->log("uid for '$dn' must not be an empty string", Util::ERROR);
129
+            throw new \InvalidArgumentException('uid must not be an empty string!');
130
+        }
131
+
132
+        $this->access              = $access;
133
+        $this->connection          = $access->getConnection();
134
+        $this->config              = $config;
135
+        $this->fs                  = $fs;
136
+        $this->dn                  = $dn;
137
+        $this->uid                 = $username;
138
+        $this->image               = $image;
139
+        $this->log                 = $log;
140
+        $this->avatarManager       = $avatarManager;
141
+        $this->userManager         = $userManager;
142
+        $this->notificationManager = $notificationManager;
143
+
144
+        \OCP\Util::connectHook('OC_User', 'post_login', $this, 'handlePasswordExpiry');
145
+    }
146
+
147
+    /**
148
+     * @brief updates properties like email, quota or avatar provided by LDAP
149
+     * @return null
150
+     */
151
+    public function update() {
152
+        if(is_null($this->dn)) {
153
+            return null;
154
+        }
155
+
156
+        $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
157
+                self::USER_PREFKEY_FIRSTLOGIN, 0);
158
+
159
+        if($this->needsRefresh()) {
160
+            $this->updateEmail();
161
+            $this->updateQuota();
162
+            if($hasLoggedIn !== 0) {
163
+                //we do not need to try it, when the user has not been logged in
164
+                //before, because the file system will not be ready.
165
+                $this->updateAvatar();
166
+                //in order to get an avatar as soon as possible, mark the user
167
+                //as refreshed only when updating the avatar did happen
168
+                $this->markRefreshTime();
169
+            }
170
+        }
171
+    }
172
+
173
+    /**
174
+     * processes results from LDAP for attributes as returned by getAttributesToRead()
175
+     * @param array $ldapEntry the user entry as retrieved from LDAP
176
+     */
177
+    public function processAttributes($ldapEntry) {
178
+        $this->markRefreshTime();
179
+        //Quota
180
+        $attr = strtolower($this->connection->ldapQuotaAttribute);
181
+        if(isset($ldapEntry[$attr])) {
182
+            $this->updateQuota($ldapEntry[$attr][0]);
183
+        } else {
184
+            if ($this->connection->ldapQuotaDefault !== '') {
185
+                $this->updateQuota();
186
+            }
187
+        }
188
+        unset($attr);
189
+
190
+        //Email
191
+        $attr = strtolower($this->connection->ldapEmailAttribute);
192
+        if(isset($ldapEntry[$attr])) {
193
+            $this->updateEmail($ldapEntry[$attr][0]);
194
+        }
195
+        unset($attr);
196
+
197
+        //displayName
198
+        $displayName = $displayName2 = '';
199
+        $attr = strtolower($this->connection->ldapUserDisplayName);
200
+        if(isset($ldapEntry[$attr])) {
201
+            $displayName = strval($ldapEntry[$attr][0]);
202
+        }
203
+        $attr = strtolower($this->connection->ldapUserDisplayName2);
204
+        if(isset($ldapEntry[$attr])) {
205
+            $displayName2 = strval($ldapEntry[$attr][0]);
206
+        }
207
+        if ($displayName !== '') {
208
+            $this->composeAndStoreDisplayName($displayName);
209
+            $this->access->cacheUserDisplayName(
210
+                $this->getUsername(),
211
+                $displayName,
212
+                $displayName2
213
+            );
214
+        }
215
+        unset($attr);
216
+
217
+        // LDAP Username, needed for s2s sharing
218
+        if(isset($ldapEntry['uid'])) {
219
+            $this->storeLDAPUserName($ldapEntry['uid'][0]);
220
+        } else if(isset($ldapEntry['samaccountname'])) {
221
+            $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
222
+        }
223
+
224
+        //homePath
225
+        if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
226
+            $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
227
+            if(isset($ldapEntry[$attr])) {
228
+                $this->access->cacheUserHome(
229
+                    $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
230
+            }
231
+        }
232
+
233
+        //memberOf groups
234
+        $cacheKey = 'getMemberOf'.$this->getUsername();
235
+        $groups = false;
236
+        if(isset($ldapEntry['memberof'])) {
237
+            $groups = $ldapEntry['memberof'];
238
+        }
239
+        $this->connection->writeToCache($cacheKey, $groups);
240
+
241
+        //Avatar
242
+        $attrs = array('jpegphoto', 'thumbnailphoto');
243
+        foreach ($attrs as $attr)  {
244
+            if(isset($ldapEntry[$attr])) {
245
+                $this->avatarImage = $ldapEntry[$attr][0];
246
+                // the call to the method that saves the avatar in the file
247
+                // system must be postponed after the login. It is to ensure
248
+                // external mounts are mounted properly (e.g. with login
249
+                // credentials from the session).
250
+                \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
251
+                break;
252
+            }
253
+        }
254
+    }
255
+
256
+    /**
257
+     * @brief returns the LDAP DN of the user
258
+     * @return string
259
+     */
260
+    public function getDN() {
261
+        return $this->dn;
262
+    }
263
+
264
+    /**
265
+     * @brief returns the Nextcloud internal username of the user
266
+     * @return string
267
+     */
268
+    public function getUsername() {
269
+        return $this->uid;
270
+    }
271
+
272
+    /**
273
+     * returns the home directory of the user if specified by LDAP settings
274
+     * @param string $valueFromLDAP
275
+     * @return bool|string
276
+     * @throws \Exception
277
+     */
278
+    public function getHomePath($valueFromLDAP = null) {
279
+        $path = strval($valueFromLDAP);
280
+        $attr = null;
281
+
282
+        if (is_null($valueFromLDAP)
283
+           && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
284
+           && $this->access->connection->homeFolderNamingRule !== 'attr:')
285
+        {
286
+            $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
287
+            $homedir = $this->access->readAttribute(
288
+                $this->access->username2dn($this->getUsername()), $attr);
289
+            if ($homedir && isset($homedir[0])) {
290
+                $path = $homedir[0];
291
+            }
292
+        }
293
+
294
+        if ($path !== '') {
295
+            //if attribute's value is an absolute path take this, otherwise append it to data dir
296
+            //check for / at the beginning or pattern c:\ resp. c:/
297
+            if(   '/' !== $path[0]
298
+               && !(3 < strlen($path) && ctype_alpha($path[0])
299
+                   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
300
+            ) {
301
+                $path = $this->config->getSystemValue('datadirectory',
302
+                        \OC::$SERVERROOT.'/data' ) . '/' . $path;
303
+            }
304
+            //we need it to store it in the DB as well in case a user gets
305
+            //deleted so we can clean up afterwards
306
+            $this->config->setUserValue(
307
+                $this->getUsername(), 'user_ldap', 'homePath', $path
308
+            );
309
+            return $path;
310
+        }
311
+
312
+        if(    !is_null($attr)
313
+            && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
314
+        ) {
315
+            // a naming rule attribute is defined, but it doesn't exist for that LDAP user
316
+            throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
317
+        }
318
+
319
+        //false will apply default behaviour as defined and done by OC_User
320
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
321
+        return false;
322
+    }
323
+
324
+    public function getMemberOfGroups() {
325
+        $cacheKey = 'getMemberOf'.$this->getUsername();
326
+        $memberOfGroups = $this->connection->getFromCache($cacheKey);
327
+        if(!is_null($memberOfGroups)) {
328
+            return $memberOfGroups;
329
+        }
330
+        $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
331
+        $this->connection->writeToCache($cacheKey, $groupDNs);
332
+        return $groupDNs;
333
+    }
334
+
335
+    /**
336
+     * @brief reads the image from LDAP that shall be used as Avatar
337
+     * @return string data (provided by LDAP) | false
338
+     */
339
+    public function getAvatarImage() {
340
+        if(!is_null($this->avatarImage)) {
341
+            return $this->avatarImage;
342
+        }
343
+
344
+        $this->avatarImage = false;
345
+        $attributes = array('jpegPhoto', 'thumbnailPhoto');
346
+        foreach($attributes as $attribute) {
347
+            $result = $this->access->readAttribute($this->dn, $attribute);
348
+            if($result !== false && is_array($result) && isset($result[0])) {
349
+                $this->avatarImage = $result[0];
350
+                break;
351
+            }
352
+        }
353
+
354
+        return $this->avatarImage;
355
+    }
356
+
357
+    /**
358
+     * @brief marks the user as having logged in at least once
359
+     * @return null
360
+     */
361
+    public function markLogin() {
362
+        $this->config->setUserValue(
363
+            $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
364
+    }
365
+
366
+    /**
367
+     * @brief marks the time when user features like email have been updated
368
+     * @return null
369
+     */
370
+    public function markRefreshTime() {
371
+        $this->config->setUserValue(
372
+            $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
373
+    }
374
+
375
+    /**
376
+     * @brief checks whether user features needs to be updated again by
377
+     * comparing the difference of time of the last refresh to now with the
378
+     * desired interval
379
+     * @return bool
380
+     */
381
+    private function needsRefresh() {
382
+        $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
383
+            self::USER_PREFKEY_LASTREFRESH, 0);
384
+
385
+        //TODO make interval configurable
386
+        if((time() - intval($lastChecked)) < 86400 ) {
387
+            return false;
388
+        }
389
+        return  true;
390
+    }
391
+
392
+    /**
393
+     * Stores a key-value pair in relation to this user
394
+     *
395
+     * @param string $key
396
+     * @param string $value
397
+     */
398
+    private function store($key, $value) {
399
+        $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
400
+    }
401
+
402
+    /**
403
+     * Composes the display name and stores it in the database. The final
404
+     * display name is returned.
405
+     *
406
+     * @param string $displayName
407
+     * @param string $displayName2
408
+     * @returns string the effective display name
409
+     */
410
+    public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
411
+        $displayName2 = strval($displayName2);
412
+        if($displayName2 !== '') {
413
+            $displayName .= ' (' . $displayName2 . ')';
414
+        }
415
+        $this->store('displayName', $displayName);
416
+        return $displayName;
417
+    }
418
+
419
+    /**
420
+     * Stores the LDAP Username in the Database
421
+     * @param string $userName
422
+     */
423
+    public function storeLDAPUserName($userName) {
424
+        $this->store('uid', $userName);
425
+    }
426
+
427
+    /**
428
+     * @brief checks whether an update method specified by feature was run
429
+     * already. If not, it will marked like this, because it is expected that
430
+     * the method will be run, when false is returned.
431
+     * @param string $feature email | quota | avatar (can be extended)
432
+     * @return bool
433
+     */
434
+    private function wasRefreshed($feature) {
435
+        if(isset($this->refreshedFeatures[$feature])) {
436
+            return true;
437
+        }
438
+        $this->refreshedFeatures[$feature] = 1;
439
+        return false;
440
+    }
441
+
442
+    /**
443
+     * fetches the email from LDAP and stores it as Nextcloud user value
444
+     * @param string $valueFromLDAP if known, to save an LDAP read request
445
+     * @return null
446
+     */
447
+    public function updateEmail($valueFromLDAP = null) {
448
+        if($this->wasRefreshed('email')) {
449
+            return;
450
+        }
451
+        $email = strval($valueFromLDAP);
452
+        if(is_null($valueFromLDAP)) {
453
+            $emailAttribute = $this->connection->ldapEmailAttribute;
454
+            if ($emailAttribute !== '') {
455
+                $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
456
+                if(is_array($aEmail) && (count($aEmail) > 0)) {
457
+                    $email = strval($aEmail[0]);
458
+                }
459
+            }
460
+        }
461
+        if ($email !== '') {
462
+            $user = $this->userManager->get($this->uid);
463
+            if (!is_null($user)) {
464
+                $currentEmail = strval($user->getEMailAddress());
465
+                if ($currentEmail !== $email) {
466
+                    $user->setEMailAddress($email);
467
+                }
468
+            }
469
+        }
470
+    }
471
+
472
+    /**
473
+     * Overall process goes as follow:
474
+     * 1. fetch the quota from LDAP and check if it's parseable with the "verifyQuotaValue" function
475
+     * 2. if the value can't be fetched, is empty or not parseable, use the default LDAP quota
476
+     * 3. if the default LDAP quota can't be parsed, use the Nextcloud's default quota (use 'default')
477
+     * 4. check if the target user exists and set the quota for the user.
478
+     *
479
+     * In order to improve performance and prevent an unwanted extra LDAP call, the $valueFromLDAP
480
+     * parameter can be passed with the value of the attribute. This value will be considered as the
481
+     * quota for the user coming from the LDAP server (step 1 of the process) It can be useful to
482
+     * fetch all the user's attributes in one call and use the fetched values in this function.
483
+     * The expected value for that parameter is a string describing the quota for the user. Valid
484
+     * values are 'none' (unlimited), 'default' (the Nextcloud's default quota), '1234' (quota in
485
+     * bytes), '1234 MB' (quota in MB - check the \OC_Helper::computerFileSize method for more info)
486
+     *
487
+     * fetches the quota from LDAP and stores it as Nextcloud user value
488
+     * @param string $valueFromLDAP the quota attribute's value can be passed,
489
+     * to save the readAttribute request
490
+     * @return null
491
+     */
492
+    public function updateQuota($valueFromLDAP = null) {
493
+        if($this->wasRefreshed('quota')) {
494
+            return;
495
+        }
496
+
497
+        $quota = false;
498
+        if(is_null($valueFromLDAP)) {
499
+            $quotaAttribute = $this->connection->ldapQuotaAttribute;
500
+            if ($quotaAttribute !== '') {
501
+                $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
502
+                if($aQuota && (count($aQuota) > 0)) {
503
+                    if ($this->verifyQuotaValue($aQuota[0])) {
504
+                        $quota = $aQuota[0];
505
+                    } else {
506
+                        $this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $aQuota[0] . ']', \OCP\Util::WARN);
507
+                    }
508
+                }
509
+            }
510
+        } else {
511
+            if ($this->verifyQuotaValue($valueFromLDAP)) {
512
+                $quota = $valueFromLDAP;
513
+            } else {
514
+                $this->log->log('not suitable LDAP quota found for user ' . $this->uid . ': [' . $valueFromLDAP . ']', \OCP\Util::WARN);
515
+            }
516
+        }
517
+
518
+        if ($quota === false) {
519
+            // quota not found using the LDAP attribute (or not parseable). Try the default quota
520
+            $defaultQuota = $this->connection->ldapQuotaDefault;
521
+            if ($this->verifyQuotaValue($defaultQuota)) {
522
+                $quota = $defaultQuota;
523
+            }
524
+        }
525
+
526
+        $targetUser = $this->userManager->get($this->uid);
527
+        if ($targetUser) {
528
+            if($quota !== false) {
529
+                $targetUser->setQuota($quota);
530
+            } else {
531
+                $this->log->log('not suitable default quota found for user ' . $this->uid . ': [' . $defaultQuota . ']', \OCP\Util::WARN);
532
+                $targetUser->setQuota('default');
533
+            }
534
+        } else {
535
+            $this->log->log('trying to set a quota for user ' . $this->uid . ' but the user is missing', \OCP\Util::ERROR);
536
+        }
537
+    }
538
+
539
+    private function verifyQuotaValue($quotaValue) {
540
+        return $quotaValue === 'none' || $quotaValue === 'default' || \OC_Helper::computerFileSize($quotaValue) !== false;
541
+    }
542
+
543
+    /**
544
+     * called by a post_login hook to save the avatar picture
545
+     *
546
+     * @param array $params
547
+     */
548
+    public function updateAvatarPostLogin($params) {
549
+        if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
550
+            $this->updateAvatar();
551
+        }
552
+    }
553
+
554
+    /**
555
+     * @brief attempts to get an image from LDAP and sets it as Nextcloud avatar
556
+     * @return null
557
+     */
558
+    public function updateAvatar() {
559
+        if($this->wasRefreshed('avatar')) {
560
+            return;
561
+        }
562
+        $avatarImage = $this->getAvatarImage();
563
+        if($avatarImage === false) {
564
+            //not set, nothing left to do;
565
+            return;
566
+        }
567
+        $this->image->loadFromBase64(base64_encode($avatarImage));
568
+        $this->setOwnCloudAvatar();
569
+    }
570
+
571
+    /**
572
+     * @brief sets an image as Nextcloud avatar
573
+     * @return null
574
+     */
575
+    private function setOwnCloudAvatar() {
576
+        if(!$this->image->valid()) {
577
+            $this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
578
+            return;
579
+        }
580
+        //make sure it is a square and not bigger than 128x128
581
+        $size = min(array($this->image->width(), $this->image->height(), 128));
582
+        if(!$this->image->centerCrop($size)) {
583
+            $this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
584
+            return;
585
+        }
586
+
587
+        if(!$this->fs->isLoaded()) {
588
+            $this->fs->setup($this->uid);
589
+        }
590
+
591
+        try {
592
+            $avatar = $this->avatarManager->getAvatar($this->uid);
593
+            $avatar->set($this->image);
594
+        } catch (\Exception $e) {
595
+            \OC::$server->getLogger()->notice(
596
+                'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
597
+                ['app' => 'user_ldap']);
598
+        }
599
+    }
600
+
601
+    /**
602
+     * called by a post_login hook to handle password expiry
603
+     *
604
+     * @param array $params
605
+     */
606
+    public function handlePasswordExpiry($params) {
607
+        $ppolicyDN = $this->connection->ldapDefaultPPolicyDN;
608
+        if (empty($ppolicyDN) || (intval($this->connection->turnOnPasswordChange) !== 1)) {
609
+            return;//password expiry handling disabled
610
+        }
611
+        $uid = $params['uid'];
612
+        if(isset($uid) && $uid === $this->getUsername()) {
613
+            //retrieve relevant user attributes
614
+            $result = $this->access->search('objectclass=*', $this->dn, ['pwdpolicysubentry', 'pwdgraceusetime', 'pwdreset', 'pwdchangedtime']);
615 615
 			
616
-			if(array_key_exists('pwdpolicysubentry', $result[0])) {
617
-				$pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
618
-				if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
619
-					$ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
620
-				}
621
-			}
616
+            if(array_key_exists('pwdpolicysubentry', $result[0])) {
617
+                $pwdPolicySubentry = $result[0]['pwdpolicysubentry'];
618
+                if($pwdPolicySubentry && (count($pwdPolicySubentry) > 0)){
619
+                    $ppolicyDN = $pwdPolicySubentry[0];//custom ppolicy DN
620
+                }
621
+            }
622 622
 			
623
-			$pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : null;
624
-			$pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : null;
625
-			$pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
623
+            $pwdGraceUseTime = array_key_exists('pwdgraceusetime', $result[0]) ? $result[0]['pwdgraceusetime'] : null;
624
+            $pwdReset = array_key_exists('pwdreset', $result[0]) ? $result[0]['pwdreset'] : null;
625
+            $pwdChangedTime = array_key_exists('pwdchangedtime', $result[0]) ? $result[0]['pwdchangedtime'] : null;
626 626
 			
627
-			//retrieve relevant password policy attributes
628
-			$cacheKey = 'ppolicyAttributes' . $ppolicyDN;
629
-			$result = $this->connection->getFromCache($cacheKey);
630
-			if(is_null($result)) {
631
-				$result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
632
-				$this->connection->writeToCache($cacheKey, $result);
633
-			}
627
+            //retrieve relevant password policy attributes
628
+            $cacheKey = 'ppolicyAttributes' . $ppolicyDN;
629
+            $result = $this->connection->getFromCache($cacheKey);
630
+            if(is_null($result)) {
631
+                $result = $this->access->search('objectclass=*', $ppolicyDN, ['pwdgraceauthnlimit', 'pwdmaxage', 'pwdexpirewarning']);
632
+                $this->connection->writeToCache($cacheKey, $result);
633
+            }
634 634
 			
635
-			$pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : null;
636
-			$pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : null;
637
-			$pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : null;
635
+            $pwdGraceAuthNLimit = array_key_exists('pwdgraceauthnlimit', $result[0]) ? $result[0]['pwdgraceauthnlimit'] : null;
636
+            $pwdMaxAge = array_key_exists('pwdmaxage', $result[0]) ? $result[0]['pwdmaxage'] : null;
637
+            $pwdExpireWarning = array_key_exists('pwdexpirewarning', $result[0]) ? $result[0]['pwdexpirewarning'] : null;
638 638
 			
639
-			//handle grace login
640
-			$pwdGraceUseTimeCount = count($pwdGraceUseTime);
641
-			if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
642
-				if($pwdGraceAuthNLimit 
643
-					&& (count($pwdGraceAuthNLimit) > 0)
644
-					&&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
645
-					$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
646
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
647
-					'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
648
-				} else { //no more grace login available
649
-					header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
650
-					'user_ldap.renewPassword.showLoginFormInvalidPassword', array('user' => $uid)));
651
-				}
652
-				exit();
653
-			}
654
-			//handle pwdReset attribute
655
-			if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
656
-				$this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
657
-				header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
658
-				'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
659
-				exit();
660
-			}
661
-			//handle password expiry warning
662
-			if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
663
-				if($pwdMaxAge && (count($pwdMaxAge) > 0)
664
-					&& $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
665
-					$pwdMaxAgeInt = intval($pwdMaxAge[0]);
666
-					$pwdExpireWarningInt = intval($pwdExpireWarning[0]);
667
-					if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
668
-						$pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
669
-						$pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
670
-						$currentDateTime = new \DateTime();
671
-						$secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
672
-						if($secondsToExpiry <= $pwdExpireWarningInt) {
673
-							//remove last password expiry warning if any
674
-							$notification = $this->notificationManager->createNotification();
675
-							$notification->setApp('user_ldap')
676
-								->setUser($uid)
677
-								->setObject('pwd_exp_warn', $uid)
678
-							;
679
-							$this->notificationManager->markProcessed($notification);
680
-							//create new password expiry warning
681
-							$notification = $this->notificationManager->createNotification();
682
-							$notification->setApp('user_ldap')
683
-								->setUser($uid)
684
-								->setDateTime($currentDateTime)
685
-								->setObject('pwd_exp_warn', $uid) 
686
-								->setSubject('pwd_exp_warn_days', [strval(ceil($secondsToExpiry / 60 / 60 / 24))])
687
-							;
688
-							$this->notificationManager->notify($notification);
689
-						}
690
-					}
691
-				}
692
-			}
693
-		}
694
-	}
639
+            //handle grace login
640
+            $pwdGraceUseTimeCount = count($pwdGraceUseTime);
641
+            if($pwdGraceUseTime && $pwdGraceUseTimeCount > 0) { //was this a grace login?
642
+                if($pwdGraceAuthNLimit 
643
+                    && (count($pwdGraceAuthNLimit) > 0)
644
+                    &&($pwdGraceUseTimeCount < intval($pwdGraceAuthNLimit[0]))) { //at least one more grace login available?
645
+                    $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
646
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
647
+                    'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
648
+                } else { //no more grace login available
649
+                    header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
650
+                    'user_ldap.renewPassword.showLoginFormInvalidPassword', array('user' => $uid)));
651
+                }
652
+                exit();
653
+            }
654
+            //handle pwdReset attribute
655
+            if($pwdReset && (count($pwdReset) > 0) && $pwdReset[0] === 'TRUE') { //user must change his password
656
+                $this->config->setUserValue($uid, 'user_ldap', 'needsPasswordReset', 'true');
657
+                header('Location: '.\OC::$server->getURLGenerator()->linkToRouteAbsolute(
658
+                'user_ldap.renewPassword.showRenewPasswordForm', array('user' => $uid)));
659
+                exit();
660
+            }
661
+            //handle password expiry warning
662
+            if($pwdChangedTime && (count($pwdChangedTime) > 0)) {
663
+                if($pwdMaxAge && (count($pwdMaxAge) > 0)
664
+                    && $pwdExpireWarning && (count($pwdExpireWarning) > 0)) {
665
+                    $pwdMaxAgeInt = intval($pwdMaxAge[0]);
666
+                    $pwdExpireWarningInt = intval($pwdExpireWarning[0]);
667
+                    if($pwdMaxAgeInt > 0 && $pwdExpireWarningInt > 0){
668
+                        $pwdChangedTimeDt = \DateTime::createFromFormat('YmdHisZ', $pwdChangedTime[0]);
669
+                        $pwdChangedTimeDt->add(new \DateInterval('PT'.$pwdMaxAgeInt.'S'));
670
+                        $currentDateTime = new \DateTime();
671
+                        $secondsToExpiry = $pwdChangedTimeDt->getTimestamp() - $currentDateTime->getTimestamp();
672
+                        if($secondsToExpiry <= $pwdExpireWarningInt) {
673
+                            //remove last password expiry warning if any
674
+                            $notification = $this->notificationManager->createNotification();
675
+                            $notification->setApp('user_ldap')
676
+                                ->setUser($uid)
677
+                                ->setObject('pwd_exp_warn', $uid)
678
+                            ;
679
+                            $this->notificationManager->markProcessed($notification);
680
+                            //create new password expiry warning
681
+                            $notification = $this->notificationManager->createNotification();
682
+                            $notification->setApp('user_ldap')
683
+                                ->setUser($uid)
684
+                                ->setDateTime($currentDateTime)
685
+                                ->setObject('pwd_exp_warn', $uid) 
686
+                                ->setSubject('pwd_exp_warn_days', [strval(ceil($secondsToExpiry / 60 / 60 / 24))])
687
+                            ;
688
+                            $this->notificationManager->notify($notification);
689
+                        }
690
+                    }
691
+                }
692
+            }
693
+        }
694
+    }
695 695
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/Manager.php 1 patch
Indentation   +204 added lines, -204 removed lines patch added patch discarded remove patch
@@ -43,209 +43,209 @@
 block discarded – undo
43 43
  * cache
44 44
  */
45 45
 class Manager {
46
-	/** @var IUserTools */
47
-	protected $access;
48
-
49
-	/** @var IConfig */
50
-	protected $ocConfig;
51
-
52
-	/** @var IDBConnection */
53
-	protected $db;
54
-
55
-	/** @var IUserManager */
56
-	protected $userManager;
57
-
58
-	/** @var INotificationManager */
59
-	protected $notificationManager;
60
-
61
-	/** @var FilesystemHelper */
62
-	protected $ocFilesystem;
63
-
64
-	/** @var LogWrapper */
65
-	protected $ocLog;
66
-
67
-	/** @var Image */
68
-	protected $image;
69
-
70
-	/** @param \OCP\IAvatarManager */
71
-	protected $avatarManager;
72
-
73
-	/**
74
-	 * @var CappedMemoryCache $usersByDN
75
-	 */
76
-	protected $usersByDN;
77
-	/**
78
-	 * @var CappedMemoryCache $usersByUid
79
-	 */
80
-	protected $usersByUid;
81
-
82
-	/**
83
-	 * @param IConfig $ocConfig
84
-	 * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
85
-	 * gives access to necessary functions from the OC filesystem
86
-	 * @param  \OCA\User_LDAP\LogWrapper $ocLog
87
-	 * @param IAvatarManager $avatarManager
88
-	 * @param Image $image an empty image instance
89
-	 * @param IDBConnection $db
90
-	 * @throws \Exception when the methods mentioned above do not exist
91
-	 */
92
-	public function __construct(IConfig $ocConfig,
93
-								FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
94
-								IAvatarManager $avatarManager, Image $image,
95
-								IDBConnection $db, IUserManager $userManager,
96
-								INotificationManager $notificationManager) {
97
-
98
-		$this->ocConfig            = $ocConfig;
99
-		$this->ocFilesystem        = $ocFilesystem;
100
-		$this->ocLog               = $ocLog;
101
-		$this->avatarManager       = $avatarManager;
102
-		$this->image               = $image;
103
-		$this->db                  = $db;
104
-		$this->userManager         = $userManager;
105
-		$this->notificationManager = $notificationManager;
106
-		$this->usersByDN           = new CappedMemoryCache();
107
-		$this->usersByUid          = new CappedMemoryCache();
108
-	}
109
-
110
-	/**
111
-	 * @brief binds manager to an instance of IUserTools (implemented by
112
-	 * Access). It needs to be assigned first before the manager can be used.
113
-	 * @param IUserTools
114
-	 */
115
-	public function setLdapAccess(IUserTools $access) {
116
-		$this->access = $access;
117
-	}
118
-
119
-	/**
120
-	 * @brief creates an instance of User and caches (just runtime) it in the
121
-	 * property array
122
-	 * @param string $dn the DN of the user
123
-	 * @param string $uid the internal (owncloud) username
124
-	 * @return \OCA\User_LDAP\User\User
125
-	 */
126
-	private function createAndCache($dn, $uid) {
127
-		$this->checkAccess();
128
-		$user = new User($uid, $dn, $this->access, $this->ocConfig,
129
-			$this->ocFilesystem, clone $this->image, $this->ocLog,
130
-			$this->avatarManager, $this->userManager, 
131
-			$this->notificationManager);
132
-		$this->usersByDN[$dn]   = $user;
133
-		$this->usersByUid[$uid] = $user;
134
-		return $user;
135
-	}
136
-
137
-	/**
138
-	 * @brief checks whether the Access instance has been set
139
-	 * @throws \Exception if Access has not been set
140
-	 * @return null
141
-	 */
142
-	private function checkAccess() {
143
-		if(is_null($this->access)) {
144
-			throw new \Exception('LDAP Access instance must be set first');
145
-		}
146
-	}
147
-
148
-	/**
149
-	 * returns a list of attributes that will be processed further, e.g. quota,
150
-	 * email, displayname, or others.
151
-	 * @param bool $minimal - optional, set to true to skip attributes with big
152
-	 * payload
153
-	 * @return string[]
154
-	 */
155
-	public function getAttributes($minimal = false) {
156
-		$attributes = array('dn', 'uid', 'samaccountname', 'memberof');
157
-		$possible = array(
158
-			$this->access->getConnection()->ldapQuotaAttribute,
159
-			$this->access->getConnection()->ldapEmailAttribute,
160
-			$this->access->getConnection()->ldapUserDisplayName,
161
-			$this->access->getConnection()->ldapUserDisplayName2,
162
-		);
163
-		foreach($possible as $attr) {
164
-			if(!is_null($attr)) {
165
-				$attributes[] = $attr;
166
-			}
167
-		}
168
-
169
-		$homeRule = $this->access->getConnection()->homeFolderNamingRule;
170
-		if(strpos($homeRule, 'attr:') === 0) {
171
-			$attributes[] = substr($homeRule, strlen('attr:'));
172
-		}
173
-
174
-		if(!$minimal) {
175
-			// attributes that are not really important but may come with big
176
-			// payload.
177
-			$attributes = array_merge($attributes, array(
178
-				'jpegphoto',
179
-				'thumbnailphoto'
180
-			));
181
-		}
182
-
183
-		return $attributes;
184
-	}
185
-
186
-	/**
187
-	 * Checks whether the specified user is marked as deleted
188
-	 * @param string $id the Nextcloud user name
189
-	 * @return bool
190
-	 */
191
-	public function isDeletedUser($id) {
192
-		$isDeleted = $this->ocConfig->getUserValue(
193
-			$id, 'user_ldap', 'isDeleted', 0);
194
-		return intval($isDeleted) === 1;
195
-	}
196
-
197
-	/**
198
-	 * creates and returns an instance of OfflineUser for the specified user
199
-	 * @param string $id
200
-	 * @return \OCA\User_LDAP\User\OfflineUser
201
-	 */
202
-	public function getDeletedUser($id) {
203
-		return new OfflineUser(
204
-			$id,
205
-			$this->ocConfig,
206
-			$this->db,
207
-			$this->access->getUserMapper());
208
-	}
209
-
210
-	/**
211
-	 * @brief returns a User object by it's Nextcloud username
212
-	 * @param string $id the DN or username of the user
213
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
214
-	 */
215
-	protected function createInstancyByUserName($id) {
216
-		//most likely a uid. Check whether it is a deleted user
217
-		if($this->isDeletedUser($id)) {
218
-			return $this->getDeletedUser($id);
219
-		}
220
-		$dn = $this->access->username2dn($id);
221
-		if($dn !== false) {
222
-			return $this->createAndCache($dn, $id);
223
-		}
224
-		return null;
225
-	}
226
-
227
-	/**
228
-	 * @brief returns a User object by it's DN or Nextcloud username
229
-	 * @param string $id the DN or username of the user
230
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
231
-	 * @throws \Exception when connection could not be established
232
-	 */
233
-	public function get($id) {
234
-		$this->checkAccess();
235
-		if(isset($this->usersByDN[$id])) {
236
-			return $this->usersByDN[$id];
237
-		} else if(isset($this->usersByUid[$id])) {
238
-			return $this->usersByUid[$id];
239
-		}
240
-
241
-		if($this->access->stringResemblesDN($id) ) {
242
-			$uid = $this->access->dn2username($id);
243
-			if($uid !== false) {
244
-				return $this->createAndCache($id, $uid);
245
-			}
246
-		}
247
-
248
-		return $this->createInstancyByUserName($id);
249
-	}
46
+    /** @var IUserTools */
47
+    protected $access;
48
+
49
+    /** @var IConfig */
50
+    protected $ocConfig;
51
+
52
+    /** @var IDBConnection */
53
+    protected $db;
54
+
55
+    /** @var IUserManager */
56
+    protected $userManager;
57
+
58
+    /** @var INotificationManager */
59
+    protected $notificationManager;
60
+
61
+    /** @var FilesystemHelper */
62
+    protected $ocFilesystem;
63
+
64
+    /** @var LogWrapper */
65
+    protected $ocLog;
66
+
67
+    /** @var Image */
68
+    protected $image;
69
+
70
+    /** @param \OCP\IAvatarManager */
71
+    protected $avatarManager;
72
+
73
+    /**
74
+     * @var CappedMemoryCache $usersByDN
75
+     */
76
+    protected $usersByDN;
77
+    /**
78
+     * @var CappedMemoryCache $usersByUid
79
+     */
80
+    protected $usersByUid;
81
+
82
+    /**
83
+     * @param IConfig $ocConfig
84
+     * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
85
+     * gives access to necessary functions from the OC filesystem
86
+     * @param  \OCA\User_LDAP\LogWrapper $ocLog
87
+     * @param IAvatarManager $avatarManager
88
+     * @param Image $image an empty image instance
89
+     * @param IDBConnection $db
90
+     * @throws \Exception when the methods mentioned above do not exist
91
+     */
92
+    public function __construct(IConfig $ocConfig,
93
+                                FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
94
+                                IAvatarManager $avatarManager, Image $image,
95
+                                IDBConnection $db, IUserManager $userManager,
96
+                                INotificationManager $notificationManager) {
97
+
98
+        $this->ocConfig            = $ocConfig;
99
+        $this->ocFilesystem        = $ocFilesystem;
100
+        $this->ocLog               = $ocLog;
101
+        $this->avatarManager       = $avatarManager;
102
+        $this->image               = $image;
103
+        $this->db                  = $db;
104
+        $this->userManager         = $userManager;
105
+        $this->notificationManager = $notificationManager;
106
+        $this->usersByDN           = new CappedMemoryCache();
107
+        $this->usersByUid          = new CappedMemoryCache();
108
+    }
109
+
110
+    /**
111
+     * @brief binds manager to an instance of IUserTools (implemented by
112
+     * Access). It needs to be assigned first before the manager can be used.
113
+     * @param IUserTools
114
+     */
115
+    public function setLdapAccess(IUserTools $access) {
116
+        $this->access = $access;
117
+    }
118
+
119
+    /**
120
+     * @brief creates an instance of User and caches (just runtime) it in the
121
+     * property array
122
+     * @param string $dn the DN of the user
123
+     * @param string $uid the internal (owncloud) username
124
+     * @return \OCA\User_LDAP\User\User
125
+     */
126
+    private function createAndCache($dn, $uid) {
127
+        $this->checkAccess();
128
+        $user = new User($uid, $dn, $this->access, $this->ocConfig,
129
+            $this->ocFilesystem, clone $this->image, $this->ocLog,
130
+            $this->avatarManager, $this->userManager, 
131
+            $this->notificationManager);
132
+        $this->usersByDN[$dn]   = $user;
133
+        $this->usersByUid[$uid] = $user;
134
+        return $user;
135
+    }
136
+
137
+    /**
138
+     * @brief checks whether the Access instance has been set
139
+     * @throws \Exception if Access has not been set
140
+     * @return null
141
+     */
142
+    private function checkAccess() {
143
+        if(is_null($this->access)) {
144
+            throw new \Exception('LDAP Access instance must be set first');
145
+        }
146
+    }
147
+
148
+    /**
149
+     * returns a list of attributes that will be processed further, e.g. quota,
150
+     * email, displayname, or others.
151
+     * @param bool $minimal - optional, set to true to skip attributes with big
152
+     * payload
153
+     * @return string[]
154
+     */
155
+    public function getAttributes($minimal = false) {
156
+        $attributes = array('dn', 'uid', 'samaccountname', 'memberof');
157
+        $possible = array(
158
+            $this->access->getConnection()->ldapQuotaAttribute,
159
+            $this->access->getConnection()->ldapEmailAttribute,
160
+            $this->access->getConnection()->ldapUserDisplayName,
161
+            $this->access->getConnection()->ldapUserDisplayName2,
162
+        );
163
+        foreach($possible as $attr) {
164
+            if(!is_null($attr)) {
165
+                $attributes[] = $attr;
166
+            }
167
+        }
168
+
169
+        $homeRule = $this->access->getConnection()->homeFolderNamingRule;
170
+        if(strpos($homeRule, 'attr:') === 0) {
171
+            $attributes[] = substr($homeRule, strlen('attr:'));
172
+        }
173
+
174
+        if(!$minimal) {
175
+            // attributes that are not really important but may come with big
176
+            // payload.
177
+            $attributes = array_merge($attributes, array(
178
+                'jpegphoto',
179
+                'thumbnailphoto'
180
+            ));
181
+        }
182
+
183
+        return $attributes;
184
+    }
185
+
186
+    /**
187
+     * Checks whether the specified user is marked as deleted
188
+     * @param string $id the Nextcloud user name
189
+     * @return bool
190
+     */
191
+    public function isDeletedUser($id) {
192
+        $isDeleted = $this->ocConfig->getUserValue(
193
+            $id, 'user_ldap', 'isDeleted', 0);
194
+        return intval($isDeleted) === 1;
195
+    }
196
+
197
+    /**
198
+     * creates and returns an instance of OfflineUser for the specified user
199
+     * @param string $id
200
+     * @return \OCA\User_LDAP\User\OfflineUser
201
+     */
202
+    public function getDeletedUser($id) {
203
+        return new OfflineUser(
204
+            $id,
205
+            $this->ocConfig,
206
+            $this->db,
207
+            $this->access->getUserMapper());
208
+    }
209
+
210
+    /**
211
+     * @brief returns a User object by it's Nextcloud username
212
+     * @param string $id the DN or username of the user
213
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
214
+     */
215
+    protected function createInstancyByUserName($id) {
216
+        //most likely a uid. Check whether it is a deleted user
217
+        if($this->isDeletedUser($id)) {
218
+            return $this->getDeletedUser($id);
219
+        }
220
+        $dn = $this->access->username2dn($id);
221
+        if($dn !== false) {
222
+            return $this->createAndCache($dn, $id);
223
+        }
224
+        return null;
225
+    }
226
+
227
+    /**
228
+     * @brief returns a User object by it's DN or Nextcloud username
229
+     * @param string $id the DN or username of the user
230
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
231
+     * @throws \Exception when connection could not be established
232
+     */
233
+    public function get($id) {
234
+        $this->checkAccess();
235
+        if(isset($this->usersByDN[$id])) {
236
+            return $this->usersByDN[$id];
237
+        } else if(isset($this->usersByUid[$id])) {
238
+            return $this->usersByUid[$id];
239
+        }
240
+
241
+        if($this->access->stringResemblesDN($id) ) {
242
+            $uid = $this->access->dn2username($id);
243
+            if($uid !== false) {
244
+                return $this->createAndCache($id, $uid);
245
+            }
246
+        }
247
+
248
+        return $this->createInstancyByUserName($id);
249
+    }
250 250
 
251 251
 }
Please login to merge, or discard this patch.