-
Notifications
You must be signed in to change notification settings - Fork 79
Expand file tree
/
Copy pathCorePDOHandler.php
More file actions
1090 lines (943 loc) · 41.1 KB
/
Copy pathCorePDOHandler.php
File metadata and controls
1090 lines (943 loc) · 41.1 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
/*******************************************************************************
*
* CorePDOHandler.php - Class to handle any database using the PDO abstraction
*
* Copyright (c) 2004-2016 NagVis Project (Contact: info@nagvis.org)
*
* License:
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 2 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
*
******************************************************************************/
function _build_dsn_sqlite($params)
{
return $params['filename'];
}
function _build_dsn_common($params)
{
$connData = array_filter(
[
"host" => $params['dbhost'],
"port" => $params['dbport'],
"dbname" => $params['dbname'],
],
function ($v) {
return isset($v) && strlen($v) > 0;
}
);
return implode(
';',
array_map(
function ($k, $v) {
return "$k=$v";
},
array_keys($connData),
$connData
)
);
}
class CorePDOHandler
{
/** @var PDO|null */
private $DB = null;
/** @var string|null */
private $file = null;
/** @var string|null */
private $dsn = null;
/** @var string|null */
private $driver = null;
/** @var array|null */
private $data = null;
/** @var bool */
private $updating = false;
/** @var string|null */
private $lastErrorInfo = null;
/** @var bool */
private $inTrans = false;
/**
* needs to be initialized after class declaration because directly
* initializing it here is a syntax error in PHP 5.3
*
* @var array|null
*/
private static $DRIVERS = null;
/**
* @return void
*/
public static function initialize_static()
{
self::$DRIVERS = [
'_common' => [
'queries' => [
'-perm-add' => 'INSERT INTO perms ("mod", act, obj) VALUES (:mod, :act, :obj)',
'-perm-check' => 'SELECT COUNT(obj) AS num FROM perms WHERE "mod" = :mod AND act = :act AND obj = :obj',
'-perm-count' => 'SELECT COUNT(*) AS num FROM perms WHERE "mod"=:mod AND act=:act AND obj=:obj',
'-perm-delete-by-obj' => 'DELETE FROM perms WHERE "mod"=:mod AND obj=:obj',
'-perm-get-all' => 'SELECT "permId", "mod", act, obj FROM perms ORDER BY "mod",act,obj',
'-perm-get-by-user' => 'SELECT perms."mod" AS "mod", perms.act AS act, perms.obj AS obj '
. 'FROM users2roles '
. 'INNER JOIN roles2perms ON roles2perms."roleId" = users2roles."roleId" '
. 'INNER JOIN perms ON perms."permId" = roles2perms."permId" '
. 'WHERE users2roles."userId" = :id',
'-perm-rename-map' => 'UPDATE perms SET obj=:new_name ' .
' WHERE "mod"=\'Map\' AND obj=:old_name',
'-perm-change-act' => 'UPDATE perms SET act=:new_act WHERE mod=:mod and act=:old_act',
'-role-add' => 'INSERT INTO roles (name) VALUES (:name)',
'-role-add-with-id' => 'INSERT INTO roles ("roleId", name) VALUES (:roleId, :name)',
'-role-add-perm' => 'INSERT INTO roles2perms ("roleId", "permId") VALUES (:roleId, :permId)',
'-role-add-user-by-id' => 'INSERT INTO users2roles("userId", "roleId") VALUES(:userId, :roleId)',
'-role-count-by-name' => 'SELECT COUNT(*) AS num FROM roles WHERE name=:name',
'-role-delete-by-id' => 'DELETE FROM roles WHERE "roleId"=:roleId',
'-role-delete-by-user-id' => 'DELETE FROM users2roles WHERE "userId"=:userId',
'-role-delete-perm-by-id' => 'DELETE FROM roles2perms WHERE "roleId"=:roleId',
'-role-delete-perm-by-obj' => 'DELETE FROM roles2perms WHERE "permId" IN (SELECT "permId" FROM perms WHERE "mod"=:mod AND obj=:obj)',
'-role-get-all' => 'SELECT "roleId", name FROM roles ORDER BY name',
'-role-get-by-name' => 'SELECT "roleId" FROM roles WHERE name=:name',
'-role-get-by-user' => 'SELECT users2roles."roleId" AS "roleId", roles.name AS name ' .
'FROM users2roles ' .
'LEFT JOIN roles ON users2roles."roleId"=roles."roleId" ' .
'WHERE "userId"=:id',
'-role-get-perm-by-id' => 'SELECT "permId" FROM roles2perms WHERE "roleId"=:roleId',
'-role-used-by' => 'SELECT users.name AS name FROM users2roles ' .
'LEFT JOIN users ON users2roles."userId"=users."userId" ' .
'WHERE users2roles."roleId"=:roleId',
'-user-add' => 'INSERT INTO users (name,password) VALUES (:name, :password)',
'-user-add-with-id' => 'INSERT INTO users ("userId", name, password) VALUES (:userId, :name, :password)',
'-user-count' => 'SELECT COUNT(*) AS num FROM users WHERE name=:name',
'-user-count-by-id' => 'SELECT COUNT(*) AS num FROM users WHERE "userId"=:userId',
'-user-delete' => 'DELETE FROM users WHERE "userId"=:userId',
'-user-delete-roles' => 'DELETE FROM users2roles WHERE "userId"=:userId',
'-user-get-all' => 'SELECT "userId", name FROM users ORDER BY name',
'-user-get-by-name' => 'SELECT "userId" FROM users WHERE name=:name',
'-user-get-by-pass' => 'SELECT "userId" FROM users WHERE name=:name AND password=:password',
'-user-get-pw-hash' => 'SELECT "password" FROM users WHERE name=:name',
'-user-update-pass' => 'UPDATE users SET password=:password WHERE "userId"=:id',
'-check-roles-perms' => 'SELECT COUNT(roles."name") AS num ' .
'FROM perms ' .
'INNER JOIN roles2perms ON roles2perms."permId" = perms."permId" ' .
'INNER JOIN roles ON roles."roleId" = roles2perms."roleId" ' .
'WHERE "mod" = :mod AND act = :act AND obj = :obj AND roles.name = :name',
'-create-pop-roles-perms-1' => 'INSERT INTO roles2perms ("roleId", "permId") ' .
'SELECT r."roleId", p."permId" ' .
'FROM roles r, perms p ' .
'WHERE r.name = :r1 ' .
' AND p."mod" = :mod AND p.act = :act AND p.obj = :obj',
'-create-pop-roles-perms-2' => 'INSERT INTO roles2perms ("roleId", "permId") ' .
'SELECT r."roleId", p."permId" ' .
'FROM roles r, perms p ' .
'WHERE r.name IN (:r1, :r2) ' .
' AND p."mod" = :mod AND p.act = :act AND p.obj = :obj',
'-create-pop-roles-perms-3' => 'INSERT INTO roles2perms ("roleId", "permId") ' .
'SELECT r."roleId", p."permId" ' .
'FROM roles r, perms p ' .
'WHERE r.name IN (:r1, :r2, :r3) ' .
' AND p."mod" = :mod AND p.act = :act AND p.obj = :obj',
'-create-pop-perms-from-perms' => 'INSERT INTO perms ("mod", act, obj) ' .
'SELECT :mod, :act, obj ' .
'FROM perms ' .
'WHERE "mod" = :fmod AND act = :fact',
'-create-update-db-version' => 'UPDATE version SET version=:version',
],
'updates' => [
'1100500' => [
['-perm-add', ['mod' => 'Map', 'act' => 'editHtml', 'obj' => '*']],
],
'1091500' => [
['-perm-change-act', ['mod' => 'ChangePassword', 'old_act' => 'change', 'new_act' => '*']]
],
'1080600' => [
['-perm-add', ['mod' => 'Url', 'act' => 'view', 'obj' => '*']],
[
'-create-pop-roles-perms-3', [
'r1' => 'Managers', 'r2' => 'Users (read-only)', 'r3' => 'Guests',
'mod' => 'Url', 'act' => 'view', 'obj' => '*'
]
],
],
'1080500' => [
['-perm-add', ['mod' => 'Action', 'act' => 'perform', 'obj' => '*']],
[
'-create-pop-roles-perms-2', [
'r1' => 'Managers', 'r2' => 'Users (read-only)',
'mod' => 'Action', 'act' => 'perform', 'obj' => '*'
]
],
],
'1060022' => [
['-perm-add', ['mod' => 'User', 'act' => 'setOption', 'obj' => '*']],
[
'-create-pop-roles-perms-3', [
'r1' => 'Managers', 'r2' => 'Users (read-only)', 'r3' => 'Guests',
'mod' => 'User', 'act' => 'setOption', 'obj' => '*'
]
],
],
'1050400' => [
['-perm-add', ['mod' => 'Multisite', 'act' => 'getMaps', 'obj' => '*']],
[
'-create-pop-roles-perms-3', [
'r1' => 'Managers', 'r2' => 'Users (read-only)', 'r3' => 'Guests',
'mod' => 'Multisite', 'act' => 'getMaps', 'obj' => '*'
]
],
],
'1050300' => [
['-perm-add', ['mod' => 'ManageBackgrounds', 'act' => 'manage', 'obj' => '*']],
['-perm-add', ['mod' => 'ManageShapes', 'act' => 'manage', 'obj' => '*']],
['-perm-add', ['mod' => 'Map', 'act' => 'manage', 'obj' => '*']],
[
'-create-pop-roles-perms-1', [
'r1' => 'Managers',
'mod' => 'ManageBackgrounds', 'act' => 'manage', 'obj' => '*'
]
],
[
'-create-pop-roles-perms-1', [
'r1' => 'Managers',
'mod' => 'ManageShapes', 'act' => 'manage', 'obj' => '*'
]
],
[
'-create-pop-roles-perms-1', [
'r1' => 'Managers',
'mod' => 'Map', 'act' => 'manage', 'obj' => '*'
]
],
],
'1050024' => [
[
'-create-pop-perms-from-perms', [
'mod' => 'Map', 'act' => 'addModify',
'fmod' => 'Map', 'fact' => 'view'
]
],
[
'-create-pop-roles-perms-1', [
'r1' => 'Managers',
'mod' => 'Map', 'act' => 'addModify', 'obj' => '*'
]
],
],
],
],
'sqlite' => [
'build_dsn' => '_build_dsn_sqlite',
// Note that these require a '.load' of an appropriate regex() function module!
're_op' => 'REGEXP',
're_op_neg' => 'NOT REGEXP',
'queries' => [
'-create-auth-users' => 'CREATE TABLE users (userId INTEGER, name VARCHAR(100), password VARCHAR(40), PRIMARY KEY(userId), UNIQUE(name))',
'-create-auth-roles' => 'CREATE TABLE roles (roleId INTEGER, name VARCHAR(100), PRIMARY KEY(roleId), UNIQUE(name))',
'-create-auth-perms' => 'CREATE TABLE perms (permId INTEGER, mod VARCHAR(100), act VARCHAR(100), obj VARCHAR(100), PRIMARY KEY(permId), UNIQUE(mod,act,obj))',
'-create-auth-users2roles' => 'CREATE TABLE users2roles (userId INTEGER, roleId INTEGER, PRIMARY KEY(userId, roleId))',
'-create-auth-roles2perms' => 'CREATE TABLE roles2perms (roleId INTEGER, permId INTEGER, PRIMARY KEY(roleId, permId))',
'-create-auth-version' => 'CREATE TABLE version (version VARCHAR(100), PRIMARY KEY(version))',
'-version-insert' => 'INSERT INTO version (version) VALUES (:version)',
'-version-update' => 'UPDATE version SET version=:version',
'-table-exists' => "SELECT * FROM sqlite_master WHERE type='table' AND name=:name",
],
'init' => [
'PRAGMA journal_mode = wal',
],
],
'mysql' => [
'build_dsn' => '_build_dsn_common',
're_op' => 'REGEXP BINARY',
're_op_neg' => 'NOT REGEXP BINARY',
'queries' => [
'-create-auth-users' => 'CREATE TABLE users (userId INTEGER AUTO_INCREMENT, name VARCHAR(100), password VARCHAR(40), PRIMARY KEY(userId), UNIQUE(name))',
'-create-auth-roles' => 'CREATE TABLE roles ("roleId" INTEGER AUTO_INCREMENT, name VARCHAR(100), PRIMARY KEY(roleId), UNIQUE(name))',
'-create-auth-perms' => 'CREATE TABLE perms ("permId" INTEGER AUTO_INCREMENT, "mod" VARCHAR(100), act VARCHAR(100), obj VARCHAR(100), PRIMARY KEY("permId"), UNIQUE("mod", act, obj))',
'-create-auth-users2roles' => 'CREATE TABLE users2roles ("userId" INTEGER, "roleId" INTEGER, PRIMARY KEY("userId", "roleId"))',
'-create-auth-roles2perms' => 'CREATE TABLE roles2perms ("roleId" INTEGER, "permId" INTEGER, PRIMARY KEY("roleId", "permId"))',
'-create-auth-version' => 'CREATE TABLE version (version VARCHAR(100), PRIMARY KEY(version))',
'-version-insert' => 'INSERT INTO version (version) VALUES (:version)',
'-version-update' => 'UPDATE version SET version=:version',
'-table-exists' => "SHOW TABLES LIKE :name",
],
'init' => [
"SET SESSION sql_mode = 'PIPES_AS_CONCAT,ANSI_QUOTES,IGNORE_SPACE'",
],
],
'pgsql' => [
'build_dsn' => '_build_dsn_common',
're_op' => '~',
're_op_neg' => '!~',
'queries' => [
'-table-exists' => "SELECT table_name " .
"FROM information_schema.tables " .
"WHERE table_schema='public' AND table_name = :name",
],
],
];
}
public function __construct()
{
}
/**
* @param string $driver
* @param array $params
* @param string $username
* @param string $password
* @return bool
*/
public function open($driver, $params, $username, $password)
{
if ($driver == '_common') {
error_log("Internal error: '_common' is not supposed to be used as a driver name");
return false;
} elseif (!array_key_exists($driver, self::$DRIVERS)) {
error_log("Internal error: invalid database driver '$driver'");
return false;
}
$drv_data = self::$DRIVERS[$driver];
$dsn = "$driver:" . $drv_data['build_dsn']($params);
$this->dsn = $dsn;
try {
$this->DB = new PDO($dsn, $username, $password, [
// PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
// TODO: This should be loaded from the configuration (e.g. in cae of backends)
//PDO::ATTR_TIMEOUT => 1,
]);
} catch (PDOException $e) {
error_log('Could not initialize a database connection: ' . $e->getMessage());
$this->lastErrorInfo = $e->getMessage();
return false;
}
$this->driver = $driver;
$this->data = $drv_data;
$this->updating = false;
$this->lastErrorInfo = null;
if (isset($drv_data['init'])) {
foreach ($drv_data['init'] as $q) {
$res = $this->DB->exec($q);
if ($res === false) {
$this->DB = null;
$this->lastErrorInfo = "Initial DB query ($q) failed";
return false;
}
}
}
return true;
}
/**
* @return string|null
*/
public function getDSN()
{
return $this->dsn;
}
/**
* @return string
*/
public function getRegularExpressionOperator()
{
return $this->data['re_op'];
}
/**
* @return string
*/
public function getNegatedRegularExpressionOperator()
{
return $this->data['re_op_neg'];
}
/**
* @param string $q
* @return false|PDOStatement
*/
public function prep($q)
{
// TODO: some kind of LRU cache for the dynamically built queries
if (array_key_exists($q, $this->data['queries'])) {
$sql = $this->data['queries'][$q];
} elseif (array_key_exists($q, self::$DRIVERS['_common']['queries'])) {
$sql = self::$DRIVERS['_common']['queries'][$q];
} else {
$sql = $q;
}
$st = $this->DB->prepare($sql);
if ($st === false) {
$this->lastErrorInfo = $this->DB->errorInfo();
return false;
}
$st->setFetchMode(PDO::FETCH_ASSOC);
return $st;
}
/**
* @param string $table
* @return bool
*/
public function tableExist($table)
{
$res = $this->query('-table-exists', ['name' => $table]);
/* rowCount() is not always available for SELECT statements, so try the next best thing... */
return $res !== false && $res->fetch() !== false;
}
/**
* @param string $query
* @param array $params
* @return false|PDOStatement
*/
public function query($query, $params = [])
{
$this->lastErrorInfo = null;
$st = $this->prep($query);
if ($st === false) {
return false;
}
if ($st->execute($params) === false) {
$this->lastErrorInfo = $st->errorInfo();
return false;
}
return $st;
}
/**
* @param string $s
* @param array $params
* @return PDOStatement|void
*/
public function queryFatal($s, $params = [])
{
$res = $this->query($s, $params);
if ($res === false) {
die("Could not execute the $s query: " . $this->errorString());
} else {
return $res;
}
}
/**
* @param string $query
* @param array $params
* @return int
*/
public function count($query, $params)
{
$RET = $this->query($query, $params)->fetch();
return intval($RET['num']);
}
/**
* @return array|string|null
*/
public function error()
{
if (isset($this->lastErrorInfo)) {
return $this->lastErrorInfo;
} else {
return $this->DB ? $this->DB->errorInfo() : '';
}
}
/**
* @return mixed|string
*/
public function errorString()
{
$err = $this->error();
$msg = $err[0];
if (isset($err[1])) {
$msg .= '( ' . $err[1] . ')';
}
if (isset($err[2])) {
$msg .= ': ' . $err[2];
}
return $msg;
}
/**
* @return void
*/
public function close()
{
$this->DB = null;
}
/**
* Checks whether a value (a string or an integer) returned by a database query
* represents a valid integer.
*
* @param int|string $v
* @return bool
*/
public function is_nonnull_int($v)
{
return isset($v) && preg_match('/^-? (?: 0 | [1-9][0-9]* ) $/x', $v);
}
/**
* Checks whether a value (a string or an integer) returned by a database query
* is a valid integer and is equal to the specified one.
*
* @param int|string $v
* @param int|string $exp
* @return bool
*/
public function eq_int($v, $exp)
{
return $this->is_nonnull_int($v) && intval($v) == $exp;
}
/**
* Checks whether a value (a string or an integer) returned by a database query
* is either null or a valid integer equal to the specified one.
* Returns true for an empty string; the caller should take care to use this
* function only on database fields that are supposed to be integers.
*
* @param int|string $v
* @param int|string $exp
* @return bool
*/
public function null_or_eq_int($v, $exp)
{
return !isset($v) || $v === '' || $this->eq_int($v, $exp);
}
/**
* @param string $mod
* @param string $name
* @return void
*/
public function deletePermissions($mod, $name)
{
// Only create when not existing
if ($this->count('-perm-count', ['mod' => $mod, 'act' => 'view', 'obj' => $name]) > 0) {
if (DEBUG && DEBUGLEVEL & 2) {
debug('auth.db: delete permissions for ' . $mod . ' ' . $name);
}
$this->query('-role-delete-perm-by-obj', ['mod' => $mod, 'obj' => $name]);
$this->query('-perm-delete-by-obj', ['mod' => $mod, 'obj' => $name]);
} elseif (DEBUG && DEBUGLEVEL & 2) {
debug('auth.db: won\'t delete ' . $mod . ' permissions ' . $name);
}
}
/**
* @param string $name
* @return true
*/
public function createMapPermissions($name)
{
// Only create when not existing
if ($this->count('-perm-count', ['mod' => 'Map', 'act' => 'view', 'obj' => $name]) <= 0) {
if (DEBUG && DEBUGLEVEL & 2) {
debug('auth.db: create permissions for map ' . $name);
}
if ($this->updating && !$this->inTrans) {
$this->DB->beginTransaction();
$this->inTrans = true;
}
$this->query('-perm-add', ['mod' => 'Map', 'act' => 'view', 'obj' => $name]);
$this->query('-perm-add', ['mod' => 'Map', 'act' => 'edit', 'obj' => $name]);
$this->query('-perm-add', ['mod' => 'Map', 'act' => 'delete', 'obj' => $name]);
} elseif (DEBUG && DEBUGLEVEL & 2) {
debug('auth.db: won\'t create permissions for map ' . $name);
}
return true;
}
/**
* @param string $name
* @return true
*/
public function createRotationPermissions($name)
{
// Only create when not existing
if ($this->count('-perm-count', ['mod' => 'Rotation', 'act' => 'view', 'obj' => $name]) <= 0) {
if (DEBUG && DEBUGLEVEL & 2) {
debug('auth.db: create permissions for rotation ' . $name);
}
$this->query('-perm-add', ['mod' => 'Rotation', 'act' => 'view', 'obj' => $name]);
} elseif (DEBUG && DEBUGLEVEL & 2) {
debug('auth.db: won\'t create permissions for rotation ' . $name);
}
return true;
}
/**
* @return void
* @throws NagVisException
*/
public function updateDb()
{
// Read the current version from db
$dbVersion = 0;
if (!$this->tableExist('version')) {
$this->createVersionTable();
} else {
$dbVersion = GlobalCore::getInstance()->versionToTag($this->getDbVersion());
}
$reason = 'Could not start a database transaction';
$this->inTrans = false;
$this->updating = true;
try {
ksort(self::$DRIVERS['_common']['updates']);
foreach (self::$DRIVERS['_common']['updates'] as $ver => $queries) {
if (intval($ver) < $dbVersion) {
continue;
}
if (!$this->inTrans) {
$this->DB->beginTransaction();
$this->inTrans = true;
}
foreach ($queries as $q) {
$reason = "Could not update the database to version $ver: '$q[0]'";
$this->query($q[0], $q[1]);
}
}
foreach (GlobalCore::getInstance()->demoMaps as $map) {
if (count(GlobalCore::getInstance()->getAvailableMaps('/^' . $map . '$/')) <= 0) {
continue;
}
$this->createMapPermissions($map);
// Ignore errors here; these may already have been set up
if (
$this->count(
'-check-roles-perms',
['name' => 'Guests', 'mod' => 'map', 'act' => 'view', 'obj' => $map]
) > 1
) {
if (!$this->inTrans) {
$this->DB->beginTransaction();
$this->inTrans = true;
}
$this->query(
'-create-pop-roles-perms-1',
['r1' => 'Guests', 'mod' => 'Map', 'act' => 'view', 'obj' => $map]
);
}
}
if ($dbVersion < GlobalCore::getInstance()->versionToTag(CONST_VERSION)) {
if (!$this->inTrans) {
$this->DB->beginTransaction();
$this->inTrans = true;
}
$reason = 'Could not update the NagVis version in the database to ' . CONST_VERSION;
$this->query('-create-update-db-version', ['version' => CONST_VERSION]);
}
$reason = 'Could not commit the transaction for updating the database schema';
} catch (PDOException $e) {
error_log($reason . ': ' . $e->getMessage());
if ($this->inTrans) {
try {
$this->DB->rollBack();
} catch (PDOException $e) {
error_log('Could not roll back the database update transaction: ' . $e->getMessage());
}
$this->inTrans = false;
}
}
if ($this->inTrans) {
try {
$this->DB->commit();
} catch (PDOException $e) {
error_log("Could not commit the database transaction: " . $e->getMessage());
}
$this->inTrans = false;
}
$this->updating = false;
}
/**
* @return string
*/
public function getDbVersion()
{
$data = $this->query('SELECT version FROM version')->fetch();
return $data['version'];
}
/**
* @return void
*/
public function updateDbVersion()
{
$this->query('-version-update', ['version' => CONST_VERSION]);
}
/**
* @return void
*/
public function createVersionTable()
{
$this->query('-create-auth-version');
$this->query('-version-insert', ['version' => CONST_VERSION]);
}
/**
* @return void
*/
public function createInitialDb()
{
$this->queryFatal('-create-auth-users');
$this->queryFatal('-create-auth-roles');
$this->queryFatal('-create-auth-perms');
$this->queryFatal('-create-auth-users2roles');
$this->queryFatal('-create-auth-roles2perms');
$this->createVersionTable();
// If running in OMD create the 'omdadmin' user instead of 'admin'
if (GlobalCore::getInstance()->omdSite() !== null) {
$this->queryFatal(
'-user-add-with-id',
['userId' => 1, 'name' => 'omdadmin', 'password' => '051e0bbcfb79ea2a3ce5c487cc111051aac51ae8']
);
} else {
$this->queryFatal(
'-user-add-with-id',
['userId' => 1, 'name' => 'admin', 'password' => '868103841a2244768b2dbead5dbea2b533940e20']
);
}
$this->queryFatal(
'-user-add-with-id',
['userId' => 2, 'name' => 'guest', 'password' => 'a4e74a1d28ec981c945310d87f8d7b535d794cd2']
);
$this->queryFatal('-role-add-with-id', ['roleId' => 1, 'name' => 'Administrators']);
$this->queryFatal('-role-add-with-id', ['roleId' => 2, 'name' => 'Users (read-only)']);
$this->queryFatal('-role-add-with-id', ['roleId' => 3, 'name' => 'Guests']);
$this->queryFatal('-role-add-with-id', ['roleId' => 4, 'name' => 'Managers']);
// Access controll: Full access to everything
$this->queryFatal('-perm-add', ['mod' => '*', 'act' => '*', 'obj' => '*']);
// Access controll: Overview module levels
$this->queryFatal('-perm-add', ['mod' => 'Overview', 'act' => 'view', 'obj' => '*']);
// Access controll: Access to all General actions
$this->queryFatal('-perm-add', ['mod' => 'General', 'act' => '*', 'obj' => '*']);
// Create permissions for Action/peform/*
$this->queryFatal('-perm-add', ['mod' => 'Action', 'act' => 'perform', 'obj' => '*']);
// Access controll: Map module levels for the demo maps
foreach (GlobalCore::getInstance()->demoMaps as $map) {
$this->createMapPermissions($map);
}
// Access controll: Rotation module levels for rotation "demo"
$this->createRotationPermissions('demo');
// Access controll: Change user options
$this->queryFatal('-perm-add', ['mod' => 'User', 'act' => 'setOption', 'obj' => '*']);
// Access controll: Change own password
$this->queryFatal('-perm-add', ['mod' => 'ChangePassword', 'act' => '*', 'obj' => '*']);
// Access controll: View maps via multisite
$this->queryFatal('-perm-add', ['mod' => 'Multisite', 'act' => 'getMaps', 'obj' => '*']);
// Access controll: Search objects on maps
$this->queryFatal('-perm-add', ['mod' => 'Search', 'act' => 'view', 'obj' => '*']);
// Access controll: Authentication: Logout
$this->queryFatal('-perm-add', ['mod' => 'Auth', 'act' => 'logout', 'obj' => '*']);
// Access controll: Summary permissions for viewing/editing/deleting all maps
$this->createMapPermissions('*');
// Access controll: Rotation module levels for viewing all rotations
$this->queryFatal('-perm-add', ['mod' => 'Rotation', 'act' => 'view', 'obj' => '*']);
// Access controll: Manage users
$this->queryFatal('-perm-add', ['mod' => 'UserMgmt', 'act' => 'manage', 'obj' => '*']);
// Access controll: Manage roles
$this->queryFatal('-perm-add', ['mod' => 'RoleMgmt', 'act' => 'manage', 'obj' => '*']);
// Access control: WUI Management pages
$this->queryFatal('-perm-add', ['mod' => 'ManageBackgrounds', 'act' => 'manage', 'obj' => '*']);
$this->queryFatal('-perm-add', ['mod' => 'ManageShapes', 'act' => 'manage', 'obj' => '*']);
// Access controll: Edit/Delete maps
$this->queryFatal('-perm-add', ['mod' => 'Map', 'act' => 'manage', 'obj' => '*']);
$this->queryFatal('-perm-add', ['mod' => 'Map', 'act' => 'add', 'obj' => '*']);
// Access controll: Edit HTML content of map objects, grantable via the
// role management GUI (CVE-2024-47090)
$this->queryFatal('-perm-add', ['mod' => 'Map', 'act' => 'editHtml', 'obj' => '*']);
$this->queryFatal('-perm-add', ['mod' => 'MainCfg', 'act' => 'edit', 'obj' => '*']);
// Access control: View URLs e.g. in rotation pools
$this->queryFatal('-perm-add', ['mod' => 'Url', 'act' => 'view', 'obj' => '*']);
// Assign the new permission to the managers, users, guests
$this->queryFatal('-create-pop-roles-perms-3', [
'r1' => 'Managers', 'r2' => 'Users (read-only)', 'r3' => 'Guests',
'mod' => 'Url', 'act' => 'view', 'obj' => '*'
]);
/*
* Administrators handling
*/
$data = $this->queryFatal('-role-get-by-name', ['name' => 'Administrators'])->fetch();
$this->queryFatal('-role-add-user-by-id', ['userId' => 1, 'roleId' => $data['roleId']]);
// Access assignment: Administrators => * * *
$this->queryFatal('-create-pop-roles-perms-1', [
'r1' => 'Administrators',
'mod' => '*',
'act' => '*',
'obj' => '*'
]);
/*
* Managers handling
*/
// Permit all actions in General module
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'General', 'act' => '*', 'obj' => '*']
);
// Managers are allowed to perform actions
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Action', 'act' => 'perform', 'obj' => '*']
);
// Access assignment: Managers => Allowed to update user options
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'User', 'act' => 'setOption', 'obj' => '*']
);
// Access assignment: Managers => Allowed to edit/delete all maps
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Map', 'act' => 'manage', 'obj' => '*']
);
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Map', 'act' => 'delete', 'obj' => '*']
);
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Map', 'act' => 'edit', 'obj' => '*']
);
// Access assignment: Managers => Allowed to create maps
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Map', 'act' => 'add', 'obj' => '*']
);
// Access assignment: Managers => Allowed to manage backgrounds and shapes
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'ManageBackgrounds', 'act' => 'manage', 'obj' => '*']
);
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'ManageShapes', 'act' => 'manage', 'obj' => '*']
);
// Access assignment: Managers => Allowed to view the overview
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Overview', 'act' => 'view', 'obj' => '*']
);
// Access assignment: Managers => Allowed to view all maps
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Map', 'act' => 'view', 'obj' => '*']
);
// Access assignment: Managers => Allowed to view all rotations
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Rotation', 'act' => 'view', 'obj' => '*']
);
// Access assignment: Managers => Allowed to change their passwords
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'ChangePassword', 'act' => 'change', 'obj' => '*']
);
// Access assignment: Managers => Allowed to view their maps via multisite
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Multisite', 'act' => 'getMaps', 'obj' => '*']
);
// Access assignment: Managers => Allowed to search objects
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Search', 'act' => 'view', 'obj' => '*']
);
// Access assignment: Managers => Allowed to logout
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Managers', 'mod' => 'Auth', 'act' => 'logout', 'obj' => '*']
);
/*
* Users handling
*/
// Users are allowed to perform actions
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Users (read-only)', 'mod' => 'Action', 'act' => 'perform', 'obj' => '*']
);
// Permit all actions in General module
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Users (read-only)', 'mod' => 'General', 'act' => '*', 'obj' => '*']
);
// Access assignment: Users => Allowed to update user options
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Users (read-only)', 'mod' => 'User', 'act' => 'setOption', 'obj' => '*']
);
// Access assignment: Users => Allowed to view the overview
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Users (read-only)', 'mod' => 'Overview', 'act' => 'view', 'obj' => '*']
);
// Access assignment: Users => Allowed to view all maps
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Users (read-only)', 'mod' => 'Map', 'act' => 'view', 'obj' => '*']
);
// Access assignment: Users => Allowed to view all rotations
$this->queryFatal(
'-create-pop-roles-perms-1',
['r1' => 'Users (read-only)', 'mod' => 'Rotation', 'act' => 'view', 'obj' => '*']
);