Axis--User.php

Go to the documentation of this file.
00001 <?PHP
00002 
00003 #
00004 #   Axis--User.php
00005 #   An Object for Handling User Information
00006 #
00007 #   Copyright 1999-2001 Axis Data
00008 #   This code is free software that can be used or redistributed under the
00009 #   terms of Version 2 of the GNU General Public License, as published by the
00010 #   Free Software Foundation (http://www.fsf.org).
00011 #
00012 #   Author:  Edward Almasy (almasy@axisdata.com)
00013 #
00014 #   Part of the AxisPHP library v1.2.4
00015 #   For more information see http://www.axisdata.com/AxisPHP/
00016 #
00017 
00018 # status values (error codes)
00019 define("U_OKAY",                0);
00020 define("U_ERROR",               1);
00021 define("U_BADPASSWORD",         2);
00022 define("U_NOSUCHUSER",          3);
00023 define("U_PASSWORDSDONTMATCH",  4);
00024 define("U_EMAILSDONTMATCH",     5);
00025 define("U_DUPLICATEUSERNAME",   6);
00026 define("U_ILLEGALUSERNAME",     7);
00027 define("U_EMPTYUSERNAME",       8);
00028 define("U_ILLEGALPASSWORD",     9);
00029 define("U_ILLEGALPASSWORDAGAIN",10);
00030 define("U_EMPTYPASSWORD",       11);
00031 define("U_EMPTYPASSWORDAGAIN",  12);
00032 define("U_ILLEGALEMAIL",        13);
00033 define("U_ILLEGALEMAILAGAIN",   14);
00034 define("U_EMPTYEMAIL",          15);
00035 define("U_EMPTYEMAILAGAIN",     16);
00036 define("U_NOTLOGGEDIN",         17);
00037 define("U_MAILINGERROR",        18);
00038 define("U_TEMPLATENOTFOUND",    19);
00039 define("U_DUPLICATEEMAIL",      20);
00040 
00041 
00042 class User {
00043 
00044     # ---- PUBLIC INTERFACE --------------------------------------------------
00045 
00046     function User(&$SessionOrDb, $UserInfo=NULL)
00047     {
00048         # assume constructor will succeed and user is not logged in
00049         $this->Result = U_OKAY;
00050         $this->LoggedIn = FALSE;
00051 
00052         # if a session was passed in
00053         if (is_object($SessionOrDb) && method_exists($SessionOrDb, "Session"))
00054         {
00055             # save pointer to session
00056             $this->Session =& $SessionOrDb;
00057 
00058             # swipe database handle from session
00059             $this->DB =& $this->Session->DB;
00060 
00061             # if user ID is available from session
00062             if ($this->Session->Get("APUserId") !== NULL)
00063             {
00064                 # save user ID
00065                 $this->UserId = $this->Session->Get("APUserId");
00066 
00067                 # set flag indicating user is currently logged in
00068                 $this->LoggedIn = TRUE;
00069             }
00070         }
00071         # else if database handle was passed in
00072         elseif (is_object($SessionOrDb)
00073                 && method_exists($SessionOrDb, "Database"))
00074         {
00075             # save database handle
00076             $this->DB =& $SessionOrDb;
00077 
00078             # if user ID was passed in
00079             if (is_int($UserInfo))
00080             {
00081                 # save user ID
00082                 $this->UserId = $UserInfo;
00083             }
00084             # else if user name was passed in
00085             elseif (is_string($UserInfo))
00086             {
00087                 # look up user ID in database
00088                 $this->DB->Query("SELECT UserId FROM APUsers"
00089                         ." WHERE UserName='".addslashes($UserInfo)."'");
00090 
00091                 # if user ID was found
00092                 if ($this->DB->NumRowsSelected() > 0)
00093                 {
00094                     $this->UserId = $this->DB->FetchField("UserId");
00095                 }
00096                 else
00097                 {
00098                     # if name looks like it could actually be a user ID
00099                     if (preg_match("/^[0-9-]$/", $UserInfo))
00100                     {
00101                         # assume name was user ID
00102                         $this->UserId = $UserInfo;
00103                     }
00104                     else
00105                     {
00106                         # set code indicating no user found
00107                         $this->Result = U_NOSUCHUSER;
00108                     }
00109                 }
00110             }
00111         }
00112         else
00113         {
00114             # error out
00115             $this->Result = U_ERROR;
00116             exit("ERROR: User object creation attempted without DB or session");
00117         }
00118     }
00119 
00120     function Status()
00121     {
00122         return $this->Result;
00123     }
00124 
00125     # return text message corresponding to current (or specified) status code
00126     function StatusMessage($StatusCode = NULL)
00127     {
00128         $APUserStatusMessages = array(
00129                 U_OKAY                => "The operation was successful.",
00130                 U_ERROR               => "There has been an error.",
00131                 U_BADPASSWORD         => "The password you entered was"
00132                                             ." incorrect.",
00133                 U_NOSUCHUSER          => "No such user name was found.",
00134                 U_PASSWORDSDONTMATCH  => "The new passwords you entered do"
00135                                             ." not match.",
00136                 U_EMAILSDONTMATCH     => "The e-mail addresses you entered"
00137                                             ." do not match.",
00138                 U_DUPLICATEUSERNAME   => "The user name you requested is"
00139                                             ." already in use.",
00140                 U_ILLEGALUSERNAME     => "The user name you requested is too"
00141                                             ." short, too long, or contains"
00142                                             ." illegal characters.",
00143                 U_ILLEGALPASSWORD     => "The new password you requested is"
00144                                             ." too short, too long, or"
00145                                             ." contains illegal characters.",
00146                 U_ILLEGALEMAIL        => "The e-mail address you entered"
00147                                             ." appears to be invalid.",
00148                 U_NOTLOGGEDIN         => "The user is not logged in.",
00149                 U_MAILINGERROR        => "An error occurred while attempting"
00150                                             ." to send e-mail.  Please notify"
00151                                             ." the system administrator.",
00152                 U_TEMPLATENOTFOUND    => "An error occurred while attempting"
00153                                             ." to generate e-mail.  Please"
00154                                             ." notify the system administrator.",
00155                 U_DUPLICATEEMAIL      => "The e-mail address you supplied already"
00156                                             ." has an account associated with it.",
00157                 );
00158 
00159         return ($StatusCode === NULL) ? $APUserStatusMessages[$this->Result]
00160                 : $APUserStatusMessages[$StatusCode];
00161     }
00162 
00163     function Delete()
00164     {
00165         # clear priv list values
00166         $this->DB->Query("DELETE FROM APUserPrivileges WHERE UserId = '".$this->UserId."'");
00167 
00168         # delete user record from database
00169         $this->DB->Query("DELETE FROM APUsers WHERE UserId = '".$this->UserId."'");
00170 
00171         # report to caller that everything succeeded
00172         $this->Result = U_OKAY;
00173         return $this->Result;
00174     }
00175 
00176 
00177     # ---- Getting/Setting Values --------------------------------------------
00178 
00179     function Id()
00180     {
00181         return $this->UserId;
00182     }
00183     function Name()
00184     {
00185         return $this->Get("UserName");
00186     }
00187     function LastLocation($NewLocation = NULL)
00188     {
00189         if ($NewLocation)
00190         {
00191             $this->DB->Query("UPDATE APUsers SET"
00192                     ." LastLocation = '".addslashes($NewLocation)."',"
00193                     ." LastActiveDate = NOW(),"
00194                     ." LastIPAddress = '".$_SERVER["REMOTE_ADDR"]."'"
00195                     ." WHERE UserId = '".addslashes($this->UserId)."'");
00196             if (isset($this->DBFields))
00197             {
00198                 $this->DBFields["LastLocation"] = $NewLocation;
00199                 $this->DBFields["LastActiveDate"] = date("Y-m-d H:i:s");
00200             }
00201         }
00202         return $this->Get("LastLocation");
00203     }
00204     function LastActiveDate()
00205     {
00206         return $this->Get("LastActiveDate");
00207     }
00208     function LastIPAddress()
00209     {
00210         return $this->Get("LastIPAddress");
00211     }
00212 
00213     # get value from specified field
00214     function Get($FieldName)
00215     {
00216         return $this->UpdateValue($FieldName);
00217     }
00218 
00219     # get value (formatted as a date) from specified field
00220     function GetDate($FieldName, $Format = "")
00221     {
00222         # retrieve specified value from database
00223         if (strlen($Format) > 0)
00224         {
00225             $this->DB->Query("SELECT DATE_FORMAT(`".addslashes($FieldName)."`, '".addslashes($Format)."') AS `".addslashes($FieldName)."` FROM APUsers WHERE UserId='".$this->UserId."'");
00226         }
00227         else
00228         {
00229             $this->DB->Query("SELECT `".addslashes($FieldName)."` FROM APUsers WHERE UserId='".$this->UserId."'");
00230         }
00231         $Record = $this->DB->FetchRow();
00232 
00233         # return value to caller
00234         return $Record[$FieldName];
00235     }
00236 
00237     # set value in specified field
00238     function Set($FieldName, $NewValue)
00239     {
00240         $this->UpdateValue($FieldName, $NewValue);
00241         $this->Result = U_OKAY;
00242         return $this->Result;
00243     }
00244 
00245 
00246     # ---- Login Functions ---------------------------------------------------
00247 
00248     function Login($UserName, $Password, $IgnorePassword = FALSE)
00249     {
00250         global $APUserId;
00251 
00252         # error out if we are not part of a session
00253         if (!isset($this->Session))
00254         {
00255             exit("ERROR: User->Login() called on object without session");
00256         }
00257 
00258         # if user not found in DB
00259         $this->DB->Query("SELECT * FROM APUsers"
00260                 ." WHERE UserName = '"
00261                         .addslashes($this->NormalizeUserName($UserName))."'");
00262         if ($this->DB->NumRowsSelected() < 1)
00263         {
00264             # result is no user by that name
00265             $this->Result = U_NOSUCHUSER;
00266         }
00267         else
00268         {
00269             # grab password from DB
00270             $Record = $this->DB->FetchRow();
00271             $StoredPassword = $Record["UserPassword"];
00272 
00273             if (isset($Password[0]) && $Password[0] == " ")
00274             {
00275                 $Challenge = md5(date("Ymd").$_SERVER["REMOTE_ADDR"]);
00276                 $StoredPassword = md5( $Challenge . $StoredPassword );
00277 
00278                 $EncryptedPassword = trim($Password);
00279             }
00280             else
00281             {
00282                 # if supplied password matches encrypted password
00283                 $EncryptedPassword = crypt($Password, $StoredPassword);
00284             }
00285 
00286             if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
00287             {
00288                 # result is success
00289                 $this->Result = U_OKAY;
00290 
00291                 # store user ID for session
00292                 $this->UserId = $Record["UserId"];
00293                 $APUserId = $this->UserId;
00294                 $this->Session->RegisterVariable("APUserId");
00295 
00296                 # update last login date
00297                 $this->DB->Query("UPDATE APUsers SET LastLoginDate = NOW() "
00298                         ."WHERE UserId = '".$this->UserId."'");
00299 
00300                 # Check for old format hashes, and rehash if possible
00301                 if ($EncryptedPassword === $StoredPassword &&
00302                     substr($StoredPassword,0,3) !== "$1$" &&
00303                     $Password[0] !== " " &&
00304                     CRYPT_MD5 )
00305                 {
00306                     $NewPassword = crypt($Password);
00307                     $this->DB->Query(
00308                         "UPDATE APUsers SET UserPassword='".addslashes($NewPassword)."' "
00309                         ."WHERE UserId='".$this->UserId."'");
00310                 }
00311 
00312                 # set flag to indicate we are logged in
00313                 $this->LoggedIn = TRUE;
00314             }
00315             else
00316             {
00317                 # result is bad password
00318                 $this->Result = U_BADPASSWORD;
00319             }
00320         }
00321 
00322         # return result to caller
00323         return $this->Result;
00324     }
00325 
00326     # log this user out
00327     function Logout()
00328     {
00329         # if we are part of a session
00330         if (isset($this->Session))
00331         {
00332             # clear user ID for session
00333             $this->Session->UnregisterVariable("APUserId");
00334         }
00335 
00336         # set flag to indicate user is no longer logged in
00337         $this->LoggedIn = FALSE;
00338     }
00339 
00340     function GetPasswordSalt($UserName)
00341     {
00342         $this->DB->Query(
00343             "SELECT * FROM APUsers WHERE UserName = '"
00344             .addslashes($this->NormalizeUserName($UserName))."'");
00345 
00346         if ($this->DB->NumRowsSelected() < 1)
00347         {
00348             # result is no user by that name, generate a fake salt
00349             # to prevent user enumeration.
00350             $SaltString = $_SERVER["SERVER_ADDR"].$UserName;
00351             $Result = "$1$".substr(base64_encode(md5($SaltString)),0,8)."$";
00352         }
00353         else
00354         {
00355             # grab password from DB
00356             # Assumes that we used php's crypt() for the passowrd
00357             # management stuff, and will need to be changed if we
00358             # go to something else.
00359             $Record = $this->DB->FetchRow();
00360             $StoredPassword = $Record["UserPassword"];
00361 
00362             if (substr($StoredPassword,0,3)==="$1$")
00363             {
00364                 $Result = substr($StoredPassword, 0,12);
00365             }
00366             else
00367             {
00368                 $Result = substr($StoredPassword, 0,2);
00369             }
00370         }
00371 
00372         return $Result;
00373     }
00374 
00375     # report whether this user is or is not currently logged in
00376     function IsLoggedIn() {  return $this->LoggedIn;  }
00377     function IsNotLoggedIn() {  return !$this->LoggedIn;  }
00378 
00379 
00380     # ---- Password Functions ------------------------------------------------
00381 
00382     # set new password (with checks against old password)
00383     function ChangePassword($OldPassword, $NewPassword, $NewPasswordAgain)
00384     {
00385         # if we are part of a session make sure a user is logged in
00386         if (isset($this->Session) && ($this->IsLoggedIn() == FALSE))
00387         {
00388             $this->Result = U_NOTLOGGEDIN;
00389             return $this->Result;
00390         }
00391 
00392         # if old password is not correct
00393         $StoredPassword = $this->DB->Query("SELECT UserPassword FROM APUsers"
00394                 ." WHERE UserId='".$this->UserId."'", "UserPassword");
00395         $EncryptedPassword = crypt($OldPassword, $StoredPassword);
00396         if ($EncryptedPassword != $StoredPassword)
00397         {
00398             # set status to indicate error
00399             $this->Result = U_BADPASSWORD;
00400         }
00401         # else if new password is not legal
00402         elseif (!$this->IsValidPassword($NewPassword))
00403         {
00404             # set status to indicate error
00405             $this->Result = U_ILLEGALPASSWORD;
00406         }
00407         # else if both instances of new password do not match
00408         elseif ($this->NormalizePassword($NewPassword)
00409                 != $this->NormalizePassword($NewPasswordAgain))
00410         {
00411             # set status to indicate error
00412             $this->Result = U_PASSWORDSDONTMATCH;
00413         }
00414         else
00415         {
00416             # set new password
00417             $this->SetPassword($NewPassword);
00418 
00419             # set status to indicate password successfully changed
00420             $this->Result = U_OKAY;
00421         }
00422 
00423         # report to caller that everything succeeded
00424         return $this->Result;
00425     }
00426 
00427     # set new password
00428     function SetPassword($NewPassword)
00429     {
00430         # generate encrypted password
00431         $EncryptedPassword = crypt($this->NormalizePassword($NewPassword));
00432 
00433         # save encrypted password
00434         $this->UpdateValue("UserPassword", $EncryptedPassword);
00435     }
00436 
00437     function CreateNewUserWithEMailedPassword(
00438             $UserName, $EMail, $EMailAgain,
00439             $TemplateFile = "Axis--User--EMailTemplate.txt")
00440     {
00441         return CreateNewUserAndMailPasswordFromFile(
00442                 $UserName, $EMail, $EMailAgain, $TemplateFile);
00443     }
00444 
00445     function CreateNewUserAndMailPasswordFromFile(
00446             $UserName, $EMail, $EMailAgain,
00447             $TemplateFile = "Axis--User--EMailTemplate.txt")
00448     {
00449         # load e-mail template from file (first line is subject)
00450         $Template = file($TemplateFile, 1);
00451         $EMailSubject = array_shift($Template);
00452         $EMailBody = join("", $Template);
00453 
00454         return CreateNewUserAndMailPassword(
00455                 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
00456     }
00457 
00458     function CreateNewUserAndMailPassword(
00459             $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
00460     {
00461         # make sure e-mail addresses match
00462         if ($EMail != $EMailAgain)
00463         {
00464             $this->Result = U_EMAILSDONTMATCH;
00465             return $this->Result;
00466         }
00467 
00468         # make sure e-mail address looks valid
00469         if ($this->IsValidLookingEMailAddress($EMail) == FALSE)
00470         {
00471             $this->Result = U_ILLEGALEMAIL;
00472             return $this->Result;
00473         }
00474 
00475         # generate random password
00476         $Password = $this->GetRandomPassword();
00477 
00478         # attempt to create new user with password
00479         $Result = $this->CreateNewUser($UserName, $Password, $Password);
00480 
00481         # if user creation failed
00482         if ($Result != U_OKAY)
00483         {
00484             # report error result to caller
00485             return $Result;
00486         }
00487         # else
00488         else
00489         {
00490             # set e-mail address in user record
00491             $this->Set("EMail", $EMail);
00492 
00493             # plug appropriate values into subject and body of e-mail message
00494             $EMailSubject = str_replace("X-USERNAME-X", $UserName, $EMailSubject);
00495             $EMailBody = str_replace("X-USERNAME-X", $UserName, $EMailBody);
00496             $EMailBody = str_replace("X-PASSWORD-X", $Password, $EMailBody);
00497 
00498             # send out e-mail message with new account info
00499             $Result = mail($EMail, $EMailSubject, $EMailBody,
00500                 "Auto-Submitted: auto-generated");
00501 
00502             # if mailing attempt failed
00503             if ($Result != TRUE)
00504             {
00505                 # report error to caller
00506                 $this->Result = U_MAILINGERROR;
00507                 return $this->Result;
00508             }
00509             # else
00510             else
00511             {
00512                 # report success to caller
00513                 $this->Result = U_OKAY;
00514                 return $this->Result;
00515             }
00516         }
00517     }
00518 
00519     # get code for user to submit to confirm registration
00520     function GetActivationCode()
00521     {
00522         # code is MD5 sum based on user name and encrypted password
00523         $ActivationCodeLength = 6;
00524         return $this->GetUniqueCode("Activation", $ActivationCodeLength);
00525     }
00526 
00527     # check whether confirmation code is valid
00528     function IsActivationCodeGood($Code)
00529     {
00530         return (strtoupper(trim($Code)) == $this->GetActivationCode())
00531                 ? TRUE : FALSE;
00532     }
00533 
00534     # get/set whether user registration has been confirmed
00535     function IsActivated($NewValue = DB_NOVALUE)
00536     {
00537         return $this->UpdateValue("RegistrationConfirmed", $NewValue);
00538     }
00539 
00540     # get code for user to submit to confirm password reset
00541     function GetResetCode()
00542     {
00543         # code is MD5 sum based on user name and encrypted password
00544         $ResetCodeLength = 10;
00545         return $this->GetUniqueCode("Reset", $ResetCodeLength);
00546     }
00547 
00548     # check whether password reset code is valid
00549     function IsResetCodeGood($Code)
00550     {
00551         return (strtoupper(trim($Code)) == $this->GetResetCode())
00552                 ? TRUE : FALSE;
00553     }
00554 
00555     # get code for user to submit to confirm mail change request
00556     function GetMailChangeCode()
00557     {
00558       $ResetCodeLength = 10;
00559 
00560       return $this->GetUniqueCode("MailChange".$this->Get("EMail").$this->Get("NewEMail"),
00561                                   $ResetCodeLength);
00562     }
00563 
00564     function IsMailChangeCodeGood($Code)
00565     {
00566       return (strtoupper(trim($Code)) == $this->GetMailChangeCode())
00567         ? TRUE : FALSE;
00568     }
00569 
00570     # send e-mail to user (returns TRUE on success)
00571     function SendEMail(
00572                   $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
00573                   $ToAddress = NULL)
00574     {
00575         # if template is file name
00576         if (@is_file($TemplateTextOrFileName))
00577         {
00578             # load in template from file
00579             $Template = file($TemplateTextOrFileName, 1);
00580 
00581             # report error to caller if template load failed
00582             if ($Template == FALSE)
00583             {
00584                 $this->Status = U_TEMPLATENOTFOUND;
00585                 return $this->Status;
00586             }
00587 
00588             # join into one text block
00589             $TemplateTextOrFileName = join("", $Template);
00590         }
00591 
00592         # split template into lines
00593         $Template = explode("\n", $TemplateTextOrFileName);
00594 
00595         # strip any comments out of template
00596         $FilteredTemplate = array();
00597         foreach ($Template as $Line)
00598         {
00599             if (!preg_match("/^[\\s]*#/", $Line))
00600             {
00601                 $FilteredTemplate[] = $Line;
00602             }
00603         }
00604 
00605         # split subject line out of template (first non-comment line in file)
00606         $EMailSubject = array_shift($FilteredTemplate);
00607         $EMailBody = join("\n", $FilteredTemplate);
00608 
00609         # set up our substitutions
00610         $Substitutions = array(
00611                 "X-USERNAME-X" => $this->Get("UserName"),
00612                 "X-EMAILADDRESS-X" =>  $this->Get("EMail"),
00613                 "X-ACTIVATIONCODE-X" => $this->GetActivationCode(),
00614                 "X-RESETCODE-X" => $this->GetResetCode(),
00615                 "X-CHANGECODE-X" => $this->GetMailChangeCode(),
00616                 "X-IPADDRESS-X" => @$_SERVER["REMOTE_ADDR"],
00617                 );
00618 
00619         # if caller provided additional substitutions
00620         if (is_array($MoreSubstitutions))
00621         {
00622             # add in entries from caller to substitution list
00623             $Substitutions = array_merge(
00624                     $Substitutions, $MoreSubstitutions);
00625         }
00626 
00627         # perform substitutions on subject and body of message
00628         $EMailSubject = str_replace(array_keys($Substitutions),
00629                 array_values($Substitutions), $EMailSubject);
00630         $EMailBody = str_replace(array_keys($Substitutions),
00631                 array_values($Substitutions), $EMailBody);
00632 
00633         $AdditionalHeaders = "Auto-Submitted: auto-generated";
00634 
00635         # if caller provided "From" address
00636         if ($FromAddress)
00637         {
00638             # prepend "From" address onto message
00639             $AdditionalHeaders .= "\r\nFrom: ".$FromAddress;
00640         }
00641 
00642         # send out mail message
00643         $Result = mail(is_null($ToAddress)?$this->Get("EMail"):$ToAddress,
00644                        $EMailSubject,
00645                        $EMailBody, $AdditionalHeaders);
00646 
00647         # report result of mailing attempt to caller
00648         $this->Status = ($Result == TRUE) ? U_OKAY : U_MAILINGERROR;
00649         return ($this->Status == U_OKAY);
00650     }
00651 
00652 
00653     # ---- Privilege Functions -----------------------------------------------
00654 
00655     function HasPriv($Privilege, $Privilege2 = NULL, $Privilege3 = NULL,
00656             $Privilege4 = NULL, $Privilege5 = NULL, $Privilege6 = NULL)
00657     {
00658         # make sure a user is logged in (no privileges if not logged in)
00659         if ($this->IsLoggedIn() == FALSE) {  return FALSE;  }
00660 
00661         # build database query to check privileges
00662         $Query = "SELECT COUNT(*) AS PrivCount FROM APUserPrivileges "
00663                         ."WHERE UserId='".$this->UserId."'"
00664                             ." AND (Privilege='".$Privilege."'";
00665         if ($Privilege2 != NULL)
00666                 { $Query .= " OR Privilege='".$Privilege2."'";  }
00667         if ($Privilege3 != NULL)
00668                 {  $Query .= " OR Privilege='".$Privilege3."'";  }
00669         if ($Privilege4 != NULL)
00670                 {  $Query .= " OR Privilege='".$Privilege4."'";  }
00671         if ($Privilege5 != NULL)
00672                 {  $Query .= " OR Privilege='".$Privilege5."'";  }
00673         if ($Privilege6 != NULL)
00674                 {  $Query .= " OR Privilege='".$Privilege6."'";  }
00675         $Query .= ")";
00676 
00677         # look for privilege in database
00678         $PrivCount = $this->DB->Query($Query, "PrivCount");
00679 
00680         # return value to caller
00681         return ($PrivCount > 0) ? TRUE : FALSE;
00682     }
00683 
00684     function GrantPriv($Privilege)
00685     {
00686         # if privilege value is invalid
00687         if (intval($Privilege) != trim($Privilege))
00688         {
00689             # set code to indicate error
00690             $this->Result = U_ERROR;
00691         }
00692         else
00693         {
00694             # if user does not already have privilege
00695             $PrivCount = $this->DB->Query("SELECT COUNT(*) AS PrivCount"
00696                     ." FROM APUserPrivileges"
00697                     ." WHERE UserId='".$this->UserId."'"
00698                     ." AND Privilege='".$Privilege."'",
00699                     "PrivCount");
00700             if ($PrivCount == 0)
00701             {
00702                 # add privilege for this user to database
00703                 $this->DB->Query("INSERT INTO APUserPrivileges"
00704                         ." (UserId, Privilege) VALUES"
00705                         ." ('".$this->UserId."', ".$Privilege.")");
00706             }
00707 
00708             # set code to indicate success
00709             $this->Result = U_OKAY;
00710         }
00711 
00712         # report result to caller
00713         return $this->Result;
00714     }
00715 
00716     function RevokePriv($Privilege)
00717     {
00718         # remove privilege from database (if present)
00719         $this->DB->Query("DELETE FROM APUserPrivileges"
00720                          ." WHERE UserId = '".$this->UserId."'"
00721                          ." AND Privilege = '".$Privilege."'");
00722 
00723         # report success to caller
00724         $this->Result = U_OKAY;
00725         return $this->Result;
00726     }
00727 
00728     function GetPrivList()
00729     {
00730         # read privileges from database and return array to caller
00731         $this->DB->Query("SELECT Privilege FROM APUserPrivileges"
00732                 ." WHERE UserId='".$this->UserId."'");
00733         return $this->DB->FetchColumn("Privilege");
00734     }
00735 
00736     function SetPrivList($NewPrivileges)
00737     {
00738         # clear old priv list values
00739         $this->DB->Query("DELETE FROM APUserPrivileges"
00740                 ." WHERE UserId='".$this->UserId."'");
00741 
00742         # for each priv value passed in
00743         foreach ($NewPrivileges as $Privilege)
00744         {
00745             # set priv for user
00746             $this->GrantPriv($Privilege);
00747         }
00748     }
00749 
00750 
00751     # ---- Miscellaneous Functions -------------------------------------------
00752 
00753     # get unique alphanumeric code for user
00754     function GetUniqueCode($SeedString, $CodeLength)
00755     {
00756         return substr(strtoupper(md5(
00757                 $this->Get("UserName").$this->Get("UserPassword").$SeedString)),
00758                 0, $CodeLength);
00759     }
00760 
00761 
00762     # ---- PRIVATE INTERFACE -------------------------------------------------
00763 
00764     var $DB;        # handle to SQL database we use to store user information
00765     var $Session;   # session to use in storing persistent information
00766     var $UserId;    # user ID number for reference into database
00767     var $Result;    # result of last operation
00768     var $LoggedIn;  # flag indicating whether user is logged in
00769     var $DBFields;  # used for caching user values
00770 
00771     # check whether a user name is valid  (alphanumeric string of 2-24 chars)
00772     function IsValidUserName($UserName)
00773     {
00774         if (preg_match("/^[a-zA-Z0-9]{2,24}$/", $UserName)) {  return TRUE;  } else {  return FALSE;  }
00775     }
00776 
00777     # check whether a password is valid  (at least 6 characters)
00778     function IsValidPassword($Password)
00779     {
00780         if (strlen(User::NormalizePassword($Password)) < 6)
00781                 {  return FALSE;  } else {  return TRUE;  }
00782     }
00783 
00784     # check whether an e-mail address looks valid
00785     function IsValidLookingEMailAddress($EMail)
00786     {
00787         if (preg_match("/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/", $EMail)) {  return TRUE;  } else {  return FALSE;  }
00788     }
00789 
00790     # get normalized version of e-mail address
00791     # (may be called statically)
00792     function NormalizeEMailAddress($EMailAddress)
00793     {
00794         return strtolower(trim($EMailAddress));
00795     }
00796 
00797     # get normalized version of user name
00798     # (may be called statically)
00799     function NormalizeUserName($UserName)
00800     {
00801         return trim($UserName);
00802     }
00803 
00804     # get normalized version of password
00805     # (may be called statically)
00806     function NormalizePassword($Password)
00807     {
00808         return trim($Password);
00809     }
00810 
00811     # generate random password
00812     # generate random password
00813     function GetRandomPassword($PasswordMinLength = 6, $PasswordMaxLength = 8)
00814     {
00815         # seed random number generator
00816         mt_srand((double)microtime() * 1000000);
00817 
00818         # generate password of requested length
00819         return sprintf("%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
00820                 (pow(10, $PasswordMaxLength) - 1)));
00821     }
00822 
00823     # convenience function to supply parameters to Database->UpdateValue()
00824     function UpdateValue($FieldName, $NewValue = DB_NOVALUE)
00825     {
00826         return $this->DB->UpdateValue("APUsers", $FieldName, $NewValue,
00827                 "UserId = '".$this->UserId."'", $this->DBFields);
00828     }
00829 
00830     # methods for backward compatibility with earlier versions of User
00831     function GivePriv($Privilege) {  $this->GrantPriv($Privilege);  }
00832 };
00833 
00834 
00835 ?>