5 # An Object for Handling User Information
7 # Copyright 1999-2001 Axis Data
8 # This code is free software that can be used or redistributed under the
9 # terms of Version 2 of the GNU General Public License, as published by the
10 # Free Software Foundation (http://www.fsf.org).
12 # Author: Edward Almasy (almasy@axisdata.com)
14 # Part of the AxisPHP library v1.2.4
15 # For more information see http://www.axisdata.com/AxisPHP/
18 # status values (error codes)
21 define(
"U_BADPASSWORD", 2);
22 define(
"U_NOSUCHUSER", 3);
23 define(
"U_PASSWORDSDONTMATCH", 4);
24 define(
"U_EMAILSDONTMATCH", 5);
25 define(
"U_DUPLICATEUSERNAME", 6);
26 define(
"U_ILLEGALUSERNAME", 7);
27 define(
"U_EMPTYUSERNAME", 8);
28 define(
"U_ILLEGALPASSWORD", 9);
29 define(
"U_ILLEGALPASSWORDAGAIN",10);
30 define(
"U_EMPTYPASSWORD", 11);
31 define(
"U_EMPTYPASSWORDAGAIN", 12);
32 define(
"U_ILLEGALEMAIL", 13);
33 define(
"U_ILLEGALEMAILAGAIN", 14);
34 define(
"U_EMPTYEMAIL", 15);
35 define(
"U_EMPTYEMAILAGAIN", 16);
36 define(
"U_NOTLOGGEDIN", 17);
37 define(
"U_MAILINGERROR", 18);
38 define(
"U_TEMPLATENOTFOUND", 19);
39 define(
"U_DUPLICATEEMAIL", 20);
44 # ---- PUBLIC INTERFACE --------------------------------------------------
46 function User($UserInfoOne = NULL, $UserInfoTwo = NULL)
48 # assume constructor will succeed and user is not logged in
50 $this->LoggedIn = FALSE;
52 # create database connection
55 # if user info passed in
56 if (is_int($UserInfoOne) || is_string($UserInfoOne)
57 || is_int($UserInfoTwo) || is_string($UserInfoTwo))
59 # if user ID was passed in
60 if (is_int($UserInfoOne) || is_int($UserInfoTwo))
63 $this->UserId = is_int($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
67 # look up user ID in database
68 $UserInfoTwo = is_string($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
69 $this->DB->Query(
"SELECT UserId, LoggedIn FROM APUsers"
70 .
" WHERE UserName='".addslashes($UserInfoTwo).
"'");
71 $Record = $this->DB->FetchRow();
74 $this->UserId = $Record[
"UserId"];
75 $this->LoggedIn = $Record[
"LoggedIn"];
78 # if user ID was not found
79 if ($Record === FALSE)
81 # if name looks like it could actually be a user ID
82 if (preg_match(
"/^[-]*[0-9]+$/", $UserInfoTwo))
84 # assume name was user ID
85 $this->UserId = intval($UserInfoTwo);
89 # set code indicating no user found
98 # if user ID is available from session
99 if (isset($_SESSION[
"APUserId"]))
102 $this->UserId = $_SESSION[
"APUserId"];
104 # set flag indicating user is currently logged in
105 $this->LoggedIn = TRUE;
112 return $this->Result;
115 # return text message corresponding to current (or specified) status code
118 $APUserStatusMessages = array(
119 U_OKAY =>
"The operation was successful.",
120 U_ERROR =>
"There has been an error.",
131 .
" short, too long, or contains"
132 .
" illegal characters.",
134 .
" too short, too long, or"
135 .
" contains illegal characters.",
137 .
" appears to be invalid.",
140 .
" to send e-mail. Please notify"
141 .
" the system administrator.",
143 .
" to generate e-mail. Please"
144 .
" notify the system administrator.",
146 .
" has an account associated with it.",
149 return ($StatusCode === NULL) ? $APUserStatusMessages[$this->Result]
150 : $APUserStatusMessages[$StatusCode];
155 # clear priv list values
156 $this->DB->Query(
"DELETE FROM APUserPrivileges WHERE UserId = '".$this->UserId.
"'");
158 # delete user record from database
159 $this->DB->Query(
"DELETE FROM APUsers WHERE UserId = '".$this->UserId.
"'");
161 # report to caller that everything succeeded
163 return $this->Result;
173 if (is_callable($NewValue))
175 self::$EmailFunc = $NewValue;
180 # ---- Getting/Setting Values --------------------------------------------
184 return $this->UserId;
188 return $this->
Get(
"UserName");
194 $this->DB->Query(
"UPDATE APUsers SET"
195 .
" LastLocation = '".addslashes($NewLocation).
"',"
196 .
" LastActiveDate = NOW(),"
197 .
" LastIPAddress = '".$_SERVER[
"REMOTE_ADDR"].
"'"
198 .
" WHERE UserId = '".addslashes($this->UserId).
"'");
199 if (isset($this->DBFields))
201 $this->DBFields[
"LastLocation"] = $NewLocation;
202 $this->DBFields[
"LastActiveDate"] = date(
"Y-m-d H:i:s");
205 return $this->
Get(
"LastLocation");
209 return $this->
Get(
"LastActiveDate");
213 return $this->
Get(
"LastIPAddress");
216 # get value from specified field
222 # get value (formatted as a date) from specified field
225 # retrieve specified value from database
226 if (strlen($Format) > 0)
228 $this->DB->Query(
"SELECT DATE_FORMAT(`".addslashes($FieldName).
"`, '".addslashes($Format).
"') AS `".addslashes($FieldName).
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
232 $this->DB->Query(
"SELECT `".addslashes($FieldName).
"` FROM APUsers WHERE UserId='".$this->UserId.
"'");
234 $Record = $this->DB->FetchRow();
236 # return value to caller
237 return $Record[$FieldName];
240 # set value in specified field
241 function Set($FieldName, $NewValue)
245 return $this->Result;
249 # ---- Login Functions ---------------------------------------------------
251 function Login($UserName, $Password, $IgnorePassword = FALSE)
253 # if user not found in DB
254 $this->DB->Query(
"SELECT * FROM APUsers"
255 .
" WHERE UserName = '"
256 .addslashes(self::NormalizeUserName($UserName)).
"'");
257 if ($this->DB->NumRowsSelected() < 1)
259 # result is no user by that name
264 # grab password from DB
265 $Record = $this->DB->FetchRow();
266 $StoredPassword = $Record[
"UserPassword"];
268 if (isset($Password[0]) && $Password[0] ==
" ")
270 $Challenge = md5(date(
"Ymd").$_SERVER[
"REMOTE_ADDR"]);
271 $StoredPassword = md5( $Challenge . $StoredPassword );
273 $EncryptedPassword = trim($Password);
277 # if supplied password matches encrypted password
278 $EncryptedPassword = crypt($Password, $StoredPassword);
281 if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
286 # store user ID for session
287 $this->UserId = $Record[
"UserId"];
288 $_SESSION[
"APUserId"] = $this->UserId;
290 # update last login date
291 $this->DB->Query(
"UPDATE APUsers SET LastLoginDate = NOW(),"
293 .
" WHERE UserId = '".$this->UserId.
"'");
295 # Check for old format hashes, and rehash if possible
296 if ($EncryptedPassword === $StoredPassword &&
297 substr($StoredPassword,0,3) !==
"$1$" &&
298 $Password[0] !==
" " &&
301 $NewPassword = crypt($Password);
303 "UPDATE APUsers SET UserPassword='".addslashes($NewPassword).
"' "
304 .
"WHERE UserId='".$this->UserId.
"'");
307 # since self::DBFields might already have been set to false if
308 # the user wasn't logged in when this is called, populate it
309 # with user data so that a call to self::UpdateValue will be
310 # able to properly fetch the data associated with the user
311 $this->DBFields = $Record;
313 # set flag to indicate we are logged in
314 $this->LoggedIn = TRUE;
318 # result is bad password
323 # return result to caller
324 return $this->Result;
330 # clear user ID (if any) for session
331 unset($_SESSION[
"APUserId"]);
333 # if user is marked as logged in
336 # set flag to indicate user is no longer logged in
337 $this->LoggedIn = FALSE;
339 # clear login flag in database
341 "UPDATE APUsers SET LoggedIn = '0' "
342 .
"WHERE UserId='".$this->UserId.
"'");
349 "SELECT * FROM APUsers WHERE UserName = '"
350 .addslashes(self::NormalizeUserName($UserName)).
"'");
352 if ($this->DB->NumRowsSelected() < 1)
354 # result is no user by that name, generate a fake salt
355 # to discourage user enumeration. Make it be an old-format
356 # crypt() salt so that it's harder.
357 $SaltString = $_SERVER[
"SERVER_ADDR"].$UserName;
358 $Result = substr(base64_encode(md5($SaltString)),0,2);
362 # grab password from DB
363 # Assumes that we used php's crypt() for the passowrd
364 # management stuff, and will need to be changed if we
365 # go to something else.
366 $Record = $this->DB->FetchRow();
367 $StoredPassword = $Record[
"UserPassword"];
369 if (substr($StoredPassword,0,3)===
"$1$")
371 $Result = substr($StoredPassword, 0,12);
375 $Result = substr($StoredPassword, 0,2);
382 # report whether this user is or is not currently logged in
387 # ---- Password Functions ------------------------------------------------
389 # set new password (with checks against old password)
392 # make sure a user is logged in
396 return $this->Result;
399 # if old password is not correct
400 $StoredPassword = $this->DB->Query(
"SELECT UserPassword FROM APUsers"
401 .
" WHERE UserId='".$this->UserId.
"'",
"UserPassword");
402 $EncryptedPassword = crypt($OldPassword, $StoredPassword);
403 if ($EncryptedPassword != $StoredPassword)
405 # set status to indicate error
408 # else if new password is not legal
411 # set status to indicate error
414 # else if both instances of new password do not match
415 elseif (self::NormalizePassword($NewPassword)
416 != self::NormalizePassword($NewPasswordAgain))
418 # set status to indicate error
426 # set status to indicate password successfully changed
430 # report to caller that everything succeeded
431 return $this->Result;
437 # generate encrypted password
438 $EncryptedPassword = crypt(self::NormalizePassword($NewPassword));
440 # save encrypted password
441 $this->
UpdateValue(
"UserPassword", $EncryptedPassword);
445 $UserName, $EMail, $EMailAgain,
446 $TemplateFile =
"Axis--User--EMailTemplate.txt")
449 $UserName, $EMail, $EMailAgain, $TemplateFile);
453 $UserName, $EMail, $EMailAgain,
454 $TemplateFile =
"Axis--User--EMailTemplate.txt")
456 # load e-mail template from file (first line is subject)
457 $Template = file($TemplateFile, 1);
458 $EMailSubject = array_shift($Template);
459 $EMailBody = join(
"", $Template);
462 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
466 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
468 # make sure e-mail addresses match
469 if ($EMail != $EMailAgain)
472 return $this->Result;
475 # make sure e-mail address looks valid
479 return $this->Result;
482 # generate random password
485 # attempt to create new user with password
486 $Result = $this->CreateNewUser($UserName, $Password, $Password);
488 # if user creation failed
491 # report error result to caller
497 # set e-mail address in user record
498 $this->
Set(
"EMail", $EMail);
500 # plug appropriate values into subject and body of e-mail message
501 $EMailSubject = str_replace(
"X-USERNAME-X", $UserName, $EMailSubject);
502 $EMailBody = str_replace(
"X-USERNAME-X", $UserName, $EMailBody);
503 $EMailBody = str_replace(
"X-PASSWORD-X", $Password, $EMailBody);
505 # send out e-mail message with new account info
506 if (is_Callable(self::$EmailFunc))
508 $Result = call_user_func(self::$EmailFunc,
509 $EMail, $EMailSubject, $EMailBody,
510 "Auto-Submitted: auto-generated");
514 $Result = mail($EMail, $EMailSubject, $EMailBody,
515 "Auto-Submitted: auto-generated");
518 # if mailing attempt failed
521 # report error to caller
523 return $this->Result;
528 # report success to caller
530 return $this->Result;
535 # get code for user to submit to confirm registration
538 # code is MD5 sum based on user name and encrypted password
539 $ActivationCodeLength = 6;
540 return $this->
GetUniqueCode(
"Activation", $ActivationCodeLength);
543 # check whether confirmation code is valid
550 # get/set whether user registration has been confirmed
553 return $this->
UpdateValue(
"RegistrationConfirmed", $NewValue);
556 # get code for user to submit to confirm password reset
559 # code is MD5 sum based on user name and encrypted password
560 $ResetCodeLength = 10;
564 # check whether password reset code is valid
567 return (strtoupper(trim($Code)) == $this->
GetResetCode())
571 # get code for user to submit to confirm mail change request
574 $ResetCodeLength = 10;
586 # send e-mail to user (returns TRUE on success)
588 $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
591 # if template is file name
592 if (@is_file($TemplateTextOrFileName))
594 # load in template from file
595 $Template = file($TemplateTextOrFileName, 1);
597 # report error to caller if template load failed
598 if ($Template == FALSE)
601 return $this->Status;
604 # join into one text block
605 $TemplateTextOrFileName = join(
"", $Template);
608 # split template into lines
609 $Template = explode(
"\n", $TemplateTextOrFileName);
611 # strip any comments out of template
612 $FilteredTemplate = array();
613 foreach ($Template as $Line)
615 if (!preg_match(
"/^[\\s]*#/", $Line))
617 $FilteredTemplate[] = $Line;
621 # split subject line out of template (first non-comment line in file)
622 $EMailSubject = array_shift($FilteredTemplate);
623 $EMailBody = join(
"\n", $FilteredTemplate);
625 # set up our substitutions
626 $Substitutions = array(
627 "X-USERNAME-X" => $this->
Get(
"UserName"),
628 "X-EMAILADDRESS-X" => $this->
Get(
"EMail"),
632 "X-IPADDRESS-X" => @$_SERVER[
"REMOTE_ADDR"],
635 # if caller provided additional substitutions
636 if (is_array($MoreSubstitutions))
638 # add in entries from caller to substitution list
639 $Substitutions = array_merge(
640 $Substitutions, $MoreSubstitutions);
643 # perform substitutions on subject and body of message
644 $EMailSubject = str_replace(array_keys($Substitutions),
645 array_values($Substitutions), $EMailSubject);
646 $EMailBody = str_replace(array_keys($Substitutions),
647 array_values($Substitutions), $EMailBody);
649 $AdditionalHeaders =
"Auto-Submitted: auto-generated";
651 # if caller provided "From" address
654 # prepend "From" address onto message
655 $AdditionalHeaders .=
"\r\nFrom: ".$FromAddress;
658 # send out mail message
659 if (is_Callable(self::$EmailFunc))
661 $Result = call_user_func(self::$EmailFunc,
662 is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
663 $EMailSubject, $EMailBody, $AdditionalHeaders);
667 $Result = mail(is_null($ToAddress)?$this->
Get(
"EMail"):$ToAddress,
669 $EMailBody, $AdditionalHeaders);
672 # report result of mailing attempt to caller
678 # ---- Privilege Functions -----------------------------------------------
688 function HasPriv($Privilege, $Privileges = NULL)
690 # make sure a user is logged in (no privileges if not logged in)
691 if ($this->
IsLoggedIn() == FALSE) {
return FALSE; }
693 # bail out if empty array of privileges passed in
694 if (is_array($Privilege) && !count($Privilege) && (func_num_args() < 2))
697 # set up beginning of database query
698 $Query =
"SELECT COUNT(*) AS PrivCount FROM APUserPrivileges "
699 .
"WHERE UserId='".$this->UserId.
"' AND (";
701 # add first privilege(s) to query (first arg may be single value or array)
702 if (is_array($Privilege))
705 foreach ($Privilege as $Priv)
707 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
713 $Query .=
"Privilege='".$Privilege.
"'";
717 # add any privileges from additional args to query
718 $Args = func_get_args();
720 foreach ($Args as $Arg)
722 $Query .= $Sep.
"Privilege='".$Arg.
"'";
729 # look for privilege in database
730 $PrivCount = $this->DB->Query($Query,
"PrivCount");
732 # return value to caller
733 return ($PrivCount > 0) ? TRUE : FALSE;
746 # set up beginning of database query
747 $Query =
"SELECT UserId FROM APUserPrivileges "
750 # add first privilege(s) to query (first arg may be single value or array)
751 if (is_array($Privilege))
754 foreach ($Privilege as $Priv)
756 $Query .= $Sep.
"Privilege='".addslashes($Priv).
"'";
762 $Query .=
"Privilege='".$Privilege.
"'";
766 # add any privileges from additional args to query
767 $Args = func_get_args();
769 foreach ($Args as $Arg)
771 $Query .= $Sep.
"Privilege='".$Arg.
"'";
775 # return query to caller
781 # if privilege value is invalid
782 if (intval($Privilege) != trim($Privilege))
784 # set code to indicate error
789 # if user does not already have privilege
790 $PrivCount = $this->DB->Query(
"SELECT COUNT(*) AS PrivCount"
791 .
" FROM APUserPrivileges"
792 .
" WHERE UserId='".$this->UserId.
"'"
793 .
" AND Privilege='".$Privilege.
"'",
797 # add privilege for this user to database
798 $this->DB->Query(
"INSERT INTO APUserPrivileges"
799 .
" (UserId, Privilege) VALUES"
800 .
" ('".$this->UserId.
"', ".$Privilege.
")");
803 # set code to indicate success
807 # report result to caller
808 return $this->Result;
813 # remove privilege from database (if present)
814 $this->DB->Query(
"DELETE FROM APUserPrivileges"
815 .
" WHERE UserId = '".$this->UserId.
"'"
816 .
" AND Privilege = '".$Privilege.
"'");
818 # report success to caller
820 return $this->Result;
825 # read privileges from database and return array to caller
826 $this->DB->Query(
"SELECT Privilege FROM APUserPrivileges"
827 .
" WHERE UserId='".$this->UserId.
"'");
828 return $this->DB->FetchColumn(
"Privilege");
833 # clear old priv list values
834 $this->DB->Query(
"DELETE FROM APUserPrivileges"
835 .
" WHERE UserId='".$this->UserId.
"'");
837 # for each priv value passed in
838 foreach ($NewPrivileges as $Privilege)
846 # ---- Miscellaneous Functions -------------------------------------------
848 # get unique alphanumeric code for user
851 return substr(strtoupper(md5(
852 $this->
Get(
"UserName").$this->
Get(
"UserPassword").$SeedString)),
857 # ---- PRIVATE INTERFACE -------------------------------------------------
859 protected $DB; # handle to SQL database we use to store user information
860 private $UserId; # user ID number
for reference into database
861 private $Result; # result of last operation
862 private $LoggedIn; # flag indicating whether user is logged in
863 private $DBFields; # used
for caching user values
865 # optional mail function to use instead of mail()
866 private static $EmailFunc = NULL;
868 # check whether a user name is valid (alphanumeric string of 2-24 chars)
871 if (preg_match(
"/^[a-zA-Z0-9]{2,24}$/", $UserName)) {
return TRUE; }
else {
return FALSE; }
874 # check whether a password is valid (at least 6 characters)
877 if (strlen(self::NormalizePassword($Password)) < 6)
878 {
return FALSE; }
else {
return TRUE; }
881 # check whether an e-mail address looks valid
884 if (preg_match(
"/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/", $EMail)) {
return TRUE; }
else {
return FALSE; }
887 # get normalized version of e-mail address
890 return strtolower(trim($EMailAddress));
893 # get normalized version of user name
896 return trim($UserName);
899 # get normalized version of password
902 return trim($Password);
905 # generate random password
908 # seed random number generator
909 mt_srand((
double)microtime() * 1000000);
911 # generate password of requested length
912 return sprintf(
"%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
913 (pow(10, $PasswordMaxLength) - 1)));
916 # convenience function to supply parameters to Database->UpdateValue()
919 return $this->DB->UpdateValue(
"APUsers", $FieldName, $NewValue,
920 "UserId = '".$this->UserId.
"'", $this->DBFields);
923 # methods for backward compatibility with earlier versions of User