-
Notifications
You must be signed in to change notification settings - Fork 19
/
lib-user.php
1432 lines (1233 loc) · 53.1 KB
/
lib-user.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.2 |
// +---------------------------------------------------------------------------+
// | lib-user.php |
// | |
// | User-related functions needed in more than one place. |
// +---------------------------------------------------------------------------+
// | Copyright (C) 2000-2019 by the following authors: |
// | |
// | Authors: Tony Bibbs - tony AT tonybibbs DOT com |
// | Mark Limburg - mlimburg AT users DOT sourceforge DOT net |
// | Jason Whittenburg - jwhitten AT securitygeeks 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. |
// | |
// +---------------------------------------------------------------------------+
if (strpos(strtolower($_SERVER['PHP_SELF']), 'lib-user.php') !== false) {
die('This file can not be used on its own!');
}
/**
* Delete a user account
*
* @param int $uid id of the user to delete
* @return boolean true = user deleted, false = an error occurred
*/
function USER_deleteAccount($uid)
{
global $_CONF, $_TABLES, $_USER;
// first some checks ...
if ((($uid == $_USER['uid']) && ($_CONF['allow_account_delete'] == 1)) ||
SEC_hasRights('user.delete')
) {
if (SEC_inGroup('Root', $uid)) {
if (!SEC_inGroup('Root')) {
// can't delete a Root user without being in the Root group
COM_accessLog("User {$_USER['uid']} just tried to delete Root user $uid with insufficient privileges.");
return false;
} else {
$rootgrp = DB_getItem($_TABLES['groups'], 'grp_id',
"grp_name = 'Root'");
$result = DB_query("SELECT COUNT(DISTINCT {$_TABLES['users']}.uid) AS count FROM {$_TABLES['users']},{$_TABLES['group_assignments']} WHERE {$_TABLES['users']}.uid > 1 AND {$_TABLES['users']}.uid = {$_TABLES['group_assignments']}.ug_uid AND ({$_TABLES['group_assignments']}.ug_main_grp_id = $rootgrp)");
$A = DB_fetchArray($result);
if ($A['count'] <= 1) {
// make sure there's at least 1 Root user left
COM_errorLog("You can't delete the last user from the Root group.", 1);
return false;
}
}
}
} else {
// you can only delete your own account (if enabled) or you need
// proper permissions to do so (user.delete)
COM_accessLog("User {$_USER['uid']} just tried to delete user $uid with insufficient privileges.");
return false;
}
// log the user out
SESS_endUserSession($uid);
// Ok, now delete everything related to this user
// let plugins update their data for this user
PLG_deleteUser($uid);
// remove from all security groups
DB_delete($_TABLES['group_assignments'], 'ug_uid', $uid);
// remove user information and preferences
DB_delete($_TABLES['userprefs'], 'uid', $uid);
DB_delete($_TABLES['userindex'], 'uid', $uid);
DB_delete($_TABLES['usercomment'], 'uid', $uid);
DB_delete($_TABLES['userinfo'], 'uid', $uid);
DB_delete($_TABLES['backup_codes'], 'uid', $uid);
DB_delete($_TABLES['likes'], 'uid', $uid);
// avoid having orphand stories/comments by making them anonymous posts
DB_query("UPDATE {$_TABLES['comments']} SET uid = 1 WHERE uid = $uid");
DB_query("UPDATE {$_TABLES['stories']} SET uid = 1 WHERE uid = $uid");
DB_query("UPDATE {$_TABLES['stories']} SET owner_id = 1 WHERE owner_id = $uid");
// delete submissions
DB_delete($_TABLES['storysubmission'], 'uid', $uid);
DB_delete($_TABLES['commentsubmissions'], 'uid', $uid); // Includes article and plugin submissions
// delete user photo, if enabled & exists
if ($_CONF['allow_user_photo'] == 1) {
$photo = DB_getItem($_TABLES['users'], 'photo', "uid = $uid");
USER_deletePhoto($photo, false);
}
// in case the user owned any objects that require Admin access, assign
// them to the Root user with the lowest uid
$rootGroup = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Root'");
$result = DB_query("SELECT DISTINCT ug_uid FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = $rootGroup ORDER BY ug_uid LIMIT 1");
$A = DB_fetchArray($result);
$rootUser = $A['ug_uid'];
DB_query("UPDATE {$_TABLES['blocks']} SET owner_id = {$rootUser} WHERE owner_id = {$uid} ");
DB_query("UPDATE {$_TABLES['topics']} SET owner_id = {$rootUser} WHERE owner_id = {$uid} ");
// now delete the user itself
DB_delete($_TABLES['users'], 'uid', $uid);
return true;
}
/**
* Create a new password and send it to the user
*
* @param string $username user's login name
* @param string $useremail user's email address
* @param int $uid user ID
* @param string $email_type
* @return boolean true = success, false = an error occurred
*/
function USER_createAndSendPassword($username, $useremail, $uid, $email_type = '')
{
global $_CONF, $LANG04;
$passwd = null;
SEC_updateUserPassword($passwd, $uid);
if ($email_type == '' && file_exists($_CONF['path_data'] . 'welcome_email.txt')) {
$template = COM_newTemplate(CTL_core_templatePath($_CONF['path_data']));
$template->set_file(array('mail' => 'welcome_email.txt'));
$template->set_var('auth_info',
"$LANG04[2]: $username\n$LANG04[4]: $passwd");
$template->set_var('site_name', $_CONF['site_name']);
$template->set_var('site_slogan', $_CONF['site_slogan']);
$template->set_var('lang_text1', $LANG04[15]);
$template->set_var('lang_text2', $LANG04[14]);
$template->set_var('lang_username', $LANG04[2]);
$template->set_var('lang_password', $LANG04[4]);
$template->set_var('username', $username);
$template->set_var('password', $passwd);
$template->set_var('name', COM_getDisplayName($uid));
$template->parse('output', 'mail');
$mailtext = $template->get_var('output');
} else {
if ($email_type == 'convert_remote') {
$mailtext = $LANG04['email_convert_remote'] . "\n\n";
} else {
$mailtext = $LANG04[15] . "\n\n";
}
$mailtext .= $LANG04[2] . ": $username\n";
$mailtext .= $LANG04[4] . ": $passwd\n\n";
$mailtext .= $LANG04[14] . "\n\n";
$mailtext .= $_CONF['site_name'] . "\n";
$mailtext .= $_CONF['site_url'] . "\n";
}
$subject = $_CONF['site_name'] . ': ' . $LANG04[16];
if ($_CONF['site_mail'] !== $_CONF['noreply_mail']) {
$mailfrom = $_CONF['noreply_mail'];
$mailtext .= LB . LB . $LANG04[159];
} else {
$mailfrom = $_CONF['site_mail'];
}
return COM_mail($useremail, $subject, $mailtext, $mailfrom);
}
/**
* Inform a user their account has been activated.
*
* @param string $userName user's login name
* @param string $userEmail user's email address
* @return boolean true = success, false = an error occurred
*/
function USER_sendActivationEmail($userName, $userEmail)
{
global $_CONF, $LANG04;
if (file_exists($_CONF['path_data'] . 'activation_email.txt')) {
$template = COM_newTemplate(CTL_core_templatePath($_CONF['path_data']));
$template->set_file(array('mail' => 'activation_email.txt'));
$template->set_var('site_name', $_CONF['site_name']);
$template->set_var('site_slogan', $_CONF['site_slogan']);
$template->set_var('lang_text1', $LANG04[15]);
$template->set_var('lang_text2', $LANG04[14]);
$template->parse('output', 'mail');
$mailText = $template->get_var('output');
} else {
$mailText = str_replace("<username>", $userName, $LANG04[118]) . "\n\n";
$mailText .= $_CONF['site_url'] . "\n\n";
$mailText .= $LANG04[119] . "\n\n";
$mailText .= $_CONF['site_url'] . "/users.php?mode=getpassword\n\n";
$mailText .= $_CONF['site_name'] . "\n";
$mailText .= $_CONF['site_url'] . "\n";
}
$subject = $_CONF['site_name'] . ': ' . $LANG04[120];
if ($_CONF['site_mail'] !== $_CONF['noreply_mail']) {
$mailFrom = $_CONF['noreply_mail'];
$mailText .= LB . LB . $LANG04[159];
} else {
$mailFrom = $_CONF['site_mail'];
}
return COM_mail($userEmail, $subject, $mailText, $mailFrom);
}
/**
* Create a new user
* Also calls the custom user registration (if enabled) and plugin functions.
* NOTE: Does NOT send out password emails.
*
* @param string $username username (mandatory) and needs to be unique without any spaces in the front or trailing
* @param string $email user's email address (mandatory) and should be unique
* @param string $passwd password (optional, see above)
* @param string $fullname user's full name (optional)
* @param string $homepage user's home page (optional)
* @param string $remoteUserName
* @param string $service
* @param boolean $batchImport set to true when called from importuser() in admin/users.php (optional)
* @return int new user's ID
*/
function USER_createAccount($username, $email, $passwd = '', $fullname = '', $homepage = '', $remoteUserName = '', $service = '', $batchImport = false)
{
global $_CONF, $_TABLES;
$queueUser = false;
// username should have had COM_applyFilter (so no punctuation, etc..) and been trimmed of spaces and checked if unique before this as if not this function does not fail gracefully
// Might as well double check as having spaces and 4 byte characters could cause issues. Better to fail in this function than later in the process
// If username filters change remember to change same process for remote accounts (like in ouath helper class and doAction function)
$username = trim(GLText::remove4byteUtf8Chars($username));
$username = DB_escapeString($username);
$email = DB_escapeString($email);
$regdate = strftime('%Y-%m-%d %H:%M:%S', time());
$fields = 'username,email,regdate,cookietimeout';
$values = "'$username','$email','$regdate','{$_CONF['default_perm_cookie_timeout']}'";
if (!empty($passwd)) {
// Since no uid exists yet we can't use SEC_updateUserPassword and must handle things manually
$salt = SEC_generateSalt();
$passwd = SEC_encryptPassword($passwd, $salt, $_CONF['pass_alg'], $_CONF['pass_stretch']);
$fields .= ',passwd,salt,algorithm,stretch';
$values .= ",'$passwd','$salt','" . $_CONF['pass_alg'] . "','" . $_CONF['pass_stretch'] . "'";
}
if (!empty($fullname)) {
$fullname = DB_escapeString($fullname);
$fields .= ',fullname';
$values .= ",'$fullname'";
}
if (!empty($homepage)) {
$homepage = DB_escapeString($homepage);
$fields .= ',homepage';
$values .= ",'$homepage'";
}
if (($_CONF['usersubmission'] == 1) && !SEC_hasRights('user.edit')) {
$queueUser = true;
if (!empty($_CONF['allow_domains'])) {
if (USER_emailMatches($email, $_CONF['allow_domains'])) {
$queueUser = false;
}
}
if ($queueUser) {
$fields .= ',status';
$values .= ',' . USER_ACCOUNT_AWAITING_APPROVAL;
}
} else {
if (!empty($remoteUserName)) {
$fields .= ',remoteusername';
$values .= ",'$remoteUserName'";
}
if (!empty($service)) {
$fields .= ',remoteservice';
$values .= ",'$service'";
}
}
DB_query("INSERT INTO {$_TABLES['users']} ($fields) VALUES ($values)");
// Get the uid of the user, possibly given a service:
if ($remoteUserName != '') {
$uid = DB_getItem($_TABLES['users'], 'uid', "remoteusername = '$remoteUserName' AND remoteservice='$service'");
} else {
$uid = DB_getItem($_TABLES['users'], 'uid', "username = '$username' AND remoteservice IS NULL");
}
// Add user to Logged-in group (i.e. members) and the All Users group
$normal_grp = DB_getItem($_TABLES['groups'], 'grp_id',
"grp_name='Logged-in Users'");
$all_grp = DB_getItem($_TABLES['groups'], 'grp_id',
"grp_name='All Users'");
DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id, ug_uid) VALUES ($normal_grp, $uid)");
DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id, ug_uid) VALUES ($all_grp, $uid)");
// any default groups?
$result = DB_query("SELECT grp_id FROM {$_TABLES['groups']} WHERE grp_default = 1");
$num_groups = DB_numRows($result);
for ($i = 0; $i < $num_groups; $i++) {
list($def_grp) = DB_fetchArray($result);
DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id, ug_uid) VALUES ($def_grp, $uid)");
}
DB_query("INSERT INTO {$_TABLES['userprefs']} (uid) VALUES ($uid)");
if ($_CONF['emailstoriesperdefault'] == 1) {
DB_query("INSERT INTO {$_TABLES['userindex']} (uid,etids) VALUES ($uid,'')");
} else {
DB_query("INSERT INTO {$_TABLES['userindex']} (uid,etids) VALUES ($uid, '-')");
}
DB_query("INSERT INTO {$_TABLES['usercomment']} (uid,commentmode,commentorder,commentlimit) VALUES ($uid,'{$_CONF['comment_mode']}','{$_CONF['comment_order']}','{$_CONF['comment_limit']}')");
DB_query("INSERT INTO {$_TABLES['userinfo']} (uid) VALUES ($uid)");
// Call plugins back on user creation
PLG_createUser($uid);
// Notify the admin?
if (isset($_CONF['notification']) && in_array('user', $_CONF['notification'])) {
$mode = $queueUser ? 'inactive' : 'active';
$username = COM_getDisplayName($uid, $username, $fullname, $remoteUserName, $service);
USER_sendNotification($username, $email, $uid, $mode);
}
return $uid;
}
/**
* Send an email notification when a new user registers with the site.
*
* @param string $userName Username of the new user
* @param string $email Email address of the new user
* @param int $uid User id of the new user
* @param string $mode Mode user was added at.
* @return boolean true = success, false = an error occurred
*/
function USER_sendNotification($userName, $email, $uid, $mode = 'inactive')
{
global $_CONF, $LANG01, $LANG04, $LANG08, $LANG28, $LANG29;
$mailBody = "$LANG04[2]: $userName\n"
. "$LANG04[5]: $email\n"
. "$LANG28[14]: " . strftime($_CONF['date']) . "\n\n";
if ($mode === 'inactive') {
// user needs admin approval
$mailBody .= "{$LANG01[10]} <{$_CONF['site_admin_url']}/moderation.php>\n\n";
} else {
// user has been created, or has activated themselves:
$mailBody .= "{$LANG29[4]} <{$_CONF['site_url']}/users.php?mode=profile&uid={$uid}>\n\n";
}
$mailBody .= "\n------------------------------\n";
$mailBody .= "\n{$LANG08[34]}\n";
$mailBody .= "\n------------------------------\n";
$mailSubject = $_CONF['site_name'] . ' ' . $LANG29[40];
return COM_mail($_CONF['site_mail'], $mailSubject, $mailBody);
}
/**
* Send an email notification when invalid logins max is reached.
*
* @param string $userName Username of the new user
* @param string $email Email address of the new user
* @param int $uid User id of the new user
* @param string $mode Mode user was added at.
* @return boolean true = success, false = an error occurred
*/
function USER_sendInvalidLoginAlert($userName, $email, $uid, $mode = 'inactive')
{
global $_CONF, $LANG04, $LANG08, $LANG29;
$remoteAddress = $_SERVER['REMOTE_ADDR'];
$mailBody = "$LANG04[2]: $userName\n"
. "$LANG04[5]: $email\n";
$mailBody .= sprintf($LANG29['max_invalid_login_msg'] . "\n\n", $remoteAddress);
$mailBody .= "{$LANG29[4]} <{$_CONF['site_url']}/users.php?mode=profile&uid={$uid}>\n\n";
$mailBody .= "\n------------------------------\n";
$mailBody .= "\n{$LANG08[34]}\n";
$mailBody .= "\n------------------------------\n";
$mailSubject = $_CONF['site_name'] . ' ' . $LANG29['max_invalid_login'];
return COM_mail($_CONF['site_mail'], $mailSubject, $mailBody);
}
/**
* Get a user's photo, either uploaded or from an external service
* NOTE: All parameters are optional and can be passed as 0 / empty string.
*
* @param int $uid User ID
* @param string $photo name of the user's uploaded image
* @param string $email user's email address (for gravatar.com)
* @param int $width preferred image width
* @return string <img> tag or empty string if no image available
*/
function USER_getPhoto($uid = 0, $photo = '', $email = '', $width = 0)
{
global $_CONF, $_TABLES, $_USER;
$userPhoto = '';
if ($_CONF['allow_user_photo'] == 1) {
if (($width == 0) && !empty($_CONF['force_photo_width'])) {
$width = $_CONF['force_photo_width'];
}
// collect user's information with as few SQL requests as possible
if ($uid == 0) {
$uid = $_USER['uid'];
if (empty($email)) {
$email = $_USER['email'];
}
if (!empty($_USER['photo']) && (empty($photo) || ($photo === '(none)'))) {
$photo = $_USER['photo'];
}
}
if ((empty($photo) || ($photo === '(none)')) || (empty($email) && $_CONF['use_gravatar'])) {
$result = DB_query("SELECT email,photo FROM {$_TABLES['users']} WHERE uid = '{$uid}'");
list($newEmail, $newPhoto) = DB_fetchArray($result);
if (empty($photo) || ($photo === '(none)')) {
$photo = $newPhoto;
}
if (empty($email)) {
$email = $newEmail;
}
}
$img = '';
if (empty($photo) || ($photo == 'none')) {
// no photo - try gravatar.com, if allowed
if ($_CONF['use_gravatar']) {
$img = 'https://www.gravatar.com/avatar/' . md5($email);
$params = array();
if ($width > 0) {
$params[] = 's=' . $width;
}
if (!empty($_CONF['gravatar_rating'])) {
$params[] = 'r=' . $_CONF['gravatar_rating'];
}
// Since Geeklog-2.1.2
if (!empty($_CONF['gravatar_identicon'])) {
if (!in_array($_CONF['gravatar_identicon'], array('mm', 'identicon', 'monsterid', 'wavatar', 'retro'))) {
$_CONF['gravatar_identicon'] = 'identicon';
}
$params[] = 'd=' . urlencode($_CONF['gravatar_identicon']);
}
if (count($params) > 0) {
$img .= '?' . implode('&', $params);
}
}
} else {
// check if images are inside or outside the document root
if (strstr($_CONF['path_images'], $_CONF['path_html'])) {
$imgPath = substr($_CONF['path_images'], strlen($_CONF['path_html']));
$img = $_CONF['site_url'] . '/' . $imgPath . 'userphotos/' . $photo;
} else {
$img = $_CONF['site_url'] . '/getimage.php?mode=userphotos&image=' . $photo;
}
}
if (empty($img) && !empty($_CONF['default_photo'])) {
$img = $_CONF['default_photo'];
}
if (!empty($img)) {
$userPhoto = '<img src="' . $img . '"';
if ($width > 0) {
$userPhoto .= ' width="' . $width . '"';
}
$userPhoto .= ' alt="" class="userphoto"' . XHTML . '>';
}
}
return $userPhoto;
}
/**
* Delete a user's photo (i.e. the actual file)
* NOTE: Will silently ignore non-existing files.
*
* @param string $photo name of the photo (without the path)
* @param boolean $abortOnError true: abort script on error, false: don't
* @return void
*/
function USER_deletePhoto($photo, $abortOnError = true)
{
global $_CONF, $LANG04;
if (!empty($photo)) {
$fileToDelete = $_CONF['path_images'] . 'userphotos/' . $photo;
if (file_exists($fileToDelete)) {
if (!@unlink($fileToDelete)) {
if ($abortOnError) {
$display = COM_errorLog("Unable to remove file $photo");
$display = COM_createHTMLDocument($display, array('pagetitle' => $LANG04[21]));
echo $display;
exit;
} else {
// just log the problem, but don't abort
COM_errorLog("Unable to remove file {$photo}");
}
}
}
}
}
/**
* Convert a user account from remote to local.
* If user status is active and a email address exists then a new password email will be sent
*
* @param int $uid User id
* @return int 0 = Problems, not converted
* 1 = User account converted successfully
* 2 = User account converted successfully and email sent with password info
*/
function USER_convertRemote($uid)
{
global $_TABLES;
$remote_grp = DB_getItem($_TABLES['groups'], 'grp_id', "grp_name = 'Remote Users'");
// Find all Google accounts
$sql = "SELECT status, username, email, remoteusername, remoteservice FROM {$_TABLES['users']} WHERE uid = $uid";
$result = DB_query($sql);
$numRows = DB_numRows($result);
if ($numRows == 1) {
list($status, $username, $email, $remoteusername, $remoteservice) = DB_fetchArray($result);
// Confirm actually a remote account
if (!empty($remoteusername) || !empty($remoteservice)) {
// Remove them from remote accounts group
DB_query("DELETE FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = $remote_grp AND ug_uid = $uid");
// If user account is active and has no email then it cannot function as a regular account so lock it
// Cannot set status to USER_ACCOUNT_NEW_EMAIL since user doesn't know his password as a new one is being created
if ($status == USER_ACCOUNT_ACTIVE && empty($email)) {
$status = USER_ACCOUNT_LOCKED;
}
// If account looking for new email then lock it since user does not know password and admin has deemed email to be invalid
if ($status == USER_ACCOUNT_NEW_EMAIL) {
$status = USER_ACCOUNT_LOCKED;
}
// Add null to remoteusername and remoteservice
$sql = "UPDATE {$_TABLES['users']} SET
remoteusername = NULL, remoteservice = NULL, status = $status
WHERE uid = $uid";
DB_query($sql);
// Update user with random password
if ($status == USER_ACCOUNT_ACTIVE && !empty($email)) {
USER_createAndSendPassword($username, $email, $uid, 'convert_remote');
return 1; // Account converted NO email sent
} else {
$passwd = NULL; //Pass null so random will be created
SEC_updateUserPassword($passwd, $uid);
return 2; // Account converted and email sent
}
}
}
return 0;
}
/**
* Add user to group if user does not belong to specified group
* This is part of the Geeklog user implementation. This function
* looks up whether a user belongs to a specified group and if not
* adds them to the group
*
* @param int $groupId Group we want to see if user belongs to and if not add to group
* @param int $uid ID for user to check if in group and if not add user. If empty current user.
* @return boolean true if user is added to group, otherwise false
*/
function USER_addGroup($groupId, $uid = 0)
{
global $_TABLES, $_USER;
// set $uid if $uid is empty
if (empty($uid)) {
// bail for anonymous users
if (COM_isAnonUser()) {
return false;
} else {
// If logged in set to current uid
$uid = $_USER['uid'];
}
}
if (($groupId < 1) || SEC_inGroup($groupId, $uid)) {
return false;
} else {
DB_query("INSERT INTO {$_TABLES['group_assignments']} (ug_main_grp_id, ug_uid) VALUES ('{$groupId}', {$uid})");
return true;
}
}
/**
* Delete from group if user belongs to specified group
* This is part of the Geeklog user implementation. This function
* looks up whether a user belongs to a specified group and if so
* removes them from the group
*
* @param int $groupId Group we want to see if user belongs to and if so delete user from group
* @param int $uid ID for user to delete. If empty current user.
* @return boolean true if user is removed from group, otherwise false
*/
function USER_delGroup($groupId, $uid = 0)
{
global $_TABLES, $_USER;
// set $uid if $uid is empty
if (empty($uid)) {
// bail for anonymous users
if (COM_isAnonUser()) {
return false;
} else {
// If logged in set to current uid
$uid = $_USER['uid'];
}
}
if (($groupId > 0) && SEC_inGroup($groupId, $uid)) {
DB_query("DELETE FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = {$groupId} AND ug_uid = {$uid}");
return true;
} else {
return false;
}
}
/**
* Check email address against a list of domains
* Checks if the given email's domain part matches one of the entries in a
* comma-separated list of domain names (regular expressions are allowed).
*
* @param string $email email address to check
* @param string $domain_list list of domain names
* @return boolean true if match found, otherwise false
*/
function USER_emailMatches($email, $domain_list)
{
$match_found = false;
if (!empty($domain_list)) {
$domains = explode(',', $domain_list);
// Note: We should already have made sure that $email is a valid address
$email_domain = substr($email, strpos($email, '@') + 1);
foreach ($domains as $domain) {
$domain = trim($domain); // To fix bug #0001701
if (preg_match("#{$domain}#i", $email_domain)) {
$match_found = true;
break;
}
}
}
return $match_found;
}
/**
* Ensure unique username
* Checks that $username does not exist yet and creates a new unique username
* (based off of $username) if necessary.
* Mostly useful for creating accounts for remote users.
*
* @param string $username initial username
* @return string unique username
* @todo Bugs: Race conditions apply ...
*/
function USER_uniqueUsername($username)
{
global $_TABLES;
if (function_exists('CUSTOM_uniqueUsername')) {
return CUSTOM_uniqueUsername($username);
}
$try = $username;
do {
$try = DB_escapeString($try);
$uid = DB_getItem($_TABLES['users'], 'uid', "username = '$try'");
if (!empty($uid)) {
$r = rand(2, 9999);
if (strlen($username) > 12) {
$try = sprintf('%s%d', substr($username, 0, 12), $r);
} else {
$try = sprintf('%s%d', $username, $r);
}
}
} while (!empty($uid));
return $try;
}
/**
* Used to return an array of groups that a base group contains
* GL supports hierarchical groups and this will return all the child groups
*
* @param int $groupId Group id to get list of groups for
* @return array Array of child groups
*/
function USER_getChildGroups($groupId)
{
global $_TABLES;
$to_check = array();
array_push($to_check, $groupId);
$groups = array();
while (count($to_check) > 0) {
$thisGroup = array_pop($to_check);
if ($thisGroup > 0) {
$result = DB_query("SELECT ug_grp_id FROM {$_TABLES['group_assignments']} WHERE ug_main_grp_id = {$thisGroup}");
$numGroups = DB_numRows($result);
for ($i = 0; $i < $numGroups; $i++) {
$A = DB_fetchArray($result);
if (!in_array($A['ug_grp_id'], $groups)) {
if (!in_array($A['ug_grp_id'], $to_check)) {
array_push($to_check, $A['ug_grp_id']);
}
}
}
$groups[] = $thisGroup;
}
}
return $groups;
}
/**
* Subscribe user to a topic (for the Daily Digest)
*
* @param string $tid Topic ID
*/
function USER_subscribeToTopic($tid)
{
global $_CONF, $_TABLES, $_USER;
if ($_CONF['emailstories'] == 0) {
return;
}
if (COM_isAnonUser()) {
return;
}
if (!SEC_hasTopicAccess($tid)) {
return;
}
$user_etids = DB_getItem($_TABLES['userindex'], 'etids',
"uid = {$_USER['uid']}");
if (empty($user_etids)) {
return; // already subscribed to all topics
}
if ($user_etids == '-') {
$user_etids = $tid; // first topic user subscribed to
} else {
$eTids = explode(' ', $user_etids);
if (in_array($tid, $eTids)) {
return; // already subscribed
}
$eTids[] = $tid;
$user_etids = implode(' ', $eTids);
}
$user_etids = DB_escapeString($user_etids);
DB_query("UPDATE {$_TABLES['userindex']} SET etids = '{$user_etids}' WHERE uid = {$_USER['uid']}");
}
/**
* Unsubscribe user from a topic (for the Daily Digest)
*
* @param string $tid Topic ID
*/
function USER_unsubscribeFromTopic($tid)
{
global $_CONF, $_TABLES, $_USER;
if ($_CONF['emailstories'] == 0) {
return;
}
if (COM_isAnonUser()) {
return;
}
// no check for SEC_hasTopicAccess here to unsubscribe user "just in case"
$user_etids = DB_getItem($_TABLES['userindex'], 'etids', "uid = {$_USER['uid']}");
if ($user_etids == '-') {
return; // not subscribed to any topics
}
if (empty($user_etids)) {
// subscribed to all topics - get list
$etids = USER_getAllowedTopics();
} else {
$etids = explode(' ', $user_etids);
}
$key = array_search($tid, $etids);
if ($key === false) {
return; // not subscribed to this topic
}
unset($etids[$key]);
if (count($etids) == 0) {
$user_etids = '-';
} else {
$user_etids = implode(' ', $etids);
}
$user_etids = DB_escapeString($user_etids);
DB_query("UPDATE {$_TABLES['userindex']} SET etids = '$user_etids' WHERE uid = {$_USER['uid']}");
}
/**
* Check if user is subscribed to a topic
*
* @param string $tid Topic ID
* @return boolean true: subscribed, false: not subscribed
*/
function USER_isSubscribedToTopic($tid)
{
global $_CONF, $_TABLES, $_USER;
if ($_CONF['emailstories'] == 0) {
return false;
}
if (COM_isAnonUser()) {
return false;
}
if (!SEC_hasTopicAccess($tid)) {
return false;
}
$user_etids = DB_getItem($_TABLES['userindex'], 'etids',
"uid = {$_USER['uid']}");
if (empty($user_etids)) {
return true; // subscribed to all topics
} elseif ($user_etids == '-') {
return false; // not subscribed to any topics
}
$eTids = explode(' ', $user_etids);
return in_array($tid, $eTids);
}
/**
* Get topics the current user has access to
*
* @return array Array of topic IDs
*/
function USER_getAllowedTopics()
{
global $_TABLES;
$topics = array();
$result = DB_query("SELECT tid FROM {$_TABLES['topics']}");
$numRows = DB_numRows($result);
for ($i = 0; $i < $numRows; $i++) {
$A = DB_fetchArray($result);
if (SEC_hasTopicAccess($A['tid'])) {
$topics[] = $A['tid'];
}
}
return $topics;
}
/**
* Return if the current user can send email to the user
*
* @param int $toUid
* @return bool true if the current user can send email to the user
*/
function USER_isCanSendMail($toUid = 0)
{
global $_CONF, $_TABLES;
$retval = false;
// Anonymous users cannot send email at this site
if (($_CONF['loginrequired'] || $_CONF['emailuserloginrequired']) && COM_isAnonUser()) {
return $retval;
}
$toUid = (int) $toUid;
if ($toUid > 1) {
$sql = "SELECT emailfromadmin, emailfromuser FROM {$_TABLES['userprefs']} "
. "WHERE (uid = {$toUid})";
$result = DB_query($sql);
if (!DB_error()) {
$A = DB_fetchArray($result, false);
$retval = (bool) $A['emailfromuser'] || ((bool) $A['emailfromadmin'] && SEC_inGroup('Root'));
}
}
return $retval;
}
/**
* Shows a profile for a user
* This grabs the user profile for a given user and displays it
*
* @param int $uid User ID of profile to get
* @param boolean $preview whether being called as preview from My Account
* @param int $msg Message to display (if != 0)
* @param string $plugin optional plugin name for message
* @return string HTML for user profile page
*/
function USER_showProfile($uid, $preview = false, $msg = 0, $plugin = '')
{
global $_CONF, $_TABLES, $_USER, $_IMAGE_TYPE,
$LANG01, $LANG04, $LANG09, $LANG28, $LANG_LOGIN, $LANG_ADMIN;
$retval = '';
if (COM_isAnonUser() && (($_CONF['loginrequired'] == 1) || ($_CONF['profileloginrequired'] == 1))) {
$retval .= SEC_loginRequiredForm();
$retval = COM_createHTMLDocument($retval, array('pagetitle' => $LANG_LOGIN[1]));
return $retval;
}
$result = DB_query("SELECT {$_TABLES['users']}.uid,username,fullname,regdate,homepage,about,location,pgpkey,photo,email,status FROM {$_TABLES['userinfo']},{$_TABLES['users']} WHERE {$_TABLES['userinfo']}.uid = {$_TABLES['users']}.uid AND {$_TABLES['users']}.uid = $uid");
$numRows = DB_numRows($result);
if ($numRows == 0) { // no such user
COM_handle404();
}
$A = DB_fetchArray($result);
if ($A['status'] == USER_ACCOUNT_DISABLED && !SEC_hasRights('user.edit')) {
COM_displayMessageAndAbort(30, '', 403, 'Forbidden');
}
if ($A['status'] != USER_ACCOUNT_ACTIVE && !SEC_hasRights('user.edit')) {
COM_handle404();
}
$display_name = COM_getDisplayName($uid, $A['username'], $A['fullname']);
$display_name = htmlspecialchars($display_name);
if (!$preview) {
if ($msg > 0) {
$retval .= COM_showMessage($msg, $plugin);
}
}
// format date/time to user preference
$currentTime = COM_getUserDateTimeFormat($A['regdate']);
$A['regdate'] = $currentTime[0];
$user_templates = COM_newTemplate(CTL_core_templatePath($_CONF['path_layout'] . 'users'));
$user_templates->set_file(array(
'profile' => 'profile.thtml'
));
$blocks = array('display_field', 'field_statistic', 'last10_block', 'last10_row');
foreach ($blocks as $block) {
$user_templates->set_block('profile', $block);
}