Completed
Push — master ( 00968e...9fe34e )
by Thomas
08:07
created

AllConfig::getUsersForUserValue()   B

Complexity

Conditions 3
Paths 4

Size

Total Lines 38
Code Lines 23

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 23
nc 4
nop 3
dl 0
loc 38
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/**
3
 * @author Bart Visscher <[email protected]>
4
 * @author Joas Schilling <[email protected]>
5
 * @author Jörn Friedrich Dreyer <[email protected]>
6
 * @author Lukas Reschke <[email protected]>
7
 * @author Morris Jobke <[email protected]>
8
 * @author Robin Appelman <[email protected]>
9
 * @author Robin McCorkell <[email protected]>
10
 * @author Thomas Müller <[email protected]>
11
 * @author Vincent Petry <[email protected]>
12
 *
13
 * @copyright Copyright (c) 2016, ownCloud GmbH.
14
 * @license AGPL-3.0
15
 *
16
 * This code is free software: you can redistribute it and/or modify
17
 * it under the terms of the GNU Affero General Public License, version 3,
18
 * as published by the Free Software Foundation.
19
 *
20
 * This program is distributed in the hope that it will be useful,
21
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23
 * GNU Affero General Public License for more details.
24
 *
25
 * You should have received a copy of the GNU Affero General Public License, version 3,
26
 * along with this program.  If not, see <http://www.gnu.org/licenses/>
27
 *
28
 */
29
30
namespace OC;
31
use Doctrine\DBAL\Platforms\OraclePlatform;
32
use OC\Cache\CappedMemoryCache;
33
use OCP\IDBConnection;
34
use OCP\PreConditionNotMetException;
35
36
/**
37
 * Class to combine all the configuration options ownCloud offers
38
 */
39
class AllConfig implements \OCP\IConfig {
40
	/** @var SystemConfig */
41
	private $systemConfig;
42
43
	/** @var IDBConnection */
44
	private $connection;
45
46
	/**
47
	 * 3 dimensional array with the following structure:
48
	 * [ $userId =>
49
	 *     [ $appId =>
50
	 *         [ $key => $value ]
51
	 *     ]
52
	 * ]
53
	 *
54
	 * database table: preferences
55
	 *
56
	 * methods that use this:
57
	 *   - setUserValue
58
	 *   - getUserValue
59
	 *   - getUserKeys
60
	 *   - deleteUserValue
61
	 *   - deleteAllUserValues
62
	 *   - deleteAppFromAllUsers
63
	 *
64
	 * @var CappedMemoryCache $userCache
65
	 */
66
	private $userCache;
67
68
	/**
69
	 * @param SystemConfig $systemConfig
70
	 */
71
	function __construct(SystemConfig $systemConfig) {
72
		$this->userCache = new CappedMemoryCache();
73
		$this->systemConfig = $systemConfig;
74
	}
75
76
	/**
77
	 * TODO - FIXME This fixes an issue with base.php that cause cyclic
78
	 * dependencies, especially with autoconfig setup
79
	 *
80
	 * Replace this by properly injected database connection. Currently the
81
	 * base.php triggers the getDatabaseConnection too early which causes in
82
	 * autoconfig setup case a too early distributed database connection and
83
	 * the autoconfig then needs to reinit all already initialized dependencies
84
	 * that use the database connection.
85
	 *
86
	 * otherwise a SQLite database is created in the wrong directory
87
	 * because the database connection was created with an uninitialized config
88
	 */
89
	private function fixDIInit() {
90
		if($this->connection === null) {
91
			$this->connection = \OC::$server->getDatabaseConnection();
92
		}
93
	}
94
95
	/**
96
	 * Sets and deletes system wide values
97
	 *
98
	 * @param array $configs Associative array with `key => value` pairs
99
	 *                       If value is null, the config key will be deleted
100
	 */
101
	public function setSystemValues(array $configs) {
102
		$this->systemConfig->setValues($configs);
103
	}
104
105
	/**
106
	 * Sets a new system wide value
107
	 *
108
	 * @param string $key the key of the value, under which will be saved
109
	 * @param mixed $value the value that should be stored
110
	 */
111
	public function setSystemValue($key, $value) {
112
		$this->systemConfig->setValue($key, $value);
113
	}
114
115
	/**
116
	 * Looks up a system wide defined value
117
	 *
118
	 * @param string $key the key of the value, under which it was saved
119
	 * @param mixed $default the default value to be returned if the value isn't set
120
	 * @return mixed the value or $default
121
	 */
122
	public function getSystemValue($key, $default = '') {
123
		return $this->systemConfig->getValue($key, $default);
124
	}
125
126
	/**
127
	 * Looks up a system wide defined value and filters out sensitive data
128
	 *
129
	 * @param string $key the key of the value, under which it was saved
130
	 * @param mixed $default the default value to be returned if the value isn't set
131
	 * @return mixed the value or $default
132
	 */
133
	public function getFilteredSystemValue($key, $default = '') {
134
		return $this->systemConfig->getFilteredValue($key, $default);
135
	}
136
137
	/**
138
	 * Delete a system wide defined value
139
	 *
140
	 * @param string $key the key of the value, under which it was saved
141
	 */
142
	public function deleteSystemValue($key) {
143
		$this->systemConfig->deleteValue($key);
144
	}
145
146
	/**
147
	 * Get all keys stored for an app
148
	 *
149
	 * @param string $appName the appName that we stored the value under
150
	 * @return string[] the keys stored for the app
151
	 */
152
	public function getAppKeys($appName) {
153
		return \OC::$server->getAppConfig()->getKeys($appName);
154
	}
155
156
	/**
157
	 * Writes a new app wide value
158
	 *
159
	 * @param string $appName the appName that we want to store the value under
160
	 * @param string $key the key of the value, under which will be saved
161
	 * @param string|float|int $value the value that should be stored
162
	 */
163
	public function setAppValue($appName, $key, $value) {
164
		\OC::$server->getAppConfig()->setValue($appName, $key, $value);
165
	}
166
167
	/**
168
	 * Looks up an app wide defined value
169
	 *
170
	 * @param string $appName the appName that we stored the value under
171
	 * @param string $key the key of the value, under which it was saved
172
	 * @param string $default the default value to be returned if the value isn't set
173
	 * @return string the saved value
174
	 */
175
	public function getAppValue($appName, $key, $default = '') {
176
		return \OC::$server->getAppConfig()->getValue($appName, $key, $default);
177
	}
178
179
	/**
180
	 * Delete an app wide defined value
181
	 *
182
	 * @param string $appName the appName that we stored the value under
183
	 * @param string $key the key of the value, under which it was saved
184
	 */
185
	public function deleteAppValue($appName, $key) {
186
		\OC::$server->getAppConfig()->deleteKey($appName, $key);
187
	}
188
189
	/**
190
	 * Removes all keys in appconfig belonging to the app
191
	 *
192
	 * @param string $appName the appName the configs are stored under
193
	 */
194
	public function deleteAppValues($appName) {
195
		\OC::$server->getAppConfig()->deleteApp($appName);
196
	}
197
198
199
	/**
200
	 * Set a user defined value
201
	 *
202
	 * @param string $userId the userId of the user that we want to store the value under
203
	 * @param string $appName the appName that we want to store the value under
204
	 * @param string $key the key under which the value is being stored
205
	 * @param string|float|int $value the value that you want to store
206
	 * @param string $preCondition only update if the config value was previously the value passed as $preCondition
207
	 * @throws \OCP\PreConditionNotMetException if a precondition is specified and is not met
208
	 * @throws \UnexpectedValueException when trying to store an unexpected value
209
	 */
210
	public function setUserValue($userId, $appName, $key, $value, $preCondition = null) {
211
		if (!is_int($value) && !is_float($value) && !is_string($value)) {
212
			throw new \UnexpectedValueException('Only integers, floats and strings are allowed as value');
213
		}
214
215
		// TODO - FIXME
216
		$this->fixDIInit();
217
218
		$preconditionArray = [];
219
		if (isset($preCondition)) {
220
			$preconditionArray = [
221
				'configvalue' => $preCondition,
222
			];
223
		}
224
225
		$this->connection->setValues('preferences', [
226
			'userid' => $userId,
227
			'appid' => $appName,
228
			'configkey' => $key,
229
		], [
230
			'configvalue' => $value,
231
		], $preconditionArray);
232
233
		// only add to the cache if we already loaded data for the user
234
		if (isset($this->userCache[$userId])) {
235
			if (!isset($this->userCache[$userId][$appName])) {
236
				$this->userCache[$userId][$appName] = [];
237
			}
238
			$this->userCache[$userId][$appName][$key] = $value;
239
		}
240
	}
241
242
	/**
243
	 * Getting a user defined value
244
	 *
245
	 * @param string $userId the userId of the user that we want to store the value under
246
	 * @param string $appName the appName that we stored the value under
247
	 * @param string $key the key under which the value is being stored
248
	 * @param mixed $default the default value to be returned if the value isn't set
249
	 * @return string
250
	 */
251
	public function getUserValue($userId, $appName, $key, $default = '') {
252
		$data = $this->getUserValues($userId);
253
		if (isset($data[$appName]) and isset($data[$appName][$key])) {
254
			return $data[$appName][$key];
255
		} else {
256
			return $default;
257
		}
258
	}
259
260
	/**
261
	 * Get the keys of all stored by an app for the user
262
	 *
263
	 * @param string $userId the userId of the user that we want to store the value under
264
	 * @param string $appName the appName that we stored the value under
265
	 * @return string[]
266
	 */
267
	public function getUserKeys($userId, $appName) {
268
		$data = $this->getUserValues($userId);
269
		if (isset($data[$appName])) {
270
			return array_keys($data[$appName]);
271
		} else {
272
			return [];
273
		}
274
	}
275
276
	/**
277
	 * Delete a user value
278
	 *
279
	 * @param string $userId the userId of the user that we want to store the value under
280
	 * @param string $appName the appName that we stored the value under
281
	 * @param string $key the key under which the value is being stored
282
	 */
283
	public function deleteUserValue($userId, $appName, $key) {
284
		// TODO - FIXME
285
		$this->fixDIInit();
286
287
		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
288
				'WHERE `userid` = ? AND `appid` = ? AND `configkey` = ?';
289
		$this->connection->executeUpdate($sql, [$userId, $appName, $key]);
290
291
		if (isset($this->userCache[$userId]) and isset($this->userCache[$userId][$appName])) {
292
			unset($this->userCache[$userId][$appName][$key]);
293
		}
294
	}
295
296
	/**
297
	 * Delete all user values
298
	 *
299
	 * @param string $userId the userId of the user that we want to remove all values from
300
	 */
301
	public function deleteAllUserValues($userId) {
302
		// TODO - FIXME
303
		$this->fixDIInit();
304
305
		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
306
			'WHERE `userid` = ?';
307
		$this->connection->executeUpdate($sql, [$userId]);
308
309
		unset($this->userCache[$userId]);
310
	}
311
312
	/**
313
	 * Delete all user related values of one app
314
	 *
315
	 * @param string $appName the appName of the app that we want to remove all values from
316
	 */
317
	public function deleteAppFromAllUsers($appName) {
318
		// TODO - FIXME
319
		$this->fixDIInit();
320
321
		$sql  = 'DELETE FROM `*PREFIX*preferences` '.
322
				'WHERE `appid` = ?';
323
		$this->connection->executeUpdate($sql, [$appName]);
324
325
		foreach ($this->userCache as &$userCache) {
0 ignored issues
show
Bug introduced by
The expression $this->userCache of type object<OC\Cache\CappedMemoryCache> is not traversable.
Loading history...
326
			unset($userCache[$appName]);
327
		}
328
	}
329
330
	/**
331
	 * Returns all user configs sorted by app of one user
332
	 *
333
	 * @param string $userId the user ID to get the app configs from
334
	 * @return array[] - 2 dimensional array with the following structure:
335
	 *     [ $appId =>
336
	 *         [ $key => $value ]
337
	 *     ]
338
	 */
339
	private function getUserValues($userId) {
340
		// TODO - FIXME
341
		$this->fixDIInit();
342
343
		if (isset($this->userCache[$userId])) {
344
			return $this->userCache[$userId];
345
		}
346
		$data = [];
347
		$query = 'SELECT `appid`, `configkey`, `configvalue` FROM `*PREFIX*preferences` WHERE `userid` = ?';
348
		$result = $this->connection->executeQuery($query, [$userId]);
349
		while ($row = $result->fetch()) {
350
			$appId = $row['appid'];
351
			if (!isset($data[$appId])) {
352
				$data[$appId] = [];
353
			}
354
			$data[$appId][$row['configkey']] = $row['configvalue'];
355
		}
356
		$this->userCache[$userId] = $data;
357
		return $data;
358
	}
359
360
	/**
361
	 * Fetches a mapped list of userId -> value, for a specified app and key and a list of user IDs.
362
	 *
363
	 * @param string $appName app to get the value for
364
	 * @param string $key the key to get the value for
365
	 * @param array $userIds the user IDs to fetch the values for
366
	 * @return array Mapped values: userId => value
367
	 */
368
	public function getUserValueForUsers($appName, $key, $userIds) {
369
		// TODO - FIXME
370
		$this->fixDIInit();
371
372
		if (empty($userIds) || !is_array($userIds)) {
373
			return [];
374
		}
375
376
		$chunkedUsers = array_chunk($userIds, 50, true);
377
		$placeholders50 = implode(',', array_fill(0, 50, '?'));
378
379
		$userValues = [];
380
		foreach ($chunkedUsers as $chunk) {
381
			$queryParams = $chunk;
382
			// create [$app, $key, $chunkedUsers]
383
			array_unshift($queryParams, $key);
384
			array_unshift($queryParams, $appName);
385
386
			$placeholders = (sizeof($chunk) == 50) ? $placeholders50 :  implode(',', array_fill(0, sizeof($chunk), '?'));
387
388
			$query    = 'SELECT `userid`, `configvalue` ' .
389
						'FROM `*PREFIX*preferences` ' .
390
						'WHERE `appid` = ? AND `configkey` = ? ' .
391
						'AND `userid` IN (' . $placeholders . ')';
392
			$result = $this->connection->executeQuery($query, $queryParams);
393
394
			while ($row = $result->fetch()) {
395
				$userValues[$row['userid']] = $row['configvalue'];
396
			}
397
		}
398
399
		return $userValues;
400
	}
401
402
	/**
403
	 * Determines the users that have the given value set for a specific app-key-pair
404
	 *
405
	 * @param string $appName the app to get the user for
406
	 * @param string $key the key to get the user for
407
	 * @param string $value the value to get the user for
408
	 * @return array of user IDs
409
	 */
410
	public function getUsersForUserValue($appName, $key, $value) {
411
		// TODO - FIXME
412
		$this->fixDIInit();
413
414
		$queryBuilder = $this->connection->getQueryBuilder();
415
		$queryBuilder->select('userid')
416
			->from('preferences')
417
			->where($queryBuilder->expr()->eq(
418
				'appid', $queryBuilder->createNamedParameter($appName))
419
			)
420
			->andWhere($queryBuilder->expr()->eq(
421
				'configkey', $queryBuilder->createNamedParameter($key))
422
			)
423
			->andWhere($queryBuilder->expr()->isNotNull('configvalue'));
424
425
426
		if ($this->connection->getDatabasePlatform() instanceof OraclePlatform) {
427
			//oracle can only compare the first 4000 bytes of a CLOB column
428
			$queryBuilder->andWhere($queryBuilder->expr()->eq(
429
				$queryBuilder->createFunction('dbms_lob.substr(`configvalue`, 4000, 1)'),
430
				$queryBuilder->createNamedParameter($value))
431
			);
432
		} else {
433
			$queryBuilder->andWhere($queryBuilder->expr()->eq(
434
				'configvalue', $queryBuilder->createNamedParameter($value))
435
			);
436
		}
437
		$query = $queryBuilder->execute();
438
439
		$userIDs = [];
440
		while ($row = $query->fetch()) {
441
			$userIDs[] = $row['userid'];
442
		}
443
444
		$query->closeCursor();
445
446
		return $userIDs;
447
	}
448
}
449