4 # An Object for Handling User Information 6 # Copyright 1999-2001 Axis Data 7 # This code is free software that can be used or redistributed under the 8 # terms of Version 2 of the GNU General Public License, as published by the 9 # Free Software Foundation (http://www.fsf.org). 11 # Author: Edward Almasy (almasy@axisdata.com) 13 # Part of the AxisPHP library v1.2.4 14 # For more information see http://www.axisdata.com/AxisPHP/ 17 # status values (error codes) 20 define(
"U_BADPASSWORD", 2);
21 define(
"U_NOSUCHUSER", 3);
22 define(
"U_PASSWORDSDONTMATCH", 4);
23 define(
"U_EMAILSDONTMATCH", 5);
24 define(
"U_DUPLICATEUSERNAME", 6);
25 define(
"U_ILLEGALUSERNAME", 7);
26 define(
"U_EMPTYUSERNAME", 8);
27 define(
"U_ILLEGALPASSWORD", 9);
28 define(
"U_ILLEGALPASSWORDAGAIN", 10);
29 define(
"U_EMPTYPASSWORD", 11);
30 define(
"U_EMPTYPASSWORDAGAIN", 12);
31 define(
"U_ILLEGALEMAIL", 13);
32 define(
"U_ILLEGALEMAILAGAIN", 14);
33 define(
"U_EMPTYEMAIL", 15);
34 define(
"U_EMPTYEMAILAGAIN", 16);
35 define(
"U_NOTLOGGEDIN", 17);
36 define(
"U_MAILINGERROR", 18);
37 define(
"U_TEMPLATENOTFOUND", 19);
38 define(
"U_DUPLICATEEMAIL", 20);
39 define(
"U_NOTACTIVATED", 21);
40 define(
"U_PASSWORDCONTAINSUSERNAME", 22);
41 define(
"U_PASSWORDCONTAINSEMAIL", 23);
42 define(
"U_PASSWORDTOOSHORT", 24);
43 define(
"U_PASSWORDTOOSIMPLE", 25);
44 define(
"U_PASSWORDNEEDSPUNCTUATION", 26);
45 define(
"U_PASSWORDNEEDSMIXEDCASE", 27);
46 define(
"U_PASSWORDNEEDSDIGIT", 28);
50 # ---- CLASS CONSTANTS --------------------------------------------------- 55 # ---- PUBLIC INTERFACE -------------------------------------------------- 57 public function __construct($UserInfoOne = NULL, $UserInfoTwo = NULL)
59 # create database connection 62 # if we're looking up a user by UserId 63 if (is_numeric($UserInfoOne) || is_numeric($UserInfoTwo))
65 $UserId = is_numeric($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
66 $this->DB->Query(
"SELECT * FROM APUsers" 67 .
" WHERE UserId='".intval(
$UserId).
"'");
68 $Record = $this->DB->FetchRow();
70 # if we're looking up a user by name or email address 71 elseif (is_string($UserInfoOne) || is_string($UserInfoTwo))
73 $UserName = is_string($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
74 $this->DB->Query(
"SELECT * FROM APUsers" 75 .
" WHERE UserName='".addslashes($UserName).
"'");
76 $Record = $this->DB->FetchRow();
78 if ($Record === FALSE)
80 $this->DB->Query(
"SELECT * FROM APUsers" 81 .
" WHERE EMail='".addslashes(
82 self::NormalizeEMailAddress($UserName)).
"'");
83 $Record = $this->DB->FetchRow();
86 # if a UserId is available from the session 87 elseif (isset($_SESSION[
"APUserId"]))
89 $UserId = $_SESSION[
"APUserId"];
90 $this->DB->Query(
"SELECT * FROM APUsers" 91 .
" WHERE UserId='".intval(
$UserId).
"'");
92 $Record = $this->DB->FetchRow();
94 # otherwise, create an anonymous user 102 # if a record was found, load data from it 103 if ($Record !== FALSE)
105 $this->DBFields = $Record;
106 $this->UserId = $Record[
"UserId"];
107 $this->LoggedIn = $Record[
"LoggedIn"] ? TRUE : FALSE;
112 # otherwise, set code indicating no user found 122 # return text message corresponding to current status code 125 return self::GetStatusMessageForCode($this->Result);
135 $APUserStatusMessages = array(
136 U_OKAY =>
"The operation was successful.",
137 U_ERROR =>
"There has been an error.",
141 "The new passwords you entered do not match.",
143 "The e-mail addresses you entered do not match.",
145 "The user name you requested is already in use.",
147 "The user name you requested is too short, too long, " 148 .
"does not start with a letter, " 149 .
"or contains illegal characters.",
151 "The new password you requested is not valid.",
153 "The e-mail address you entered appears to be invalid.",
156 "An error occurred while attempting to send e-mail. " 157 .
"Please notify the system administrator.",
159 "An error occurred while attempting to generate e-mail. " 160 .
"Please notify the system administrator.",
162 "The e-mail address you supplied already has an account " 163 .
"associated with it.",
165 "The password you entered contains your username.",
167 "The password you entered contains your email address.",
170 "Passwords must be at least ".self::$PasswordMinLength
171 .
" characters long.",
173 "Passwords must have at least ".self::$PasswordMinUniqueChars
174 .
" different characters.",
176 "Passwords must contain at least one punctuation character.",
178 "Passwords must contain a mixture of uppercase and " 179 .
"lowercase letters",
181 "Passwords must contain at least one number.",
184 return (isset($APUserStatusMessages[$StatusCode]) ?
185 $APUserStatusMessages[$StatusCode] :
186 "Unknown user status code: ".$StatusCode );
191 # clear priv list values 192 $this->DB->Query(
"DELETE FROM APUserPrivileges WHERE UserId = '" 195 # delete user record from database 196 $this->DB->Query(
"DELETE FROM APUsers WHERE UserId = '".$this->UserId.
"'");
198 # report to caller that everything succeeded 210 if (is_callable($NewValue))
212 self::$EmailFunc = $NewValue;
216 # ---- Getting/Setting Values -------------------------------------------- 224 return $this->
Get(
"UserName");
234 $RealName = $this->
Get(
"RealName");
236 # the real name is available, so use it 237 if (strlen(trim($RealName)))
242 # the real name isn't available, so use the user name 243 return $this->
Get(
"UserName");
248 # return NULL if not associated with a particular user 249 if ($this->UserId === NULL) {
return NULL; }
253 $this->DB->Query(
"UPDATE APUsers SET" 254 .
" LastLocation = '".addslashes($NewLocation).
"'," 255 .
" LastActiveDate = NOW()," 256 .
" LastIPAddress = '".$_SERVER[
"REMOTE_ADDR"].
"'" 257 .
" WHERE UserId = '".addslashes($this->UserId).
"'");
258 if (isset($this->DBFields))
260 $this->DBFields[
"LastLocation"] = $NewLocation;
261 $this->DBFields[
"LastActiveDate"] = date(
"Y-m-d H:i:s");
264 return $this->
Get(
"LastLocation");
268 return $this->
Get(
"LastActiveDate");
272 return $this->
Get(
"LastIPAddress");
275 # get value from specified field 276 public function Get($FieldName)
278 # return NULL if not associated with a particular user 279 if ($this->UserId === NULL) {
return NULL; }
284 # get value (formatted as a date) from specified field 285 public function GetDate($FieldName, $Format =
"")
287 # return NULL if not associated with a particular user 288 if ($this->UserId === NULL) {
return NULL; }
290 # retrieve specified value from database 291 if (strlen($Format) > 0)
293 $this->DB->Query(
"SELECT DATE_FORMAT(`".addslashes($FieldName)
294 .
"`, '".addslashes($Format).
"') AS `".addslashes($FieldName)
295 .
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
299 $this->DB->Query(
"SELECT `".addslashes($FieldName).
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
301 $Record = $this->DB->FetchRow();
303 # return value to caller 304 return $Record[$FieldName];
307 # set value in specified field 308 public function Set($FieldName, $NewValue)
310 # return error if not associated with a particular user 313 # transform booleans to 0 or 1 for storage 314 if (is_bool($NewValue))
316 $NewValue = $NewValue ? 1 : 0;
326 # ---- Login Functions --------------------------------------------------- 328 public function Login($UserName, $Password, $IgnorePassword = FALSE)
330 # if user not found in DB 331 $this->DB->Query(
"SELECT * FROM APUsers" 332 .
" WHERE UserName = '" 333 .addslashes(self::NormalizeUserName($UserName)).
"'");
334 if ($this->DB->NumRowsSelected() < 1)
336 # result is no user by that name 341 # if user account not yet activated 342 $Record = $this->DB->FetchRow();
343 if (!$Record[
"RegistrationConfirmed"])
345 # result is user registration not confirmed 350 # grab password from DB 351 $StoredPassword = $Record[
"UserPassword"];
353 if (isset($Password[0]) && $Password[0] ==
" ")
355 $Challenge = md5(date(
"Ymd").$_SERVER[
"REMOTE_ADDR"]);
356 $StoredPassword = md5( $Challenge . $StoredPassword );
358 $EncryptedPassword = trim($Password);
362 # if supplied password matches encrypted password 363 $EncryptedPassword = crypt($Password, $StoredPassword);
366 if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
371 # store user ID for session 372 $this->UserId = $Record[
"UserId"];
375 # update last login date 376 $this->DB->Query(
"UPDATE APUsers SET LastLoginDate = NOW()," 378 .
" WHERE UserId = '".$this->UserId.
"'");
380 # Check for old format hashes, and rehash if possible 381 if ($EncryptedPassword === $StoredPassword &&
382 substr($StoredPassword, 0, 3) !==
"$1$" &&
383 $Password[0] !==
" " &&
386 $NewPassword = crypt($Password, self::GetSaltForCrypt() );
388 "UPDATE APUsers SET UserPassword='" 389 .addslashes($NewPassword).
"' " 390 .
"WHERE UserId='".$this->UserId.
"'");
393 # since self::DBFields might already have been set to false if 394 # the user wasn't logged in when this is called, populate it 395 # with user data so that a call to self::UpdateValue will be 396 # able to properly fetch the data associated with the user 397 $this->DBFields = $Record;
399 # set flag to indicate we are logged in 400 $this->LoggedIn = TRUE;
404 # result is bad password 410 # return result to caller 417 # clear user ID (if any) for session 418 unset($_SESSION[
"APUserId"]);
420 # if user is marked as logged in 423 # set flag to indicate user is no longer logged in 424 $this->LoggedIn = FALSE;
426 # clear login flag in database 428 "UPDATE APUsers SET LoggedIn = '0' " 429 .
"WHERE UserId='".$this->UserId.
"'");
436 "SELECT * FROM APUsers WHERE UserName = '" 437 .addslashes(self::NormalizeUserName($UserName)).
"'");
439 if ($this->DB->NumRowsSelected() < 1)
441 # result is no user by that name, generate a fake salt 442 # to discourage user enumeration. Make it be an old-format 443 # crypt() salt so that it's harder. 444 $SaltString = $_SERVER[
"SERVER_ADDR"].$UserName;
445 $Result = substr(base64_encode(md5($SaltString)), 0, 2);
449 # grab password from DB 450 # Assumes that we used php's crypt() for the passowrd 451 # management stuff, and will need to be changed if we 452 # go to something else. 453 $Record = $this->DB->FetchRow();
454 $StoredPassword = $Record[
"UserPassword"];
456 if (substr($StoredPassword, 0, 3) ===
"$1$")
458 $Result = substr($StoredPassword, 0, 12);
462 $Result = substr($StoredPassword, 0, 2);
476 if (!isset($this->LoggedIn))
478 $this->LoggedIn = $this->DB->Query(
" 479 SELECT LoggedIn FROM APUsers 480 WHERE UserId='".addslashes($this->UserId).
"'",
481 "LoggedIn") ? TRUE : FALSE;
502 return ($this->UserId === NULL) ? TRUE : FALSE;
506 # ---- Password Functions ------------------------------------------------ 508 # set new password (with checks against old password) 518 # return error if not associated with a particular user 519 if ($this->UserId === NULL)
524 # if old password is not correct 525 $StoredPassword = $this->DB->Query(
"SELECT UserPassword FROM APUsers" 526 .
" WHERE UserId='".$this->UserId.
"'",
"UserPassword");
527 $EncryptedPassword = crypt($OldPassword, $StoredPassword);
528 if ($EncryptedPassword != $StoredPassword)
530 # set status to indicate error 533 # else if both instances of new password do not match 534 elseif (self::NormalizePassword($NewPassword)
535 != self::NormalizePassword($NewPasswordAgain))
537 # set status to indicate error 540 # perform other validity checks 541 elseif (!self::IsValidPassword(
542 $NewPassword, $this->
Get(
"UserName"), $this->
Get(
"EMail")) )
544 # set status to indicate error 552 # set status to indicate password successfully changed 556 # report to caller that everything succeeded 563 # generate encrypted password 564 $EncryptedPassword = crypt(self::NormalizePassword($NewPassword),
565 self::GetSaltForCrypt() );
567 # save encrypted password 568 $this->
UpdateValue(
"UserPassword", $EncryptedPassword);
573 # save encrypted password 574 $this->
UpdateValue(
"UserPassword", $NewEncryptedPassword);
577 # get code for user to submit to confirm registration 580 # code is MD5 sum based on user name and encrypted password 581 $ActivationCodeLength = 6;
582 return $this->
GetUniqueCode(
"Activation", $ActivationCodeLength);
585 # check whether confirmation code is valid 592 # get/set whether user registration has been confirmed 595 return $this->
UpdateValue(
"RegistrationConfirmed", $NewValue);
598 # get code for user to submit to confirm password reset 601 # code is MD5 sum based on user name and encrypted password 602 $ResetCodeLength = 10;
606 # check whether password reset code is valid 609 return (strtoupper(trim($Code)) == $this->
GetResetCode())
613 # get code for user to submit to confirm mail change request 616 $ResetCodeLength = 10;
618 .$this->
Get(
"EMailNew"),
628 # send e-mail to user (returns TRUE on success) 630 $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
633 # if template is file name 634 if (@is_file($TemplateTextOrFileName))
636 # load in template from file 637 $Template = file($TemplateTextOrFileName, 1);
639 # report error to caller if template load failed 640 if ($Template == FALSE)
646 # join into one text block 647 $TemplateTextOrFileName = join(
"", $Template);
650 # split template into lines 651 $Template = explode(
"\n", $TemplateTextOrFileName);
653 # strip any comments out of template 654 $FilteredTemplate = array();
655 foreach ($Template as $Line)
657 if (!preg_match(
"/^[\\s]*#/", $Line))
659 $FilteredTemplate[] = $Line;
663 # split subject line out of template (first non-comment line in file) 664 $EMailSubject = array_shift($FilteredTemplate);
665 $EMailBody = join(
"\n", $FilteredTemplate);
667 # set up our substitutions 668 $Substitutions = array(
669 "X-USERNAME-X" => $this->
Get(
"UserName"),
670 "X-EMAILADDRESS-X" => $this->
Get(
"EMail"),
674 "X-IPADDRESS-X" => @$_SERVER[
"REMOTE_ADDR"],
677 # if caller provided additional substitutions 678 if (is_array($MoreSubstitutions))
680 # add in entries from caller to substitution list 681 $Substitutions = array_merge(
682 $Substitutions, $MoreSubstitutions);
685 # perform substitutions on subject and body of message 686 $EMailSubject = str_replace(array_keys($Substitutions),
687 array_values($Substitutions), $EMailSubject);
688 $EMailBody = str_replace(array_keys($Substitutions),
689 array_values($Substitutions), $EMailBody);
691 $AdditionalHeaders =
"Auto-Submitted: auto-generated";
693 # if caller provided "From" address 696 # prepend "From" address onto message 697 $AdditionalHeaders .=
"\r\nFrom: ".$FromAddress;
700 # send out mail message 701 if (is_callable(self::$EmailFunc))
703 $Result = call_user_func(self::$EmailFunc,
704 is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
705 $EMailSubject, $EMailBody, $AdditionalHeaders);
709 $Result = mail(is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
711 $EMailBody, $AdditionalHeaders);
714 # report result of mailing attempt to caller 720 # ---- Privilege Functions ----------------------------------------------- 730 public function HasPriv($Privilege, $Privileges = NULL)
732 # return FALSE if not associated with a particular user 733 if ($this->UserId === NULL) {
return FALSE; }
735 # bail out if empty array of privileges passed in 736 if (is_array($Privilege) && !count($Privilege) && (func_num_args() < 2))
739 # set up beginning of database query 740 $Query =
"SELECT COUNT(*) AS PrivCount FROM APUserPrivileges " 741 .
"WHERE UserId='".$this->UserId.
"' AND (";
743 # add first privilege(s) to query (first arg may be single value or array) 744 if (is_array($Privilege))
747 foreach ($Privilege as $Priv)
749 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
755 $Query .=
"Privilege='".$Privilege.
"'";
759 # add any privileges from additional args to query 760 $Args = func_get_args();
762 foreach ($Args as $Arg)
764 $Query .= $Sep.
"Privilege='".$Arg.
"'";
771 # look for privilege in database 772 $PrivCount = $this->DB->Query($Query,
"PrivCount");
774 # return value to caller 775 return ($PrivCount > 0) ? TRUE : FALSE;
788 # set up beginning of database query 789 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 792 # add first privilege(s) to query (first arg may be single value or array) 793 if (is_array($Privilege))
796 foreach ($Privilege as $Priv)
798 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
804 $Query .=
"Privilege='".$Privilege.
"'";
808 # add any privileges from additional args to query 809 $Args = func_get_args();
811 foreach ($Args as $Arg)
813 $Query .= $Sep.
"Privilege='".$Arg.
"'";
817 # return query to caller 831 # set up beginning of database query 832 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 835 # add first privilege(s) to query (first arg may be single value or array) 836 if (is_array($Privilege))
839 foreach ($Privilege as $Priv)
841 $Query .= $Sep.
"Privilege != '".addslashes($Priv).
"'";
847 $Query .=
"Privilege != '".$Privilege.
"'";
851 # add any privileges from additional args to query 852 $Args = func_get_args();
854 foreach ($Args as $Arg)
856 $Query .= $Sep.
"Privilege != '".$Arg.
"'";
860 # return query to caller 866 # return error if not associated with a particular user 869 # if privilege value is invalid 870 if (intval($Privilege) != trim($Privilege))
872 # set code to indicate error 877 # if user does not already have privilege 878 $PrivCount = $this->DB->Query(
"SELECT COUNT(*) AS PrivCount" 879 .
" FROM APUserPrivileges" 880 .
" WHERE UserId='".$this->UserId.
"'" 881 .
" AND Privilege='".$Privilege.
"'",
885 # add privilege for this user to database 886 $this->DB->Query(
"INSERT INTO APUserPrivileges" 887 .
" (UserId, Privilege) VALUES" 888 .
" ('".$this->UserId.
"', ".$Privilege.
")");
891 # set code to indicate success 895 # report result to caller 901 # return error if not associated with a particular user 904 # remove privilege from database (if present) 905 $this->DB->Query(
"DELETE FROM APUserPrivileges" 906 .
" WHERE UserId = '".$this->UserId.
"'" 907 .
" AND Privilege = '".$Privilege.
"'");
909 # report success to caller 916 # return empty list if not associated with a particular user 917 if ($this->UserId === NULL) {
return array(); }
919 # read privileges from database and return array to caller 920 $this->DB->Query(
"SELECT Privilege FROM APUserPrivileges" 921 .
" WHERE UserId='".$this->UserId.
"'");
922 return $this->DB->FetchColumn(
"Privilege");
927 # return error if not associated with a particular user 930 # clear old priv list values 931 $this->DB->Query(
"DELETE FROM APUserPrivileges" 932 .
" WHERE UserId='".$this->UserId.
"'");
934 # for each priv value passed in 935 foreach ($NewPrivileges as $Privilege)
950 # if we have a UserId in the session, move it aside 951 if (isset($_SESSION[
"APUserId"]))
953 $OldUserId = $_SESSION[
"APUserId"];
954 unset($_SESSION[
"APUserId"]);
957 # create a new anonymous user 958 $CalledClass = get_called_class();
962 # restore the $_SESSION value 963 if (isset($OldUserId))
965 $_SESSION[
"APUserId"] = $OldUserId;
968 # return our anonymous user 972 # ---- Miscellaneous Functions ------------------------------------------- 974 # get unique alphanumeric code for user 977 # return NULL if not associated with a particular user 978 if ($this->UserId === NULL) {
return NULL; }
980 return substr(strtoupper(md5(
981 $this->
Get(
"UserName").$this->
Get(
"UserPassword").$SeedString)),
986 # ---- PRIVATE INTERFACE ------------------------------------------------- 988 protected $DB; # handle to SQL database we use to store user information
989 protected $UserId = NULL; # user ID number
for reference into database
991 protected $LoggedIn; # flag indicating whether user is logged in
994 private $DBFields; # used
for caching user values
996 # optional mail function to use instead of mail() 997 private static $EmailFunc = NULL;
999 # check whether a user name is valid 1000 # (alphanumeric string of 2-24 chars that starts with a letter) 1003 if (preg_match(
"/^[a-zA-Z][a-zA-Z0-9]{1,23}$/", $UserName))
1010 # check whether a password is valid (at least 6 characters) 1012 $Password, $UserName, $Email)
1014 return count(self::CheckPasswordForErrors(
1015 $Password, $UserName, $Email)) == 0 ?
1029 $Password, $UserName = NULL, $Email = NULL)
1031 # start off assuming no errors 1034 # normalize incoming password 1035 $Password = self::NormalizePassword($Password);
1037 # username provided and password contains username 1038 if ($UserName !== NULL &&
1039 stripos($Password, $UserName) !== FALSE)
1044 # email provided and password contains email 1045 if ($Email !== NULL &&
1046 stripos($Password, $Email) !== FALSE)
1051 # length requirement 1052 if (strlen($Password) == 0)
1056 elseif (strlen($Password) < self::$PasswordMinLength)
1061 # unique characters requirement 1062 $UniqueChars = count(array_unique(
1063 preg_split(
'//u', $Password, NULL, PREG_SPLIT_NO_EMPTY)));
1065 if ($UniqueChars < self::$PasswordMinUniqueChars)
1070 # for the following complexity checks, use unicode character properties 1071 # in PCRE as in: http://php.net/manual/en/regexp.reference.unicode.php 1073 # check for punctuation, uppercase letters, and numbers as per the system 1075 if (self::$PasswordRules & self::PW_REQUIRE_PUNCTUATION &&
1076 !preg_match(
'/\p{P}/u', $Password) )
1081 if (self::$PasswordRules & self::PW_REQUIRE_MIXEDCASE &&
1082 (!preg_match(
'/\p{Lu}/u', $Password) ||
1083 !preg_match(
'/\p{Ll}/u', $Password) ) )
1089 if (self::$PasswordRules & self::PW_REQUIRE_DIGITS &&
1090 !preg_match(
'/\p{N}/u', $Password))
1098 # check whether an e-mail address looks valid 1101 if (preg_match(
"/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/",
1112 # get normalized version of e-mail address 1115 return strtolower(trim($EMailAddress));
1118 # get normalized version of user name 1121 return trim($UserName);
1124 # get normalized version of password 1127 return trim($Password);
1130 # generate random password 1133 # seed random number generator 1134 mt_srand((
double)microtime() * 1000000);
1136 # generate password of requested length 1137 return sprintf(
"%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
1138 (pow(10, $PasswordMaxLength) - 1)));
1141 # convenience function to supply parameters to Database->UpdateValue() 1144 return $this->DB->UpdateValue(
"APUsers", $FieldName, $NewValue,
1145 "UserId = '".$this->UserId.
"'", $this->DBFields);
1148 # methods for backward compatibility with earlier versions of User 1161 self::$PasswordRules = $NewValue;
1170 self::$PasswordMinLength = $NewValue;
1179 self::$PasswordMinUniqueChars = $NewValue;
1188 return "Passwords are case-sensitive, cannot contain your username or email, " 1189 .
"must be at least ".self::$PasswordMinLength
1190 .
" characters long, " 1191 .
" have at least ".self::$PasswordMinUniqueChars
1192 .
" different characters" 1193 .(self::$PasswordRules & self::PW_REQUIRE_PUNCTUATION ?
1194 ", include punctuation":
"")
1195 .(self::$PasswordRules & self::PW_REQUIRE_MIXEDCASE ?
1196 ", include capital and lowercase letters":
"")
1197 .(self::$PasswordRules & self::PW_REQUIRE_DIGITS ?
1198 ", include a number":
"").
".";
1204 private static function GetSaltForCrypt()
1206 # generate a password salt by grabbing CRYPT_SALT_LENGTH 1207 # random bytes, then base64 encoding while filtering out 1208 # non-alphanumeric characters to get a string all the hashes 1210 $Salt = preg_replace(
"/[^A-Za-z0-9]/",
"",
1211 base64_encode(openssl_random_pseudo_bytes(
1212 CRYPT_SALT_LENGTH) ));
1214 # select the best available hashing algorithm, provide a salt 1215 # in the correct format for that algorithm 1216 if (CRYPT_SHA512==1)
1218 return '$6$'.substr($Salt, 0, 16);
1220 elseif (CRYPT_SHA256==1)
1222 return '$5$'.substr($Salt, 0, 16);
1224 elseif (CRYPT_BLOWFISH==1)
1226 return '$2y$'.substr($Salt, 0, 22);
1228 elseif (CRYPT_MD5==1)
1230 return '$1$'.substr($Salt, 0, 12);
1232 elseif (CRYPT_EXT_DES==1)
1234 return '_'.substr($Salt, 0, 8);
1238 return substr($Salt, 0, 2);
1242 private static $PasswordMinLength = 6;
1243 private static $PasswordMinUniqueChars = 4;
1245 # default to no additional requirements beyond length 1246 private static $PasswordRules = 0;
GetRandomPassword($PasswordMinLength=6, $PasswordMaxLength=8)
static GetAnonymousUser()
Get the anonymous user (i.e., the User object that exists when no user is logged in), useful when a permission check needs to know if something should be visible to the general public.
static NormalizeUserName($UserName)
IsLoggedIn()
Report whether user is currently logged in.
static IsValidLookingEMailAddress($EMail)
static SetPasswordMinLength($NewValue)
Set password minimum length.
GetUniqueCode($SeedString, $CodeLength)
__construct($UserInfoOne=NULL, $UserInfoTwo=NULL)
SQL database abstraction object with smart query caching.
static CheckPasswordForErrors($Password, $UserName=NULL, $Email=NULL)
Determine if a provided password complies with the configured rules, optionally checking that it does...
IsMailChangeCodeGood($Code)
UpdateValue($FieldName, $NewValue=DB_NOVALUE)
static NormalizePassword($Password)
const U_PASSWORDNEEDSPUNCTUATION
const U_PASSWORDNEEDSDIGIT
Login($UserName, $Password, $IgnorePassword=FALSE)
SetEncryptedPassword($NewEncryptedPassword)
const U_PASSWORDCONTAINSEMAIL
const PW_REQUIRE_MIXEDCASE
static IsValidUserName($UserName)
static GetSqlQueryForUsersWithPriv($Privilege, $Privileges=NULL)
Get an SQL query that will return IDs of all users that have the specified privilege flags...
GetPasswordSalt($UserName)
LastLocation($NewLocation=NULL)
static SetPasswordMinUniqueChars($NewValue)
Set password minimum unique characters.
static SetPasswordRules($NewValue)
Set password requirements.
IsActivated($NewValue=DB_NOVALUE)
static GetStatusMessageForCode($StatusCode)
Get text error message for a specified error code.
const PW_REQUIRE_PUNCTUATION
HasPriv($Privilege, $Privileges=NULL)
Check whether user has specified privilege(s).
const U_PASSWORDNEEDSMIXEDCASE
GetBestName()
Get the best available name associated with a user, i.e., the real name or, if it isn't available...
SendEMail($TemplateTextOrFileName, $FromAddress=NULL, $MoreSubstitutions=NULL, $ToAddress=NULL)
const U_PASSWORDCONTAINSUSERNAME
const U_PASSWORDTOOSIMPLE
Set($FieldName, $NewValue)
IsAnonymous()
Report whether user is anonymous user.
static GetPasswordRulesDescription()
Get a string describing the password rules.
const U_DUPLICATEUSERNAME
static SetEmailFunction($NewValue)
Set email function to use instead of mail().
static IsValidPassword($Password, $UserName, $Email)
static NormalizeEMailAddress($EMailAddress)
GetDate($FieldName, $Format="")
IsNotLoggedIn()
Report whether user is not currently logged in.
SetPassword($NewPassword)
SetPrivList($NewPrivileges)
ChangePassword($OldPassword, $NewPassword, $NewPasswordAgain)
Check provided password and set a new one if it war correct.
IsActivationCodeGood($Code)
static GetSqlQueryForUsersWithoutPriv($Privilege, $Privileges=NULL)
Get an SQL query that will return IDs of all users that do not have the specified privilege flags...
const U_PASSWORDSDONTMATCH