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 .
"or contains illegal characters.",
150 "The new password you requested is not valid.",
152 "The e-mail address you entered appears to be invalid.",
155 "An error occurred while attempting to send e-mail. " 156 .
"Please notify the system administrator.",
158 "An error occurred while attempting to generate e-mail. " 159 .
"Please notify the system administrator.",
161 "The e-mail address you supplied already has an account " 162 .
"associated with it.",
164 "The password you entered contains your username.",
166 "The password you entered contains your email address.",
169 "Passwords must be at least ".self::$PasswordMinLength
170 .
" characters long.",
172 "Passwords must have at least ".self::$PasswordMinUniqueChars
173 .
" different characters.",
175 "Passwords must contain at least one punctuation character.",
177 "Passwords must contain a mixture of uppercase and " 178 .
"lowercase letters",
180 "Passwords must contain at least one number.",
183 return (isset($APUserStatusMessages[$StatusCode]) ?
184 $APUserStatusMessages[$StatusCode] :
185 "Unknown user status code: ".$StatusCode );
190 # clear priv list values 191 $this->DB->Query(
"DELETE FROM APUserPrivileges WHERE UserId = '" 194 # delete user record from database 195 $this->DB->Query(
"DELETE FROM APUsers WHERE UserId = '".$this->UserId.
"'");
197 # report to caller that everything succeeded 209 if (is_callable($NewValue))
211 self::$EmailFunc = $NewValue;
215 # ---- Getting/Setting Values -------------------------------------------- 223 return $this->
Get(
"UserName");
233 $RealName = $this->
Get(
"RealName");
235 # the real name is available, so use it 236 if (strlen(trim($RealName)))
241 # the real name isn't available, so use the user name 242 return $this->
Get(
"UserName");
247 # return NULL if not associated with a particular user 248 if ($this->UserId === NULL) {
return NULL; }
252 $this->DB->Query(
"UPDATE APUsers SET" 253 .
" LastLocation = '".addslashes($NewLocation).
"'," 254 .
" LastActiveDate = NOW()," 255 .
" LastIPAddress = '".$_SERVER[
"REMOTE_ADDR"].
"'" 256 .
" WHERE UserId = '".addslashes($this->UserId).
"'");
257 if (isset($this->DBFields))
259 $this->DBFields[
"LastLocation"] = $NewLocation;
260 $this->DBFields[
"LastActiveDate"] = date(
"Y-m-d H:i:s");
263 return $this->
Get(
"LastLocation");
267 return $this->
Get(
"LastActiveDate");
271 return $this->
Get(
"LastIPAddress");
274 # get value from specified field 275 public function Get($FieldName)
277 # return NULL if not associated with a particular user 278 if ($this->UserId === NULL) {
return NULL; }
283 # get value (formatted as a date) from specified field 284 public function GetDate($FieldName, $Format =
"")
286 # return NULL if not associated with a particular user 287 if ($this->UserId === NULL) {
return NULL; }
289 # retrieve specified value from database 290 if (strlen($Format) > 0)
292 $this->DB->Query(
"SELECT DATE_FORMAT(`".addslashes($FieldName)
293 .
"`, '".addslashes($Format).
"') AS `".addslashes($FieldName)
294 .
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
298 $this->DB->Query(
"SELECT `".addslashes($FieldName).
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
300 $Record = $this->DB->FetchRow();
302 # return value to caller 303 return $Record[$FieldName];
306 # set value in specified field 307 public function Set($FieldName, $NewValue)
309 # return error if not associated with a particular user 312 # transform booleans to 0 or 1 for storage 313 if (is_bool($NewValue))
315 $NewValue = $NewValue ? 1 : 0;
325 # ---- Login Functions --------------------------------------------------- 327 public function Login($UserName, $Password, $IgnorePassword = FALSE)
329 # if user not found in DB 330 $this->DB->Query(
"SELECT * FROM APUsers" 331 .
" WHERE UserName = '" 332 .addslashes(self::NormalizeUserName($UserName)).
"'");
333 if ($this->DB->NumRowsSelected() < 1)
335 # result is no user by that name 340 # if user account not yet activated 341 $Record = $this->DB->FetchRow();
342 if (!$Record[
"RegistrationConfirmed"])
344 # result is user registration not confirmed 349 # grab password from DB 350 $StoredPassword = $Record[
"UserPassword"];
352 if (isset($Password[0]) && $Password[0] ==
" ")
354 $Challenge = md5(date(
"Ymd").$_SERVER[
"REMOTE_ADDR"]);
355 $StoredPassword = md5( $Challenge . $StoredPassword );
357 $EncryptedPassword = trim($Password);
361 # if supplied password matches encrypted password 362 $EncryptedPassword = crypt($Password, $StoredPassword);
365 if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
370 # store user ID for session 371 $this->UserId = $Record[
"UserId"];
374 # update last login date 375 $this->DB->Query(
"UPDATE APUsers SET LastLoginDate = NOW()," 377 .
" WHERE UserId = '".$this->UserId.
"'");
379 # Check for old format hashes, and rehash if possible 380 if ($EncryptedPassword === $StoredPassword &&
381 substr($StoredPassword, 0, 3) !==
"$1$" &&
382 $Password[0] !==
" " &&
385 $NewPassword = crypt($Password, self::GetSaltForCrypt() );
387 "UPDATE APUsers SET UserPassword='" 388 .addslashes($NewPassword).
"' " 389 .
"WHERE UserId='".$this->UserId.
"'");
392 # since self::DBFields might already have been set to false if 393 # the user wasn't logged in when this is called, populate it 394 # with user data so that a call to self::UpdateValue will be 395 # able to properly fetch the data associated with the user 396 $this->DBFields = $Record;
398 # set flag to indicate we are logged in 399 $this->LoggedIn = TRUE;
403 # result is bad password 409 # return result to caller 416 # clear user ID (if any) for session 417 unset($_SESSION[
"APUserId"]);
419 # if user is marked as logged in 422 # set flag to indicate user is no longer logged in 423 $this->LoggedIn = FALSE;
425 # clear login flag in database 427 "UPDATE APUsers SET LoggedIn = '0' " 428 .
"WHERE UserId='".$this->UserId.
"'");
435 "SELECT * FROM APUsers WHERE UserName = '" 436 .addslashes(self::NormalizeUserName($UserName)).
"'");
438 if ($this->DB->NumRowsSelected() < 1)
440 # result is no user by that name, generate a fake salt 441 # to discourage user enumeration. Make it be an old-format 442 # crypt() salt so that it's harder. 443 $SaltString = $_SERVER[
"SERVER_ADDR"].$UserName;
444 $Result = substr(base64_encode(md5($SaltString)), 0, 2);
448 # grab password from DB 449 # Assumes that we used php's crypt() for the passowrd 450 # management stuff, and will need to be changed if we 451 # go to something else. 452 $Record = $this->DB->FetchRow();
453 $StoredPassword = $Record[
"UserPassword"];
455 if (substr($StoredPassword, 0, 3) ===
"$1$")
457 $Result = substr($StoredPassword, 0, 12);
461 $Result = substr($StoredPassword, 0, 2);
475 if (!isset($this->LoggedIn))
477 $this->LoggedIn = $this->DB->Query(
" 478 SELECT LoggedIn FROM APUsers 479 WHERE UserId='".addslashes($this->UserId).
"'",
480 "LoggedIn") ? TRUE : FALSE;
501 return ($this->UserId === NULL) ? TRUE : FALSE;
505 # ---- Password Functions ------------------------------------------------ 507 # set new password (with checks against old password) 517 # return error if not associated with a particular user 518 if ($this->UserId === NULL)
523 # if old password is not correct 524 $StoredPassword = $this->DB->Query(
"SELECT UserPassword FROM APUsers" 525 .
" WHERE UserId='".$this->UserId.
"'",
"UserPassword");
526 $EncryptedPassword = crypt($OldPassword, $StoredPassword);
527 if ($EncryptedPassword != $StoredPassword)
529 # set status to indicate error 532 # else if both instances of new password do not match 533 elseif (self::NormalizePassword($NewPassword)
534 != self::NormalizePassword($NewPasswordAgain))
536 # set status to indicate error 539 # perform other validity checks 540 elseif (!self::IsValidPassword(
541 $NewPassword, $this->
Get(
"UserName"), $this->
Get(
"EMail")) )
543 # set status to indicate error 551 # set status to indicate password successfully changed 555 # report to caller that everything succeeded 562 # generate encrypted password 563 $EncryptedPassword = crypt(self::NormalizePassword($NewPassword),
564 self::GetSaltForCrypt() );
566 # save encrypted password 567 $this->
UpdateValue(
"UserPassword", $EncryptedPassword);
572 # save encrypted password 573 $this->
UpdateValue(
"UserPassword", $NewEncryptedPassword);
577 $UserName, $EMail, $EMailAgain,
578 $TemplateFile =
"Axis--User--EMailTemplate.txt")
581 $UserName, $EMail, $EMailAgain, $TemplateFile);
585 $UserName, $EMail, $EMailAgain,
586 $TemplateFile =
"Axis--User--EMailTemplate.txt")
588 # load e-mail template from file (first line is subject) 589 $Template = file($TemplateFile, 1);
590 $EMailSubject = array_shift($Template);
591 $EMailBody = join(
"", $Template);
594 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
598 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
600 # make sure e-mail addresses match 601 if ($EMail != $EMailAgain)
607 # make sure e-mail address looks valid 614 # generate random password 617 # attempt to create new user with password 618 $Result = $this->CreateNewUser($UserName, $Password, $Password);
620 # if user creation failed 623 # report error result to caller 629 # set e-mail address in user record 630 $this->
Set(
"EMail", $EMail);
632 # plug appropriate values into subject and body of e-mail message 633 $EMailSubject = str_replace(
"X-USERNAME-X", $UserName, $EMailSubject);
634 $EMailBody = str_replace(
"X-USERNAME-X", $UserName, $EMailBody);
635 $EMailBody = str_replace(
"X-PASSWORD-X", $Password, $EMailBody);
637 # send out e-mail message with new account info 638 if (is_Callable(self::$EmailFunc))
640 $Result = call_user_func(self::$EmailFunc,
641 $EMail, $EMailSubject, $EMailBody,
642 "Auto-Submitted: auto-generated");
646 $Result = mail($EMail, $EMailSubject, $EMailBody,
647 "Auto-Submitted: auto-generated");
650 # if mailing attempt failed 653 # report error to caller 660 # report success to caller 667 # get code for user to submit to confirm registration 670 # code is MD5 sum based on user name and encrypted password 671 $ActivationCodeLength = 6;
672 return $this->
GetUniqueCode(
"Activation", $ActivationCodeLength);
675 # check whether confirmation code is valid 682 # get/set whether user registration has been confirmed 685 return $this->
UpdateValue(
"RegistrationConfirmed", $NewValue);
688 # get code for user to submit to confirm password reset 691 # code is MD5 sum based on user name and encrypted password 692 $ResetCodeLength = 10;
696 # check whether password reset code is valid 699 return (strtoupper(trim($Code)) == $this->
GetResetCode())
703 # get code for user to submit to confirm mail change request 706 $ResetCodeLength = 10;
708 .$this->
Get(
"EMailNew"),
718 # send e-mail to user (returns TRUE on success) 720 $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
723 # if template is file name 724 if (@is_file($TemplateTextOrFileName))
726 # load in template from file 727 $Template = file($TemplateTextOrFileName, 1);
729 # report error to caller if template load failed 730 if ($Template == FALSE)
733 return $this->Status;
736 # join into one text block 737 $TemplateTextOrFileName = join(
"", $Template);
740 # split template into lines 741 $Template = explode(
"\n", $TemplateTextOrFileName);
743 # strip any comments out of template 744 $FilteredTemplate = array();
745 foreach ($Template as $Line)
747 if (!preg_match(
"/^[\\s]*#/", $Line))
749 $FilteredTemplate[] = $Line;
753 # split subject line out of template (first non-comment line in file) 754 $EMailSubject = array_shift($FilteredTemplate);
755 $EMailBody = join(
"\n", $FilteredTemplate);
757 # set up our substitutions 758 $Substitutions = array(
759 "X-USERNAME-X" => $this->
Get(
"UserName"),
760 "X-EMAILADDRESS-X" => $this->
Get(
"EMail"),
764 "X-IPADDRESS-X" => @$_SERVER[
"REMOTE_ADDR"],
767 # if caller provided additional substitutions 768 if (is_array($MoreSubstitutions))
770 # add in entries from caller to substitution list 771 $Substitutions = array_merge(
772 $Substitutions, $MoreSubstitutions);
775 # perform substitutions on subject and body of message 776 $EMailSubject = str_replace(array_keys($Substitutions),
777 array_values($Substitutions), $EMailSubject);
778 $EMailBody = str_replace(array_keys($Substitutions),
779 array_values($Substitutions), $EMailBody);
781 $AdditionalHeaders =
"Auto-Submitted: auto-generated";
783 # if caller provided "From" address 786 # prepend "From" address onto message 787 $AdditionalHeaders .=
"\r\nFrom: ".$FromAddress;
790 # send out mail message 791 if (is_Callable(self::$EmailFunc))
793 $Result = call_user_func(self::$EmailFunc,
794 is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
795 $EMailSubject, $EMailBody, $AdditionalHeaders);
799 $Result = mail(is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
801 $EMailBody, $AdditionalHeaders);
804 # report result of mailing attempt to caller 810 # ---- Privilege Functions ----------------------------------------------- 820 public function HasPriv($Privilege, $Privileges = NULL)
822 # return FALSE if not associated with a particular user 823 if ($this->UserId === NULL) {
return FALSE; }
825 # bail out if empty array of privileges passed in 826 if (is_array($Privilege) && !count($Privilege) && (func_num_args() < 2))
829 # set up beginning of database query 830 $Query =
"SELECT COUNT(*) AS PrivCount FROM APUserPrivileges " 831 .
"WHERE UserId='".$this->UserId.
"' AND (";
833 # add first privilege(s) to query (first arg may be single value or array) 834 if (is_array($Privilege))
837 foreach ($Privilege as $Priv)
839 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
845 $Query .=
"Privilege='".$Privilege.
"'";
849 # add any privileges from additional args to query 850 $Args = func_get_args();
852 foreach ($Args as $Arg)
854 $Query .= $Sep.
"Privilege='".$Arg.
"'";
861 # look for privilege in database 862 $PrivCount = $this->DB->Query($Query,
"PrivCount");
864 # return value to caller 865 return ($PrivCount > 0) ? TRUE : FALSE;
878 # set up beginning of database query 879 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 882 # add first privilege(s) to query (first arg may be single value or array) 883 if (is_array($Privilege))
886 foreach ($Privilege as $Priv)
888 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
894 $Query .=
"Privilege='".$Privilege.
"'";
898 # add any privileges from additional args to query 899 $Args = func_get_args();
901 foreach ($Args as $Arg)
903 $Query .= $Sep.
"Privilege='".$Arg.
"'";
907 # return query to caller 921 # set up beginning of database query 922 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 925 # add first privilege(s) to query (first arg may be single value or array) 926 if (is_array($Privilege))
929 foreach ($Privilege as $Priv)
931 $Query .= $Sep.
"Privilege != '".addslashes($Priv).
"'";
937 $Query .=
"Privilege != '".$Privilege.
"'";
941 # add any privileges from additional args to query 942 $Args = func_get_args();
944 foreach ($Args as $Arg)
946 $Query .= $Sep.
"Privilege != '".$Arg.
"'";
950 # return query to caller 956 # return error if not associated with a particular user 959 # if privilege value is invalid 960 if (intval($Privilege) != trim($Privilege))
962 # set code to indicate error 967 # if user does not already have privilege 968 $PrivCount = $this->DB->Query(
"SELECT COUNT(*) AS PrivCount" 969 .
" FROM APUserPrivileges" 970 .
" WHERE UserId='".$this->UserId.
"'" 971 .
" AND Privilege='".$Privilege.
"'",
975 # add privilege for this user to database 976 $this->DB->Query(
"INSERT INTO APUserPrivileges" 977 .
" (UserId, Privilege) VALUES" 978 .
" ('".$this->UserId.
"', ".$Privilege.
")");
981 # set code to indicate success 985 # report result to caller 991 # return error if not associated with a particular user 994 # remove privilege from database (if present) 995 $this->DB->Query(
"DELETE FROM APUserPrivileges" 996 .
" WHERE UserId = '".$this->UserId.
"'" 997 .
" AND Privilege = '".$Privilege.
"'");
999 # report success to caller 1006 # return empty list if not associated with a particular user 1007 if ($this->UserId === NULL) {
return array(); }
1009 # read privileges from database and return array to caller 1010 $this->DB->Query(
"SELECT Privilege FROM APUserPrivileges" 1011 .
" WHERE UserId='".$this->UserId.
"'");
1012 return $this->DB->FetchColumn(
"Privilege");
1017 # return error if not associated with a particular user 1020 # clear old priv list values 1021 $this->DB->Query(
"DELETE FROM APUserPrivileges" 1022 .
" WHERE UserId='".$this->UserId.
"'");
1024 # for each priv value passed in 1025 foreach ($NewPrivileges as $Privilege)
1040 # if we have a UserId in the session, move it aside 1041 if (isset($_SESSION[
"APUserId"]))
1043 $OldUserId = $_SESSION[
"APUserId"];
1044 unset($_SESSION[
"APUserId"]);
1047 # create a new anonymous user 1048 $CalledClass = get_called_class();
1052 # restore the $_SESSION value 1053 if (isset($OldUserId))
1055 $_SESSION[
"APUserId"] = $OldUserId;
1058 # return our anonymous user 1062 # ---- Miscellaneous Functions ------------------------------------------- 1064 # get unique alphanumeric code for user 1067 # return NULL if not associated with a particular user 1068 if ($this->UserId === NULL) {
return NULL; }
1070 return substr(strtoupper(md5(
1071 $this->
Get(
"UserName").$this->
Get(
"UserPassword").$SeedString)),
1076 # ---- PRIVATE INTERFACE ------------------------------------------------- 1078 protected $DB; # handle to SQL database we use to store user information
1079 protected $UserId = NULL; # user ID number
for reference into database
1081 protected $LoggedIn; # flag indicating whether user is logged in
1082 private $DBFields; # used
for caching user values
1084 # optional mail function to use instead of mail() 1085 private static $EmailFunc = NULL;
1087 # check whether a user name is valid (alphanumeric string of 2-24 chars) 1090 if (preg_match(
"/^[a-zA-Z0-9]{2,24}$/", $UserName))
1100 # check whether a password is valid (at least 6 characters) 1102 $Password, $UserName, $Email)
1104 return count(self::CheckPasswordForErrors(
1105 $Password, $UserName, $Email)) == 0 ?
1119 $Password, $UserName = NULL, $Email = NULL)
1121 # start off assuming no errors 1124 # normalize incoming password 1125 $Password = self::NormalizePassword($Password);
1127 # username provided and password contains username 1128 if ($UserName !== NULL &&
1129 stripos($Password, $UserName) !== FALSE)
1134 # email provided and password contains email 1135 if ($Email !== NULL &&
1136 stripos($Password, $Email) !== FALSE)
1141 # length requirement 1142 if (strlen($Password) == 0)
1146 elseif (strlen($Password) < self::$PasswordMinLength)
1151 # unique characters requirement 1152 $UniqueChars = count(array_unique(
1153 preg_split(
'//u', $Password, NULL, PREG_SPLIT_NO_EMPTY)));
1155 if ($UniqueChars < self::$PasswordMinUniqueChars)
1160 # for the following complexity checks, use unicode character properties 1161 # in PCRE as in: http://php.net/manual/en/regexp.reference.unicode.php 1163 # check for punctuation, uppercase letters, and numbers as per the system 1165 if (self::$PasswordRules & self::PW_REQUIRE_PUNCTUATION &&
1166 !preg_match(
'/\p{P}/u', $Password) )
1171 if (self::$PasswordRules & self::PW_REQUIRE_MIXEDCASE &&
1172 (!preg_match(
'/\p{Lu}/u', $Password) ||
1173 !preg_match(
'/\p{Ll}/u', $Password) ) )
1179 if (self::$PasswordRules & self::PW_REQUIRE_DIGITS &&
1180 !preg_match(
'/\p{N}/u', $Password))
1188 # check whether an e-mail address looks valid 1191 if (preg_match(
"/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/",
1202 # get normalized version of e-mail address 1205 return strtolower(trim($EMailAddress));
1208 # get normalized version of user name 1211 return trim($UserName);
1214 # get normalized version of password 1217 return trim($Password);
1220 # generate random password 1223 # seed random number generator 1224 mt_srand((
double)microtime() * 1000000);
1226 # generate password of requested length 1227 return sprintf(
"%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
1228 (pow(10, $PasswordMaxLength) - 1)));
1231 # convenience function to supply parameters to Database->UpdateValue() 1234 return $this->DB->UpdateValue(
"APUsers", $FieldName, $NewValue,
1235 "UserId = '".$this->UserId.
"'", $this->DBFields);
1238 # methods for backward compatibility with earlier versions of User 1251 self::$PasswordRules = $NewValue;
1260 self::$PasswordMinLength = $NewValue;
1269 self::$PasswordMinUniqueChars = $NewValue;
1278 return "Passwords are case-sensitive, cannot contain your username or email, " 1279 .
"must be at least ".self::$PasswordMinLength
1280 .
" characters long, " 1281 .
" have at least ".self::$PasswordMinUniqueChars
1282 .
" different characters" 1283 .(self::$PasswordRules & self::PW_REQUIRE_PUNCTUATION ?
1284 ", include punctuation":
"")
1285 .(self::$PasswordRules & self::PW_REQUIRE_MIXEDCASE ?
1286 ", include capital and lowercase letters":
"")
1287 .(self::$PasswordRules & self::PW_REQUIRE_DIGITS ?
1288 ", include a number":
"").
".";
1294 private static function GetSaltForCrypt()
1296 # generate a password salt by grabbing CRYPT_SALT_LENGTH 1297 # random bytes, then base64 encoding while filtering out 1298 # non-alphanumeric characters to get a string all the hashes 1300 $Salt = preg_replace(
"/[^A-Za-z0-9]/",
"",
1301 base64_encode(openssl_random_pseudo_bytes(
1302 CRYPT_SALT_LENGTH) ));
1304 # select the best available hashing algorithm, provide a salt 1305 # in the correct format for that algorithm 1306 if (CRYPT_SHA512==1)
1308 return '$6$'.substr($Salt, 0, 16);
1310 elseif (CRYPT_SHA256==1)
1312 return '$5$'.substr($Salt, 0, 16);
1314 elseif (CRYPT_BLOWFISH==1)
1316 return '$2y$'.substr($Salt, 0, 22);
1318 elseif (CRYPT_MD5==1)
1320 return '$1$'.substr($Salt, 0, 12);
1322 elseif (CRYPT_EXT_DES==1)
1324 return '_'.substr($Salt, 0, 8);
1328 return substr($Salt, 0, 2);
1332 private static $PasswordMinLength = 6;
1333 private static $PasswordMinUniqueChars = 4;
1335 # default to no additional requirements beyond length 1336 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)
CreateNewUserAndMailPassword($UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
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="")
CreateNewUserWithEMailedPassword($UserName, $EMail, $EMailAgain, $TemplateFile="Axis--User--EMailTemplate.txt")
IsNotLoggedIn()
Report whether user is not currently logged in.
CreateNewUserAndMailPasswordFromFile($UserName, $EMail, $EMailAgain, $TemplateFile="Axis--User--EMailTemplate.txt")
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