-
-
Notifications
You must be signed in to change notification settings - Fork 4.8k
Expand file tree
/
Copy pathUserConfig.php
More file actions
2094 lines (1897 loc) · 65.4 KB
/
UserConfig.php
File metadata and controls
2094 lines (1897 loc) · 65.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
declare(strict_types=1);
/**
* SPDX-FileCopyrightText: 2024 Nextcloud GmbH and Nextcloud contributors
* SPDX-License-Identifier: AGPL-3.0-or-later
*/
namespace OC\Config;
use Generator;
use InvalidArgumentException;
use JsonException;
use OC\AppFramework\Bootstrap\Coordinator;
use OCP\Config\Exceptions\IncorrectTypeException;
use OCP\Config\Exceptions\TypeConflictException;
use OCP\Config\Exceptions\UnknownKeyException;
use OCP\Config\IUserConfig;
use OCP\Config\Lexicon\Entry;
use OCP\Config\Lexicon\ILexicon;
use OCP\Config\Lexicon\Strictness;
use OCP\Config\ValueType;
use OCP\DB\Exception as DBException;
use OCP\DB\IResult;
use OCP\DB\QueryBuilder\IQueryBuilder;
use OCP\EventDispatcher\IEventDispatcher;
use OCP\IConfig;
use OCP\IDBConnection;
use OCP\Security\ICrypto;
use OCP\User\Events\UserConfigChangedEvent;
use Psr\Log\LoggerInterface;
/**
* This class provides an easy way for apps to store user config in the
* database.
* Supports **lazy loading**
*
* ### What is lazy loading ?
* In order to avoid loading useless user config into memory for each request,
* only non-lazy values are now loaded.
*
* Once a value that is lazy is requested, all lazy values will be loaded.
*
* Similarly, some methods from this class are marked with a warning about ignoring
* lazy loading. Use them wisely and only on parts of the code that are called
* during specific requests or actions to avoid loading the lazy values all the time.
*
* @since 31.0.0
*/
class UserConfig implements IUserConfig {
private const USER_MAX_LENGTH = 64;
private const APP_MAX_LENGTH = 32;
private const KEY_MAX_LENGTH = 64;
private const INDEX_MAX_LENGTH = 64;
private const ENCRYPTION_PREFIX = '$UserConfigEncryption$';
private const ENCRYPTION_PREFIX_LENGTH = 22; // strlen(self::ENCRYPTION_PREFIX)
/** @var array<string, array<string, array<string, mixed>>> [ass'user_id' => ['app_id' => ['key' => 'value']]] */
private array $fastCache = []; // cache for normal config keys
/** @var array<string, array<string, array<string, mixed>>> ['user_id' => ['app_id' => ['key' => 'value']]] */
private array $lazyCache = []; // cache for lazy config keys
/** @var array<string, array<string, array<string, array<string, mixed>>>> ['user_id' => ['app_id' => ['key' => ['type' => ValueType, 'flags' => bitflag]]]] */
private array $valueDetails = []; // type for all config values
/** @var array<string, boolean> ['user_id' => bool] */
private array $fastLoaded = [];
/** @var array<string, boolean> ['user_id' => bool] */
private array $lazyLoaded = [];
/** @var array<string, array{entries: array<string, Entry>, aliases: array<string, string>, strictness: Strictness}> ['app_id' => ['strictness' => ConfigLexiconStrictness, 'entries' => ['config_key' => ConfigLexiconEntry[]]] */
private array $configLexiconDetails = [];
private bool $ignoreLexiconAliases = false;
private array $strictnessApplied = [];
public function __construct(
protected IDBConnection $connection,
protected IConfig $config,
private readonly ConfigManager $configManager,
private readonly PresetManager $presetManager,
protected LoggerInterface $logger,
protected ICrypto $crypto,
protected IEventDispatcher $dispatcher,
) {
}
/**
* @inheritDoc
*
* @param string $appId optional id of app
*
* @return list<string> list of userIds
* @since 31.0.0
*/
public function getUserIds(string $appId = ''): array {
$this->assertParams(app: $appId, allowEmptyUser: true, allowEmptyApp: true);
$qb = $this->connection->getQueryBuilder();
$qb->from('preferences');
$qb->select('userid');
$qb->groupBy('userid');
if ($appId !== '') {
$qb->where($qb->expr()->eq('appid', $qb->createNamedParameter($appId)));
}
$result = $qb->executeQuery();
$rows = $result->fetchAll();
$userIds = [];
foreach ($rows as $row) {
$userIds[] = $row['userid'];
}
return $userIds;
}
/**
* @inheritDoc
*
* @return list<string> list of app ids
* @since 31.0.0
*/
public function getApps(string $userId): array {
$this->assertParams($userId, allowEmptyApp: true);
$this->loadConfigAll($userId);
$apps = array_merge(array_keys($this->fastCache[$userId] ?? []), array_keys($this->lazyCache[$userId] ?? []));
sort($apps);
return array_values(array_unique($apps));
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
*
* @return list<string> list of stored config keys
* @since 31.0.0
*/
public function getKeys(string $userId, string $app): array {
$this->assertParams($userId, $app);
$this->loadConfigAll($userId);
// array_merge() will remove numeric keys (here config keys), so addition arrays instead
$keys = array_map('strval', array_keys(($this->fastCache[$userId][$app] ?? []) + ($this->lazyCache[$userId][$app] ?? [])));
sort($keys);
return array_values(array_unique($keys));
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
*
* @return bool TRUE if key exists
* @since 31.0.0
*/
public function hasKey(string $userId, string $app, string $key, ?bool $lazy = false): bool {
$this->assertParams($userId, $app, $key);
$this->loadConfig($userId, $lazy);
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
if ($lazy === null) {
$appCache = $this->getValues($userId, $app);
return isset($appCache[$key]);
}
if ($lazy) {
return isset($this->lazyCache[$userId][$app][$key]);
}
return isset($this->fastCache[$userId][$app][$key]);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
*
* @return bool
* @throws UnknownKeyException if config key is not known
* @since 31.0.0
*/
public function isSensitive(string $userId, string $app, string $key, ?bool $lazy = false): bool {
$this->assertParams($userId, $app, $key);
$this->loadConfig($userId, $lazy);
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
if (!isset($this->valueDetails[$userId][$app][$key])) {
throw new UnknownKeyException('unknown config key');
}
return $this->isFlagged(self::FLAG_SENSITIVE, $this->valueDetails[$userId][$app][$key]['flags']);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool|null $lazy TRUE to search within lazy loaded config, NULL to search within all config
*
* @return bool
* @throws UnknownKeyException if config key is not known
* @since 31.0.0
*/
public function isIndexed(string $userId, string $app, string $key, ?bool $lazy = false): bool {
$this->assertParams($userId, $app, $key);
$this->loadConfig($userId, $lazy);
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
if (!isset($this->valueDetails[$userId][$app][$key])) {
throw new UnknownKeyException('unknown config key');
}
return $this->isFlagged(self::FLAG_INDEXED, $this->valueDetails[$userId][$app][$key]['flags']);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app if of the app
* @param string $key config key
*
* @return bool TRUE if config is lazy loaded
* @throws UnknownKeyException if config key is not known
* @see IUserConfig for details about lazy loading
* @since 31.0.0
*/
public function isLazy(string $userId, string $app, string $key): bool {
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
// there is a huge probability the non-lazy config are already loaded
// meaning that we can start by only checking if a current non-lazy key exists
if ($this->hasKey($userId, $app, $key, false)) {
// meaning key is not lazy.
return false;
}
// as key is not found as non-lazy, we load and search in the lazy config
if ($this->hasKey($userId, $app, $key, true)) {
return true;
}
throw new UnknownKeyException('unknown config key');
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $prefix config keys prefix to search
* @param bool $filtered TRUE to hide sensitive config values. Value are replaced by {@see IConfig::SENSITIVE_VALUE}
*
* @return array<string, string|int|float|bool|array> [key => value]
* @since 31.0.0
*/
public function getValues(
string $userId,
string $app,
string $prefix = '',
bool $filtered = false,
): array {
$this->assertParams($userId, $app, $prefix);
// if we want to filter values, we need to get sensitivity
$this->loadConfigAll($userId);
// array_merge() will remove numeric keys (here config keys), so addition arrays instead
$values = array_filter(
$this->formatAppValues($userId, $app, ($this->fastCache[$userId][$app] ?? []) + ($this->lazyCache[$userId][$app] ?? []), $filtered),
function (string $key) use ($prefix): bool {
// filter values based on $prefix
return str_starts_with($key, $prefix);
}, ARRAY_FILTER_USE_KEY
);
return $values;
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param bool $filtered TRUE to hide sensitive config values. Value are replaced by {@see IConfig::SENSITIVE_VALUE}
*
* @return array<string, array<string, string|int|float|bool|array>> [appId => [key => value]]
* @since 31.0.0
*/
public function getAllValues(string $userId, bool $filtered = false): array {
$this->assertParams($userId, allowEmptyApp: true);
$this->loadConfigAll($userId);
$result = [];
foreach ($this->getApps($userId) as $app) {
// array_merge() will remove numeric keys (here config keys), so addition arrays instead
$cached = ($this->fastCache[$userId][$app] ?? []) + ($this->lazyCache[$userId][$app] ?? []);
$result[$app] = $this->formatAppValues($userId, $app, $cached, $filtered);
}
return $result;
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $key config key
* @param bool $lazy search within lazy loaded config
* @param ValueType|null $typedAs enforce type for the returned values
*
* @return array<string, string|int|float|bool|array> [appId => value]
* @since 31.0.0
*/
public function getValuesByApps(string $userId, string $key, bool $lazy = false, ?ValueType $typedAs = null): array {
$this->assertParams($userId, '', $key, allowEmptyApp: true);
$this->loadConfig($userId, $lazy);
/** @var array<array-key, array<array-key, mixed>> $cache */
if ($lazy) {
$cache = $this->lazyCache[$userId];
} else {
$cache = $this->fastCache[$userId];
}
$values = [];
foreach (array_keys($cache) as $app) {
if (isset($cache[$app][$key])) {
$value = $cache[$app][$key];
try {
$this->decryptSensitiveValue($userId, $app, $key, $value);
$value = $this->convertTypedValue($value, $typedAs ?? $this->getValueType($userId, $app, $key, $lazy));
} catch (IncorrectTypeException|UnknownKeyException) {
}
$values[$app] = $value;
}
}
return $values;
}
/**
* @inheritDoc
*
* @param string $app id of the app
* @param string $key config key
* @param ValueType|null $typedAs enforce type for the returned values
* @param array|null $userIds limit to a list of user ids
*
* @return array<string, string|int|float|bool|array> [userId => value]
* @since 31.0.0
*/
public function getValuesByUsers(
string $app,
string $key,
?ValueType $typedAs = null,
?array $userIds = null,
): array {
$this->assertParams('', $app, $key, allowEmptyUser: true);
$this->matchAndApplyLexiconDefinition('', $app, $key);
$qb = $this->connection->getQueryBuilder();
$qb->select('userid', 'configvalue', 'type')
->from('preferences')
->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)))
->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
$values = [];
// this nested function will execute current Query and store result within $values.
$executeAndStoreValue = function (IQueryBuilder $qb) use (&$values, $typedAs): IResult {
$result = $qb->executeQuery();
while ($row = $result->fetch()) {
$value = $row['configvalue'];
try {
$value = $this->convertTypedValue($value, $typedAs ?? ValueType::from((int)$row['type']));
} catch (IncorrectTypeException) {
}
$values[$row['userid']] = $value;
}
return $result;
};
// if no userIds to filter, we execute query as it is and returns all values ...
if ($userIds === null) {
$result = $executeAndStoreValue($qb);
$result->closeCursor();
return $values;
}
// if userIds to filter, we chunk the list and execute the same query multiple times until we get all values
$result = null;
$qb->andWhere($qb->expr()->in('userid', $qb->createParameter('userIds')));
foreach (array_chunk($userIds, 50, true) as $chunk) {
$qb->setParameter('userIds', $chunk, IQueryBuilder::PARAM_STR_ARRAY);
$result = $executeAndStoreValue($qb);
}
$result?->closeCursor();
return $values;
}
/**
* @inheritDoc
*
* @param string $app id of the app
* @param string $key config key
* @param string $value config value
* @param bool $caseInsensitive non-case-sensitive search, only works if $value is a string
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValueString(string $app, string $key, string $value, bool $caseInsensitive = false): Generator {
return $this->searchUsersByTypedValue($app, $key, $value, $caseInsensitive);
}
/**
* @inheritDoc
*
* @param string $app id of the app
* @param string $key config key
* @param int $value config value
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValueInt(string $app, string $key, int $value): Generator {
return $this->searchUsersByValueString($app, $key, (string)$value);
}
/**
* @inheritDoc
*
* @param string $app id of the app
* @param string $key config key
* @param array $values list of config values
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValues(string $app, string $key, array $values): Generator {
return $this->searchUsersByTypedValue($app, $key, $values);
}
/**
* @inheritDoc
*
* @param string $app id of the app
* @param string $key config key
* @param bool $value config value
*
* @return Generator<string>
* @since 31.0.0
*/
public function searchUsersByValueBool(string $app, string $key, bool $value): Generator {
$values = ['0', 'off', 'false', 'no'];
if ($value) {
$values = ['1', 'on', 'true', 'yes'];
}
return $this->searchUsersByValues($app, $key, $values);
}
/**
* returns a list of users with config key set to a specific value, or within the list of
* possible values
*
* @param string $app
* @param string $key
* @param string|array $value
* @param bool $caseInsensitive
*
* @return Generator<string>
*/
private function searchUsersByTypedValue(string $app, string $key, string|array $value, bool $caseInsensitive = false): Generator {
$this->assertParams('', $app, $key, allowEmptyUser: true);
$this->matchAndApplyLexiconDefinition('', $app, $key);
$lexiconEntry = $this->getLexiconEntry($app, $key);
if ($lexiconEntry?->isFlagged(self::FLAG_INDEXED) === false) {
$this->logger->notice('UserConfig+Lexicon: using searchUsersByTypedValue on config key ' . $app . '/' . $key . ' which is not set as indexed');
}
$qb = $this->connection->getQueryBuilder();
$qb->from('preferences');
$qb->select('userid');
$qb->where($qb->expr()->eq('appid', $qb->createNamedParameter($app)));
$qb->andWhere($qb->expr()->eq('configkey', $qb->createNamedParameter($key)));
$configValueColumn = ($this->connection->getDatabaseProvider() === IDBConnection::PLATFORM_ORACLE) ? $qb->expr()->castColumn('configvalue', IQueryBuilder::PARAM_STR) : 'configvalue';
if (is_array($value)) {
$where = $qb->expr()->in('indexed', $qb->createNamedParameter($value, IQueryBuilder::PARAM_STR_ARRAY));
// in case lexicon does not exist for this key - or is not set as indexed - we keep searching for non-index entries if 'flags' is set as not indexed
if ($lexiconEntry?->isFlagged(self::FLAG_INDEXED) !== true) {
$where = $qb->expr()->orX(
$where,
$qb->expr()->andX(
$qb->expr()->neq($qb->expr()->bitwiseAnd('flags', self::FLAG_INDEXED), $qb->createNamedParameter(self::FLAG_INDEXED, IQueryBuilder::PARAM_INT)),
$qb->expr()->in($configValueColumn, $qb->createNamedParameter($value, IQueryBuilder::PARAM_STR_ARRAY))
)
);
}
} else {
if ($caseInsensitive) {
$where = $qb->expr()->eq($qb->func()->lower('indexed'), $qb->createNamedParameter(strtolower($value)));
// in case lexicon does not exist for this key - or is not set as indexed - we keep searching for non-index entries if 'flags' is set as not indexed
if ($lexiconEntry?->isFlagged(self::FLAG_INDEXED) !== true) {
$where = $qb->expr()->orX(
$where,
$qb->expr()->andX(
$qb->expr()->neq($qb->expr()->bitwiseAnd('flags', self::FLAG_INDEXED), $qb->createNamedParameter(self::FLAG_INDEXED, IQueryBuilder::PARAM_INT)),
$qb->expr()->eq($qb->func()->lower($configValueColumn), $qb->createNamedParameter(strtolower($value)))
)
);
}
} else {
$where = $qb->expr()->eq('indexed', $qb->createNamedParameter($value));
// in case lexicon does not exist for this key - or is not set as indexed - we keep searching for non-index entries if 'flags' is set as not indexed
if ($lexiconEntry?->isFlagged(self::FLAG_INDEXED) !== true) {
$where = $qb->expr()->orX(
$where,
$qb->expr()->andX(
$qb->expr()->neq($qb->expr()->bitwiseAnd('flags', self::FLAG_INDEXED), $qb->createNamedParameter(self::FLAG_INDEXED, IQueryBuilder::PARAM_INT)),
$qb->expr()->eq($configValueColumn, $qb->createNamedParameter($value))
)
);
}
}
}
$qb->andWhere($where);
$result = $qb->executeQuery();
while ($row = $result->fetch()) {
yield $row['userid'];
}
}
/**
* Get the config value as string.
* If the value does not exist the given default will be returned.
*
* Set lazy to `null` to ignore it and get the value from either source.
*
* **WARNING:** Method is internal and **SHOULD** not be used, as it is better to get the value with a type.
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param string $default config value
* @param null|bool $lazy get config as lazy loaded or not. can be NULL
*
* @return string the value or $default
* @throws TypeConflictException
* @internal
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see getValueString()
* @see getValueInt()
* @see getValueFloat()
* @see getValueBool()
* @see getValueArray()
*/
public function getValueMixed(
string $userId,
string $app,
string $key,
string $default = '',
?bool $lazy = false,
): string {
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
try {
$lazy ??= $this->isLazy($userId, $app, $key);
} catch (UnknownKeyException) {
return $default;
}
return $this->getTypedValue(
$userId,
$app,
$key,
$default,
$lazy,
ValueType::MIXED
);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param string $default default value
* @param bool $lazy search within lazy loaded config
*
* @return string stored config value or $default if not set in database
* @throws InvalidArgumentException if one of the argument format is invalid
* @throws TypeConflictException in case of conflict with the value type set in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function getValueString(
string $userId,
string $app,
string $key,
string $default = '',
bool $lazy = false,
): string {
return $this->getTypedValue($userId, $app, $key, $default, $lazy, ValueType::STRING);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param int $default default value
* @param bool $lazy search within lazy loaded config
*
* @return int stored config value or $default if not set in database
* @throws InvalidArgumentException if one of the argument format is invalid
* @throws TypeConflictException in case of conflict with the value type set in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function getValueInt(
string $userId,
string $app,
string $key,
int $default = 0,
bool $lazy = false,
): int {
return (int)$this->getTypedValue($userId, $app, $key, (string)$default, $lazy, ValueType::INT);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param float $default default value
* @param bool $lazy search within lazy loaded config
*
* @return float stored config value or $default if not set in database
* @throws InvalidArgumentException if one of the argument format is invalid
* @throws TypeConflictException in case of conflict with the value type set in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function getValueFloat(
string $userId,
string $app,
string $key,
float $default = 0,
bool $lazy = false,
): float {
return (float)$this->getTypedValue($userId, $app, $key, (string)$default, $lazy, ValueType::FLOAT);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool $default default value
* @param bool $lazy search within lazy loaded config
*
* @return bool stored config value or $default if not set in database
* @throws InvalidArgumentException if one of the argument format is invalid
* @throws TypeConflictException in case of conflict with the value type set in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function getValueBool(
string $userId,
string $app,
string $key,
bool $default = false,
bool $lazy = false,
): bool {
$b = strtolower((string)$this->getTypedValue($userId, $app, $key, $default ? 'true' : 'false', $lazy, ValueType::BOOL));
return in_array($b, ['1', 'true', 'yes', 'on']);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param array $default default value
* @param bool $lazy search within lazy loaded config
*
* @return array stored config value or $default if not set in database
* @throws InvalidArgumentException if one of the argument format is invalid
* @throws TypeConflictException in case of conflict with the value type set in database
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function getValueArray(
string $userId,
string $app,
string $key,
array $default = [],
bool $lazy = false,
): array {
try {
$defaultJson = json_encode($default, JSON_THROW_ON_ERROR);
$value = json_decode($this->getTypedValue($userId, $app, $key, $defaultJson, $lazy, ValueType::ARRAY), true, flags: JSON_THROW_ON_ERROR);
return is_array($value) ? $value : [];
} catch (JsonException) {
return [];
}
}
/**
* @param string $userId
* @param string $app id of the app
* @param string $key config key
* @param string $default default value
* @param bool $lazy search within lazy loaded config
* @param ValueType $type value type
*
* @return string
* @throws TypeConflictException if type from database is not VALUE_MIXED and different from the requested one
*/
private function getTypedValue(
string $userId,
string $app,
string $key,
string $default,
bool $lazy,
ValueType $type,
): string {
$this->assertParams($userId, $app, $key);
$origKey = $key;
$matched = $this->matchAndApplyLexiconDefinition($userId, $app, $key, $lazy, $type, default: $default);
if ($default === null) {
// there is no logical reason for it to be null
throw new \Exception('default cannot be null');
}
// returns default if strictness of lexicon is set to WARNING (block and report)
if (!$matched) {
return $default;
}
$this->loadConfig($userId, $lazy);
/**
* We ignore check if mixed type is requested.
* If type of stored value is set as mixed, we don't filter.
* If type of stored value is defined, we compare with the one requested.
*/
$knownType = $this->valueDetails[$userId][$app][$key]['type'] ?? null;
if ($type !== ValueType::MIXED
&& $knownType !== null
&& $knownType !== ValueType::MIXED
&& $type !== $knownType) {
$this->logger->warning('conflict with value type from database', ['app' => $app, 'key' => $key, 'type' => $type, 'knownType' => $knownType]);
throw new TypeConflictException('conflict with value type from database');
}
/**
* - the pair $app/$key cannot exist in both array,
* - we should still return an existing non-lazy value even if current method
* is called with $lazy is true
*
* This way, lazyCache will be empty until the load for lazy config value is requested.
*/
if (isset($this->lazyCache[$userId][$app][$key])) {
$value = $this->lazyCache[$userId][$app][$key];
} elseif (isset($this->fastCache[$userId][$app][$key])) {
$value = $this->fastCache[$userId][$app][$key];
} else {
return $default;
}
$this->decryptSensitiveValue($userId, $app, $key, $value);
// in case the key was modified while running matchAndApplyLexiconDefinition() we are
// interested to check options in case a modification of the value is needed
// ie inverting value from previous key when using lexicon option RENAME_INVERT_BOOLEAN
if ($origKey !== $key && $type === ValueType::BOOL) {
$value = ($this->configManager->convertToBool($value, $this->getLexiconEntry($app, $key))) ? '1' : '0';
}
return $value;
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
*
* @return ValueType type of the value
* @throws UnknownKeyException if config key is not known
* @throws IncorrectTypeException if config value type is not known
* @since 31.0.0
*/
public function getValueType(string $userId, string $app, string $key, ?bool $lazy = null): ValueType {
$this->assertParams($userId, $app, $key);
$this->loadConfig($userId, $lazy);
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
if (!isset($this->valueDetails[$userId][$app][$key]['type'])) {
throw new UnknownKeyException('unknown config key');
}
return $this->valueDetails[$userId][$app][$key]['type'];
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param bool $lazy lazy loading
*
* @return int flags applied to value
* @throws UnknownKeyException if config key is not known
* @throws IncorrectTypeException if config value type is not known
* @since 31.0.0
*/
public function getValueFlags(string $userId, string $app, string $key, bool $lazy = false): int {
$this->assertParams($userId, $app, $key);
$this->loadConfig($userId, $lazy);
$this->matchAndApplyLexiconDefinition($userId, $app, $key);
if (!isset($this->valueDetails[$userId][$app][$key])) {
throw new UnknownKeyException('unknown config key');
}
return $this->valueDetails[$userId][$app][$key]['flags'];
}
/**
* Store a config key and its value in database as VALUE_MIXED
*
* **WARNING:** Method is internal and **MUST** not be used as it is best to set a real value type
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param string $value config value
* @param bool $lazy set config as lazy loaded
* @param bool $sensitive if TRUE value will be hidden when listing config values.
*
* @return bool TRUE if value was different, therefor updated in database
* @throws TypeConflictException if type from database is not VALUE_MIXED
* @internal
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
* @see setValueString()
* @see setValueInt()
* @see setValueFloat()
* @see setValueBool()
* @see setValueArray()
*/
public function setValueMixed(
string $userId,
string $app,
string $key,
string $value,
bool $lazy = false,
int $flags = 0,
): bool {
return $this->setTypedValue(
$userId,
$app,
$key,
$value,
$lazy,
$flags,
ValueType::MIXED
);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param string $value config value
* @param bool $lazy set config as lazy loaded
* @param bool $sensitive if TRUE value will be hidden when listing config values.
*
* @return bool TRUE if value was different, therefor updated in database
* @throws TypeConflictException if type from database is not VALUE_MIXED and different from the requested one
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function setValueString(
string $userId,
string $app,
string $key,
string $value,
bool $lazy = false,
int $flags = 0,
): bool {
return $this->setTypedValue(
$userId,
$app,
$key,
$value,
$lazy,
$flags,
ValueType::STRING
);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param int $value config value
* @param bool $lazy set config as lazy loaded
* @param bool $sensitive if TRUE value will be hidden when listing config values.
*
* @return bool TRUE if value was different, therefor updated in database
* @throws TypeConflictException if type from database is not VALUE_MIXED and different from the requested one
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function setValueInt(
string $userId,
string $app,
string $key,
int $value,
bool $lazy = false,
int $flags = 0,
): bool {
if ($value > 2000000000) {
$this->logger->debug('You are trying to store an integer value around/above 2,147,483,647. This is a reminder that reaching this theoretical limit on 32 bits system will throw an exception.');
}
return $this->setTypedValue(
$userId,
$app,
$key,
(string)$value,
$lazy,
$flags,
ValueType::INT
);
}
/**
* @inheritDoc
*
* @param string $userId id of the user
* @param string $app id of the app
* @param string $key config key
* @param float $value config value
* @param bool $lazy set config as lazy loaded
* @param bool $sensitive if TRUE value will be hidden when listing config values.
*
* @return bool TRUE if value was different, therefor updated in database
* @throws TypeConflictException if type from database is not VALUE_MIXED and different from the requested one
* @since 31.0.0
* @see IUserConfig for explanation about lazy loading
*/
public function setValueFloat(
string $userId,
string $app,
string $key,
float $value,
bool $lazy = false,
int $flags = 0,
): bool {
return $this->setTypedValue(
$userId,
$app,
$key,
(string)$value,
$lazy,
$flags,
ValueType::FLOAT
);
}
/**
* @inheritDoc
*
* @param string $userId id of the user