forked from zikula/core
/
UserUtil.php
2142 lines (1892 loc) · 97.1 KB
/
UserUtil.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
/**
* Copyright Zikula Foundation 2009 - Zikula Application Framework
*
* This work is contributed to the Zikula Foundation under one or more
* Contributor Agreements and licensed to You under the following license:
*
* @license GNU/LGPv3 (or at your option any later version).
* @package Util
*
* Please see the NOTICE file distributed with this source code for further
* information regarding copyright and licensing.
*/
/**
* UserUtil
*/
class UserUtil
{
/**
* Cache for groups.
*
* @var array
*/
protected static $groupCache = array();
/**
* Clear group cache.
*
* @return void
*/
public function clearGroupCache()
{
self::$groupCache = array();
}
/**
* Return a user object.
*
* @param integer $uid The userID of the user to retrieve.
* @param boolean $getVars Obsolete, we also return the attributes.
*
* @deprecated since 1.3.0
* @see self::getVars()
*
* @return array The resulting user object.
*/
public static function getPNUser($uid, $getVars = false)
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getVars')), E_USER_DEPRECATED);
return self::getVars($uid);
}
/**
* Return a field from a user object.
*
* @param integer $id The userID of the user to retrieve.
* @param string $field The field from the user object to get.
*
* @deprecated since 1.3.0
* @see self::getVars()
*
* @return mixed The requested field.
*/
public static function getPNUserField($id, $field)
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getVar')), E_USER_DEPRECATED);
return self::getVar($field, $id);
}
/**
* Return a hash structure mapping uid to username.
*
* @param string $where The where clause to use (optional).
* @param string $orderBy The order by clause to use (optional).
* @param integer $limitOffset The select-limit offset (optional) (default=-1).
* @param integer $limitNumRows The number of rows to fetch (optional) (default=-1).
* @param string $assocKey The associative key to apply (optional) (default='gid').
*
* @deprecated since 1.3.0
*
* @return array An array mapping uid to username.
*/
public static function getPNUsers($where = '', $orderBy = '', $limitOffset = -1, $limitNumRows = -1, $assocKey = 'uid')
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getUsers')), E_USER_DEPRECATED);
return self::getUsers($where, $orderBy, $limitOffset, $limitNumRows, $assocKey);
}
/**
* Return a hash structure mapping uid to username.
*
* @param string $where The where clause to use (optional).
* @param string $orderBy The order by clause to use (optional).
* @param integer $limitOffset The select-limit offset (optional) (default=-1).
* @param integer $limitNumRows The number of rows to fetch (optional) (default=-1).
* @param string $assocKey The associative key to apply (optional) (default='gid').
*
* @deprecated since 1.3.0
*
* @return array An array mapping uid to username.
*/
public static function getUsers($where = '', $orderBy = '', $limitOffset = -1, $limitNumRows = -1, $assocKey = 'uid')
{
return DBUtil::selectObjectArray('users', $where, $orderBy, $limitOffset, $limitNumRows, $assocKey);
}
/**
* Return a group object.
*
* @param integer $gid The groupID to retrieve.
*
* @deprecated since 1.3.0
* @see UserUtil::getGroup()
*
* @return array The resulting group object.
*/
public static function getPNGroup($gid)
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getGroup')), E_USER_DEPRECATED);
return self::getGroup($gid);
}
/**
* Return a group object.
*
* @param integer $gid The groupID to retrieve.
*
* @todo Decouple UserUtil and Groups?
*
* @return array The resulting group object.
*/
public static function getGroup($gid)
{
return DBUtil::selectObjectByID('groups', $gid, 'gid');
}
/**
* Return a hash structure mapping gid to groupname.
*
* @param string $where The where clause to use (optional) (default='').
* @param string $orderBy The order by clause to use (optional) (default='').
* @param integer $limitOffset The select-limit offset (optional) (default=-1).
* @param integer $limitNumRows The number of rows to fetch (optional) (default=-1).
* @param string $assocKey The associative key to apply (optional) (default='gid').
*
* @deprecated since 1.3.0
*
* @return array An array mapping gid to groupname
*/
public static function getPNGroups($where = '', $orderBy = '', $limitOffset = -1, $limitNumRows = -1, $assocKey = 'gid')
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getGroups')), E_USER_DEPRECATED);
return self::getGroups();
}
/**
* Return a hash structure mapping gid to groupname.
*
* @param string $where The where clause to use (optional) (default='').
* @param string $orderBy The order by clause to use (optional) (default='').
* @param integer $limitOffset The select-limit offset (optional) (default=-1).
* @param integer $limitNumRows The number of rows to fetch (optional) (default=-1).
* @param string $assocKey The associative key to apply (optional) (default='gid').
*
* @return array An array mapping gid to groupname.
*/
public static function getGroups($where = '', $orderBy = '', $limitOffset = -1, $limitNumRows = -1, $assocKey = 'gid')
{
return DBUtil::selectObjectArray('groups', $where, $orderBy, $limitOffset, $limitNumRows, $assocKey);
}
/**
* Return a (string) list of user-ids which can then be used in a SQL 'IN (...)' clause.
*
* @param string $where The where clause to use (optional).
* @param string $orderBy The order by clause to use (optional).
* @param string $separator The field separator to use (default=",") (optional).
*
* @deprecated since 1.3.0
* @see UserUtil::getUserIdList()
*
* @return string A string list of user ids.
*/
public static function getPNUserIdList($where = '', $orderBy = '', $separator = ',')
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getUserIdList')), E_USER_DEPRECATED);
return self::getUserIdList($where, $orderBy, $separator);
}
/**
* Return a (string) list of user-ids which can then be used in a SQL 'IN (...)' clause.
*
* @param string $where The where clause to use (optional).
* @param string $orderBy The order by clause to use (optional).
* @param string $separator The field separator to use (default=",") (optional).
*
* @return string A string list of user ids.
*/
public static function getUserIdList($where = '', $orderBy = '', $separator = ',')
{
$userdata = self::getUsers($where, $orderBy);
$list = '-1';
if ($userdata && count($userdata)) {
$uids = array_keys($userdata);
sort($uids);
$list = implode((string)$separator, $uids);
}
return $list;
}
/**
* Return a (string) list of group-ids which can then be used in a SQL 'IN (...)' clause.
*
* @param string $where The where clause to use (optional).
* @param string $orderBy The order by clause to use (optional).
* @param string $separator The field separator to use (default=",") (optional).
*
* @deprecated since 1.3.0
* @see UserUtil::getGroupIdList()
*
* @return string A string list of group ids
*/
public static function getPNGroupIdList($where = '', $orderBy = '', $separator = ',')
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getGroupIdList')), E_USER_DEPRECATED);
return self::getGroupIdList($where, $orderBy, $separator);
}
/**
* Return a (string) list of group-ids which can then be used in a SQL 'IN (...)' clause.
*
* @param string $where The where clause to use (optional).
* @param string $orderBy The order by clause to use (optional).
* @param string $separator The field separator to use (default=",") (optional).
*
* @return string A string list of group ids.
*/
public static function getGroupIdList($where = '', $orderBy = '', $separator = ',')
{
$groupdata = self::getGroups($where, $orderBy);
$list = '';
if ($groupdata && count($groupdata)) {
$gids = array_keys($groupdata);
sort($gids);
$list = implode((string)$separator, $gids);
}
return $list;
}
/**
* Return an array group-ids for the specified user.
*
* @param integer $uid The user ID for which we want the groups.
*
* @return array An array of group IDs.
*/
public static function getGroupsForUser($uid)
{
if (empty($uid)) {
return array();
}
$where = '';
if ($uid != -1) {
$where = "WHERE uid = '" . DataUtil::formatForStore($uid) . "'";
}
return DBUtil::selectFieldArray('group_membership', 'gid', $where);
}
/**
* Return a string list of group-ids for the specified user.
*
* @param integer $uid The user ID for which we want the groups.
* @param string $separator The field separator to use (default=",") (optional).
*
* @return string A string list of group ids.
*/
public static function getGroupListForUser($uid = null, $separator = ',')
{
if (!$uid) {
$uid = self::getVar('uid');
}
if (!$uid) {
return '-1';
}
if (!isset(self::$groupCache[$uid])) {
$gidArray = self::getGroupsForUser($uid);
if ($gidArray && (bool)count($gidArray)) {
sort($gidArray);
self::$groupCache[$uid] = implode((string)$separator, $gidArray);
} else {
self::$groupCache[$uid] = '-1';
}
}
return self::$groupCache[$uid];
}
/**
* Return a string list of user-ids for the specified group.
*
* @param integer $gid The group ID for which we want the users.
*
* @return array An array of user IDs.
*/
public static function getUsersForGroup($gid)
{
if (!$gid) {
return array();
}
$where = "WHERE gid = '" . DataUtil::formatForStore($gid) . "'";
return DBUtil::selectFieldArray('group_membership', 'uid', $where);
}
/**
* Get a unique string for a user, depending on this group memberships.
*
* String ready to be used as part of the CacheID of the output views.
* Useful when there aren't another user-based access privilegies, just group permissions.
*
* @param integer $uid User ID to get the group memberships from. Default: current user.
*
* @return string Cache GIDs string to use on Zikula_View.
*/
public static function getGidCacheString($uid = null)
{
$str = UserUtil::getGroupListForUser($uid, '_');
return $str == '-1' ? 'guest' : 'groups_'.$str;
}
/**
* Get a unique string for a user, based on the uid.
*
* String ready to be used as part of the CacheID of the output views.
* Useful for user-based access privilegies.
*
* @param integer $uid User ID to get string from. Default: current user.
*
* @return string Cache UID string to use on Zikula_View.
*/
public static function getUidCacheString($uid = null)
{
$uid = $uid ? (int)$uid : self::getVar('uid');
return !$uid ? 'guest' : 'uid_'.$uid;
}
/**
* Return the defined dynamic user data fields.
*
* @return array An array of dynamic data field definitions.
*/
public static function getDynamicDataFields()
{
// decide if we have to use the (obsolete) DUDs from the Profile module
$profileModule = System::getVar('profilemodule', '');
if (empty($profileModule) || $profileModule != 'Profile' || !ModUtil::available($profileModule)) {
return array();
}
ModUtil::dbInfoLoad($profileModule);
return DBUtil::selectObjectArray('user_property');
}
/**
* Return a string list of user-ids for the specified group.
*
* @param integer $uid The user ID for which we want the users.
* @param string $assocKey The associate Key to use.
* @param boolean $standardFields Whether or not to also marshall the standard user properties into the DUD array.
*
* @todo No this is not what this functions does, but what does it do? It is not used within the core
* @deprecated 1.3.0
*
* @return array An array of user IDs.
*/
public static function getUserDynamicDataFields($uid, $assocKey = 'uda_propid', $standardFields = false)
{
if (!$uid) {
return array();
}
return self::getVars($uid, '__ATTRIBUTES__');
}
/**
* Return a PN array structure for the PN user group selector.
*
* @param mixed $defaultValue The default value of the selector (default=0) (optional).
* @param string $defaultText The text of the default value (optional).
* @param array $ignore An array of keys to ignore (optional).
* @param mixed $includeAll Whether to include an "All" choice (optional).
* @param string $allText The text to display for the "All" choice (optional).
*
* @deprecated since 1.3.0
* @see UserUtil::getSelectorData_Group()
*
* @return array The array structure for the user group selector
*/
public static function getSelectorData_PNGroup($defaultValue = 0, $defaultText = '', $ignore = array(), $includeAll = 0, $allText = '')
{
LogUtil::log(__f('Warning! UserUtil::%1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::getSelectorData_Group')), E_USER_DEPRECATED);
return self::getSelectorData_Group($defaultValue, $defaultText, $ignore, $includeAll, $allText);
}
/**
* Return a array structure for the user group selector.
*
* @param mixed $defaultValue The default value of the selector (default=0) (optional).
* @param string $defaultText The text of the default value (optional).
* @param array $ignore An array of keys to ignore (optional).
* @param mixed $includeAll Whether to include an "All" choice (optional).
* @param string $allText The text to display for the "All" choice (optional).
*
* @return array The array structure for the user group selector.
*/
public static function getSelectorData_Group($defaultValue = 0, $defaultText = '', $ignore = array(), $includeAll = 0, $allText = '')
{
$dropdown = array();
if ($defaultText) {
$dropdown[] = array('id' => $defaultValue, 'name' => $defaultText);
}
$groupdata = self::getGroups('', 'ORDER BY name');
if (!$groupdata || !count($groupdata)) {
return $dropdown;
}
if ($includeAll) {
$dropdown[] = array('id' => $includeAll, 'name' => $allText);
}
foreach (array_keys($groupdata) as $gid) {
if (!isset($ignore[$gid])) {
$gname = $groupdata[$gid]['name'];
$dropdown[$gname] = array('id' => $gid, 'name' => $gname);
}
}
ksort($dropdown);
return $dropdown;
}
/**
* Return a array strcuture for the user dropdown box.
*
* @param miexed $defaultValue The default value of the selector (optional) (default=0).
* @param string $defaultText The text of the default value (optional) (default='').
* @param array $ignore An array of keys to ignore (optional) (default=array()).
* @param miexed $includeAll Whether to include an "All" choice (optional) (default=0).
* @param string $allText The text to display for the "All" choice (optional) (default='').
* @param string $exclude An SQL IN-LIST string to exclude specified uids.
*
* @return array The array structure for the user group selector.
*/
public static function getSelectorData_User($defaultValue = 0, $defaultText = '', $ignore = array(), $includeAll = 0, $allText = '', $exclude = '')
{
$dropdown = array();
if ($defaultText) {
$dropdown[] = array('id' => $defaultValue, 'name' => $defaultText);
}
$where = '';
if ($exclude) {
$where = "WHERE uid NOT IN (" . DataUtil::formatForStore($exclude) . ")";
}
$userdata = self::getUsers($where, 'ORDER BY uname');
if (!$userdata || !count($userdata)) {
return $dropdown;
}
if ($includeAll) {
$dropdown[] = array('id' => $includeAll, 'name' => $allText);
}
foreach (array_keys($userdata) as $uid) {
if (!isset($ignore[$uid])) {
$uname = $userdata[$uid]['uname'];
$dropdown[$uname] = array('id' => $uid, 'name' => $uname);
}
}
ksort($uname);
return $dropdown;
}
/**
* Retrieve the account recovery information for a user from the various authentication modules.
*
* @param numeric $uid The user id of the user for which account recovery information should be retrieved; optional, defaults to the
* currently logged in user (an exception occurs if the current user is not logged in).
*
* @return array An array of account recovery information.
*
* @throws Zikula_Exception_Fatal If the $uid parameter is not valid.
*/
public static function getUserAccountRecoveryInfo($uid = -1)
{
if (!isset($uid) || !is_numeric($uid) || ((string)((int)$uid) != $uid) || (($uid < -1) || ($uid == 0) || ($uid == 1))) {
throw new Zikula_Exception_Fatal('Attempt to get authentication information for an invalid user id.');
}
if ($uid == -1) {
if (self::isLoggedIn()) {
$uid = self::getVar('uid');
} else {
throw new Zikula_Exception_Fatal('Attempt to get authentication information for an invalid user id.');
}
}
$userAuthenticationInfo = array();
$authenticationModules = ModUtil::getModulesCapableOf(Users_Constant::CAPABILITY_AUTHENTICATION);
if ($authenticationModules) {
$accountRecoveryArgs = array (
'uid' => $uid,
);
foreach ($authenticationModules as $authenticationModule) {
$moduleUserAuthenticationInfo = ModUtil::apiFunc($authenticationModule['name'], 'authentication', 'getAccountRecoveryInfoForUid', $accountRecoveryArgs, 'Zikula_Api_AbstractAuthentication');
if (is_array($moduleUserAuthenticationInfo)) {
$userAuthenticationInfo = array_merge($userAuthenticationInfo, $moduleUserAuthenticationInfo);
}
}
}
return $userAuthenticationInfo;
}
/**
* Login.
*
* @param string $loginID Login Id.
* @param string $userEnteredPassword The Password.
* @param boolean $rememberme Whether or not to remember login.
* @param boolean $checkPassword Whether or not to check the password.
*
* @return boolean
*/
public static function login($loginID, $userEnteredPassword, $rememberme = false, $checkPassword = true)
{
LogUtil::log(__f('Warning! Function %1$s is deprecated. Please use %2$s instead.', array(__METHOD__, 'UserUtil::loginUsing()')), E_USER_DEPRECATED);
$authenticationInfo = array(
'login_id' => $loginID,
'pass' => $userEnteredPassword,
);
$authenticationMethod = array(
'modname' => 'Users',
);
if (ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_LOGIN_METHOD, Users_Constant::DEFAULT_LOGIN_METHOD) == Users_Constant::LOGIN_METHOD_EMAIL) {
$authenticationMethod['method'] = 'email';
} else {
$authenticationMethod['method'] = 'uname';
}
return self::loginUsing($authenticationMethod, $authenticationInfo, $rememberme, null, $checkPassword);
}
/**
* Validation method previous authentication.
*
* @param array $authenticationMethod Auth method.
* @param string $reentrantURL Reentrant URL (optional).
*
* @throws Zikula_Exception_Fatal
*
* @return true
*/
private static function preAuthenticationValidation(array $authenticationMethod, $reentrantURL = null)
{
if (empty($authenticationMethod) || (count($authenticationMethod) != 2)) {
throw new Zikula_Exception_Fatal(__f('An invalid %1$s parameter was received.', array('authenticationMethod')));
}
if (!isset($authenticationMethod['modname']) || !is_string($authenticationMethod['modname']) || empty($authenticationMethod['modname'])) {
throw new Zikula_Exception_Fatal(__f('An invalid %1$s parameter was received.', array('modname')));
} elseif (!ModUtil::getInfoFromName($authenticationMethod['modname'])) {
throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' could not be found.', array($authenticationMethod['modname'])));
} elseif (!ModUtil::available($authenticationMethod['modname'])) {
throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' is not available.', array($authenticationMethod['modname'])));
} elseif (!ModUtil::loadApi($authenticationMethod['modname'], 'Authentication')) {
throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' could not be loaded.', array($authenticationMethod['modname'])));
}
if (!isset($authenticationMethod['method']) || !is_string($authenticationMethod['method']) || empty($authenticationMethod['method'])) {
throw new Zikula_Exception_Fatal(__f('An invalid %1$s parameter was received.', array('method')));
} elseif (!ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'supportsAuthenticationMethod', array('method' => $authenticationMethod['method']), 'Zikula_Api_AbstractAuthentication')) {
throw new Zikula_Exception_Fatal(__f('The authentication method \'%1$s\' is not supported by the authentication module \'%2$s\'.', array($authenticationMethod['method'], $authenticationMethod['modname'])));
}
if (ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'isReentrant', null, 'Zikula_Api_AbstractAuthentication') && (!isset($reentrantURL) || empty($reentrantURL))) {
throw new Zikula_Exception_Fatal(__f('The authentication module \'%1$s\' is reentrant. A %2$s is required.', array($authenticationMethod['modname'], 'reentrantURL')));
}
return true;
}
/**
* Authenticate a user's credentials against an authentication module, without any attempt to log the user in or look up a Zikula user account record.
*
* NOTE: Checking a password with an authentication method defined by the Users module is a special case.
* The password is stored along with the account information, therefore the account information has to be
* looked up by the checkPassword function in that module. Authentication modules other than the Users module should
* make no attempt to look up account information,
*
* This function is used to check that a user is who he says he is without any attempt to log the user into the
* Zikula system or look up his account information or status. It could be used, for example, to check the user's
* credentials prior to registering with an authentication method like OpenID or Google Federated Login.
*
* This function differs from {@link authenticateUserUsing()} in that it does not make any attempt to look up a Zikula account
* record for the user (nor should the authentication method specified).
*
* This function differs from {@link loginUsing()} in that it does not make any attempt to look up a Zikula account
* record for the user (nor should the authentication method specified), and additionally it makes no attempt to log the user into
* the Zikula system.
*
* ATTENTION: The authentication module function(s) called during this process may redirect the user to an external server
* to perform authorization and/or authentication. The function calling checkPasswordUsing must already have anticipated
* the reentrant nature of this process, must already have saved pertinent user state, must have supplied a
* reentrant URL pointing to a function that will handle reentry into the login process silently, and must clear
* any save user state immediately following the return of this function.
*
* @param array $authenticationMethod Authentication module and method name.
* @param array $authenticationInfo Auth info array.
* @param string $reentrantURL If the authentication module needs to redirect to an external authentication server (e.g., OpenID), then
* this is the URL to return to in order to re-enter the log-in process. The pertinent user
* state must have already been saved by the function calling checkPasswordUsing(), and the URL must
* point to a Zikula_AbstractController function that is equipped to detect reentry, restore the
* saved user state, and get the user back to the point where loginUsing is re-executed. This
* is only optional if the authentication module identified by $authenticationMethod reports that it is not
* reentrant (e.g., Users is guaranteed to not be reentrant).
*
* @return bool True if authentication info authenticates; otherwise false.
*/
public static function checkPasswordUsing(array $authenticationMethod, array $authenticationInfo, $reentrantURL = null)
{
if (self::preAuthenticationValidation($authenticationMethod, $reentrantURL)) {
// Authenticate the loginID and userEnteredPassword against the specified authentication module.
// This should return the uid of the user logging in. Note that there are two routes here, both get a uid.
$checkPasswordArgs = array(
'authentication_info' => $authenticationInfo,
'authentication_method' => $authenticationMethod,
'reentrant_url' => $reentrantURL,
);
return ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'checkPassword', $checkPasswordArgs, 'Zikula_Api_AbstractAuthentication');
} else {
return false;
}
}
/**
* Authenticate a user's credentials against an authentication module, without any attempt to log the user in.
*
* This function is used to check that a user is who he says he is, and that he has a valid user account with the
* Zikula system. No attempt is made to log the user in to the Zikula system. It could be used, for example, to check
* the user's credentials and Zikula system accoun status prior to performing a sensitive operation.
*
* This function differs from {@link checkPasswordUsing()} in that it attempts to look up a Zikula account
* record for the user, and takes the user's account status into account when returning a value.
*
* This function differs from {@link loginUsing()} in that it makes no attempt to log the user into the Zikula system.
*
* ATTENTION: The authentication module function(s) called during this process may redirect the user to an external server
* to perform authorization and/or authentication. The function calling authenticateUserUsing must already have anticipated
* the reentrant nature of this process, must already have saved pertinent user state, must have supplied a
* reentrant URL pointing to a function that will handle reentry into the login process silently, and must clear
* any save user state immediately following the return of this function.
*
* @param array $authenticationMethod The name of the authentication module to use for authentication and the method name as defined by that module.
* @param array $authenticationInfo The information needed by the authentication module for authentication, typically a loginID and pass.
* @param string $reentrantURL If the authentication module needs to redirect to an external authentication server (e.g., OpenID), then
* this is the URL to return to in order to re-enter the log-in process. The pertinent user
* state must have already been saved by the function calling authenticateUserUsing(), and the URL must
* point to a Zikula_AbstractController function that is equipped to detect reentry, restore the
* saved user state, and get the user back to the point where loginUsing is re-executed. This
* is only optional if the authentication module identified by $authenticationMethod reports that it is not
* reentrant (e.g., Users is guaranteed to not be reentrant).
*
* @return mixed Zikula uid if the authentication info authenticates with the authentication module; otherwise false.
*/
private static function internalAuthenticateUserUsing(array $authenticationMethod, array $authenticationInfo, $reentrantURL = null)
{
$authenticatedUid = false;
if (self::preAuthenticationValidation($authenticationMethod, $reentrantURL)) {
$authenticateUserArgs = array(
'authentication_info' => $authenticationInfo,
'authentication_method' => $authenticationMethod,
'reentrant_url' => $reentrantURL,
);
$authenticatedUid = ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'authenticateUser', $authenticateUserArgs, 'Zikula_Api_AbstractAuthentication');
}
return $authenticatedUid;
}
private static function internalUserAccountValidation($uid, $reportErrors = false, $userObj = false)
{
if (!$uid || !is_numeric($uid) || ((int)$uid != $uid)) {
// We got something other than a uid from the authentication process.
if (!LogUtil::hasErrors() && $reportErrors) {
LogUtil::registerError(__('Sorry! Login failed. The information you provided was incorrect.'));
}
} else {
if (!$userObj) {
// Need to make sure the Users module stuff is loaded and available, especially if we are authenticating during
// an upgrade or install.
ModUtil::dbInfoLoad('Users', 'Users');
ModUtil::loadApi('Users', 'user', true);
// The user's credentials have authenticated with the authentication module's method, but
// now we have to check the account status itself. If the account status would not allow the
// user to log in, then we return false.
$userObj = self::getVars($uid);
if (!$userObj) {
// Might be a registration
$userObj = self::getVars($uid, false, 'uid', true);
}
}
if (!$userObj || !is_array($userObj)) {
// Note that we have not actually logged into anything yet, just authenticated.
throw new Zikula_Exception_Fatal(__f('A %1$s (%2$s) was returned by the authenticating module, but a user account record (or registration request record) could not be found.', array('uid', $uid)));
}
if (!isset($userObj['activated'])) {
// Provide a sane value.
$userObj['activated'] = Users_Constant::ACTIVATED_INACTIVE;
}
if ($userObj['activated'] != Users_Constant::ACTIVATED_ACTIVE) {
if ($reportErrors) {
$displayVerifyPending = ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_LOGIN_DISPLAY_VERIFY_STATUS, Users_Constant::DEFAULT_LOGIN_DISPLAY_VERIFY_STATUS);
$displayApprovalPending = ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_LOGIN_DISPLAY_APPROVAL_STATUS, Users_Constant::DEFAULT_LOGIN_DISPLAY_VERIFY_STATUS);
if (($userObj['activated'] == Users_Constant::ACTIVATED_PENDING_REG) && ($displayApprovalPending || $displayVerifyPending)) {
$moderationOrder = ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_REGISTRATION_APPROVAL_SEQUENCE, Users_Constant::DEFAULT_REGISTRATION_APPROVAL_SEQUENCE);
if (!$userObj['isverified']
&& (($moderationOrder == Users_Constant::APPROVAL_AFTER) || ($moderationOrder == Users_Constant::APPROVAL_ANY)
|| (!empty($userObj['approved_by'])))
&& $displayVerifyPending
) {
$message = __('Your request to register with this site is still waiting for verification of your e-mail address. Please check your inbox for a message from us.');
} elseif (empty($userObj['approved_by'])
&& (($moderationOrder == Users_Constant::APPROVAL_BEFORE) || ($moderationOrder == Users_Constant::APPROVAL_ANY))
&& $displayApprovalPending
) {
$message = __('Your request to register with this site is still waiting for approval from a site administrator.');
}
if (isset($message) && !empty($message)) {
return LogUtil::registerError($message);
}
// It is a pending registration but the site admin elected to not display this to the user.
// No exception here because the answer is simply "no." This will fall through to return false.
} elseif (($userObj['activated'] == Users_Constant::ACTIVATED_INACTIVE) && ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_LOGIN_DISPLAY_INACTIVE_STATUS, Users_Constant::DEFAULT_LOGIN_DISPLAY_INACTIVE_STATUS)) {
$message = __('Your account has been disabled. Please contact a site administrator for more information.');
} elseif (($userObj['activated'] == Users_Constant::ACTIVATED_PENDING_DELETE) && ModUtil::getVar(Users_Constant::MODNAME, Users_Constant::MODVAR_LOGIN_DISPLAY_DELETE_STATUS, Users_Constant::DEFAULT_LOGIN_DISPLAY_DELETE_STATUS)) {
$message = __('Your account has been disabled and is scheduled for removal. Please contact a site administrator for more information.');
} else {
$message = __('Sorry! Either there is no active user in our system with that information, or the information you provided does not match the information for your account.');
}
LogUtil::registerError($message);
}
$userObj = false;
}
}
return $userObj;
}
/**
* Authenticate a user's credentials against an authentication module, without any attempt to log the user in.
*
* This function is used to check that a user is who he says he is, and that he has a valid user account with the
* Zikula system. No attempt is made to log the user in to the Zikula system. It could be used, for example, to check
* the user's credentials and Zikula system accoun status prior to performing a sensitive operation.
*
* This function differs from {@link checkPasswordUsing()} in that it attempts to look up a Zikula account
* record for the user, and takes the user's account status into account when returning a value.
*
* This function differs from {@link loginUsing()} in that it makes no attempt to log the user into the Zikula system.
*
* ATTENTION: The authentication module function(s) called during this process may redirect the user to an external server
* to perform authorization and/or authentication. The function calling authenticateUserUsing must already have anticipated
* the reentrant nature of this process, must already have saved pertinent user state, must have supplied a
* reentrant URL pointing to a function that will handle reentry into the login process silently, and must clear
* any save user state immediately following the return of this function.
*
* @param array $authenticationMethod The name of the authentication module to use for authentication and the method name as defined by that module.
* @param array $authenticationInfo The information needed by the authentication module for authentication, typically a loginID and pass.
* @param string $reentrantURL If the authentication module needs to redirect to an external authentication server (e.g., OpenID), then
* this is the URL to return to in order to re-enter the log-in process. The pertinent user
* state must have already been saved by the function calling authenticateUserUsing(), and the URL must
* point to a Zikula_AbstractController function that is equipped to detect reentry, restore the
* saved user state, and get the user back to the point where loginUsing is re-executed. This
* is only optional if the authentication module identified by $authenticationMethod reports that it is not
* reentrant (e.g., Users is guaranteed to not be reentrant).
* @param boolean $reportErrors If true, then when validation of the account's ability to log in is performed, if errors are detected then
* they will be reported through registering errors with Zikula's logging and error reporting system. If
* false, then error reporting is supressed, and only the return value will indicate success or failure.
*
* @return array|bool The user account record of the user with the given credentials, if his credentials authenticate; otherwise false
*/
public static function authenticateUserUsing(array $authenticationMethod, array $authenticationInfo, $reentrantURL = null, $reportErrors = false)
{
$userObj = false;
$authenticatedUid = self::internalAuthenticateUserUsing($authenticationMethod, $authenticationInfo, $reentrantURL);
if ($authenticatedUid) {
$userObj = self::internalUserAccountValidation($authenticatedUid, $reportErrors);
}
return $userObj;
}
/**
* Authenticate a user's credentials against an authentication module, logging him into the Zikula system.
*
* If the user is already logged in, then this function should behave as if {@link authenticateUserUsing()} was called.
*
* This function is used to check that a user is who he says he is, and that he has a valid user account with the
* Zikula system. If so, the user is logged in to the Zikula system (if he is not already logged in). This function
* should be used only to log a user into the Zikula system.
*
* This function differs from {@link checkPasswordUsing()} in that it attempts to look up a Zikula account
* record for the user, and takes the user's account status into account when returning a value. Additionally,
* the user is logged into the Zikula system if his credentials are verified with the authentication module specified.
*
* This function differs from {@link authenticateUserUsing()} in that it attempts to log the user into the Zikula system,
* if he is not already logged in. If he is already logged in, then it should behave similarly to authenticateUserUsing().
*
* ATTENTION: The authentication module function(s) called during this process may redirect the user to an external server
* to perform authorization and/or authentication. The function calling loginUsing must already have anticipated
* the reentrant nature of this process, must already have saved pertinent user state, must have supplied a
* reentrant URL pointing to a function that will handle reentry into the login process silently, and must clear
* any save user state immediately following the return of this function.
*
* @param array $authenticationMethod Auth module name.
* @param array $authenticationInfo Auth info array.
* @param boolean $rememberMe Whether or not to remember login.
* @param string $reentrantURL If the authentication module needs to redirect to an external authentication server (e.g., OpenID), then
* this is the URL to return to in order to re-enter the log-in process. The pertinent user
* state must have already been saved by the function calling loginUsing(), and the URL must
* point to a Zikula_AbstractController function that is equipped to detect reentry, restore the
* saved user state, and get the user back to the point where loginUsing is re-executed. This
* is only optional if the authentication module identified by $authenticationMethod reports that it is not
* reentrant (e.g., Users is guaranteed to not be reentrant), or if $checkPassword is false.
* @param boolean $checkPassword Whether or not to check the password.
* @param boolean $preauthenticatedUser Whether ot not is a preauthenticated user.
*
* @return array|bool The user account record of the user that has logged in successfully, otherwise false
*/
public static function loginUsing(array $authenticationMethod, array $authenticationInfo, $rememberMe = false, $reentrantURL = null, $checkPassword = true, $preauthenticatedUser = null)
{
$userObj = false;
if (self::preAuthenticationValidation($authenticationMethod, $authenticationInfo, $reentrantURL)) {
// Authenticate the loginID and userEnteredPassword against the specified authentication module.
// This should return the uid of the user logging in. Note that there are two routes here, both get a uid.
// We do the authentication check first, before checking any account status information, because if the
// person logging in cannot supply the proper credentials, then we should not show any detailed account status
// to them. Instead they should just get the generic "no such user found or bad password" message.
if ($checkPassword) {
$authenticatedUid = self::internalAuthenticateUserUsing($authenticationMethod, $authenticationInfo, $reentrantURL, true);
} elseif (isset($preauthenticatedUser)) {
if (is_numeric($preauthenticatedUser)) {
$authenticatedUid = $preauthenticatedUser;
} elseif (is_array($preauthenticatedUser)) {
$authenticatedUid = $preauthenticatedUser['uid'];
$userObj = $preauthenticatedUser;
} else {
throw new Zikula_Exception_Fatal();
}
} else {
$authArgs = array(
'authentication_info' => $authenticationInfo,
'authentication_method' => $authenticationMethod,
);
$authenticatedUid = ModUtil::apiFunc($authenticationMethod['modname'], 'Authentication', 'getUidForAuththenticationInfo', $authArgs, 'Zikula_Api_AbstractAuthentication');
}
$userObj = self::internalUserAccountValidation($authenticatedUid, true, isset($userObj) ? $userObj : null);
if ($userObj && is_array($userObj)) {
// BEGIN ACTUAL LOGIN
// Made it through all the checks. We can actually log in now.
// Give any interested module one last chance to prevent the login from happening.
$eventArgs = array(
'authentication_method' => $authenticationMethod,
'uid' => $userObj['uid'],
);
$event = new Zikula_Event('user.login.veto', $userObj, $eventArgs);
$event = EventUtil::notify($event);
if ($event->isStopped()) {
// The login attempt has been vetoed by one or more modules.
$eventData = $event->getData();
if (isset($eventData['retry']) && $eventData['retry']) {
$sessionVarName = 'Users_Controller_User_login';
$sessionNamespace = 'Zikula_Users';
$redirectURL = ModUtil::url('Users', 'user', 'login', array('csrftoken' => SecurityUtil::generateCsrfToken()));
} elseif (isset($eventData['redirect_func'])) {
if (isset($eventData['redirect_func']['session'])) {
$sessionVarName = $eventData['redirect_func']['session']['var'];
$sessionNamespace = isset($eventData['redirect_func']['session']['namespace']) ? $eventData['redirect_func']['session']['namespace'] : '/';
}
$redirectURL = ModUtil::url($eventData['redirect_func']['modname'], $eventData['redirect_func']['type'], $eventData['redirect_func']['func'], $eventData['redirect_func']['args']);
}
if (isset($redirectURL)) {
if (isset($sessionVarName)) {
SessionUtil::requireSession();
$sessionVars = SessionUtil::getVar('Users_User_Controller_login', array(), 'Zikula_Users', false, false);
$sessionVars = array(
'returnpage' => isset($sessionVars['returnpage']) ? $sessionVars['returnpage'] : '',
'authentication_info' => $authenticationInfo,
'authentication_method' => $authenticationMethod,
'rememberme' => $rememberMe,
'user_obj' => $userObj,
);
SessionUtil::setVar($sessionVarName, $sessionVars, $sessionNamespace, true, true);
}
$userObj = false;
//System::redirect($redirectURL);
throw new Zikula_Exception_Redirect($redirectURL);
} else {
throw new Zikula_Exception_Forbidden();
}
} else {
// The login has not been vetoed
// This is what really does the Zikula login
self::setUserByUid($userObj['uid'], $rememberMe, $authenticationMethod);
}
}
}
return $userObj;
}
/**
* Sets the currently logged in active user to the user account for the given Users module uname.
*
* No events are fired from this function. To receive events, use {@link loginUsing()}.
*
* @param string $uname The user name of the user who should be logged into the system; required.
* @param boolean $rememberMe If the user's login should be maintained on the computer from which the user is logging in, set this to true;
* optional, defaults to false.
*
* @return void
*/
public static function setUserByUname($uname, $rememberMe = false)
{
if (!isset($uname) || !is_string($uname) || empty($uname)) {
throw new Zikula_Exception_Fatal(__('Attempt to set the current user with an invalid uname.'));
}
$uid = self::getIdFromName($uname);
$authenticationMethod = array(
'modname' => 'Users',
'method' => 'uname',
);