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 # assume constructor will succeed and user is not logged in 62 # create database connection 65 # if user info passed in 66 if (is_numeric($UserInfoOne) || is_string($UserInfoOne)
67 || is_numeric($UserInfoTwo) || is_string($UserInfoTwo))
69 # if user ID was passed in 70 if (is_numeric($UserInfoOne) || is_numeric($UserInfoTwo))
73 $this->UserId = is_numeric($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
77 # look up user ID in database 78 $UserInfoTwo = is_string($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
79 $this->DB->Query(
"SELECT UserId, LoggedIn FROM APUsers" 80 .
" WHERE UserName='".addslashes($UserInfoTwo).
"'");
81 $Record = $this->DB->FetchRow();
84 $this->UserId = $Record[
"UserId"];
85 $this->LoggedIn = $Record[
"LoggedIn"] ? TRUE : FALSE;
88 # if user ID was not found 89 if ($Record === FALSE)
91 # if name looks like it could actually be a user ID 92 if (preg_match(
"/^[-]*[0-9]+$/", $UserInfoTwo))
94 # assume name was user ID 95 $this->UserId = intval($UserInfoTwo);
99 # set code indicating no user found 101 unset($this->UserId);
108 # if user ID is available from session 109 if (isset($_SESSION[
"APUserId"]))
112 $this->UserId = $_SESSION[
"APUserId"];
114 # set flag indicating user is currently logged in 115 $this->LoggedIn = TRUE;
125 # return text message corresponding to current status code 128 return self::GetStatusMessageForCode($this->Result);
138 $APUserStatusMessages = array(
139 U_OKAY =>
"The operation was successful.",
140 U_ERROR =>
"There has been an error.",
144 "The new passwords you entered do not match.",
146 "The e-mail addresses you entered do not match.",
148 "The user name you requested is already in use.",
150 "The user name you requested is too short, too long, " 151 .
"or contains illegal characters.",
153 "The new password you requested is not valid.",
155 "The e-mail address you entered appears to be invalid.",
158 "An error occurred while attempting to send e-mail. " 159 .
"Please notify the system administrator.",
161 "An error occurred while attempting to generate e-mail. " 162 .
"Please notify the system administrator.",
164 "The e-mail address you supplied already has an account " 165 .
"associated with it.",
167 "The password you entered contains your username.",
169 "The password you entered contains your email address.",
172 "Passwords must be at least ".self::$PasswordMinLength
173 .
" characters long.",
175 "Passwords must have at least ".self::$PasswordMinUniqueChars
176 .
" different characters.",
178 "Passwords must contain at least one punctuation character.",
180 "Passwords must contain a mixture of uppercase and " 181 .
"lowercase letters",
183 "Passwords must contain at least one number.",
186 return (isset($APUserStatusMessages[$StatusCode]) ?
187 $APUserStatusMessages[$StatusCode] :
188 "Unknown user status code: ".$StatusCode );
193 # clear priv list values 194 $this->DB->Query(
"DELETE FROM APUserPrivileges WHERE UserId = '" 197 # delete user record from database 198 $this->DB->Query(
"DELETE FROM APUsers WHERE UserId = '".$this->UserId.
"'");
200 # report to caller that everything succeeded 212 if (is_callable($NewValue))
214 self::$EmailFunc = $NewValue;
218 # ---- Getting/Setting Values -------------------------------------------- 226 return $this->
Get(
"UserName");
236 $RealName = $this->
Get(
"RealName");
238 # the real name is available, so use it 239 if (strlen(trim($RealName)))
244 # the real name isn't available, so use the user name 245 return $this->
Get(
"UserName");
250 # return NULL if not associated with a particular user 251 if ($this->UserId === NULL) {
return NULL; }
255 $this->DB->Query(
"UPDATE APUsers SET" 256 .
" LastLocation = '".addslashes($NewLocation).
"'," 257 .
" LastActiveDate = NOW()," 258 .
" LastIPAddress = '".$_SERVER[
"REMOTE_ADDR"].
"'" 259 .
" WHERE UserId = '".addslashes($this->UserId).
"'");
260 if (isset($this->DBFields))
262 $this->DBFields[
"LastLocation"] = $NewLocation;
263 $this->DBFields[
"LastActiveDate"] = date(
"Y-m-d H:i:s");
266 return $this->
Get(
"LastLocation");
270 return $this->
Get(
"LastActiveDate");
274 return $this->
Get(
"LastIPAddress");
277 # get value from specified field 278 public function Get($FieldName)
280 # return NULL if not associated with a particular user 281 if ($this->UserId === NULL) {
return NULL; }
286 # get value (formatted as a date) from specified field 287 public function GetDate($FieldName, $Format =
"")
289 # return NULL if not associated with a particular user 290 if ($this->UserId === NULL) {
return NULL; }
292 # retrieve specified value from database 293 if (strlen($Format) > 0)
295 $this->DB->Query(
"SELECT DATE_FORMAT(`".addslashes($FieldName)
296 .
"`, '".addslashes($Format).
"') AS `".addslashes($FieldName)
297 .
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
301 $this->DB->Query(
"SELECT `".addslashes($FieldName).
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
303 $Record = $this->DB->FetchRow();
305 # return value to caller 306 return $Record[$FieldName];
309 # set value in specified field 310 public function Set($FieldName, $NewValue)
312 # return error if not associated with a particular user 321 # ---- Login Functions --------------------------------------------------- 323 public function Login($UserName, $Password, $IgnorePassword = FALSE)
325 # if user not found in DB 326 $this->DB->Query(
"SELECT * FROM APUsers" 327 .
" WHERE UserName = '" 328 .addslashes(self::NormalizeUserName($UserName)).
"'");
329 if ($this->DB->NumRowsSelected() < 1)
331 # result is no user by that name 336 # if user account not yet activated 337 $Record = $this->DB->FetchRow();
338 if (!$Record[
"RegistrationConfirmed"])
340 # result is user registration not confirmed 345 # grab password from DB 346 $StoredPassword = $Record[
"UserPassword"];
348 if (isset($Password[0]) && $Password[0] ==
" ")
350 $Challenge = md5(date(
"Ymd").$_SERVER[
"REMOTE_ADDR"]);
351 $StoredPassword = md5( $Challenge . $StoredPassword );
353 $EncryptedPassword = trim($Password);
357 # if supplied password matches encrypted password 358 $EncryptedPassword = crypt($Password, $StoredPassword);
361 if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
366 # store user ID for session 367 $this->UserId = $Record[
"UserId"];
370 # update last login date 371 $this->DB->Query(
"UPDATE APUsers SET LastLoginDate = NOW()," 373 .
" WHERE UserId = '".$this->UserId.
"'");
375 # Check for old format hashes, and rehash if possible 376 if ($EncryptedPassword === $StoredPassword &&
377 substr($StoredPassword, 0, 3) !==
"$1$" &&
378 $Password[0] !==
" " &&
381 $NewPassword = crypt($Password, self::GetSaltForCrypt() );
383 "UPDATE APUsers SET UserPassword='" 384 .addslashes($NewPassword).
"' " 385 .
"WHERE UserId='".$this->UserId.
"'");
388 # since self::DBFields might already have been set to false if 389 # the user wasn't logged in when this is called, populate it 390 # with user data so that a call to self::UpdateValue will be 391 # able to properly fetch the data associated with the user 392 $this->DBFields = $Record;
394 # set flag to indicate we are logged in 395 $this->LoggedIn = TRUE;
399 # result is bad password 405 # return result to caller 412 # clear user ID (if any) for session 413 unset($_SESSION[
"APUserId"]);
415 # if user is marked as logged in 418 # set flag to indicate user is no longer logged in 419 $this->LoggedIn = FALSE;
421 # clear login flag in database 423 "UPDATE APUsers SET LoggedIn = '0' " 424 .
"WHERE UserId='".$this->UserId.
"'");
431 "SELECT * FROM APUsers WHERE UserName = '" 432 .addslashes(self::NormalizeUserName($UserName)).
"'");
434 if ($this->DB->NumRowsSelected() < 1)
436 # result is no user by that name, generate a fake salt 437 # to discourage user enumeration. Make it be an old-format 438 # crypt() salt so that it's harder. 439 $SaltString = $_SERVER[
"SERVER_ADDR"].$UserName;
440 $Result = substr(base64_encode(md5($SaltString)), 0, 2);
444 # grab password from DB 445 # Assumes that we used php's crypt() for the passowrd 446 # management stuff, and will need to be changed if we 447 # go to something else. 448 $Record = $this->DB->FetchRow();
449 $StoredPassword = $Record[
"UserPassword"];
451 if (substr($StoredPassword, 0, 3) ===
"$1$")
453 $Result = substr($StoredPassword, 0, 12);
457 $Result = substr($StoredPassword, 0, 2);
471 if (!isset($this->LoggedIn))
473 $this->LoggedIn = $this->DB->Query(
" 474 SELECT LoggedIn FROM APUsers 475 WHERE UserId='".addslashes($this->UserId).
"'",
476 "LoggedIn") ? TRUE : FALSE;
497 return ($this->UserId === NULL) ? TRUE : FALSE;
501 # ---- Password Functions ------------------------------------------------ 503 # set new password (with checks against old password) 513 # return error if not associated with a particular user 514 if ($this->UserId === NULL)
519 # if old password is not correct 520 $StoredPassword = $this->DB->Query(
"SELECT UserPassword FROM APUsers" 521 .
" WHERE UserId='".$this->UserId.
"'",
"UserPassword");
522 $EncryptedPassword = crypt($OldPassword, $StoredPassword);
523 if ($EncryptedPassword != $StoredPassword)
525 # set status to indicate error 528 # else if both instances of new password do not match 529 elseif (self::NormalizePassword($NewPassword)
530 != self::NormalizePassword($NewPasswordAgain))
532 # set status to indicate error 535 # perform other validity checks 536 elseif (!self::IsValidPassword(
537 $NewPassword, $this->
Get(
"UserName"), $this->
Get(
"EMail")) )
539 # set status to indicate error 547 # set status to indicate password successfully changed 551 # report to caller that everything succeeded 558 # generate encrypted password 559 $EncryptedPassword = crypt(self::NormalizePassword($NewPassword),
560 self::GetSaltForCrypt() );
562 # save encrypted password 563 $this->
UpdateValue(
"UserPassword", $EncryptedPassword);
568 # save encrypted password 569 $this->
UpdateValue(
"UserPassword", $NewEncryptedPassword);
573 $UserName, $EMail, $EMailAgain,
574 $TemplateFile =
"Axis--User--EMailTemplate.txt")
577 $UserName, $EMail, $EMailAgain, $TemplateFile);
581 $UserName, $EMail, $EMailAgain,
582 $TemplateFile =
"Axis--User--EMailTemplate.txt")
584 # load e-mail template from file (first line is subject) 585 $Template = file($TemplateFile, 1);
586 $EMailSubject = array_shift($Template);
587 $EMailBody = join(
"", $Template);
590 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
594 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
596 # make sure e-mail addresses match 597 if ($EMail != $EMailAgain)
603 # make sure e-mail address looks valid 610 # generate random password 613 # attempt to create new user with password 614 $Result = $this->CreateNewUser($UserName, $Password, $Password);
616 # if user creation failed 619 # report error result to caller 625 # set e-mail address in user record 626 $this->
Set(
"EMail", $EMail);
628 # plug appropriate values into subject and body of e-mail message 629 $EMailSubject = str_replace(
"X-USERNAME-X", $UserName, $EMailSubject);
630 $EMailBody = str_replace(
"X-USERNAME-X", $UserName, $EMailBody);
631 $EMailBody = str_replace(
"X-PASSWORD-X", $Password, $EMailBody);
633 # send out e-mail message with new account info 634 if (is_Callable(self::$EmailFunc))
636 $Result = call_user_func(self::$EmailFunc,
637 $EMail, $EMailSubject, $EMailBody,
638 "Auto-Submitted: auto-generated");
642 $Result = mail($EMail, $EMailSubject, $EMailBody,
643 "Auto-Submitted: auto-generated");
646 # if mailing attempt failed 649 # report error to caller 656 # report success to caller 663 # get code for user to submit to confirm registration 666 # code is MD5 sum based on user name and encrypted password 667 $ActivationCodeLength = 6;
668 return $this->
GetUniqueCode(
"Activation", $ActivationCodeLength);
671 # check whether confirmation code is valid 678 # get/set whether user registration has been confirmed 681 return $this->
UpdateValue(
"RegistrationConfirmed", $NewValue);
684 # get code for user to submit to confirm password reset 687 # code is MD5 sum based on user name and encrypted password 688 $ResetCodeLength = 10;
692 # check whether password reset code is valid 695 return (strtoupper(trim($Code)) == $this->
GetResetCode())
699 # get code for user to submit to confirm mail change request 702 $ResetCodeLength = 10;
704 .$this->
Get(
"NewEMail"),
714 # send e-mail to user (returns TRUE on success) 716 $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
719 # if template is file name 720 if (@is_file($TemplateTextOrFileName))
722 # load in template from file 723 $Template = file($TemplateTextOrFileName, 1);
725 # report error to caller if template load failed 726 if ($Template == FALSE)
729 return $this->Status;
732 # join into one text block 733 $TemplateTextOrFileName = join(
"", $Template);
736 # split template into lines 737 $Template = explode(
"\n", $TemplateTextOrFileName);
739 # strip any comments out of template 740 $FilteredTemplate = array();
741 foreach ($Template as $Line)
743 if (!preg_match(
"/^[\\s]*#/", $Line))
745 $FilteredTemplate[] = $Line;
749 # split subject line out of template (first non-comment line in file) 750 $EMailSubject = array_shift($FilteredTemplate);
751 $EMailBody = join(
"\n", $FilteredTemplate);
753 # set up our substitutions 754 $Substitutions = array(
755 "X-USERNAME-X" => $this->
Get(
"UserName"),
756 "X-EMAILADDRESS-X" => $this->
Get(
"EMail"),
760 "X-IPADDRESS-X" => @$_SERVER[
"REMOTE_ADDR"],
763 # if caller provided additional substitutions 764 if (is_array($MoreSubstitutions))
766 # add in entries from caller to substitution list 767 $Substitutions = array_merge(
768 $Substitutions, $MoreSubstitutions);
771 # perform substitutions on subject and body of message 772 $EMailSubject = str_replace(array_keys($Substitutions),
773 array_values($Substitutions), $EMailSubject);
774 $EMailBody = str_replace(array_keys($Substitutions),
775 array_values($Substitutions), $EMailBody);
777 $AdditionalHeaders =
"Auto-Submitted: auto-generated";
779 # if caller provided "From" address 782 # prepend "From" address onto message 783 $AdditionalHeaders .=
"\r\nFrom: ".$FromAddress;
786 # send out mail message 787 if (is_Callable(self::$EmailFunc))
789 $Result = call_user_func(self::$EmailFunc,
790 is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
791 $EMailSubject, $EMailBody, $AdditionalHeaders);
795 $Result = mail(is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
797 $EMailBody, $AdditionalHeaders);
800 # report result of mailing attempt to caller 806 # ---- Privilege Functions ----------------------------------------------- 816 public function HasPriv($Privilege, $Privileges = NULL)
818 # return FALSE if not associated with a particular user 819 if ($this->UserId === NULL) {
return FALSE; }
821 # bail out if empty array of privileges passed in 822 if (is_array($Privilege) && !count($Privilege) && (func_num_args() < 2))
825 # set up beginning of database query 826 $Query =
"SELECT COUNT(*) AS PrivCount FROM APUserPrivileges " 827 .
"WHERE UserId='".$this->UserId.
"' AND (";
829 # add first privilege(s) to query (first arg may be single value or array) 830 if (is_array($Privilege))
833 foreach ($Privilege as $Priv)
835 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
841 $Query .=
"Privilege='".$Privilege.
"'";
845 # add any privileges from additional args to query 846 $Args = func_get_args();
848 foreach ($Args as $Arg)
850 $Query .= $Sep.
"Privilege='".$Arg.
"'";
857 # look for privilege in database 858 $PrivCount = $this->DB->Query($Query,
"PrivCount");
860 # return value to caller 861 return ($PrivCount > 0) ? TRUE : FALSE;
874 # set up beginning of database query 875 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 878 # add first privilege(s) to query (first arg may be single value or array) 879 if (is_array($Privilege))
882 foreach ($Privilege as $Priv)
884 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
890 $Query .=
"Privilege='".$Privilege.
"'";
894 # add any privileges from additional args to query 895 $Args = func_get_args();
897 foreach ($Args as $Arg)
899 $Query .= $Sep.
"Privilege='".$Arg.
"'";
903 # return query to caller 917 # set up beginning of database query 918 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 921 # add first privilege(s) to query (first arg may be single value or array) 922 if (is_array($Privilege))
925 foreach ($Privilege as $Priv)
927 $Query .= $Sep.
"Privilege != '".addslashes($Priv).
"'";
933 $Query .=
"Privilege != '".$Privilege.
"'";
937 # add any privileges from additional args to query 938 $Args = func_get_args();
940 foreach ($Args as $Arg)
942 $Query .= $Sep.
"Privilege != '".$Arg.
"'";
946 # return query to caller 952 # return error if not associated with a particular user 955 # if privilege value is invalid 956 if (intval($Privilege) != trim($Privilege))
958 # set code to indicate error 963 # if user does not already have privilege 964 $PrivCount = $this->DB->Query(
"SELECT COUNT(*) AS PrivCount" 965 .
" FROM APUserPrivileges" 966 .
" WHERE UserId='".$this->UserId.
"'" 967 .
" AND Privilege='".$Privilege.
"'",
971 # add privilege for this user to database 972 $this->DB->Query(
"INSERT INTO APUserPrivileges" 973 .
" (UserId, Privilege) VALUES" 974 .
" ('".$this->UserId.
"', ".$Privilege.
")");
977 # set code to indicate success 981 # report result to caller 987 # return error if not associated with a particular user 990 # remove privilege from database (if present) 991 $this->DB->Query(
"DELETE FROM APUserPrivileges" 992 .
" WHERE UserId = '".$this->UserId.
"'" 993 .
" AND Privilege = '".$Privilege.
"'");
995 # report success to caller 1002 # return empty list if not associated with a particular user 1003 if ($this->UserId === NULL) {
return array(); }
1005 # read privileges from database and return array to caller 1006 $this->DB->Query(
"SELECT Privilege FROM APUserPrivileges" 1007 .
" WHERE UserId='".$this->UserId.
"'");
1008 return $this->DB->FetchColumn(
"Privilege");
1013 # return error if not associated with a particular user 1016 # clear old priv list values 1017 $this->DB->Query(
"DELETE FROM APUserPrivileges" 1018 .
" WHERE UserId='".$this->UserId.
"'");
1020 # for each priv value passed in 1021 foreach ($NewPrivileges as $Privilege)
1036 # if we have a UserId in the session, move it aside 1037 if (isset($_SESSION[
"APUserId"]))
1039 $OldUserId = $_SESSION[
"APUserId"];
1040 unset($_SESSION[
"APUserId"]);
1043 # create a new anonymous user 1044 $CalledClass = get_called_class();
1048 # restore the $_SESSION value 1049 if (isset($OldUserId))
1051 $_SESSION[
"APUserId"] = $OldUserId;
1054 # return our anonymous user 1058 # ---- Miscellaneous Functions ------------------------------------------- 1060 # get unique alphanumeric code for user 1063 # return NULL if not associated with a particular user 1064 if ($this->UserId === NULL) {
return NULL; }
1066 return substr(strtoupper(md5(
1067 $this->
Get(
"UserName").$this->
Get(
"UserPassword").$SeedString)),
1072 # ---- PRIVATE INTERFACE ------------------------------------------------- 1074 protected $DB; # handle to SQL database we use to store user information
1075 protected $UserId = NULL; # user ID number
for reference into database
1077 protected $LoggedIn; # flag indicating whether user is logged in
1078 private $DBFields; # used
for caching user values
1080 # optional mail function to use instead of mail() 1081 private static $EmailFunc = NULL;
1083 # check whether a user name is valid (alphanumeric string of 2-24 chars) 1086 if (preg_match(
"/^[a-zA-Z0-9]{2,24}$/", $UserName))
1096 # check whether a password is valid (at least 6 characters) 1098 $Password, $UserName, $Email)
1100 return count(self::CheckPasswordForErrors(
1101 $Password, $UserName, $Email)) == 0 ?
1115 $Password, $UserName = NULL, $Email = NULL)
1117 # start off assuming no errors 1120 # normalize incoming password 1121 $Password = self::NormalizePassword($Password);
1123 # username provided and password contains username 1124 if ($UserName !== NULL &&
1125 stripos($Password, $UserName) !== FALSE)
1130 # email provided and password contains email 1131 if ($Email !== NULL &&
1132 stripos($Password, $Email) !== FALSE)
1137 # length requirement 1138 if (strlen($Password) == 0)
1142 elseif (strlen($Password) < self::$PasswordMinLength)
1147 # unique characters requirement 1148 $UniqueChars = count(array_unique(
1149 preg_split(
'//u', $Password, NULL, PREG_SPLIT_NO_EMPTY)));
1151 if ($UniqueChars < self::$PasswordMinUniqueChars)
1156 # for the following complexity checks, use unicode character properties 1157 # in PCRE as in: http://php.net/manual/en/regexp.reference.unicode.php 1159 # check for punctuation, uppercase letters, and numbers as per the system 1161 if (self::$PasswordRules & self::PW_REQUIRE_PUNCTUATION &&
1162 !preg_match(
'/\p{P}/u', $Password) )
1167 if (self::$PasswordRules & self::PW_REQUIRE_MIXEDCASE &&
1168 (!preg_match(
'/\p{Lu}/u', $Password) ||
1169 !preg_match(
'/\p{Ll}/u', $Password) ) )
1175 if (self::$PasswordRules & self::PW_REQUIRE_DIGITS &&
1176 !preg_match(
'/\p{N}/u', $Password))
1184 # check whether an e-mail address looks valid 1187 if (preg_match(
"/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/",
1198 # get normalized version of e-mail address 1201 return strtolower(trim($EMailAddress));
1204 # get normalized version of user name 1207 return trim($UserName);
1210 # get normalized version of password 1213 return trim($Password);
1216 # generate random password 1219 # seed random number generator 1220 mt_srand((
double)microtime() * 1000000);
1222 # generate password of requested length 1223 return sprintf(
"%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
1224 (pow(10, $PasswordMaxLength) - 1)));
1227 # convenience function to supply parameters to Database->UpdateValue() 1230 return $this->DB->UpdateValue(
"APUsers", $FieldName, $NewValue,
1231 "UserId = '".$this->UserId.
"'", $this->DBFields);
1234 # methods for backward compatibility with earlier versions of User 1247 self::$PasswordRules = $NewValue;
1256 self::$PasswordMinLength = $NewValue;
1265 self::$PasswordMinUniqueChars = $NewValue;
1274 return "Passwords are case-sensitive, cannot contain your username or email, " 1275 .
"must be at least ".self::$PasswordMinLength
1276 .
" characters long, " 1277 .
" have at least ".self::$PasswordMinUniqueChars
1278 .
" different characters" 1279 .(self::$PasswordRules & self::PW_REQUIRE_PUNCTUATION ?
1280 ", include punctuation":
"")
1281 .(self::$PasswordRules & self::PW_REQUIRE_MIXEDCASE ?
1282 ", include capital and lowercase letters":
"")
1283 .(self::$PasswordRules & self::PW_REQUIRE_DIGITS ?
1284 ", include a number":
"").
".";
1290 private static function GetSaltForCrypt()
1292 # generate a password salt by grabbing CRYPT_SALT_LENGTH 1293 # random bytes, then base64 encoding while filtering out 1294 # non-alphanumeric characters to get a string all the hashes 1296 $Salt = preg_replace(
"/[^A-Za-z0-9]/",
"",
1297 base64_encode(openssl_random_pseudo_bytes(
1298 CRYPT_SALT_LENGTH) ));
1300 # select the best available hashing algorithm, provide a salt 1301 # in the correct format for that algorithm 1302 if (CRYPT_SHA512==1)
1304 return '$6$'.substr($Salt, 0, 16);
1306 elseif (CRYPT_SHA256==1)
1308 return '$5$'.substr($Salt, 0, 16);
1310 elseif (CRYPT_BLOWFISH==1)
1312 return '$2y$'.substr($Salt, 0, 22);
1314 elseif (CRYPT_MD5==1)
1316 return '$1$'.substr($Salt, 0, 12);
1318 elseif (CRYPT_EXT_DES==1)
1320 return '_'.substr($Salt, 0, 8);
1324 return substr($Salt, 0, 2);
1328 private static $PasswordMinLength = 6;
1329 private static $PasswordMinUniqueChars = 4;
1331 # default to no additional requirements beyond length 1332 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