-
-
Notifications
You must be signed in to change notification settings - Fork 212
/
user_handler.php
2383 lines (1996 loc) · 68.7 KB
/
user_handler.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
/*
* e107 website system
*
* Copyright (C) 2008-2016 e107 Inc (e107.org)
* Released under the terms and conditions of the
* GNU General Public License (http://www.gnu.org/licenses/gpl.txt)
*
* Handler - user-related functions
*
*/
/**
*
* @package e107
* @subpackage e107_handlers
*
* USER HANDLER CLASS - manages login and various user functions
*
*/
if (!defined('e107_INIT')) { exit; }
// Codes for `user_ban` field (not all used ATM)
define('USER_VALIDATED',0);
define('USER_BANNED',1);
define('USER_REGISTERED_NOT_VALIDATED',2);
define('USER_EMAIL_BOUNCED', 3);
define('USER_BOUNCED_RESET', 4);
define('USER_TEMPORARY_ACCOUNT', 5);
define('PASSWORD_E107_MD5',0);
define('PASSWORD_E107_SALT',1);
define('PASSWORD_E107_PHP', 3); // PHP Default - Using the bcrypt algorithm (default as of PHP 5.5.0).
define('PASSWORD_E107_ID','$E$'); // E107 salted
define('PASSWORD_INVALID', false);
define('PASSWORD_VALID',TRUE);
define ('PASSWORD_DEFAULT_TYPE',PASSWORD_E107_MD5);
//define ('PASSWORD_DEFAULT_TYPE',PASSWORD_E107_SALT);
// Required language file - if not loaded elsewhere, uncomment next line
e107::includeLan(e_LANGUAGEDIR.e_LANGUAGE.'/lan_user.php');
class UserHandler
{
var $userVettingInfo = array();
var $preferred = PASSWORD_DEFAULT_TYPE; // Preferred password format
var $passwordOpts = 0; // Copy of pref
var $passwordEmail = false; // True if can use email address to log in
private $otherFields = array();
private $passwordAPI = false;
// Constructor
public function __construct()
{
$pref = e107::getPref();
e107::lan('core','user');
if(function_exists('password_verify'))
{
$this->passwordAPI = true;
}
/**
Table of vetting methods for user data - lists every field whose value could be set manually.
Valid 'vetMethod' values (use comma separated list for multiple vetting):
0 - Null method
1 - Check for duplicates
2 - Check against $pref['signup_disallow_text']
3 - Check email address against remote server, only if option enabled
Index is the destination field name. If the source index name is different, specify 'srcName' in the array.
Possible processing options:
'dbClean' - 'sanitising' method for final value:
- 'toDB' - passes final value through $tp->toDB()
- 'intval' - converts to an integer
- 'image' - checks image for size
- 'avatar' - checks an image in the avatars directory
'stripTags' - strips HTML tags from the value (not an error if there are some)
'minLength' - minimum length (in utf-8 characters) for the string
'maxLength' - minimum length (in utf-8 characters) for the string
'longTrim' - if set, and the string exceeds maxLength, its trimmed
'enablePref' - value is processed only if the named $pref evaluates to true; otherwise any input is discarded without error
*/
$this->userVettingInfo = array(
'user_name' => array('niceName'=> LAN_USER_01, 'fieldType' => 'string', 'vetMethod' => '1,2', 'vetParam' => 'signup_disallow_text', 'srcName' => 'username', 'stripTags' => TRUE, 'stripChars' => '/ |\#|\=|\$/', 'fixedBlock' => 'anonymous', 'minLength' => 2, 'maxLength' => varset($pref['displayname_maxlength'],15)), // Display name
//'user_loginname' => array('niceName'=> LAN_USER_02, 'fieldType' => 'string', 'vetMethod' => '1', 'vetParam' => '', 'srcName' => 'loginname', 'stripTags' => TRUE, 'stripChars' => '#[^a-z0-9_\.]#i', 'minLength' => 2, 'maxLength' => varset($pref['loginname_maxlength'],30)), // User name
'user_loginname' => array('niceName'=> LAN_USER_02, 'fieldType' => 'string', 'vetMethod' => '1', 'vetParam' => '', 'srcName' => 'loginname', 'stripTags' => TRUE, 'stripChars' => '#[^\p{L}\p{M}a-z0-9_\.]#ui', 'minLength' => 2, 'maxLength' => varset($pref['loginname_maxlength'],30)), // User name
'user_login' => array('niceName'=> LAN_USER_03, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'realname', 'dbClean' => 'toDB', 'stripTags' => TRUE, 'stripChars' => '#<|>#i'), // Real name (no real vetting)
'user_customtitle' => array('niceName'=> LAN_USER_04, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'customtitle', 'dbClean' => 'toDB', 'enablePref' => 'signup_option_customtitle', 'stripTags' => TRUE, 'stripChars' => '#<|>#i'), // No real vetting
'user_password' => array('niceName'=> LAN_PASSWORD, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'password1', 'dataType' => 2, 'minLength' => varset($pref['signup_pass_len'],1)),
'user_sess' => array('niceName'=> LAN_USER_06, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'stripChars' => "#\"|'|(|)#", 'dbClean' => 'image', 'imagePath' => e_AVATAR_UPLOAD, 'maxHeight' => varset($pref['im_height'], 100), 'maxWidth' => varset($pref['im_width'], 120)), // Photo
'user_image' => array('niceName'=> LAN_USER_07, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'image', 'stripChars' => "#\"|'|(|)#", 'dbClean' => 'avatar'), //, 'maxHeight' => varset($pref['im_height'], 100), 'maxWidth' => varset($pref['im_width'], 120) resized on-the-fly // Avatar
'user_email' => array('niceName'=> LAN_EMAIL, 'fieldType' => 'string', 'vetMethod' => '1,3', 'vetParam' => '', 'fieldOptional' => varset($pref['disable_emailcheck'],0), 'srcName' => 'email', 'dbClean' => 'toDB'),
'user_signature' => array('niceName'=> LAN_USER_09, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'signature', 'dbClean' => 'toDB'),
'user_hideemail' => array('niceName'=> LAN_USER_10, 'fieldType' => 'int', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'hideemail', 'dbClean' => 'intval'),
'user_xup' => array('niceName'=> "XUP File", 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'user_xup', 'dbClean' => 'toDB'),
'user_class' => array('niceName'=> LAN_USER_12, 'fieldType' => 'string', 'vetMethod' => '0', 'vetParam' => '', 'srcName' => 'class', 'dataType' => '1')
);
$this->otherFields = array(
'user_join' => LAN_USER_14,
'user_lastvisit' => LAN_USER_15,
'user_currentvisit' => LAN_USER_16,
'user_comments' => LAN_COMMENTS,
'user_ip' => LAN_USER_18,
'user_ban' => LAN_USER_19,
'user_prefs' => LAN_USER_20,
'user_visits' => LAN_USER_21,
'user_admin' => LAN_USER_22,
'user_perms' => LAN_USER_23,
'user_pwchange' => LAN_USER_24
// user_chats int(10) unsigned NOT NULL default '0',
);
$this->otherFieldTypes = array(
'user_join' => 'int',
'user_lastvisit' => 'int',
'user_currentvisit' => 'int',
'user_comments' => 'int',
'user_ip' => 'string',
'user_ban' => 'int',
'user_prefs' => 'string',
'user_visits' => 'int',
'user_admin' => 'int',
'user_perms' => 'string',
'user_pwchange' => 'int'
);
$this->passwordOpts = varset($pref['passwordEncoding'], 0);
$this->passwordEmail = varset($pref['allowEmailLogin'], false);
switch ($this->passwordOpts)
{
case 3 :
$this->preferred = PASSWORD_E107_PHP;
break;
case 1 :
case 2 :
$this->preferred = PASSWORD_E107_SALT;
break;
case 0 :
default :
$this->preferred = PASSWORD_E107_MD5;
$this->passwordOpts = 0; // In case it got set to some stupid value
break;
}
return false;
}
/**
* Return the code for the current default password hash-type
* @return int
*/
public function getDefaultHashType()
{
return $this->preferred;
}
/**
* Returns true if PHP5.5+ password API is found, otherwise return false.
* @return bool
*/
public function passwordAPIExists()
{
return $this->passwordAPI;
}
/**
* Check if a user posted field is readonly (should not be user-editable) - used in usersettings.php
* @param array $posted
* @return bool
*/
public function hasReadonlyField($posted)
{
$restricted = array_keys($this->otherFields);
$pref = e107::getPref();
if(empty($pref['signup_option_class']))
{
$restricted[] = 'user_class';
}
foreach($posted as $k=>$v)
{
if(in_array($k,$restricted))
{
return true;
}
}
return false;
}
/**
* Given plaintext password and login name, generate password string to store in DB
*
* @param string $password - plaintext password as entered by user
* @param string $login_name - string used to log in (could actually be email address)
* @param string $force empty| PASSWORD_E107_MD 5| PASSWORD_E107_SALT | PASSWORD_E107_PHP $force - if non-empty, forces a particular type of password
*
* @return string|boolean - false if invalid emcoding method, else encoded password to store in DB
*/
public function HashPassword($password, $login_name='', $force=false)
{
if($force === false)
{
$force = $this->preferred;
}
if(($force == PASSWORD_E107_PHP) && $this->passwordAPI === false)
{
$force = PASSWORD_E107_SALT; // fallback.
}
switch ($force)
{
case PASSWORD_E107_MD5 :
return md5($password);
case PASSWORD_E107_SALT :
return PASSWORD_E107_ID.md5(md5($password).$login_name);
break;
case PASSWORD_E107_PHP :
return password_hash($password, PASSWORD_DEFAULT);
break;
}
return false;
}
/**
* Verify existing plaintext password against a stored hash value (which defines the encoding format and any 'salt')
*
* @param string $password - plaintext password as entered by user
* @param string $login_name - string used to log in (could actually be email address)
* @param string $stored_hash - required value for password to match
*
* @return string PASSWORD_INVALID|PASSWORD_VALID|string
* PASSWORD_INVALID if no match
* PASSWORD_VALID if valid password
* Return a new hash to store if valid password but non-preferred encoding
*/
public function CheckPassword($password, $login_name, $stored_hash)
{
$password = trim($password);
if(empty($password))
{
return PASSWORD_INVALID;
}
$type = $this->getHashType($stored_hash);
switch($type)
{
case PASSWORD_E107_MD5:// &&
if (md5($password) !== $stored_hash) return PASSWORD_INVALID;
if ($this->preferred == PASSWORD_E107_MD5 && ($this->passwordOpts <= 1)) return PASSWORD_VALID;
return $this->HashPassword($password); // Valid password, but non-preferred encoding; return the new hash
break;
case PASSWORD_E107_SALT:
$hash = $this->HashPassword($password, $login_name, PASSWORD_E107_SALT);
if ($hash === false) return PASSWORD_INVALID;
return ($hash == $stored_hash) ? PASSWORD_VALID : PASSWORD_INVALID;
break;
case PASSWORD_E107_PHP: // PHP 5.5+ Blowfish+
if($this->passwordAPI === true && password_verify($password,$stored_hash))
{
return PASSWORD_VALID;
}
break;
}
return PASSWORD_INVALID;
}
/**
* If necessary, rehash the user password to the currently set algorythm and updated database. .
* @param array $user - user fields. required: user_id, user_loginname, user_password
* @param string $password - plain text password.
* @return bool|string returns new password hash on success or false.
*/
public function rehashPassword($user, $password)
{
$type = $this->getHashType($user['user_password']);
if($type == $this->preferred || empty($user['user_id']) || empty($user['user_password']) || empty($user['user_loginname']))
{
return false;
}
$sql = e107::getDb();
$newPasswordHash = $this->HashPassword($password, $user['user_loginname']);
$update = array(
'data' => array(
'user_password' => $newPasswordHash,
),
'WHERE' => "user_id = ".intval($user['user_id'])." LIMIT 1",
'_FIELD_TYPES' => array('user_password' => 'safestr'),
);
if($sql->update('user', $update)!==false)
{
return $newPasswordHash;
}
return false;
}
/**
* Detect Password Hash Algorythm type
* @param string $hash - Password hash to analyse
* @param string $mode - (optional) set to 'text' for a plain-text description.
* @return bool|int|array
*/
public function getHashType($hash, $mode='constant')
{
if(empty($hash))
{
return false;
}
$num = false;
$name = '';
if((strlen($hash) === 32))
{
$num = PASSWORD_E107_MD5;
$name = 'md5';
}
elseif ((strlen($hash) === 35) && (strpos($hash, PASSWORD_E107_ID) === 0))
{
$num = PASSWORD_E107_SALT;
$name = 'md5-salt';
}
elseif($this->passwordAPI)
{
$info = password_get_info($hash);
if(!empty($info['algo']))
{
$num = PASSWORD_E107_PHP;
$name = $info['algoName'];
}
}
if($mode == 'array' && !empty($name))
{
return array($num,$name);
}
return $num;
}
/**
* Reset the user's password with an auto-generated string.
* @param $uid
* @param string $loginName (optional)
* @param array $options
* @return bool|string rawPassword
*/
public function resetPassword($uid, $loginName='', $options=array())
{
if(empty($uid))
{
return false;
}
$rawPassword = $this->generateRandomString(str_repeat('*', rand(8, 12)));
$hash = $this->HashPassword($rawPassword, $loginName);
$updateQry = array(
'data' => array( 'user_password' => $hash ),
'WHERE' => 'user_id = '.intval($uid)." LIMIT 1",
'_FIELD_TYPES' => array( 'user_password' => 'safestr' )
);
if(e107::getDb()->update('user', $updateQry))
{
if(!empty($options['return']) && $options['return'] == 'array')
{
return array('password'=>$rawPassword, 'hash'=>$hash);
}
return $rawPassword;
}
return false;
}
/**
* Verifies a standard response to a CHAP challenge
*
* @param string $challenge - the string sent to the user
* @param string $response - the response returned by the user
* @param string $login_name - user's login name
* @param string $stored_hash - password hash as stored in DB
*
* @return PASSWORD_INVALID|PASSWORD_VALID
*/
public function CheckCHAP($challenge, $response, $login_name, $stored_hash )
{
if (strlen($challenge) != 40) return PASSWORD_INVALID;
if (strlen($response) != 32) return PASSWORD_INVALID;
$valid_ret = PASSWORD_VALID;
if (strlen($stored_hash) == 32)
{ // Its simple md5 password storage
$stored_hash = PASSWORD_E107_ID.md5($stored_hash.$login_name); // Convert to the salted format always used by CHAP
if ($this->passwordOpts != PASSWORD_E107_MD5) $valid_ret = $stored_hash;
}
$testval = md5(substr($stored_hash,strlen(PASSWORD_E107_ID)).$challenge);
if ($testval == $response) return $valid_ret;
return PASSWORD_INVALID;
}
/**
* Checks whether the user has to validate a change of user settings by entering password (basically, if that field affects the
* stored password value)
*
* @param string $fieldName - name of field being changed
*
* @return bool TRUE if change required, false otherwise
*/
public function isPasswordRequired($fieldName)
{
if ($this->preferred == PASSWORD_E107_MD5) return false;
switch ($fieldName)
{
case 'user_email' :
return $this->passwordEmail;
case 'user_loginname' :
return TRUE;
}
return false;
}
/**
* Determines whether its necessary to store a separate password for email address validation
*
* @return bool TRUE if separate password
*/
public function needEmailPassword()
{
if ($this->preferred == PASSWORD_E107_MD5) return false;
if ($this->passwordEmail) return TRUE;
return false;
}
public function newUserExpired($userjoined)
{
$new_user_period = (int) e107::getPref('user_new_period', 0);
if(empty($new_user_period))
{
return true;
}
$userjoined = (int) $userjoined;
return (time() > ($userjoined + ( $new_user_period)*86400));
}
/**
* Checks whether the password value can be converted to the current default
*
* @param string $password - hashed password
* @return bool TRUE if conversion possible, false if not possible, or not needed.
*/
public function canConvert($password)
{
if ($this->preferred == PASSWORD_E107_MD5) return false;
if (strlen($password) == 32) return TRUE; // Can convert from md5 to salted
return false;
}
/**
* Given md5-encoded password and login name, generate password string to store in DB
*
* @param string $password - MD5-hashed password
* @param string $login_name - user's login name
*
* @return string hashed password to store in DB, converted as necessary
*/
public function ConvertPassword($password, $login_name)
{
if ($this->canConvert($password) === false) return $password;
return PASSWORD_E107_ID.md5($password.$login_name);
}
/**
* Generates a random user login name according to some pattern.
* Checked for uniqueness.
*
* @param string $pattern - defines the format of the username
* @param int $seed - may be used with the random pattern generator
*
* @return string a user login name, guaranteed unique in the database.
*/
public function generateUserLogin($pattern, $seed='')
{
$ul_sql = new db;
if (strlen($pattern) < 6) $pattern = '##....';
do
{
$newname = $this->generateRandomString($pattern, $seed);
} while ($ul_sql->select('user','user_id',"`user_loginname`='{$newname}'"));
return $newname;
}
/**
* Generates a random string - for user login name, password etc, according to some pattern.
* @param string $pattern - defines the output format:
* # - an alpha character
* . - a numeric character
* * - an alphanumeric character
* ! - symbol character
* ? - alpha, numeric or symbol character.
* ^ - next character from seed
* alphanumerics are included 'as is'
* @param int $seed - may be used with the random pattern generator
*
* @return string - the required random string
*/
public function generateRandomString($pattern='', $seed = '')
{
if (empty($pattern))
{
$pattern = '##....';
}
$newname = '';
// Create alpha [A-Z][a-z]
$alpha = 'AaBbCcDdEeFfGgHhIiJjKkLMmNnPpQqRrSsTtUuVvWwXxYyZz'; // O, o and l removed to avoid possible confusion with numbers.
$alphaLength = strlen($alpha) - 1;
// Create digit [0-9]
$digit = '0123456789';
$digitLength = strlen($digit) - 1;
// Create alpha numeric [A-Z][a-z]
$alphaNum = $alpha.$digit.chr(45).chr(95); // add support for - and _
$alphaNumLength = strlen($alphaNum) - 1;
$symbols = "~!@#$%^*-+?;:"; // avoid < > and quotes.
$symbolsLength = strlen($symbols) - 1;
$alphaNumSymbol = $alphaNum.$symbols;
$alphaNumSymbolLength = strlen($alphaNumSymbol) - 1;
// Next character of seed (if used)
$seed_ptr = 0;
for ($i = 0, $patternLength = strlen($pattern); $i < $patternLength; $i++)
{
$c = $pattern[$i];
switch ($c)
{
// Symbols only.
case '!':
$t = rand(0, $symbolsLength);
$newname .= $symbols[$t];
break;
// Alphanumeric + Symbols (most secure)
case '?':
$t = rand(0, $alphaNumSymbolLength);
$newname .= $alphaNumSymbol[$t];
break;
case '#' :
$t = rand(0, $alphaLength);
$newname .= $alpha[$t];
break;
// Numeric only - [0-9]
case '.' :
$t = rand(0, $digitLength);
$newname .= $digit[$t];
break;
// Alphanumeric
case '*' :
$t = rand(0, $alphaNumLength);
$newname .= $alphaNum[$t];
break;
// Next character from seed
case '^' :
if ($seed_ptr < strlen($seed))
{
$newname .= $seed[$seed_ptr];
$seed_ptr++;
}
break;
// (else just ignore other characters in pattern)
default :
if (strrpos($alphaNum, $c) !== false)
{
$newname .= $c;
}
}
}
return $newname;
}
/**
* Split up an email address to check for banned domains.
* @param string $email - email address to process
* @param string $fieldname - name of field being searched in DB
*
* @return bool|string false if invalid address. Otherwise returns a set of values to check
* Moved to IPHandler
*/
/*
public function make_email_query($email, $fieldname = 'banlist_ip')
{
return e107::getIPHandler()->makeEmailQuery($v, $fieldname); // Valid 'stub' if required
$tp = e107::getParser();
$tmp = strtolower($tp -> toDB(trim(substr($email, strrpos($email, "@")+1)))); // Pull out the domain name
if ($tmp == '') return false;
if (strpos($tmp,'.') === false) return false;
$em = array_reverse(explode('.',$tmp));
$line = '';
$out = array($fieldname."='*@{$tmp}'"); // First element looks for domain as email address
foreach ($em as $e)
{
$line = '.'.$e.$line;
$out[] = '`'.$fieldname."`='*{$line}'";
}
return implode(' OR ',$out);
}
*/
/**
* Create user cookie
*
* @param array $lode - user information from DB - 'user_id' and 'user_password' required
* @param bool $autologin - TRUE if the 'Remember Me' box ticked
*
* @return void
*/
public function makeUserCookie($lode,$autologin = false)
{
if(e107::isCli())
{
return true;
}
$cookieval = $lode['user_id'].'.'.md5($lode['user_password']); // (Use extra md5 on cookie value to obscure hashed value for password)
if (e107::getPref('user_tracking','session') == 'session')
{
$_SESSION[e107::getPref('cookie_name')] = $cookieval;
}
else
{
if ($autologin == 1)
{ // Cookie valid for up to 30 days
cookie(e107::getPref('cookie_name'), $cookieval, (time() + 3600 * 24 * 30));
$_COOKIE[e107::getPref('cookie_name')] = $cookieval; // make it available to the global scope before the page is reloaded
}
else
{
cookie(e107::getPref('cookie_name'), $cookieval);
$_COOKIE[e107::getPref('cookie_name')] = $cookieval; // make it available to the global scope before the page is reloaded
}
}
// echo "Debug: making cookie: ".$cookieval ." from ".print_a($lode,true);
// exit;
}
/**
* Generate an array of all the basic classes a user belongs to
*
* Note that the passed data may relate to the currently logged in user, or if an admin is logged in, to a different user
*
* @param array $userData - user's data record - must include the 'user_class' element
* @param boolean $asArray if TRUE, returns results in an array; else as a comma-separated string
* @param boolean $incInherited if TRUE, includes inherited classes
* @param boolean $fromAdmin - if TRUE, adds e_UC_ADMIN and e_UC_MAINADMIN in if current user's entitlement permits
*
* @return array|string of userclass information according to $asArray
*/
public function addCommonClasses($userData, $asArray = false, $incInherited = false, $fromAdmin = false)
{
if ($incInherited)
{
$classList = e107::getUserClass()->get_all_user_classes($userData['user_class']);
}
else
{
if (!empty($userData['user_class'])) $classList = explode(',',$userData['user_class']);
}
foreach (array(e_UC_MEMBER, e_UC_READONLY, e_UC_PUBLIC) as $c)
{
if (!in_array($c, vartrue($classList, array())))
{
$classList[] = $c;
}
}
if (((varset($userData['user_admin'],0) == 1) && strlen($userData['user_perms'])) || ($fromAdmin && ADMIN))
{
$classList[] = e_UC_ADMIN;
if ((strpos($userData['user_perms'],'0') === 0) || getperms('0'))
{
$classList[] = e_UC_MAINADMIN;
}
}
if ($asArray) return $classList;
return implode(',',$classList);
}
/**
* Return an array of descriptive names for each field in the user DB.
* @param bool $all if false, just returns modifiable fields. Else returns all
* @return array - key is field name, value is 'nice name' (descriptive name)
*/
public function getNiceNames($all = false)
{
// $ret = array('user_id' => LAN_USER_13);
foreach ($this->userVettingInfo as $k => $v)
{
$ret[$k] = $v['niceName'];
}
if ($all)
{
$ret = array_merge($ret, $this->otherFields);
}
return $ret;
}
//===================================================
// User Field validation
//===================================================
/* $_POST field names:
DB signup usersettings quick add function
------------------------------------------------------------------------------
user_id - user_id - Unique user ID
user_name name$ username username Display name
user_loginname loginname loginname loginname User name (login name)
user_customtitle - customtitle - Custom title
user_password password1 password1 password1 Password (prior to encoding)
password2 password2 password1 (Check password field)
user_sess * - Photo (file on server)
user_email email email email Email address
email_confirm
user_signature signature signature - User signature
user_image image image* - Avatar (may be external URL or file on server)
user_hideemail hideemail hideemail - Flag to hide user's email address
user_login realname realname realname User Real name
user_xup xupexist$ user_xup - XUP file link
user_class class class userclass User class (array on form)
user_loginname may be auto-generated
* avatar (user_image) and photo (user_sess) may be uploaded files
$changed to match the majority vote
Following fields auto-filled in code as required:
user_join
user_lastvisit
user_currentvisit
user_chats
user_comments
user_forums
user_ip
user_ban
user_prefs
user_viewed
user_visits
user_admin
user_perms
user_pwchange
*/
/**
* Function does validation specific to user data. Updates the $targetData array as appropriate.
*
* @param array $targetData - user data generated from earlier vetting stages - only the data in $targetData['data'] is checked
*
* @return bool TRUE if nothing updated; false if errors found
*/
public function userValidation(&$targetData)
{
$u_sql = e107::getDb('u');
$ret = TRUE;
$errMsg = '';
if (isset($targetData['data']['user_email']))
{
$v = trim($targetData['data']['user_email']); // Always check email address if its entered
if ($v == '')
{
if (!e107::getPref('disable_emailcheck'))
{
$errMsg = ERR_MISSING_VALUE;
}
}
elseif (!check_email($v))
{
$errMsg = ERR_INVALID_EMAIL;
}
elseif ($u_sql->count('user', '(*)', "WHERE `user_email`='".filter_var($v,FILTER_SANITIZE_EMAIL)."' AND `user_ban`=1 "))
{
$errMsg = ERR_BANNED_USER;
}
else
{ // See if email address banned
$wc = e107::getIPHandler()->makeEmailQuery($v); // Generate the query for the ban list
if ($wc) { $wc = "`banlist_ip`='{$v}' OR ".$wc; }
if (($wc === false) || !e107::getIPHandler()->checkBan($wc, false, TRUE))
{
// echo "Email banned<br />";
$errMsg = ERR_BANNED_EMAIL;
}
}
if ($errMsg)
{
unset($targetData['data']['user_email']); // Remove the valid entry
}
}
else
{
if (!isset($targetData['errors']['user_email']) && !e107::getPref('disable_emailcheck'))
{ // We may have already picked up an error on the email address - or it may be allowed to be empty
$errMsg = ERR_MISSING_VALUE;
}
}
if ($errMsg)
{ // Update the error
$targetData['errors']['user_email'] = $errMsg;
$targetData['failed']['user_email'] = $v;
$ret = false;
}
return $ret;
}
/**
* Given an array of user data intended to be written to the DB, adds empty strings (or other default value) for any field which doesn't have a default in the SQL definition.
* (Avoids problems with MySQL in STRICT mode.).
*
* @param array $userInfo - user data destined for the database
*
* @return bool TRUE if additions made, false if no change.
*
* @todo - may be unnecessary with auto-generation of _NOTNULL array in db handler
*/
public function addNonDefaulted(&$userInfo)
{
// $nonDefaulted = array('user_signature' => '', 'user_prefs' => '', 'user_class' => '', 'user_perms' => '');
$nonDefaulted = array('user_signature' => '', 'user_prefs' => '', 'user_class' => '', 'user_perms' => '', 'user_realm' => ''); // Delete when McFly finished
$ret = false;
foreach ($nonDefaulted as $k => $v)
{
if (!isset($userInfo[$k]))
{
$userInfo[$k] = $v;
$ret = TRUE;
}
}
return $ret;
}
/**
* Delete time-expired partial registrations from the user DB, clean up user_extended table
*
* @param bool $force - set TRUE to force check of user_extended table
*
* @return int number of user records deleted
*/
public function deleteExpired($force = false)
{
$pref = e107::getPref();
$sql = e107::getDb();
$temp1 = 0;
if (isset($pref['del_unv']) && $pref['del_unv'] && intval($pref['user_reg_veri']) != 2)
{
$threshold= intval(time() - ($pref['del_unv'] * 60));
if(($temp1 = $sql->delete('user', 'user_ban = 2 AND user_join < '.$threshold)) > 0)
{
$force = true;
}
}
if ($force) // Remove 'orphaned' extended user field records
{
$sql->gen("DELETE `#user_extended` FROM `#user_extended` LEFT JOIN `#user` ON `#user_extended`.`user_extended_id` = `#user`.`user_id`
WHERE `#user`.`user_id` IS NULL");
}
return $temp1;
}
/**
* Called to update initial user classes, probationary user class etc after various user events
*
* @param array $user - user data. 'user_class' must be present
* @param string $event = userveri|userall|userfull|userpartial - defines event
*
* @return boolean - true if $user['user_class'] updated, false otherwise
*/
public function userClassUpdate($user, $event='userfull')
{
$pref = e107::getPref();
$tp = e107::getParser();
$initClassStage = isset($pref['init_class_stage']) ? intval($pref['init_class_stage']) : 0;
$initClasses = array();
$doClasses = false;
$doProbation = false;
$ret = false;
switch($event)
{
case 'userall':
$doClasses = true;
$doProbation = true;
break;
case 'userfull':
if(!$pref['user_reg_veri'] || ($initClassStage == 2))
{
$doClasses = true;
}
$doProbation = true;
break;