Passed
Push — master ( 7c68e0...2cc411 )
by Joas
11:56
created

AllConfig::getSystemValueBool()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 2
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 1
nc 1
nop 2
dl 0
loc 2
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * @copyright Copyright (c) 2016, ownCloud, Inc.
4
 *
5
 * @author Bart Visscher <[email protected]>
6
 * @author Joas Schilling <[email protected]>
7
 * @author Jörn Friedrich Dreyer <[email protected]>
8
 * @author Loki3000 <[email protected]>
9
 * @author Lukas Reschke <[email protected]>
10
 * @author Morris Jobke <[email protected]>
11
 * @author Robin Appelman <[email protected]>
12
 * @author Robin McCorkell <[email protected]>
13
 * @author Roeland Jago Douma <[email protected]>
14
 * @author Thomas Müller <[email protected]>
15
 * @author Vincent Petry <[email protected]>
16
 *
17
 * @license AGPL-3.0
18
 *
19
 * This code is free software: you can redistribute it and/or modify
20
 * it under the terms of the GNU Affero General Public License, version 3,
21
 * as published by the Free Software Foundation.
22
 *
23
 * This program is distributed in the hope that it will be useful,
24
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
25
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26
 * GNU Affero General Public License for more details.
27
 *
28
 * You should have received a copy of the GNU Affero General Public License, version 3,
29
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
30
 *
31
 */
32
33
namespace OC;
34
use OC\Cache\CappedMemoryCache;
35
use OCP\IDBConnection;
36
use OCP\PreConditionNotMetException;
37
38
/**
39
 * Class to combine all the configuration options ownCloud offers
40
 */
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 boolean system wide defined value
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
	 * @since 16.0.0
135
	 */
136
	public function getSystemValueBool(string $key, bool $default = false): bool {
137
		return (bool) $this->getSystemValue($key, $default);
138
	}
139
140
	/**
141
	 * Looks up an integer system wide defined value
142
	 *
143
	 * @param string $key the key of the value, under which it was saved
144
	 * @param mixed $default the default value to be returned if the value isn't set
145
	 * @return mixed the value or $default
146
	 * @since 16.0.0
147
	 */
148
	public function getSystemValueInt(string $key, int $default = 0): int {
149
		return (int) $this->getSystemValue($key, $default);
150
	}
151
152
	/**
153
	 * Looks up a string system wide defined value
154
	 *
155
	 * @param string $key the key of the value, under which it was saved
156
	 * @param mixed $default the default value to be returned if the value isn't set
157
	 * @return mixed the value or $default
158
	 * @since 16.0.0
159
	 */
160
	public function getSystemValueString(string $key, string $default = ''): string {
161
		return (string) $this->getSystemValue($key, $default);
162
	}
163
164
	/**
165
	 * Looks up a system wide defined value and filters out sensitive data
166
	 *
167
	 * @param string $key the key of the value, under which it was saved
168
	 * @param mixed $default the default value to be returned if the value isn't set
169
	 * @return mixed the value or $default
170
	 */
171
	public function getFilteredSystemValue($key, $default = '') {
172
		return $this->systemConfig->getFilteredValue($key, $default);
173
	}
174
175
	/**
176
	 * Delete a system wide defined value
177
	 *
178
	 * @param string $key the key of the value, under which it was saved
179
	 */
180
	public function deleteSystemValue($key) {
181
		$this->systemConfig->deleteValue($key);
182
	}
183
184
	/**
185
	 * Get all keys stored for an app
186
	 *
187
	 * @param string $appName the appName that we stored the value under
188
	 * @return string[] the keys stored for the app
189
	 */
190
	public function getAppKeys($appName) {
191
		return \OC::$server->query(\OC\AppConfig::class)->getKeys($appName);
192
	}
193
194
	/**
195
	 * Writes a new app wide value
196
	 *
197
	 * @param string $appName the appName that we want to store the value under
198
	 * @param string $key the key of the value, under which will be saved
199
	 * @param string|float|int $value the value that should be stored
200
	 */
201
	public function setAppValue($appName, $key, $value) {
202
		\OC::$server->query(\OC\AppConfig::class)->setValue($appName, $key, $value);
203
	}
204
205
	/**
206
	 * Looks up an app wide defined value
207
	 *
208
	 * @param string $appName the appName that we stored the value under
209
	 * @param string $key the key of the value, under which it was saved
210
	 * @param string $default the default value to be returned if the value isn't set
211
	 * @return string the saved value
212
	 */
213
	public function getAppValue($appName, $key, $default = '') {
214
		return \OC::$server->query(\OC\AppConfig::class)->getValue($appName, $key, $default);
215
	}
216
217
	/**
218
	 * Delete an app wide defined value
219
	 *
220
	 * @param string $appName the appName that we stored the value under
221
	 * @param string $key the key of the value, under which it was saved
222
	 */
223
	public function deleteAppValue($appName, $key) {
224
		\OC::$server->query(\OC\AppConfig::class)->deleteKey($appName, $key);
225
	}
226
227
	/**
228
	 * Removes all keys in appconfig belonging to the app
229
	 *
230
	 * @param string $appName the appName the configs are stored under
231
	 */
232
	public function deleteAppValues($appName) {
233
		\OC::$server->query(\OC\AppConfig::class)->deleteApp($appName);
234
	}
235
236
237
	/**
238
	 * Set a user defined value
239
	 *
240
	 * @param string $userId the userId of the user that we want to store the value under
241
	 * @param string $appName the appName that we want to store the value under
242
	 * @param string $key the key under which the value is being stored
243
	 * @param string|float|int $value the value that you want to store
244
	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
245
	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
246
	 * @throws \UnexpectedValueException when trying to store an unexpected value
247
	 */
248
	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
249
		if (!is_int($value) && !is_float($value) && !is_string($value)) {
0 ignored issues
show
introduced by
The condition is_string($value) is always true.
Loading history...
250
			throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
251
		}
252
253
		// TODO - FIXME
254
		$this->fixDIInit();
255
256
		$prevValue = $this->getUserValue($userId, $appName, $key, null);
257
258
		if ($prevValue !== null) {
0 ignored issues
show
introduced by
The condition $prevValue !== null is always true.
Loading history...
259
			if ($prevValue === (string)$value) {
260
				return;
261
			} else if ($preCondition !== null && $prevValue !== (string)$preCondition) {
262
				throw new PreConditionNotMetException();
263
			} else {
264
				$qb = $this->connection->getQueryBuilder();
265
				$qb->update('preferences')
266
					->set('configvalue', $qb->createNamedParameter($value))
267
					->where($qb->expr()->eq('userid', $qb->createNamedParameter($userId)))
268
					->andWhere($qb->expr()->eq('appid', $qb->createNamedParameter($appName)))
269
					->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
270
				$qb->execute();
271
272
				$this->userCache[$userId][$appName][$key] = (string)$value;
273
				return;
274
			}
275
		}
276
277
		$preconditionArray = [];
278
		if (isset($preCondition)) {
279
			$preconditionArray = [
280
				'configvalue' => $preCondition,
281
			];
282
		}
283
284
		$this->connection->setValues('preferences', [
285
			'userid' => $userId,
286
			'appid' => $appName,
287
			'configkey' => $key,
288
		], [
289
			'configvalue' => $value,
290
		], $preconditionArray);
291
292
		// only add to the cache if we already loaded data for the user
293
		if (isset($this->userCache[$userId])) {
294
			if (!isset($this->userCache[$userId][$appName])) {
295
				$this->userCache[$userId][$appName] = array();
296
			}
297
			$this->userCache[$userId][$appName][$key] = (string)$value;
298
		}
299
	}
300
301
	/**
302
	 * Getting a user defined value
303
	 *
304
	 * @param string $userId the userId of the user that we want to store the value under
305
	 * @param string $appName the appName that we stored the value under
306
	 * @param string $key the key under which the value is being stored
307
	 * @param mixed $default the default value to be returned if the value isn't set
308
	 * @return string
309
	 */
310
	public function getUserValue($userId, $appName, $key, $default = '') {
311
		$data = $this->getUserValues($userId);
312
		if (isset($data[$appName]) and isset($data[$appName][$key])) {
313
			return $data[$appName][$key];
314
		} else {
315
			return $default;
316
		}
317
	}
318
319
	/**
320
	 * Get the keys of all stored by an app for the user
321
	 *
322
	 * @param string $userId the userId of the user that we want to store the value under
323
	 * @param string $appName the appName that we stored the value under
324
	 * @return string[]
325
	 */
326
	public function getUserKeys($userId, $appName) {
327
		$data = $this->getUserValues($userId);
328
		if (isset($data[$appName])) {
329
			return array_keys($data[$appName]);
330
		} else {
331
			return array();
332
		}
333
	}
334
335
	/**
336
	 * Delete a user value
337
	 *
338
	 * @param string $userId the userId of the user that we want to store the value under
339
	 * @param string $appName the appName that we stored the value under
340
	 * @param string $key the key under which the value is being stored
341
	 */
342
	public function deleteUserValue($userId, $appName, $key) {
343
		// TODO - FIXME
344
		$this->fixDIInit();
345
346
		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
347
				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
348
		$this->connection->executeUpdate($sql, array($userId, $appName, $key));
349
350
		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
351
			unset($this->userCache[$userId][$appName][$key]);
352
		}
353
	}
354
355
	/**
356
	 * Delete all user values
357
	 *
358
	 * @param string $userId the userId of the user that we want to remove all values from
359
	 */
360
	public function deleteAllUserValues($userId) {
361
		// TODO - FIXME
362
		$this->fixDIInit();
363
364
		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
365
			'WHERE `userid` = ?';
366
		$this->connection->executeUpdate($sql, array($userId));
367
368
		unset($this->userCache[$userId]);
369
	}
370
371
	/**
372
	 * Delete all user related values of one app
373
	 *
374
	 * @param string $appName the appName of the app that we want to remove all values from
375
	 */
376
	public function deleteAppFromAllUsers($appName) {
377
		// TODO - FIXME
378
		$this->fixDIInit();
379
380
		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
381
				'WHERE `appid` = ?';
382
		$this->connection->executeUpdate($sql, array($appName));
383
384
		foreach ($this->userCache as &$userCache) {
385
			unset($userCache[$appName]);
386
		}
387
	}
388
389
	/**
390
	 * Returns all user configs sorted by app of one user
391
	 *
392
	 * @param string $userId the user ID to get the app configs from
393
	 * @return array[] - 2 dimensional array with the following structure:
394
	 *     [ $appId =>
395
	 *         [ $key => $value ]
396
	 *     ]
397
	 */
398
	private function getUserValues($userId) {
399
		if (isset($this->userCache[$userId])) {
400
			return $this->userCache[$userId];
401
		}
402
		if ($userId === null || $userId === '') {
403
			$this->userCache[$userId]=array();
404
			return $this->userCache[$userId];
405
		}
406
407
		// TODO - FIXME
408
		$this->fixDIInit();
409
410
		$data = array();
411
		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
412
		$result = $this->connection->executeQuery($query, array($userId));
413
		while ($row = $result->fetch()) {
414
			$appId = $row['appid'];
415
			if (!isset($data[$appId])) {
416
				$data[$appId] = array();
417
			}
418
			$data[$appId][$row['configkey']] = $row['configvalue'];
419
		}
420
		$this->userCache[$userId] = $data;
421
		return $data;
422
	}
423
424
	/**
425
	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
426
	 *
427
	 * @param string $appName app to get the value for
428
	 * @param string $key the key to get the value for
429
	 * @param array $userIds the user IDs to fetch the values for
430
	 * @return array Mapped values: userId => value
431
	 */
432
	public function getUserValueForUsers($appName, $key, $userIds) {
433
		// TODO - FIXME
434
		$this->fixDIInit();
435
436
		if (empty($userIds) || !is_array($userIds)) {
437
			return array();
438
		}
439
440
		$chunkedUsers = array_chunk($userIds, 50, true);
441
		$placeholders50 = implode(',', array_fill(0, 50, '?'));
442
443
		$userValues = array();
444
		foreach ($chunkedUsers as $chunk) {
445
			$queryParams = $chunk;
446
			// create [$app, $key, $chunkedUsers]
447
			array_unshift($queryParams, $key);
448
			array_unshift($queryParams, $appName);
449
450
			$placeholders = (count($chunk) === 50) ? $placeholders50 :  implode(',', array_fill(0, count($chunk), '?'));
451
452
			$query    = 'SELECT `userid`, `configvalue` ' .
453
						'FROM `*PREFIX*preferences` ' .
454
						'WHERE `appid` = ? AND `configkey` = ? ' .
455
						'AND `userid` IN (' . $placeholders . ')';
456
			$result = $this->connection->executeQuery($query, $queryParams);
457
458
			while ($row = $result->fetch()) {
459
				$userValues[$row['userid']] = $row['configvalue'];
460
			}
461
		}
462
463
		return $userValues;
464
	}
465
466
	/**
467
	 * Determines the users that have the given value set for a specific app-key-pair
468
	 *
469
	 * @param string $appName the app to get the user for
470
	 * @param string $key the key to get the user for
471
	 * @param string $value the value to get the user for
472
	 * @return array of user IDs
473
	 */
474
	public function getUsersForUserValue($appName, $key, $value) {
475
		// TODO - FIXME
476
		$this->fixDIInit();
477
478
		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
479
				'WHERE `appid` = ? AND `configkey` = ? ';
480
481
		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
482
			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
483
			$sql .= 'AND to_char(`configvalue`) = ?';
484
		} else {
485
			$sql .= 'AND `configvalue` = ?';
486
		}
487
488
		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
489
490
		$userIDs = array();
491
		while ($row = $result->fetch()) {
492
			$userIDs[] = $row['userid'];
493
		}
494
495
		return $userIDs;
496
	}
497
498
	/**
499
	 * Determines the users that have the given value set for a specific app-key-pair
500
	 *
501
	 * @param string $appName the app to get the user for
502
	 * @param string $key the key to get the user for
503
	 * @param string $value the value to get the user for
504
	 * @return array of user IDs
505
	 */
506
	public function getUsersForUserValueCaseInsensitive($appName, $key, $value) {
507
		// TODO - FIXME
508
		$this->fixDIInit();
509
510
		$sql  = 'SELECT `userid` FROM `*PREFIX*preferences` ' .
511
			'WHERE `appid` = ? AND `configkey` = ? ';
512
513
		if($this->getSystemValue('dbtype', 'sqlite') === 'oci') {
514
			//oracle hack: need to explicitly cast CLOB to CHAR for comparison
515
			$sql .= 'AND LOWER(to_char(`configvalue`)) = LOWER(?)';
516
		} else {
517
			$sql .= 'AND LOWER(`configvalue`) = LOWER(?)';
518
		}
519
520
		$result = $this->connection->executeQuery($sql, array($appName, $key, $value));
521
522
		$userIDs = array();
523
		while ($row = $result->fetch()) {
524
			$userIDs[] = $row['userid'];
525
		}
526
527
		return $userIDs;
528
	}
529
530
	public function getSystemConfig() {
531
		return $this->systemConfig;
532
	}
533
}
534