-
Notifications
You must be signed in to change notification settings - Fork 933
/
CUser.php
1584 lines (1346 loc) · 47.9 KB
/
CUser.php
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
/*
** Zabbix
** Copyright (C) 2001-2019 Zabbix SIA
**
** This program is free software; you can redistribute it and/or modify
** it under the terms of the GNU General Public License as published by
** the Free Software Foundation; either version 2 of the License, or
** (at your option) any later version.
**
** 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
**/
/**
* Class containing methods for operations with users.
*/
class CUser extends CApiService {
protected $tableName = 'users';
protected $tableAlias = 'u';
protected $sortColumns = ['userid', 'alias'];
/**
* Get users data.
*
* @param array $options
* @param array $options['usrgrpids'] filter by UserGroup IDs
* @param array $options['userids'] filter by User IDs
* @param bool $options['type'] filter by User type [USER_TYPE_ZABBIX_USER: 1, USER_TYPE_ZABBIX_ADMIN: 2, USER_TYPE_SUPER_ADMIN: 3]
* @param bool $options['selectUsrgrps'] extend with UserGroups data for each User
* @param bool $options['getAccess'] extend with access data for each User
* @param bool $options['count'] output only count of objects in result. (result returned in property 'rowscount')
* @param string $options['pattern'] filter by Host name containing only give pattern
* @param int $options['limit'] output will be limited to given number
* @param string $options['sortfield'] output will be sorted by given property ['userid', 'alias']
* @param string $options['sortorder'] output will be sorted in given order ['ASC', 'DESC']
*
* @return array
*/
public function get($options = []) {
$result = [];
$sqlParts = [
'select' => ['users' => 'u.userid'],
'from' => ['users' => 'users u'],
'where' => [],
'order' => [],
'limit' => null
];
$defOptions = [
'usrgrpids' => null,
'userids' => null,
'mediaids' => null,
'mediatypeids' => null,
// filter
'filter' => null,
'search' => null,
'searchByAny' => null,
'startSearch' => false,
'excludeSearch' => false,
'searchWildcardsEnabled' => null,
// output
'output' => API_OUTPUT_EXTEND,
'editable' => false,
'selectUsrgrps' => null,
'selectMedias' => null,
'selectMediatypes' => null,
'getAccess' => null,
'countOutput' => false,
'preservekeys' => false,
'sortfield' => '',
'sortorder' => '',
'limit' => null
];
$options = zbx_array_merge($defOptions, $options);
// permission check
if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
if (!$options['editable']) {
$sqlParts['from']['users_groups'] = 'users_groups ug';
$sqlParts['where']['uug'] = 'u.userid=ug.userid';
$sqlParts['where'][] = 'ug.usrgrpid IN ('.
' SELECT uug.usrgrpid'.
' FROM users_groups uug'.
' WHERE uug.userid='.self::$userData['userid'].
')';
}
else {
$sqlParts['where'][] = 'u.userid='.self::$userData['userid'];
}
}
// userids
if ($options['userids'] !== null) {
zbx_value2array($options['userids']);
$sqlParts['where'][] = dbConditionInt('u.userid', $options['userids']);
}
// usrgrpids
if ($options['usrgrpids'] !== null) {
zbx_value2array($options['usrgrpids']);
$sqlParts['from']['users_groups'] = 'users_groups ug';
$sqlParts['where'][] = dbConditionInt('ug.usrgrpid', $options['usrgrpids']);
$sqlParts['where']['uug'] = 'u.userid=ug.userid';
}
// mediaids
if ($options['mediaids'] !== null) {
zbx_value2array($options['mediaids']);
$sqlParts['from']['media'] = 'media m';
$sqlParts['where'][] = dbConditionInt('m.mediaid', $options['mediaids']);
$sqlParts['where']['mu'] = 'm.userid=u.userid';
}
// mediatypeids
if ($options['mediatypeids'] !== null) {
zbx_value2array($options['mediatypeids']);
$sqlParts['from']['media'] = 'media m';
$sqlParts['where'][] = dbConditionInt('m.mediatypeid', $options['mediatypeids']);
$sqlParts['where']['mu'] = 'm.userid=u.userid';
}
// filter
if (is_array($options['filter'])) {
if (array_key_exists('autologout', $options['filter']) && $options['filter']['autologout'] !== null) {
$options['filter']['autologout'] = getTimeUnitFilters($options['filter']['autologout']);
}
if (array_key_exists('refresh', $options['filter']) && $options['filter']['refresh'] !== null) {
$options['filter']['refresh'] = getTimeUnitFilters($options['filter']['refresh']);
}
if (isset($options['filter']['passwd'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('It is not possible to filter by user password.'));
}
$this->dbFilter('users u', $options, $sqlParts);
}
// search
if (is_array($options['search'])) {
if (isset($options['search']['passwd'])) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('It is not possible to search by user password.'));
}
zbx_db_search('users u', $options, $sqlParts);
}
// limit
if (zbx_ctype_digit($options['limit']) && $options['limit']) {
$sqlParts['limit'] = $options['limit'];
}
$userIds = [];
$sqlParts = $this->applyQueryOutputOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
$sqlParts = $this->applyQuerySortOptions($this->tableName(), $this->tableAlias(), $options, $sqlParts);
$res = DBselect($this->createSelectQueryFromParts($sqlParts), $sqlParts['limit']);
while ($user = DBfetch($res)) {
unset($user['passwd']);
if ($options['countOutput']) {
$result = $user['rowscount'];
}
else {
$userIds[$user['userid']] = $user['userid'];
$result[$user['userid']] = $user;
}
}
if ($options['countOutput']) {
return $result;
}
/*
* Adding objects
*/
if ($options['getAccess'] !== null) {
foreach ($result as $userid => $user) {
$result[$userid] += ['gui_access' => 0, 'debug_mode' => 0, 'users_status' => 0];
}
$access = DBselect(
'SELECT ug.userid,MAX(g.gui_access) AS gui_access,'.
' MAX(g.debug_mode) AS debug_mode,MAX(g.users_status) AS users_status'.
' FROM usrgrp g,users_groups ug'.
' WHERE '.dbConditionInt('ug.userid', $userIds).
' AND g.usrgrpid=ug.usrgrpid'.
' GROUP BY ug.userid'
);
while ($userAccess = DBfetch($access)) {
$result[$userAccess['userid']] = zbx_array_merge($result[$userAccess['userid']], $userAccess);
}
}
if ($result) {
$result = $this->addRelatedObjects($options, $result);
}
// removing keys
if (!$options['preservekeys']) {
$result = zbx_cleanHashes($result);
}
return $result;
}
/**
* @param array $users
*
* @return array
*/
public function create(array $users) {
$this->validateCreate($users);
$ins_users = [];
foreach ($users as $user) {
unset($user['usrgrps'], $user['user_medias']);
$ins_users[] = $user;
}
$userids = DB::insert('users', $ins_users);
foreach ($users as $index => &$user) {
$user['userid'] = $userids[$index];
}
unset($user);
$this->updateUsersGroups($users, __FUNCTION__);
$this->updateMedias($users, __FUNCTION__);
$this->addAuditBulk(AUDIT_ACTION_ADD, AUDIT_RESOURCE_USER, $users);
return ['userids' => $userids];
}
/**
* @param array $users
*
* @throws APIException if the input is invalid.
*/
private function validateCreate(array &$users) {
if (self::$userData['type'] != USER_TYPE_SUPER_ADMIN) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('You do not have permissions to create users.'));
}
$locales = array_keys(getLocales());
$themes = THEME_DEFAULT.','.implode(',', array_keys(Z::getThemes()));
$api_input_rules = ['type' => API_OBJECTS, 'flags' => API_NOT_EMPTY | API_NORMALIZE, 'uniq' => [['alias']], 'fields' => [
'alias' => ['type' => API_STRING_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY, 'length' => DB::getFieldLength('users', 'alias')],
'name' => ['type' => API_STRING_UTF8, 'length' => DB::getFieldLength('users', 'name')],
'surname' => ['type' => API_STRING_UTF8, 'length' => DB::getFieldLength('users', 'surname')],
'passwd' => ['type' => API_STRING_UTF8, 'flags' => API_NOT_EMPTY, 'length' => 255],
'url' => ['type' => API_URL, 'length' => DB::getFieldLength('users', 'url')],
'autologin' => ['type' => API_INT32, 'in' => '0,1'],
'autologout' => ['type' => API_TIME_UNIT, 'flags' => API_NOT_EMPTY, 'in' => '0,90:'.SEC_PER_DAY],
'lang' => ['type' => API_STRING_UTF8, 'flags' => API_NOT_EMPTY, 'in' => implode(',', $locales)],
'theme' => ['type' => API_STRING_UTF8, 'in' => $themes, 'length' => DB::getFieldLength('users', 'theme')],
'type' => ['type' => API_INT32, 'in' => implode(',', [USER_TYPE_ZABBIX_USER, USER_TYPE_ZABBIX_ADMIN, USER_TYPE_SUPER_ADMIN])],
'refresh' => ['type' => API_TIME_UNIT, 'flags' => API_NOT_EMPTY, 'in' => '0:'.SEC_PER_HOUR],
'rows_per_page' => ['type' => API_INT32, 'in' => '1:999999'],
'usrgrps' => ['type' => API_OBJECTS, 'flags' => API_REQUIRED | API_NOT_EMPTY, 'uniq' => [['usrgrpid']], 'fields' => [
'usrgrpid' => ['type' => API_ID, 'flags' => API_REQUIRED]
]],
'user_medias' => ['type' => API_OBJECTS, 'fields' => [
'mediatypeid' => ['type' => API_ID, 'flags' => API_REQUIRED],
'sendto' => ['type' => API_STRINGS_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY | API_NORMALIZE],
'active' => ['type' => API_INT32, 'in' => implode(',', [MEDIA_STATUS_ACTIVE, MEDIA_STATUS_DISABLED])],
'severity' => ['type' => API_INT32, 'in' => '0:63'],
'period' => ['type' => API_TIME_PERIOD, 'flags' => API_ALLOW_USER_MACRO, 'length' => DB::getFieldLength('media', 'period')]
]]
]];
if (!CApiInputValidator::validate($api_input_rules, $users, '/', $error)) {
self::exception(ZBX_API_ERROR_PARAMETERS, $error);
}
foreach ($users as &$user) {
$user = $this->checkLoginOptions($user);
/*
* If user is created without a password (e.g. for GROUP_GUI_ACCESS_LDAP), store an empty string
* as his password in database.
*/
$user['passwd'] = array_key_exists('passwd', $user)
? password_hash($user['passwd'], PASSWORD_BCRYPT, ['cost' => ZBX_BCRYPT_COST])
: '';
}
unset($user);
$this->checkDuplicates(zbx_objectValues($users, 'alias'));
$this->checkLanguages(zbx_objectValues($users, 'lang'));
$this->checkUserGroups($users, []);
$db_mediatypes = $this->checkMediaTypes($users);
$this->validateMediaRecipients($users, $db_mediatypes);
}
/**
* @param array $users
*
* @return array
*/
public function update(array $users) {
$this->validateUpdate($users, $db_users);
$upd_users = [];
foreach ($users as $user) {
$db_user = $db_users[$user['userid']];
$upd_user = [];
// strings
$field_names = ['alias', 'name', 'surname', 'autologout', 'passwd', 'refresh', 'url', 'lang', 'theme'];
foreach ($field_names as $field_name) {
if (array_key_exists($field_name, $user) && $user[$field_name] !== $db_user[$field_name]) {
$upd_user[$field_name] = $user[$field_name];
}
}
// integers
foreach (['autologin', 'type', 'rows_per_page'] as $field_name) {
if (array_key_exists($field_name, $user) && $user[$field_name] != $db_user[$field_name]) {
$upd_user[$field_name] = $user[$field_name];
}
}
if ($upd_user) {
$upd_users[] = [
'values' => $upd_user,
'where' => ['userid' => $user['userid']]
];
}
}
if ($upd_users) {
DB::update('users', $upd_users);
}
$this->updateUsersGroups($users, __FUNCTION__);
$this->updateMedias($users, __FUNCTION__);
$this->addAuditBulk(AUDIT_ACTION_UPDATE, AUDIT_RESOURCE_USER, $users, $db_users);
return ['userids' => zbx_objectValues($users, 'userid')];
}
/**
* @param array $users
* @param array $db_users
*
* @throws APIException if the input is invalid.
*/
private function validateUpdate(array &$users, array &$db_users = null) {
$locales = array_keys(getLocales());
$themes = THEME_DEFAULT.','.implode(',', array_keys(Z::getThemes()));
$api_input_rules = ['type' => API_OBJECTS, 'flags' => API_NOT_EMPTY | API_NORMALIZE, 'uniq' => [['userid'], ['alias']], 'fields' => [
'userid' => ['type' => API_ID, 'flags' => API_REQUIRED],
'alias' => ['type' => API_STRING_UTF8, 'flags' => API_NOT_EMPTY, 'length' => DB::getFieldLength('users', 'alias')],
'name' => ['type' => API_STRING_UTF8, 'length' => DB::getFieldLength('users', 'name')],
'surname' => ['type' => API_STRING_UTF8, 'length' => DB::getFieldLength('users', 'surname')],
'passwd' => ['type' => API_STRING_UTF8, 'flags' => API_NOT_EMPTY, 'length' => 255],
'url' => ['type' => API_URL, 'length' => DB::getFieldLength('users', 'url')],
'autologin' => ['type' => API_INT32, 'in' => '0,1'],
'autologout' => ['type' => API_TIME_UNIT, 'flags' => API_NOT_EMPTY, 'in' => '0,90:'.SEC_PER_DAY],
'lang' => ['type' => API_STRING_UTF8, 'flags' => API_NOT_EMPTY, 'in' => implode(',', $locales)],
'theme' => ['type' => API_STRING_UTF8, 'in' => $themes, 'length' => DB::getFieldLength('users', 'theme')],
'type' => ['type' => API_INT32, 'in' => implode(',', [USER_TYPE_ZABBIX_USER, USER_TYPE_ZABBIX_ADMIN, USER_TYPE_SUPER_ADMIN])],
'refresh' => ['type' => API_TIME_UNIT, 'flags' => API_NOT_EMPTY, 'in' => '0:'.SEC_PER_HOUR],
'rows_per_page' => ['type' => API_INT32, 'in' => '1:999999'],
'usrgrps' => ['type' => API_OBJECTS, 'flags' => API_NOT_EMPTY, 'uniq' => [['usrgrpid']], 'fields' => [
'usrgrpid' => ['type' => API_ID, 'flags' => API_REQUIRED]
]],
'user_medias' => ['type' => API_OBJECTS, 'fields' => [
'mediatypeid' => ['type' => API_ID, 'flags' => API_REQUIRED],
'sendto' => ['type' => API_STRINGS_UTF8, 'flags' => API_REQUIRED | API_NOT_EMPTY | API_NORMALIZE],
'active' => ['type' => API_INT32, 'in' => implode(',', [MEDIA_STATUS_ACTIVE, MEDIA_STATUS_DISABLED])],
'severity' => ['type' => API_INT32, 'in' => '0:63'],
'period' => ['type' => API_TIME_PERIOD, 'flags' => API_ALLOW_USER_MACRO, 'length' => DB::getFieldLength('media', 'period')]
]]
]];
if (!CApiInputValidator::validate($api_input_rules, $users, '/', $error)) {
self::exception(ZBX_API_ERROR_PARAMETERS, $error);
}
$db_users = $this->get([
'output' => [],
'userids' => zbx_objectValues($users, 'userid'),
'editable' => true,
'preservekeys' => true
]);
// 'passwd' can't be received by the user.get method
$db_users = DB::select('users', [
'output' => ['userid', 'alias', 'name', 'surname', 'passwd', 'url', 'autologin', 'autologout', 'lang',
'theme', 'type', 'refresh', 'rows_per_page'
],
'userids' => array_keys($db_users),
'preservekeys' => true
]);
$aliases = [];
foreach ($users as &$user) {
if (!array_key_exists($user['userid'], $db_users)) {
self::exception(ZBX_API_ERROR_PERMISSIONS,
_('No permissions to referred object or it does not exist!')
);
}
$db_user = $db_users[$user['userid']];
if (array_key_exists('alias', $user) && $user['alias'] !== $db_user['alias']) {
if ($db_user['alias'] === ZBX_GUEST_USER) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Cannot rename guest user.'));
}
$aliases[] = $user['alias'];
}
$user = $this->checkLoginOptions($user);
if (array_key_exists('passwd', $user)) {
if ($db_user['alias'] == ZBX_GUEST_USER) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('Not allowed to set password for user "guest".'));
}
$user['passwd'] = password_hash($user['passwd'], PASSWORD_BCRYPT, ['cost' => ZBX_BCRYPT_COST]);
}
}
unset($user);
if ($aliases) {
$this->checkDuplicates($aliases);
}
$this->checkLanguages(zbx_objectValues($users, 'lang'));
$this->checkUserGroups($users, $db_users);
$db_mediatypes = $this->checkMediaTypes($users);
$this->validateMediaRecipients($users, $db_mediatypes);
$this->checkHimself($users);
}
/**
* Check for duplicated users.
*
* @param array $aliases
*
* @throws APIException if user already exists.
*/
private function checkDuplicates(array $aliases) {
$db_users = DB::select('users', [
'output' => ['alias'],
'filter' => ['alias' => $aliases],
'limit' => 1
]);
if ($db_users) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('User with alias "%s" already exists.', $db_users[0]['alias'])
);
}
}
/**
* Check for valid user groups.
*
* @param array $users
* @param array $users[]['passwd'] (optional)
* @param array $users[]['usrgrps'] (optional)
* @param array $db_users
* @param array $db_users[]['passwd']
*
* @throws APIException if user groups is not exists.
*/
private function checkUserGroups(array $users, array $db_users) {
$usrgrpids = [];
foreach ($users as $user) {
if (array_key_exists('usrgrps', $user)) {
foreach ($user['usrgrps'] as $usrgrp) {
$usrgrpids[$usrgrp['usrgrpid']] = true;
}
}
}
if (!$usrgrpids) {
return;
}
$usrgrpids = array_keys($usrgrpids);
$db_usrgrps = DB::select('usrgrp', [
'output' => ['gui_access'],
'usrgrpids' => $usrgrpids,
'preservekeys' => true
]);
foreach ($usrgrpids as $usrgrpid) {
if (!array_key_exists($usrgrpid, $db_usrgrps)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('User group with ID "%1$s" is not available.', $usrgrpid));
}
}
foreach ($users as $user) {
if (array_key_exists('passwd', $user)) {
$passwd = $user['passwd'];
}
elseif (array_key_exists('userid', $user) && array_key_exists($user['userid'], $db_users)) {
$passwd = $db_users[$user['userid']]['passwd'];
}
else {
$passwd = '';
}
// Do not allow empty password for users with GROUP_GUI_ACCESS_INTERNAL.
if ($passwd === '' && self::hasInternalAuth($user, $db_usrgrps)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Incorrect value for field "%1$s": %2$s.', 'passwd', _('cannot be empty'))
);
}
}
}
/**
* Check if specified language has dependent locale installed.
*
* @param array $languages
*
* @throws APIException if language locale is not installed.
*/
private function checkLanguages(array $languages) {
foreach ($languages as $lang) {
if ($lang !== 'en_GB' && !setlocale(LC_MONETARY, zbx_locale_variants($lang))) {
self::exception(ZBX_API_ERROR_PARAMETERS, _s('Language "%1$s" is not supported.', $lang));
}
}
}
/**
* Returns true if user has internal authentication type.
*
* @param array $user
* @param string $user['usrgrps'][]['usrgrpid']
* @param array $db_usrgrps
* @param int $db_usrgrps[usrgrpid]['gui_access']
*
* @return bool
*/
private static function hasInternalAuth($user, $db_usrgrps) {
$config = select_config();
$system_gui_access = ($config['authentication_type'] == ZBX_AUTH_INTERNAL)
? GROUP_GUI_ACCESS_INTERNAL
: GROUP_GUI_ACCESS_LDAP;
foreach($user['usrgrps'] as $usrgrp) {
$gui_access = (int) $db_usrgrps[$usrgrp['usrgrpid']]['gui_access'];
$gui_access = ($gui_access == GROUP_GUI_ACCESS_SYSTEM) ? $system_gui_access : $gui_access;
if ($gui_access == GROUP_GUI_ACCESS_INTERNAL) {
return true;
}
}
return false;
}
/**
* Check for valid media types.
*
* @param array $users Array of users.
* @param array $users[]['user_medias'] (optional) Array of user medias.
*
* @throws APIException if user media type does not exist.
*
* @return array Returns valid media types.
*/
private function checkMediaTypes(array $users) {
$mediatypeids = [];
foreach ($users as $user) {
if (array_key_exists('user_medias', $user)) {
foreach ($user['user_medias'] as $media) {
$mediatypeids[$media['mediatypeid']] = true;
}
}
}
if (!$mediatypeids) {
return [];
}
$mediatypeids = array_keys($mediatypeids);
$db_mediatypes = DB::select('media_type', [
'output' => ['mediatypeid', 'type'],
'mediatypeids' => $mediatypeids,
'preservekeys' => true
]);
foreach ($mediatypeids as $mediatypeid) {
if (!array_key_exists($mediatypeid, $db_mediatypes)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Media type with ID "%1$s" is not available.', $mediatypeid)
);
}
}
return $db_mediatypes;
}
/**
* Check if the passed 'sendto' value is a valid input according to the mediatype. Currently validates
* only e-mail media types.
*
* @param array $users Array of users.
* @param string $users[]['user_medias'][]['mediatypeid'] Media type ID.
* @param array|string $users[]['user_medias'][]['sendto'] Address where to send the alert.
* @param array $db_mediatypes List of available media types.
*
* @throws APIException if e-mail is not valid or exeeds maximum DB field length.
*/
private function validateMediaRecipients(array $users, array $db_mediatypes) {
if ($db_mediatypes) {
$email_mediatypes = [];
foreach ($db_mediatypes as $db_mediatype) {
if ($db_mediatype['type'] == MEDIA_TYPE_EMAIL) {
$email_mediatypes[$db_mediatype['mediatypeid']] = true;
}
}
$max_length = DB::getFieldLength('media', 'sendto');
$email_validator = new CEmailValidator();
foreach ($users as $user) {
if (array_key_exists('user_medias', $user)) {
foreach ($user['user_medias'] as $media) {
/*
* For non-email media types only one value allowed. Since value is normalized, need to validate
* if array contains only one item. If there are more than one string, error message is
* displayed, indicating that passed value is not a string.
*/
if (!array_key_exists($media['mediatypeid'], $email_mediatypes)
&& count($media['sendto']) > 1) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid parameter "%1$s": %2$s.', 'sendto', _('a character string is expected'))
);
}
/*
* If input value is an array with empty string, ApiInputValidator identifies it as valid since
* values are normalized. That's why value must be revalidated.
*/
foreach ($media['sendto'] as $sendto) {
if ($sendto === '') {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid parameter "%1$s": %2$s.', 'sendto', _('cannot be empty'))
);
}
}
/*
* If media type is email, validate each given string against email pattern.
* Additionally, total lenght of emails must be checked, because all media type emails are
* separated by newline and stored as a string in single database field. Newline characters
* consumes extra space, so additional validation must be made.
*/
if (array_key_exists($media['mediatypeid'], $email_mediatypes)) {
foreach ($media['sendto'] as $sendto) {
if (!$email_validator->validate($sendto)) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Invalid email address for media type with ID "%1$s".',
$media['mediatypeid']
)
);
}
elseif (strlen(implode("\n", $media['sendto'])) > $max_length) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Maximum total length of email address exceeded for media type with ID "%1$s".',
$media['mediatypeid']
)
);
}
}
}
}
}
}
}
}
/**
* Additional check to exclude an opportunity to deactivate himself.
*
* @param array $users
* @param array $users[]['usrgrps'] (optional)
*
* @throws APIException
*/
private function checkHimself(array $users) {
foreach ($users as $user) {
if (bccomp($user['userid'], self::$userData['userid']) == 0) {
if (array_key_exists('type', $user)) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('User cannot change their user type.'));
}
if (array_key_exists('usrgrps', $user)) {
$db_usrgrps = DB::select('usrgrp', [
'output' => ['gui_access', 'users_status'],
'usrgrpids' => zbx_objectValues($user['usrgrps'], 'usrgrpid')
]);
foreach ($db_usrgrps as $db_usrgrp) {
if ($db_usrgrp['gui_access'] == GROUP_GUI_ACCESS_DISABLED
|| $db_usrgrp['users_status'] == GROUP_STATUS_DISABLED) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('User cannot add himself to a disabled group or a group with disabled GUI access.')
);
}
}
}
break;
}
}
}
/**
* Additional check to exclude an opportunity to enable auto-login and auto-logout options together..
*
* @param array $user
* @param int $user[]['autologin'] (optional)
* @param string $user[]['autologout'] (optional)
*
* @throws APIException
*/
private function checkLoginOptions(array $user) {
if (!array_key_exists('autologout', $user) && array_key_exists('autologin', $user) && $user['autologin'] != 0) {
$user['autologout'] = '0';
}
if (!array_key_exists('autologin', $user) && array_key_exists('autologout', $user)
&& timeUnitToSeconds($user['autologout']) != 0) {
$user['autologin'] = 0;
}
if (array_key_exists('autologin', $user) && array_key_exists('autologout', $user)
&& $user['autologin'] != 0 && timeUnitToSeconds($user['autologout']) != 0) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_('Auto-login and auto-logout options cannot be enabled together.')
);
}
return $user;
}
/**
* Update table "users_groups".
*
* @param array $users
* @param string $method
*/
private function updateUsersGroups(array $users, $method) {
$users_groups = [];
foreach ($users as $user) {
if (array_key_exists('usrgrps', $user)) {
$users_groups[$user['userid']] = [];
foreach ($user['usrgrps'] as $usrgrp) {
$users_groups[$user['userid']][$usrgrp['usrgrpid']] = true;
}
}
}
if (!$users_groups) {
return;
}
$db_users_groups = ($method === 'update')
? DB::select('users_groups', [
'output' => ['id', 'usrgrpid', 'userid'],
'filter' => ['userid' => array_keys($users_groups)]
])
: [];
$ins_users_groups = [];
$del_ids = [];
foreach ($db_users_groups as $db_user_group) {
if (array_key_exists($db_user_group['usrgrpid'], $users_groups[$db_user_group['userid']])) {
unset($users_groups[$db_user_group['userid']][$db_user_group['usrgrpid']]);
}
else {
$del_ids[] = $db_user_group['id'];
}
}
foreach ($users_groups as $userid => $usrgrpids) {
foreach (array_keys($usrgrpids) as $usrgrpid) {
$ins_users_groups[] = [
'userid' => $userid,
'usrgrpid' => $usrgrpid
];
}
}
if ($ins_users_groups) {
DB::insertBatch('users_groups', $ins_users_groups);
}
if ($del_ids) {
DB::delete('users_groups', ['id' => $del_ids]);
}
}
/**
* Auxiliary function for updateMedias().
*
* @param array $medias
* @param string $mediatypeid
* @param string $sendto
*
* @return int
*/
private function getSimilarMedia(array $medias, $mediatypeid, $sendto) {
foreach ($medias as $index => $media) {
if (bccomp($media['mediatypeid'], $mediatypeid) == 0 && $media['sendto'] === $sendto) {
return $index;
}
}
return -1;
}
/**
* Update table "media".
*
* @param array $users
* @param string $method
*/
private function updateMedias(array $users, $method) {
$medias = [];
foreach ($users as $user) {
if (array_key_exists('user_medias', $user)) {
$medias[$user['userid']] = [];
foreach ($user['user_medias'] as $media) {
$media['sendto'] = implode("\n", $media['sendto']);
$medias[$user['userid']][] = $media;
}
}
}
if (!$medias) {
return;
}
$db_medias = ($method === 'update')
? DB::select('media', [
'output' => ['mediaid', 'userid', 'mediatypeid', 'sendto', 'active', 'severity', 'period'],
'filter' => ['userid' => array_keys($medias)]
])
: [];
$ins_medias = [];
$upd_medias = [];
$del_mediaids = [];
foreach ($db_medias as $db_media) {
$index = $this->getSimilarMedia($medias[$db_media['userid']], $db_media['mediatypeid'],
$db_media['sendto']
);
if ($index != -1) {
$media = $medias[$db_media['userid']][$index];
$upd_media = [];
if (array_key_exists('active', $media) && $media['active'] != $db_media['active']) {
$upd_media['active'] = $media['active'];
}
if (array_key_exists('severity', $media) && $media['severity'] != $db_media['severity']) {
$upd_media['severity'] = $media['severity'];
}
if (array_key_exists('period', $media) && $media['period'] !== $db_media['period']) {
$upd_media['period'] = $media['period'];
}
if ($upd_media) {
$upd_medias[] = [
'values' => $upd_media,
'where' => ['mediaid' => $db_media['mediaid']]
];
}
unset($medias[$db_media['userid']][$index]);
}
else {
$del_mediaids[] = $db_media['mediaid'];
}
}
foreach ($medias as $userid => $user_medias) {
foreach ($user_medias as $media) {
$ins_medias[] = ['userid' => $userid] + $media;
}
}
if ($ins_medias) {
DB::insert('media', $ins_medias);
}
if ($upd_medias) {
DB::update('media', $upd_medias);
}
if ($del_mediaids) {
DB::delete('media', ['mediaid' => $del_mediaids]);
}
}
/**
* @param array $userids
*
* @return array
*/
public function delete(array $userids) {
$this->validateDelete($userids, $db_users);
DB::delete('media', ['userid' => $userids]);
DB::delete('profiles', ['userid' => $userids]);
DB::delete('users_groups', ['userid' => $userids]);
DB::delete('users', ['userid' => $userids]);
$this->addAuditBulk(AUDIT_ACTION_DELETE, AUDIT_RESOURCE_USER, $db_users);
return ['userids' => $userids];
}
/**
* @param array $userids
* @param array $db_users
*
* @throws APIException if the input is invalid.
*/
private function validateDelete(array &$userids, array &$db_users = null) {
$api_input_rules = ['type' => API_IDS, 'flags' => API_NOT_EMPTY, 'uniq' => true];
if (!CApiInputValidator::validate($api_input_rules, $userids, '/', $error)) {
self::exception(ZBX_API_ERROR_PARAMETERS, $error);
}
$db_users = $this->get([
'output' => ['userid', 'alias'],
'userids' => $userids,
'editable' => true,
'preservekeys' => true
]);
foreach ($userids as $userid) {
if (!array_key_exists($userid, $db_users)) {
self::exception(ZBX_API_ERROR_PERMISSIONS,
_('No permissions to referred object or it does not exist!')
);
}
$db_user = $db_users[$userid];
if (bccomp($userid, self::$userData['userid']) == 0) {
self::exception(ZBX_API_ERROR_PARAMETERS, _('User is not allowed to delete himself.'));
}
if ($db_user['alias'] == ZBX_GUEST_USER) {
self::exception(ZBX_API_ERROR_PARAMETERS,
_s('Cannot delete Zabbix internal user "%1$s", try disabling that user.', ZBX_GUEST_USER)
);
}
}
// Check if deleted users used in actions.
$db_actions = DBselect(
'SELECT a.name,om.userid'.