CWIS Developer Documentation
Axis--User.php
Go to the documentation of this file.
1 <?PHP
2 
3 #
4 # Axis--User.php
5 # An Object for Handling User Information
6 #
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).
11 #
12 # Author: Edward Almasy (almasy@axisdata.com)
13 #
14 # Part of the AxisPHP library v1.2.4
15 # For more information see http://www.axisdata.com/AxisPHP/
16 #
17 
18 # status values (error codes)
19 define("U_OKAY", 0);
20 define("U_ERROR", 1);
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);
40 define("U_NOTACTIVATED", 21);
41 
42 
43 class User {
44 
45  # ---- PUBLIC INTERFACE --------------------------------------------------
46 
47  function User($UserInfoOne = NULL, $UserInfoTwo = NULL)
48  {
49  # assume constructor will succeed and user is not logged in
50  $this->Result = U_OKAY;
51  $this->LoggedIn = FALSE;
52 
53  # create database connection
54  $this->DB = new Database();
55 
56  # if user info passed in
57  if (is_int($UserInfoOne) || is_string($UserInfoOne)
58  || is_int($UserInfoTwo) || is_string($UserInfoTwo))
59  {
60  # if user ID was passed in
61  if (is_int($UserInfoOne) || is_int($UserInfoTwo))
62  {
63  # save user ID
64  $this->UserId = is_int($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
65 
66  # get whether the user is logged in
67  $this->LoggedIn = (bool) $this->DB->Query("
68  SELECT LoggedIn FROM APUsers
69  WHERE UserId='".addslashes($this->UserId)."'",
70  "LoggedIn");
71  }
72  else
73  {
74  # look up user ID in database
75  $UserInfoTwo = is_string($UserInfoOne) ? $UserInfoOne : $UserInfoTwo;
76  $this->DB->Query("SELECT UserId, LoggedIn FROM APUsers"
77  ." WHERE UserName='".addslashes($UserInfoTwo)."'");
78  $Record = $this->DB->FetchRow();
79  if ($Record)
80  {
81  $this->UserId = $Record["UserId"];
82  $this->LoggedIn = $Record["LoggedIn"];
83  }
84 
85  # if user ID was not found
86  if ($Record === FALSE)
87  {
88  # if name looks like it could actually be a user ID
89  if (preg_match("/^[-]*[0-9]+$/", $UserInfoTwo))
90  {
91  # assume name was user ID
92  $this->UserId = intval($UserInfoTwo);
93  }
94  else
95  {
96  # set code indicating no user found
97  $this->Result = U_NOSUCHUSER;
98  unset($this->UserId);
99  }
100  }
101  }
102  }
103  else
104  {
105  # if user ID is available from session
106  if (isset($_SESSION["APUserId"]))
107  {
108  # save user ID
109  $this->UserId = $_SESSION["APUserId"];
110 
111  # set flag indicating user is currently logged in
112  $this->LoggedIn = TRUE;
113  }
114  }
115  }
116 
117  function Status()
118  {
119  return $this->Result;
120  }
121 
122  # return text message corresponding to current (or specified) status code
123  function StatusMessage($StatusCode = NULL)
124  {
125  $APUserStatusMessages = array(
126  U_OKAY => "The operation was successful.",
127  U_ERROR => "There has been an error.",
128  U_BADPASSWORD => "The password you entered was"
129  ." incorrect.",
130  U_NOSUCHUSER => "No such user name was found.",
131  U_PASSWORDSDONTMATCH => "The new passwords you entered do"
132  ." not match.",
133  U_EMAILSDONTMATCH => "The e-mail addresses you entered"
134  ." do not match.",
135  U_DUPLICATEUSERNAME => "The user name you requested is"
136  ." already in use.",
137  U_ILLEGALUSERNAME => "The user name you requested is too"
138  ." short, too long, or contains"
139  ." illegal characters.",
140  U_ILLEGALPASSWORD => "The new password you requested is"
141  ." too short, too long, or"
142  ." contains illegal characters.",
143  U_ILLEGALEMAIL => "The e-mail address you entered"
144  ." appears to be invalid.",
145  U_NOTLOGGEDIN => "The user is not logged in.",
146  U_MAILINGERROR => "An error occurred while attempting"
147  ." to send e-mail. Please notify"
148  ." the system administrator.",
149  U_TEMPLATENOTFOUND => "An error occurred while attempting"
150  ." to generate e-mail. Please"
151  ." notify the system administrator.",
152  U_DUPLICATEEMAIL => "The e-mail address you supplied already"
153  ." has an account associated with it.",
154  );
155 
156  return ($StatusCode === NULL) ? $APUserStatusMessages[$this->Result]
157  : $APUserStatusMessages[$StatusCode];
158  }
159 
160  function Delete()
161  {
162  # clear priv list values
163  $this->DB->Query("DELETE FROM APUserPrivileges WHERE UserId = '".$this->UserId."'");
164 
165  # delete user record from database
166  $this->DB->Query("DELETE FROM APUsers WHERE UserId = '".$this->UserId."'");
167 
168  # report to caller that everything succeeded
169  $this->Result = U_OKAY;
170  return $this->Result;
171  }
172 
178  static function SetEmailFunction($NewValue)
179  {
180  if (is_callable($NewValue))
181  {
182  self::$EmailFunc = $NewValue;
183  }
184  }
185 
186 
187  # ---- Getting/Setting Values --------------------------------------------
188 
189  function Id()
190  {
191  return $this->UserId;
192  }
193  function Name()
194  {
195  return $this->Get("UserName");
196  }
197 
203  public function GetBestName()
204  {
205  $RealName = $this->Get("RealName");
206 
207  # the real name is available, so use it
208  if (strlen(trim($RealName)))
209  {
210  return $RealName;
211  }
212 
213  # the real name isn't available, so use the user name
214  return $this->Get("UserName");
215  }
216 
217  function LastLocation($NewLocation = NULL)
218  {
219  # return NULL if not associated with a particular user
220  if ($this->UserId === NULL) { return NULL; }
221 
222  if ($NewLocation)
223  {
224  $this->DB->Query("UPDATE APUsers SET"
225  ." LastLocation = '".addslashes($NewLocation)."',"
226  ." LastActiveDate = NOW(),"
227  ." LastIPAddress = '".$_SERVER["REMOTE_ADDR"]."'"
228  ." WHERE UserId = '".addslashes($this->UserId)."'");
229  if (isset($this->DBFields))
230  {
231  $this->DBFields["LastLocation"] = $NewLocation;
232  $this->DBFields["LastActiveDate"] = date("Y-m-d H:i:s");
233  }
234  }
235  return $this->Get("LastLocation");
236  }
237  function LastActiveDate()
238  {
239  return $this->Get("LastActiveDate");
240  }
241  function LastIPAddress()
242  {
243  return $this->Get("LastIPAddress");
244  }
245 
246  # get value from specified field
247  function Get($FieldName)
248  {
249  # return NULL if not associated with a particular user
250  if ($this->UserId === NULL) { return NULL; }
251 
252  return $this->UpdateValue($FieldName);
253  }
254 
255  # get value (formatted as a date) from specified field
256  function GetDate($FieldName, $Format = "")
257  {
258  # return NULL if not associated with a particular user
259  if ($this->UserId === NULL) { return NULL; }
260 
261  # retrieve specified value from database
262  if (strlen($Format) > 0)
263  {
264  $this->DB->Query("SELECT DATE_FORMAT(`".addslashes($FieldName)."`, '".addslashes($Format)."') AS `".addslashes($FieldName)."` FROM APUsers WHERE UserId='".$this->UserId."'");
265  }
266  else
267  {
268  $this->DB->Query("SELECT `".addslashes($FieldName)."` FROM APUsers WHERE UserId='".$this->UserId."'");
269  }
270  $Record = $this->DB->FetchRow();
271 
272  # return value to caller
273  return $Record[$FieldName];
274  }
275 
276  # set value in specified field
277  function Set($FieldName, $NewValue)
278  {
279  # return error if not associated with a particular user
280  if ($this->UserId === NULL) { return U_NOTLOGGEDIN; }
281 
282  $this->UpdateValue($FieldName, $NewValue);
283  $this->Result = U_OKAY;
284  return $this->Result;
285  }
286 
287 
288  # ---- Login Functions ---------------------------------------------------
289 
290  function Login($UserName, $Password, $IgnorePassword = FALSE)
291  {
292  # if user not found in DB
293  $this->DB->Query("SELECT * FROM APUsers"
294  ." WHERE UserName = '"
295  .addslashes(self::NormalizeUserName($UserName))."'");
296  if ($this->DB->NumRowsSelected() < 1)
297  {
298  # result is no user by that name
299  $this->Result = U_NOSUCHUSER;
300  }
301  else
302  {
303  # if user account not yet activated
304  $Record = $this->DB->FetchRow();
305  if (!$Record["RegistrationConfirmed"])
306  {
307  # result is user registration not confirmed
308  $this->Result = U_NOTACTIVATED;
309  }
310  else
311  {
312  # grab password from DB
313  $StoredPassword = $Record["UserPassword"];
314 
315  if (isset($Password[0]) && $Password[0] == " ")
316  {
317  $Challenge = md5(date("Ymd").$_SERVER["REMOTE_ADDR"]);
318  $StoredPassword = md5( $Challenge . $StoredPassword );
319 
320  $EncryptedPassword = trim($Password);
321  }
322  else
323  {
324  # if supplied password matches encrypted password
325  $EncryptedPassword = crypt($Password, $StoredPassword);
326  }
327 
328  if (($EncryptedPassword == $StoredPassword) || $IgnorePassword)
329  {
330  # result is success
331  $this->Result = U_OKAY;
332 
333  # store user ID for session
334  $this->UserId = $Record["UserId"];
335  $_SESSION["APUserId"] = $this->UserId;
336 
337  # update last login date
338  $this->DB->Query("UPDATE APUsers SET LastLoginDate = NOW(),"
339  ." LoggedIn = '1'"
340  ." WHERE UserId = '".$this->UserId."'");
341 
342  # Check for old format hashes, and rehash if possible
343  if ($EncryptedPassword === $StoredPassword &&
344  substr($StoredPassword,0,3) !== "$1$" &&
345  $Password[0] !== " " &&
346  CRYPT_MD5 )
347  {
348  $NewPassword = crypt($Password);
349  $this->DB->Query(
350  "UPDATE APUsers SET UserPassword='".addslashes($NewPassword)."' "
351  ."WHERE UserId='".$this->UserId."'");
352  }
353 
354  # since self::DBFields might already have been set to false if
355  # the user wasn't logged in when this is called, populate it
356  # with user data so that a call to self::UpdateValue will be
357  # able to properly fetch the data associated with the user
358  $this->DBFields = $Record;
359 
360  # set flag to indicate we are logged in
361  $this->LoggedIn = TRUE;
362  }
363  else
364  {
365  # result is bad password
366  $this->Result = U_BADPASSWORD;
367  }
368  }
369  }
370 
371  # return result to caller
372  return $this->Result;
373  }
374 
375  # log this user out
376  function Logout()
377  {
378  # clear user ID (if any) for session
379  unset($_SESSION["APUserId"]);
380 
381  # if user is marked as logged in
382  if ($this->LoggedIn)
383  {
384  # set flag to indicate user is no longer logged in
385  $this->LoggedIn = FALSE;
386 
387  # clear login flag in database
388  $this->DB->Query(
389  "UPDATE APUsers SET LoggedIn = '0' "
390  ."WHERE UserId='".$this->UserId."'");
391  }
392  }
393 
394  function GetPasswordSalt($UserName)
395  {
396  $this->DB->Query(
397  "SELECT * FROM APUsers WHERE UserName = '"
398  .addslashes(self::NormalizeUserName($UserName))."'");
399 
400  if ($this->DB->NumRowsSelected() < 1)
401  {
402  # result is no user by that name, generate a fake salt
403  # to discourage user enumeration. Make it be an old-format
404  # crypt() salt so that it's harder.
405  $SaltString = $_SERVER["SERVER_ADDR"].$UserName;
406  $Result = substr(base64_encode(md5($SaltString)),0,2);
407  }
408  else
409  {
410  # grab password from DB
411  # Assumes that we used php's crypt() for the passowrd
412  # management stuff, and will need to be changed if we
413  # go to something else.
414  $Record = $this->DB->FetchRow();
415  $StoredPassword = $Record["UserPassword"];
416 
417  if (substr($StoredPassword,0,3)==="$1$")
418  {
419  $Result = substr($StoredPassword, 0,12);
420  }
421  else
422  {
423  $Result = substr($StoredPassword, 0,2);
424  }
425  }
426 
427  return $Result;
428  }
429 
430  # report whether this user is or is not currently logged in
431  function IsLoggedIn() { return $this->LoggedIn; }
432  function IsNotLoggedIn() { return !$this->LoggedIn; }
433 
434 
435  # ---- Password Functions ------------------------------------------------
436 
437  # set new password (with checks against old password)
438  function ChangePassword($OldPassword, $NewPassword, $NewPasswordAgain)
439  {
440  # return error if not associated with a particular user
441  if ($this->UserId === NULL) { return U_NOTLOGGEDIN; }
442 
443  # if old password is not correct
444  $StoredPassword = $this->DB->Query("SELECT UserPassword FROM APUsers"
445  ." WHERE UserId='".$this->UserId."'", "UserPassword");
446  $EncryptedPassword = crypt($OldPassword, $StoredPassword);
447  if ($EncryptedPassword != $StoredPassword)
448  {
449  # set status to indicate error
450  $this->Result = U_BADPASSWORD;
451  }
452  # else if new password is not legal
453  elseif (!$this->IsValidPassword($NewPassword))
454  {
455  # set status to indicate error
456  $this->Result = U_ILLEGALPASSWORD;
457  }
458  # else if both instances of new password do not match
459  elseif (self::NormalizePassword($NewPassword)
460  != self::NormalizePassword($NewPasswordAgain))
461  {
462  # set status to indicate error
463  $this->Result = U_PASSWORDSDONTMATCH;
464  }
465  else
466  {
467  # set new password
468  $this->SetPassword($NewPassword);
469 
470  # set status to indicate password successfully changed
471  $this->Result = U_OKAY;
472  }
473 
474  # report to caller that everything succeeded
475  return $this->Result;
476  }
477 
478  # set new password
479  function SetPassword($NewPassword)
480  {
481  # generate encrypted password
482  $EncryptedPassword = crypt(self::NormalizePassword($NewPassword));
483 
484  # save encrypted password
485  $this->UpdateValue("UserPassword", $EncryptedPassword);
486  }
487 
489  $UserName, $EMail, $EMailAgain,
490  $TemplateFile = "Axis--User--EMailTemplate.txt")
491  {
493  $UserName, $EMail, $EMailAgain, $TemplateFile);
494  }
495 
497  $UserName, $EMail, $EMailAgain,
498  $TemplateFile = "Axis--User--EMailTemplate.txt")
499  {
500  # load e-mail template from file (first line is subject)
501  $Template = file($TemplateFile, 1);
502  $EMailSubject = array_shift($Template);
503  $EMailBody = join("", $Template);
504 
506  $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody);
507  }
508 
510  $UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
511  {
512  # make sure e-mail addresses match
513  if ($EMail != $EMailAgain)
514  {
515  $this->Result = U_EMAILSDONTMATCH;
516  return $this->Result;
517  }
518 
519  # make sure e-mail address looks valid
520  if ($this->IsValidLookingEMailAddress($EMail) == FALSE)
521  {
522  $this->Result = U_ILLEGALEMAIL;
523  return $this->Result;
524  }
525 
526  # generate random password
527  $Password = $this->GetRandomPassword();
528 
529  # attempt to create new user with password
530  $Result = $this->CreateNewUser($UserName, $Password, $Password);
531 
532  # if user creation failed
533  if ($Result != U_OKAY)
534  {
535  # report error result to caller
536  return $Result;
537  }
538  # else
539  else
540  {
541  # set e-mail address in user record
542  $this->Set("EMail", $EMail);
543 
544  # plug appropriate values into subject and body of e-mail message
545  $EMailSubject = str_replace("X-USERNAME-X", $UserName, $EMailSubject);
546  $EMailBody = str_replace("X-USERNAME-X", $UserName, $EMailBody);
547  $EMailBody = str_replace("X-PASSWORD-X", $Password, $EMailBody);
548 
549  # send out e-mail message with new account info
550  if (is_Callable(self::$EmailFunc))
551  {
552  $Result = call_user_func(self::$EmailFunc,
553  $EMail, $EMailSubject, $EMailBody,
554  "Auto-Submitted: auto-generated");
555  }
556  else
557  {
558  $Result = mail($EMail, $EMailSubject, $EMailBody,
559  "Auto-Submitted: auto-generated");
560  }
561 
562  # if mailing attempt failed
563  if ($Result != TRUE)
564  {
565  # report error to caller
566  $this->Result = U_MAILINGERROR;
567  return $this->Result;
568  }
569  # else
570  else
571  {
572  # report success to caller
573  $this->Result = U_OKAY;
574  return $this->Result;
575  }
576  }
577  }
578 
579  # get code for user to submit to confirm registration
580  function GetActivationCode()
581  {
582  # code is MD5 sum based on user name and encrypted password
583  $ActivationCodeLength = 6;
584  return $this->GetUniqueCode("Activation", $ActivationCodeLength);
585  }
586 
587  # check whether confirmation code is valid
588  function IsActivationCodeGood($Code)
589  {
590  return (strtoupper(trim($Code)) == $this->GetActivationCode())
591  ? TRUE : FALSE;
592  }
593 
594  # get/set whether user registration has been confirmed
595  function IsActivated($NewValue = DB_NOVALUE)
596  {
597  return $this->UpdateValue("RegistrationConfirmed", $NewValue);
598  }
599 
600  # get code for user to submit to confirm password reset
601  function GetResetCode()
602  {
603  # code is MD5 sum based on user name and encrypted password
604  $ResetCodeLength = 10;
605  return $this->GetUniqueCode("Reset", $ResetCodeLength);
606  }
607 
608  # check whether password reset code is valid
609  function IsResetCodeGood($Code)
610  {
611  return (strtoupper(trim($Code)) == $this->GetResetCode())
612  ? TRUE : FALSE;
613  }
614 
615  # get code for user to submit to confirm mail change request
616  function GetMailChangeCode()
617  {
618  $ResetCodeLength = 10;
619 
620  return $this->GetUniqueCode("MailChange".$this->Get("EMail").$this->Get("NewEMail"),
621  $ResetCodeLength);
622  }
623 
624  function IsMailChangeCodeGood($Code)
625  {
626  return (strtoupper(trim($Code)) == $this->GetMailChangeCode())
627  ? TRUE : FALSE;
628  }
629 
630  # send e-mail to user (returns TRUE on success)
631  function SendEMail(
632  $TemplateTextOrFileName, $FromAddress = NULL, $MoreSubstitutions = NULL,
633  $ToAddress = NULL)
634  {
635  # if template is file name
636  if (@is_file($TemplateTextOrFileName))
637  {
638  # load in template from file
639  $Template = file($TemplateTextOrFileName, 1);
640 
641  # report error to caller if template load failed
642  if ($Template == FALSE)
643  {
644  $this->Status = U_TEMPLATENOTFOUND;
645  return $this->Status;
646  }
647 
648  # join into one text block
649  $TemplateTextOrFileName = join("", $Template);
650  }
651 
652  # split template into lines
653  $Template = explode("\n", $TemplateTextOrFileName);
654 
655  # strip any comments out of template
656  $FilteredTemplate = array();
657  foreach ($Template as $Line)
658  {
659  if (!preg_match("/^[\\s]*#/", $Line))
660  {
661  $FilteredTemplate[] = $Line;
662  }
663  }
664 
665  # split subject line out of template (first non-comment line in file)
666  $EMailSubject = array_shift($FilteredTemplate);
667  $EMailBody = join("\n", $FilteredTemplate);
668 
669  # set up our substitutions
670  $Substitutions = array(
671  "X-USERNAME-X" => $this->Get("UserName"),
672  "X-EMAILADDRESS-X" => $this->Get("EMail"),
673  "X-ACTIVATIONCODE-X" => $this->GetActivationCode(),
674  "X-RESETCODE-X" => $this->GetResetCode(),
675  "X-CHANGECODE-X" => $this->GetMailChangeCode(),
676  "X-IPADDRESS-X" => @$_SERVER["REMOTE_ADDR"],
677  );
678 
679  # if caller provided additional substitutions
680  if (is_array($MoreSubstitutions))
681  {
682  # add in entries from caller to substitution list
683  $Substitutions = array_merge(
684  $Substitutions, $MoreSubstitutions);
685  }
686 
687  # perform substitutions on subject and body of message
688  $EMailSubject = str_replace(array_keys($Substitutions),
689  array_values($Substitutions), $EMailSubject);
690  $EMailBody = str_replace(array_keys($Substitutions),
691  array_values($Substitutions), $EMailBody);
692 
693  $AdditionalHeaders = "Auto-Submitted: auto-generated";
694 
695  # if caller provided "From" address
696  if ($FromAddress)
697  {
698  # prepend "From" address onto message
699  $AdditionalHeaders .= "\r\nFrom: ".$FromAddress;
700  }
701 
702  # send out mail message
703  if (is_Callable(self::$EmailFunc))
704  {
705  $Result = call_user_func(self::$EmailFunc,
706  is_null($ToAddress)?$this->Get("EMail"):$ToAddress,
707  $EMailSubject, $EMailBody, $AdditionalHeaders);
708  }
709  else
710  {
711  $Result = mail(is_null($ToAddress)?$this->Get("EMail"):$ToAddress,
712  $EMailSubject,
713  $EMailBody, $AdditionalHeaders);
714  }
715 
716  # report result of mailing attempt to caller
717  $this->Status = ($Result == TRUE) ? U_OKAY : U_MAILINGERROR;
718  return ($this->Status == U_OKAY);
719  }
720 
721 
722  # ---- Privilege Functions -----------------------------------------------
723 
732  function HasPriv($Privilege, $Privileges = NULL)
733  {
734  # return FALSE if not associated with a particular user
735  if ($this->UserId === NULL) { return FALSE; }
736 
737  # bail out if empty array of privileges passed in
738  if (is_array($Privilege) && !count($Privilege) && (func_num_args() < 2))
739  { return FALSE; }
740 
741  # set up beginning of database query
742  $Query = "SELECT COUNT(*) AS PrivCount FROM APUserPrivileges "
743  ."WHERE UserId='".$this->UserId."' AND (";
744 
745  # add first privilege(s) to query (first arg may be single value or array)
746  if (is_array($Privilege))
747  {
748  $Sep = "";
749  foreach ($Privilege as $Priv)
750  {
751  $Query .= $Sep."Privilege='".addslashes($Priv)."'";
752  $Sep = " OR ";
753  }
754  }
755  else
756  {
757  $Query .= "Privilege='".$Privilege."'";
758  $Sep = " OR ";
759  }
760 
761  # add any privileges from additional args to query
762  $Args = func_get_args();
763  array_shift($Args);
764  foreach ($Args as $Arg)
765  {
766  $Query .= $Sep."Privilege='".$Arg."'";
767  $Sep = " OR ";
768  }
769 
770  # close out query
771  $Query .= ")";
772 
773  # look for privilege in database
774  $PrivCount = $this->DB->Query($Query, "PrivCount");
775 
776  # return value to caller
777  return ($PrivCount > 0) ? TRUE : FALSE;
778  }
779 
788  static function GetSqlQueryForUsersWithPriv($Privilege, $Privileges = NULL)
789  {
790  # set up beginning of database query
791  $Query = "SELECT DISTINCT UserId FROM APUserPrivileges "
792  ."WHERE ";
793 
794  # add first privilege(s) to query (first arg may be single value or array)
795  if (is_array($Privilege))
796  {
797  $Sep = "";
798  foreach ($Privilege as $Priv)
799  {
800  $Query .= $Sep."Privilege='".addslashes($Priv)."'";
801  $Sep = " OR ";
802  }
803  }
804  else
805  {
806  $Query .= "Privilege='".$Privilege."'";
807  $Sep = " OR ";
808  }
809 
810  # add any privileges from additional args to query
811  $Args = func_get_args();
812  array_shift($Args);
813  foreach ($Args as $Arg)
814  {
815  $Query .= $Sep."Privilege='".$Arg."'";
816  $Sep = " OR ";
817  }
818 
819  # return query to caller
820  return $Query;
821  }
822 
831  static function GetSqlQueryForUsersWithoutPriv($Privilege, $Privileges = NULL)
832  {
833  # set up beginning of database query
834  $Query = "SELECT DISTINCT UserId FROM APUserPrivileges "
835  ."WHERE ";
836 
837  # add first privilege(s) to query (first arg may be single value or array)
838  if (is_array($Privilege))
839  {
840  $Sep = "";
841  foreach ($Privilege as $Priv)
842  {
843  $Query .= $Sep."Privilege != '".addslashes($Priv)."'";
844  $Sep = " AND ";
845  }
846  }
847  else
848  {
849  $Query .= "Privilege != '".$Privilege."'";
850  $Sep = " AND ";
851  }
852 
853  # add any privileges from additional args to query
854  $Args = func_get_args();
855  array_shift($Args);
856  foreach ($Args as $Arg)
857  {
858  $Query .= $Sep."Privilege != '".$Arg."'";
859  $Sep = " AND ";
860  }
861 
862  # return query to caller
863  return $Query;
864  }
865 
866  function GrantPriv($Privilege)
867  {
868  # return error if not associated with a particular user
869  if ($this->UserId === NULL) { return U_NOTLOGGEDIN; }
870 
871  # if privilege value is invalid
872  if (intval($Privilege) != trim($Privilege))
873  {
874  # set code to indicate error
875  $this->Result = U_ERROR;
876  }
877  else
878  {
879  # if user does not already have privilege
880  $PrivCount = $this->DB->Query("SELECT COUNT(*) AS PrivCount"
881  ." FROM APUserPrivileges"
882  ." WHERE UserId='".$this->UserId."'"
883  ." AND Privilege='".$Privilege."'",
884  "PrivCount");
885  if ($PrivCount == 0)
886  {
887  # add privilege for this user to database
888  $this->DB->Query("INSERT INTO APUserPrivileges"
889  ." (UserId, Privilege) VALUES"
890  ." ('".$this->UserId."', ".$Privilege.")");
891  }
892 
893  # set code to indicate success
894  $this->Result = U_OKAY;
895  }
896 
897  # report result to caller
898  return $this->Result;
899  }
900 
901  function RevokePriv($Privilege)
902  {
903  # return error if not associated with a particular user
904  if ($this->UserId === NULL) { return U_NOTLOGGEDIN; }
905 
906  # remove privilege from database (if present)
907  $this->DB->Query("DELETE FROM APUserPrivileges"
908  ." WHERE UserId = '".$this->UserId."'"
909  ." AND Privilege = '".$Privilege."'");
910 
911  # report success to caller
912  $this->Result = U_OKAY;
913  return $this->Result;
914  }
915 
916  function GetPrivList()
917  {
918  # return empty list if not associated with a particular user
919  if ($this->UserId === NULL) { return array(); }
920 
921  # read privileges from database and return array to caller
922  $this->DB->Query("SELECT Privilege FROM APUserPrivileges"
923  ." WHERE UserId='".$this->UserId."'");
924  return $this->DB->FetchColumn("Privilege");
925  }
926 
927  function SetPrivList($NewPrivileges)
928  {
929  # return error if not associated with a particular user
930  if ($this->UserId === NULL) { return U_NOTLOGGEDIN; }
931 
932  # clear old priv list values
933  $this->DB->Query("DELETE FROM APUserPrivileges"
934  ." WHERE UserId='".$this->UserId."'");
935 
936  # for each priv value passed in
937  foreach ($NewPrivileges as $Privilege)
938  {
939  # set priv for user
940  $this->GrantPriv($Privilege);
941  }
942  }
943 
944 
945  # ---- Miscellaneous Functions -------------------------------------------
946 
947  # get unique alphanumeric code for user
948  function GetUniqueCode($SeedString, $CodeLength)
949  {
950  # return NULL if not associated with a particular user
951  if ($this->UserId === NULL) { return NULL; }
952 
953  return substr(strtoupper(md5(
954  $this->Get("UserName").$this->Get("UserPassword").$SeedString)),
955  0, $CodeLength);
956  }
957 
958 
959  # ---- PRIVATE INTERFACE -------------------------------------------------
960 
961  protected $DB; # handle to SQL database we use to store user information
962  protected $UserId = NULL; # user ID number for reference into database
963  protected $Result; # result of last operation
964  protected $LoggedIn; # flag indicating whether user is logged in
965  private $DBFields; # used for caching user values
966 
967  # optional mail function to use instead of mail()
968  private static $EmailFunc = NULL;
969 
970  # check whether a user name is valid (alphanumeric string of 2-24 chars)
971  static function IsValidUserName($UserName)
972  {
973  if (preg_match("/^[a-zA-Z0-9]{2,24}$/", $UserName)) { return TRUE; } else { return FALSE; }
974  }
975 
976  # check whether a password is valid (at least 6 characters)
977  static function IsValidPassword($Password)
978  {
979  if (strlen(self::NormalizePassword($Password)) < 6)
980  { return FALSE; } else { return TRUE; }
981  }
982 
983  # check whether an e-mail address looks valid
984  static function IsValidLookingEMailAddress($EMail)
985  {
986  if (preg_match("/^[a-zA-Z0-9._\-]+@[a-zA-Z0-9._\-]+\.[a-zA-Z]{2,3}$/", $EMail)) { return TRUE; } else { return FALSE; }
987  }
988 
989  # get normalized version of e-mail address
990  static function NormalizeEMailAddress($EMailAddress)
991  {
992  return strtolower(trim($EMailAddress));
993  }
994 
995  # get normalized version of user name
996  static function NormalizeUserName($UserName)
997  {
998  return trim($UserName);
999  }
1000 
1001  # get normalized version of password
1002  static function NormalizePassword($Password)
1003  {
1004  return trim($Password);
1005  }
1006 
1007  # generate random password
1008  function GetRandomPassword($PasswordMinLength = 6, $PasswordMaxLength = 8)
1009  {
1010  # seed random number generator
1011  mt_srand((double)microtime() * 1000000);
1012 
1013  # generate password of requested length
1014  return sprintf("%06d", mt_rand(pow(10, ($PasswordMinLength - 1)),
1015  (pow(10, $PasswordMaxLength) - 1)));
1016  }
1017 
1018  # convenience function to supply parameters to Database->UpdateValue()
1019  function UpdateValue($FieldName, $NewValue = DB_NOVALUE)
1020  {
1021  return $this->DB->UpdateValue("APUsers", $FieldName, $NewValue,
1022  "UserId = '".$this->UserId."'", $this->DBFields);
1023  }
1024 
1025  # methods for backward compatibility with earlier versions of User
1026  function GivePriv($Privilege) { $this->GrantPriv($Privilege); }
1027 
1028 }
Get($FieldName)
Definition: Axis--User.php:247
GetRandomPassword($PasswordMinLength=6, $PasswordMaxLength=8)
static NormalizeUserName($UserName)
Definition: Axis--User.php:996
IsLoggedIn()
Definition: Axis--User.php:431
static IsValidLookingEMailAddress($EMail)
Definition: Axis--User.php:984
GetMailChangeCode()
Definition: Axis--User.php:616
GetUniqueCode($SeedString, $CodeLength)
Definition: Axis--User.php:948
const U_BADPASSWORD
Definition: Axis--User.php:21
GivePriv($Privilege)
GrantPriv($Privilege)
Definition: Axis--User.php:866
const U_ILLEGALUSERNAME
Definition: Axis--User.php:26
SQL database abstraction object with smart query caching.
IsMailChangeCodeGood($Code)
Definition: Axis--User.php:624
const DB_NOVALUE
GetResetCode()
Definition: Axis--User.php:601
UpdateValue($FieldName, $NewValue=DB_NOVALUE)
static NormalizePassword($Password)
CreateNewUserAndMailPassword($UserName, $EMail, $EMailAgain, $EMailSubject, $EMailBody)
Definition: Axis--User.php:509
GetActivationCode()
Definition: Axis--User.php:580
static IsValidPassword($Password)
Definition: Axis--User.php:977
const U_NOSUCHUSER
Definition: Axis--User.php:22
Login($UserName, $Password, $IgnorePassword=FALSE)
Definition: Axis--User.php:290
User($UserInfoOne=NULL, $UserInfoTwo=NULL)
Definition: Axis--User.php:47
StatusMessage($StatusCode=NULL)
Definition: Axis--User.php:123
Delete()
Definition: Axis--User.php:160
const U_TEMPLATENOTFOUND
Definition: Axis--User.php:38
IsResetCodeGood($Code)
Definition: Axis--User.php:609
static IsValidUserName($UserName)
Definition: Axis--User.php:971
const U_DUPLICATEEMAIL
Definition: Axis--User.php:39
static GetSqlQueryForUsersWithPriv($Privilege, $Privileges=NULL)
Get an SQL query that will return IDs of all users that have the specified privilege flags...
Definition: Axis--User.php:788
const U_NOTACTIVATED
Definition: Axis--User.php:40
GetPasswordSalt($UserName)
Definition: Axis--User.php:394
LastLocation($NewLocation=NULL)
Definition: Axis--User.php:217
GetPrivList()
Definition: Axis--User.php:916
IsActivated($NewValue=DB_NOVALUE)
Definition: Axis--User.php:595
HasPriv($Privilege, $Privileges=NULL)
Check whether user has specified privilege(s).
Definition: Axis--User.php:732
PHP
Definition: OAIClient.php:39
const U_DUPLICATEUSERNAME
Definition: Axis--User.php:25
GetBestName()
Get the best available name associated with a user, i.e., the real name or, if it isn't available...
Definition: Axis--User.php:203
SendEMail($TemplateTextOrFileName, $FromAddress=NULL, $MoreSubstitutions=NULL, $ToAddress=NULL)
Definition: Axis--User.php:631
const U_ERROR
Definition: Axis--User.php:20
const U_NOTLOGGEDIN
Definition: Axis--User.php:36
Set($FieldName, $NewValue)
Definition: Axis--User.php:277
const U_PASSWORDSDONTMATCH
Definition: Axis--User.php:23
static SetEmailFunction($NewValue)
Set email function to use instead of mail().
Definition: Axis--User.php:178
static NormalizeEMailAddress($EMailAddress)
Definition: Axis--User.php:990
const U_ILLEGALPASSWORD
Definition: Axis--User.php:28
GetDate($FieldName, $Format="")
Definition: Axis--User.php:256
CreateNewUserWithEMailedPassword($UserName, $EMail, $EMailAgain, $TemplateFile="Axis--User--EMailTemplate.txt")
Definition: Axis--User.php:488
Status()
Definition: Axis--User.php:117
IsNotLoggedIn()
Definition: Axis--User.php:432
const U_ILLEGALEMAIL
Definition: Axis--User.php:32
Logout()
Definition: Axis--User.php:376
LastActiveDate()
Definition: Axis--User.php:237
CreateNewUserAndMailPasswordFromFile($UserName, $EMail, $EMailAgain, $TemplateFile="Axis--User--EMailTemplate.txt")
Definition: Axis--User.php:496
LastIPAddress()
Definition: Axis--User.php:241
SetPassword($NewPassword)
Definition: Axis--User.php:479
const U_MAILINGERROR
Definition: Axis--User.php:37
const U_OKAY
Definition: Axis--User.php:19
SetPrivList($NewPrivileges)
Definition: Axis--User.php:927
ChangePassword($OldPassword, $NewPassword, $NewPasswordAgain)
Definition: Axis--User.php:438
IsActivationCodeGood($Code)
Definition: Axis--User.php:588
RevokePriv($Privilege)
Definition: Axis--User.php:901
const U_EMAILSDONTMATCH
Definition: Axis--User.php:24
Name()
Definition: Axis--User.php:193
static GetSqlQueryForUsersWithoutPriv($Privilege, $Privileges=NULL)
Get an SQL query that will return IDs of all users that do not have the specified privilege flags...
Definition: Axis--User.php:831