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);
43 # ---- PUBLIC INTERFACE -------------------------------------------------- 45 public function __construct($UserInfoOne = NULL, $UserInfoTwo = NULL)
47 # assume constructor will succeed and user is not logged in 49 $this->LoggedIn = FALSE;
51 # create database connection 54 # if user info passed in 55 if (is_int($UserInfoOne) || is_string($UserInfoOne)
56 || is_int($UserInfoTwo) || is_string($UserInfoTwo))
58 # if user ID was passed in 59 if (is_int($UserInfoOne) || is_int($UserInfoTwo))
62 $this->UserId = is_int($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
64 # get whether the user is logged in 65 $this->LoggedIn = (bool)$this->DB->Query(
" 66 SELECT LoggedIn FROM APUsers 67 WHERE UserId='".addslashes($this->UserId).
"'",
72 # look up user ID in database 73 $UserInfoTwo = is_string($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
74 $this->DB->Query(
"SELECT UserId, LoggedIn FROM APUsers" 75 .
" WHERE UserName='".addslashes($UserInfoTwo).
"'");
76 $Record = $this->DB->FetchRow();
79 $this->UserId = $Record[
"UserId"];
80 $this->LoggedIn = $Record[
"LoggedIn"];
83 # if user ID was not found 84 if ($Record === FALSE)
86 # if name looks like it could actually be a user ID 87 if (preg_match(
"/^[-]*[0-9]+$/", $UserInfoTwo))
89 # assume name was user ID 90 $this->UserId = intval($UserInfoTwo);
94 # set code indicating no user found 103 # if user ID is available from session 104 if (isset($_SESSION[
"APUserId"]))
107 $this->UserId = $_SESSION[
"APUserId"];
109 # set flag indicating user is currently logged in 110 $this->LoggedIn = TRUE;
120 # return text message corresponding to current (or specified) status code 123 $APUserStatusMessages = array(
124 U_OKAY =>
"The operation was successful.",
125 U_ERROR =>
"There has been an error.",
136 .
" short, too long, or contains" 137 .
" illegal characters.",
139 .
" too short, too long, or" 140 .
" contains illegal characters.",
142 .
" appears to be invalid.",
145 .
" to send e-mail. Please notify" 146 .
" the system administrator.",
148 .
" to generate e-mail. Please" 149 .
" notify the system administrator.",
151 .
" has an account associated with it.",
154 return ($StatusCode === NULL) ? $APUserStatusMessages[
$this->Result]
155 : $APUserStatusMessages[$StatusCode];
160 # clear priv list values 161 $this->DB->Query(
"DELETE FROM APUserPrivileges WHERE UserId = '" 164 # delete user record from database 165 $this->DB->Query(
"DELETE FROM APUsers WHERE UserId = '".$this->UserId.
"'");
167 # report to caller that everything succeeded 179 if (is_callable($NewValue))
181 self::$EmailFunc = $NewValue;
186 # ---- Getting/Setting Values -------------------------------------------- 194 return $this->
Get(
"UserName");
204 $RealName = $this->
Get(
"RealName");
206 # the real name is available, so use it 207 if (strlen(trim($RealName)))
212 # the real name isn't available, so use the user name 213 return $this->
Get(
"UserName");
218 # return NULL if not associated with a particular user 219 if ($this->UserId === NULL) {
return NULL; }
223 $this->DB->Query(
"UPDATE APUsers SET" 224 .
" LastLocation = '".addslashes($NewLocation).
"'," 225 .
" LastActiveDate = NOW()," 226 .
" LastIPAddress = '".$_SERVER[
"REMOTE_ADDR"].
"'" 227 .
" WHERE UserId = '".addslashes($this->UserId).
"'");
228 if (isset($this->DBFields))
230 $this->DBFields[
"LastLocation"] = $NewLocation;
231 $this->DBFields[
"LastActiveDate"] = date(
"Y-m-d H:i:s");
234 return $this->
Get(
"LastLocation");
238 return $this->
Get(
"LastActiveDate");
242 return $this->
Get(
"LastIPAddress");
245 # get value from specified field 246 public function Get($FieldName)
248 # return NULL if not associated with a particular user 249 if ($this->UserId === NULL) {
return NULL; }
254 # get value (formatted as a date) from specified field 255 public function GetDate($FieldName, $Format =
"")
257 # return NULL if not associated with a particular user 258 if ($this->UserId === NULL) {
return NULL; }
260 # retrieve specified value from database 261 if (strlen($Format) > 0)
263 $this->DB->Query(
"SELECT DATE_FORMAT(`".addslashes($FieldName)
264 .
"`, '".addslashes($Format).
"') AS `".addslashes($FieldName)
265 .
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
269 $this->DB->Query(
"SELECT `".addslashes($FieldName).
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
271 $Record = $this->DB->FetchRow();
273 # return value to caller 274 return $Record[$FieldName];
277 # set value in specified field 278 public function Set($FieldName, $NewValue)
280 # return error if not associated with a particular user 289 # ---- Login Functions --------------------------------------------------- 291 public function Login($UserName, $Password, $IgnorePassword = FALSE)
293 # if user not found in DB 294 $this->DB->Query(
"SELECT * FROM APUsers" 295 .
" WHERE UserName = '" 296 .addslashes(self::NormalizeUserName($UserName)).
"'");
297 if ($this->DB->NumRowsSelected() < 1)
299 # result is no user by that name 304 # if user account not yet activated 305 $Record = $this->DB->FetchRow();
306 if (!$Record[
"RegistrationConfirmed"])
308 # result is user registration not confirmed 313 # grab password from DB 314 $StoredPassword = $Record[
"UserPassword"];
316 if (isset($Password[0]) && $Password[0] ==
" ")
318 $Challenge = md5(date(
"Ymd").$_SERVER[
"REMOTE_ADDR"]);
319 $StoredPassword = md5( $Challenge . $StoredPassword );
321 $EncryptedPassword = trim($Password);
325 # if supplied password matches encrypted password 326 $EncryptedPassword = crypt($Password, $StoredPassword);
329 if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
334 # store user ID for session 335 $this->UserId = $Record[
"UserId"];
338 # update last login date 339 $this->DB->Query(
"UPDATE APUsers SET LastLoginDate = NOW()," 341 .
" WHERE UserId = '".$this->UserId.
"'");
343 # Check for old format hashes, and rehash if possible 344 if ($EncryptedPassword === $StoredPassword &&
345 substr($StoredPassword, 0, 3) !==
"$1$" &&
346 $Password[0] !==
" " &&
349 $NewPassword = crypt($Password);
351 "UPDATE APUsers SET UserPassword='" 352 .addslashes($NewPassword).
"' " 353 .
"WHERE UserId='".$this->UserId.
"'");
356 # since self::DBFields might already have been set to false if 357 # the user wasn't logged in when this is called, populate it 358 # with user data so that a call to self::UpdateValue will be 359 # able to properly fetch the data associated with the user 360 $this->DBFields = $Record;
362 # set flag to indicate we are logged in 363 $this->LoggedIn = TRUE;
367 # result is bad password 373 # return result to caller 380 # clear user ID (if any) for session 381 unset($_SESSION[
"APUserId"]);
383 # if user is marked as logged in 386 # set flag to indicate user is no longer logged in 387 $this->LoggedIn = FALSE;
389 # clear login flag in database 391 "UPDATE APUsers SET LoggedIn = '0' " 392 .
"WHERE UserId='".$this->UserId.
"'");
399 "SELECT * FROM APUsers WHERE UserName = '" 400 .addslashes(self::NormalizeUserName($UserName)).
"'");
402 if ($this->DB->NumRowsSelected() < 1)
404 # result is no user by that name, generate a fake salt 405 # to discourage user enumeration. Make it be an old-format 406 # crypt() salt so that it's harder. 407 $SaltString = $_SERVER[
"SERVER_ADDR"].$UserName;
408 $Result = substr(base64_encode(md5($SaltString)), 0, 2);
412 # grab password from DB 413 # Assumes that we used php's crypt() for the passowrd 414 # management stuff, and will need to be changed if we 415 # go to something else. 416 $Record = $this->DB->FetchRow();
417 $StoredPassword = $Record[
"UserPassword"];
419 if (substr($StoredPassword, 0, 3) ===
"$1$")
421 $Result = substr($StoredPassword, 0, 12);
425 $Result = substr($StoredPassword, 0, 2);
432 # report whether this user is or is not currently logged in 443 # ---- Password Functions ------------------------------------------------ 445 # set new password (with checks against old password) 448 # return error if not associated with a particular user 451 # if old password is not correct 452 $StoredPassword = $this->DB->Query(
"SELECT UserPassword FROM APUsers" 453 .
" WHERE UserId='".$this->UserId.
"'",
"UserPassword");
454 $EncryptedPassword = crypt($OldPassword, $StoredPassword);
455 if ($EncryptedPassword != $StoredPassword)
457 # set status to indicate error 460 # else if new password is not legal 463 # set status to indicate error 466 # else if both instances of new password do not match 467 elseif (self::NormalizePassword($NewPassword)
468 != self::NormalizePassword($NewPasswordAgain))
470 # set status to indicate error 478 # set status to indicate password successfully changed 482 # report to caller that everything succeeded 489 # generate encrypted password 490 $EncryptedPassword = crypt(self::NormalizePassword($NewPassword));
492 # save encrypted password 493 $this->
UpdateValue(
"UserPassword", $EncryptedPassword);
498 # save encrypted password 499 $this->
UpdateValue(
"UserPassword", $NewEncryptedPassword);
503 $UserName, $EMail, $EMailAgain,
504 $TemplateFile =
"Axis--User--EMailTemplate.txt")
507 $UserName, $EMail, $EMailAgain, $TemplateFile);
511 $UserName, $EMail, $EMailAgain,
512 $TemplateFile =
"Axis--User--EMailTemplate.txt")
514 # load e-mail template from file (first line is subject) 515 $Template = file($TemplateFile, 1);
516 $EMailSubject = array_shift($Template);
517 $EMailBody = join(
"", $Template);
520 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
524 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
526 # make sure e-mail addresses match 527 if ($EMail != $EMailAgain)
533 # make sure e-mail address looks valid 540 # generate random password 543 # attempt to create new user with password 544 $Result = $this->CreateNewUser($UserName, $Password, $Password);
546 # if user creation failed 549 # report error result to caller 555 # set e-mail address in user record 556 $this->
Set(
"EMail", $EMail);
558 # plug appropriate values into subject and body of e-mail message 559 $EMailSubject = str_replace(
"X-USERNAME-X", $UserName, $EMailSubject);
560 $EMailBody = str_replace(
"X-USERNAME-X", $UserName, $EMailBody);
561 $EMailBody = str_replace(
"X-PASSWORD-X", $Password, $EMailBody);
563 # send out e-mail message with new account info 564 if (is_Callable(self::$EmailFunc))
566 $Result = call_user_func(self::$EmailFunc,
567 $EMail, $EMailSubject, $EMailBody,
568 "Auto-Submitted: auto-generated");
572 $Result = mail($EMail, $EMailSubject, $EMailBody,
573 "Auto-Submitted: auto-generated");
576 # if mailing attempt failed 579 # report error to caller 586 # report success to caller 593 # get code for user to submit to confirm registration 596 # code is MD5 sum based on user name and encrypted password 597 $ActivationCodeLength = 6;
598 return $this->
GetUniqueCode(
"Activation", $ActivationCodeLength);
601 # check whether confirmation code is valid 608 # get/set whether user registration has been confirmed 611 return $this->
UpdateValue(
"RegistrationConfirmed", $NewValue);
614 # get code for user to submit to confirm password reset 617 # code is MD5 sum based on user name and encrypted password 618 $ResetCodeLength = 10;
622 # check whether password reset code is valid 625 return (strtoupper(trim($Code)) == $this->
GetResetCode())
629 # get code for user to submit to confirm mail change request 632 $ResetCodeLength = 10;
634 .$this->
Get(
"NewEMail"),
644 # send e-mail to user (returns TRUE on success) 646 $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
649 # if template is file name 650 if (@is_file($TemplateTextOrFileName))
652 # load in template from file 653 $Template = file($TemplateTextOrFileName, 1);
655 # report error to caller if template load failed 656 if ($Template == FALSE)
659 return $this->Status;
662 # join into one text block 663 $TemplateTextOrFileName = join(
"", $Template);
666 # split template into lines 667 $Template = explode(
"\n", $TemplateTextOrFileName);
669 # strip any comments out of template 670 $FilteredTemplate = array();
671 foreach ($Template as $Line)
673 if (!preg_match(
"/^[\\s]*#/", $Line))
675 $FilteredTemplate[] = $Line;
679 # split subject line out of template (first non-comment line in file) 680 $EMailSubject = array_shift($FilteredTemplate);
681 $EMailBody = join(
"\n", $FilteredTemplate);
683 # set up our substitutions 684 $Substitutions = array(
685 "X-USERNAME-X" => $this->
Get(
"UserName"),
686 "X-EMAILADDRESS-X" => $this->
Get(
"EMail"),
690 "X-IPADDRESS-X" => @$_SERVER[
"REMOTE_ADDR"],
693 # if caller provided additional substitutions 694 if (is_array($MoreSubstitutions))
696 # add in entries from caller to substitution list 697 $Substitutions = array_merge(
698 $Substitutions, $MoreSubstitutions);
701 # perform substitutions on subject and body of message 702 $EMailSubject = str_replace(array_keys($Substitutions),
703 array_values($Substitutions), $EMailSubject);
704 $EMailBody = str_replace(array_keys($Substitutions),
705 array_values($Substitutions), $EMailBody);
707 $AdditionalHeaders =
"Auto-Submitted: auto-generated";
709 # if caller provided "From" address 712 # prepend "From" address onto message 713 $AdditionalHeaders .=
"\r\nFrom: ".$FromAddress;
716 # send out mail message 717 if (is_Callable(self::$EmailFunc))
719 $Result = call_user_func(self::$EmailFunc,
720 is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
721 $EMailSubject, $EMailBody, $AdditionalHeaders);
725 $Result = mail(is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
727 $EMailBody, $AdditionalHeaders);
730 # report result of mailing attempt to caller 736 # ---- Privilege Functions ----------------------------------------------- 746 public function HasPriv($Privilege, $Privileges = NULL)
748 # return FALSE if not associated with a particular user 749 if ($this->UserId === NULL) {
return FALSE; }
751 # bail out if empty array of privileges passed in 752 if (is_array($Privilege) && !count($Privilege) && (func_num_args() < 2))
755 # set up beginning of database query 756 $Query =
"SELECT COUNT(*) AS PrivCount FROM APUserPrivileges " 757 .
"WHERE UserId='".$this->UserId.
"' AND (";
759 # add first privilege(s) to query (first arg may be single value or array) 760 if (is_array($Privilege))
763 foreach ($Privilege as $Priv)
765 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
771 $Query .=
"Privilege='".$Privilege.
"'";
775 # add any privileges from additional args to query 776 $Args = func_get_args();
778 foreach ($Args as $Arg)
780 $Query .= $Sep.
"Privilege='".$Arg.
"'";
787 # look for privilege in database 788 $PrivCount = $this->DB->Query($Query,
"PrivCount");
790 # return value to caller 791 return ($PrivCount > 0) ? TRUE : FALSE;
804 # set up beginning of database query 805 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 808 # add first privilege(s) to query (first arg may be single value or array) 809 if (is_array($Privilege))
812 foreach ($Privilege as $Priv)
814 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
820 $Query .=
"Privilege='".$Privilege.
"'";
824 # add any privileges from additional args to query 825 $Args = func_get_args();
827 foreach ($Args as $Arg)
829 $Query .= $Sep.
"Privilege='".$Arg.
"'";
833 # return query to caller 847 # set up beginning of database query 848 $Query =
"SELECT DISTINCT UserId FROM APUserPrivileges " 851 # add first privilege(s) to query (first arg may be single value or array) 852 if (is_array($Privilege))
855 foreach ($Privilege as $Priv)
857 $Query .= $Sep.
"Privilege != '".addslashes($Priv).
"'";
863 $Query .=
"Privilege != '".$Privilege.
"'";
867 # add any privileges from additional args to query 868 $Args = func_get_args();
870 foreach ($Args as $Arg)
872 $Query .= $Sep.
"Privilege != '".$Arg.
"'";
876 # return query to caller 882 # return error if not associated with a particular user 885 # if privilege value is invalid 886 if (intval($Privilege) != trim($Privilege))
888 # set code to indicate error 893 # if user does not already have privilege 894 $PrivCount = $this->DB->Query(
"SELECT COUNT(*) AS PrivCount" 895 .
" FROM APUserPrivileges" 896 .
" WHERE UserId='".$this->UserId.
"'" 897 .
" AND Privilege='".$Privilege.
"'",
901 # add privilege for this user to database 902 $this->DB->Query(
"INSERT INTO APUserPrivileges" 903 .
" (UserId, Privilege) VALUES" 904 .
" ('".$this->UserId.
"', ".$Privilege.
")");
907 # set code to indicate success 911 # report result to caller 917 # return error if not associated with a particular user 920 # remove privilege from database (if present) 921 $this->DB->Query(
"DELETE FROM APUserPrivileges" 922 .
" WHERE UserId = '".$this->UserId.
"'" 923 .
" AND Privilege = '".$Privilege.
"'");
925 # report success to caller 932 # return empty list if not associated with a particular user 933 if ($this->UserId === NULL) {
return array(); }
935 # read privileges from database and return array to caller 936 $this->DB->Query(
"SELECT Privilege FROM APUserPrivileges" 937 .
" WHERE UserId='".$this->UserId.
"'");
938 return $this->DB->FetchColumn(
"Privilege");
943 # return error if not associated with a particular user 946 # clear old priv list values 947 $this->DB->Query(
"DELETE FROM APUserPrivileges" 948 .
" WHERE UserId='".$this->UserId.
"'");
950 # for each priv value passed in 951 foreach ($NewPrivileges as $Privilege)
959 # ---- Miscellaneous Functions ------------------------------------------- 961 # get unique alphanumeric code for user 964 # return NULL if not associated with a particular user 965 if ($this->UserId === NULL) {
return NULL; }
967 return substr(strtoupper(md5(
968 $this->
Get(
"UserName").$this->
Get(
"UserPassword").$SeedString)),
973 # ---- PRIVATE INTERFACE ------------------------------------------------- 975 protected $DB; # handle to SQL database we use to store user information
976 protected $UserId = NULL; # user ID number
for reference into database
978 protected $LoggedIn; # flag indicating whether user is logged in
979 private $DBFields; # used
for caching user values
981 # optional mail function to use instead of mail() 982 private static $EmailFunc = NULL;
984 # check whether a user name is valid (alphanumeric string of 2-24 chars) 987 if (preg_match(
"/^[a-zA-Z0-9]{2,24}$/", $UserName))
997 # check whether a password is valid (at least 6 characters) 1000 if (strlen(self::NormalizePassword($Password)) < 6)
1010 # check whether an e-mail address looks valid 1013 if (preg_match(
"/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/",
1024 # get normalized version of e-mail address 1027 return strtolower(trim($EMailAddress));
1030 # get normalized version of user name 1033 return trim($UserName);
1036 # get normalized version of password 1039 return trim($Password);
1042 # generate random password 1045 # seed random number generator 1046 mt_srand((
double)microtime() * 1000000);
1048 # generate password of requested length 1049 return sprintf(
"%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
1050 (pow(10, $PasswordMaxLength) - 1)));
1053 # convenience function to supply parameters to Database->UpdateValue() 1056 return $this->DB->UpdateValue(
"APUsers", $FieldName, $NewValue,
1057 "UserId = '".$this->UserId.
"'", $this->DBFields);
1060 # methods for backward compatibility with earlier versions of User
GetRandomPassword($PasswordMinLength=6, $PasswordMaxLength=8)
static NormalizeUserName($UserName)
static IsValidLookingEMailAddress($EMail)
GetUniqueCode($SeedString, $CodeLength)
__construct($UserInfoOne=NULL, $UserInfoTwo=NULL)
SQL database abstraction object with smart query caching.
IsMailChangeCodeGood($Code)
UpdateValue($FieldName, $NewValue=DB_NOVALUE)
static NormalizePassword($Password)
CreateNewUserAndMailPassword($UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
static IsValidPassword($Password)
Login($UserName, $Password, $IgnorePassword=FALSE)
SetEncryptedPassword($NewEncryptedPassword)
StatusMessage($StatusCode=NULL)
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)
IsActivated($NewValue=DB_NOVALUE)
HasPriv($Privilege, $Privileges=NULL)
Check whether user has specified privilege(s).
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)
Set($FieldName, $NewValue)
const U_DUPLICATEUSERNAME
static SetEmailFunction($NewValue)
Set email function to use instead of mail().
static NormalizeEMailAddress($EMailAddress)
GetDate($FieldName, $Format="")
CreateNewUserWithEMailedPassword($UserName, $EMail, $EMailAgain, $TemplateFile="Axis--User--EMailTemplate.txt")
CreateNewUserAndMailPasswordFromFile($UserName, $EMail, $EMailAgain, $TemplateFile="Axis--User--EMailTemplate.txt")
SetPassword($NewPassword)
SetPrivList($NewPrivileges)
ChangePassword($OldPassword, $NewPassword, $NewPasswordAgain)
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