Search:

CWIS Developers Documentation

  • Main Page
  • Classes
  • Files
  • File List
  • File Members

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(self::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(self::NormalizeUserName($UserName))."'");
00345 
00346         if ($this->DB->NumRowsSelected() < 1)
00347         {
00348             # result is no user by that name, generate a fake salt
00349             # to discourage user enumeration. Make it be an old-format
00350             # crypt() salt so that it's harder.
00351             $SaltString = $_SERVER["SERVER_ADDR"].$UserName;
00352             $Result = substr(base64_encode(md5($SaltString)),0,2);
00353         }
00354         else
00355         {
00356             # grab password from DB
00357             # Assumes that we used php's crypt() for the passowrd
00358             # management stuff, and will need to be changed if we
00359             # go to something else.
00360             $Record = $this->DB->FetchRow();
00361             $StoredPassword = $Record["UserPassword"];
00362 
00363             if (substr($StoredPassword,0,3)==="$1$")
00364             {
00365                 $Result = substr($StoredPassword, 0,12);
00366             }
00367             else
00368             {
00369                 $Result = substr($StoredPassword, 0,2);
00370             }
00371         }
00372 
00373         return $Result;
00374     }
00375 
00376     # report whether this user is or is not currently logged in
00377     function IsLoggedIn() {  return $this->LoggedIn;  }
00378     function IsNotLoggedIn() {  return !$this->LoggedIn;  }
00379 
00380 
00381     # ---- Password Functions ------------------------------------------------
00382 
00383     # set new password (with checks against old password)
00384     function ChangePassword($OldPassword, $NewPassword, $NewPasswordAgain)
00385     {
00386         # if we are part of a session make sure a user is logged in
00387         if (isset($this->Session) && ($this->IsLoggedIn() == FALSE))
00388         {
00389             $this->Result = U_NOTLOGGEDIN;
00390             return $this->Result;
00391         }
00392 
00393         # if old password is not correct
00394         $StoredPassword = $this->DB->Query("SELECT UserPassword FROM APUsers"
00395                 ." WHERE UserId='".$this->UserId."'", "UserPassword");
00396         $EncryptedPassword = crypt($OldPassword, $StoredPassword);
00397         if ($EncryptedPassword != $StoredPassword)
00398         {
00399             # set status to indicate error
00400             $this->Result = U_BADPASSWORD;
00401         }
00402         # else if new password is not legal
00403         elseif (!$this->IsValidPassword($NewPassword))
00404         {
00405             # set status to indicate error
00406             $this->Result = U_ILLEGALPASSWORD;
00407         }
00408         # else if both instances of new password do not match
00409         elseif (self::NormalizePassword($NewPassword)
00410                 != self::NormalizePassword($NewPasswordAgain))
00411         {
00412             # set status to indicate error
00413             $this->Result = U_PASSWORDSDONTMATCH;
00414         }
00415         else
00416         {
00417             # set new password
00418             $this->SetPassword($NewPassword);
00419 
00420             # set status to indicate password successfully changed
00421             $this->Result = U_OKAY;
00422         }
00423 
00424         # report to caller that everything succeeded
00425         return $this->Result;
00426     }
00427 
00428     # set new password
00429     function SetPassword($NewPassword)
00430     {
00431         # generate encrypted password
00432         $EncryptedPassword = crypt(self::NormalizePassword($NewPassword));
00433 
00434         # save encrypted password
00435         $this->UpdateValue("UserPassword", $EncryptedPassword);
00436     }
00437 
00438     function CreateNewUserWithEMailedPassword(
00439             $UserName, $EMail, $EMailAgain,
00440             $TemplateFile = "Axis--User--EMailTemplate.txt")
00441     {
00442         return CreateNewUserAndMailPasswordFromFile(
00443                 $UserName, $EMail, $EMailAgain, $TemplateFile);
00444     }
00445 
00446     function CreateNewUserAndMailPasswordFromFile(
00447             $UserName, $EMail, $EMailAgain,
00448             $TemplateFile = "Axis--User--EMailTemplate.txt")
00449     {
00450         # load e-mail template from file (first line is subject)
00451         $Template = file($TemplateFile, 1);
00452         $EMailSubject = array_shift($Template);
00453         $EMailBody = join("", $Template);
00454 
00455         return CreateNewUserAndMailPassword(
00456                 $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
00457     }
00458 
00459     function CreateNewUserAndMailPassword(
00460             $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
00461     {
00462         # make sure e-mail addresses match
00463         if ($EMail != $EMailAgain)
00464         {
00465             $this->Result = U_EMAILSDONTMATCH;
00466             return $this->Result;
00467         }
00468 
00469         # make sure e-mail address looks valid
00470         if ($this->IsValidLookingEMailAddress($EMail) == FALSE)
00471         {
00472             $this->Result = U_ILLEGALEMAIL;
00473             return $this->Result;
00474         }
00475 
00476         # generate random password
00477         $Password = $this->GetRandomPassword();
00478 
00479         # attempt to create new user with password
00480         $Result = $this->CreateNewUser($UserName, $Password, $Password);
00481 
00482         # if user creation failed
00483         if ($Result != U_OKAY)
00484         {
00485             # report error result to caller
00486             return $Result;
00487         }
00488         # else
00489         else
00490         {
00491             # set e-mail address in user record
00492             $this->Set("EMail", $EMail);
00493 
00494             # plug appropriate values into subject and body of e-mail message
00495             $EMailSubject = str_replace("X-USERNAME-X", $UserName, $EMailSubject);
00496             $EMailBody = str_replace("X-USERNAME-X", $UserName, $EMailBody);
00497             $EMailBody = str_replace("X-PASSWORD-X", $Password, $EMailBody);
00498 
00499             # send out e-mail message with new account info
00500             $Result = mail($EMail, $EMailSubject, $EMailBody,
00501                 "Auto-Submitted: auto-generated");
00502 
00503             # if mailing attempt failed
00504             if ($Result != TRUE)
00505             {
00506                 # report error to caller
00507                 $this->Result = U_MAILINGERROR;
00508                 return $this->Result;
00509             }
00510             # else
00511             else
00512             {
00513                 # report success to caller
00514                 $this->Result = U_OKAY;
00515                 return $this->Result;
00516             }
00517         }
00518     }
00519 
00520     # get code for user to submit to confirm registration
00521     function GetActivationCode()
00522     {
00523         # code is MD5 sum based on user name and encrypted password
00524         $ActivationCodeLength = 6;
00525         return $this->GetUniqueCode("Activation", $ActivationCodeLength);
00526     }
00527 
00528     # check whether confirmation code is valid
00529     function IsActivationCodeGood($Code)
00530     {
00531         return (strtoupper(trim($Code)) == $this->GetActivationCode())
00532                 ? TRUE : FALSE;
00533     }
00534 
00535     # get/set whether user registration has been confirmed
00536     function IsActivated($NewValue = DB_NOVALUE)
00537     {
00538         return $this->UpdateValue("RegistrationConfirmed", $NewValue);
00539     }
00540 
00541     # get code for user to submit to confirm password reset
00542     function GetResetCode()
00543     {
00544         # code is MD5 sum based on user name and encrypted password
00545         $ResetCodeLength = 10;
00546         return $this->GetUniqueCode("Reset", $ResetCodeLength);
00547     }
00548 
00549     # check whether password reset code is valid
00550     function IsResetCodeGood($Code)
00551     {
00552         return (strtoupper(trim($Code)) == $this->GetResetCode())
00553                 ? TRUE : FALSE;
00554     }
00555 
00556     # get code for user to submit to confirm mail change request
00557     function GetMailChangeCode()
00558     {
00559       $ResetCodeLength = 10;
00560 
00561       return $this->GetUniqueCode("MailChange".$this->Get("EMail").$this->Get("NewEMail"),
00562                                   $ResetCodeLength);
00563     }
00564 
00565     function IsMailChangeCodeGood($Code)
00566     {
00567       return (strtoupper(trim($Code)) == $this->GetMailChangeCode())
00568         ? TRUE : FALSE;
00569     }
00570 
00571     # send e-mail to user (returns TRUE on success)
00572     function SendEMail(
00573                   $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
00574                   $ToAddress = NULL)
00575     {
00576         # if template is file name
00577         if (@is_file($TemplateTextOrFileName))
00578         {
00579             # load in template from file
00580             $Template = file($TemplateTextOrFileName, 1);
00581 
00582             # report error to caller if template load failed
00583             if ($Template == FALSE)
00584             {
00585                 $this->Status = U_TEMPLATENOTFOUND;
00586                 return $this->Status;
00587             }
00588 
00589             # join into one text block
00590             $TemplateTextOrFileName = join("", $Template);
00591         }
00592 
00593         # split template into lines
00594         $Template = explode("\n", $TemplateTextOrFileName);
00595 
00596         # strip any comments out of template
00597         $FilteredTemplate = array();
00598         foreach ($Template as $Line)
00599         {
00600             if (!preg_match("/^[\\s]*#/", $Line))
00601             {
00602                 $FilteredTemplate[] = $Line;
00603             }
00604         }
00605 
00606         # split subject line out of template (first non-comment line in file)
00607         $EMailSubject = array_shift($FilteredTemplate);
00608         $EMailBody = join("\n", $FilteredTemplate);
00609 
00610         # set up our substitutions
00611         $Substitutions = array(
00612                 "X-USERNAME-X" => $this->Get("UserName"),
00613                 "X-EMAILADDRESS-X" =>  $this->Get("EMail"),
00614                 "X-ACTIVATIONCODE-X" => $this->GetActivationCode(),
00615                 "X-RESETCODE-X" => $this->GetResetCode(),
00616                 "X-CHANGECODE-X" => $this->GetMailChangeCode(),
00617                 "X-IPADDRESS-X" => @$_SERVER["REMOTE_ADDR"],
00618                 );
00619 
00620         # if caller provided additional substitutions
00621         if (is_array($MoreSubstitutions))
00622         {
00623             # add in entries from caller to substitution list
00624             $Substitutions = array_merge(
00625                     $Substitutions, $MoreSubstitutions);
00626         }
00627 
00628         # perform substitutions on subject and body of message
00629         $EMailSubject = str_replace(array_keys($Substitutions),
00630                 array_values($Substitutions), $EMailSubject);
00631         $EMailBody = str_replace(array_keys($Substitutions),
00632                 array_values($Substitutions), $EMailBody);
00633 
00634         $AdditionalHeaders = "Auto-Submitted: auto-generated";
00635 
00636         # if caller provided "From" address
00637         if ($FromAddress)
00638         {
00639             # prepend "From" address onto message
00640             $AdditionalHeaders .= "\r\nFrom: ".$FromAddress;
00641         }
00642 
00643         # send out mail message
00644         $Result = mail(is_null($ToAddress)?$this->Get("EMail"):$ToAddress,
00645                        $EMailSubject,
00646                        $EMailBody, $AdditionalHeaders);
00647 
00648         # report result of mailing attempt to caller
00649         $this->Status = ($Result == TRUE) ? U_OKAY : U_MAILINGERROR;
00650         return ($this->Status == U_OKAY);
00651     }
00652 
00653 
00654     # ---- Privilege Functions -----------------------------------------------
00655 
00656     function HasPriv($Privilege, $Privilege2 = NULL, $Privilege3 = NULL,
00657             $Privilege4 = NULL, $Privilege5 = NULL, $Privilege6 = NULL)
00658     {
00659         # make sure a user is logged in (no privileges if not logged in)
00660         if ($this->IsLoggedIn() == FALSE) {  return FALSE;  }
00661 
00662         # build database query to check privileges
00663         $Query = "SELECT COUNT(*) AS PrivCount FROM APUserPrivileges "
00664                         ."WHERE UserId='".$this->UserId."'"
00665                             ." AND (Privilege='".$Privilege."'";
00666         if ($Privilege2 != NULL)
00667                 { $Query .= " OR Privilege='".$Privilege2."'";  }
00668         if ($Privilege3 != NULL)
00669                 {  $Query .= " OR Privilege='".$Privilege3."'";  }
00670         if ($Privilege4 != NULL)
00671                 {  $Query .= " OR Privilege='".$Privilege4."'";  }
00672         if ($Privilege5 != NULL)
00673                 {  $Query .= " OR Privilege='".$Privilege5."'";  }
00674         if ($Privilege6 != NULL)
00675                 {  $Query .= " OR Privilege='".$Privilege6."'";  }
00676         $Query .= ")";
00677 
00678         # look for privilege in database
00679         $PrivCount = $this->DB->Query($Query, "PrivCount");
00680 
00681         # return value to caller
00682         return ($PrivCount > 0) ? TRUE : FALSE;
00683     }
00684 
00685     function GrantPriv($Privilege)
00686     {
00687         # if privilege value is invalid
00688         if (intval($Privilege) != trim($Privilege))
00689         {
00690             # set code to indicate error
00691             $this->Result = U_ERROR;
00692         }
00693         else
00694         {
00695             # if user does not already have privilege
00696             $PrivCount = $this->DB->Query("SELECT COUNT(*) AS PrivCount"
00697                     ." FROM APUserPrivileges"
00698                     ." WHERE UserId='".$this->UserId."'"
00699                     ." AND Privilege='".$Privilege."'",
00700                     "PrivCount");
00701             if ($PrivCount == 0)
00702             {
00703                 # add privilege for this user to database
00704                 $this->DB->Query("INSERT INTO APUserPrivileges"
00705                         ." (UserId, Privilege) VALUES"
00706                         ." ('".$this->UserId."', ".$Privilege.")");
00707             }
00708 
00709             # set code to indicate success
00710             $this->Result = U_OKAY;
00711         }
00712 
00713         # report result to caller
00714         return $this->Result;
00715     }
00716 
00717     function RevokePriv($Privilege)
00718     {
00719         # remove privilege from database (if present)
00720         $this->DB->Query("DELETE FROM APUserPrivileges"
00721                          ." WHERE UserId = '".$this->UserId."'"
00722                          ." AND Privilege = '".$Privilege."'");
00723 
00724         # report success to caller
00725         $this->Result = U_OKAY;
00726         return $this->Result;
00727     }
00728 
00729     function GetPrivList()
00730     {
00731         # read privileges from database and return array to caller
00732         $this->DB->Query("SELECT Privilege FROM APUserPrivileges"
00733                 ." WHERE UserId='".$this->UserId."'");
00734         return $this->DB->FetchColumn("Privilege");
00735     }
00736 
00737     function SetPrivList($NewPrivileges)
00738     {
00739         # clear old priv list values
00740         $this->DB->Query("DELETE FROM APUserPrivileges"
00741                 ." WHERE UserId='".$this->UserId."'");
00742 
00743         # for each priv value passed in
00744         foreach ($NewPrivileges as $Privilege)
00745         {
00746             # set priv for user
00747             $this->GrantPriv($Privilege);
00748         }
00749     }
00750 
00751 
00752     # ---- Miscellaneous Functions -------------------------------------------
00753 
00754     # get unique alphanumeric code for user
00755     function GetUniqueCode($SeedString, $CodeLength)
00756     {
00757         return substr(strtoupper(md5(
00758                 $this->Get("UserName").$this->Get("UserPassword").$SeedString)),
00759                 0, $CodeLength);
00760     }
00761 
00762 
00763     # ---- PRIVATE INTERFACE -------------------------------------------------
00764 
00765     var $DB;        # handle to SQL database we use to store user information
00766     var $Session;   # session to use in storing persistent information
00767     var $UserId;    # user ID number for reference into database
00768     var $Result;    # result of last operation
00769     var $LoggedIn;  # flag indicating whether user is logged in
00770     var $DBFields;  # used for caching user values
00771 
00772     # check whether a user name is valid  (alphanumeric string of 2-24 chars)
00773     static function IsValidUserName($UserName)
00774     {
00775         if (preg_match("/^[a-zA-Z0-9]{2,24}$/", $UserName)) {  return TRUE;  } else {  return FALSE;  }
00776     }
00777 
00778     # check whether a password is valid  (at least 6 characters)
00779     static function IsValidPassword($Password)
00780     {
00781         if (strlen(self::NormalizePassword($Password)) < 6)
00782                 {  return FALSE;  } else {  return TRUE;  }
00783     }
00784 
00785     # check whether an e-mail address looks valid
00786     static function IsValidLookingEMailAddress($EMail)
00787     {
00788         if (preg_match("/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/", $EMail)) {  return TRUE;  } else {  return FALSE;  }
00789     }
00790 
00791     # get normalized version of e-mail address
00792     static function NormalizeEMailAddress($EMailAddress)
00793     {
00794         return strtolower(trim($EMailAddress));
00795     }
00796 
00797     # get normalized version of user name
00798     static function NormalizeUserName($UserName)
00799     {
00800         return trim($UserName);
00801     }
00802 
00803     # get normalized version of password
00804     static function NormalizePassword($Password)
00805     {
00806         return trim($Password);
00807     }
00808 
00809     # generate random password
00810     function GetRandomPassword($PasswordMinLength = 6, $PasswordMaxLength = 8)
00811     {
00812         # seed random number generator
00813         mt_srand((double)microtime() * 1000000);
00814 
00815         # generate password of requested length
00816         return sprintf("%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
00817                 (pow(10, $PasswordMaxLength) - 1)));
00818     }
00819 
00820     # convenience function to supply parameters to Database->UpdateValue()
00821     function UpdateValue($FieldName, $NewValue = DB_NOVALUE)
00822     {
00823         return $this->DB->UpdateValue("APUsers", $FieldName, $NewValue,
00824                 "UserId = '".$this->UserId."'", $this->DBFields);
00825     }
00826 
00827     # methods for backward compatibility with earlier versions of User
00828     function GivePriv($Privilege) {  $this->GrantPriv($Privilege);  }
00829 
00830 }

CWIS logo doxygen
Copyright 2010 Internet Scout