-
Notifications
You must be signed in to change notification settings - Fork 19
/
lib-security.php
2018 lines (1758 loc) · 67.7 KB
/
lib-security.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
/* Reminder: always indent with 4 spaces (no tabs). */
// +---------------------------------------------------------------------------+
// | Geeklog 2.1 |
// +---------------------------------------------------------------------------+
// | lib-security.php |
// | |
// | Geeklog security library. |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2000-2010 by the following authors: |
// | |
// | Authors: Tony Bibbs - tony AT tonybibbs DOT com |
// | Mark Limburg - mlimburg AT users DOT sourceforge DOT net |
// | Vincent Furia - vmf AT abtech DOT org |
// | Michael Jervis - mike AT fuckingbrit DOT com |
// | Dirk Haun - dirk AT haun-online DOT de |
// +---------------------------------------------------------------------------+
// | |
// | 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. |
// | |
// +---------------------------------------------------------------------------+
/**
* This is the security library for Geeklog. This is used to implement Geeklog's
* *nix-style security system.
* Programming notes: For items you need security on you need the following for
* each record in your database:
* owner_id | mediumint(8)
* group_id | mediumint(8)
* perm_owner | tinyint(1) unsigned
* perm_group | tinyint(1) unsigned
* perm_members | tinyint(1) unsigned
* perm_anon | tinyint(1) unsigned
* For display one function can handle most needs:
* function SEC_hasAccess($owner_id,$group_id,$perm_owner,$perm_group,$perm_members,$perm_anon)
* A call to this function will allow you to determine if the current user should see the item.
* For the admin screen several functions will make life easier:
* function SEC_getPermissionsHTML($perm_owner,$perm_group,$perm_members,$perm_anon)
* This function displays the permissions widget with arrays for each permission
* function SEC_getPermissionValues($perm_owner,$perm_group,$perm_members,$perm_anon)
* This function takes the permissions from the previous function and converts them into
* an integer for saving back to the database.
*/
// Turn this on to get various debug messages from the code in this library
$_SEC_VERBOSE = false;
if (stripos($_SERVER['PHP_SELF'], 'lib-security.php') !== false) {
die('This file can not be used on its own!');
}
/* Constants for account stats */
define('USER_ACCOUNT_DISABLED', 0); // Account is banned/disabled
define('USER_ACCOUNT_AWAITING_ACTIVATION', 1); // Account awaiting user to login.
define('USER_ACCOUNT_AWAITING_APPROVAL', 2); // Account awaiting moderator approval
define('USER_ACCOUNT_ACTIVE', 3); // active account
/* Constant for Security Token */
if (!defined('CSRF_TOKEN')) {
define('CSRF_TOKEN', '_glsectoken');
}
/**
* Returns the groups a user belongs to
*
* This is part of the GL security implementation. This function returns
* all the groups a user belongs to. This function is called recursively
* as groups can belong to other groups
*
* Note: this is an expensive function -- if you are concerned about speed it should only
* be used once at the beginning of a page. The resulting array $_GROUPS can then be
* used through out the page.
*
* @param int $uid User ID to get information for. If empty current user.
* @return array Associative Array grp_name -> ug_main_grp_id of group ID's user belongs to
*
*/
function SEC_getUserGroups($uid='')
{
global $_TABLES, $_USER, $_SEC_VERBOSE, $_USER_MAINGROUPS;
if ($_SEC_VERBOSE) {
COM_errorLog("****************in getusergroups(uid=$uid,usergroups=$usergroups,cur_grp_id=$cur_grp_id)***************",1);
}
$groups = array();
if (empty($uid)) {
if (empty($_USER['uid'])) {
$uid = 1;
} else {
$uid = $_USER['uid'];
}
} else {
$_USER_MAINGROUPS = array();
$tuid = $uid;
}
$result = DB_query("SELECT ug_main_grp_id,grp_name FROM {$_TABLES["group_assignments"]},{$_TABLES["groups"]}"
. " WHERE grp_id = ug_main_grp_id AND ug_uid = $uid", 1);
if ($result === false) {
return $groups;
}
$nrows = DB_numRows($result);
if ($_SEC_VERBOSE) {
COM_errorLog("got $nrows rows",1);
}
while ($nrows > 0) {
$cgroups = array();
for ($i = 1; $i <= $nrows; $i++) {
$A = DB_fetchArray($result);
if ($_SEC_VERBOSE) {
COM_errorLog('user is in group ' . $A['grp_name'], 1);
}
if (!in_array($A['ug_main_grp_id'], $groups)) {
array_push($cgroups, $A['ug_main_grp_id']);
$groups[$A['grp_name']] = $A['ug_main_grp_id'];
}
}
if (count($cgroups) > 0) {
if (empty($_USER_MAINGROUPS) && !empty($tuid)) { $_USER_MAINGROUPS = $cgroups; }
$glist = implode(',', $cgroups);
$result = DB_query("SELECT ug_main_grp_id,grp_name FROM {$_TABLES["group_assignments"]},{$_TABLES["groups"]}"
. " WHERE grp_id = ug_main_grp_id AND ug_grp_id IN ($glist)", 1);
$nrows = DB_numRows($result);
} else {
$nrows = 0;
}
}
uksort($groups, 'strcasecmp');
if ($_SEC_VERBOSE) {
COM_errorLog("****************leaving getusergroups(uid=$uid)***************",1);
}
return $groups;
}
/**
* Checks to see if a user has admin access to the "Remote Users" group
* Admin users will probably not be members, but, User Admin, Root, and
* group admin will have access to it. However, we can not be sure what
* the group id for "Remote User" group is, because it's a later static
* group, and upgraded systems could have it in any id slot.
*
* @param groupid int The id of a group, which might be the remote users group
* @param groups array Array of group ids the user has access to.
* @return boolean
*/
function SEC_groupIsRemoteUserAndHaveAccess($groupid, $groups)
{
global $_TABLES, $_CONF;
if (!isset($_CONF['remote_users_group_id'])) {
$result = DB_query("SELECT grp_id FROM {$_TABLES['groups']} WHERE grp_name='Remote Users'");
if ($result) {
$row = DB_fetchArray($result);
$_CONF['remote_users_group_id'] = $row['grp_id'];
}
}
if ($groupid == $_CONF['remote_users_group_id']) {
if (in_array(1, $groups) || // root
in_array(9, $groups) || // user admin
in_array(11, $groups) // Group admin
) {
return true;
} else {
return false;
}
} else {
return false;
}
}
/**
* Determines if user belongs to specified group
* This is part of the Geeklog security implementation. This function
* looks up whether a user belongs to a specified group
*
* @param string $grp_to_verify Group we want to see if user belongs to
* @param int $uid ID for user to check. If empty current user.
* @param string $cur_grp_id NOT USED Current group we are working with in hierarchy
* @return boolean true if user is in group, otherwise false
*/
function SEC_inGroup($grp_to_verify, $uid = '', $cur_grp_id = '')
{
global $_USER, $_GROUPS;
if (empty($uid)) {
if (empty($_USER['uid'])) {
$uid = 1;
} else {
$uid = $_USER['uid'];
}
}
if ((empty($_USER['uid']) && ($uid == 1)) ||
(isset($_USER['uid']) && ($uid == $_USER['uid']))
) {
if (empty($_GROUPS)) {
$_GROUPS = SEC_getUserGroups($uid);
}
$groups = $_GROUPS;
} else {
$groups = SEC_getUserGroups($uid);
}
if (is_numeric($grp_to_verify)) {
return in_array($grp_to_verify, $groups);
} else {
return !empty($groups[$grp_to_verify]);
}
}
/**
* Determines if current user is a moderator of any kind
* Checks to see if this user is a moderator for any of the GL features OR
* GL plugins
*
* @return boolean returns if user has any .moderate rights
*/
function SEC_isModerator()
{
global $_RIGHTS;
// Loop through GL core rights.
for ($i = 0; $i < count($_RIGHTS); $i++) {
if (stristr($_RIGHTS[$i], '.moderate')) {
return true;
}
}
// If we get this far they are not a Geeklog moderator
// So, let's return if they're a plugin moderator
return PLG_isModerator();
}
/**
* Checks to see if current user has access to a configuration
*
* @return boolean returns if user has any config. rights
*/
function SEC_hasConfigAccess()
{
global $_CONF_FT;
if (SEC_hasRights($_CONF_FT, 'OR')) {
return true;
}
return false;
}
/**
* Deprecated - use SEC_hasConfigAccess instead
*
* @deprecated since Geeklog 2.0.0
* @see SEC_hasConfigAccess
*/
function SEC_hasConfigAcess()
{
COM_deprecatedLog(__FUNCTION__, '2.0.0', '3.0.0', 'SEC_hasConfigAccess');
return SEC_hasConfigAccess();
}
/**
* Checks to see if current user has access to a admin moderation page
*
* @return boolean
*/
function SEC_hasModerationAccess()
{
global $_CONF;
$hasAccess = false;
if (SEC_hasRights('story.moderate')) {
$hasAccess = true;
}
if ($_CONF['listdraftstories'] == 1) {
if (SEC_hasRights('story.edit')) {
$hasAccess = true;
}
}
if ($_CONF['commentsubmission'] == 1) {
if (SEC_hasRights('comment.moderate')) {
$hasAccess = true;
}
}
if ($_CONF['usersubmission'] == 1) {
if (SEC_hasRights('user.edit') && SEC_hasRights('user.delete')) {
$hasAccess = true;
}
}
if (PLG_isModerator()) {
$hasAccess = false;
}
return $hasAccess;
}
/**
* Checks to see if current user has access to a topic
*
* @param string $tid ID for topic to check on
* @return int returns 3 for read/edit 2 for read only 0 for no access
*/
function SEC_hasTopicAccess($tid)
{
global $_TABLES;
if (empty($tid)) {
return 0;
}
$result = DB_query("SELECT owner_id,group_id,perm_owner,perm_group,perm_members,perm_anon FROM {$_TABLES['topics']} WHERE tid = '$tid'");
$A = DB_fetchArray($result);
return SEC_hasAccess($A['owner_id'], $A['group_id'], $A['perm_owner'], $A['perm_group'], $A['perm_members'], $A['perm_anon']);
}
/**
* Checks if current user has access to the given object
* This function takes the access info from a Geeklog object
* and let's us know if they have access to the object
* returns 3 for read/edit, 2 for read only and 0 for no
* access
*
* @param int $owner_id ID of the owner of object
* @param int $group_id ID of group object belongs to
* @param int $perm_owner Permissions the owner has
* @param int $perm_group Permissions the gorup has
* @param int $perm_members Permissions logged in members have
* @param int $perm_anon Permissions anonymous users have
* @param int $uid User id or 0 = current user
* @return int returns 3 for read/edit 2 for read only 0 for no access
*/
function SEC_hasAccess($owner_id, $group_id, $perm_owner, $perm_group, $perm_members, $perm_anon, $uid = 0)
{
global $_USER;
if ($uid == 0) {
// Cache current user id
if (empty($_USER['uid'])) {
$uid = 1;
} else {
$uid = $_USER['uid'];
}
}
// If user is in Root group then return full access
if (SEC_inGroup('Root', $uid)) {
return 3;
}
// If user is owner then return 1 now
if ($uid == $owner_id) {
return $perm_owner;
}
// Not private, if user is in group then give access
if (SEC_inGroup($group_id, $uid)) {
return $perm_group;
} else {
if ($uid == 1) {
// This is an anonymous user, return it's rights
return $perm_anon;
} else {
// This is a logged in member, return their rights
return $perm_members;
}
}
}
/**
* Checks if current user has rights to a feature
* Takes either a single feature or an array of features and returns
* an array of whether the user has those rights
*
* @param string|array $features Features to check
* @param string $operator Either 'and' or 'or'. Default is 'and'. Used if checking more than one feature.
* @return boolean Return true if current user has access to feature(s), otherwise false.
*/
function SEC_hasRights($features, $operator = 'AND')
{
global $_RIGHTS, $_SEC_VERBOSE;
if (is_string($features) && strstr($features, ',')) {
$features = explode(',', $features);
}
if (is_array($features)) {
// check all values passed
for ($i = 0; $i < count($features); $i++) {
if ($operator == 'OR') {
// OR operator, return as soon as we find a true one
if (in_array($features[$i], $_RIGHTS)) {
if ($_SEC_VERBOSE) {
COM_errorLog('SECURITY: user has access to ' . $features[$i], 1);
}
return true;
}
} else {
// this is an "AND" operator, bail if we find a false one
if (!in_array($features[$i], $_RIGHTS)) {
if ($_SEC_VERBOSE) {
COM_errorLog('SECURITY: user does not have access to ' . $features[$i], 1);
}
return false;
}
}
}
if ($operator == 'OR') {
if ($_SEC_VERBOSE) {
COM_errorLog('SECURITY: user does not have access to ' . $features[$i], 1);
}
return false;
} else {
if ($_SEC_VERBOSE) {
COM_errorLog('SECURITY: user has access to ' . $features[$i], 1);
}
return true;
}
} else {
// Check the one value
if ($_SEC_VERBOSE) {
if (in_array($features, $_RIGHTS)) {
COM_errorLog('SECURITY: user has access to ' . $features, 1);
} else {
COM_errorLog('SECURITY: user does not have access to ' . $features, 1);
}
}
return in_array($features, $_RIGHTS);
}
}
/**
* Shows security control for an object
* This will return the HTML needed to create the security control seen on the
* admin screen for GL objects (i.e. stories, etc)
*
* @param int $perm_owner Permissions the owner has 1 = edit 2 = read 3 = read/edit
* @param int $perm_group Permission the group has
* @param int $perm_members Permissions logged in members have
* @param int $perm_anon Permissions anonymous users have
* @return string needed HTML (table) in HTML $perm_owner = array of permissions [edit,read], etc edit = 1 if
* permission, read = 2 if permission
*/
function SEC_getPermissionsHTML($perm_owner, $perm_group, $perm_members, $perm_anon)
{
global $_CONF, $LANG_ACCESS;
$retval = '';
$perm_templates = COM_newTemplate($_CONF['path_layout'] . 'admin/common');
$perm_templates->set_file(array('editor' => 'edit_permissions.thtml'));
$perm_templates->set_var('lang_owner', $LANG_ACCESS['owner']);
$perm_templates->set_var('owner', $LANG_ACCESS['owner']);
$perm_templates->set_var('lang_group', $LANG_ACCESS['group']);
$perm_templates->set_var('group', $LANG_ACCESS['group']);
$perm_templates->set_var('lang_members', $LANG_ACCESS['members']);
$perm_templates->set_var('members', $LANG_ACCESS['members']);
$perm_templates->set_var('lang_anonymous', $LANG_ACCESS['anonymous']);
$perm_templates->set_var('anonymous', $LANG_ACCESS['anonymous']);
// Owner Permissions
if ($perm_owner >= 2) {
$perm_templates->set_var('owner_r_checked', ' checked="checked"');
}
if ($perm_owner == 3) {
$perm_templates->set_var('owner_e_checked', ' checked="checked"');
}
// Group Permissions
if ($perm_group >= 2) {
$perm_templates->set_var('group_r_checked', ' checked="checked"');
}
if ($perm_group == 3) {
$perm_templates->set_var('group_e_checked', ' checked="checked"');
}
// Member Permissions
if ($perm_members == 2) {
$perm_templates->set_var('members_checked', ' checked="checked"');
}
// Anonymous Permissions
if ($perm_anon == 2) {
$perm_templates->set_var('anon_checked', ' checked="checked"');
}
$perm_templates->parse('output', 'editor');
$retval .= $perm_templates->finish($perm_templates->get_var('output'));
return $retval;
}
/**
* Gets everything a user has permissions to within the system
* This is part of the Geeklog security implementation. This function
* will get all the permissions the current user has. Calls itself recursively.
*
* @param int $grp_id DO NOT USE (Used for recursion) Current group function is working on
* @param int $uid User to check, if empty current user.
* @return string returns comma delimited list of features the user has access to
*/
function SEC_getUserPermissions($grp_id = '', $uid = '')
{
global $_TABLES, $_USER, $_SEC_VERBOSE, $_GROUPS;
$retval = '';
if ($_SEC_VERBOSE) {
COM_errorLog("**********inside SEC_getUserPermissions(grp_id=$grp_id)**********", 1);
}
// Get user ID if we don't already have it
if (empty($uid)) {
if (empty($_USER['uid'])) {
$uid = 1;
} else {
$uid = $_USER['uid'];
}
}
if ((empty($_USER['uid']) && ($uid == 1)) || (!empty($_USER['uid']) && ($uid == $_USER['uid']))) {
if (empty($_GROUPS)) {
$_GROUPS = SEC_getUserGroups($uid);
}
$groups = $_GROUPS;
} else {
$groups = SEC_getUserGroups($uid);
}
if (empty($groups)) {
// this shouldn't happen - make a graceful exit to avoid an SQL error
return '';
}
$glist = implode(',', $groups);
$result = DB_query("SELECT DISTINCT ft_name FROM {$_TABLES["access"]},{$_TABLES["features"]} "
. "WHERE ft_id = acc_ft_id AND acc_grp_id IN ($glist)");
$nrows = DB_numrows($result);
for ($j = 1; $j <= $nrows; $j++) {
$A = DB_fetchArray($result);
if ($_SEC_VERBOSE) {
COM_errorLog('Adding right ' . $A['ft_name'] . ' in SEC_getUserPermissions', 1);
}
$retval .= $A['ft_name'];
if ($j < $nrows) {
$retval .= ',';
}
}
return $retval;
}
/**
* Converts permissions to numeric values
* This function will take all permissions for an object and get the numeric value
* that can then be used to save the database.
*
* @param array $perm_owner Array of owner permissions These arrays are set up by SEC_getPermissionsHTML
* @param array $perm_group Array of group permissions
* @param array $perm_members Array of member permissions
* @param array $perm_anon Array of anonymous user permissions
* @return array returns numeric equivalent for each permissions array (2 = read, 3=edit/read)
* @see SEC_getPermissionsHTML
* @see SEC_getPermissionValue
*/
function SEC_getPermissionValues($perm_owner, $perm_group, $perm_members, $perm_anon)
{
global $_SEC_VERBOSE;
if ($_SEC_VERBOSE) {
COM_errorLog('**** Inside SEC_getPermissionValues ****', 1);
}
if (is_array($perm_owner)) {
$perm_owner = SEC_getPermissionValue($perm_owner);
} else {
$perm_owner = 0;
}
if (is_array($perm_group)) {
$perm_group = SEC_getPermissionValue($perm_group);
} else {
$perm_group = 0;
}
if (is_array($perm_members)) {
$perm_members = SEC_getPermissionValue($perm_members);
} else {
$perm_members = 0;
}
if (is_array($perm_anon)) {
$perm_anon = SEC_getPermissionValue($perm_anon);
} else {
$perm_anon = 0;
}
if ($_SEC_VERBOSE) {
COM_errorLog('perm_owner = ' . $perm_owner, 1);
COM_errorLog('perm_group = ' . $perm_group, 1);
COM_errorLog('perm_member = ' . $perm_members, 1);
COM_errorLog('perm_anon = ' . $perm_anon, 1);
COM_errorLog('**** Leaving SEC_getPermissionValues ****', 1);
}
return array($perm_owner, $perm_group, $perm_members, $perm_anon);
}
/**
* Converts permission array into numeric value
* This function converts an array of permissions for either
* the owner/group/members/anon and returns the numeric
* equivalent. This is typically called by the admin screens
* to prepare the permissions to be save to the database
*
* @param array $perm_x Array of permission values
* @return int int representation of a permission array 2 = read 3 = edit/read
* @see SEC_getPermissionValues
*/
function SEC_getPermissionValue($perm_x)
{
global $_SEC_VERBOSE;
if ($_SEC_VERBOSE) {
COM_errorLog('**** Inside SEC_getPermissionValue ***', 1);
}
$retval = 0;
for ($i = 1; $i <= count($perm_x); $i++) {
if ($_SEC_VERBOSE) {
COM_errorLog("perm_x[$i] = " . current($perm_x), 1);
}
$retval = $retval + current($perm_x);
next($perm_x);
}
// if they have edit rights, assume read rights
if ($retval == 1) {
$retval = 3;
}
if ($_SEC_VERBOSE) {
COM_errorLog("Got $retval permission value", 1);
COM_errorLog('**** Leaving SEC_getPermissionValue ***', 1);
}
return $retval;
}
/**
* Return the group to a given feature.
* Scenario: We have a feature and we want to know from which group the user
* got this feature. Always returns the lowest group ID, in case the feature
* has been inherited from more than one group.
*
* @param string $feature the feature, e.g 'story.edit'
* @param int $uid (optional) user ID
* @return int group ID or 0
*/
function SEC_getFeatureGroup($feature, $uid = '')
{
global $_GROUPS, $_TABLES, $_USER;
$ugroups = array();
if (empty($uid)) {
if (empty($_USER['uid'])) {
$uid = 1;
} else {
$uid = $_USER['uid'];
}
}
if ((empty($_USER['uid']) && ($uid == 1)) || ($uid == $_USER['uid'])) {
if (empty($_GROUPS)) {
$_GROUPS = SEC_getUserGroups($uid);
}
$ugroups = $_GROUPS;
} else {
$ugroups = SEC_getUserGroups($uid);
}
$group = 0;
$ft_id = DB_getItem($_TABLES['features'], 'ft_id', "ft_name = '$feature'");
if (($ft_id > 0) && (count($ugroups) > 0)) {
$grouplist = implode(',', $ugroups);
$result = DB_query("SELECT acc_grp_id FROM {$_TABLES['access']} WHERE (acc_ft_id = $ft_id) AND (acc_grp_id IN ($grouplist)) ORDER BY acc_grp_id LIMIT 1");
$A = DB_fetchArray($result);
if (isset($A['acc_grp_id'])) {
$group = $A['acc_grp_id'];
}
}
return $group;
}
/**
* Attempt to login a user.
* Checks a users username and password against the database. Returns
* users status.
*
* @param string $username who is logging in?
* @param string $password what they claim is their password
* @param int $uid This is an OUTPUT param, pass by ref,
* sends back UID inside it.
* @return int user status, -1 for fail.
*/
function SEC_authenticate($username, $password, &$uid)
{
global $_CONF, $_TABLES, $LANG01;
$password = str_replace(array("\015", "\012"), '', $password);
$result = DB_query("SELECT status, passwd, email, uid FROM {$_TABLES['users']} WHERE username='$username' AND ((remoteservice is null) or (remoteservice = ''))");
$tmp = DB_error();
$nrows = DB_numRows($result);
if (($tmp == 0) && ($nrows == 1)) {
$U = DB_fetchArray($result);
$uid = $U['uid'];
if ($U['status'] == USER_ACCOUNT_DISABLED) {
// banned, jump to here to save an password hash calc.
return USER_ACCOUNT_DISABLED;
} elseif (SEC_encryptUserPassword($password, $uid) < 0) {
return -1; // failed login
} elseif ($U['status'] == USER_ACCOUNT_AWAITING_APPROVAL) {
return USER_ACCOUNT_AWAITING_APPROVAL;
} elseif ($U['status'] == USER_ACCOUNT_AWAITING_ACTIVATION) {
// Awaiting user activation, activate:
DB_change($_TABLES['users'], 'status', USER_ACCOUNT_ACTIVE,
'username', $username);
return USER_ACCOUNT_ACTIVE;
} else {
return $U['status']; // just return their status
}
} else {
$tmp = $LANG01[32] . ": '" . $username . "'";
COM_accessLog($tmp);
return -1;
}
}
/**
* Return the current user status for a user.
* NOTE: May not return for banned/non-approved users.
*
* @param int $userid Valid uid value.
* @return int user status, 0-3
*/
function SEC_checkUserStatus($userid)
{
global $_CONF, $_TABLES;
// Check user status
$status = DB_getItem($_TABLES['users'], 'status', "uid=$userid");
// only do redirects if we aren't on users.php in a valid mode (logout or
// default)
if (strpos($_SERVER['PHP_SELF'], 'users.php') === false) {
$redirect = true;
} else {
if (empty($_REQUEST['mode']) || (Geeklog\Input::request('mode') === 'logout')) {
$redirect = false;
} else {
$redirect = true;
}
}
if ($status == USER_ACCOUNT_AWAITING_ACTIVATION) {
DB_change($_TABLES['users'], 'status', USER_ACCOUNT_ACTIVE, 'uid', $userid);
} elseif ($status == USER_ACCOUNT_AWAITING_APPROVAL) {
// If we aren't on users.php with a default action then go to it
if ($redirect) {
COM_accessLog("SECURITY: Attempted Cookie Session login from user awaiting approval $userid.");
COM_redirect($_CONF['site_url'] . '/users.php?msg=70');
}
} elseif ($status == USER_ACCOUNT_DISABLED) {
if ($redirect) {
COM_accessLog("SECURITY: Attempted Cookie Session login from banned user $userid.");
COM_redirect($_CONF['site_url'] . '/users.php?msg=69');
}
}
return $status;
}
/**
* Check to see if we can authenticate this user with a remote server
* A user has not managed to login localy, but has an @ in their user
* name and we have enabled distributed authentication. Firstly, try to
* see if we have cached the module that we used to authenticate them
* when they signed up (i.e. they've actualy changed their password
* elsewhere and we need to synch.) If not, then try to authenticate
* them with /every/ authentication module. If this suceeds, create
* a user for them.
*
* @param string $loginname Their username
* @param string $passwd The password entered
* @param string $service The service portion of $username
* @param string $uid OUTPUT parameter, pass it by ref to get uid back.
* @return int user status, -1 for fail.
*/
function SEC_remoteAuthentication(&$loginname, $passwd, $service, &$uid)
{
global $_CONF, $_TABLES;
/* First try a local cached login */
$remoteusername = DB_escapeString($loginname);
$remoteservice = DB_escapeString($service);
$result = DB_query("SELECT passwd, status, uid FROM {$_TABLES['users']} WHERE remoteusername='$remoteusername' AND remoteservice='$remoteservice'");
$tmp = DB_error();
$nrows = DB_numRows($result);
if (($tmp == 0) && ($nrows == 1)) {
$U = DB_fetchArray($result);
$uid = $U['uid'];
$mypass = $U['passwd']; // also used to see if the user existed later.
if ($mypass == SEC_encryptPassword($passwd)) {
/* Valid password for cached user, return status */
return $U['status'];
}
}
$service = COM_sanitizeFilename($service);
$servicefile = $_CONF['path_system'] . 'classes/authentication/' . $service
. '.auth.class.php';
if (file_exists($servicefile)) {
require_once $servicefile;
$authmodule = new $service();
if ($authmodule->authenticate($loginname, $passwd)) {
/* check to see if they have logged in before: */
if (empty($mypass)) {
// no such user, create them
// Check to see if their remoteusername is unique locally
$checkName = DB_getItem($_TABLES['users'], 'username',
"username='$remoteusername'");
if (!empty($checkName)) {
// no, call custom function.
if (function_exists('CUSTOM_uniqueRemoteUsername')) {
$loginname = CUSTOM_uniqueRemoteUsername($loginname,
$service);
}
}
USER_createAccount($loginname, $authmodule->email, $passwd, $authmodule->fullname, $authmodule->homepage, $remoteusername, $remoteservice);
$uid = DB_getItem($_TABLES['users'], 'uid', "remoteusername = '$remoteusername' AND remoteservice='$remoteservice'");
// Store full remote account name:
DB_query("UPDATE {$_TABLES['users']} SET remoteusername='$remoteusername', remoteservice='$remoteservice', status=3 WHERE uid='$uid'");
// Add to remote users:
$remote_grp = DB_getItem($_TABLES['groups'], 'grp_id',
"grp_name='Remote Users'");
DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id,ug_uid) VALUES ($remote_grp, $uid)");
return 3; // Remote auth precludes usersubmission,
// and integrates user activation, see?
} else {
// user existed, update local password:
DB_change($_TABLES['users'], 'passwd', SEC_encryptPassword($passwd), array('remoteusername', 'remoteservice'), array($remoteusername, $remoteservice));
// and return their status
return DB_getItem($_TABLES['users'], 'status', "remoteusername='$remoteusername' AND remoteservice='$remoteservice'");
}
} else {
return -1;
}
} else {
return -1;
}
}
/**
* Return available modules for Remote Authentication
*
* @return array Names of available remote authentication modules
*/
function SEC_collectRemoteAuthenticationModules()
{
global $_CONF;
$modules = array();
$modulespath = $_CONF['path_system'] . 'classes/authentication/';
if (is_dir($modulespath)) {
$folder = opendir($modulespath);
while (($filename = @readdir($folder)) !== false) {
$pos = strpos($filename, '.auth.class.php');
if ($pos && (substr($filename, strlen($filename) - 4) == '.php')) {
$modules[] = substr($filename, 0, $pos);
}
}
}
return $modules;
}
/**
* Add user to a group
* work in progress
* Rather self explanitory shortcut function
* Is this the right place for this, Dirk?
*
* @author Trinity L Bays, trinity93 AT gmail DOT com
* @param string $uid Their user id
* @param string $gname The group name
* @return boolean status, true or false.
*/
function SEC_addUserToGroup($uid, $gname)
{
global $_TABLES, $_CONF;
$remote_grp = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name='" . $gname . "'");
DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id,ug_uid) VALUES ($remote_grp, $uid)");
}
/**
* Set default permissions for an object
*
* @param array $A target array
* @param array $use_permissions permissions to set
*/
function SEC_setDefaultPermissions(&$A, $use_permissions = array())
{
if (!is_array($use_permissions) || (count($use_permissions) != 4)) {
$use_permissions = array(3, 2, 2, 2);
}
// sanity checks
if (($use_permissions[0] > 3) || ($use_permissions[0] < 0) ||
($use_permissions[0] == 1)
) {
$use_permissions[0] = 3;
}
if (($use_permissions[1] > 3) || ($use_permissions[1] < 0) ||
($use_permissions[1] == 1)
) {
$use_permissions[1] = 2;
}
if (($use_permissions[2] != 2) && ($use_permissions[2] != 0)) {
$use_permissions[2] = 2;
}
if (($use_permissions[3] != 2) && ($use_permissions[3] != 0)) {
$use_permissions[3] = 2;
}
$A['perm_owner'] = $use_permissions[0];
$A['perm_group'] = $use_permissions[1];
$A['perm_members'] = $use_permissions[2];
$A['perm_anon'] = $use_permissions[3];
}
/**
* Common function used to build group access SQL
*
* @param string $clause Optional parm 'WHERE' - default is 'AND'
* @return string $groupsql Formatted SQL string to be appended in calling script SQL statement
*/
function SEC_buildAccessSql($clause = 'AND')
{
global $_TABLES, $_USER;