Passed
Push — master ( 377203...c41934 )
by Morris
11:31 queued 11s
created
apps/user_ldap/lib/Helper.php 1 patch
Indentation   +285 added lines, -285 removed lines patch added patch discarded remove patch
@@ -39,133 +39,133 @@  discard block
 block discarded – undo
39 39
 
40 40
 class Helper {
41 41
 
42
-	/** @var IConfig */
43
-	private $config;
44
-
45
-	/** @var CappedMemoryCache */
46
-	protected $sanitizeDnCache;
47
-
48
-	/**
49
-	 * Helper constructor.
50
-	 *
51
-	 * @param IConfig $config
52
-	 */
53
-	public function __construct(IConfig $config) {
54
-		$this->config = $config;
55
-		$this->sanitizeDnCache = new CappedMemoryCache(10000);
56
-	}
57
-
58
-	/**
59
-	 * returns prefixes for each saved LDAP/AD server configuration.
60
-	 *
61
-	 * @param bool $activeConfigurations optional, whether only active configuration shall be
62
-	 * retrieved, defaults to false
63
-	 * @return array with a list of the available prefixes
64
-	 *
65
-	 * Configuration prefixes are used to set up configurations for n LDAP or
66
-	 * AD servers. Since configuration is stored in the database, table
67
-	 * appconfig under appid user_ldap, the common identifiers in column
68
-	 * 'configkey' have a prefix. The prefix for the very first server
69
-	 * configuration is empty.
70
-	 * Configkey Examples:
71
-	 * Server 1: ldap_login_filter
72
-	 * Server 2: s1_ldap_login_filter
73
-	 * Server 3: s2_ldap_login_filter
74
-	 *
75
-	 * The prefix needs to be passed to the constructor of Connection class,
76
-	 * except the default (first) server shall be connected to.
77
-	 *
78
-	 */
79
-	public function getServerConfigurationPrefixes($activeConfigurations = false) {
80
-		$referenceConfigkey = 'ldap_configuration_active';
81
-
82
-		$keys = $this->getServersConfig($referenceConfigkey);
83
-
84
-		$prefixes = [];
85
-		foreach ($keys as $key) {
86
-			if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
87
-				continue;
88
-			}
89
-
90
-			$len = strlen($key) - strlen($referenceConfigkey);
91
-			$prefixes[] = substr($key, 0, $len);
92
-		}
93
-		asort($prefixes);
94
-
95
-		return $prefixes;
96
-	}
97
-
98
-	/**
99
-	 *
100
-	 * determines the host for every configured connection
101
-	 *
102
-	 * @return array an array with configprefix as keys
103
-	 *
104
-	 */
105
-	public function getServerConfigurationHosts() {
106
-		$referenceConfigkey = 'ldap_host';
107
-
108
-		$keys = $this->getServersConfig($referenceConfigkey);
109
-
110
-		$result = [];
111
-		foreach ($keys as $key) {
112
-			$len = strlen($key) - strlen($referenceConfigkey);
113
-			$prefix = substr($key, 0, $len);
114
-			$result[$prefix] = $this->config->getAppValue('user_ldap', $key);
115
-		}
116
-
117
-		return $result;
118
-	}
119
-
120
-	/**
121
-	 * return the next available configuration prefix
122
-	 *
123
-	 * @return string
124
-	 */
125
-	public function getNextServerConfigurationPrefix() {
126
-		$serverConnections = $this->getServerConfigurationPrefixes();
127
-
128
-		if (count($serverConnections) === 0) {
129
-			return 's01';
130
-		}
131
-
132
-		sort($serverConnections);
133
-		$lastKey = array_pop($serverConnections);
134
-		$lastNumber = (int)str_replace('s', '', $lastKey);
135
-		return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
136
-	}
137
-
138
-	private function getServersConfig($value) {
139
-		$regex = '/' . $value . '$/S';
140
-
141
-		$keys = $this->config->getAppKeys('user_ldap');
142
-		$result = [];
143
-		foreach ($keys as $key) {
144
-			if (preg_match($regex, $key) === 1) {
145
-				$result[] = $key;
146
-			}
147
-		}
148
-
149
-		return $result;
150
-	}
151
-
152
-	/**
153
-	 * deletes a given saved LDAP/AD server configuration.
154
-	 *
155
-	 * @param string $prefix the configuration prefix of the config to delete
156
-	 * @return bool true on success, false otherwise
157
-	 */
158
-	public function deleteServerConfiguration($prefix) {
159
-		if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
160
-			return false;
161
-		}
162
-
163
-		$saveOtherConfigurations = '';
164
-		if (empty($prefix)) {
165
-			$saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
166
-		}
167
-
168
-		$query = \OC_DB::prepare('
42
+    /** @var IConfig */
43
+    private $config;
44
+
45
+    /** @var CappedMemoryCache */
46
+    protected $sanitizeDnCache;
47
+
48
+    /**
49
+     * Helper constructor.
50
+     *
51
+     * @param IConfig $config
52
+     */
53
+    public function __construct(IConfig $config) {
54
+        $this->config = $config;
55
+        $this->sanitizeDnCache = new CappedMemoryCache(10000);
56
+    }
57
+
58
+    /**
59
+     * returns prefixes for each saved LDAP/AD server configuration.
60
+     *
61
+     * @param bool $activeConfigurations optional, whether only active configuration shall be
62
+     * retrieved, defaults to false
63
+     * @return array with a list of the available prefixes
64
+     *
65
+     * Configuration prefixes are used to set up configurations for n LDAP or
66
+     * AD servers. Since configuration is stored in the database, table
67
+     * appconfig under appid user_ldap, the common identifiers in column
68
+     * 'configkey' have a prefix. The prefix for the very first server
69
+     * configuration is empty.
70
+     * Configkey Examples:
71
+     * Server 1: ldap_login_filter
72
+     * Server 2: s1_ldap_login_filter
73
+     * Server 3: s2_ldap_login_filter
74
+     *
75
+     * The prefix needs to be passed to the constructor of Connection class,
76
+     * except the default (first) server shall be connected to.
77
+     *
78
+     */
79
+    public function getServerConfigurationPrefixes($activeConfigurations = false) {
80
+        $referenceConfigkey = 'ldap_configuration_active';
81
+
82
+        $keys = $this->getServersConfig($referenceConfigkey);
83
+
84
+        $prefixes = [];
85
+        foreach ($keys as $key) {
86
+            if ($activeConfigurations && $this->config->getAppValue('user_ldap', $key, '0') !== '1') {
87
+                continue;
88
+            }
89
+
90
+            $len = strlen($key) - strlen($referenceConfigkey);
91
+            $prefixes[] = substr($key, 0, $len);
92
+        }
93
+        asort($prefixes);
94
+
95
+        return $prefixes;
96
+    }
97
+
98
+    /**
99
+     *
100
+     * determines the host for every configured connection
101
+     *
102
+     * @return array an array with configprefix as keys
103
+     *
104
+     */
105
+    public function getServerConfigurationHosts() {
106
+        $referenceConfigkey = 'ldap_host';
107
+
108
+        $keys = $this->getServersConfig($referenceConfigkey);
109
+
110
+        $result = [];
111
+        foreach ($keys as $key) {
112
+            $len = strlen($key) - strlen($referenceConfigkey);
113
+            $prefix = substr($key, 0, $len);
114
+            $result[$prefix] = $this->config->getAppValue('user_ldap', $key);
115
+        }
116
+
117
+        return $result;
118
+    }
119
+
120
+    /**
121
+     * return the next available configuration prefix
122
+     *
123
+     * @return string
124
+     */
125
+    public function getNextServerConfigurationPrefix() {
126
+        $serverConnections = $this->getServerConfigurationPrefixes();
127
+
128
+        if (count($serverConnections) === 0) {
129
+            return 's01';
130
+        }
131
+
132
+        sort($serverConnections);
133
+        $lastKey = array_pop($serverConnections);
134
+        $lastNumber = (int)str_replace('s', '', $lastKey);
135
+        return 's' . str_pad($lastNumber + 1, 2, '0', STR_PAD_LEFT);
136
+    }
137
+
138
+    private function getServersConfig($value) {
139
+        $regex = '/' . $value . '$/S';
140
+
141
+        $keys = $this->config->getAppKeys('user_ldap');
142
+        $result = [];
143
+        foreach ($keys as $key) {
144
+            if (preg_match($regex, $key) === 1) {
145
+                $result[] = $key;
146
+            }
147
+        }
148
+
149
+        return $result;
150
+    }
151
+
152
+    /**
153
+     * deletes a given saved LDAP/AD server configuration.
154
+     *
155
+     * @param string $prefix the configuration prefix of the config to delete
156
+     * @return bool true on success, false otherwise
157
+     */
158
+    public function deleteServerConfiguration($prefix) {
159
+        if (!in_array($prefix, self::getServerConfigurationPrefixes())) {
160
+            return false;
161
+        }
162
+
163
+        $saveOtherConfigurations = '';
164
+        if (empty($prefix)) {
165
+            $saveOtherConfigurations = 'AND `configkey` NOT LIKE \'s%\'';
166
+        }
167
+
168
+        $query = \OC_DB::prepare('
169 169
 			DELETE
170 170
 			FROM `*PREFIX*appconfig`
171 171
 			WHERE `configkey` LIKE ?
@@ -173,162 +173,162 @@  discard block
 block discarded – undo
173 173
 				AND `appid` = \'user_ldap\'
174 174
 				AND `configkey` NOT IN (\'enabled\', \'installed_version\', \'types\', \'bgjUpdateGroupsLastRun\')
175 175
 		');
176
-		$delRows = $query->execute([$prefix . '%']);
177
-
178
-		if ($delRows === null) {
179
-			return false;
180
-		}
181
-
182
-		if ($delRows === 0) {
183
-			return false;
184
-		}
185
-
186
-		return true;
187
-	}
188
-
189
-	/**
190
-	 * checks whether there is one or more disabled LDAP configurations
191
-	 *
192
-	 * @return bool
193
-	 * @throws \Exception
194
-	 */
195
-	public function haveDisabledConfigurations() {
196
-		$all = $this->getServerConfigurationPrefixes(false);
197
-		$active = $this->getServerConfigurationPrefixes(true);
198
-
199
-		if (!is_array($all) || !is_array($active)) {
200
-			throw new \Exception('Unexpected Return Value');
201
-		}
202
-
203
-		return count($all) !== count($active) || count($all) === 0;
204
-	}
205
-
206
-	/**
207
-	 * extracts the domain from a given URL
208
-	 *
209
-	 * @param string $url the URL
210
-	 * @return string|false domain as string on success, false otherwise
211
-	 */
212
-	public function getDomainFromURL($url) {
213
-		$uinfo = parse_url($url);
214
-		if (!is_array($uinfo)) {
215
-			return false;
216
-		}
217
-
218
-		$domain = false;
219
-		if (isset($uinfo['host'])) {
220
-			$domain = $uinfo['host'];
221
-		} elseif (isset($uinfo['path'])) {
222
-			$domain = $uinfo['path'];
223
-		}
224
-
225
-		return $domain;
226
-	}
227
-
228
-	/**
229
-	 *
230
-	 * Set the LDAPProvider in the config
231
-	 *
232
-	 */
233
-	public function setLDAPProvider() {
234
-		$current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
235
-		if (is_null($current)) {
236
-			\OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class);
237
-		}
238
-	}
239
-
240
-	/**
241
-	 * sanitizes a DN received from the LDAP server
242
-	 *
243
-	 * @param array $dn the DN in question
244
-	 * @return array|string the sanitized DN
245
-	 */
246
-	public function sanitizeDN($dn) {
247
-		//treating multiple base DNs
248
-		if (is_array($dn)) {
249
-			$result = [];
250
-			foreach ($dn as $singleDN) {
251
-				$result[] = $this->sanitizeDN($singleDN);
252
-			}
253
-			return $result;
254
-		}
255
-
256
-		if (!is_string($dn)) {
257
-			throw new \LogicException('String expected ' . \gettype($dn) . ' given');
258
-		}
259
-
260
-		if (($sanitizedDn = $this->sanitizeDnCache->get($dn)) !== null) {
261
-			return $sanitizedDn;
262
-		}
263
-
264
-		//OID sometimes gives back DNs with whitespace after the comma
265
-		// a la "uid=foo, cn=bar, dn=..." We need to tackle this!
266
-		$sanitizedDn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
267
-
268
-		//make comparisons and everything work
269
-		$sanitizedDn = mb_strtolower($sanitizedDn, 'UTF-8');
270
-
271
-		//escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
272
-		//to use the DN in search filters, \ needs to be escaped to \5c additionally
273
-		//to use them in bases, we convert them back to simple backslashes in readAttribute()
274
-		$replacements = [
275
-			'\,' => '\5c2C',
276
-			'\=' => '\5c3D',
277
-			'\+' => '\5c2B',
278
-			'\<' => '\5c3C',
279
-			'\>' => '\5c3E',
280
-			'\;' => '\5c3B',
281
-			'\"' => '\5c22',
282
-			'\#' => '\5c23',
283
-			'(' => '\28',
284
-			')' => '\29',
285
-			'*' => '\2A',
286
-		];
287
-		$sanitizedDn = str_replace(array_keys($replacements), array_values($replacements), $sanitizedDn);
288
-		$this->sanitizeDnCache->set($dn, $sanitizedDn);
289
-
290
-		return $sanitizedDn;
291
-	}
292
-
293
-	/**
294
-	 * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
295
-	 *
296
-	 * @param string $dn the DN
297
-	 * @return string
298
-	 */
299
-	public function DNasBaseParameter($dn) {
300
-		return str_ireplace('\\5c', '\\', $dn);
301
-	}
302
-
303
-	/**
304
-	 * listens to a hook thrown by server2server sharing and replaces the given
305
-	 * login name by a username, if it matches an LDAP user.
306
-	 *
307
-	 * @param array $param
308
-	 * @throws \Exception
309
-	 */
310
-	public static function loginName2UserName($param) {
311
-		if (!isset($param['uid'])) {
312
-			throw new \Exception('key uid is expected to be set in $param');
313
-		}
314
-
315
-		//ain't it ironic?
316
-		$helper = new Helper(\OC::$server->getConfig());
317
-
318
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
319
-		$ldapWrapper = new LDAP();
320
-		$ocConfig = \OC::$server->getConfig();
321
-		$notificationManager = \OC::$server->getNotificationManager();
322
-
323
-		$userSession = \OC::$server->getUserSession();
324
-		$userPluginManager = \OC::$server->query(UserPluginManager::class);
325
-
326
-		$userBackend = new User_Proxy(
327
-			$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
328
-		);
329
-		$uid = $userBackend->loginName2UserName($param['uid']);
330
-		if ($uid !== false) {
331
-			$param['uid'] = $uid;
332
-		}
333
-	}
176
+        $delRows = $query->execute([$prefix . '%']);
177
+
178
+        if ($delRows === null) {
179
+            return false;
180
+        }
181
+
182
+        if ($delRows === 0) {
183
+            return false;
184
+        }
185
+
186
+        return true;
187
+    }
188
+
189
+    /**
190
+     * checks whether there is one or more disabled LDAP configurations
191
+     *
192
+     * @return bool
193
+     * @throws \Exception
194
+     */
195
+    public function haveDisabledConfigurations() {
196
+        $all = $this->getServerConfigurationPrefixes(false);
197
+        $active = $this->getServerConfigurationPrefixes(true);
198
+
199
+        if (!is_array($all) || !is_array($active)) {
200
+            throw new \Exception('Unexpected Return Value');
201
+        }
202
+
203
+        return count($all) !== count($active) || count($all) === 0;
204
+    }
205
+
206
+    /**
207
+     * extracts the domain from a given URL
208
+     *
209
+     * @param string $url the URL
210
+     * @return string|false domain as string on success, false otherwise
211
+     */
212
+    public function getDomainFromURL($url) {
213
+        $uinfo = parse_url($url);
214
+        if (!is_array($uinfo)) {
215
+            return false;
216
+        }
217
+
218
+        $domain = false;
219
+        if (isset($uinfo['host'])) {
220
+            $domain = $uinfo['host'];
221
+        } elseif (isset($uinfo['path'])) {
222
+            $domain = $uinfo['path'];
223
+        }
224
+
225
+        return $domain;
226
+    }
227
+
228
+    /**
229
+     *
230
+     * Set the LDAPProvider in the config
231
+     *
232
+     */
233
+    public function setLDAPProvider() {
234
+        $current = \OC::$server->getConfig()->getSystemValue('ldapProviderFactory', null);
235
+        if (is_null($current)) {
236
+            \OC::$server->getConfig()->setSystemValue('ldapProviderFactory', LDAPProviderFactory::class);
237
+        }
238
+    }
239
+
240
+    /**
241
+     * sanitizes a DN received from the LDAP server
242
+     *
243
+     * @param array $dn the DN in question
244
+     * @return array|string the sanitized DN
245
+     */
246
+    public function sanitizeDN($dn) {
247
+        //treating multiple base DNs
248
+        if (is_array($dn)) {
249
+            $result = [];
250
+            foreach ($dn as $singleDN) {
251
+                $result[] = $this->sanitizeDN($singleDN);
252
+            }
253
+            return $result;
254
+        }
255
+
256
+        if (!is_string($dn)) {
257
+            throw new \LogicException('String expected ' . \gettype($dn) . ' given');
258
+        }
259
+
260
+        if (($sanitizedDn = $this->sanitizeDnCache->get($dn)) !== null) {
261
+            return $sanitizedDn;
262
+        }
263
+
264
+        //OID sometimes gives back DNs with whitespace after the comma
265
+        // a la "uid=foo, cn=bar, dn=..." We need to tackle this!
266
+        $sanitizedDn = preg_replace('/([^\\\]),(\s+)/u', '\1,', $dn);
267
+
268
+        //make comparisons and everything work
269
+        $sanitizedDn = mb_strtolower($sanitizedDn, 'UTF-8');
270
+
271
+        //escape DN values according to RFC 2253 – this is already done by ldap_explode_dn
272
+        //to use the DN in search filters, \ needs to be escaped to \5c additionally
273
+        //to use them in bases, we convert them back to simple backslashes in readAttribute()
274
+        $replacements = [
275
+            '\,' => '\5c2C',
276
+            '\=' => '\5c3D',
277
+            '\+' => '\5c2B',
278
+            '\<' => '\5c3C',
279
+            '\>' => '\5c3E',
280
+            '\;' => '\5c3B',
281
+            '\"' => '\5c22',
282
+            '\#' => '\5c23',
283
+            '(' => '\28',
284
+            ')' => '\29',
285
+            '*' => '\2A',
286
+        ];
287
+        $sanitizedDn = str_replace(array_keys($replacements), array_values($replacements), $sanitizedDn);
288
+        $this->sanitizeDnCache->set($dn, $sanitizedDn);
289
+
290
+        return $sanitizedDn;
291
+    }
292
+
293
+    /**
294
+     * converts a stored DN so it can be used as base parameter for LDAP queries, internally we store them for usage in LDAP filters
295
+     *
296
+     * @param string $dn the DN
297
+     * @return string
298
+     */
299
+    public function DNasBaseParameter($dn) {
300
+        return str_ireplace('\\5c', '\\', $dn);
301
+    }
302
+
303
+    /**
304
+     * listens to a hook thrown by server2server sharing and replaces the given
305
+     * login name by a username, if it matches an LDAP user.
306
+     *
307
+     * @param array $param
308
+     * @throws \Exception
309
+     */
310
+    public static function loginName2UserName($param) {
311
+        if (!isset($param['uid'])) {
312
+            throw new \Exception('key uid is expected to be set in $param');
313
+        }
314
+
315
+        //ain't it ironic?
316
+        $helper = new Helper(\OC::$server->getConfig());
317
+
318
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
319
+        $ldapWrapper = new LDAP();
320
+        $ocConfig = \OC::$server->getConfig();
321
+        $notificationManager = \OC::$server->getNotificationManager();
322
+
323
+        $userSession = \OC::$server->getUserSession();
324
+        $userPluginManager = \OC::$server->query(UserPluginManager::class);
325
+
326
+        $userBackend = new User_Proxy(
327
+            $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
328
+        );
329
+        $uid = $userBackend->loginName2UserName($param['uid']);
330
+        if ($uid !== false) {
331
+            $param['uid'] = $uid;
332
+        }
333
+    }
334 334
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Migration/UUIDFixGroup.php 1 patch
Indentation   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -33,10 +33,10 @@
 block discarded – undo
33 33
 use OCP\IConfig;
34 34
 
35 35
 class UUIDFixGroup extends UUIDFix {
36
-	public function __construct(GroupMapping $mapper, LDAP $ldap, IConfig $config, Helper $helper) {
37
-		$this->mapper = $mapper;
38
-		$this->proxy = new User_Proxy($helper->getServerConfigurationPrefixes(true), $ldap, $config,
39
-			\OC::$server->getNotificationManager(), \OC::$server->getUserSession(),
40
-			\OC::$server->query(UserPluginManager::class));
41
-	}
36
+    public function __construct(GroupMapping $mapper, LDAP $ldap, IConfig $config, Helper $helper) {
37
+        $this->mapper = $mapper;
38
+        $this->proxy = new User_Proxy($helper->getServerConfigurationPrefixes(true), $ldap, $config,
39
+            \OC::$server->getNotificationManager(), \OC::$server->getUserSession(),
40
+            \OC::$server->query(UserPluginManager::class));
41
+    }
42 42
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Migration/UUIDFixUser.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -33,9 +33,9 @@
 block discarded – undo
33 33
 use OCP\IConfig;
34 34
 
35 35
 class UUIDFixUser extends UUIDFix {
36
-	public function __construct(UserMapping $mapper, LDAP $ldap, IConfig $config, Helper $helper) {
37
-		$this->mapper = $mapper;
38
-		$groupPluginManager = \OC::$server->query(GroupPluginManager::class);
39
-		$this->proxy = new Group_Proxy($helper->getServerConfigurationPrefixes(true), $ldap, $groupPluginManager);
40
-	}
36
+    public function __construct(UserMapping $mapper, LDAP $ldap, IConfig $config, Helper $helper) {
37
+        $this->mapper = $mapper;
38
+        $groupPluginManager = \OC::$server->query(GroupPluginManager::class);
39
+        $this->proxy = new Group_Proxy($helper->getServerConfigurationPrefixes(true), $ldap, $groupPluginManager);
40
+    }
41 41
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 1 patch
Indentation   +164 added lines, -164 removed lines patch added patch discarded remove patch
@@ -47,183 +47,183 @@
 block discarded – undo
47 47
 use OCP\ILogger;
48 48
 
49 49
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
50
-	private static $groupsFromDB;
51
-
52
-	private static $groupBE;
53
-
54
-	public function __construct() {
55
-		$this->interval = self::getRefreshInterval();
56
-	}
57
-
58
-	/**
59
-	 * @param mixed $argument
60
-	 */
61
-	public function run($argument) {
62
-		self::updateGroups();
63
-	}
64
-
65
-	public static function updateGroups() {
66
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
67
-
68
-		$knownGroups = array_keys(self::getKnownGroups());
69
-		$actualGroups = self::getGroupBE()->getGroups();
70
-
71
-		if (empty($actualGroups) && empty($knownGroups)) {
72
-			\OCP\Util::writeLog('user_ldap',
73
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
74
-				ILogger::INFO);
75
-			return;
76
-		}
77
-
78
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
79
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
80
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
81
-
82
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
83
-	}
84
-
85
-	/**
86
-	 * @return int
87
-	 */
88
-	private static function getRefreshInterval() {
89
-		//defaults to every hour
90
-		return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
91
-	}
92
-
93
-	/**
94
-	 * @param string[] $groups
95
-	 */
96
-	private static function handleKnownGroups($groups) {
97
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
98
-		$query = \OC_DB::prepare('
50
+    private static $groupsFromDB;
51
+
52
+    private static $groupBE;
53
+
54
+    public function __construct() {
55
+        $this->interval = self::getRefreshInterval();
56
+    }
57
+
58
+    /**
59
+     * @param mixed $argument
60
+     */
61
+    public function run($argument) {
62
+        self::updateGroups();
63
+    }
64
+
65
+    public static function updateGroups() {
66
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', ILogger::DEBUG);
67
+
68
+        $knownGroups = array_keys(self::getKnownGroups());
69
+        $actualGroups = self::getGroupBE()->getGroups();
70
+
71
+        if (empty($actualGroups) && empty($knownGroups)) {
72
+            \OCP\Util::writeLog('user_ldap',
73
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
74
+                ILogger::INFO);
75
+            return;
76
+        }
77
+
78
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
79
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
80
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
81
+
82
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', ILogger::DEBUG);
83
+    }
84
+
85
+    /**
86
+     * @return int
87
+     */
88
+    private static function getRefreshInterval() {
89
+        //defaults to every hour
90
+        return \OC::$server->getConfig()->getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
91
+    }
92
+
93
+    /**
94
+     * @param string[] $groups
95
+     */
96
+    private static function handleKnownGroups($groups) {
97
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', ILogger::DEBUG);
98
+        $query = \OC_DB::prepare('
99 99
 			UPDATE `*PREFIX*ldap_group_members`
100 100
 			SET `owncloudusers` = ?
101 101
 			WHERE `owncloudname` = ?
102 102
 		');
103
-		foreach ($groups as $group) {
104
-			//we assume, that self::$groupsFromDB has been retrieved already
105
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
106
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
107
-			$hasChanged = false;
108
-			foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
109
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
110
-				\OCP\Util::writeLog('user_ldap',
111
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
112
-					ILogger::INFO);
113
-				$hasChanged = true;
114
-			}
115
-			foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
116
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
117
-				\OCP\Util::writeLog('user_ldap',
118
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
119
-					ILogger::INFO);
120
-				$hasChanged = true;
121
-			}
122
-			if ($hasChanged) {
123
-				$query->execute([serialize($actualUsers), $group]);
124
-			}
125
-		}
126
-		\OCP\Util::writeLog('user_ldap',
127
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
128
-			ILogger::DEBUG);
129
-	}
130
-
131
-	/**
132
-	 * @param string[] $createdGroups
133
-	 */
134
-	private static function handleCreatedGroups($createdGroups) {
135
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
136
-		$query = \OC_DB::prepare('
103
+        foreach ($groups as $group) {
104
+            //we assume, that self::$groupsFromDB has been retrieved already
105
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
106
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
107
+            $hasChanged = false;
108
+            foreach (array_diff($knownUsers, $actualUsers) as $removedUser) {
109
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', ['uid' => $removedUser, 'gid' => $group]);
110
+                \OCP\Util::writeLog('user_ldap',
111
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
112
+                    ILogger::INFO);
113
+                $hasChanged = true;
114
+            }
115
+            foreach (array_diff($actualUsers, $knownUsers) as $addedUser) {
116
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', ['uid' => $addedUser, 'gid' => $group]);
117
+                \OCP\Util::writeLog('user_ldap',
118
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
119
+                    ILogger::INFO);
120
+                $hasChanged = true;
121
+            }
122
+            if ($hasChanged) {
123
+                $query->execute([serialize($actualUsers), $group]);
124
+            }
125
+        }
126
+        \OCP\Util::writeLog('user_ldap',
127
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
128
+            ILogger::DEBUG);
129
+    }
130
+
131
+    /**
132
+     * @param string[] $createdGroups
133
+     */
134
+    private static function handleCreatedGroups($createdGroups) {
135
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', ILogger::DEBUG);
136
+        $query = \OC_DB::prepare('
137 137
 			INSERT
138 138
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
139 139
 			VALUES (?, ?)
140 140
 		');
141
-		foreach ($createdGroups as $createdGroup) {
142
-			\OCP\Util::writeLog('user_ldap',
143
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
144
-				ILogger::INFO);
145
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
146
-			$query->execute([$createdGroup, $users]);
147
-		}
148
-		\OCP\Util::writeLog('user_ldap',
149
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
150
-			ILogger::DEBUG);
151
-	}
152
-
153
-	/**
154
-	 * @param string[] $removedGroups
155
-	 */
156
-	private static function handleRemovedGroups($removedGroups) {
157
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
158
-		$query = \OC_DB::prepare('
141
+        foreach ($createdGroups as $createdGroup) {
142
+            \OCP\Util::writeLog('user_ldap',
143
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
144
+                ILogger::INFO);
145
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
146
+            $query->execute([$createdGroup, $users]);
147
+        }
148
+        \OCP\Util::writeLog('user_ldap',
149
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
150
+            ILogger::DEBUG);
151
+    }
152
+
153
+    /**
154
+     * @param string[] $removedGroups
155
+     */
156
+    private static function handleRemovedGroups($removedGroups) {
157
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', ILogger::DEBUG);
158
+        $query = \OC_DB::prepare('
159 159
 			DELETE
160 160
 			FROM `*PREFIX*ldap_group_members`
161 161
 			WHERE `owncloudname` = ?
162 162
 		');
163
-		foreach ($removedGroups as $removedGroup) {
164
-			\OCP\Util::writeLog('user_ldap',
165
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
166
-				ILogger::INFO);
167
-			$query->execute([$removedGroup]);
168
-		}
169
-		\OCP\Util::writeLog('user_ldap',
170
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
171
-			ILogger::DEBUG);
172
-	}
173
-
174
-	/**
175
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
176
-	 */
177
-	private static function getGroupBE() {
178
-		if (!is_null(self::$groupBE)) {
179
-			return self::$groupBE;
180
-		}
181
-		$helper = new Helper(\OC::$server->getConfig());
182
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
183
-		$ldapWrapper = new LDAP();
184
-		if (count($configPrefixes) === 1) {
185
-			//avoid the proxy when there is only one LDAP server configured
186
-			$dbc = \OC::$server->getDatabaseConnection();
187
-			$userManager = new Manager(
188
-				\OC::$server->getConfig(),
189
-				new FilesystemHelper(),
190
-				new LogWrapper(),
191
-				\OC::$server->getAvatarManager(),
192
-				new \OCP\Image(),
193
-				$dbc,
194
-				\OC::$server->getUserManager(),
195
-				\OC::$server->getNotificationManager());
196
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
197
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
198
-			$groupMapper = new GroupMapping($dbc);
199
-			$userMapper  = new UserMapping($dbc);
200
-			$ldapAccess->setGroupMapper($groupMapper);
201
-			$ldapAccess->setUserMapper($userMapper);
202
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query(GroupPluginManager::class));
203
-		} else {
204
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query(GroupPluginManager::class));
205
-		}
206
-
207
-		return self::$groupBE;
208
-	}
209
-
210
-	/**
211
-	 * @return array
212
-	 */
213
-	private static function getKnownGroups() {
214
-		if (is_array(self::$groupsFromDB)) {
215
-			return self::$groupsFromDB;
216
-		}
217
-		$query = \OC_DB::prepare('
163
+        foreach ($removedGroups as $removedGroup) {
164
+            \OCP\Util::writeLog('user_ldap',
165
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
166
+                ILogger::INFO);
167
+            $query->execute([$removedGroup]);
168
+        }
169
+        \OCP\Util::writeLog('user_ldap',
170
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
171
+            ILogger::DEBUG);
172
+    }
173
+
174
+    /**
175
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
176
+     */
177
+    private static function getGroupBE() {
178
+        if (!is_null(self::$groupBE)) {
179
+            return self::$groupBE;
180
+        }
181
+        $helper = new Helper(\OC::$server->getConfig());
182
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
183
+        $ldapWrapper = new LDAP();
184
+        if (count($configPrefixes) === 1) {
185
+            //avoid the proxy when there is only one LDAP server configured
186
+            $dbc = \OC::$server->getDatabaseConnection();
187
+            $userManager = new Manager(
188
+                \OC::$server->getConfig(),
189
+                new FilesystemHelper(),
190
+                new LogWrapper(),
191
+                \OC::$server->getAvatarManager(),
192
+                new \OCP\Image(),
193
+                $dbc,
194
+                \OC::$server->getUserManager(),
195
+                \OC::$server->getNotificationManager());
196
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
197
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper, \OC::$server->getConfig(), \OC::$server->getUserManager());
198
+            $groupMapper = new GroupMapping($dbc);
199
+            $userMapper  = new UserMapping($dbc);
200
+            $ldapAccess->setGroupMapper($groupMapper);
201
+            $ldapAccess->setUserMapper($userMapper);
202
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess, \OC::$server->query(GroupPluginManager::class));
203
+        } else {
204
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query(GroupPluginManager::class));
205
+        }
206
+
207
+        return self::$groupBE;
208
+    }
209
+
210
+    /**
211
+     * @return array
212
+     */
213
+    private static function getKnownGroups() {
214
+        if (is_array(self::$groupsFromDB)) {
215
+            return self::$groupsFromDB;
216
+        }
217
+        $query = \OC_DB::prepare('
218 218
 			SELECT `owncloudname`, `owncloudusers`
219 219
 			FROM `*PREFIX*ldap_group_members`
220 220
 		');
221
-		$result = $query->execute()->fetchAll();
222
-		self::$groupsFromDB = [];
223
-		foreach ($result as $dataset) {
224
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
225
-		}
226
-
227
-		return self::$groupsFromDB;
228
-	}
221
+        $result = $query->execute()->fetchAll();
222
+        self::$groupsFromDB = [];
223
+        foreach ($result as $dataset) {
224
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
225
+        }
226
+
227
+        return self::$groupsFromDB;
228
+    }
229 229
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/CleanUp.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -45,197 +45,197 @@
 block discarded – undo
45 45
  * @package OCA\User_LDAP\Jobs;
46 46
  */
47 47
 class CleanUp extends TimedJob {
48
-	/** @var int $limit amount of users that should be checked per run */
49
-	protected $limit;
50
-
51
-	/** @var int $defaultIntervalMin default interval in minutes */
52
-	protected $defaultIntervalMin = 51;
53
-
54
-	/** @var User_LDAP|User_Proxy $userBackend */
55
-	protected $userBackend;
56
-
57
-	/** @var \OCP\IConfig $ocConfig */
58
-	protected $ocConfig;
59
-
60
-	/** @var \OCP\IDBConnection $db */
61
-	protected $db;
62
-
63
-	/** @var Helper $ldapHelper */
64
-	protected $ldapHelper;
65
-
66
-	/** @var UserMapping */
67
-	protected $mapping;
68
-
69
-	/** @var DeletedUsersIndex */
70
-	protected $dui;
71
-
72
-	public function __construct() {
73
-		$minutes = \OC::$server->getConfig()->getSystemValue(
74
-			'ldapUserCleanupInterval', (string)$this->defaultIntervalMin);
75
-		$this->setInterval((int)$minutes * 60);
76
-	}
77
-
78
-	/**
79
-	 * assigns the instances passed to run() to the class properties
80
-	 * @param array $arguments
81
-	 */
82
-	public function setArguments($arguments) {
83
-		//Dependency Injection is not possible, because the constructor will
84
-		//only get values that are serialized to JSON. I.e. whatever we would
85
-		//pass in app.php we do add here, except something else is passed e.g.
86
-		//in tests.
87
-
88
-		if (isset($arguments['helper'])) {
89
-			$this->ldapHelper = $arguments['helper'];
90
-		} else {
91
-			$this->ldapHelper = new Helper(\OC::$server->getConfig());
92
-		}
93
-
94
-		if (isset($arguments['ocConfig'])) {
95
-			$this->ocConfig = $arguments['ocConfig'];
96
-		} else {
97
-			$this->ocConfig = \OC::$server->getConfig();
98
-		}
99
-
100
-		if (isset($arguments['userBackend'])) {
101
-			$this->userBackend = $arguments['userBackend'];
102
-		} else {
103
-			$this->userBackend =  new User_Proxy(
104
-				$this->ldapHelper->getServerConfigurationPrefixes(true),
105
-				new LDAP(),
106
-				$this->ocConfig,
107
-				\OC::$server->getNotificationManager(),
108
-				\OC::$server->getUserSession(),
109
-				\OC::$server->query(UserPluginManager::class)
110
-			);
111
-		}
112
-
113
-		if (isset($arguments['db'])) {
114
-			$this->db = $arguments['db'];
115
-		} else {
116
-			$this->db = \OC::$server->getDatabaseConnection();
117
-		}
118
-
119
-		if (isset($arguments['mapping'])) {
120
-			$this->mapping = $arguments['mapping'];
121
-		} else {
122
-			$this->mapping = new UserMapping($this->db);
123
-		}
124
-
125
-		if (isset($arguments['deletedUsersIndex'])) {
126
-			$this->dui = $arguments['deletedUsersIndex'];
127
-		} else {
128
-			$this->dui = new DeletedUsersIndex(
129
-				$this->ocConfig, $this->db, $this->mapping);
130
-		}
131
-	}
132
-
133
-	/**
134
-	 * makes the background job do its work
135
-	 * @param array $argument
136
-	 */
137
-	public function run($argument) {
138
-		$this->setArguments($argument);
139
-
140
-		if (!$this->isCleanUpAllowed()) {
141
-			return;
142
-		}
143
-		$users = $this->mapping->getList($this->getOffset(), $this->getChunkSize());
144
-		if (!is_array($users)) {
145
-			//something wrong? Let's start from the beginning next time and
146
-			//abort
147
-			$this->setOffset(true);
148
-			return;
149
-		}
150
-		$resetOffset = $this->isOffsetResetNecessary(count($users));
151
-		$this->checkUsers($users);
152
-		$this->setOffset($resetOffset);
153
-	}
154
-
155
-	/**
156
-	 * checks whether next run should start at 0 again
157
-	 * @param int $resultCount
158
-	 * @return bool
159
-	 */
160
-	public function isOffsetResetNecessary($resultCount) {
161
-		return $resultCount < $this->getChunkSize();
162
-	}
163
-
164
-	/**
165
-	 * checks whether cleaning up LDAP users is allowed
166
-	 * @return bool
167
-	 */
168
-	public function isCleanUpAllowed() {
169
-		try {
170
-			if ($this->ldapHelper->haveDisabledConfigurations()) {
171
-				return false;
172
-			}
173
-		} catch (\Exception $e) {
174
-			return false;
175
-		}
176
-
177
-		return $this->isCleanUpEnabled();
178
-	}
179
-
180
-	/**
181
-	 * checks whether clean up is enabled by configuration
182
-	 * @return bool
183
-	 */
184
-	private function isCleanUpEnabled() {
185
-		return (bool)$this->ocConfig->getSystemValue(
186
-			'ldapUserCleanupInterval', (string)$this->defaultIntervalMin);
187
-	}
188
-
189
-	/**
190
-	 * checks users whether they are still existing
191
-	 * @param array $users result from getMappedUsers()
192
-	 */
193
-	private function checkUsers(array $users) {
194
-		foreach ($users as $user) {
195
-			$this->checkUser($user);
196
-		}
197
-	}
198
-
199
-	/**
200
-	 * checks whether a user is still existing in LDAP
201
-	 * @param string[] $user
202
-	 */
203
-	private function checkUser(array $user) {
204
-		if ($this->userBackend->userExistsOnLDAP($user['name'])) {
205
-			//still available, all good
206
-
207
-			return;
208
-		}
209
-
210
-		$this->dui->markUser($user['name']);
211
-	}
212
-
213
-	/**
214
-	 * gets the offset to fetch users from the mappings table
215
-	 * @return int
216
-	 */
217
-	private function getOffset() {
218
-		return (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobOffset', 0);
219
-	}
220
-
221
-	/**
222
-	 * sets the new offset for the next run
223
-	 * @param bool $reset whether the offset should be set to 0
224
-	 */
225
-	public function setOffset($reset = false) {
226
-		$newOffset = $reset ? 0 :
227
-			$this->getOffset() + $this->getChunkSize();
228
-		$this->ocConfig->setAppValue('user_ldap', 'cleanUpJobOffset', $newOffset);
229
-	}
230
-
231
-	/**
232
-	 * returns the chunk size (limit in DB speak)
233
-	 * @return int
234
-	 */
235
-	public function getChunkSize() {
236
-		if ($this->limit === null) {
237
-			$this->limit = (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobChunkSize', 50);
238
-		}
239
-		return $this->limit;
240
-	}
48
+    /** @var int $limit amount of users that should be checked per run */
49
+    protected $limit;
50
+
51
+    /** @var int $defaultIntervalMin default interval in minutes */
52
+    protected $defaultIntervalMin = 51;
53
+
54
+    /** @var User_LDAP|User_Proxy $userBackend */
55
+    protected $userBackend;
56
+
57
+    /** @var \OCP\IConfig $ocConfig */
58
+    protected $ocConfig;
59
+
60
+    /** @var \OCP\IDBConnection $db */
61
+    protected $db;
62
+
63
+    /** @var Helper $ldapHelper */
64
+    protected $ldapHelper;
65
+
66
+    /** @var UserMapping */
67
+    protected $mapping;
68
+
69
+    /** @var DeletedUsersIndex */
70
+    protected $dui;
71
+
72
+    public function __construct() {
73
+        $minutes = \OC::$server->getConfig()->getSystemValue(
74
+            'ldapUserCleanupInterval', (string)$this->defaultIntervalMin);
75
+        $this->setInterval((int)$minutes * 60);
76
+    }
77
+
78
+    /**
79
+     * assigns the instances passed to run() to the class properties
80
+     * @param array $arguments
81
+     */
82
+    public function setArguments($arguments) {
83
+        //Dependency Injection is not possible, because the constructor will
84
+        //only get values that are serialized to JSON. I.e. whatever we would
85
+        //pass in app.php we do add here, except something else is passed e.g.
86
+        //in tests.
87
+
88
+        if (isset($arguments['helper'])) {
89
+            $this->ldapHelper = $arguments['helper'];
90
+        } else {
91
+            $this->ldapHelper = new Helper(\OC::$server->getConfig());
92
+        }
93
+
94
+        if (isset($arguments['ocConfig'])) {
95
+            $this->ocConfig = $arguments['ocConfig'];
96
+        } else {
97
+            $this->ocConfig = \OC::$server->getConfig();
98
+        }
99
+
100
+        if (isset($arguments['userBackend'])) {
101
+            $this->userBackend = $arguments['userBackend'];
102
+        } else {
103
+            $this->userBackend =  new User_Proxy(
104
+                $this->ldapHelper->getServerConfigurationPrefixes(true),
105
+                new LDAP(),
106
+                $this->ocConfig,
107
+                \OC::$server->getNotificationManager(),
108
+                \OC::$server->getUserSession(),
109
+                \OC::$server->query(UserPluginManager::class)
110
+            );
111
+        }
112
+
113
+        if (isset($arguments['db'])) {
114
+            $this->db = $arguments['db'];
115
+        } else {
116
+            $this->db = \OC::$server->getDatabaseConnection();
117
+        }
118
+
119
+        if (isset($arguments['mapping'])) {
120
+            $this->mapping = $arguments['mapping'];
121
+        } else {
122
+            $this->mapping = new UserMapping($this->db);
123
+        }
124
+
125
+        if (isset($arguments['deletedUsersIndex'])) {
126
+            $this->dui = $arguments['deletedUsersIndex'];
127
+        } else {
128
+            $this->dui = new DeletedUsersIndex(
129
+                $this->ocConfig, $this->db, $this->mapping);
130
+        }
131
+    }
132
+
133
+    /**
134
+     * makes the background job do its work
135
+     * @param array $argument
136
+     */
137
+    public function run($argument) {
138
+        $this->setArguments($argument);
139
+
140
+        if (!$this->isCleanUpAllowed()) {
141
+            return;
142
+        }
143
+        $users = $this->mapping->getList($this->getOffset(), $this->getChunkSize());
144
+        if (!is_array($users)) {
145
+            //something wrong? Let's start from the beginning next time and
146
+            //abort
147
+            $this->setOffset(true);
148
+            return;
149
+        }
150
+        $resetOffset = $this->isOffsetResetNecessary(count($users));
151
+        $this->checkUsers($users);
152
+        $this->setOffset($resetOffset);
153
+    }
154
+
155
+    /**
156
+     * checks whether next run should start at 0 again
157
+     * @param int $resultCount
158
+     * @return bool
159
+     */
160
+    public function isOffsetResetNecessary($resultCount) {
161
+        return $resultCount < $this->getChunkSize();
162
+    }
163
+
164
+    /**
165
+     * checks whether cleaning up LDAP users is allowed
166
+     * @return bool
167
+     */
168
+    public function isCleanUpAllowed() {
169
+        try {
170
+            if ($this->ldapHelper->haveDisabledConfigurations()) {
171
+                return false;
172
+            }
173
+        } catch (\Exception $e) {
174
+            return false;
175
+        }
176
+
177
+        return $this->isCleanUpEnabled();
178
+    }
179
+
180
+    /**
181
+     * checks whether clean up is enabled by configuration
182
+     * @return bool
183
+     */
184
+    private function isCleanUpEnabled() {
185
+        return (bool)$this->ocConfig->getSystemValue(
186
+            'ldapUserCleanupInterval', (string)$this->defaultIntervalMin);
187
+    }
188
+
189
+    /**
190
+     * checks users whether they are still existing
191
+     * @param array $users result from getMappedUsers()
192
+     */
193
+    private function checkUsers(array $users) {
194
+        foreach ($users as $user) {
195
+            $this->checkUser($user);
196
+        }
197
+    }
198
+
199
+    /**
200
+     * checks whether a user is still existing in LDAP
201
+     * @param string[] $user
202
+     */
203
+    private function checkUser(array $user) {
204
+        if ($this->userBackend->userExistsOnLDAP($user['name'])) {
205
+            //still available, all good
206
+
207
+            return;
208
+        }
209
+
210
+        $this->dui->markUser($user['name']);
211
+    }
212
+
213
+    /**
214
+     * gets the offset to fetch users from the mappings table
215
+     * @return int
216
+     */
217
+    private function getOffset() {
218
+        return (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobOffset', 0);
219
+    }
220
+
221
+    /**
222
+     * sets the new offset for the next run
223
+     * @param bool $reset whether the offset should be set to 0
224
+     */
225
+    public function setOffset($reset = false) {
226
+        $newOffset = $reset ? 0 :
227
+            $this->getOffset() + $this->getChunkSize();
228
+        $this->ocConfig->setAppValue('user_ldap', 'cleanUpJobOffset', $newOffset);
229
+    }
230
+
231
+    /**
232
+     * returns the chunk size (limit in DB speak)
233
+     * @return int
234
+     */
235
+    public function getChunkSize() {
236
+        if ($this->limit === null) {
237
+            $this->limit = (int)$this->ocConfig->getAppValue('user_ldap', 'cleanUpJobChunkSize', 50);
238
+        }
239
+        return $this->limit;
240
+    }
241 241
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Command/Search.php 1 patch
Indentation   +95 added lines, -95 removed lines patch added patch discarded remove patch
@@ -43,106 +43,106 @@
 block discarded – undo
43 43
 use Symfony\Component\Console\Output\OutputInterface;
44 44
 
45 45
 class Search extends Command {
46
-	/** @var \OCP\IConfig */
47
-	protected $ocConfig;
46
+    /** @var \OCP\IConfig */
47
+    protected $ocConfig;
48 48
 
49
-	/**
50
-	 * @param \OCP\IConfig $ocConfig
51
-	 */
52
-	public function __construct(IConfig $ocConfig) {
53
-		$this->ocConfig = $ocConfig;
54
-		parent::__construct();
55
-	}
49
+    /**
50
+     * @param \OCP\IConfig $ocConfig
51
+     */
52
+    public function __construct(IConfig $ocConfig) {
53
+        $this->ocConfig = $ocConfig;
54
+        parent::__construct();
55
+    }
56 56
 
57
-	protected function configure() {
58
-		$this
59
-			->setName('ldap:search')
60
-			->setDescription('executes a user or group search')
61
-			->addArgument(
62
-					'search',
63
-					InputArgument::REQUIRED,
64
-					'the search string (can be empty)'
65
-					 )
66
-			->addOption(
67
-					'group',
68
-					null,
69
-					InputOption::VALUE_NONE,
70
-					'searches groups instead of users'
71
-					 )
72
-			->addOption(
73
-					'offset',
74
-					null,
75
-					InputOption::VALUE_REQUIRED,
76
-					'The offset of the result set. Needs to be a multiple of limit. defaults to 0.',
77
-					0
78
-					 )
79
-			->addOption(
80
-					'limit',
81
-					null,
82
-					InputOption::VALUE_REQUIRED,
83
-					'limit the results. 0 means no limit, defaults to 15',
84
-					15
85
-					 )
86
-		;
87
-	}
57
+    protected function configure() {
58
+        $this
59
+            ->setName('ldap:search')
60
+            ->setDescription('executes a user or group search')
61
+            ->addArgument(
62
+                    'search',
63
+                    InputArgument::REQUIRED,
64
+                    'the search string (can be empty)'
65
+                        )
66
+            ->addOption(
67
+                    'group',
68
+                    null,
69
+                    InputOption::VALUE_NONE,
70
+                    'searches groups instead of users'
71
+                        )
72
+            ->addOption(
73
+                    'offset',
74
+                    null,
75
+                    InputOption::VALUE_REQUIRED,
76
+                    'The offset of the result set. Needs to be a multiple of limit. defaults to 0.',
77
+                    0
78
+                        )
79
+            ->addOption(
80
+                    'limit',
81
+                    null,
82
+                    InputOption::VALUE_REQUIRED,
83
+                    'limit the results. 0 means no limit, defaults to 15',
84
+                    15
85
+                        )
86
+        ;
87
+    }
88 88
 
89
-	/**
90
-	 * Tests whether the offset and limit options are valid
91
-	 * @param int $offset
92
-	 * @param int $limit
93
-	 * @throws \InvalidArgumentException
94
-	 */
95
-	protected function validateOffsetAndLimit($offset, $limit) {
96
-		if ($limit < 0) {
97
-			throw new \InvalidArgumentException('limit must be  0 or greater');
98
-		}
99
-		if ($offset  < 0) {
100
-			throw new \InvalidArgumentException('offset must be 0 or greater');
101
-		}
102
-		if ($limit === 0 && $offset !== 0) {
103
-			throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0');
104
-		}
105
-		if ($offset > 0 && ($offset % $limit !== 0)) {
106
-			throw new \InvalidArgumentException('offset must be a multiple of limit');
107
-		}
108
-	}
89
+    /**
90
+     * Tests whether the offset and limit options are valid
91
+     * @param int $offset
92
+     * @param int $limit
93
+     * @throws \InvalidArgumentException
94
+     */
95
+    protected function validateOffsetAndLimit($offset, $limit) {
96
+        if ($limit < 0) {
97
+            throw new \InvalidArgumentException('limit must be  0 or greater');
98
+        }
99
+        if ($offset  < 0) {
100
+            throw new \InvalidArgumentException('offset must be 0 or greater');
101
+        }
102
+        if ($limit === 0 && $offset !== 0) {
103
+            throw new \InvalidArgumentException('offset must be 0 if limit is also set to 0');
104
+        }
105
+        if ($offset > 0 && ($offset % $limit !== 0)) {
106
+            throw new \InvalidArgumentException('offset must be a multiple of limit');
107
+        }
108
+    }
109 109
 
110
-	protected function execute(InputInterface $input, OutputInterface $output): int {
111
-		$helper = new Helper($this->ocConfig);
112
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
113
-		$ldapWrapper = new LDAP();
110
+    protected function execute(InputInterface $input, OutputInterface $output): int {
111
+        $helper = new Helper($this->ocConfig);
112
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
113
+        $ldapWrapper = new LDAP();
114 114
 
115
-		$offset = (int)$input->getOption('offset');
116
-		$limit = (int)$input->getOption('limit');
117
-		$this->validateOffsetAndLimit($offset, $limit);
115
+        $offset = (int)$input->getOption('offset');
116
+        $limit = (int)$input->getOption('limit');
117
+        $this->validateOffsetAndLimit($offset, $limit);
118 118
 
119
-		if ($input->getOption('group')) {
120
-			$proxy = new Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query(GroupPluginManager::class));
121
-			$getMethod = 'getGroups';
122
-			$printID = false;
123
-			// convert the limit of groups to null. This will show all the groups available instead of
124
-			// nothing, and will match the same behaviour the search for users has.
125
-			if ($limit === 0) {
126
-				$limit = null;
127
-			}
128
-		} else {
129
-			$proxy = new User_Proxy(
130
-				$configPrefixes,
131
-				$ldapWrapper,
132
-				$this->ocConfig,
133
-				\OC::$server->getNotificationManager(),
134
-				\OC::$server->getUserSession(),
135
-				\OC::$server->query(UserPluginManager::class)
136
-			);
137
-			$getMethod = 'getDisplayNames';
138
-			$printID = true;
139
-		}
119
+        if ($input->getOption('group')) {
120
+            $proxy = new Group_Proxy($configPrefixes, $ldapWrapper, \OC::$server->query(GroupPluginManager::class));
121
+            $getMethod = 'getGroups';
122
+            $printID = false;
123
+            // convert the limit of groups to null. This will show all the groups available instead of
124
+            // nothing, and will match the same behaviour the search for users has.
125
+            if ($limit === 0) {
126
+                $limit = null;
127
+            }
128
+        } else {
129
+            $proxy = new User_Proxy(
130
+                $configPrefixes,
131
+                $ldapWrapper,
132
+                $this->ocConfig,
133
+                \OC::$server->getNotificationManager(),
134
+                \OC::$server->getUserSession(),
135
+                \OC::$server->query(UserPluginManager::class)
136
+            );
137
+            $getMethod = 'getDisplayNames';
138
+            $printID = true;
139
+        }
140 140
 
141
-		$result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset);
142
-		foreach ($result as $id => $name) {
143
-			$line = $name . ($printID ? ' ('.$id.')' : '');
144
-			$output->writeln($line);
145
-		}
146
-		return 0;
147
-	}
141
+        $result = $proxy->$getMethod($input->getArgument('search'), $limit, $offset);
142
+        foreach ($result as $id => $name) {
143
+            $line = $name . ($printID ? ' ('.$id.')' : '');
144
+            $output->writeln($line);
145
+        }
146
+        return 0;
147
+    }
148 148
 }
Please login to merge, or discard this patch.
apps/user_ldap/appinfo/app.php 2 patches
Indentation   +21 added lines, -21 removed lines patch added patch discarded remove patch
@@ -32,33 +32,33 @@
 block discarded – undo
32 32
 $helper = new \OCA\User_LDAP\Helper(\OC::$server->getConfig());
33 33
 $configPrefixes = $helper->getServerConfigurationPrefixes(true);
34 34
 if (count($configPrefixes) > 0) {
35
-	$ldapWrapper = new OCA\User_LDAP\LDAP();
36
-	$ocConfig = \OC::$server->getConfig();
37
-	$notificationManager = \OC::$server->getNotificationManager();
38
-	$notificationManager->registerNotifierService(\OCA\User_LDAP\Notification\Notifier::class);
39
-	$userSession = \OC::$server->getUserSession();
35
+    $ldapWrapper = new OCA\User_LDAP\LDAP();
36
+    $ocConfig = \OC::$server->getConfig();
37
+    $notificationManager = \OC::$server->getNotificationManager();
38
+    $notificationManager->registerNotifierService(\OCA\User_LDAP\Notification\Notifier::class);
39
+    $userSession = \OC::$server->getUserSession();
40 40
 
41
-	$userPluginManager = \OC::$server->query(\OCA\User_LDAP\UserPluginManager::class);
42
-	$groupPluginManager = \OC::$server->query(\OCA\User_LDAP\GroupPluginManager::class);
41
+    $userPluginManager = \OC::$server->query(\OCA\User_LDAP\UserPluginManager::class);
42
+    $groupPluginManager = \OC::$server->query(\OCA\User_LDAP\GroupPluginManager::class);
43 43
 
44
-	$userBackend  = new OCA\User_LDAP\User_Proxy(
45
-		$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
46
-	);
47
-	$groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, $groupPluginManager);
48
-	// register user backend
49
-	OC_User::useBackend($userBackend);
44
+    $userBackend  = new OCA\User_LDAP\User_Proxy(
45
+        $configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
46
+    );
47
+    $groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, $groupPluginManager);
48
+    // register user backend
49
+    OC_User::useBackend($userBackend);
50 50
 
51
-	// Hook to allow plugins to work on registered backends
52
-	OC::$server->getEventDispatcher()->dispatch('OCA\\User_LDAP\\User\\User::postLDAPBackendAdded');
51
+    // Hook to allow plugins to work on registered backends
52
+    OC::$server->getEventDispatcher()->dispatch('OCA\\User_LDAP\\User\\User::postLDAPBackendAdded');
53 53
 
54
-	\OC::$server->getGroupManager()->addBackend($groupBackend);
54
+    \OC::$server->getGroupManager()->addBackend($groupBackend);
55 55
 
56
-	$app->registerBackendDependents();
56
+    $app->registerBackendDependents();
57 57
 }
58 58
 
59 59
 \OCP\Util::connectHook(
60
-	'\OCA\Files_Sharing\API\Server2Server',
61
-	'preLoginNameUsedAsUserName',
62
-	'\OCA\User_LDAP\Helper',
63
-	'loginName2UserName'
60
+    '\OCA\Files_Sharing\API\Server2Server',
61
+    'preLoginNameUsedAsUserName',
62
+    '\OCA\User_LDAP\Helper',
63
+    'loginName2UserName'
64 64
 );
Please login to merge, or discard this patch.
Spacing   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -41,10 +41,10 @@
 block discarded – undo
41 41
 	$userPluginManager = \OC::$server->query(\OCA\User_LDAP\UserPluginManager::class);
42 42
 	$groupPluginManager = \OC::$server->query(\OCA\User_LDAP\GroupPluginManager::class);
43 43
 
44
-	$userBackend  = new OCA\User_LDAP\User_Proxy(
44
+	$userBackend = new OCA\User_LDAP\User_Proxy(
45 45
 		$configPrefixes, $ldapWrapper, $ocConfig, $notificationManager, $userSession, $userPluginManager
46 46
 	);
47
-	$groupBackend  = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, $groupPluginManager);
47
+	$groupBackend = new OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper, $groupPluginManager);
48 48
 	// register user backend
49 49
 	OC_User::useBackend($userBackend);
50 50
 
Please login to merge, or discard this patch.
apps/user_ldap/appinfo/register_command.php 1 patch
Indentation   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -36,15 +36,15 @@  discard block
 block discarded – undo
36 36
 $helper = new Helper(\OC::$server->getConfig());
37 37
 $ocConfig = \OC::$server->getConfig();
38 38
 $uBackend = new User_Proxy(
39
-	$helper->getServerConfigurationPrefixes(true),
40
-	new LDAP(),
41
-	$ocConfig,
42
-	\OC::$server->getNotificationManager(),
43
-	\OC::$server->getUserSession(),
44
-	\OC::$server->query(\OCA\User_LDAP\UserPluginManager::class)
39
+    $helper->getServerConfigurationPrefixes(true),
40
+    new LDAP(),
41
+    $ocConfig,
42
+    \OC::$server->getNotificationManager(),
43
+    \OC::$server->getUserSession(),
44
+    \OC::$server->query(\OCA\User_LDAP\UserPluginManager::class)
45 45
 );
46 46
 $deletedUsersIndex = new DeletedUsersIndex(
47
-	$ocConfig, $dbConnection, $userMapping
47
+    $ocConfig, $dbConnection, $userMapping
48 48
 );
49 49
 
50 50
 $application->add(new OCA\User_LDAP\Command\ShowConfig($helper));
@@ -54,8 +54,8 @@  discard block
 block discarded – undo
54 54
 $application->add(new OCA\User_LDAP\Command\DeleteConfig($helper));
55 55
 $application->add(new OCA\User_LDAP\Command\Search($ocConfig));
56 56
 $application->add(new OCA\User_LDAP\Command\ShowRemnants(
57
-	$deletedUsersIndex, \OC::$server->getDateTimeFormatter())
57
+    $deletedUsersIndex, \OC::$server->getDateTimeFormatter())
58 58
 );
59 59
 $application->add(new OCA\User_LDAP\Command\CheckUser(
60
-	$uBackend, $helper, $deletedUsersIndex, $userMapping)
60
+    $uBackend, $helper, $deletedUsersIndex, $userMapping)
61 61
 );
Please login to merge, or discard this patch.