Completed
Pull Request — master (#3676)
by Individual IT
12:49
created
apps/user_ldap/lib/LDAP.php 1 patch
Indentation   +337 added lines, -337 removed lines patch added patch discarded remove patch
@@ -33,341 +33,341 @@
 block discarded – undo
33 33
 use OCA\User_LDAP\Exceptions\ConstraintViolationException;
34 34
 
35 35
 class LDAP implements ILDAPWrapper {
36
-	protected $curFunc = '';
37
-	protected $curArgs = array();
38
-
39
-	/**
40
-	 * @param resource $link
41
-	 * @param string $dn
42
-	 * @param string $password
43
-	 * @return bool|mixed
44
-	 */
45
-	public function bind($link, $dn, $password) {
46
-		return $this->invokeLDAPMethod('bind', $link, $dn, $password);
47
-	}
48
-
49
-	/**
50
-	 * @param string $host
51
-	 * @param string $port
52
-	 * @return mixed
53
-	 */
54
-	public function connect($host, $port) {
55
-		if(strpos($host, '://') === false) {
56
-			$host = 'ldap://' . $host;
57
-		}
58
-		if(strpos($host, ':', strpos($host, '://') + 1) === false) {
59
-			//ldap_connect ignores port parameter when URLs are passed
60
-			$host .= ':' . $port;
61
-		}
62
-		return $this->invokeLDAPMethod('connect', $host);
63
-	}
64
-
65
-	/**
66
-	 * @param LDAP $link
67
-	 * @param LDAP $result
68
-	 * @param string $cookie
69
-	 * @return bool|LDAP
70
-	 */
71
-	public function controlPagedResultResponse($link, $result, &$cookie) {
72
-		$this->preFunctionCall('ldap_control_paged_result_response',
73
-			array($link, $result, $cookie));
74
-		$result = ldap_control_paged_result_response($link, $result, $cookie);
75
-		$this->postFunctionCall();
76
-
77
-		return $result;
78
-	}
79
-
80
-	/**
81
-	 * @param LDAP $link
82
-	 * @param int $pageSize
83
-	 * @param bool $isCritical
84
-	 * @param string $cookie
85
-	 * @return mixed|true
86
-	 */
87
-	public function controlPagedResult($link, $pageSize, $isCritical, $cookie) {
88
-		return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize,
89
-										$isCritical, $cookie);
90
-	}
91
-
92
-	/**
93
-	 * @param LDAP $link
94
-	 * @param LDAP $result
95
-	 * @return mixed
96
-	 */
97
-	public function countEntries($link, $result) {
98
-		return $this->invokeLDAPMethod('count_entries', $link, $result);
99
-	}
100
-
101
-	/**
102
-	 * @param LDAP $link
103
-	 * @return mixed|string
104
-	 */
105
-	public function errno($link) {
106
-		return $this->invokeLDAPMethod('errno', $link);
107
-	}
108
-
109
-	/**
110
-	 * @param LDAP $link
111
-	 * @return int|mixed
112
-	 */
113
-	public function error($link) {
114
-		return $this->invokeLDAPMethod('error', $link);
115
-	}
116
-
117
-	/**
118
-	 * Splits DN into its component parts
119
-	 * @param string $dn
120
-	 * @param int @withAttrib
121
-	 * @return array|false
122
-	 * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
123
-	 */
124
-	public function explodeDN($dn, $withAttrib) {
125
-		return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
126
-	}
127
-
128
-	/**
129
-	 * @param LDAP $link
130
-	 * @param LDAP $result
131
-	 * @return mixed
132
-	 */
133
-	public function firstEntry($link, $result) {
134
-		return $this->invokeLDAPMethod('first_entry', $link, $result);
135
-	}
136
-
137
-	/**
138
-	 * @param LDAP $link
139
-	 * @param LDAP $result
140
-	 * @return array|mixed
141
-	 */
142
-	public function getAttributes($link, $result) {
143
-		return $this->invokeLDAPMethod('get_attributes', $link, $result);
144
-	}
145
-
146
-	/**
147
-	 * @param LDAP $link
148
-	 * @param LDAP $result
149
-	 * @return mixed|string
150
-	 */
151
-	public function getDN($link, $result) {
152
-		return $this->invokeLDAPMethod('get_dn', $link, $result);
153
-	}
154
-
155
-	/**
156
-	 * @param LDAP $link
157
-	 * @param LDAP $result
158
-	 * @return array|mixed
159
-	 */
160
-	public function getEntries($link, $result) {
161
-		return $this->invokeLDAPMethod('get_entries', $link, $result);
162
-	}
163
-
164
-	/**
165
-	 * @param LDAP $link
166
-	 * @param resource $result
167
-	 * @return mixed
168
-	 */
169
-	public function nextEntry($link, $result) {
170
-		return $this->invokeLDAPMethod('next_entry', $link, $result);
171
-	}
172
-
173
-	/**
174
-	 * @param LDAP $link
175
-	 * @param string $baseDN
176
-	 * @param string $filter
177
-	 * @param array $attr
178
-	 * @return mixed
179
-	 */
180
-	public function read($link, $baseDN, $filter, $attr) {
181
-		return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr);
182
-	}
183
-
184
-	/**
185
-	 * @param LDAP $link
186
-	 * @param string $baseDN
187
-	 * @param string $filter
188
-	 * @param array $attr
189
-	 * @param int $attrsOnly
190
-	 * @param int $limit
191
-	 * @return mixed
192
-	 */
193
-	public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
194
-		return $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
195
-	}
196
-
197
-	/**
198
-	 * @param LDAP $link
199
-	 * @param string $userDN
200
-	 * @param string $password
201
-	 * @return bool
202
-	 */
203
-	public function modReplace($link, $userDN, $password) {
204
-		return $this->invokeLDAPMethod('mod_replace', $link, $userDN, array('userPassword' => $password));
205
-	}
206
-
207
-	/**
208
-	 * @param LDAP $link
209
-	 * @param string $option
210
-	 * @param int $value
211
-	 * @return bool|mixed
212
-	 */
213
-	public function setOption($link, $option, $value) {
214
-		return $this->invokeLDAPMethod('set_option', $link, $option, $value);
215
-	}
216
-
217
-	/**
218
-	 * @param LDAP $link
219
-	 * @return mixed|true
220
-	 */
221
-	public function startTls($link) {
222
-		return $this->invokeLDAPMethod('start_tls', $link);
223
-	}
224
-
225
-	/**
226
-	 * @param resource $link
227
-	 * @return bool|mixed
228
-	 */
229
-	public function unbind($link) {
230
-		return $this->invokeLDAPMethod('unbind', $link);
231
-	}
232
-
233
-	/**
234
-	 * Checks whether the server supports LDAP
235
-	 * @return boolean if it the case, false otherwise
236
-	 * */
237
-	public function areLDAPFunctionsAvailable() {
238
-		return function_exists('ldap_connect');
239
-	}
240
-
241
-	/**
242
-	 * Checks whether PHP supports LDAP Paged Results
243
-	 * @return boolean if it the case, false otherwise
244
-	 * */
245
-	public function hasPagedResultSupport() {
246
-		$hasSupport = function_exists('ldap_control_paged_result')
247
-			&& function_exists('ldap_control_paged_result_response');
248
-		return $hasSupport;
249
-	}
250
-
251
-	/**
252
-	 * Checks whether the submitted parameter is a resource
253
-	 * @param Resource $resource the resource variable to check
254
-	 * @return bool true if it is a resource, false otherwise
255
-	 */
256
-	public function isResource($resource) {
257
-		return is_resource($resource);
258
-	}
259
-
260
-	/**
261
-	 * Checks whether the return value from LDAP is wrong or not.
262
-	 *
263
-	 * When using ldap_search we provide an array, in case multiple bases are
264
-	 * configured. Thus, we need to check the array elements.
265
-	 *
266
-	 * @param $result
267
-	 * @return bool
268
-	 */
269
-	protected function isResultFalse($result) {
270
-		if($result === false) {
271
-			return true;
272
-		}
273
-
274
-		if($this->curFunc === 'ldap_search' && is_array($result)) {
275
-			foreach ($result as $singleResult) {
276
-				if($singleResult === false) {
277
-					return true;
278
-				}
279
-			}
280
-		}
281
-
282
-		return false;
283
-	}
284
-
285
-	/**
286
-	 * @return mixed
287
-	 */
288
-	protected function invokeLDAPMethod() {
289
-		$arguments = func_get_args();
290
-		$func = 'ldap_' . array_shift($arguments);
291
-		if(function_exists($func)) {
292
-			$this->preFunctionCall($func, $arguments);
293
-			$result = call_user_func_array($func, $arguments);
294
-			if ($this->isResultFalse($result)) {
295
-				$this->postFunctionCall();
296
-			}
297
-			return $result;
298
-		}
299
-		return null;
300
-	}
301
-
302
-	/**
303
-	 * @param string $functionName
304
-	 * @param array $args
305
-	 */
306
-	private function preFunctionCall($functionName, $args) {
307
-		$this->curFunc = $functionName;
308
-		$this->curArgs = $args;
309
-	}
310
-
311
-	/**
312
-	 * Analyzes the returned LDAP error and acts accordingly if not 0
313
-	 *
314
-	 * @param resource $resource the LDAP Connection resource
315
-	 * @throws ConstraintViolationException
316
-	 * @throws ServerNotAvailableException
317
-	 * @throws \Exception
318
-	 */
319
-	private function processLDAPError($resource) {
320
-		$errorCode = ldap_errno($resource);
321
-		if($errorCode === 0) {
322
-			return;
323
-		}
324
-		$errorMsg  = ldap_error($resource);
325
-
326
-		if($this->curFunc === 'ldap_get_entries'
327
-			&& $errorCode === -4) {
328
-		} else if ($errorCode === 32) {
329
-			//for now
330
-		} else if ($errorCode === 10) {
331
-			//referrals, we switch them off, but then there is AD :)
332
-		} else if ($errorCode === -1) {
333
-			throw new ServerNotAvailableException('Lost connection to LDAP server.');
334
-		} else if ($errorCode === 48) {
335
-			throw new \Exception('LDAP authentication method rejected', $errorCode);
336
-		} else if ($errorCode === 1) {
337
-			throw new \Exception('LDAP Operations error', $errorCode);
338
-		} else if ($errorCode === 19) {
339
-			ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
340
-			throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
341
-		} else {
342
-			\OCP\Util::writeLog('user_ldap',
343
-				'LDAP error '.$errorMsg.' (' .
344
-				$errorCode.') after calling '.
345
-				$this->curFunc,
346
-				\OCP\Util::DEBUG);
347
-		}
348
-	}
349
-
350
-	/**
351
-	 * Called after an ldap method is run to act on LDAP error if necessary
352
-	 */
353
-	private function postFunctionCall() {
354
-		if($this->isResource($this->curArgs[0])) {
355
-			$resource = $this->curArgs[0];
356
-		} else if(
357
-			   $this->curFunc === 'ldap_search'
358
-			&& is_array($this->curArgs[0])
359
-			&& $this->isResource($this->curArgs[0][0])
360
-		) {
361
-			// we use always the same LDAP connection resource, is enough to
362
-			// take the first one.
363
-			$resource = $this->curArgs[0][0];
364
-		} else {
365
-			return;
366
-		}
367
-
368
-		$this->processLDAPError($resource);
369
-
370
-		$this->curFunc = '';
371
-		$this->curArgs = [];
372
-	}
36
+    protected $curFunc = '';
37
+    protected $curArgs = array();
38
+
39
+    /**
40
+     * @param resource $link
41
+     * @param string $dn
42
+     * @param string $password
43
+     * @return bool|mixed
44
+     */
45
+    public function bind($link, $dn, $password) {
46
+        return $this->invokeLDAPMethod('bind', $link, $dn, $password);
47
+    }
48
+
49
+    /**
50
+     * @param string $host
51
+     * @param string $port
52
+     * @return mixed
53
+     */
54
+    public function connect($host, $port) {
55
+        if(strpos($host, '://') === false) {
56
+            $host = 'ldap://' . $host;
57
+        }
58
+        if(strpos($host, ':', strpos($host, '://') + 1) === false) {
59
+            //ldap_connect ignores port parameter when URLs are passed
60
+            $host .= ':' . $port;
61
+        }
62
+        return $this->invokeLDAPMethod('connect', $host);
63
+    }
64
+
65
+    /**
66
+     * @param LDAP $link
67
+     * @param LDAP $result
68
+     * @param string $cookie
69
+     * @return bool|LDAP
70
+     */
71
+    public function controlPagedResultResponse($link, $result, &$cookie) {
72
+        $this->preFunctionCall('ldap_control_paged_result_response',
73
+            array($link, $result, $cookie));
74
+        $result = ldap_control_paged_result_response($link, $result, $cookie);
75
+        $this->postFunctionCall();
76
+
77
+        return $result;
78
+    }
79
+
80
+    /**
81
+     * @param LDAP $link
82
+     * @param int $pageSize
83
+     * @param bool $isCritical
84
+     * @param string $cookie
85
+     * @return mixed|true
86
+     */
87
+    public function controlPagedResult($link, $pageSize, $isCritical, $cookie) {
88
+        return $this->invokeLDAPMethod('control_paged_result', $link, $pageSize,
89
+                                        $isCritical, $cookie);
90
+    }
91
+
92
+    /**
93
+     * @param LDAP $link
94
+     * @param LDAP $result
95
+     * @return mixed
96
+     */
97
+    public function countEntries($link, $result) {
98
+        return $this->invokeLDAPMethod('count_entries', $link, $result);
99
+    }
100
+
101
+    /**
102
+     * @param LDAP $link
103
+     * @return mixed|string
104
+     */
105
+    public function errno($link) {
106
+        return $this->invokeLDAPMethod('errno', $link);
107
+    }
108
+
109
+    /**
110
+     * @param LDAP $link
111
+     * @return int|mixed
112
+     */
113
+    public function error($link) {
114
+        return $this->invokeLDAPMethod('error', $link);
115
+    }
116
+
117
+    /**
118
+     * Splits DN into its component parts
119
+     * @param string $dn
120
+     * @param int @withAttrib
121
+     * @return array|false
122
+     * @link http://www.php.net/manual/en/function.ldap-explode-dn.php
123
+     */
124
+    public function explodeDN($dn, $withAttrib) {
125
+        return $this->invokeLDAPMethod('explode_dn', $dn, $withAttrib);
126
+    }
127
+
128
+    /**
129
+     * @param LDAP $link
130
+     * @param LDAP $result
131
+     * @return mixed
132
+     */
133
+    public function firstEntry($link, $result) {
134
+        return $this->invokeLDAPMethod('first_entry', $link, $result);
135
+    }
136
+
137
+    /**
138
+     * @param LDAP $link
139
+     * @param LDAP $result
140
+     * @return array|mixed
141
+     */
142
+    public function getAttributes($link, $result) {
143
+        return $this->invokeLDAPMethod('get_attributes', $link, $result);
144
+    }
145
+
146
+    /**
147
+     * @param LDAP $link
148
+     * @param LDAP $result
149
+     * @return mixed|string
150
+     */
151
+    public function getDN($link, $result) {
152
+        return $this->invokeLDAPMethod('get_dn', $link, $result);
153
+    }
154
+
155
+    /**
156
+     * @param LDAP $link
157
+     * @param LDAP $result
158
+     * @return array|mixed
159
+     */
160
+    public function getEntries($link, $result) {
161
+        return $this->invokeLDAPMethod('get_entries', $link, $result);
162
+    }
163
+
164
+    /**
165
+     * @param LDAP $link
166
+     * @param resource $result
167
+     * @return mixed
168
+     */
169
+    public function nextEntry($link, $result) {
170
+        return $this->invokeLDAPMethod('next_entry', $link, $result);
171
+    }
172
+
173
+    /**
174
+     * @param LDAP $link
175
+     * @param string $baseDN
176
+     * @param string $filter
177
+     * @param array $attr
178
+     * @return mixed
179
+     */
180
+    public function read($link, $baseDN, $filter, $attr) {
181
+        return $this->invokeLDAPMethod('read', $link, $baseDN, $filter, $attr);
182
+    }
183
+
184
+    /**
185
+     * @param LDAP $link
186
+     * @param string $baseDN
187
+     * @param string $filter
188
+     * @param array $attr
189
+     * @param int $attrsOnly
190
+     * @param int $limit
191
+     * @return mixed
192
+     */
193
+    public function search($link, $baseDN, $filter, $attr, $attrsOnly = 0, $limit = 0) {
194
+        return $this->invokeLDAPMethod('search', $link, $baseDN, $filter, $attr, $attrsOnly, $limit);
195
+    }
196
+
197
+    /**
198
+     * @param LDAP $link
199
+     * @param string $userDN
200
+     * @param string $password
201
+     * @return bool
202
+     */
203
+    public function modReplace($link, $userDN, $password) {
204
+        return $this->invokeLDAPMethod('mod_replace', $link, $userDN, array('userPassword' => $password));
205
+    }
206
+
207
+    /**
208
+     * @param LDAP $link
209
+     * @param string $option
210
+     * @param int $value
211
+     * @return bool|mixed
212
+     */
213
+    public function setOption($link, $option, $value) {
214
+        return $this->invokeLDAPMethod('set_option', $link, $option, $value);
215
+    }
216
+
217
+    /**
218
+     * @param LDAP $link
219
+     * @return mixed|true
220
+     */
221
+    public function startTls($link) {
222
+        return $this->invokeLDAPMethod('start_tls', $link);
223
+    }
224
+
225
+    /**
226
+     * @param resource $link
227
+     * @return bool|mixed
228
+     */
229
+    public function unbind($link) {
230
+        return $this->invokeLDAPMethod('unbind', $link);
231
+    }
232
+
233
+    /**
234
+     * Checks whether the server supports LDAP
235
+     * @return boolean if it the case, false otherwise
236
+     * */
237
+    public function areLDAPFunctionsAvailable() {
238
+        return function_exists('ldap_connect');
239
+    }
240
+
241
+    /**
242
+     * Checks whether PHP supports LDAP Paged Results
243
+     * @return boolean if it the case, false otherwise
244
+     * */
245
+    public function hasPagedResultSupport() {
246
+        $hasSupport = function_exists('ldap_control_paged_result')
247
+            && function_exists('ldap_control_paged_result_response');
248
+        return $hasSupport;
249
+    }
250
+
251
+    /**
252
+     * Checks whether the submitted parameter is a resource
253
+     * @param Resource $resource the resource variable to check
254
+     * @return bool true if it is a resource, false otherwise
255
+     */
256
+    public function isResource($resource) {
257
+        return is_resource($resource);
258
+    }
259
+
260
+    /**
261
+     * Checks whether the return value from LDAP is wrong or not.
262
+     *
263
+     * When using ldap_search we provide an array, in case multiple bases are
264
+     * configured. Thus, we need to check the array elements.
265
+     *
266
+     * @param $result
267
+     * @return bool
268
+     */
269
+    protected function isResultFalse($result) {
270
+        if($result === false) {
271
+            return true;
272
+        }
273
+
274
+        if($this->curFunc === 'ldap_search' && is_array($result)) {
275
+            foreach ($result as $singleResult) {
276
+                if($singleResult === false) {
277
+                    return true;
278
+                }
279
+            }
280
+        }
281
+
282
+        return false;
283
+    }
284
+
285
+    /**
286
+     * @return mixed
287
+     */
288
+    protected function invokeLDAPMethod() {
289
+        $arguments = func_get_args();
290
+        $func = 'ldap_' . array_shift($arguments);
291
+        if(function_exists($func)) {
292
+            $this->preFunctionCall($func, $arguments);
293
+            $result = call_user_func_array($func, $arguments);
294
+            if ($this->isResultFalse($result)) {
295
+                $this->postFunctionCall();
296
+            }
297
+            return $result;
298
+        }
299
+        return null;
300
+    }
301
+
302
+    /**
303
+     * @param string $functionName
304
+     * @param array $args
305
+     */
306
+    private function preFunctionCall($functionName, $args) {
307
+        $this->curFunc = $functionName;
308
+        $this->curArgs = $args;
309
+    }
310
+
311
+    /**
312
+     * Analyzes the returned LDAP error and acts accordingly if not 0
313
+     *
314
+     * @param resource $resource the LDAP Connection resource
315
+     * @throws ConstraintViolationException
316
+     * @throws ServerNotAvailableException
317
+     * @throws \Exception
318
+     */
319
+    private function processLDAPError($resource) {
320
+        $errorCode = ldap_errno($resource);
321
+        if($errorCode === 0) {
322
+            return;
323
+        }
324
+        $errorMsg  = ldap_error($resource);
325
+
326
+        if($this->curFunc === 'ldap_get_entries'
327
+            && $errorCode === -4) {
328
+        } else if ($errorCode === 32) {
329
+            //for now
330
+        } else if ($errorCode === 10) {
331
+            //referrals, we switch them off, but then there is AD :)
332
+        } else if ($errorCode === -1) {
333
+            throw new ServerNotAvailableException('Lost connection to LDAP server.');
334
+        } else if ($errorCode === 48) {
335
+            throw new \Exception('LDAP authentication method rejected', $errorCode);
336
+        } else if ($errorCode === 1) {
337
+            throw new \Exception('LDAP Operations error', $errorCode);
338
+        } else if ($errorCode === 19) {
339
+            ldap_get_option($this->curArgs[0], LDAP_OPT_ERROR_STRING, $extended_error);
340
+            throw new ConstraintViolationException(!empty($extended_error)?$extended_error:$errorMsg, $errorCode);
341
+        } else {
342
+            \OCP\Util::writeLog('user_ldap',
343
+                'LDAP error '.$errorMsg.' (' .
344
+                $errorCode.') after calling '.
345
+                $this->curFunc,
346
+                \OCP\Util::DEBUG);
347
+        }
348
+    }
349
+
350
+    /**
351
+     * Called after an ldap method is run to act on LDAP error if necessary
352
+     */
353
+    private function postFunctionCall() {
354
+        if($this->isResource($this->curArgs[0])) {
355
+            $resource = $this->curArgs[0];
356
+        } else if(
357
+                $this->curFunc === 'ldap_search'
358
+            && is_array($this->curArgs[0])
359
+            && $this->isResource($this->curArgs[0][0])
360
+        ) {
361
+            // we use always the same LDAP connection resource, is enough to
362
+            // take the first one.
363
+            $resource = $this->curArgs[0][0];
364
+        } else {
365
+            return;
366
+        }
367
+
368
+        $this->processLDAPError($resource);
369
+
370
+        $this->curFunc = '';
371
+        $this->curArgs = [];
372
+    }
373 373
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/User.php 1 patch
Indentation   +499 added lines, -499 removed lines patch added patch discarded remove patch
@@ -41,504 +41,504 @@
 block discarded – undo
41 41
  * represents an LDAP user, gets and holds user-specific information from LDAP
42 42
  */
43 43
 class User {
44
-	/**
45
-	 * @var IUserTools
46
-	 */
47
-	protected $access;
48
-	/**
49
-	 * @var Connection
50
-	 */
51
-	protected $connection;
52
-	/**
53
-	 * @var IConfig
54
-	 */
55
-	protected $config;
56
-	/**
57
-	 * @var FilesystemHelper
58
-	 */
59
-	protected $fs;
60
-	/**
61
-	 * @var Image
62
-	 */
63
-	protected $image;
64
-	/**
65
-	 * @var LogWrapper
66
-	 */
67
-	protected $log;
68
-	/**
69
-	 * @var IAvatarManager
70
-	 */
71
-	protected $avatarManager;
72
-	/**
73
-	 * @var IUserManager
74
-	 */
75
-	protected $userManager;
76
-	/**
77
-	 * @var string
78
-	 */
79
-	protected $dn;
80
-	/**
81
-	 * @var string
82
-	 */
83
-	protected $uid;
84
-	/**
85
-	 * @var string[]
86
-	 */
87
-	protected $refreshedFeatures = array();
88
-	/**
89
-	 * @var string
90
-	 */
91
-	protected $avatarImage;
92
-
93
-	/**
94
-	 * DB config keys for user preferences
95
-	 */
96
-	const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
97
-	const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
98
-
99
-	/**
100
-	 * @brief constructor, make sure the subclasses call this one!
101
-	 * @param string $username the internal username
102
-	 * @param string $dn the LDAP DN
103
-	 * @param IUserTools $access an instance that implements IUserTools for
104
-	 * LDAP interaction
105
-	 * @param IConfig $config
106
-	 * @param FilesystemHelper $fs
107
-	 * @param Image $image any empty instance
108
-	 * @param LogWrapper $log
109
-	 * @param IAvatarManager $avatarManager
110
-	 * @param IUserManager $userManager
111
-	 */
112
-	public function __construct($username, $dn, IUserTools $access,
113
-		IConfig $config, FilesystemHelper $fs, Image $image,
114
-		LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager) {
115
-
116
-		if ($username === null) {
117
-			$log->log("uid for '$dn' must not be null!", Util::ERROR);
118
-			throw new \InvalidArgumentException('uid must not be null!');
119
-		} else if ($username === '') {
120
-			$log->log("uid for '$dn' must not be an empty string", Util::ERROR);
121
-			throw new \InvalidArgumentException('uid must not be an empty string!');
122
-		}
123
-
124
-		$this->access        = $access;
125
-		$this->connection    = $access->getConnection();
126
-		$this->config        = $config;
127
-		$this->fs            = $fs;
128
-		$this->dn            = $dn;
129
-		$this->uid           = $username;
130
-		$this->image         = $image;
131
-		$this->log           = $log;
132
-		$this->avatarManager = $avatarManager;
133
-		$this->userManager   = $userManager;
134
-	}
135
-
136
-	/**
137
-	 * @brief updates properties like email, quota or avatar provided by LDAP
138
-	 * @return null
139
-	 */
140
-	public function update() {
141
-		if(is_null($this->dn)) {
142
-			return null;
143
-		}
144
-
145
-		$hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
146
-				self::USER_PREFKEY_FIRSTLOGIN, 0);
147
-
148
-		if($this->needsRefresh()) {
149
-			$this->updateEmail();
150
-			$this->updateQuota();
151
-			if($hasLoggedIn !== 0) {
152
-				//we do not need to try it, when the user has not been logged in
153
-				//before, because the file system will not be ready.
154
-				$this->updateAvatar();
155
-				//in order to get an avatar as soon as possible, mark the user
156
-				//as refreshed only when updating the avatar did happen
157
-				$this->markRefreshTime();
158
-			}
159
-		}
160
-	}
161
-
162
-	/**
163
-	 * processes results from LDAP for attributes as returned by getAttributesToRead()
164
-	 * @param array $ldapEntry the user entry as retrieved from LDAP
165
-	 */
166
-	public function processAttributes($ldapEntry) {
167
-		$this->markRefreshTime();
168
-		//Quota
169
-		$attr = strtolower($this->connection->ldapQuotaAttribute);
170
-		if(isset($ldapEntry[$attr])) {
171
-			$this->updateQuota($ldapEntry[$attr][0]);
172
-		}
173
-		unset($attr);
174
-
175
-		//Email
176
-		$attr = strtolower($this->connection->ldapEmailAttribute);
177
-		if(isset($ldapEntry[$attr])) {
178
-			$this->updateEmail($ldapEntry[$attr][0]);
179
-		}
180
-		unset($attr);
181
-
182
-		//displayName
183
-		$displayName = $displayName2 = '';
184
-		$attr = strtolower($this->connection->ldapUserDisplayName);
185
-		if(isset($ldapEntry[$attr])) {
186
-			$displayName = strval($ldapEntry[$attr][0]);
187
-		}
188
-		$attr = strtolower($this->connection->ldapUserDisplayName2);
189
-		if(isset($ldapEntry[$attr])) {
190
-			$displayName2 = strval($ldapEntry[$attr][0]);
191
-		}
192
-		if ($displayName !== '') {
193
-			$this->composeAndStoreDisplayName($displayName);
194
-			$this->access->cacheUserDisplayName(
195
-				$this->getUsername(),
196
-				$displayName,
197
-				$displayName2
198
-			);
199
-		}
200
-		unset($attr);
201
-
202
-		// LDAP Username, needed for s2s sharing
203
-		if(isset($ldapEntry['uid'])) {
204
-			$this->storeLDAPUserName($ldapEntry['uid'][0]);
205
-		} else if(isset($ldapEntry['samaccountname'])) {
206
-			$this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
207
-		}
208
-
209
-		//homePath
210
-		if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
211
-			$attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
212
-			if(isset($ldapEntry[$attr])) {
213
-				$this->access->cacheUserHome(
214
-					$this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
215
-			}
216
-		}
217
-
218
-		//memberOf groups
219
-		$cacheKey = 'getMemberOf'.$this->getUsername();
220
-		$groups = false;
221
-		if(isset($ldapEntry['memberof'])) {
222
-			$groups = $ldapEntry['memberof'];
223
-		}
224
-		$this->connection->writeToCache($cacheKey, $groups);
225
-
226
-		//Avatar
227
-		$attrs = array('jpegphoto', 'thumbnailphoto');
228
-		foreach ($attrs as $attr)  {
229
-			if(isset($ldapEntry[$attr])) {
230
-				$this->avatarImage = $ldapEntry[$attr][0];
231
-				// the call to the method that saves the avatar in the file
232
-				// system must be postponed after the login. It is to ensure
233
-				// external mounts are mounted properly (e.g. with login
234
-				// credentials from the session).
235
-				\OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
236
-				break;
237
-			}
238
-		}
239
-	}
240
-
241
-	/**
242
-	 * @brief returns the LDAP DN of the user
243
-	 * @return string
244
-	 */
245
-	public function getDN() {
246
-		return $this->dn;
247
-	}
248
-
249
-	/**
250
-	 * @brief returns the ownCloud internal username of the user
251
-	 * @return string
252
-	 */
253
-	public function getUsername() {
254
-		return $this->uid;
255
-	}
256
-
257
-	/**
258
-	 * returns the home directory of the user if specified by LDAP settings
259
-	 * @param string $valueFromLDAP
260
-	 * @return bool|string
261
-	 * @throws \Exception
262
-	 */
263
-	public function getHomePath($valueFromLDAP = null) {
264
-		$path = strval($valueFromLDAP);
265
-		$attr = null;
266
-
267
-		if (is_null($valueFromLDAP)
268
-		   && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
269
-		   && $this->access->connection->homeFolderNamingRule !== 'attr:')
270
-		{
271
-			$attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
272
-			$homedir = $this->access->readAttribute(
273
-				$this->access->username2dn($this->getUsername()), $attr);
274
-			if ($homedir && isset($homedir[0])) {
275
-				$path = $homedir[0];
276
-			}
277
-		}
278
-
279
-		if ($path !== '') {
280
-			//if attribute's value is an absolute path take this, otherwise append it to data dir
281
-			//check for / at the beginning or pattern c:\ resp. c:/
282
-			if(   '/' !== $path[0]
283
-			   && !(3 < strlen($path) && ctype_alpha($path[0])
284
-			       && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
285
-			) {
286
-				$path = $this->config->getSystemValue('datadirectory',
287
-						\OC::$SERVERROOT.'/data' ) . '/' . $path;
288
-			}
289
-			//we need it to store it in the DB as well in case a user gets
290
-			//deleted so we can clean up afterwards
291
-			$this->config->setUserValue(
292
-				$this->getUsername(), 'user_ldap', 'homePath', $path
293
-			);
294
-			return $path;
295
-		}
296
-
297
-		if(    !is_null($attr)
298
-			&& $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
299
-		) {
300
-			// a naming rule attribute is defined, but it doesn't exist for that LDAP user
301
-			throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
302
-		}
303
-
304
-		//false will apply default behaviour as defined and done by OC_User
305
-		$this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
306
-		return false;
307
-	}
308
-
309
-	public function getMemberOfGroups() {
310
-		$cacheKey = 'getMemberOf'.$this->getUsername();
311
-		$memberOfGroups = $this->connection->getFromCache($cacheKey);
312
-		if(!is_null($memberOfGroups)) {
313
-			return $memberOfGroups;
314
-		}
315
-		$groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
316
-		$this->connection->writeToCache($cacheKey, $groupDNs);
317
-		return $groupDNs;
318
-	}
319
-
320
-	/**
321
-	 * @brief reads the image from LDAP that shall be used as Avatar
322
-	 * @return string data (provided by LDAP) | false
323
-	 */
324
-	public function getAvatarImage() {
325
-		if(!is_null($this->avatarImage)) {
326
-			return $this->avatarImage;
327
-		}
328
-
329
-		$this->avatarImage = false;
330
-		$attributes = array('jpegPhoto', 'thumbnailPhoto');
331
-		foreach($attributes as $attribute) {
332
-			$result = $this->access->readAttribute($this->dn, $attribute);
333
-			if($result !== false && is_array($result) && isset($result[0])) {
334
-				$this->avatarImage = $result[0];
335
-				break;
336
-			}
337
-		}
338
-
339
-		return $this->avatarImage;
340
-	}
341
-
342
-	/**
343
-	 * @brief marks the user as having logged in at least once
344
-	 * @return null
345
-	 */
346
-	public function markLogin() {
347
-		$this->config->setUserValue(
348
-			$this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
349
-	}
350
-
351
-	/**
352
-	 * @brief marks the time when user features like email have been updated
353
-	 * @return null
354
-	 */
355
-	public function markRefreshTime() {
356
-		$this->config->setUserValue(
357
-			$this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
358
-	}
359
-
360
-	/**
361
-	 * @brief checks whether user features needs to be updated again by
362
-	 * comparing the difference of time of the last refresh to now with the
363
-	 * desired interval
364
-	 * @return bool
365
-	 */
366
-	private function needsRefresh() {
367
-		$lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
368
-			self::USER_PREFKEY_LASTREFRESH, 0);
369
-
370
-		//TODO make interval configurable
371
-		if((time() - intval($lastChecked)) < 86400 ) {
372
-			return false;
373
-		}
374
-		return  true;
375
-	}
376
-
377
-	/**
378
-	 * Stores a key-value pair in relation to this user
379
-	 *
380
-	 * @param string $key
381
-	 * @param string $value
382
-	 */
383
-	private function store($key, $value) {
384
-		$this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
385
-	}
386
-
387
-	/**
388
-	 * Composes the display name and stores it in the database. The final
389
-	 * display name is returned.
390
-	 *
391
-	 * @param string $displayName
392
-	 * @param string $displayName2
393
-	 * @returns string the effective display name
394
-	 */
395
-	public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
396
-		$displayName2 = strval($displayName2);
397
-		if($displayName2 !== '') {
398
-			$displayName .= ' (' . $displayName2 . ')';
399
-		}
400
-		$this->store('displayName', $displayName);
401
-		return $displayName;
402
-	}
403
-
404
-	/**
405
-	 * Stores the LDAP Username in the Database
406
-	 * @param string $userName
407
-	 */
408
-	public function storeLDAPUserName($userName) {
409
-		$this->store('uid', $userName);
410
-	}
411
-
412
-	/**
413
-	 * @brief checks whether an update method specified by feature was run
414
-	 * already. If not, it will marked like this, because it is expected that
415
-	 * the method will be run, when false is returned.
416
-	 * @param string $feature email | quota | avatar (can be extended)
417
-	 * @return bool
418
-	 */
419
-	private function wasRefreshed($feature) {
420
-		if(isset($this->refreshedFeatures[$feature])) {
421
-			return true;
422
-		}
423
-		$this->refreshedFeatures[$feature] = 1;
424
-		return false;
425
-	}
426
-
427
-	/**
428
-	 * fetches the email from LDAP and stores it as ownCloud user value
429
-	 * @param string $valueFromLDAP if known, to save an LDAP read request
430
-	 * @return null
431
-	 */
432
-	public function updateEmail($valueFromLDAP = null) {
433
-		if($this->wasRefreshed('email')) {
434
-			return;
435
-		}
436
-		$email = strval($valueFromLDAP);
437
-		if(is_null($valueFromLDAP)) {
438
-			$emailAttribute = $this->connection->ldapEmailAttribute;
439
-			if ($emailAttribute !== '') {
440
-				$aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
441
-				if(is_array($aEmail) && (count($aEmail) > 0)) {
442
-					$email = strval($aEmail[0]);
443
-				}
444
-			}
445
-		}
446
-		if ($email !== '') {
447
-			$user = $this->userManager->get($this->uid);
448
-			if (!is_null($user)) {
449
-				$currentEmail = strval($user->getEMailAddress());
450
-				if ($currentEmail !== $email) {
451
-					$user->setEMailAddress($email);
452
-				}
453
-			}
454
-		}
455
-	}
456
-
457
-	/**
458
-	 * fetches the quota from LDAP and stores it as ownCloud user value
459
-	 * @param string $valueFromLDAP the quota attribute's value can be passed,
460
-	 * to save the readAttribute request
461
-	 * @return null
462
-	 */
463
-	public function updateQuota($valueFromLDAP = null) {
464
-		if($this->wasRefreshed('quota')) {
465
-			return;
466
-		}
467
-		//can be null
468
-		$quotaDefault = $this->connection->ldapQuotaDefault;
469
-		$quota = $quotaDefault !== '' ? $quotaDefault : null;
470
-		$quota = !is_null($valueFromLDAP) ? $valueFromLDAP : $quota;
471
-
472
-		if(is_null($valueFromLDAP)) {
473
-			$quotaAttribute = $this->connection->ldapQuotaAttribute;
474
-			if ($quotaAttribute !== '') {
475
-				$aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
476
-				if($aQuota && (count($aQuota) > 0)) {
477
-					$quota = $aQuota[0];
478
-				}
479
-			}
480
-		}
481
-		if(!is_null($quota)) {
482
-			$this->userManager->get($this->uid)->setQuota($quota);
483
-		}
484
-	}
485
-
486
-	/**
487
-	 * called by a post_login hook to save the avatar picture
488
-	 *
489
-	 * @param array $params
490
-	 */
491
-	public function updateAvatarPostLogin($params) {
492
-		if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
493
-			$this->updateAvatar();
494
-		}
495
-	}
496
-
497
-	/**
498
-	 * @brief attempts to get an image from LDAP and sets it as ownCloud avatar
499
-	 * @return null
500
-	 */
501
-	public function updateAvatar() {
502
-		if($this->wasRefreshed('avatar')) {
503
-			return;
504
-		}
505
-		$avatarImage = $this->getAvatarImage();
506
-		if($avatarImage === false) {
507
-			//not set, nothing left to do;
508
-			return;
509
-		}
510
-		$this->image->loadFromBase64(base64_encode($avatarImage));
511
-		$this->setOwnCloudAvatar();
512
-	}
513
-
514
-	/**
515
-	 * @brief sets an image as ownCloud avatar
516
-	 * @return null
517
-	 */
518
-	private function setOwnCloudAvatar() {
519
-		if(!$this->image->valid()) {
520
-			$this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
521
-			return;
522
-		}
523
-		//make sure it is a square and not bigger than 128x128
524
-		$size = min(array($this->image->width(), $this->image->height(), 128));
525
-		if(!$this->image->centerCrop($size)) {
526
-			$this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
527
-			return;
528
-		}
529
-
530
-		if(!$this->fs->isLoaded()) {
531
-			$this->fs->setup($this->uid);
532
-		}
533
-
534
-		try {
535
-			$avatar = $this->avatarManager->getAvatar($this->uid);
536
-			$avatar->set($this->image);
537
-		} catch (\Exception $e) {
538
-			\OC::$server->getLogger()->notice(
539
-				'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
540
-				['app' => 'user_ldap']);
541
-		}
542
-	}
44
+    /**
45
+     * @var IUserTools
46
+     */
47
+    protected $access;
48
+    /**
49
+     * @var Connection
50
+     */
51
+    protected $connection;
52
+    /**
53
+     * @var IConfig
54
+     */
55
+    protected $config;
56
+    /**
57
+     * @var FilesystemHelper
58
+     */
59
+    protected $fs;
60
+    /**
61
+     * @var Image
62
+     */
63
+    protected $image;
64
+    /**
65
+     * @var LogWrapper
66
+     */
67
+    protected $log;
68
+    /**
69
+     * @var IAvatarManager
70
+     */
71
+    protected $avatarManager;
72
+    /**
73
+     * @var IUserManager
74
+     */
75
+    protected $userManager;
76
+    /**
77
+     * @var string
78
+     */
79
+    protected $dn;
80
+    /**
81
+     * @var string
82
+     */
83
+    protected $uid;
84
+    /**
85
+     * @var string[]
86
+     */
87
+    protected $refreshedFeatures = array();
88
+    /**
89
+     * @var string
90
+     */
91
+    protected $avatarImage;
92
+
93
+    /**
94
+     * DB config keys for user preferences
95
+     */
96
+    const USER_PREFKEY_FIRSTLOGIN  = 'firstLoginAccomplished';
97
+    const USER_PREFKEY_LASTREFRESH = 'lastFeatureRefresh';
98
+
99
+    /**
100
+     * @brief constructor, make sure the subclasses call this one!
101
+     * @param string $username the internal username
102
+     * @param string $dn the LDAP DN
103
+     * @param IUserTools $access an instance that implements IUserTools for
104
+     * LDAP interaction
105
+     * @param IConfig $config
106
+     * @param FilesystemHelper $fs
107
+     * @param Image $image any empty instance
108
+     * @param LogWrapper $log
109
+     * @param IAvatarManager $avatarManager
110
+     * @param IUserManager $userManager
111
+     */
112
+    public function __construct($username, $dn, IUserTools $access,
113
+        IConfig $config, FilesystemHelper $fs, Image $image,
114
+        LogWrapper $log, IAvatarManager $avatarManager, IUserManager $userManager) {
115
+
116
+        if ($username === null) {
117
+            $log->log("uid for '$dn' must not be null!", Util::ERROR);
118
+            throw new \InvalidArgumentException('uid must not be null!');
119
+        } else if ($username === '') {
120
+            $log->log("uid for '$dn' must not be an empty string", Util::ERROR);
121
+            throw new \InvalidArgumentException('uid must not be an empty string!');
122
+        }
123
+
124
+        $this->access        = $access;
125
+        $this->connection    = $access->getConnection();
126
+        $this->config        = $config;
127
+        $this->fs            = $fs;
128
+        $this->dn            = $dn;
129
+        $this->uid           = $username;
130
+        $this->image         = $image;
131
+        $this->log           = $log;
132
+        $this->avatarManager = $avatarManager;
133
+        $this->userManager   = $userManager;
134
+    }
135
+
136
+    /**
137
+     * @brief updates properties like email, quota or avatar provided by LDAP
138
+     * @return null
139
+     */
140
+    public function update() {
141
+        if(is_null($this->dn)) {
142
+            return null;
143
+        }
144
+
145
+        $hasLoggedIn = $this->config->getUserValue($this->uid, 'user_ldap',
146
+                self::USER_PREFKEY_FIRSTLOGIN, 0);
147
+
148
+        if($this->needsRefresh()) {
149
+            $this->updateEmail();
150
+            $this->updateQuota();
151
+            if($hasLoggedIn !== 0) {
152
+                //we do not need to try it, when the user has not been logged in
153
+                //before, because the file system will not be ready.
154
+                $this->updateAvatar();
155
+                //in order to get an avatar as soon as possible, mark the user
156
+                //as refreshed only when updating the avatar did happen
157
+                $this->markRefreshTime();
158
+            }
159
+        }
160
+    }
161
+
162
+    /**
163
+     * processes results from LDAP for attributes as returned by getAttributesToRead()
164
+     * @param array $ldapEntry the user entry as retrieved from LDAP
165
+     */
166
+    public function processAttributes($ldapEntry) {
167
+        $this->markRefreshTime();
168
+        //Quota
169
+        $attr = strtolower($this->connection->ldapQuotaAttribute);
170
+        if(isset($ldapEntry[$attr])) {
171
+            $this->updateQuota($ldapEntry[$attr][0]);
172
+        }
173
+        unset($attr);
174
+
175
+        //Email
176
+        $attr = strtolower($this->connection->ldapEmailAttribute);
177
+        if(isset($ldapEntry[$attr])) {
178
+            $this->updateEmail($ldapEntry[$attr][0]);
179
+        }
180
+        unset($attr);
181
+
182
+        //displayName
183
+        $displayName = $displayName2 = '';
184
+        $attr = strtolower($this->connection->ldapUserDisplayName);
185
+        if(isset($ldapEntry[$attr])) {
186
+            $displayName = strval($ldapEntry[$attr][0]);
187
+        }
188
+        $attr = strtolower($this->connection->ldapUserDisplayName2);
189
+        if(isset($ldapEntry[$attr])) {
190
+            $displayName2 = strval($ldapEntry[$attr][0]);
191
+        }
192
+        if ($displayName !== '') {
193
+            $this->composeAndStoreDisplayName($displayName);
194
+            $this->access->cacheUserDisplayName(
195
+                $this->getUsername(),
196
+                $displayName,
197
+                $displayName2
198
+            );
199
+        }
200
+        unset($attr);
201
+
202
+        // LDAP Username, needed for s2s sharing
203
+        if(isset($ldapEntry['uid'])) {
204
+            $this->storeLDAPUserName($ldapEntry['uid'][0]);
205
+        } else if(isset($ldapEntry['samaccountname'])) {
206
+            $this->storeLDAPUserName($ldapEntry['samaccountname'][0]);
207
+        }
208
+
209
+        //homePath
210
+        if(strpos($this->connection->homeFolderNamingRule, 'attr:') === 0) {
211
+            $attr = strtolower(substr($this->connection->homeFolderNamingRule, strlen('attr:')));
212
+            if(isset($ldapEntry[$attr])) {
213
+                $this->access->cacheUserHome(
214
+                    $this->getUsername(), $this->getHomePath($ldapEntry[$attr][0]));
215
+            }
216
+        }
217
+
218
+        //memberOf groups
219
+        $cacheKey = 'getMemberOf'.$this->getUsername();
220
+        $groups = false;
221
+        if(isset($ldapEntry['memberof'])) {
222
+            $groups = $ldapEntry['memberof'];
223
+        }
224
+        $this->connection->writeToCache($cacheKey, $groups);
225
+
226
+        //Avatar
227
+        $attrs = array('jpegphoto', 'thumbnailphoto');
228
+        foreach ($attrs as $attr)  {
229
+            if(isset($ldapEntry[$attr])) {
230
+                $this->avatarImage = $ldapEntry[$attr][0];
231
+                // the call to the method that saves the avatar in the file
232
+                // system must be postponed after the login. It is to ensure
233
+                // external mounts are mounted properly (e.g. with login
234
+                // credentials from the session).
235
+                \OCP\Util::connectHook('OC_User', 'post_login', $this, 'updateAvatarPostLogin');
236
+                break;
237
+            }
238
+        }
239
+    }
240
+
241
+    /**
242
+     * @brief returns the LDAP DN of the user
243
+     * @return string
244
+     */
245
+    public function getDN() {
246
+        return $this->dn;
247
+    }
248
+
249
+    /**
250
+     * @brief returns the ownCloud internal username of the user
251
+     * @return string
252
+     */
253
+    public function getUsername() {
254
+        return $this->uid;
255
+    }
256
+
257
+    /**
258
+     * returns the home directory of the user if specified by LDAP settings
259
+     * @param string $valueFromLDAP
260
+     * @return bool|string
261
+     * @throws \Exception
262
+     */
263
+    public function getHomePath($valueFromLDAP = null) {
264
+        $path = strval($valueFromLDAP);
265
+        $attr = null;
266
+
267
+        if (is_null($valueFromLDAP)
268
+           && strpos($this->access->connection->homeFolderNamingRule, 'attr:') === 0
269
+           && $this->access->connection->homeFolderNamingRule !== 'attr:')
270
+        {
271
+            $attr = substr($this->access->connection->homeFolderNamingRule, strlen('attr:'));
272
+            $homedir = $this->access->readAttribute(
273
+                $this->access->username2dn($this->getUsername()), $attr);
274
+            if ($homedir && isset($homedir[0])) {
275
+                $path = $homedir[0];
276
+            }
277
+        }
278
+
279
+        if ($path !== '') {
280
+            //if attribute's value is an absolute path take this, otherwise append it to data dir
281
+            //check for / at the beginning or pattern c:\ resp. c:/
282
+            if(   '/' !== $path[0]
283
+               && !(3 < strlen($path) && ctype_alpha($path[0])
284
+                   && $path[1] === ':' && ('\\' === $path[2] || '/' === $path[2]))
285
+            ) {
286
+                $path = $this->config->getSystemValue('datadirectory',
287
+                        \OC::$SERVERROOT.'/data' ) . '/' . $path;
288
+            }
289
+            //we need it to store it in the DB as well in case a user gets
290
+            //deleted so we can clean up afterwards
291
+            $this->config->setUserValue(
292
+                $this->getUsername(), 'user_ldap', 'homePath', $path
293
+            );
294
+            return $path;
295
+        }
296
+
297
+        if(    !is_null($attr)
298
+            && $this->config->getAppValue('user_ldap', 'enforce_home_folder_naming_rule', true)
299
+        ) {
300
+            // a naming rule attribute is defined, but it doesn't exist for that LDAP user
301
+            throw new \Exception('Home dir attribute can\'t be read from LDAP for uid: ' . $this->getUsername());
302
+        }
303
+
304
+        //false will apply default behaviour as defined and done by OC_User
305
+        $this->config->setUserValue($this->getUsername(), 'user_ldap', 'homePath', '');
306
+        return false;
307
+    }
308
+
309
+    public function getMemberOfGroups() {
310
+        $cacheKey = 'getMemberOf'.$this->getUsername();
311
+        $memberOfGroups = $this->connection->getFromCache($cacheKey);
312
+        if(!is_null($memberOfGroups)) {
313
+            return $memberOfGroups;
314
+        }
315
+        $groupDNs = $this->access->readAttribute($this->getDN(), 'memberOf');
316
+        $this->connection->writeToCache($cacheKey, $groupDNs);
317
+        return $groupDNs;
318
+    }
319
+
320
+    /**
321
+     * @brief reads the image from LDAP that shall be used as Avatar
322
+     * @return string data (provided by LDAP) | false
323
+     */
324
+    public function getAvatarImage() {
325
+        if(!is_null($this->avatarImage)) {
326
+            return $this->avatarImage;
327
+        }
328
+
329
+        $this->avatarImage = false;
330
+        $attributes = array('jpegPhoto', 'thumbnailPhoto');
331
+        foreach($attributes as $attribute) {
332
+            $result = $this->access->readAttribute($this->dn, $attribute);
333
+            if($result !== false && is_array($result) && isset($result[0])) {
334
+                $this->avatarImage = $result[0];
335
+                break;
336
+            }
337
+        }
338
+
339
+        return $this->avatarImage;
340
+    }
341
+
342
+    /**
343
+     * @brief marks the user as having logged in at least once
344
+     * @return null
345
+     */
346
+    public function markLogin() {
347
+        $this->config->setUserValue(
348
+            $this->uid, 'user_ldap', self::USER_PREFKEY_FIRSTLOGIN, 1);
349
+    }
350
+
351
+    /**
352
+     * @brief marks the time when user features like email have been updated
353
+     * @return null
354
+     */
355
+    public function markRefreshTime() {
356
+        $this->config->setUserValue(
357
+            $this->uid, 'user_ldap', self::USER_PREFKEY_LASTREFRESH, time());
358
+    }
359
+
360
+    /**
361
+     * @brief checks whether user features needs to be updated again by
362
+     * comparing the difference of time of the last refresh to now with the
363
+     * desired interval
364
+     * @return bool
365
+     */
366
+    private function needsRefresh() {
367
+        $lastChecked = $this->config->getUserValue($this->uid, 'user_ldap',
368
+            self::USER_PREFKEY_LASTREFRESH, 0);
369
+
370
+        //TODO make interval configurable
371
+        if((time() - intval($lastChecked)) < 86400 ) {
372
+            return false;
373
+        }
374
+        return  true;
375
+    }
376
+
377
+    /**
378
+     * Stores a key-value pair in relation to this user
379
+     *
380
+     * @param string $key
381
+     * @param string $value
382
+     */
383
+    private function store($key, $value) {
384
+        $this->config->setUserValue($this->uid, 'user_ldap', $key, $value);
385
+    }
386
+
387
+    /**
388
+     * Composes the display name and stores it in the database. The final
389
+     * display name is returned.
390
+     *
391
+     * @param string $displayName
392
+     * @param string $displayName2
393
+     * @returns string the effective display name
394
+     */
395
+    public function composeAndStoreDisplayName($displayName, $displayName2 = '') {
396
+        $displayName2 = strval($displayName2);
397
+        if($displayName2 !== '') {
398
+            $displayName .= ' (' . $displayName2 . ')';
399
+        }
400
+        $this->store('displayName', $displayName);
401
+        return $displayName;
402
+    }
403
+
404
+    /**
405
+     * Stores the LDAP Username in the Database
406
+     * @param string $userName
407
+     */
408
+    public function storeLDAPUserName($userName) {
409
+        $this->store('uid', $userName);
410
+    }
411
+
412
+    /**
413
+     * @brief checks whether an update method specified by feature was run
414
+     * already. If not, it will marked like this, because it is expected that
415
+     * the method will be run, when false is returned.
416
+     * @param string $feature email | quota | avatar (can be extended)
417
+     * @return bool
418
+     */
419
+    private function wasRefreshed($feature) {
420
+        if(isset($this->refreshedFeatures[$feature])) {
421
+            return true;
422
+        }
423
+        $this->refreshedFeatures[$feature] = 1;
424
+        return false;
425
+    }
426
+
427
+    /**
428
+     * fetches the email from LDAP and stores it as ownCloud user value
429
+     * @param string $valueFromLDAP if known, to save an LDAP read request
430
+     * @return null
431
+     */
432
+    public function updateEmail($valueFromLDAP = null) {
433
+        if($this->wasRefreshed('email')) {
434
+            return;
435
+        }
436
+        $email = strval($valueFromLDAP);
437
+        if(is_null($valueFromLDAP)) {
438
+            $emailAttribute = $this->connection->ldapEmailAttribute;
439
+            if ($emailAttribute !== '') {
440
+                $aEmail = $this->access->readAttribute($this->dn, $emailAttribute);
441
+                if(is_array($aEmail) && (count($aEmail) > 0)) {
442
+                    $email = strval($aEmail[0]);
443
+                }
444
+            }
445
+        }
446
+        if ($email !== '') {
447
+            $user = $this->userManager->get($this->uid);
448
+            if (!is_null($user)) {
449
+                $currentEmail = strval($user->getEMailAddress());
450
+                if ($currentEmail !== $email) {
451
+                    $user->setEMailAddress($email);
452
+                }
453
+            }
454
+        }
455
+    }
456
+
457
+    /**
458
+     * fetches the quota from LDAP and stores it as ownCloud user value
459
+     * @param string $valueFromLDAP the quota attribute's value can be passed,
460
+     * to save the readAttribute request
461
+     * @return null
462
+     */
463
+    public function updateQuota($valueFromLDAP = null) {
464
+        if($this->wasRefreshed('quota')) {
465
+            return;
466
+        }
467
+        //can be null
468
+        $quotaDefault = $this->connection->ldapQuotaDefault;
469
+        $quota = $quotaDefault !== '' ? $quotaDefault : null;
470
+        $quota = !is_null($valueFromLDAP) ? $valueFromLDAP : $quota;
471
+
472
+        if(is_null($valueFromLDAP)) {
473
+            $quotaAttribute = $this->connection->ldapQuotaAttribute;
474
+            if ($quotaAttribute !== '') {
475
+                $aQuota = $this->access->readAttribute($this->dn, $quotaAttribute);
476
+                if($aQuota && (count($aQuota) > 0)) {
477
+                    $quota = $aQuota[0];
478
+                }
479
+            }
480
+        }
481
+        if(!is_null($quota)) {
482
+            $this->userManager->get($this->uid)->setQuota($quota);
483
+        }
484
+    }
485
+
486
+    /**
487
+     * called by a post_login hook to save the avatar picture
488
+     *
489
+     * @param array $params
490
+     */
491
+    public function updateAvatarPostLogin($params) {
492
+        if(isset($params['uid']) && $params['uid'] === $this->getUsername()) {
493
+            $this->updateAvatar();
494
+        }
495
+    }
496
+
497
+    /**
498
+     * @brief attempts to get an image from LDAP and sets it as ownCloud avatar
499
+     * @return null
500
+     */
501
+    public function updateAvatar() {
502
+        if($this->wasRefreshed('avatar')) {
503
+            return;
504
+        }
505
+        $avatarImage = $this->getAvatarImage();
506
+        if($avatarImage === false) {
507
+            //not set, nothing left to do;
508
+            return;
509
+        }
510
+        $this->image->loadFromBase64(base64_encode($avatarImage));
511
+        $this->setOwnCloudAvatar();
512
+    }
513
+
514
+    /**
515
+     * @brief sets an image as ownCloud avatar
516
+     * @return null
517
+     */
518
+    private function setOwnCloudAvatar() {
519
+        if(!$this->image->valid()) {
520
+            $this->log->log('jpegPhoto data invalid for '.$this->dn, \OCP\Util::ERROR);
521
+            return;
522
+        }
523
+        //make sure it is a square and not bigger than 128x128
524
+        $size = min(array($this->image->width(), $this->image->height(), 128));
525
+        if(!$this->image->centerCrop($size)) {
526
+            $this->log->log('croping image for avatar failed for '.$this->dn, \OCP\Util::ERROR);
527
+            return;
528
+        }
529
+
530
+        if(!$this->fs->isLoaded()) {
531
+            $this->fs->setup($this->uid);
532
+        }
533
+
534
+        try {
535
+            $avatar = $this->avatarManager->getAvatar($this->uid);
536
+            $avatar->set($this->image);
537
+        } catch (\Exception $e) {
538
+            \OC::$server->getLogger()->notice(
539
+                'Could not set avatar for ' . $this->dn	. ', because: ' . $e->getMessage(),
540
+                ['app' => 'user_ldap']);
541
+        }
542
+    }
543 543
 
544 544
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/DeletedUsersIndex.php 1 patch
Indentation   +70 added lines, -70 removed lines patch added patch discarded remove patch
@@ -31,84 +31,84 @@
 block discarded – undo
31 31
  * @package OCA\User_LDAP
32 32
  */
33 33
 class DeletedUsersIndex {
34
-	/**
35
-	 * @var \OCP\IConfig $config
36
-	 */
37
-	protected $config;
34
+    /**
35
+     * @var \OCP\IConfig $config
36
+     */
37
+    protected $config;
38 38
 
39
-	/**
40
-	 * @var \OCP\IDBConnection $db
41
-	 */
42
-	protected $db;
39
+    /**
40
+     * @var \OCP\IDBConnection $db
41
+     */
42
+    protected $db;
43 43
 
44
-	/**
45
-	 * @var \OCA\User_LDAP\Mapping\UserMapping $mapping
46
-	 */
47
-	protected $mapping;
44
+    /**
45
+     * @var \OCA\User_LDAP\Mapping\UserMapping $mapping
46
+     */
47
+    protected $mapping;
48 48
 
49
-	/**
50
-	 * @var array $deletedUsers
51
-	 */
52
-	protected $deletedUsers;
49
+    /**
50
+     * @var array $deletedUsers
51
+     */
52
+    protected $deletedUsers;
53 53
 
54
-	/**
55
-	 * @param \OCP\IConfig $config
56
-	 * @param \OCP\IDBConnection $db
57
-	 * @param \OCA\User_LDAP\Mapping\UserMapping $mapping
58
-	 */
59
-	public function __construct(\OCP\IConfig $config, \OCP\IDBConnection $db, UserMapping $mapping) {
60
-		$this->config = $config;
61
-		$this->db = $db;
62
-		$this->mapping = $mapping;
63
-	}
54
+    /**
55
+     * @param \OCP\IConfig $config
56
+     * @param \OCP\IDBConnection $db
57
+     * @param \OCA\User_LDAP\Mapping\UserMapping $mapping
58
+     */
59
+    public function __construct(\OCP\IConfig $config, \OCP\IDBConnection $db, UserMapping $mapping) {
60
+        $this->config = $config;
61
+        $this->db = $db;
62
+        $this->mapping = $mapping;
63
+    }
64 64
 
65
-	/**
66
-	 * reads LDAP users marked as deleted from the database
67
-	 * @return \OCA\User_LDAP\User\OfflineUser[]
68
-	 */
69
-	private function fetchDeletedUsers() {
70
-		$deletedUsers = $this->config->getUsersForUserValue(
71
-			'user_ldap', 'isDeleted', '1');
65
+    /**
66
+     * reads LDAP users marked as deleted from the database
67
+     * @return \OCA\User_LDAP\User\OfflineUser[]
68
+     */
69
+    private function fetchDeletedUsers() {
70
+        $deletedUsers = $this->config->getUsersForUserValue(
71
+            'user_ldap', 'isDeleted', '1');
72 72
 
73
-		$userObjects = array();
74
-		foreach($deletedUsers as $user) {
75
-			$userObjects[] = new OfflineUser($user, $this->config, $this->db, $this->mapping);
76
-		}
77
-		$this->deletedUsers = $userObjects;
73
+        $userObjects = array();
74
+        foreach($deletedUsers as $user) {
75
+            $userObjects[] = new OfflineUser($user, $this->config, $this->db, $this->mapping);
76
+        }
77
+        $this->deletedUsers = $userObjects;
78 78
 
79
-		return $this->deletedUsers;
80
-	}
79
+        return $this->deletedUsers;
80
+    }
81 81
 
82
-	/**
83
-	 * returns all LDAP users that are marked as deleted
84
-	 * @return \OCA\User_LDAP\User\OfflineUser[]
85
-	 */
86
-	public function getUsers() {
87
-		if(is_array($this->deletedUsers)) {
88
-			return $this->deletedUsers;
89
-		}
90
-		return $this->fetchDeletedUsers();
91
-	}
82
+    /**
83
+     * returns all LDAP users that are marked as deleted
84
+     * @return \OCA\User_LDAP\User\OfflineUser[]
85
+     */
86
+    public function getUsers() {
87
+        if(is_array($this->deletedUsers)) {
88
+            return $this->deletedUsers;
89
+        }
90
+        return $this->fetchDeletedUsers();
91
+    }
92 92
 
93
-	/**
94
-	 * whether at least one user was detected as deleted
95
-	 * @return bool
96
-	 */
97
-	public function hasUsers() {
98
-		if($this->deletedUsers === false) {
99
-			$this->fetchDeletedUsers();
100
-		}
101
-		if(is_array($this->deletedUsers) && count($this->deletedUsers) > 0) {
102
-			return true;
103
-		}
104
-		return false;
105
-	}
93
+    /**
94
+     * whether at least one user was detected as deleted
95
+     * @return bool
96
+     */
97
+    public function hasUsers() {
98
+        if($this->deletedUsers === false) {
99
+            $this->fetchDeletedUsers();
100
+        }
101
+        if(is_array($this->deletedUsers) && count($this->deletedUsers) > 0) {
102
+            return true;
103
+        }
104
+        return false;
105
+    }
106 106
 
107
-	/**
108
-	 * marks a user as deleted
109
-	 * @param string $ocName
110
-	 */
111
-	public function markUser($ocName) {
112
-		$this->config->setUserValue($ocName, 'user_ldap', 'isDeleted', '1');
113
-	}
107
+    /**
108
+     * marks a user as deleted
109
+     * @param string $ocName
110
+     */
111
+    public function markUser($ocName) {
112
+        $this->config->setUserValue($ocName, 'user_ldap', 'isDeleted', '1');
113
+    }
114 114
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/IUserTools.php 1 patch
Indentation   +5 added lines, -5 removed lines patch added patch discarded remove patch
@@ -30,13 +30,13 @@
 block discarded – undo
30 30
  * defines methods that are required by User class for LDAP interaction
31 31
  */
32 32
 interface IUserTools {
33
-	public function getConnection();
33
+    public function getConnection();
34 34
 
35
-	public function readAttribute($dn, $attr, $filter = 'objectClass=*');
35
+    public function readAttribute($dn, $attr, $filter = 'objectClass=*');
36 36
 
37
-	public function stringResemblesDN($string);
37
+    public function stringResemblesDN($string);
38 38
 
39
-	public function dn2username($dn, $ldapname = null);
39
+    public function dn2username($dn, $ldapname = null);
40 40
 
41
-	public function username2dn($name);
41
+    public function username2dn($name);
42 42
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/Manager.php 1 patch
Indentation   +195 added lines, -195 removed lines patch added patch discarded remove patch
@@ -42,200 +42,200 @@
 block discarded – undo
42 42
  * cache
43 43
  */
44 44
 class Manager {
45
-	/** @var IUserTools */
46
-	protected $access;
47
-
48
-	/** @var IConfig */
49
-	protected $ocConfig;
50
-
51
-	/** @var IDBConnection */
52
-	protected $db;
53
-
54
-	/** @var FilesystemHelper */
55
-	protected $ocFilesystem;
56
-
57
-	/** @var LogWrapper */
58
-	protected $ocLog;
59
-
60
-	/** @var Image */
61
-	protected $image;
62
-
63
-	/** @param \OCP\IAvatarManager */
64
-	protected $avatarManager;
65
-
66
-	/**
67
-	 * @var CappedMemoryCache $usersByDN
68
-	 */
69
-	protected $usersByDN;
70
-	/**
71
-	 * @var CappedMemoryCache $usersByUid
72
-	 */
73
-	protected $usersByUid;
74
-
75
-	/**
76
-	 * @param IConfig $ocConfig
77
-	 * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
78
-	 * gives access to necessary functions from the OC filesystem
79
-	 * @param  \OCA\User_LDAP\LogWrapper $ocLog
80
-	 * @param IAvatarManager $avatarManager
81
-	 * @param Image $image an empty image instance
82
-	 * @param IDBConnection $db
83
-	 * @throws \Exception when the methods mentioned above do not exist
84
-	 */
85
-	public function __construct(IConfig $ocConfig,
86
-								FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
87
-								IAvatarManager $avatarManager, Image $image,
88
-								IDBConnection $db, IUserManager $userManager) {
89
-
90
-		$this->ocConfig      = $ocConfig;
91
-		$this->ocFilesystem  = $ocFilesystem;
92
-		$this->ocLog         = $ocLog;
93
-		$this->avatarManager = $avatarManager;
94
-		$this->image         = $image;
95
-		$this->db            = $db;
96
-		$this->userManager   = $userManager;
97
-		$this->usersByDN     = new CappedMemoryCache();
98
-		$this->usersByUid    = new CappedMemoryCache();
99
-	}
100
-
101
-	/**
102
-	 * @brief binds manager to an instance of IUserTools (implemented by
103
-	 * Access). It needs to be assigned first before the manager can be used.
104
-	 * @param IUserTools
105
-	 */
106
-	public function setLdapAccess(IUserTools $access) {
107
-		$this->access = $access;
108
-	}
109
-
110
-	/**
111
-	 * @brief creates an instance of User and caches (just runtime) it in the
112
-	 * property array
113
-	 * @param string $dn the DN of the user
114
-	 * @param string $uid the internal (owncloud) username
115
-	 * @return \OCA\User_LDAP\User\User
116
-	 */
117
-	private function createAndCache($dn, $uid) {
118
-		$this->checkAccess();
119
-		$user = new User($uid, $dn, $this->access, $this->ocConfig,
120
-			$this->ocFilesystem, clone $this->image, $this->ocLog,
121
-			$this->avatarManager, $this->userManager);
122
-		$this->usersByDN[$dn]   = $user;
123
-		$this->usersByUid[$uid] = $user;
124
-		return $user;
125
-	}
126
-
127
-	/**
128
-	 * @brief checks whether the Access instance has been set
129
-	 * @throws \Exception if Access has not been set
130
-	 * @return null
131
-	 */
132
-	private function checkAccess() {
133
-		if(is_null($this->access)) {
134
-			throw new \Exception('LDAP Access instance must be set first');
135
-		}
136
-	}
137
-
138
-	/**
139
-	 * returns a list of attributes that will be processed further, e.g. quota,
140
-	 * email, displayname, or others.
141
-	 * @param bool $minimal - optional, set to true to skip attributes with big
142
-	 * payload
143
-	 * @return string[]
144
-	 */
145
-	public function getAttributes($minimal = false) {
146
-		$attributes = array('dn', 'uid', 'samaccountname', 'memberof');
147
-		$possible = array(
148
-			$this->access->getConnection()->ldapQuotaAttribute,
149
-			$this->access->getConnection()->ldapEmailAttribute,
150
-			$this->access->getConnection()->ldapUserDisplayName,
151
-			$this->access->getConnection()->ldapUserDisplayName2,
152
-		);
153
-		foreach($possible as $attr) {
154
-			if(!is_null($attr)) {
155
-				$attributes[] = $attr;
156
-			}
157
-		}
158
-
159
-		$homeRule = $this->access->getConnection()->homeFolderNamingRule;
160
-		if(strpos($homeRule, 'attr:') === 0) {
161
-			$attributes[] = substr($homeRule, strlen('attr:'));
162
-		}
163
-
164
-		if(!$minimal) {
165
-			// attributes that are not really important but may come with big
166
-			// payload.
167
-			$attributes = array_merge($attributes, array(
168
-				'jpegphoto',
169
-				'thumbnailphoto'
170
-			));
171
-		}
172
-
173
-		return $attributes;
174
-	}
175
-
176
-	/**
177
-	 * Checks whether the specified user is marked as deleted
178
-	 * @param string $id the ownCloud user name
179
-	 * @return bool
180
-	 */
181
-	public function isDeletedUser($id) {
182
-		$isDeleted = $this->ocConfig->getUserValue(
183
-			$id, 'user_ldap', 'isDeleted', 0);
184
-		return intval($isDeleted) === 1;
185
-	}
186
-
187
-	/**
188
-	 * creates and returns an instance of OfflineUser for the specified user
189
-	 * @param string $id
190
-	 * @return \OCA\User_LDAP\User\OfflineUser
191
-	 */
192
-	public function getDeletedUser($id) {
193
-		return new OfflineUser(
194
-			$id,
195
-			$this->ocConfig,
196
-			$this->db,
197
-			$this->access->getUserMapper());
198
-	}
199
-
200
-	/**
201
-	 * @brief returns a User object by it's ownCloud username
202
-	 * @param string $id the DN or username of the user
203
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
204
-	 */
205
-	protected function createInstancyByUserName($id) {
206
-		//most likely a uid. Check whether it is a deleted user
207
-		if($this->isDeletedUser($id)) {
208
-			return $this->getDeletedUser($id);
209
-		}
210
-		$dn = $this->access->username2dn($id);
211
-		if($dn !== false) {
212
-			return $this->createAndCache($dn, $id);
213
-		}
214
-		return null;
215
-	}
216
-
217
-	/**
218
-	 * @brief returns a User object by it's DN or ownCloud username
219
-	 * @param string $id the DN or username of the user
220
-	 * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
221
-	 * @throws \Exception when connection could not be established
222
-	 */
223
-	public function get($id) {
224
-		$this->checkAccess();
225
-		if(isset($this->usersByDN[$id])) {
226
-			return $this->usersByDN[$id];
227
-		} else if(isset($this->usersByUid[$id])) {
228
-			return $this->usersByUid[$id];
229
-		}
230
-
231
-		if($this->access->stringResemblesDN($id) ) {
232
-			$uid = $this->access->dn2username($id);
233
-			if($uid !== false) {
234
-				return $this->createAndCache($id, $uid);
235
-			}
236
-		}
237
-
238
-		return $this->createInstancyByUserName($id);
239
-	}
45
+    /** @var IUserTools */
46
+    protected $access;
47
+
48
+    /** @var IConfig */
49
+    protected $ocConfig;
50
+
51
+    /** @var IDBConnection */
52
+    protected $db;
53
+
54
+    /** @var FilesystemHelper */
55
+    protected $ocFilesystem;
56
+
57
+    /** @var LogWrapper */
58
+    protected $ocLog;
59
+
60
+    /** @var Image */
61
+    protected $image;
62
+
63
+    /** @param \OCP\IAvatarManager */
64
+    protected $avatarManager;
65
+
66
+    /**
67
+     * @var CappedMemoryCache $usersByDN
68
+     */
69
+    protected $usersByDN;
70
+    /**
71
+     * @var CappedMemoryCache $usersByUid
72
+     */
73
+    protected $usersByUid;
74
+
75
+    /**
76
+     * @param IConfig $ocConfig
77
+     * @param \OCA\User_LDAP\FilesystemHelper $ocFilesystem object that
78
+     * gives access to necessary functions from the OC filesystem
79
+     * @param  \OCA\User_LDAP\LogWrapper $ocLog
80
+     * @param IAvatarManager $avatarManager
81
+     * @param Image $image an empty image instance
82
+     * @param IDBConnection $db
83
+     * @throws \Exception when the methods mentioned above do not exist
84
+     */
85
+    public function __construct(IConfig $ocConfig,
86
+                                FilesystemHelper $ocFilesystem, LogWrapper $ocLog,
87
+                                IAvatarManager $avatarManager, Image $image,
88
+                                IDBConnection $db, IUserManager $userManager) {
89
+
90
+        $this->ocConfig      = $ocConfig;
91
+        $this->ocFilesystem  = $ocFilesystem;
92
+        $this->ocLog         = $ocLog;
93
+        $this->avatarManager = $avatarManager;
94
+        $this->image         = $image;
95
+        $this->db            = $db;
96
+        $this->userManager   = $userManager;
97
+        $this->usersByDN     = new CappedMemoryCache();
98
+        $this->usersByUid    = new CappedMemoryCache();
99
+    }
100
+
101
+    /**
102
+     * @brief binds manager to an instance of IUserTools (implemented by
103
+     * Access). It needs to be assigned first before the manager can be used.
104
+     * @param IUserTools
105
+     */
106
+    public function setLdapAccess(IUserTools $access) {
107
+        $this->access = $access;
108
+    }
109
+
110
+    /**
111
+     * @brief creates an instance of User and caches (just runtime) it in the
112
+     * property array
113
+     * @param string $dn the DN of the user
114
+     * @param string $uid the internal (owncloud) username
115
+     * @return \OCA\User_LDAP\User\User
116
+     */
117
+    private function createAndCache($dn, $uid) {
118
+        $this->checkAccess();
119
+        $user = new User($uid, $dn, $this->access, $this->ocConfig,
120
+            $this->ocFilesystem, clone $this->image, $this->ocLog,
121
+            $this->avatarManager, $this->userManager);
122
+        $this->usersByDN[$dn]   = $user;
123
+        $this->usersByUid[$uid] = $user;
124
+        return $user;
125
+    }
126
+
127
+    /**
128
+     * @brief checks whether the Access instance has been set
129
+     * @throws \Exception if Access has not been set
130
+     * @return null
131
+     */
132
+    private function checkAccess() {
133
+        if(is_null($this->access)) {
134
+            throw new \Exception('LDAP Access instance must be set first');
135
+        }
136
+    }
137
+
138
+    /**
139
+     * returns a list of attributes that will be processed further, e.g. quota,
140
+     * email, displayname, or others.
141
+     * @param bool $minimal - optional, set to true to skip attributes with big
142
+     * payload
143
+     * @return string[]
144
+     */
145
+    public function getAttributes($minimal = false) {
146
+        $attributes = array('dn', 'uid', 'samaccountname', 'memberof');
147
+        $possible = array(
148
+            $this->access->getConnection()->ldapQuotaAttribute,
149
+            $this->access->getConnection()->ldapEmailAttribute,
150
+            $this->access->getConnection()->ldapUserDisplayName,
151
+            $this->access->getConnection()->ldapUserDisplayName2,
152
+        );
153
+        foreach($possible as $attr) {
154
+            if(!is_null($attr)) {
155
+                $attributes[] = $attr;
156
+            }
157
+        }
158
+
159
+        $homeRule = $this->access->getConnection()->homeFolderNamingRule;
160
+        if(strpos($homeRule, 'attr:') === 0) {
161
+            $attributes[] = substr($homeRule, strlen('attr:'));
162
+        }
163
+
164
+        if(!$minimal) {
165
+            // attributes that are not really important but may come with big
166
+            // payload.
167
+            $attributes = array_merge($attributes, array(
168
+                'jpegphoto',
169
+                'thumbnailphoto'
170
+            ));
171
+        }
172
+
173
+        return $attributes;
174
+    }
175
+
176
+    /**
177
+     * Checks whether the specified user is marked as deleted
178
+     * @param string $id the ownCloud user name
179
+     * @return bool
180
+     */
181
+    public function isDeletedUser($id) {
182
+        $isDeleted = $this->ocConfig->getUserValue(
183
+            $id, 'user_ldap', 'isDeleted', 0);
184
+        return intval($isDeleted) === 1;
185
+    }
186
+
187
+    /**
188
+     * creates and returns an instance of OfflineUser for the specified user
189
+     * @param string $id
190
+     * @return \OCA\User_LDAP\User\OfflineUser
191
+     */
192
+    public function getDeletedUser($id) {
193
+        return new OfflineUser(
194
+            $id,
195
+            $this->ocConfig,
196
+            $this->db,
197
+            $this->access->getUserMapper());
198
+    }
199
+
200
+    /**
201
+     * @brief returns a User object by it's ownCloud username
202
+     * @param string $id the DN or username of the user
203
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
204
+     */
205
+    protected function createInstancyByUserName($id) {
206
+        //most likely a uid. Check whether it is a deleted user
207
+        if($this->isDeletedUser($id)) {
208
+            return $this->getDeletedUser($id);
209
+        }
210
+        $dn = $this->access->username2dn($id);
211
+        if($dn !== false) {
212
+            return $this->createAndCache($dn, $id);
213
+        }
214
+        return null;
215
+    }
216
+
217
+    /**
218
+     * @brief returns a User object by it's DN or ownCloud username
219
+     * @param string $id the DN or username of the user
220
+     * @return \OCA\User_LDAP\User\User|\OCA\User_LDAP\User\OfflineUser|null
221
+     * @throws \Exception when connection could not be established
222
+     */
223
+    public function get($id) {
224
+        $this->checkAccess();
225
+        if(isset($this->usersByDN[$id])) {
226
+            return $this->usersByDN[$id];
227
+        } else if(isset($this->usersByUid[$id])) {
228
+            return $this->usersByUid[$id];
229
+        }
230
+
231
+        if($this->access->stringResemblesDN($id) ) {
232
+            $uid = $this->access->dn2username($id);
233
+            if($uid !== false) {
234
+                return $this->createAndCache($id, $uid);
235
+            }
236
+        }
237
+
238
+        return $this->createInstancyByUserName($id);
239
+    }
240 240
 
241 241
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/User/OfflineUser.php 1 patch
Indentation   +193 added lines, -193 removed lines patch added patch discarded remove patch
@@ -27,205 +27,205 @@
 block discarded – undo
27 27
 use OCA\User_LDAP\Mapping\UserMapping;
28 28
 
29 29
 class OfflineUser {
30
-	/**
31
-	 * @var string $ocName
32
-	 */
33
-	protected $ocName;
34
-	/**
35
-	 * @var string $dn
36
-	 */
37
-	protected $dn;
38
-	/**
39
-	 * @var string $uid the UID as provided by LDAP
40
-	 */
41
-	protected $uid;
42
-	/**
43
-	 * @var string $displayName
44
-	 */
45
-	protected $displayName;
46
-	/**
47
-	 * @var string $homePath
48
-	 */
49
-	protected $homePath;
50
-	/**
51
-	 * @var string $lastLogin the timestamp of the last login
52
-	 */
53
-	protected $lastLogin;
54
-	/**
55
-	 * @var string $email
56
-	 */
57
-	protected $email;
58
-	/**
59
-	 * @var bool $hasActiveShares
60
-	 */
61
-	protected $hasActiveShares;
62
-	/**
63
-	 * @var \OCP\IConfig $config
64
-	 */
65
-	protected $config;
66
-	/**
67
-	 * @var \OCP\IDBConnection $db
68
-	 */
69
-	protected $db;
70
-	/**
71
-	 * @var \OCA\User_LDAP\Mapping\UserMapping
72
-	 */
73
-	protected $mapping;
74
-
75
-	/**
76
-	 * @param string $ocName
77
-	 * @param \OCP\IConfig $config
78
-	 * @param \OCP\IDBConnection $db
79
-	 * @param \OCA\User_LDAP\Mapping\UserMapping $mapping
80
-	 */
81
-	public function __construct($ocName, \OCP\IConfig $config, \OCP\IDBConnection $db, UserMapping $mapping) {
82
-		$this->ocName = $ocName;
83
-		$this->config = $config;
84
-		$this->db = $db;
85
-		$this->mapping = $mapping;
86
-		$this->fetchDetails();
87
-	}
88
-
89
-	/**
90
-	 * remove the Delete-flag from the user.
91
-	 */
92
-	public function unmark() {
93
-		$this->config->setUserValue($this->ocName, 'user_ldap', 'isDeleted', '0');
94
-	}
95
-
96
-	/**
97
-	 * exports the user details in an assoc array
98
-	 * @return array
99
-	 */
100
-	public function export() {
101
-		$data = array();
102
-		$data['ocName'] = $this->getOCName();
103
-		$data['dn'] = $this->getDN();
104
-		$data['uid'] = $this->getUID();
105
-		$data['displayName'] = $this->getDisplayName();
106
-		$data['homePath'] = $this->getHomePath();
107
-		$data['lastLogin'] = $this->getLastLogin();
108
-		$data['email'] = $this->getEmail();
109
-		$data['hasActiveShares'] = $this->getHasActiveShares();
110
-
111
-		return $data;
112
-	}
113
-
114
-	/**
115
-	 * getter for ownCloud internal name
116
-	 * @return string
117
-	 */
118
-	public function getOCName() {
119
-		return $this->ocName;
120
-	}
121
-
122
-	/**
123
-	 * getter for LDAP uid
124
-	 * @return string
125
-	 */
126
-	public function getUID() {
127
-		return $this->uid;
128
-	}
129
-
130
-	/**
131
-	 * getter for LDAP DN
132
-	 * @return string
133
-	 */
134
-	public function getDN() {
135
-		return $this->dn;
136
-	}
137
-
138
-	/**
139
-	 * getter for display name
140
-	 * @return string
141
-	 */
142
-	public function getDisplayName() {
143
-		return $this->displayName;
144
-	}
145
-
146
-	/**
147
-	 * getter for email
148
-	 * @return string
149
-	 */
150
-	public function getEmail() {
151
-		return $this->email;
152
-	}
153
-
154
-	/**
155
-	 * getter for home directory path
156
-	 * @return string
157
-	 */
158
-	public function getHomePath() {
159
-		return $this->homePath;
160
-	}
161
-
162
-	/**
163
-	 * getter for the last login timestamp
164
-	 * @return int
165
-	 */
166
-	public function getLastLogin() {
167
-		return intval($this->lastLogin);
168
-	}
169
-
170
-	/**
171
-	 * getter for having active shares
172
-	 * @return bool
173
-	 */
174
-	public function getHasActiveShares() {
175
-		return $this->hasActiveShares;
176
-	}
177
-
178
-	/**
179
-	 * reads the user details
180
-	 */
181
-	protected function fetchDetails() {
182
-		$properties = array (
183
-			'displayName' => 'user_ldap',
184
-			'uid'         => 'user_ldap',
185
-			'homePath'    => 'user_ldap',
186
-			'email'       => 'settings',
187
-			'lastLogin'   => 'login'
188
-		);
189
-		foreach($properties as $property => $app) {
190
-			$this->$property = $this->config->getUserValue($this->ocName, $app, $property, '');
191
-		}
192
-
193
-		$dn = $this->mapping->getDNByName($this->ocName);
194
-		$this->dn = ($dn !== false) ? $dn : '';
195
-
196
-		$this->determineShares();
197
-	}
198
-
199
-
200
-	/**
201
-	 * finds out whether the user has active shares. The result is stored in
202
-	 * $this->hasActiveShares
203
-	 */
204
-	protected function determineShares() {
205
-		$query = $this->db->prepare('
30
+    /**
31
+     * @var string $ocName
32
+     */
33
+    protected $ocName;
34
+    /**
35
+     * @var string $dn
36
+     */
37
+    protected $dn;
38
+    /**
39
+     * @var string $uid the UID as provided by LDAP
40
+     */
41
+    protected $uid;
42
+    /**
43
+     * @var string $displayName
44
+     */
45
+    protected $displayName;
46
+    /**
47
+     * @var string $homePath
48
+     */
49
+    protected $homePath;
50
+    /**
51
+     * @var string $lastLogin the timestamp of the last login
52
+     */
53
+    protected $lastLogin;
54
+    /**
55
+     * @var string $email
56
+     */
57
+    protected $email;
58
+    /**
59
+     * @var bool $hasActiveShares
60
+     */
61
+    protected $hasActiveShares;
62
+    /**
63
+     * @var \OCP\IConfig $config
64
+     */
65
+    protected $config;
66
+    /**
67
+     * @var \OCP\IDBConnection $db
68
+     */
69
+    protected $db;
70
+    /**
71
+     * @var \OCA\User_LDAP\Mapping\UserMapping
72
+     */
73
+    protected $mapping;
74
+
75
+    /**
76
+     * @param string $ocName
77
+     * @param \OCP\IConfig $config
78
+     * @param \OCP\IDBConnection $db
79
+     * @param \OCA\User_LDAP\Mapping\UserMapping $mapping
80
+     */
81
+    public function __construct($ocName, \OCP\IConfig $config, \OCP\IDBConnection $db, UserMapping $mapping) {
82
+        $this->ocName = $ocName;
83
+        $this->config = $config;
84
+        $this->db = $db;
85
+        $this->mapping = $mapping;
86
+        $this->fetchDetails();
87
+    }
88
+
89
+    /**
90
+     * remove the Delete-flag from the user.
91
+     */
92
+    public function unmark() {
93
+        $this->config->setUserValue($this->ocName, 'user_ldap', 'isDeleted', '0');
94
+    }
95
+
96
+    /**
97
+     * exports the user details in an assoc array
98
+     * @return array
99
+     */
100
+    public function export() {
101
+        $data = array();
102
+        $data['ocName'] = $this->getOCName();
103
+        $data['dn'] = $this->getDN();
104
+        $data['uid'] = $this->getUID();
105
+        $data['displayName'] = $this->getDisplayName();
106
+        $data['homePath'] = $this->getHomePath();
107
+        $data['lastLogin'] = $this->getLastLogin();
108
+        $data['email'] = $this->getEmail();
109
+        $data['hasActiveShares'] = $this->getHasActiveShares();
110
+
111
+        return $data;
112
+    }
113
+
114
+    /**
115
+     * getter for ownCloud internal name
116
+     * @return string
117
+     */
118
+    public function getOCName() {
119
+        return $this->ocName;
120
+    }
121
+
122
+    /**
123
+     * getter for LDAP uid
124
+     * @return string
125
+     */
126
+    public function getUID() {
127
+        return $this->uid;
128
+    }
129
+
130
+    /**
131
+     * getter for LDAP DN
132
+     * @return string
133
+     */
134
+    public function getDN() {
135
+        return $this->dn;
136
+    }
137
+
138
+    /**
139
+     * getter for display name
140
+     * @return string
141
+     */
142
+    public function getDisplayName() {
143
+        return $this->displayName;
144
+    }
145
+
146
+    /**
147
+     * getter for email
148
+     * @return string
149
+     */
150
+    public function getEmail() {
151
+        return $this->email;
152
+    }
153
+
154
+    /**
155
+     * getter for home directory path
156
+     * @return string
157
+     */
158
+    public function getHomePath() {
159
+        return $this->homePath;
160
+    }
161
+
162
+    /**
163
+     * getter for the last login timestamp
164
+     * @return int
165
+     */
166
+    public function getLastLogin() {
167
+        return intval($this->lastLogin);
168
+    }
169
+
170
+    /**
171
+     * getter for having active shares
172
+     * @return bool
173
+     */
174
+    public function getHasActiveShares() {
175
+        return $this->hasActiveShares;
176
+    }
177
+
178
+    /**
179
+     * reads the user details
180
+     */
181
+    protected function fetchDetails() {
182
+        $properties = array (
183
+            'displayName' => 'user_ldap',
184
+            'uid'         => 'user_ldap',
185
+            'homePath'    => 'user_ldap',
186
+            'email'       => 'settings',
187
+            'lastLogin'   => 'login'
188
+        );
189
+        foreach($properties as $property => $app) {
190
+            $this->$property = $this->config->getUserValue($this->ocName, $app, $property, '');
191
+        }
192
+
193
+        $dn = $this->mapping->getDNByName($this->ocName);
194
+        $this->dn = ($dn !== false) ? $dn : '';
195
+
196
+        $this->determineShares();
197
+    }
198
+
199
+
200
+    /**
201
+     * finds out whether the user has active shares. The result is stored in
202
+     * $this->hasActiveShares
203
+     */
204
+    protected function determineShares() {
205
+        $query = $this->db->prepare('
206 206
 			SELECT COUNT(`uid_owner`)
207 207
 			FROM `*PREFIX*share`
208 208
 			WHERE `uid_owner` = ?
209 209
 		', 1);
210
-		$query->execute(array($this->ocName));
211
-		$sResult = $query->fetchColumn(0);
212
-		if(intval($sResult) === 1) {
213
-			$this->hasActiveShares = true;
214
-			return;
215
-		}
216
-
217
-		$query = $this->db->prepare('
210
+        $query->execute(array($this->ocName));
211
+        $sResult = $query->fetchColumn(0);
212
+        if(intval($sResult) === 1) {
213
+            $this->hasActiveShares = true;
214
+            return;
215
+        }
216
+
217
+        $query = $this->db->prepare('
218 218
 			SELECT COUNT(`owner`)
219 219
 			FROM `*PREFIX*share_external`
220 220
 			WHERE `owner` = ?
221 221
 		', 1);
222
-		$query->execute(array($this->ocName));
223
-		$sResult = $query->fetchColumn(0);
224
-		if(intval($sResult) === 1) {
225
-			$this->hasActiveShares = true;
226
-			return;
227
-		}
228
-
229
-		$this->hasActiveShares = false;
230
-	}
222
+        $query->execute(array($this->ocName));
223
+        $sResult = $query->fetchColumn(0);
224
+        if(intval($sResult) === 1) {
225
+            $this->hasActiveShares = true;
226
+            return;
227
+        }
228
+
229
+        $this->hasActiveShares = false;
230
+    }
231 231
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/IUserLDAP.php 1 patch
Indentation   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -24,26 +24,26 @@
 block discarded – undo
24 24
 
25 25
 interface IUserLDAP {
26 26
 
27
-	//Functions used by LDAPProvider
27
+    //Functions used by LDAPProvider
28 28
 	
29
-	/**
30
-	 * Return access for LDAP interaction.
31
-	 * @param string $uid
32
-	 * @return Access instance of Access for LDAP interaction
33
-	 */
34
-	public function getLDAPAccess($uid);
29
+    /**
30
+     * Return access for LDAP interaction.
31
+     * @param string $uid
32
+     * @return Access instance of Access for LDAP interaction
33
+     */
34
+    public function getLDAPAccess($uid);
35 35
 	
36
-	/**
37
-	 * Return a new LDAP connection for the specified user.
38
-	 * @param string $uid
39
-	 * @return resource of the LDAP connection
40
-	 */
41
-	public function getNewLDAPConnection($uid);
36
+    /**
37
+     * Return a new LDAP connection for the specified user.
38
+     * @param string $uid
39
+     * @return resource of the LDAP connection
40
+     */
41
+    public function getNewLDAPConnection($uid);
42 42
 
43
-	/**
44
-	 * Return the username for the given LDAP DN, if available.
45
-	 * @param string $dn
46
-	 * @return string|false with the username
47
-	 */
48
-	public function dn2UserName($dn);
43
+    /**
44
+     * Return the username for the given LDAP DN, if available.
45
+     * @param string $dn
46
+     * @return string|false with the username
47
+     */
48
+    public function dn2UserName($dn);
49 49
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Controller/ConfigAPIController.php 1 patch
Indentation   +262 added lines, -262 removed lines patch added patch discarded remove patch
@@ -40,283 +40,283 @@
 block discarded – undo
40 40
 
41 41
 class ConfigAPIController extends OCSController {
42 42
 
43
-	/** @var Helper */
44
-	private $ldapHelper;
43
+    /** @var Helper */
44
+    private $ldapHelper;
45 45
 
46
-	/** @var ILogger */
47
-	private $logger;
46
+    /** @var ILogger */
47
+    private $logger;
48 48
 
49
-	public function __construct(
50
-		$appName,
51
-		IRequest $request,
52
-		CapabilitiesManager $capabilitiesManager,
53
-		IUserSession $userSession,
54
-		IUserManager $userManager,
55
-		Throttler $throttler,
56
-		Manager $keyManager,
57
-		Helper $ldapHelper,
58
-		ILogger $logger
59
-	) {
60
-		parent::__construct(
61
-			$appName,
62
-			$request,
63
-			$capabilitiesManager,
64
-			$userSession,
65
-			$userManager,
66
-			$throttler,
67
-			$keyManager
68
-		);
49
+    public function __construct(
50
+        $appName,
51
+        IRequest $request,
52
+        CapabilitiesManager $capabilitiesManager,
53
+        IUserSession $userSession,
54
+        IUserManager $userManager,
55
+        Throttler $throttler,
56
+        Manager $keyManager,
57
+        Helper $ldapHelper,
58
+        ILogger $logger
59
+    ) {
60
+        parent::__construct(
61
+            $appName,
62
+            $request,
63
+            $capabilitiesManager,
64
+            $userSession,
65
+            $userManager,
66
+            $throttler,
67
+            $keyManager
68
+        );
69 69
 
70 70
 
71
-		$this->ldapHelper = $ldapHelper;
72
-		$this->logger = $logger;
73
-	}
71
+        $this->ldapHelper = $ldapHelper;
72
+        $this->logger = $logger;
73
+    }
74 74
 
75
-	/**
76
-	 * creates a new (empty) configuration and returns the resulting prefix
77
-	 *
78
-	 * Example: curl -X POST -H "OCS-APIREQUEST: true"  -u $admin:$password \
79
-	 *   https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config
80
-	 *
81
-	 * results in:
82
-	 *
83
-	 * <?xml version="1.0"?>
84
-	 * <ocs>
85
-	 *   <meta>
86
-	 *     <status>ok</status>
87
-	 *     <statuscode>200</statuscode>
88
-	 *     <message>OK</message>
89
-	 *   </meta>
90
-	 *   <data>
91
-	 *     <configID>s40</configID>
92
-	 *   </data>
93
-	 * </ocs>
94
-	 *
95
-	 * Failing example: if an exception is thrown (e.g. Database connection lost)
96
-	 * the detailed error will be logged. The output will then look like:
97
-	 *
98
-	 * <?xml version="1.0"?>
99
-	 * <ocs>
100
-	 *   <meta>
101
-	 *     <status>failure</status>
102
-	 *     <statuscode>999</statuscode>
103
-	 *     <message>An issue occurred when creating the new config.</message>
104
-	 *   </meta>
105
-	 *   <data/>
106
-	 * </ocs>
107
-	 *
108
-	 * For JSON output provide the format=json parameter
109
-	 *
110
-	 * @return DataResponse
111
-	 * @throws OCSException
112
-	 */
113
-	public function create() {
114
-		try {
115
-			$configPrefix = $this->ldapHelper->getNextServerConfigurationPrefix();
116
-			$configHolder = new Configuration($configPrefix);
117
-			$configHolder->saveConfiguration();
118
-		} catch (\Exception $e) {
119
-			$this->logger->logException($e);
120
-			throw new OCSException('An issue occurred when creating the new config.');
121
-		}
122
-		return new DataResponse(['configID' => $configPrefix]);
123
-	}
75
+    /**
76
+     * creates a new (empty) configuration and returns the resulting prefix
77
+     *
78
+     * Example: curl -X POST -H "OCS-APIREQUEST: true"  -u $admin:$password \
79
+     *   https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config
80
+     *
81
+     * results in:
82
+     *
83
+     * <?xml version="1.0"?>
84
+     * <ocs>
85
+     *   <meta>
86
+     *     <status>ok</status>
87
+     *     <statuscode>200</statuscode>
88
+     *     <message>OK</message>
89
+     *   </meta>
90
+     *   <data>
91
+     *     <configID>s40</configID>
92
+     *   </data>
93
+     * </ocs>
94
+     *
95
+     * Failing example: if an exception is thrown (e.g. Database connection lost)
96
+     * the detailed error will be logged. The output will then look like:
97
+     *
98
+     * <?xml version="1.0"?>
99
+     * <ocs>
100
+     *   <meta>
101
+     *     <status>failure</status>
102
+     *     <statuscode>999</statuscode>
103
+     *     <message>An issue occurred when creating the new config.</message>
104
+     *   </meta>
105
+     *   <data/>
106
+     * </ocs>
107
+     *
108
+     * For JSON output provide the format=json parameter
109
+     *
110
+     * @return DataResponse
111
+     * @throws OCSException
112
+     */
113
+    public function create() {
114
+        try {
115
+            $configPrefix = $this->ldapHelper->getNextServerConfigurationPrefix();
116
+            $configHolder = new Configuration($configPrefix);
117
+            $configHolder->saveConfiguration();
118
+        } catch (\Exception $e) {
119
+            $this->logger->logException($e);
120
+            throw new OCSException('An issue occurred when creating the new config.');
121
+        }
122
+        return new DataResponse(['configID' => $configPrefix]);
123
+    }
124 124
 
125
-	/**
126
-	 * Deletes a LDAP configuration, if present.
127
-	 *
128
-	 * Example:
129
-	 *   curl -X DELETE -H "OCS-APIREQUEST: true" -u $admin:$password \
130
-	 *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
131
-	 *
132
-	 * <?xml version="1.0"?>
133
-	 * <ocs>
134
-	 *   <meta>
135
-	 *     <status>ok</status>
136
-	 *     <statuscode>200</statuscode>
137
-	 *     <message>OK</message>
138
-	 *   </meta>
139
-	 *   <data/>
140
-	 * </ocs>
141
-	 *
142
-	 * @param string $configID
143
-	 * @return DataResponse
144
-	 * @throws OCSBadRequestException
145
-	 * @throws OCSException
146
-	 */
147
-	public function delete($configID) {
148
-		try {
149
-			$this->ensureConfigIDExists($configID);
150
-			if(!$this->ldapHelper->deleteServerConfiguration($configID)) {
151
-				throw new OCSException('Could not delete configuration');
152
-			}
153
-		} catch(OCSException $e) {
154
-			throw $e;
155
-		} catch(\Exception $e) {
156
-			$this->logger->logException($e);
157
-			throw new OCSException('An issue occurred when deleting the config.');
158
-		}
125
+    /**
126
+     * Deletes a LDAP configuration, if present.
127
+     *
128
+     * Example:
129
+     *   curl -X DELETE -H "OCS-APIREQUEST: true" -u $admin:$password \
130
+     *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
131
+     *
132
+     * <?xml version="1.0"?>
133
+     * <ocs>
134
+     *   <meta>
135
+     *     <status>ok</status>
136
+     *     <statuscode>200</statuscode>
137
+     *     <message>OK</message>
138
+     *   </meta>
139
+     *   <data/>
140
+     * </ocs>
141
+     *
142
+     * @param string $configID
143
+     * @return DataResponse
144
+     * @throws OCSBadRequestException
145
+     * @throws OCSException
146
+     */
147
+    public function delete($configID) {
148
+        try {
149
+            $this->ensureConfigIDExists($configID);
150
+            if(!$this->ldapHelper->deleteServerConfiguration($configID)) {
151
+                throw new OCSException('Could not delete configuration');
152
+            }
153
+        } catch(OCSException $e) {
154
+            throw $e;
155
+        } catch(\Exception $e) {
156
+            $this->logger->logException($e);
157
+            throw new OCSException('An issue occurred when deleting the config.');
158
+        }
159 159
 
160
-		return new DataResponse();
161
-	}
160
+        return new DataResponse();
161
+    }
162 162
 
163
-	/**
164
-	 * modifies a configuration
165
-	 *
166
-	 * Example:
167
-	 *   curl -X PUT -d "configData[ldapHost]=ldaps://my.ldap.server&configData[ldapPort]=636" \
168
-	 *    -H "OCS-APIREQUEST: true" -u $admin:$password \
169
-	 *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
170
-	 *
171
-	 * <?xml version="1.0"?>
172
-	 * <ocs>
173
-	 *   <meta>
174
-	 *     <status>ok</status>
175
-	 *     <statuscode>200</statuscode>
176
-	 *     <message>OK</message>
177
-	 *   </meta>
178
-	 *   <data/>
179
-	 * </ocs>
180
-	 *
181
-	 * @param string $configID
182
-	 * @param array $configData
183
-	 * @return DataResponse
184
-	 * @throws OCSException
185
-	 */
186
-	public function modify($configID, $configData) {
187
-		try {
188
-			$this->ensureConfigIDExists($configID);
163
+    /**
164
+     * modifies a configuration
165
+     *
166
+     * Example:
167
+     *   curl -X PUT -d "configData[ldapHost]=ldaps://my.ldap.server&configData[ldapPort]=636" \
168
+     *    -H "OCS-APIREQUEST: true" -u $admin:$password \
169
+     *    https://nextcloud.server/ocs/v2.php/apps/user_ldap/api/v1/config/s60
170
+     *
171
+     * <?xml version="1.0"?>
172
+     * <ocs>
173
+     *   <meta>
174
+     *     <status>ok</status>
175
+     *     <statuscode>200</statuscode>
176
+     *     <message>OK</message>
177
+     *   </meta>
178
+     *   <data/>
179
+     * </ocs>
180
+     *
181
+     * @param string $configID
182
+     * @param array $configData
183
+     * @return DataResponse
184
+     * @throws OCSException
185
+     */
186
+    public function modify($configID, $configData) {
187
+        try {
188
+            $this->ensureConfigIDExists($configID);
189 189
 
190
-			if(!is_array($configData)) {
191
-				throw new OCSBadRequestException('configData is not properly set');
192
-			}
190
+            if(!is_array($configData)) {
191
+                throw new OCSBadRequestException('configData is not properly set');
192
+            }
193 193
 
194
-			$configuration = new Configuration($configID);
195
-			$configKeys = $configuration->getConfigTranslationArray();
194
+            $configuration = new Configuration($configID);
195
+            $configKeys = $configuration->getConfigTranslationArray();
196 196
 
197
-			foreach ($configKeys as $i => $key) {
198
-				if(isset($configData[$key])) {
199
-					$configuration->$key = $configData[$key];
200
-				}
201
-			}
197
+            foreach ($configKeys as $i => $key) {
198
+                if(isset($configData[$key])) {
199
+                    $configuration->$key = $configData[$key];
200
+                }
201
+            }
202 202
 
203
-			$configuration->saveConfiguration();
204
-		} catch(OCSException $e) {
205
-			throw $e;
206
-		} catch (\Exception $e) {
207
-			$this->logger->logException($e);
208
-			throw new OCSException('An issue occurred when modifying the config.');
209
-		}
203
+            $configuration->saveConfiguration();
204
+        } catch(OCSException $e) {
205
+            throw $e;
206
+        } catch (\Exception $e) {
207
+            $this->logger->logException($e);
208
+            throw new OCSException('An issue occurred when modifying the config.');
209
+        }
210 210
 
211
-		return new DataResponse();
212
-	}
211
+        return new DataResponse();
212
+    }
213 213
 
214
-	/**
215
-	 * retrieves a configuration
216
-	 *
217
-	 * <?xml version="1.0"?>
218
-	 * <ocs>
219
-	 *   <meta>
220
-	 *     <status>ok</status>
221
-	 *     <statuscode>200</statuscode>
222
-	 *     <message>OK</message>
223
-	 *   </meta>
224
-	 *   <data>
225
-	 *     <ldapHost>ldaps://my.ldap.server</ldapHost>
226
-	 *     <ldapPort>7770</ldapPort>
227
-	 *     <ldapBackupHost></ldapBackupHost>
228
-	 *     <ldapBackupPort></ldapBackupPort>
229
-	 *     <ldapBase>ou=small,dc=my,dc=ldap,dc=server</ldapBase>
230
-	 *     <ldapBaseUsers>ou=users,ou=small,dc=my,dc=ldap,dc=server</ldapBaseUsers>
231
-	 *     <ldapBaseGroups>ou=small,dc=my,dc=ldap,dc=server</ldapBaseGroups>
232
-	 *     <ldapAgentName>cn=root,dc=my,dc=ldap,dc=server</ldapAgentName>
233
-	 *     <ldapAgentPassword>clearTextWithShowPassword=1</ldapAgentPassword>
234
-	 *     <ldapTLS>1</ldapTLS>
235
-	 *     <turnOffCertCheck>0</turnOffCertCheck>
236
-	 *     <ldapIgnoreNamingRules/>
237
-	 *     <ldapUserDisplayName>displayname</ldapUserDisplayName>
238
-	 *     <ldapUserDisplayName2>uid</ldapUserDisplayName2>
239
-	 *     <ldapUserFilterObjectclass>inetOrgPerson</ldapUserFilterObjectclass>
240
-	 *     <ldapUserFilterGroups></ldapUserFilterGroups>
241
-	 *     <ldapUserFilter>(&amp;(objectclass=nextcloudUser)(nextcloudEnabled=TRUE))</ldapUserFilter>
242
-	 *     <ldapUserFilterMode>1</ldapUserFilterMode>
243
-	 *     <ldapGroupFilter>(&amp;(|(objectclass=nextcloudGroup)))</ldapGroupFilter>
244
-	 *     <ldapGroupFilterMode>0</ldapGroupFilterMode>
245
-	 *     <ldapGroupFilterObjectclass>nextcloudGroup</ldapGroupFilterObjectclass>
246
-	 *     <ldapGroupFilterGroups></ldapGroupFilterGroups>
247
-	 *     <ldapGroupDisplayName>cn</ldapGroupDisplayName>
248
-	 *     <ldapGroupMemberAssocAttr>memberUid</ldapGroupMemberAssocAttr>
249
-	 *     <ldapLoginFilter>(&amp;(|(objectclass=inetOrgPerson))(uid=%uid))</ldapLoginFilter>
250
-	 *     <ldapLoginFilterMode>0</ldapLoginFilterMode>
251
-	 *     <ldapLoginFilterEmail>0</ldapLoginFilterEmail>
252
-	 *     <ldapLoginFilterUsername>1</ldapLoginFilterUsername>
253
-	 *     <ldapLoginFilterAttributes></ldapLoginFilterAttributes>
254
-	 *     <ldapQuotaAttribute></ldapQuotaAttribute>
255
-	 *     <ldapQuotaDefault></ldapQuotaDefault>
256
-	 *     <ldapEmailAttribute>mail</ldapEmailAttribute>
257
-	 *     <ldapCacheTTL>20</ldapCacheTTL>
258
-	 *     <ldapUuidUserAttribute>auto</ldapUuidUserAttribute>
259
-	 *     <ldapUuidGroupAttribute>auto</ldapUuidGroupAttribute>
260
-	 *     <ldapOverrideMainServer></ldapOverrideMainServer>
261
-	 *     <ldapConfigurationActive>1</ldapConfigurationActive>
262
-	 *     <ldapAttributesForUserSearch>uid;sn;givenname</ldapAttributesForUserSearch>
263
-	 *     <ldapAttributesForGroupSearch></ldapAttributesForGroupSearch>
264
-	 *     <ldapExperiencedAdmin>0</ldapExperiencedAdmin>
265
-	 *     <homeFolderNamingRule></homeFolderNamingRule>
266
-	 *     <hasPagedResultSupport></hasPagedResultSupport>
267
-	 *     <hasMemberOfFilterSupport></hasMemberOfFilterSupport>
268
-	 *     <useMemberOfToDetectMembership>1</useMemberOfToDetectMembership>
269
-	 *     <ldapExpertUsernameAttr>uid</ldapExpertUsernameAttr>
270
-	 *     <ldapExpertUUIDUserAttr>uid</ldapExpertUUIDUserAttr>
271
-	 *     <ldapExpertUUIDGroupAttr></ldapExpertUUIDGroupAttr>
272
-	 *     <lastJpegPhotoLookup>0</lastJpegPhotoLookup>
273
-	 *     <ldapNestedGroups>0</ldapNestedGroups>
274
-	 *     <ldapPagingSize>500</ldapPagingSize>
275
-	 *     <turnOnPasswordChange>1</turnOnPasswordChange>
276
-	 *     <ldapDynamicGroupMemberURL></ldapDynamicGroupMemberURL>
277
-	 *   </data>
278
-	 * </ocs>
279
-	 *
280
-	 * @param string $configID
281
-	 * @param bool|string $showPassword
282
-	 * @return DataResponse
283
-	 * @throws OCSException
284
-	 */
285
-	public function show($configID, $showPassword = false) {
286
-		try {
287
-			$this->ensureConfigIDExists($configID);
214
+    /**
215
+     * retrieves a configuration
216
+     *
217
+     * <?xml version="1.0"?>
218
+     * <ocs>
219
+     *   <meta>
220
+     *     <status>ok</status>
221
+     *     <statuscode>200</statuscode>
222
+     *     <message>OK</message>
223
+     *   </meta>
224
+     *   <data>
225
+     *     <ldapHost>ldaps://my.ldap.server</ldapHost>
226
+     *     <ldapPort>7770</ldapPort>
227
+     *     <ldapBackupHost></ldapBackupHost>
228
+     *     <ldapBackupPort></ldapBackupPort>
229
+     *     <ldapBase>ou=small,dc=my,dc=ldap,dc=server</ldapBase>
230
+     *     <ldapBaseUsers>ou=users,ou=small,dc=my,dc=ldap,dc=server</ldapBaseUsers>
231
+     *     <ldapBaseGroups>ou=small,dc=my,dc=ldap,dc=server</ldapBaseGroups>
232
+     *     <ldapAgentName>cn=root,dc=my,dc=ldap,dc=server</ldapAgentName>
233
+     *     <ldapAgentPassword>clearTextWithShowPassword=1</ldapAgentPassword>
234
+     *     <ldapTLS>1</ldapTLS>
235
+     *     <turnOffCertCheck>0</turnOffCertCheck>
236
+     *     <ldapIgnoreNamingRules/>
237
+     *     <ldapUserDisplayName>displayname</ldapUserDisplayName>
238
+     *     <ldapUserDisplayName2>uid</ldapUserDisplayName2>
239
+     *     <ldapUserFilterObjectclass>inetOrgPerson</ldapUserFilterObjectclass>
240
+     *     <ldapUserFilterGroups></ldapUserFilterGroups>
241
+     *     <ldapUserFilter>(&amp;(objectclass=nextcloudUser)(nextcloudEnabled=TRUE))</ldapUserFilter>
242
+     *     <ldapUserFilterMode>1</ldapUserFilterMode>
243
+     *     <ldapGroupFilter>(&amp;(|(objectclass=nextcloudGroup)))</ldapGroupFilter>
244
+     *     <ldapGroupFilterMode>0</ldapGroupFilterMode>
245
+     *     <ldapGroupFilterObjectclass>nextcloudGroup</ldapGroupFilterObjectclass>
246
+     *     <ldapGroupFilterGroups></ldapGroupFilterGroups>
247
+     *     <ldapGroupDisplayName>cn</ldapGroupDisplayName>
248
+     *     <ldapGroupMemberAssocAttr>memberUid</ldapGroupMemberAssocAttr>
249
+     *     <ldapLoginFilter>(&amp;(|(objectclass=inetOrgPerson))(uid=%uid))</ldapLoginFilter>
250
+     *     <ldapLoginFilterMode>0</ldapLoginFilterMode>
251
+     *     <ldapLoginFilterEmail>0</ldapLoginFilterEmail>
252
+     *     <ldapLoginFilterUsername>1</ldapLoginFilterUsername>
253
+     *     <ldapLoginFilterAttributes></ldapLoginFilterAttributes>
254
+     *     <ldapQuotaAttribute></ldapQuotaAttribute>
255
+     *     <ldapQuotaDefault></ldapQuotaDefault>
256
+     *     <ldapEmailAttribute>mail</ldapEmailAttribute>
257
+     *     <ldapCacheTTL>20</ldapCacheTTL>
258
+     *     <ldapUuidUserAttribute>auto</ldapUuidUserAttribute>
259
+     *     <ldapUuidGroupAttribute>auto</ldapUuidGroupAttribute>
260
+     *     <ldapOverrideMainServer></ldapOverrideMainServer>
261
+     *     <ldapConfigurationActive>1</ldapConfigurationActive>
262
+     *     <ldapAttributesForUserSearch>uid;sn;givenname</ldapAttributesForUserSearch>
263
+     *     <ldapAttributesForGroupSearch></ldapAttributesForGroupSearch>
264
+     *     <ldapExperiencedAdmin>0</ldapExperiencedAdmin>
265
+     *     <homeFolderNamingRule></homeFolderNamingRule>
266
+     *     <hasPagedResultSupport></hasPagedResultSupport>
267
+     *     <hasMemberOfFilterSupport></hasMemberOfFilterSupport>
268
+     *     <useMemberOfToDetectMembership>1</useMemberOfToDetectMembership>
269
+     *     <ldapExpertUsernameAttr>uid</ldapExpertUsernameAttr>
270
+     *     <ldapExpertUUIDUserAttr>uid</ldapExpertUUIDUserAttr>
271
+     *     <ldapExpertUUIDGroupAttr></ldapExpertUUIDGroupAttr>
272
+     *     <lastJpegPhotoLookup>0</lastJpegPhotoLookup>
273
+     *     <ldapNestedGroups>0</ldapNestedGroups>
274
+     *     <ldapPagingSize>500</ldapPagingSize>
275
+     *     <turnOnPasswordChange>1</turnOnPasswordChange>
276
+     *     <ldapDynamicGroupMemberURL></ldapDynamicGroupMemberURL>
277
+     *   </data>
278
+     * </ocs>
279
+     *
280
+     * @param string $configID
281
+     * @param bool|string $showPassword
282
+     * @return DataResponse
283
+     * @throws OCSException
284
+     */
285
+    public function show($configID, $showPassword = false) {
286
+        try {
287
+            $this->ensureConfigIDExists($configID);
288 288
 
289
-			$config = new Configuration($configID);
290
-			$data = $config->getConfiguration();
291
-			if(!boolval(intval($showPassword))) {
292
-				$data['ldapAgentPassword'] = '***';
293
-			}
294
-			foreach ($data as $key => $value) {
295
-				if(is_array($value)) {
296
-					$value = implode(';', $value);
297
-					$data[$key] = $value;
298
-				}
299
-			}
300
-		} catch(OCSException $e) {
301
-			throw $e;
302
-		} catch (\Exception $e) {
303
-			$this->logger->logException($e);
304
-			throw new OCSException('An issue occurred when modifying the config.');
305
-		}
289
+            $config = new Configuration($configID);
290
+            $data = $config->getConfiguration();
291
+            if(!boolval(intval($showPassword))) {
292
+                $data['ldapAgentPassword'] = '***';
293
+            }
294
+            foreach ($data as $key => $value) {
295
+                if(is_array($value)) {
296
+                    $value = implode(';', $value);
297
+                    $data[$key] = $value;
298
+                }
299
+            }
300
+        } catch(OCSException $e) {
301
+            throw $e;
302
+        } catch (\Exception $e) {
303
+            $this->logger->logException($e);
304
+            throw new OCSException('An issue occurred when modifying the config.');
305
+        }
306 306
 
307
-		return new DataResponse($data);
308
-	}
307
+        return new DataResponse($data);
308
+    }
309 309
 
310
-	/**
311
-	 * if the given config ID is not available, an exception is thrown
312
-	 *
313
-	 * @param string $configID
314
-	 * @throws OCSNotFoundException
315
-	 */
316
-	private function ensureConfigIDExists($configID) {
317
-		$prefixes = $this->ldapHelper->getServerConfigurationPrefixes();
318
-		if(!in_array($configID, $prefixes, true)) {
319
-			throw new OCSNotFoundException('Config ID not found');
320
-		}
321
-	}
310
+    /**
311
+     * if the given config ID is not available, an exception is thrown
312
+     *
313
+     * @param string $configID
314
+     * @throws OCSNotFoundException
315
+     */
316
+    private function ensureConfigIDExists($configID) {
317
+        $prefixes = $this->ldapHelper->getServerConfigurationPrefixes();
318
+        if(!in_array($configID, $prefixes, true)) {
319
+            throw new OCSNotFoundException('Config ID not found');
320
+        }
321
+    }
322 322
 }
Please login to merge, or discard this patch.
apps/user_ldap/lib/Jobs/UpdateGroups.php 1 patch
Indentation   +163 added lines, -163 removed lines patch added patch discarded remove patch
@@ -41,182 +41,182 @@
 block discarded – undo
41 41
 use OCA\User_LDAP\User\Manager;
42 42
 
43 43
 class UpdateGroups extends \OC\BackgroundJob\TimedJob {
44
-	static private $groupsFromDB;
45
-
46
-	static private $groupBE;
47
-
48
-	public function __construct(){
49
-		$this->interval = self::getRefreshInterval();
50
-	}
51
-
52
-	/**
53
-	 * @param mixed $argument
54
-	 */
55
-	public function run($argument){
56
-		self::updateGroups();
57
-	}
58
-
59
-	static public function updateGroups() {
60
-		\OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
61
-
62
-		$knownGroups = array_keys(self::getKnownGroups());
63
-		$actualGroups = self::getGroupBE()->getGroups();
64
-
65
-		if(empty($actualGroups) && empty($knownGroups)) {
66
-			\OCP\Util::writeLog('user_ldap',
67
-				'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
68
-				\OCP\Util::INFO);
69
-			return;
70
-		}
71
-
72
-		self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
73
-		self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
74
-		self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
75
-
76
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
77
-	}
78
-
79
-	/**
80
-	 * @return int
81
-	 */
82
-	static private function getRefreshInterval() {
83
-		//defaults to every hour
84
-		return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
85
-	}
86
-
87
-	/**
88
-	 * @param string[] $groups
89
-	 */
90
-	static private function handleKnownGroups($groups) {
91
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
92
-		$query = \OCP\DB::prepare('
44
+    static private $groupsFromDB;
45
+
46
+    static private $groupBE;
47
+
48
+    public function __construct(){
49
+        $this->interval = self::getRefreshInterval();
50
+    }
51
+
52
+    /**
53
+     * @param mixed $argument
54
+     */
55
+    public function run($argument){
56
+        self::updateGroups();
57
+    }
58
+
59
+    static public function updateGroups() {
60
+        \OCP\Util::writeLog('user_ldap', 'Run background job "updateGroups"', \OCP\Util::DEBUG);
61
+
62
+        $knownGroups = array_keys(self::getKnownGroups());
63
+        $actualGroups = self::getGroupBE()->getGroups();
64
+
65
+        if(empty($actualGroups) && empty($knownGroups)) {
66
+            \OCP\Util::writeLog('user_ldap',
67
+                'bgJ "updateGroups" – groups do not seem to be configured properly, aborting.',
68
+                \OCP\Util::INFO);
69
+            return;
70
+        }
71
+
72
+        self::handleKnownGroups(array_intersect($actualGroups, $knownGroups));
73
+        self::handleCreatedGroups(array_diff($actualGroups, $knownGroups));
74
+        self::handleRemovedGroups(array_diff($knownGroups, $actualGroups));
75
+
76
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Finished.', \OCP\Util::DEBUG);
77
+    }
78
+
79
+    /**
80
+     * @return int
81
+     */
82
+    static private function getRefreshInterval() {
83
+        //defaults to every hour
84
+        return \OCP\Config::getAppValue('user_ldap', 'bgjRefreshInterval', 3600);
85
+    }
86
+
87
+    /**
88
+     * @param string[] $groups
89
+     */
90
+    static private function handleKnownGroups($groups) {
91
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – Dealing with known Groups.', \OCP\Util::DEBUG);
92
+        $query = \OCP\DB::prepare('
93 93
 			UPDATE `*PREFIX*ldap_group_members`
94 94
 			SET `owncloudusers` = ?
95 95
 			WHERE `owncloudname` = ?
96 96
 		');
97
-		foreach($groups as $group) {
98
-			//we assume, that self::$groupsFromDB has been retrieved already
99
-			$knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
100
-			$actualUsers = self::getGroupBE()->usersInGroup($group);
101
-			$hasChanged = false;
102
-			foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
103
-				\OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
104
-				\OCP\Util::writeLog('user_ldap',
105
-				'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
106
-				\OCP\Util::INFO);
107
-				$hasChanged = true;
108
-			}
109
-			foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
110
-				\OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
111
-				\OCP\Util::writeLog('user_ldap',
112
-				'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
113
-				\OCP\Util::INFO);
114
-				$hasChanged = true;
115
-			}
116
-			if($hasChanged) {
117
-				$query->execute(array(serialize($actualUsers), $group));
118
-			}
119
-		}
120
-		\OCP\Util::writeLog('user_ldap',
121
-			'bgJ "updateGroups" – FINISHED dealing with known Groups.',
122
-			\OCP\Util::DEBUG);
123
-	}
124
-
125
-	/**
126
-	 * @param string[] $createdGroups
127
-	 */
128
-	static private function handleCreatedGroups($createdGroups) {
129
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
130
-		$query = \OCP\DB::prepare('
97
+        foreach($groups as $group) {
98
+            //we assume, that self::$groupsFromDB has been retrieved already
99
+            $knownUsers = unserialize(self::$groupsFromDB[$group]['owncloudusers']);
100
+            $actualUsers = self::getGroupBE()->usersInGroup($group);
101
+            $hasChanged = false;
102
+            foreach(array_diff($knownUsers, $actualUsers) as $removedUser) {
103
+                \OCP\Util::emitHook('OC_User', 'post_removeFromGroup', array('uid' => $removedUser, 'gid' => $group));
104
+                \OCP\Util::writeLog('user_ldap',
105
+                'bgJ "updateGroups" – "'.$removedUser.'" removed from "'.$group.'".',
106
+                \OCP\Util::INFO);
107
+                $hasChanged = true;
108
+            }
109
+            foreach(array_diff($actualUsers, $knownUsers) as $addedUser) {
110
+                \OCP\Util::emitHook('OC_User', 'post_addToGroup', array('uid' => $addedUser, 'gid' => $group));
111
+                \OCP\Util::writeLog('user_ldap',
112
+                'bgJ "updateGroups" – "'.$addedUser.'" added to "'.$group.'".',
113
+                \OCP\Util::INFO);
114
+                $hasChanged = true;
115
+            }
116
+            if($hasChanged) {
117
+                $query->execute(array(serialize($actualUsers), $group));
118
+            }
119
+        }
120
+        \OCP\Util::writeLog('user_ldap',
121
+            'bgJ "updateGroups" – FINISHED dealing with known Groups.',
122
+            \OCP\Util::DEBUG);
123
+    }
124
+
125
+    /**
126
+     * @param string[] $createdGroups
127
+     */
128
+    static private function handleCreatedGroups($createdGroups) {
129
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with created Groups.', \OCP\Util::DEBUG);
130
+        $query = \OCP\DB::prepare('
131 131
 			INSERT
132 132
 			INTO `*PREFIX*ldap_group_members` (`owncloudname`, `owncloudusers`)
133 133
 			VALUES (?, ?)
134 134
 		');
135
-		foreach($createdGroups as $createdGroup) {
136
-			\OCP\Util::writeLog('user_ldap',
137
-				'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
138
-				\OCP\Util::INFO);
139
-			$users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
140
-			$query->execute(array($createdGroup, $users));
141
-		}
142
-		\OCP\Util::writeLog('user_ldap',
143
-			'bgJ "updateGroups" – FINISHED dealing with created Groups.',
144
-			\OCP\Util::DEBUG);
145
-	}
146
-
147
-	/**
148
-	 * @param string[] $removedGroups
149
-	 */
150
-	static private function handleRemovedGroups($removedGroups) {
151
-		\OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
152
-		$query = \OCP\DB::prepare('
135
+        foreach($createdGroups as $createdGroup) {
136
+            \OCP\Util::writeLog('user_ldap',
137
+                'bgJ "updateGroups" – new group "'.$createdGroup.'" found.',
138
+                \OCP\Util::INFO);
139
+            $users = serialize(self::getGroupBE()->usersInGroup($createdGroup));
140
+            $query->execute(array($createdGroup, $users));
141
+        }
142
+        \OCP\Util::writeLog('user_ldap',
143
+            'bgJ "updateGroups" – FINISHED dealing with created Groups.',
144
+            \OCP\Util::DEBUG);
145
+    }
146
+
147
+    /**
148
+     * @param string[] $removedGroups
149
+     */
150
+    static private function handleRemovedGroups($removedGroups) {
151
+        \OCP\Util::writeLog('user_ldap', 'bgJ "updateGroups" – dealing with removed groups.', \OCP\Util::DEBUG);
152
+        $query = \OCP\DB::prepare('
153 153
 			DELETE
154 154
 			FROM `*PREFIX*ldap_group_members`
155 155
 			WHERE `owncloudname` = ?
156 156
 		');
157
-		foreach($removedGroups as $removedGroup) {
158
-			\OCP\Util::writeLog('user_ldap',
159
-				'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
160
-				\OCP\Util::INFO);
161
-			$query->execute(array($removedGroup));
162
-		}
163
-		\OCP\Util::writeLog('user_ldap',
164
-			'bgJ "updateGroups" – FINISHED dealing with removed groups.',
165
-			\OCP\Util::DEBUG);
166
-	}
167
-
168
-	/**
169
-	 * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
170
-	 */
171
-	static private function getGroupBE() {
172
-		if(!is_null(self::$groupBE)) {
173
-			return self::$groupBE;
174
-		}
175
-		$helper = new Helper(\OC::$server->getConfig());
176
-		$configPrefixes = $helper->getServerConfigurationPrefixes(true);
177
-		$ldapWrapper = new LDAP();
178
-		if(count($configPrefixes) === 1) {
179
-			//avoid the proxy when there is only one LDAP server configured
180
-			$dbc = \OC::$server->getDatabaseConnection();
181
-			$userManager = new Manager(
182
-				\OC::$server->getConfig(),
183
-				new FilesystemHelper(),
184
-				new LogWrapper(),
185
-				\OC::$server->getAvatarManager(),
186
-				new \OCP\Image(),
187
-				$dbc,
188
-				\OC::$server->getUserManager());
189
-			$connector = new Connection($ldapWrapper, $configPrefixes[0]);
190
-			$ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper);
191
-			$groupMapper = new GroupMapping($dbc);
192
-			$userMapper  = new UserMapping($dbc);
193
-			$ldapAccess->setGroupMapper($groupMapper);
194
-			$ldapAccess->setUserMapper($userMapper);
195
-			self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
196
-		} else {
197
-			self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
198
-		}
199
-
200
-		return self::$groupBE;
201
-	}
202
-
203
-	/**
204
-	 * @return array
205
-	 */
206
-	static private function getKnownGroups() {
207
-		if(is_array(self::$groupsFromDB)) {
208
-			return self::$groupsFromDB;
209
-		}
210
-		$query = \OCP\DB::prepare('
157
+        foreach($removedGroups as $removedGroup) {
158
+            \OCP\Util::writeLog('user_ldap',
159
+                'bgJ "updateGroups" – group "'.$removedGroup.'" was removed.',
160
+                \OCP\Util::INFO);
161
+            $query->execute(array($removedGroup));
162
+        }
163
+        \OCP\Util::writeLog('user_ldap',
164
+            'bgJ "updateGroups" – FINISHED dealing with removed groups.',
165
+            \OCP\Util::DEBUG);
166
+    }
167
+
168
+    /**
169
+     * @return \OCA\User_LDAP\Group_LDAP|\OCA\User_LDAP\Group_Proxy
170
+     */
171
+    static private function getGroupBE() {
172
+        if(!is_null(self::$groupBE)) {
173
+            return self::$groupBE;
174
+        }
175
+        $helper = new Helper(\OC::$server->getConfig());
176
+        $configPrefixes = $helper->getServerConfigurationPrefixes(true);
177
+        $ldapWrapper = new LDAP();
178
+        if(count($configPrefixes) === 1) {
179
+            //avoid the proxy when there is only one LDAP server configured
180
+            $dbc = \OC::$server->getDatabaseConnection();
181
+            $userManager = new Manager(
182
+                \OC::$server->getConfig(),
183
+                new FilesystemHelper(),
184
+                new LogWrapper(),
185
+                \OC::$server->getAvatarManager(),
186
+                new \OCP\Image(),
187
+                $dbc,
188
+                \OC::$server->getUserManager());
189
+            $connector = new Connection($ldapWrapper, $configPrefixes[0]);
190
+            $ldapAccess = new Access($connector, $ldapWrapper, $userManager, $helper);
191
+            $groupMapper = new GroupMapping($dbc);
192
+            $userMapper  = new UserMapping($dbc);
193
+            $ldapAccess->setGroupMapper($groupMapper);
194
+            $ldapAccess->setUserMapper($userMapper);
195
+            self::$groupBE = new \OCA\User_LDAP\Group_LDAP($ldapAccess);
196
+        } else {
197
+            self::$groupBE = new \OCA\User_LDAP\Group_Proxy($configPrefixes, $ldapWrapper);
198
+        }
199
+
200
+        return self::$groupBE;
201
+    }
202
+
203
+    /**
204
+     * @return array
205
+     */
206
+    static private function getKnownGroups() {
207
+        if(is_array(self::$groupsFromDB)) {
208
+            return self::$groupsFromDB;
209
+        }
210
+        $query = \OCP\DB::prepare('
211 211
 			SELECT `owncloudname`, `owncloudusers`
212 212
 			FROM `*PREFIX*ldap_group_members`
213 213
 		');
214
-		$result = $query->execute()->fetchAll();
215
-		self::$groupsFromDB = array();
216
-		foreach($result as $dataset) {
217
-			self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
218
-		}
219
-
220
-		return self::$groupsFromDB;
221
-	}
214
+        $result = $query->execute()->fetchAll();
215
+        self::$groupsFromDB = array();
216
+        foreach($result as $dataset) {
217
+            self::$groupsFromDB[$dataset['owncloudname']] = $dataset;
218
+        }
219
+
220
+        return self::$groupsFromDB;
221
+    }
222 222
 }
Please login to merge, or discard this patch.