Passed
Push — master ( 6146c4...4b0cb0 )
by John
13:36
created
lib/private/User/Manager.php 1 patch
Indentation   +537 added lines, -537 removed lines patch added patch discarded remove patch
@@ -58,545 +58,545 @@
 block discarded – undo
58 58
  * @package OC\User
59 59
  */
60 60
 class Manager extends PublicEmitter implements IUserManager {
61
-	/**
62
-	 * @var \OCP\UserInterface[] $backends
63
-	 */
64
-	private $backends = array();
65
-
66
-	/**
67
-	 * @var \OC\User\User[] $cachedUsers
68
-	 */
69
-	private $cachedUsers = array();
70
-
71
-	/**
72
-	 * @var \OCP\IConfig $config
73
-	 */
74
-	private $config;
75
-
76
-	/**
77
-	 * @param \OCP\IConfig $config
78
-	 */
79
-	public function __construct(IConfig $config) {
80
-		$this->config = $config;
81
-		$cachedUsers = &$this->cachedUsers;
82
-		$this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
83
-			/** @var \OC\User\User $user */
84
-			unset($cachedUsers[$user->getUID()]);
85
-		});
86
-	}
87
-
88
-	/**
89
-	 * Get the active backends
90
-	 * @return \OCP\UserInterface[]
91
-	 */
92
-	public function getBackends() {
93
-		return $this->backends;
94
-	}
95
-
96
-	/**
97
-	 * register a user backend
98
-	 *
99
-	 * @param \OCP\UserInterface $backend
100
-	 */
101
-	public function registerBackend($backend) {
102
-		$this->backends[] = $backend;
103
-	}
104
-
105
-	/**
106
-	 * remove a user backend
107
-	 *
108
-	 * @param \OCP\UserInterface $backend
109
-	 */
110
-	public function removeBackend($backend) {
111
-		$this->cachedUsers = array();
112
-		if (($i = array_search($backend, $this->backends)) !== false) {
113
-			unset($this->backends[$i]);
114
-		}
115
-	}
116
-
117
-	/**
118
-	 * remove all user backends
119
-	 */
120
-	public function clearBackends() {
121
-		$this->cachedUsers = array();
122
-		$this->backends = array();
123
-	}
124
-
125
-	/**
126
-	 * get a user by user id
127
-	 *
128
-	 * @param string $uid
129
-	 * @return \OC\User\User|null Either the user or null if the specified user does not exist
130
-	 */
131
-	public function get($uid) {
132
-		if (is_null($uid) || $uid === '' || $uid === false) {
133
-			return null;
134
-		}
135
-		if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
136
-			return $this->cachedUsers[$uid];
137
-		}
138
-		foreach ($this->backends as $backend) {
139
-			if ($backend->userExists($uid)) {
140
-				return $this->getUserObject($uid, $backend);
141
-			}
142
-		}
143
-		return null;
144
-	}
145
-
146
-	/**
147
-	 * get or construct the user object
148
-	 *
149
-	 * @param string $uid
150
-	 * @param \OCP\UserInterface $backend
151
-	 * @param bool $cacheUser If false the newly created user object will not be cached
152
-	 * @return \OC\User\User
153
-	 */
154
-	protected function getUserObject($uid, $backend, $cacheUser = true) {
155
-		if (isset($this->cachedUsers[$uid])) {
156
-			return $this->cachedUsers[$uid];
157
-		}
158
-
159
-		$user = new User($uid, $backend, $this, $this->config);
160
-		if ($cacheUser) {
161
-			$this->cachedUsers[$uid] = $user;
162
-		}
163
-		return $user;
164
-	}
165
-
166
-	/**
167
-	 * check if a user exists
168
-	 *
169
-	 * @param string $uid
170
-	 * @return bool
171
-	 */
172
-	public function userExists($uid) {
173
-		$user = $this->get($uid);
174
-		return ($user !== null);
175
-	}
176
-
177
-	/**
178
-	 * Check if the password is valid for the user
179
-	 *
180
-	 * @param string $loginName
181
-	 * @param string $password
182
-	 * @return mixed the User object on success, false otherwise
183
-	 */
184
-	public function checkPassword($loginName, $password) {
185
-		$result = $this->checkPasswordNoLogging($loginName, $password);
186
-
187
-		if ($result === false) {
188
-			\OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
189
-		}
190
-
191
-		return $result;
192
-	}
193
-
194
-	/**
195
-	 * Check if the password is valid for the user
196
-	 *
197
-	 * @internal
198
-	 * @param string $loginName
199
-	 * @param string $password
200
-	 * @return mixed the User object on success, false otherwise
201
-	 */
202
-	public function checkPasswordNoLogging($loginName, $password) {
203
-		$loginName = str_replace("\0", '', $loginName);
204
-		$password = str_replace("\0", '', $password);
205
-
206
-		foreach ($this->backends as $backend) {
207
-			if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
208
-				$uid = $backend->checkPassword($loginName, $password);
209
-				if ($uid !== false) {
210
-					return $this->getUserObject($uid, $backend);
211
-				}
212
-			}
213
-		}
214
-
215
-		return false;
216
-	}
217
-
218
-	/**
219
-	 * search by user id
220
-	 *
221
-	 * @param string $pattern
222
-	 * @param int $limit
223
-	 * @param int $offset
224
-	 * @return \OC\User\User[]
225
-	 */
226
-	public function search($pattern, $limit = null, $offset = null) {
227
-		$users = array();
228
-		foreach ($this->backends as $backend) {
229
-			$backendUsers = $backend->getUsers($pattern, $limit, $offset);
230
-			if (is_array($backendUsers)) {
231
-				foreach ($backendUsers as $uid) {
232
-					$users[$uid] = $this->getUserObject($uid, $backend);
233
-				}
234
-			}
235
-		}
236
-
237
-		uasort($users, function ($a, $b) {
238
-			/**
239
-			 * @var \OC\User\User $a
240
-			 * @var \OC\User\User $b
241
-			 */
242
-			return strcasecmp($a->getUID(), $b->getUID());
243
-		});
244
-		return $users;
245
-	}
246
-
247
-	/**
248
-	 * search by displayName
249
-	 *
250
-	 * @param string $pattern
251
-	 * @param int $limit
252
-	 * @param int $offset
253
-	 * @return \OC\User\User[]
254
-	 */
255
-	public function searchDisplayName($pattern, $limit = null, $offset = null) {
256
-		$users = array();
257
-		foreach ($this->backends as $backend) {
258
-			$backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
259
-			if (is_array($backendUsers)) {
260
-				foreach ($backendUsers as $uid => $displayName) {
261
-					$users[] = $this->getUserObject($uid, $backend);
262
-				}
263
-			}
264
-		}
265
-
266
-		usort($users, function ($a, $b) {
267
-			/**
268
-			 * @var \OC\User\User $a
269
-			 * @var \OC\User\User $b
270
-			 */
271
-			return strcasecmp($a->getDisplayName(), $b->getDisplayName());
272
-		});
273
-		return $users;
274
-	}
275
-
276
-	/**
277
-	 * @param string $uid
278
-	 * @param string $password
279
-	 * @throws \InvalidArgumentException
280
-	 * @return bool|IUser the created user or false
281
-	 */
282
-	public function createUser($uid, $password) {
283
-		$localBackends = [];
284
-		foreach ($this->backends as $backend) {
285
-			if ($backend instanceof Database) {
286
-				// First check if there is another user backend
287
-				$localBackends[] = $backend;
288
-				continue;
289
-			}
290
-
291
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
292
-				return $this->createUserFromBackend($uid, $password, $backend);
293
-			}
294
-		}
295
-
296
-		foreach ($localBackends as $backend) {
297
-			if ($backend->implementsActions(Backend::CREATE_USER)) {
298
-				return $this->createUserFromBackend($uid, $password, $backend);
299
-			}
300
-		}
301
-
302
-		return false;
303
-	}
304
-
305
-	/**
306
-	 * @param string $uid
307
-	 * @param string $password
308
-	 * @param UserInterface $backend
309
-	 * @return IUser|null
310
-	 * @throws \InvalidArgumentException
311
-	 */
312
-	public function createUserFromBackend($uid, $password, UserInterface $backend) {
313
-		$l = \OC::$server->getL10N('lib');
314
-
315
-		// Check the name for bad characters
316
-		// Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
317
-		if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
318
-			throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
319
-				. ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
320
-		}
321
-		// No empty username
322
-		if (trim($uid) === '') {
323
-			throw new \InvalidArgumentException($l->t('A valid username must be provided'));
324
-		}
325
-		// No whitespace at the beginning or at the end
326
-		if (trim($uid) !== $uid) {
327
-			throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
328
-		}
329
-		// Username only consists of 1 or 2 dots (directory traversal)
330
-		if ($uid === '.' || $uid === '..') {
331
-			throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
332
-		}
333
-		// No empty password
334
-		if (trim($password) === '') {
335
-			throw new \InvalidArgumentException($l->t('A valid password must be provided'));
336
-		}
337
-
338
-		// Check if user already exists
339
-		if ($this->userExists($uid)) {
340
-			throw new \InvalidArgumentException($l->t('The username is already being used'));
341
-		}
342
-
343
-		$this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
344
-		$state = $backend->createUser($uid, $password);
345
-		if($state === false) {
346
-			throw new \InvalidArgumentException($l->t('Could not create user'));
347
-		}
348
-		$user = $this->getUserObject($uid, $backend);
349
-		if ($user instanceof IUser) {
350
-			$this->emit('\OC\User', 'postCreateUser', [$user, $password]);
351
-		}
352
-		return $user;
353
-	}
354
-
355
-	/**
356
-	 * returns how many users per backend exist (if supported by backend)
357
-	 *
358
-	 * @param boolean $hasLoggedIn when true only users that have a lastLogin
359
-	 *                entry in the preferences table will be affected
360
-	 * @return array|int an array of backend class as key and count number as value
361
-	 *                if $hasLoggedIn is true only an int is returned
362
-	 */
363
-	public function countUsers($hasLoggedIn = false) {
364
-		if ($hasLoggedIn) {
365
-			return $this->countSeenUsers();
366
-		}
367
-		$userCountStatistics = [];
368
-		foreach ($this->backends as $backend) {
369
-			if ($backend->implementsActions(Backend::COUNT_USERS)) {
370
-				$backendUsers = $backend->countUsers();
371
-				if($backendUsers !== false) {
372
-					if($backend instanceof IUserBackend) {
373
-						$name = $backend->getBackendName();
374
-					} else {
375
-						$name = get_class($backend);
376
-					}
377
-					if(isset($userCountStatistics[$name])) {
378
-						$userCountStatistics[$name] += $backendUsers;
379
-					} else {
380
-						$userCountStatistics[$name] = $backendUsers;
381
-					}
382
-				}
383
-			}
384
-		}
385
-		return $userCountStatistics;
386
-	}
387
-
388
-	/**
389
-	 * returns how many users per backend exist in the requested groups (if supported by backend)
390
-	 *
391
-	 * @param IGroup[] $groups an array of gid to search in
392
-	 * @return array|int an array of backend class as key and count number as value
393
-	 *                if $hasLoggedIn is true only an int is returned
394
-	 */
395
-	public function countUsersOfGroups(array $groups) {
396
-		$users = [];
397
-		foreach($groups as $group) {
398
-			$usersIds = array_map(function($user) {
399
-				return $user->getUID();
400
-			}, $group->getUsers());
401
-			$users = array_merge($users, $usersIds);
402
-		}
403
-		return count(array_unique($users));
404
-	}
405
-
406
-	/**
407
-	 * The callback is executed for each user on each backend.
408
-	 * If the callback returns false no further users will be retrieved.
409
-	 *
410
-	 * @param \Closure $callback
411
-	 * @param string $search
412
-	 * @param boolean $onlySeen when true only users that have a lastLogin entry
413
-	 *                in the preferences table will be affected
414
-	 * @since 9.0.0
415
-	 */
416
-	public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
417
-		if ($onlySeen) {
418
-			$this->callForSeenUsers($callback);
419
-		} else {
420
-			foreach ($this->getBackends() as $backend) {
421
-				$limit = 500;
422
-				$offset = 0;
423
-				do {
424
-					$users = $backend->getUsers($search, $limit, $offset);
425
-					foreach ($users as $uid) {
426
-						if (!$backend->userExists($uid)) {
427
-							continue;
428
-						}
429
-						$user = $this->getUserObject($uid, $backend, false);
430
-						$return = $callback($user);
431
-						if ($return === false) {
432
-							break;
433
-						}
434
-					}
435
-					$offset += $limit;
436
-				} while (count($users) >= $limit);
437
-			}
438
-		}
439
-	}
440
-
441
-	/**
442
-	 * returns how many users are disabled
443
-	 *
444
-	 * @return int
445
-	 * @since 12.0.0
446
-	 */
447
-	public function countDisabledUsers(): int {
448
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
449
-		$queryBuilder->select($queryBuilder->func()->count('*'))
450
-			->from('preferences')
451
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
452
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
453
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
61
+    /**
62
+     * @var \OCP\UserInterface[] $backends
63
+     */
64
+    private $backends = array();
65
+
66
+    /**
67
+     * @var \OC\User\User[] $cachedUsers
68
+     */
69
+    private $cachedUsers = array();
70
+
71
+    /**
72
+     * @var \OCP\IConfig $config
73
+     */
74
+    private $config;
75
+
76
+    /**
77
+     * @param \OCP\IConfig $config
78
+     */
79
+    public function __construct(IConfig $config) {
80
+        $this->config = $config;
81
+        $cachedUsers = &$this->cachedUsers;
82
+        $this->listen('\OC\User', 'postDelete', function ($user) use (&$cachedUsers) {
83
+            /** @var \OC\User\User $user */
84
+            unset($cachedUsers[$user->getUID()]);
85
+        });
86
+    }
87
+
88
+    /**
89
+     * Get the active backends
90
+     * @return \OCP\UserInterface[]
91
+     */
92
+    public function getBackends() {
93
+        return $this->backends;
94
+    }
95
+
96
+    /**
97
+     * register a user backend
98
+     *
99
+     * @param \OCP\UserInterface $backend
100
+     */
101
+    public function registerBackend($backend) {
102
+        $this->backends[] = $backend;
103
+    }
104
+
105
+    /**
106
+     * remove a user backend
107
+     *
108
+     * @param \OCP\UserInterface $backend
109
+     */
110
+    public function removeBackend($backend) {
111
+        $this->cachedUsers = array();
112
+        if (($i = array_search($backend, $this->backends)) !== false) {
113
+            unset($this->backends[$i]);
114
+        }
115
+    }
116
+
117
+    /**
118
+     * remove all user backends
119
+     */
120
+    public function clearBackends() {
121
+        $this->cachedUsers = array();
122
+        $this->backends = array();
123
+    }
124
+
125
+    /**
126
+     * get a user by user id
127
+     *
128
+     * @param string $uid
129
+     * @return \OC\User\User|null Either the user or null if the specified user does not exist
130
+     */
131
+    public function get($uid) {
132
+        if (is_null($uid) || $uid === '' || $uid === false) {
133
+            return null;
134
+        }
135
+        if (isset($this->cachedUsers[$uid])) { //check the cache first to prevent having to loop over the backends
136
+            return $this->cachedUsers[$uid];
137
+        }
138
+        foreach ($this->backends as $backend) {
139
+            if ($backend->userExists($uid)) {
140
+                return $this->getUserObject($uid, $backend);
141
+            }
142
+        }
143
+        return null;
144
+    }
145
+
146
+    /**
147
+     * get or construct the user object
148
+     *
149
+     * @param string $uid
150
+     * @param \OCP\UserInterface $backend
151
+     * @param bool $cacheUser If false the newly created user object will not be cached
152
+     * @return \OC\User\User
153
+     */
154
+    protected function getUserObject($uid, $backend, $cacheUser = true) {
155
+        if (isset($this->cachedUsers[$uid])) {
156
+            return $this->cachedUsers[$uid];
157
+        }
158
+
159
+        $user = new User($uid, $backend, $this, $this->config);
160
+        if ($cacheUser) {
161
+            $this->cachedUsers[$uid] = $user;
162
+        }
163
+        return $user;
164
+    }
165
+
166
+    /**
167
+     * check if a user exists
168
+     *
169
+     * @param string $uid
170
+     * @return bool
171
+     */
172
+    public function userExists($uid) {
173
+        $user = $this->get($uid);
174
+        return ($user !== null);
175
+    }
176
+
177
+    /**
178
+     * Check if the password is valid for the user
179
+     *
180
+     * @param string $loginName
181
+     * @param string $password
182
+     * @return mixed the User object on success, false otherwise
183
+     */
184
+    public function checkPassword($loginName, $password) {
185
+        $result = $this->checkPasswordNoLogging($loginName, $password);
186
+
187
+        if ($result === false) {
188
+            \OC::$server->getLogger()->warning('Login failed: \''. $loginName .'\' (Remote IP: \''. \OC::$server->getRequest()->getRemoteAddress(). '\')', ['app' => 'core']);
189
+        }
190
+
191
+        return $result;
192
+    }
193
+
194
+    /**
195
+     * Check if the password is valid for the user
196
+     *
197
+     * @internal
198
+     * @param string $loginName
199
+     * @param string $password
200
+     * @return mixed the User object on success, false otherwise
201
+     */
202
+    public function checkPasswordNoLogging($loginName, $password) {
203
+        $loginName = str_replace("\0", '', $loginName);
204
+        $password = str_replace("\0", '', $password);
205
+
206
+        foreach ($this->backends as $backend) {
207
+            if ($backend->implementsActions(Backend::CHECK_PASSWORD)) {
208
+                $uid = $backend->checkPassword($loginName, $password);
209
+                if ($uid !== false) {
210
+                    return $this->getUserObject($uid, $backend);
211
+                }
212
+            }
213
+        }
214
+
215
+        return false;
216
+    }
217
+
218
+    /**
219
+     * search by user id
220
+     *
221
+     * @param string $pattern
222
+     * @param int $limit
223
+     * @param int $offset
224
+     * @return \OC\User\User[]
225
+     */
226
+    public function search($pattern, $limit = null, $offset = null) {
227
+        $users = array();
228
+        foreach ($this->backends as $backend) {
229
+            $backendUsers = $backend->getUsers($pattern, $limit, $offset);
230
+            if (is_array($backendUsers)) {
231
+                foreach ($backendUsers as $uid) {
232
+                    $users[$uid] = $this->getUserObject($uid, $backend);
233
+                }
234
+            }
235
+        }
236
+
237
+        uasort($users, function ($a, $b) {
238
+            /**
239
+             * @var \OC\User\User $a
240
+             * @var \OC\User\User $b
241
+             */
242
+            return strcasecmp($a->getUID(), $b->getUID());
243
+        });
244
+        return $users;
245
+    }
246
+
247
+    /**
248
+     * search by displayName
249
+     *
250
+     * @param string $pattern
251
+     * @param int $limit
252
+     * @param int $offset
253
+     * @return \OC\User\User[]
254
+     */
255
+    public function searchDisplayName($pattern, $limit = null, $offset = null) {
256
+        $users = array();
257
+        foreach ($this->backends as $backend) {
258
+            $backendUsers = $backend->getDisplayNames($pattern, $limit, $offset);
259
+            if (is_array($backendUsers)) {
260
+                foreach ($backendUsers as $uid => $displayName) {
261
+                    $users[] = $this->getUserObject($uid, $backend);
262
+                }
263
+            }
264
+        }
265
+
266
+        usort($users, function ($a, $b) {
267
+            /**
268
+             * @var \OC\User\User $a
269
+             * @var \OC\User\User $b
270
+             */
271
+            return strcasecmp($a->getDisplayName(), $b->getDisplayName());
272
+        });
273
+        return $users;
274
+    }
275
+
276
+    /**
277
+     * @param string $uid
278
+     * @param string $password
279
+     * @throws \InvalidArgumentException
280
+     * @return bool|IUser the created user or false
281
+     */
282
+    public function createUser($uid, $password) {
283
+        $localBackends = [];
284
+        foreach ($this->backends as $backend) {
285
+            if ($backend instanceof Database) {
286
+                // First check if there is another user backend
287
+                $localBackends[] = $backend;
288
+                continue;
289
+            }
290
+
291
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
292
+                return $this->createUserFromBackend($uid, $password, $backend);
293
+            }
294
+        }
295
+
296
+        foreach ($localBackends as $backend) {
297
+            if ($backend->implementsActions(Backend::CREATE_USER)) {
298
+                return $this->createUserFromBackend($uid, $password, $backend);
299
+            }
300
+        }
301
+
302
+        return false;
303
+    }
304
+
305
+    /**
306
+     * @param string $uid
307
+     * @param string $password
308
+     * @param UserInterface $backend
309
+     * @return IUser|null
310
+     * @throws \InvalidArgumentException
311
+     */
312
+    public function createUserFromBackend($uid, $password, UserInterface $backend) {
313
+        $l = \OC::$server->getL10N('lib');
314
+
315
+        // Check the name for bad characters
316
+        // Allowed are: "a-z", "A-Z", "0-9" and "_.@-'"
317
+        if (preg_match('/[^a-zA-Z0-9 _\.@\-\']/', $uid)) {
318
+            throw new \InvalidArgumentException($l->t('Only the following characters are allowed in a username:'
319
+                . ' "a-z", "A-Z", "0-9", and "_.@-\'"'));
320
+        }
321
+        // No empty username
322
+        if (trim($uid) === '') {
323
+            throw new \InvalidArgumentException($l->t('A valid username must be provided'));
324
+        }
325
+        // No whitespace at the beginning or at the end
326
+        if (trim($uid) !== $uid) {
327
+            throw new \InvalidArgumentException($l->t('Username contains whitespace at the beginning or at the end'));
328
+        }
329
+        // Username only consists of 1 or 2 dots (directory traversal)
330
+        if ($uid === '.' || $uid === '..') {
331
+            throw new \InvalidArgumentException($l->t('Username must not consist of dots only'));
332
+        }
333
+        // No empty password
334
+        if (trim($password) === '') {
335
+            throw new \InvalidArgumentException($l->t('A valid password must be provided'));
336
+        }
337
+
338
+        // Check if user already exists
339
+        if ($this->userExists($uid)) {
340
+            throw new \InvalidArgumentException($l->t('The username is already being used'));
341
+        }
342
+
343
+        $this->emit('\OC\User', 'preCreateUser', [$uid, $password]);
344
+        $state = $backend->createUser($uid, $password);
345
+        if($state === false) {
346
+            throw new \InvalidArgumentException($l->t('Could not create user'));
347
+        }
348
+        $user = $this->getUserObject($uid, $backend);
349
+        if ($user instanceof IUser) {
350
+            $this->emit('\OC\User', 'postCreateUser', [$user, $password]);
351
+        }
352
+        return $user;
353
+    }
354
+
355
+    /**
356
+     * returns how many users per backend exist (if supported by backend)
357
+     *
358
+     * @param boolean $hasLoggedIn when true only users that have a lastLogin
359
+     *                entry in the preferences table will be affected
360
+     * @return array|int an array of backend class as key and count number as value
361
+     *                if $hasLoggedIn is true only an int is returned
362
+     */
363
+    public function countUsers($hasLoggedIn = false) {
364
+        if ($hasLoggedIn) {
365
+            return $this->countSeenUsers();
366
+        }
367
+        $userCountStatistics = [];
368
+        foreach ($this->backends as $backend) {
369
+            if ($backend->implementsActions(Backend::COUNT_USERS)) {
370
+                $backendUsers = $backend->countUsers();
371
+                if($backendUsers !== false) {
372
+                    if($backend instanceof IUserBackend) {
373
+                        $name = $backend->getBackendName();
374
+                    } else {
375
+                        $name = get_class($backend);
376
+                    }
377
+                    if(isset($userCountStatistics[$name])) {
378
+                        $userCountStatistics[$name] += $backendUsers;
379
+                    } else {
380
+                        $userCountStatistics[$name] = $backendUsers;
381
+                    }
382
+                }
383
+            }
384
+        }
385
+        return $userCountStatistics;
386
+    }
387
+
388
+    /**
389
+     * returns how many users per backend exist in the requested groups (if supported by backend)
390
+     *
391
+     * @param IGroup[] $groups an array of gid to search in
392
+     * @return array|int an array of backend class as key and count number as value
393
+     *                if $hasLoggedIn is true only an int is returned
394
+     */
395
+    public function countUsersOfGroups(array $groups) {
396
+        $users = [];
397
+        foreach($groups as $group) {
398
+            $usersIds = array_map(function($user) {
399
+                return $user->getUID();
400
+            }, $group->getUsers());
401
+            $users = array_merge($users, $usersIds);
402
+        }
403
+        return count(array_unique($users));
404
+    }
405
+
406
+    /**
407
+     * The callback is executed for each user on each backend.
408
+     * If the callback returns false no further users will be retrieved.
409
+     *
410
+     * @param \Closure $callback
411
+     * @param string $search
412
+     * @param boolean $onlySeen when true only users that have a lastLogin entry
413
+     *                in the preferences table will be affected
414
+     * @since 9.0.0
415
+     */
416
+    public function callForAllUsers(\Closure $callback, $search = '', $onlySeen = false) {
417
+        if ($onlySeen) {
418
+            $this->callForSeenUsers($callback);
419
+        } else {
420
+            foreach ($this->getBackends() as $backend) {
421
+                $limit = 500;
422
+                $offset = 0;
423
+                do {
424
+                    $users = $backend->getUsers($search, $limit, $offset);
425
+                    foreach ($users as $uid) {
426
+                        if (!$backend->userExists($uid)) {
427
+                            continue;
428
+                        }
429
+                        $user = $this->getUserObject($uid, $backend, false);
430
+                        $return = $callback($user);
431
+                        if ($return === false) {
432
+                            break;
433
+                        }
434
+                    }
435
+                    $offset += $limit;
436
+                } while (count($users) >= $limit);
437
+            }
438
+        }
439
+    }
440
+
441
+    /**
442
+     * returns how many users are disabled
443
+     *
444
+     * @return int
445
+     * @since 12.0.0
446
+     */
447
+    public function countDisabledUsers(): int {
448
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
449
+        $queryBuilder->select($queryBuilder->func()->count('*'))
450
+            ->from('preferences')
451
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
452
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
453
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR));
454 454
 
455 455
 		
456
-		$result = $queryBuilder->execute();
457
-		$count = $result->fetchColumn();
458
-		$result->closeCursor();
456
+        $result = $queryBuilder->execute();
457
+        $count = $result->fetchColumn();
458
+        $result->closeCursor();
459 459
 		
460
-		if ($count !== false) {
461
-			$count = (int)$count;
462
-		} else {
463
-			$count = 0;
464
-		}
465
-
466
-		return $count;
467
-	}
468
-
469
-	/**
470
-	 * returns how many users are disabled in the requested groups
471
-	 *
472
-	 * @param array $groups groupids to search
473
-	 * @return int
474
-	 * @since 14.0.0
475
-	 */
476
-	public function countDisabledUsersOfGroups(array $groups): int {
477
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
478
-		$queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
479
-			->from('preferences', 'p')
480
-			->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
481
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
482
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
483
-			->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
484
-			->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
485
-
486
-		$result = $queryBuilder->execute();
487
-		$count = $result->fetchColumn();
488
-		$result->closeCursor();
460
+        if ($count !== false) {
461
+            $count = (int)$count;
462
+        } else {
463
+            $count = 0;
464
+        }
465
+
466
+        return $count;
467
+    }
468
+
469
+    /**
470
+     * returns how many users are disabled in the requested groups
471
+     *
472
+     * @param array $groups groupids to search
473
+     * @return int
474
+     * @since 14.0.0
475
+     */
476
+    public function countDisabledUsersOfGroups(array $groups): int {
477
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
478
+        $queryBuilder->select($queryBuilder->createFunction('COUNT(DISTINCT ' . $queryBuilder->getColumnName('uid') . ')'))
479
+            ->from('preferences', 'p')
480
+            ->innerJoin('p', 'group_user', 'g', $queryBuilder->expr()->eq('p.userid', 'g.uid'))
481
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('core')))
482
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('enabled')))
483
+            ->andWhere($queryBuilder->expr()->eq('configvalue', $queryBuilder->createNamedParameter('false'), IQueryBuilder::PARAM_STR))
484
+            ->andWhere($queryBuilder->expr()->in('gid', $queryBuilder->createNamedParameter($groups, IQueryBuilder::PARAM_STR_ARRAY)));
485
+
486
+        $result = $queryBuilder->execute();
487
+        $count = $result->fetchColumn();
488
+        $result->closeCursor();
489 489
 		
490
-		if ($count !== false) {
491
-			$count = (int)$count;
492
-		} else {
493
-			$count = 0;
494
-		}
495
-
496
-		return $count;
497
-	}
498
-
499
-	/**
500
-	 * returns how many users have logged in once
501
-	 *
502
-	 * @return int
503
-	 * @since 11.0.0
504
-	 */
505
-	public function countSeenUsers() {
506
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
507
-		$queryBuilder->select($queryBuilder->func()->count('*'))
508
-			->from('preferences')
509
-			->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
510
-			->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
511
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
512
-
513
-		$query = $queryBuilder->execute();
514
-
515
-		$result = (int)$query->fetchColumn();
516
-		$query->closeCursor();
517
-
518
-		return $result;
519
-	}
520
-
521
-	/**
522
-	 * @param \Closure $callback
523
-	 * @since 11.0.0
524
-	 */
525
-	public function callForSeenUsers(\Closure $callback) {
526
-		$limit = 1000;
527
-		$offset = 0;
528
-		do {
529
-			$userIds = $this->getSeenUserIds($limit, $offset);
530
-			$offset += $limit;
531
-			foreach ($userIds as $userId) {
532
-				foreach ($this->backends as $backend) {
533
-					if ($backend->userExists($userId)) {
534
-						$user = $this->getUserObject($userId, $backend, false);
535
-						$return = $callback($user);
536
-						if ($return === false) {
537
-							return;
538
-						}
539
-						break;
540
-					}
541
-				}
542
-			}
543
-		} while (count($userIds) >= $limit);
544
-	}
545
-
546
-	/**
547
-	 * Getting all userIds that have a listLogin value requires checking the
548
-	 * value in php because on oracle you cannot use a clob in a where clause,
549
-	 * preventing us from doing a not null or length(value) > 0 check.
550
-	 *
551
-	 * @param int $limit
552
-	 * @param int $offset
553
-	 * @return string[] with user ids
554
-	 */
555
-	private function getSeenUserIds($limit = null, $offset = null) {
556
-		$queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
557
-		$queryBuilder->select(['userid'])
558
-			->from('preferences')
559
-			->where($queryBuilder->expr()->eq(
560
-				'appid', $queryBuilder->createNamedParameter('login'))
561
-			)
562
-			->andWhere($queryBuilder->expr()->eq(
563
-				'configkey', $queryBuilder->createNamedParameter('lastLogin'))
564
-			)
565
-			->andWhere($queryBuilder->expr()->isNotNull('configvalue')
566
-			);
567
-
568
-		if ($limit !== null) {
569
-			$queryBuilder->setMaxResults($limit);
570
-		}
571
-		if ($offset !== null) {
572
-			$queryBuilder->setFirstResult($offset);
573
-		}
574
-		$query = $queryBuilder->execute();
575
-		$result = [];
576
-
577
-		while ($row = $query->fetch()) {
578
-			$result[] = $row['userid'];
579
-		}
580
-
581
-		$query->closeCursor();
582
-
583
-		return $result;
584
-	}
585
-
586
-	/**
587
-	 * @param string $email
588
-	 * @return IUser[]
589
-	 * @since 9.1.0
590
-	 */
591
-	public function getByEmail($email) {
592
-		$userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
593
-
594
-		$users = array_map(function($uid) {
595
-			return $this->get($uid);
596
-		}, $userIds);
597
-
598
-		return array_values(array_filter($users, function($u) {
599
-			return ($u instanceof IUser);
600
-		}));
601
-	}
490
+        if ($count !== false) {
491
+            $count = (int)$count;
492
+        } else {
493
+            $count = 0;
494
+        }
495
+
496
+        return $count;
497
+    }
498
+
499
+    /**
500
+     * returns how many users have logged in once
501
+     *
502
+     * @return int
503
+     * @since 11.0.0
504
+     */
505
+    public function countSeenUsers() {
506
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
507
+        $queryBuilder->select($queryBuilder->func()->count('*'))
508
+            ->from('preferences')
509
+            ->where($queryBuilder->expr()->eq('appid', $queryBuilder->createNamedParameter('login')))
510
+            ->andWhere($queryBuilder->expr()->eq('configkey', $queryBuilder->createNamedParameter('lastLogin')))
511
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
512
+
513
+        $query = $queryBuilder->execute();
514
+
515
+        $result = (int)$query->fetchColumn();
516
+        $query->closeCursor();
517
+
518
+        return $result;
519
+    }
520
+
521
+    /**
522
+     * @param \Closure $callback
523
+     * @since 11.0.0
524
+     */
525
+    public function callForSeenUsers(\Closure $callback) {
526
+        $limit = 1000;
527
+        $offset = 0;
528
+        do {
529
+            $userIds = $this->getSeenUserIds($limit, $offset);
530
+            $offset += $limit;
531
+            foreach ($userIds as $userId) {
532
+                foreach ($this->backends as $backend) {
533
+                    if ($backend->userExists($userId)) {
534
+                        $user = $this->getUserObject($userId, $backend, false);
535
+                        $return = $callback($user);
536
+                        if ($return === false) {
537
+                            return;
538
+                        }
539
+                        break;
540
+                    }
541
+                }
542
+            }
543
+        } while (count($userIds) >= $limit);
544
+    }
545
+
546
+    /**
547
+     * Getting all userIds that have a listLogin value requires checking the
548
+     * value in php because on oracle you cannot use a clob in a where clause,
549
+     * preventing us from doing a not null or length(value) > 0 check.
550
+     *
551
+     * @param int $limit
552
+     * @param int $offset
553
+     * @return string[] with user ids
554
+     */
555
+    private function getSeenUserIds($limit = null, $offset = null) {
556
+        $queryBuilder = \OC::$server->getDatabaseConnection()->getQueryBuilder();
557
+        $queryBuilder->select(['userid'])
558
+            ->from('preferences')
559
+            ->where($queryBuilder->expr()->eq(
560
+                'appid', $queryBuilder->createNamedParameter('login'))
561
+            )
562
+            ->andWhere($queryBuilder->expr()->eq(
563
+                'configkey', $queryBuilder->createNamedParameter('lastLogin'))
564
+            )
565
+            ->andWhere($queryBuilder->expr()->isNotNull('configvalue')
566
+            );
567
+
568
+        if ($limit !== null) {
569
+            $queryBuilder->setMaxResults($limit);
570
+        }
571
+        if ($offset !== null) {
572
+            $queryBuilder->setFirstResult($offset);
573
+        }
574
+        $query = $queryBuilder->execute();
575
+        $result = [];
576
+
577
+        while ($row = $query->fetch()) {
578
+            $result[] = $row['userid'];
579
+        }
580
+
581
+        $query->closeCursor();
582
+
583
+        return $result;
584
+    }
585
+
586
+    /**
587
+     * @param string $email
588
+     * @return IUser[]
589
+     * @since 9.1.0
590
+     */
591
+    public function getByEmail($email) {
592
+        $userIds = $this->config->getUsersForUserValueCaseInsensitive('settings', 'email', $email);
593
+
594
+        $users = array_map(function($uid) {
595
+            return $this->get($uid);
596
+        }, $userIds);
597
+
598
+        return array_values(array_filter($users, function($u) {
599
+            return ($u instanceof IUser);
600
+        }));
601
+    }
602 602
 }
Please login to merge, or discard this patch.
lib/private/AllConfig.php 2 patches
Indentation   +455 added lines, -455 removed lines patch added patch discarded remove patch
@@ -39,459 +39,459 @@
 block discarded – undo
39 39
  * Class to combine all the configuration options ownCloud offers
40 40
  */
41 41
 class AllConfig implements \OCP\IConfig {
42
-	/** @var SystemConfig */
43
-	private $systemConfig;
44
-
45
-	/** @var IDBConnection */
46
-	private $connection;
47
-
48
-	/**
49
-	 * 3 dimensional array with the following structure:
50
-	 * [ $userId =>
51
-	 *     [ $appId =>
52
-	 *         [ $key => $value ]
53
-	 *     ]
54
-	 * ]
55
-	 *
56
-	 * database table: preferences
57
-	 *
58
-	 * methods that use this:
59
-	 *   - setUserValue
60
-	 *   - getUserValue
61
-	 *   - getUserKeys
62
-	 *   - deleteUserValue
63
-	 *   - deleteAllUserValues
64
-	 *   - deleteAppFromAllUsers
65
-	 *
66
-	 * @var CappedMemoryCache $userCache
67
-	 */
68
-	private $userCache;
69
-
70
-	/**
71
-	 * @param SystemConfig $systemConfig
72
-	 */
73
-	public function __construct(SystemConfig $systemConfig) {
74
-		$this->userCache = new CappedMemoryCache();
75
-		$this->systemConfig = $systemConfig;
76
-	}
77
-
78
-	/**
79
-	 * TODO - FIXME This fixes an issue with base.php that cause cyclic
80
-	 * dependencies, especially with autoconfig setup
81
-	 *
82
-	 * Replace this by properly injected database connection. Currently the
83
-	 * base.php triggers the getDatabaseConnection too early which causes in
84
-	 * autoconfig setup case a too early distributed database connection and
85
-	 * the autoconfig then needs to reinit all already initialized dependencies
86
-	 * that use the database connection.
87
-	 *
88
-	 * otherwise a SQLite database is created in the wrong directory
89
-	 * because the database connection was created with an uninitialized config
90
-	 */
91
-	private function fixDIInit() {
92
-		if($this->connection === null) {
93
-			$this->connection = \OC::$server->getDatabaseConnection();
94
-		}
95
-	}
96
-
97
-	/**
98
-	 * Sets and deletes system wide values
99
-	 *
100
-	 * @param array $configs Associative array with `key => value` pairs
101
-	 *                       If value is null, the config key will be deleted
102
-	 */
103
-	public function setSystemValues(array $configs) {
104
-		$this->systemConfig->setValues($configs);
105
-	}
106
-
107
-	/**
108
-	 * Sets a new system wide value
109
-	 *
110
-	 * @param string $key the key of the value, under which will be saved
111
-	 * @param mixed $value the value that should be stored
112
-	 */
113
-	public function setSystemValue($key, $value) {
114
-		$this->systemConfig->setValue($key, $value);
115
-	}
116
-
117
-	/**
118
-	 * Looks up a system wide defined value
119
-	 *
120
-	 * @param string $key the key of the value, under which it was saved
121
-	 * @param mixed $default the default value to be returned if the value isn't set
122
-	 * @return mixed the value or $default
123
-	 */
124
-	public function getSystemValue($key, $default = '') {
125
-		return $this->systemConfig->getValue($key, $default);
126
-	}
127
-
128
-	/**
129
-	 * Looks up a system wide defined value and filters out sensitive data
130
-	 *
131
-	 * @param string $key the key of the value, under which it was saved
132
-	 * @param mixed $default the default value to be returned if the value isn't set
133
-	 * @return mixed the value or $default
134
-	 */
135
-	public function getFilteredSystemValue($key, $default = '') {
136
-		return $this->systemConfig->getFilteredValue($key, $default);
137
-	}
138
-
139
-	/**
140
-	 * Delete a system wide defined value
141
-	 *
142
-	 * @param string $key the key of the value, under which it was saved
143
-	 */
144
-	public function deleteSystemValue($key) {
145
-		$this->systemConfig->deleteValue($key);
146
-	}
147
-
148
-	/**
149
-	 * Get all keys stored for an app
150
-	 *
151
-	 * @param string $appName the appName that we stored the value under
152
-	 * @return string[] the keys stored for the app
153
-	 */
154
-	public function getAppKeys($appName) {
155
-		return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName);
156
-	}
157
-
158
-	/**
159
-	 * Writes a new app wide value
160
-	 *
161
-	 * @param string $appName the appName that we want to store the value under
162
-	 * @param string $key the key of the value, under which will be saved
163
-	 * @param string|float|int $value the value that should be stored
164
-	 */
165
-	public function setAppValue($appName, $key, $value) {
166
-		\OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value);
167
-	}
168
-
169
-	/**
170
-	 * Looks up an app wide defined value
171
-	 *
172
-	 * @param string $appName the appName that we stored the value under
173
-	 * @param string $key the key of the value, under which it was saved
174
-	 * @param string $default the default value to be returned if the value isn't set
175
-	 * @return string the saved value
176
-	 */
177
-	public function getAppValue($appName, $key, $default = '') {
178
-		return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default);
179
-	}
180
-
181
-	/**
182
-	 * Delete an app wide defined value
183
-	 *
184
-	 * @param string $appName the appName that we stored the value under
185
-	 * @param string $key the key of the value, under which it was saved
186
-	 */
187
-	public function deleteAppValue($appName, $key) {
188
-		\OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key);
189
-	}
190
-
191
-	/**
192
-	 * Removes all keys in appconfig belonging to the app
193
-	 *
194
-	 * @param string $appName the appName the configs are stored under
195
-	 */
196
-	public function deleteAppValues($appName) {
197
-		\OC::$server->query(\OC\AppConfig::class)->deleteApp($appName);
198
-	}
199
-
200
-
201
-	/**
202
-	 * Set a user defined value
203
-	 *
204
-	 * @param string $userId the userId of the user that we want to store the value under
205
-	 * @param string $appName the appName that we want to store the value under
206
-	 * @param string $key the key under which the value is being stored
207
-	 * @param string|float|int $value the value that you want to store
208
-	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
209
-	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
210
-	 * @throws \UnexpectedValueException when trying to store an unexpected value
211
-	 */
212
-	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
213
-		if (!is_int($value) && !is_float($value) && !is_string($value)) {
214
-			throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
215
-		}
216
-
217
-		// TODO - FIXME
218
-		$this->fixDIInit();
219
-
220
-		$prevValue = $this->getUserValue($userId, $appName, $key, null);
221
-
222
-		if ($prevValue !== null) {
223
-			if ($prevValue === (string)$value) {
224
-				return;
225
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
226
-				throw new PreConditionNotMetException();
227
-			} else {
228
-				$qb = $this->connection->getQueryBuilder();
229
-				$qb->update('preferences')
230
-					->set('configvalue', $qb->createNamedParameter($value))
231
-					->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
232
-					->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
233
-					->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
234
-				$qb->execute();
235
-
236
-				$this->userCache[$userId][$appName][$key] = (string)$value;
237
-				return;
238
-			}
239
-		}
240
-
241
-		$preconditionArray = [];
242
-		if (isset($preCondition)) {
243
-			$preconditionArray = [
244
-				'configvalue' => $preCondition,
245
-			];
246
-		}
247
-
248
-		$this->connection->setValues('preferences', [
249
-			'userid' => $userId,
250
-			'appid' => $appName,
251
-			'configkey' => $key,
252
-		], [
253
-			'configvalue' => $value,
254
-		], $preconditionArray);
255
-
256
-		// only add to the cache if we already loaded data for the user
257
-		if (isset($this->userCache[$userId])) {
258
-			if (!isset($this->userCache[$userId][$appName])) {
259
-				$this->userCache[$userId][$appName] = array();
260
-			}
261
-			$this->userCache[$userId][$appName][$key] = (string)$value;
262
-		}
263
-	}
264
-
265
-	/**
266
-	 * Getting a user defined value
267
-	 *
268
-	 * @param string $userId the userId of the user that we want to store the value under
269
-	 * @param string $appName the appName that we stored the value under
270
-	 * @param string $key the key under which the value is being stored
271
-	 * @param mixed $default the default value to be returned if the value isn't set
272
-	 * @return string
273
-	 */
274
-	public function getUserValue($userId, $appName, $key, $default = '') {
275
-		$data = $this->getUserValues($userId);
276
-		if (isset($data[$appName]) and isset($data[$appName][$key])) {
277
-			return $data[$appName][$key];
278
-		} else {
279
-			return $default;
280
-		}
281
-	}
282
-
283
-	/**
284
-	 * Get the keys of all stored by an app for the user
285
-	 *
286
-	 * @param string $userId the userId of the user that we want to store the value under
287
-	 * @param string $appName the appName that we stored the value under
288
-	 * @return string[]
289
-	 */
290
-	public function getUserKeys($userId, $appName) {
291
-		$data = $this->getUserValues($userId);
292
-		if (isset($data[$appName])) {
293
-			return array_keys($data[$appName]);
294
-		} else {
295
-			return array();
296
-		}
297
-	}
298
-
299
-	/**
300
-	 * Delete a user value
301
-	 *
302
-	 * @param string $userId the userId of the user that we want to store the value under
303
-	 * @param string $appName the appName that we stored the value under
304
-	 * @param string $key the key under which the value is being stored
305
-	 */
306
-	public function deleteUserValue($userId, $appName, $key) {
307
-		// TODO - FIXME
308
-		$this->fixDIInit();
309
-
310
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
311
-				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
312
-		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
313
-
314
-		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
315
-			unset($this->userCache[$userId][$appName][$key]);
316
-		}
317
-	}
318
-
319
-	/**
320
-	 * Delete all user values
321
-	 *
322
-	 * @param string $userId the userId of the user that we want to remove all values from
323
-	 */
324
-	public function deleteAllUserValues($userId) {
325
-		// TODO - FIXME
326
-		$this->fixDIInit();
327
-
328
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
329
-			'WHERE `userid` = ?';
330
-		$this->connection->executeUpdate($sql, array($userId));
331
-
332
-		unset($this->userCache[$userId]);
333
-	}
334
-
335
-	/**
336
-	 * Delete all user related values of one app
337
-	 *
338
-	 * @param string $appName the appName of the app that we want to remove all values from
339
-	 */
340
-	public function deleteAppFromAllUsers($appName) {
341
-		// TODO - FIXME
342
-		$this->fixDIInit();
343
-
344
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
345
-				'WHERE `appid` = ?';
346
-		$this->connection->executeUpdate($sql, array($appName));
347
-
348
-		foreach ($this->userCache as &$userCache) {
349
-			unset($userCache[$appName]);
350
-		}
351
-	}
352
-
353
-	/**
354
-	 * Returns all user configs sorted by app of one user
355
-	 *
356
-	 * @param string $userId the user ID to get the app configs from
357
-	 * @return array[] - 2 dimensional array with the following structure:
358
-	 *     [ $appId =>
359
-	 *         [ $key => $value ]
360
-	 *     ]
361
-	 */
362
-	private function getUserValues($userId) {
363
-		if (isset($this->userCache[$userId])) {
364
-			return $this->userCache[$userId];
365
-		}
366
-		if ($userId === null || $userId === '') {
367
-			$this->userCache[$userId]=array();
368
-			return $this->userCache[$userId];
369
-		}
370
-
371
-		// TODO - FIXME
372
-		$this->fixDIInit();
373
-
374
-		$data = array();
375
-		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
376
-		$result = $this->connection->executeQuery($query, array($userId));
377
-		while ($row = $result->fetch()) {
378
-			$appId = $row['appid'];
379
-			if (!isset($data[$appId])) {
380
-				$data[$appId] = array();
381
-			}
382
-			$data[$appId][$row['configkey']] = $row['configvalue'];
383
-		}
384
-		$this->userCache[$userId] = $data;
385
-		return $data;
386
-	}
387
-
388
-	/**
389
-	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
390
-	 *
391
-	 * @param string $appName app to get the value for
392
-	 * @param string $key the key to get the value for
393
-	 * @param array $userIds the user IDs to fetch the values for
394
-	 * @return array Mapped values: userId => value
395
-	 */
396
-	public function getUserValueForUsers($appName, $key, $userIds) {
397
-		// TODO - FIXME
398
-		$this->fixDIInit();
399
-
400
-		if (empty($userIds) || !is_array($userIds)) {
401
-			return array();
402
-		}
403
-
404
-		$chunkedUsers = array_chunk($userIds, 50, true);
405
-		$placeholders50 = implode(',', array_fill(0, 50, '?'));
406
-
407
-		$userValues = array();
408
-		foreach ($chunkedUsers as $chunk) {
409
-			$queryParams = $chunk;
410
-			// create [$app, $key, $chunkedUsers]
411
-			array_unshift($queryParams, $key);
412
-			array_unshift($queryParams, $appName);
413
-
414
-			$placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
415
-
416
-			$query    = 'SELECT `userid`, `configvalue` ' .
417
-						'FROM `*PREFIX*preferences` ' .
418
-						'WHERE `appid` = ? AND `configkey` = ? ' .
419
-						'AND `userid` IN (' . $placeholders . ')';
420
-			$result = $this->connection->executeQuery($query, $queryParams);
421
-
422
-			while ($row = $result->fetch()) {
423
-				$userValues[$row['userid']] = $row['configvalue'];
424
-			}
425
-		}
426
-
427
-		return $userValues;
428
-	}
429
-
430
-	/**
431
-	 * Determines the users that have the given value set for a specific app-key-pair
432
-	 *
433
-	 * @param string $appName the app to get the user for
434
-	 * @param string $key the key to get the user for
435
-	 * @param string $value the value to get the user for
436
-	 * @return array of user IDs
437
-	 */
438
-	public function getUsersForUserValue($appName, $key, $value) {
439
-		// TODO - FIXME
440
-		$this->fixDIInit();
441
-
442
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
443
-				'WHERE `appid` = ? AND `configkey` = ? ';
444
-
445
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
446
-			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
447
-			$sql .= 'AND to_char(`configvalue`) = ?';
448
-		} else {
449
-			$sql .= 'AND `configvalue` = ?';
450
-		}
451
-
452
-		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
453
-
454
-		$userIDs = array();
455
-		while ($row = $result->fetch()) {
456
-			$userIDs[] = $row['userid'];
457
-		}
458
-
459
-		return $userIDs;
460
-	}
461
-
462
-	/**
463
-	 * Determines the users that have the given value set for a specific app-key-pair
464
-	 *
465
-	 * @param string $appName the app to get the user for
466
-	 * @param string $key the key to get the user for
467
-	 * @param string $value the value to get the user for
468
-	 * @return array of user IDs
469
-	 */
470
-	public function getUsersForUserValueCaseInsensitive($appName, $key, $value) {
471
-		// TODO - FIXME
472
-		$this->fixDIInit();
473
-
474
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
475
-			'WHERE `appid` = ? AND `configkey` = ? ';
476
-
477
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
478
-			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
479
-			$sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)';
480
-		} else {
481
-			$sql .= 'AND LOWER(`configvalue`) = LOWER(?)';
482
-		}
483
-
484
-		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
485
-
486
-		$userIDs = array();
487
-		while ($row = $result->fetch()) {
488
-			$userIDs[] = $row['userid'];
489
-		}
490
-
491
-		return $userIDs;
492
-	}
493
-
494
-	public function getSystemConfig() {
495
-		return $this->systemConfig;
496
-	}
42
+    /** @var SystemConfig */
43
+    private $systemConfig;
44
+
45
+    /** @var IDBConnection */
46
+    private $connection;
47
+
48
+    /**
49
+     * 3 dimensional array with the following structure:
50
+     * [ $userId =>
51
+     *     [ $appId =>
52
+     *         [ $key => $value ]
53
+     *     ]
54
+     * ]
55
+     *
56
+     * database table: preferences
57
+     *
58
+     * methods that use this:
59
+     *   - setUserValue
60
+     *   - getUserValue
61
+     *   - getUserKeys
62
+     *   - deleteUserValue
63
+     *   - deleteAllUserValues
64
+     *   - deleteAppFromAllUsers
65
+     *
66
+     * @var CappedMemoryCache $userCache
67
+     */
68
+    private $userCache;
69
+
70
+    /**
71
+     * @param SystemConfig $systemConfig
72
+     */
73
+    public function __construct(SystemConfig $systemConfig) {
74
+        $this->userCache = new CappedMemoryCache();
75
+        $this->systemConfig = $systemConfig;
76
+    }
77
+
78
+    /**
79
+     * TODO - FIXME This fixes an issue with base.php that cause cyclic
80
+     * dependencies, especially with autoconfig setup
81
+     *
82
+     * Replace this by properly injected database connection. Currently the
83
+     * base.php triggers the getDatabaseConnection too early which causes in
84
+     * autoconfig setup case a too early distributed database connection and
85
+     * the autoconfig then needs to reinit all already initialized dependencies
86
+     * that use the database connection.
87
+     *
88
+     * otherwise a SQLite database is created in the wrong directory
89
+     * because the database connection was created with an uninitialized config
90
+     */
91
+    private function fixDIInit() {
92
+        if($this->connection === null) {
93
+            $this->connection = \OC::$server->getDatabaseConnection();
94
+        }
95
+    }
96
+
97
+    /**
98
+     * Sets and deletes system wide values
99
+     *
100
+     * @param array $configs Associative array with `key => value` pairs
101
+     *                       If value is null, the config key will be deleted
102
+     */
103
+    public function setSystemValues(array $configs) {
104
+        $this->systemConfig->setValues($configs);
105
+    }
106
+
107
+    /**
108
+     * Sets a new system wide value
109
+     *
110
+     * @param string $key the key of the value, under which will be saved
111
+     * @param mixed $value the value that should be stored
112
+     */
113
+    public function setSystemValue($key, $value) {
114
+        $this->systemConfig->setValue($key, $value);
115
+    }
116
+
117
+    /**
118
+     * Looks up a system wide defined value
119
+     *
120
+     * @param string $key the key of the value, under which it was saved
121
+     * @param mixed $default the default value to be returned if the value isn't set
122
+     * @return mixed the value or $default
123
+     */
124
+    public function getSystemValue($key, $default = '') {
125
+        return $this->systemConfig->getValue($key, $default);
126
+    }
127
+
128
+    /**
129
+     * Looks up a system wide defined value and filters out sensitive data
130
+     *
131
+     * @param string $key the key of the value, under which it was saved
132
+     * @param mixed $default the default value to be returned if the value isn't set
133
+     * @return mixed the value or $default
134
+     */
135
+    public function getFilteredSystemValue($key, $default = '') {
136
+        return $this->systemConfig->getFilteredValue($key, $default);
137
+    }
138
+
139
+    /**
140
+     * Delete a system wide defined value
141
+     *
142
+     * @param string $key the key of the value, under which it was saved
143
+     */
144
+    public function deleteSystemValue($key) {
145
+        $this->systemConfig->deleteValue($key);
146
+    }
147
+
148
+    /**
149
+     * Get all keys stored for an app
150
+     *
151
+     * @param string $appName the appName that we stored the value under
152
+     * @return string[] the keys stored for the app
153
+     */
154
+    public function getAppKeys($appName) {
155
+        return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName);
156
+    }
157
+
158
+    /**
159
+     * Writes a new app wide value
160
+     *
161
+     * @param string $appName the appName that we want to store the value under
162
+     * @param string $key the key of the value, under which will be saved
163
+     * @param string|float|int $value the value that should be stored
164
+     */
165
+    public function setAppValue($appName, $key, $value) {
166
+        \OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value);
167
+    }
168
+
169
+    /**
170
+     * Looks up an app wide defined value
171
+     *
172
+     * @param string $appName the appName that we stored the value under
173
+     * @param string $key the key of the value, under which it was saved
174
+     * @param string $default the default value to be returned if the value isn't set
175
+     * @return string the saved value
176
+     */
177
+    public function getAppValue($appName, $key, $default = '') {
178
+        return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default);
179
+    }
180
+
181
+    /**
182
+     * Delete an app wide defined value
183
+     *
184
+     * @param string $appName the appName that we stored the value under
185
+     * @param string $key the key of the value, under which it was saved
186
+     */
187
+    public function deleteAppValue($appName, $key) {
188
+        \OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key);
189
+    }
190
+
191
+    /**
192
+     * Removes all keys in appconfig belonging to the app
193
+     *
194
+     * @param string $appName the appName the configs are stored under
195
+     */
196
+    public function deleteAppValues($appName) {
197
+        \OC::$server->query(\OC\AppConfig::class)->deleteApp($appName);
198
+    }
199
+
200
+
201
+    /**
202
+     * Set a user defined value
203
+     *
204
+     * @param string $userId the userId of the user that we want to store the value under
205
+     * @param string $appName the appName that we want to store the value under
206
+     * @param string $key the key under which the value is being stored
207
+     * @param string|float|int $value the value that you want to store
208
+     * @param string $preCondition only update if the config value was previously the value passed as $preCondition
209
+     * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
210
+     * @throws \UnexpectedValueException when trying to store an unexpected value
211
+     */
212
+    public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
213
+        if (!is_int($value) && !is_float($value) && !is_string($value)) {
214
+            throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
215
+        }
216
+
217
+        // TODO - FIXME
218
+        $this->fixDIInit();
219
+
220
+        $prevValue = $this->getUserValue($userId, $appName, $key, null);
221
+
222
+        if ($prevValue !== null) {
223
+            if ($prevValue === (string)$value) {
224
+                return;
225
+            } else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
226
+                throw new PreConditionNotMetException();
227
+            } else {
228
+                $qb = $this->connection->getQueryBuilder();
229
+                $qb->update('preferences')
230
+                    ->set('configvalue', $qb->createNamedParameter($value))
231
+                    ->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
232
+                    ->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
233
+                    ->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
234
+                $qb->execute();
235
+
236
+                $this->userCache[$userId][$appName][$key] = (string)$value;
237
+                return;
238
+            }
239
+        }
240
+
241
+        $preconditionArray = [];
242
+        if (isset($preCondition)) {
243
+            $preconditionArray = [
244
+                'configvalue' => $preCondition,
245
+            ];
246
+        }
247
+
248
+        $this->connection->setValues('preferences', [
249
+            'userid' => $userId,
250
+            'appid' => $appName,
251
+            'configkey' => $key,
252
+        ], [
253
+            'configvalue' => $value,
254
+        ], $preconditionArray);
255
+
256
+        // only add to the cache if we already loaded data for the user
257
+        if (isset($this->userCache[$userId])) {
258
+            if (!isset($this->userCache[$userId][$appName])) {
259
+                $this->userCache[$userId][$appName] = array();
260
+            }
261
+            $this->userCache[$userId][$appName][$key] = (string)$value;
262
+        }
263
+    }
264
+
265
+    /**
266
+     * Getting a user defined value
267
+     *
268
+     * @param string $userId the userId of the user that we want to store the value under
269
+     * @param string $appName the appName that we stored the value under
270
+     * @param string $key the key under which the value is being stored
271
+     * @param mixed $default the default value to be returned if the value isn't set
272
+     * @return string
273
+     */
274
+    public function getUserValue($userId, $appName, $key, $default = '') {
275
+        $data = $this->getUserValues($userId);
276
+        if (isset($data[$appName]) and isset($data[$appName][$key])) {
277
+            return $data[$appName][$key];
278
+        } else {
279
+            return $default;
280
+        }
281
+    }
282
+
283
+    /**
284
+     * Get the keys of all stored by an app for the user
285
+     *
286
+     * @param string $userId the userId of the user that we want to store the value under
287
+     * @param string $appName the appName that we stored the value under
288
+     * @return string[]
289
+     */
290
+    public function getUserKeys($userId, $appName) {
291
+        $data = $this->getUserValues($userId);
292
+        if (isset($data[$appName])) {
293
+            return array_keys($data[$appName]);
294
+        } else {
295
+            return array();
296
+        }
297
+    }
298
+
299
+    /**
300
+     * Delete a user value
301
+     *
302
+     * @param string $userId the userId of the user that we want to store the value under
303
+     * @param string $appName the appName that we stored the value under
304
+     * @param string $key the key under which the value is being stored
305
+     */
306
+    public function deleteUserValue($userId, $appName, $key) {
307
+        // TODO - FIXME
308
+        $this->fixDIInit();
309
+
310
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
311
+                'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
312
+        $this->connection->executeUpdate($sql, array($userId, $appName, $key));
313
+
314
+        if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
315
+            unset($this->userCache[$userId][$appName][$key]);
316
+        }
317
+    }
318
+
319
+    /**
320
+     * Delete all user values
321
+     *
322
+     * @param string $userId the userId of the user that we want to remove all values from
323
+     */
324
+    public function deleteAllUserValues($userId) {
325
+        // TODO - FIXME
326
+        $this->fixDIInit();
327
+
328
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
329
+            'WHERE `userid` = ?';
330
+        $this->connection->executeUpdate($sql, array($userId));
331
+
332
+        unset($this->userCache[$userId]);
333
+    }
334
+
335
+    /**
336
+     * Delete all user related values of one app
337
+     *
338
+     * @param string $appName the appName of the app that we want to remove all values from
339
+     */
340
+    public function deleteAppFromAllUsers($appName) {
341
+        // TODO - FIXME
342
+        $this->fixDIInit();
343
+
344
+        $sql  = 'DELETE FROM `*PREFIX*preferences` '.
345
+                'WHERE `appid` = ?';
346
+        $this->connection->executeUpdate($sql, array($appName));
347
+
348
+        foreach ($this->userCache as &$userCache) {
349
+            unset($userCache[$appName]);
350
+        }
351
+    }
352
+
353
+    /**
354
+     * Returns all user configs sorted by app of one user
355
+     *
356
+     * @param string $userId the user ID to get the app configs from
357
+     * @return array[] - 2 dimensional array with the following structure:
358
+     *     [ $appId =>
359
+     *         [ $key => $value ]
360
+     *     ]
361
+     */
362
+    private function getUserValues($userId) {
363
+        if (isset($this->userCache[$userId])) {
364
+            return $this->userCache[$userId];
365
+        }
366
+        if ($userId === null || $userId === '') {
367
+            $this->userCache[$userId]=array();
368
+            return $this->userCache[$userId];
369
+        }
370
+
371
+        // TODO - FIXME
372
+        $this->fixDIInit();
373
+
374
+        $data = array();
375
+        $query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
376
+        $result = $this->connection->executeQuery($query, array($userId));
377
+        while ($row = $result->fetch()) {
378
+            $appId = $row['appid'];
379
+            if (!isset($data[$appId])) {
380
+                $data[$appId] = array();
381
+            }
382
+            $data[$appId][$row['configkey']] = $row['configvalue'];
383
+        }
384
+        $this->userCache[$userId] = $data;
385
+        return $data;
386
+    }
387
+
388
+    /**
389
+     * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
390
+     *
391
+     * @param string $appName app to get the value for
392
+     * @param string $key the key to get the value for
393
+     * @param array $userIds the user IDs to fetch the values for
394
+     * @return array Mapped values: userId => value
395
+     */
396
+    public function getUserValueForUsers($appName, $key, $userIds) {
397
+        // TODO - FIXME
398
+        $this->fixDIInit();
399
+
400
+        if (empty($userIds) || !is_array($userIds)) {
401
+            return array();
402
+        }
403
+
404
+        $chunkedUsers = array_chunk($userIds, 50, true);
405
+        $placeholders50 = implode(',', array_fill(0, 50, '?'));
406
+
407
+        $userValues = array();
408
+        foreach ($chunkedUsers as $chunk) {
409
+            $queryParams = $chunk;
410
+            // create [$app, $key, $chunkedUsers]
411
+            array_unshift($queryParams, $key);
412
+            array_unshift($queryParams, $appName);
413
+
414
+            $placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
415
+
416
+            $query    = 'SELECT `userid`, `configvalue` ' .
417
+                        'FROM `*PREFIX*preferences` ' .
418
+                        'WHERE `appid` = ? AND `configkey` = ? ' .
419
+                        'AND `userid` IN (' . $placeholders . ')';
420
+            $result = $this->connection->executeQuery($query, $queryParams);
421
+
422
+            while ($row = $result->fetch()) {
423
+                $userValues[$row['userid']] = $row['configvalue'];
424
+            }
425
+        }
426
+
427
+        return $userValues;
428
+    }
429
+
430
+    /**
431
+     * Determines the users that have the given value set for a specific app-key-pair
432
+     *
433
+     * @param string $appName the app to get the user for
434
+     * @param string $key the key to get the user for
435
+     * @param string $value the value to get the user for
436
+     * @return array of user IDs
437
+     */
438
+    public function getUsersForUserValue($appName, $key, $value) {
439
+        // TODO - FIXME
440
+        $this->fixDIInit();
441
+
442
+        $sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
443
+                'WHERE `appid` = ? AND `configkey` = ? ';
444
+
445
+        if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
446
+            //oracle hack: need to explicitly cast CLOB to CHAR for comparison
447
+            $sql .= 'AND to_char(`configvalue`) = ?';
448
+        } else {
449
+            $sql .= 'AND `configvalue` = ?';
450
+        }
451
+
452
+        $result = $this->connection->executeQuery($sql, array($appName, $key, $value));
453
+
454
+        $userIDs = array();
455
+        while ($row = $result->fetch()) {
456
+            $userIDs[] = $row['userid'];
457
+        }
458
+
459
+        return $userIDs;
460
+    }
461
+
462
+    /**
463
+     * Determines the users that have the given value set for a specific app-key-pair
464
+     *
465
+     * @param string $appName the app to get the user for
466
+     * @param string $key the key to get the user for
467
+     * @param string $value the value to get the user for
468
+     * @return array of user IDs
469
+     */
470
+    public function getUsersForUserValueCaseInsensitive($appName, $key, $value) {
471
+        // TODO - FIXME
472
+        $this->fixDIInit();
473
+
474
+        $sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
475
+            'WHERE `appid` = ? AND `configkey` = ? ';
476
+
477
+        if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
478
+            //oracle hack: need to explicitly cast CLOB to CHAR for comparison
479
+            $sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)';
480
+        } else {
481
+            $sql .= 'AND LOWER(`configvalue`) = LOWER(?)';
482
+        }
483
+
484
+        $result = $this->connection->executeQuery($sql, array($appName, $key, $value));
485
+
486
+        $userIDs = array();
487
+        while ($row = $result->fetch()) {
488
+            $userIDs[] = $row['userid'];
489
+        }
490
+
491
+        return $userIDs;
492
+    }
493
+
494
+    public function getSystemConfig() {
495
+        return $this->systemConfig;
496
+    }
497 497
 }
Please login to merge, or discard this patch.
Spacing   +18 added lines, -18 removed lines patch added patch discarded remove patch
@@ -89,7 +89,7 @@  discard block
 block discarded – undo
89 89
 	 * because the database connection was created with an uninitialized config
90 90
 	 */
91 91
 	private function fixDIInit() {
92
-		if($this->connection === null) {
92
+		if ($this->connection === null) {
93 93
 			$this->connection = \OC::$server->getDatabaseConnection();
94 94
 		}
95 95
 	}
@@ -220,9 +220,9 @@  discard block
 block discarded – undo
220 220
 		$prevValue = $this->getUserValue($userId, $appName, $key, null);
221 221
 
222 222
 		if ($prevValue !== null) {
223
-			if ($prevValue === (string)$value) {
223
+			if ($prevValue === (string) $value) {
224 224
 				return;
225
-			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
225
+			} else if ($preCondition !== null && $prevValue !== (string) $preCondition) {
226 226
 				throw new PreConditionNotMetException();
227 227
 			} else {
228 228
 				$qb = $this->connection->getQueryBuilder();
@@ -233,7 +233,7 @@  discard block
 block discarded – undo
233 233
 					->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
234 234
 				$qb->execute();
235 235
 
236
-				$this->userCache[$userId][$appName][$key] = (string)$value;
236
+				$this->userCache[$userId][$appName][$key] = (string) $value;
237 237
 				return;
238 238
 			}
239 239
 		}
@@ -258,7 +258,7 @@  discard block
 block discarded – undo
258 258
 			if (!isset($this->userCache[$userId][$appName])) {
259 259
 				$this->userCache[$userId][$appName] = array();
260 260
 			}
261
-			$this->userCache[$userId][$appName][$key] = (string)$value;
261
+			$this->userCache[$userId][$appName][$key] = (string) $value;
262 262
 		}
263 263
 	}
264 264
 
@@ -307,7 +307,7 @@  discard block
 block discarded – undo
307 307
 		// TODO - FIXME
308 308
 		$this->fixDIInit();
309 309
 
310
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
310
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
311 311
 				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
312 312
 		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
313 313
 
@@ -325,7 +325,7 @@  discard block
 block discarded – undo
325 325
 		// TODO - FIXME
326 326
 		$this->fixDIInit();
327 327
 
328
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
328
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
329 329
 			'WHERE `userid` = ?';
330 330
 		$this->connection->executeUpdate($sql, array($userId));
331 331
 
@@ -341,7 +341,7 @@  discard block
 block discarded – undo
341 341
 		// TODO - FIXME
342 342
 		$this->fixDIInit();
343 343
 
344
-		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
344
+		$sql = 'DELETE FROM `*PREFIX*preferences` '.
345 345
 				'WHERE `appid` = ?';
346 346
 		$this->connection->executeUpdate($sql, array($appName));
347 347
 
@@ -364,7 +364,7 @@  discard block
 block discarded – undo
364 364
 			return $this->userCache[$userId];
365 365
 		}
366 366
 		if ($userId === null || $userId === '') {
367
-			$this->userCache[$userId]=array();
367
+			$this->userCache[$userId] = array();
368 368
 			return $this->userCache[$userId];
369 369
 		}
370 370
 
@@ -411,12 +411,12 @@  discard block
 block discarded – undo
411 411
 			array_unshift($queryParams, $key);
412 412
 			array_unshift($queryParams, $appName);
413 413
 
414
-			$placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
414
+			$placeholders = (count($chunk) === 50) ? $placeholders50 : implode(',', array_fill(0, count($chunk), '?'));
415 415
 
416
-			$query    = 'SELECT `userid`, `configvalue` ' .
417
-						'FROM `*PREFIX*preferences` ' .
418
-						'WHERE `appid` = ? AND `configkey` = ? ' .
419
-						'AND `userid` IN (' . $placeholders . ')';
416
+			$query = 'SELECT `userid`, `configvalue` '.
417
+						'FROM `*PREFIX*preferences` '.
418
+						'WHERE `appid` = ? AND `configkey` = ? '.
419
+						'AND `userid` IN ('.$placeholders.')';
420 420
 			$result = $this->connection->executeQuery($query, $queryParams);
421 421
 
422 422
 			while ($row = $result->fetch()) {
@@ -439,10 +439,10 @@  discard block
 block discarded – undo
439 439
 		// TODO - FIXME
440 440
 		$this->fixDIInit();
441 441
 
442
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
442
+		$sql = 'SELECT `userid` FROM `*PREFIX*preferences` '.
443 443
 				'WHERE `appid` = ? AND `configkey` = ? ';
444 444
 
445
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
445
+		if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
446 446
 			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
447 447
 			$sql .= 'AND to_char(`configvalue`) = ?';
448 448
 		} else {
@@ -471,10 +471,10 @@  discard block
 block discarded – undo
471 471
 		// TODO - FIXME
472 472
 		$this->fixDIInit();
473 473
 
474
-		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
474
+		$sql = 'SELECT `userid` FROM `*PREFIX*preferences` '.
475 475
 			'WHERE `appid` = ? AND `configkey` = ? ';
476 476
 
477
-		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
477
+		if ($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
478 478
 			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
479 479
 			$sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)';
480 480
 		} else {
Please login to merge, or discard this patch.