Axis--UserFactory.php

Go to the documentation of this file.
00001 <?PHP
00002 
00003 #
00004 #   Axis--UserFactory.php
00005 #   An Meta-Object for Handling User Information
00006 #
00007 #   Copyright 2003 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 class UserFactory {
00019 
00020     # ---- PUBLIC INTERFACE --------------------------------------------------
00021 
00022     # object constructor
00023     function UserFactory($SessionOrDb)
00024     {
00025         # if a session was passed in
00026         if (is_object($SessionOrDb) && method_exists($SessionOrDb, "Session"))
00027         {
00028             # swipe database handle from session
00029             $this->DB = $SessionOrDb->DB;
00030 
00031             # save session
00032             $this->Session = $SessionOrDb;
00033         }
00034         # else if database handle was passed in
00035         elseif (is_object($SessionOrDb) && method_exists($SessionOrDb, "Database"))
00036         {
00037             # save database handle
00038             $this->DB = $SessionOrDb;
00039 
00040             # create session
00041             $this->Session = new Session($this->DB);
00042         }
00043         else
00044         {
00045             # error out
00046             $this->Result = U_ERROR;
00047             exit(1);
00048         }
00049     }
00050 
00063     function CreateNewUser(
00064             $UserName, $Password, $PasswordAgain, $EMail, $EMailAgain,
00065             $IgnoreErrorCodes = NULL)
00066     {
00067         # check incoming values
00068         $ErrorCodes = $this->TestNewUserValues(
00069             $UserName, $Password, $PasswordAgain, $EMail, $EMailAgain);
00070 
00071         # discard any errors we are supposed to ignore
00072         if ($IgnoreErrorCodes)
00073         {
00074             $ErrorCodes = array_diff($ErrorCodes, $IgnoreErrorCodes);
00075         }
00076 
00077         # if error found in incoming values return error codes to caller
00078         if (count($ErrorCodes)) {  return $ErrorCodes;  }
00079 
00080         # add user to database
00081         $UserName = User::NormalizeUserName($UserName);
00082         $this->DB->Query("INSERT INTO APUsers"
00083                 ." (UserName, CreationDate)"
00084                 ." VALUES ('".addslashes($UserName)."', NOW())");
00085 
00086         # create new user object
00087         $UserId = $this->DB->LastInsertId("APUsers");
00088         $User = new User($this->DB, (int)$UserId);
00089 
00090         # if new user object creation failed return error code to caller
00091         if ($User->Status() != U_OKAY) {  return array($User->Status());  }
00092 
00093         # set password and e-mail address
00094         $User->SetPassword($Password);
00095         $User->Set("EMail", $EMail);
00096 
00097         # return new user object to caller
00098         return $User;
00099     }
00100 
00101     # test new user creation values (returns array of error codes)
00102     function TestNewUserValues(
00103             $UserName, $Password, $PasswordAgain, $EMail, $EMailAgain)
00104     {
00105         $ErrorCodes = array();
00106         if (strlen(User::NormalizeUserName($UserName)) == 0)
00107             {  $ErrorCodes[] = U_EMPTYUSERNAME;  }
00108         elseif (!User::IsValidUserName($UserName))
00109             {  $ErrorCodes[] = U_ILLEGALUSERNAME;  }
00110         elseif ($this->UserNameExists($UserName))
00111             {  $ErrorCodes[] = U_DUPLICATEUSERNAME;  }
00112 
00113         if ($this->EMailAddressIsInUse($EMail))
00114             {  $ErrorCodes[] = U_DUPLICATEEMAIL;  }
00115 
00116         $FoundOtherPasswordError = FALSE;
00117         if (strlen(User::NormalizePassword($Password)) == 0)
00118         {
00119             $ErrorCodes[] = U_EMPTYPASSWORD;
00120             $FoundOtherPasswordError = TRUE;
00121         }
00122         elseif (!User::IsValidPassword($Password))
00123         {
00124             $ErrorCodes[] = U_ILLEGALPASSWORD;
00125             $FoundOtherPasswordError = TRUE;
00126         }
00127 
00128         if (strlen(User::NormalizePassword($PasswordAgain)) == 0)
00129         {
00130             $ErrorCodes[] = U_EMPTYPASSWORDAGAIN;
00131             $FoundOtherPasswordError = TRUE;
00132         }
00133         elseif (!User::IsValidPassword($PasswordAgain))
00134         {
00135             $ErrorCodes[] = U_ILLEGALPASSWORDAGAIN;
00136             $FoundOtherPasswordError = TRUE;
00137         }
00138 
00139         if ($FoundOtherPasswordError == FALSE)
00140         {
00141             if (User::NormalizePassword($Password)
00142                     != User::NormalizePassword($PasswordAgain))
00143             {
00144                 $ErrorCodes[] = U_PASSWORDSDONTMATCH;
00145             }
00146         }
00147 
00148         $FoundOtherEMailError = FALSE;
00149         if (strlen(User::NormalizeEMailAddress($EMail)) == 0)
00150         {
00151             $ErrorCodes[] = U_EMPTYEMAIL;
00152             $FoundOtherEMailError = TRUE;
00153         }
00154         elseif (!User::IsValidLookingEMailAddress($EMail))
00155         {
00156             $ErrorCodes[] = U_ILLEGALEMAIL;
00157             $FoundOtherEMailError = TRUE;
00158         }
00159 
00160         if (strlen(User::NormalizeEMailAddress($EMailAgain)) == 0)
00161         {
00162             $ErrorCodes[] = U_EMPTYEMAILAGAIN;
00163             $FoundOtherEMailError = TRUE;
00164         }
00165         elseif (!User::IsValidLookingEMailAddress($EMailAgain))
00166         {
00167             $ErrorCodes[] = U_ILLEGALEMAILAGAIN;
00168             $FoundOtherEMailError = TRUE;
00169         }
00170 
00171         if ($FoundOtherEMailError == FALSE)
00172         {
00173             if (User::NormalizeEMailAddress($EMail)
00174                     != User::NormalizeEMailAddress($EMailAgain))
00175             {
00176                 $ErrorCodes[] = U_EMAILSDONTMATCH;
00177             }
00178         }
00179 
00180         return $ErrorCodes;
00181     }
00182 
00188     function GetUserCount($Condition = NULL)
00189     {
00190         return $this->DB->Query("SELECT COUNT(*) AS UserCount FROM APUsers"
00191                 .($Condition ? " WHERE ".$Condition : ""), "UserCount");
00192     }
00193 
00194     # return total number of user that matched last GetMatchingUsers call
00195     # before the return size was limited
00196     function GetMatchingUserCount()
00197     {
00198         return $this->MatchingUserCount;
00199     }
00200 
00201     # return array of users currently logged in
00202     function GetLoggedInUsers()
00203     {
00204         # start with empty array (to prevent array errors)
00205         $ReturnValue = array();
00206 
00207         # load array of logged in user
00208         $UserIds = $this->Session->GetFromAllSessions("APUserId");
00209 
00210         # for each logged in user
00211         foreach ($UserIds as $UserId)
00212         {
00213             # load all data values for user
00214             $this->DB->Query("SELECT * FROM APUsers WHERE UserId = '".$UserId."'");
00215             $ReturnValue[$UserId] = $this->DB->FetchRow();
00216         }
00217 
00218         # return array of user data to caller
00219         return $ReturnValue;
00220     }
00221 
00222     # return array of users recently logged in. returns 10 users by default
00223     function GetRecentlyLoggedInUsers($Since = NULL, $Limit = 10)
00224     {
00225         # start with empty array (to prevent array errors)
00226         $ReturnValue = array();
00227 
00228         # get users recently logged in during the last 24 hours if no date given
00229         if (is_null($Since))
00230         {
00231             $Date = date("Y-m-d H:i:s", time()-86400);
00232         }
00233 
00234         else
00235         {
00236             $Date = date("Y-m-d H:i:s", strtotime($Since));
00237         }
00238 
00239         # query for the users who were logged in since the given date
00240         $this->DB->Query("
00241             SELECT U.*
00242             FROM APUsers U
00243             LEFT JOIN
00244             -- the dummy table is an optimization. see the comment by Vimal
00245             -- Gupta in the MySQL docs:
00246             -- http://dev.mysql.com/doc/refman/5.0/en/in-subquery-optimization.html
00247             (SELECT DataValue
00248              FROM APSessionData
00249              WHERE DataName = 'APUserId'
00250              -- allows fetching distinct DataValue values but with GROUP BY
00251              -- optimizations
00252              GROUP BY DataValue) as Dummy
00253             -- using this convoluted method because DataValue is an integer
00254             -- (UserId) serialized by PHP to a string
00255             ON CONCAT('s:', CHAR_LENGTH(CAST(U.UserId AS CHAR)),
00256             ':\"', U.UserId,'\";') = Dummy.DataValue
00257             WHERE U.LastActiveDate >= '".$Date."'
00258             AND Dummy.DataValue IS NULL
00259             ORDER BY U.LastActiveDate DESC
00260             LIMIT ".intval($Limit));
00261 
00262         while (FALSE !== ($Row = $this->DB->FetchRow()))
00263         {
00264             $ReturnValue[$Row["UserId"]] = $Row;
00265         }
00266 
00267         # return array of user data to caller
00268         return $ReturnValue;
00269     }
00270 
00271     # return array of user names who have the specified privileges
00272     # (array index is user IDs)
00273     function GetUsersWithPrivileges()
00274     {
00275         # start with query string that will return all users
00276         $Args = func_get_args();
00277         $QueryString = "SELECT DISTINCT APUsers.UserId, UserName FROM APUsers"
00278                 .(count($Args) ? ", APUserPrivileges" : "");
00279 
00280         # for each specified privilege
00281         if (is_array(reset($Args))) {  $Args = reset($Args);  }
00282         foreach ($Args as $Index => $Arg)
00283         {
00284             # add condition to query string
00285             $QueryString .= ($Index == 0) ? " WHERE (" : " OR";
00286             $QueryString .= " APUserPrivileges.Privilege = ".$Arg;
00287         }
00288 
00289         # close privilege condition in query string and add user ID condition
00290         $QueryString .= count($Args) 
00291                 ? ") AND APUsers.UserId = APUserPrivileges.UserId" : "";
00292 
00293         # add sort by user name to query string
00294         $QueryString .= " ORDER BY UserName ASC";
00295 
00296         # perform query
00297         $this->DB->Query($QueryString);
00298 
00299         # copy query result into user info array
00300         $Users = $this->DB->FetchColumn("UserName", "UserId");
00301 
00302         # return array of users to caller
00303         return $Users;
00304     }
00305 
00306     # return array of user objects who have values matching search string
00307     # (array indexes are user IDs)
00308     function FindUsers($SearchString, $FieldName = "UserName",
00309             $SortFieldName = "UserName", $Offset = 0, $Count = 9999999)
00310     {
00311         # retrieve matching user IDs
00312         $UserNames = $this->FindUserNames(
00313                 $SearchString, $FieldName, $SortFieldName, $Offset, $Count);
00314 
00315         # create user objects
00316         $Users = array();
00317         foreach ($UserNames as $UserId => $UserName)
00318         {
00319             $Users[$UserId] = new User($this->DB, intval($UserId));
00320         }
00321 
00322         # return array of user objects to caller
00323         return $Users;
00324     }
00325 
00326     # return array of user names/IDs who have values matching search string
00327     # (array indexes are user IDs, array values are user names)
00328     function FindUserNames($SearchString, $FieldName = "UserName",
00329             $SortFieldName = "UserName", $Offset = 0, $Count = 9999999)
00330     {
00331         # Construct a database query:
00332         $QueryString = "SELECT UserId, UserName FROM APUsers WHERE";
00333 
00334         # If the search string is a valid username which is shorter than the
00335         # minimum word length indexed by the FTS, just do a normal
00336         # equality test instead of using the index.
00337         # Otherwise, FTS away.
00338         $MinWordLen = $this->DB->Query(
00339             "SHOW VARIABLES WHERE variable_name='ft_min_word_len'", "Value");
00340         if (User::IsValidUserName($SearchString) &&
00341             strlen($SearchString) < $MinWordLen )
00342         {
00343             $QueryString .= " UserName='".addslashes($SearchString)."'";
00344         }
00345         else
00346         {
00347             # massage search string to use AND logic
00348             $Words = preg_split("/[\s]+/", trim($SearchString));
00349             $NewSearchString = "";
00350             $InQuotedString = FALSE;
00351             foreach ($Words as $Word)
00352             {
00353                 if ($InQuotedString == FALSE) {  $NewSearchString .= "+";  }
00354                 if (preg_match("/^\"/", $Word)) {  $InQuotedString = TRUE;  }
00355                 if (preg_match("/\"$/", $Word)) {  $InQuotedString = FALSE;  }
00356                 $NewSearchString .= $Word." ";
00357             }
00358             $QueryString .= " MATCH (".$FieldName.")"
00359                 ." AGAINST ('".addslashes(trim($NewSearchString))."'"
00360                 ." IN BOOLEAN MODE)";
00361         }
00362         $QueryString .= " ORDER BY ".$SortFieldName
00363             ." LIMIT ".$Offset.", ".$Count;
00364 
00365         # retrieve matching user IDs
00366         $this->DB->Query($QueryString);
00367         $UserNames = $this->DB->FetchColumn("UserName", "UserId");
00368 
00369         # return names/IDs to caller
00370         return $UserNames;
00371     }
00372 
00373     # return array of users who have values matching search string (in specific field if requested)
00374     # (search string respects POSIX-compatible regular expressions)
00375     # optimization: $SearchString = ".*." and $FieldName = NULL will return all
00376     #   users ordered by $SortFieldName
00377     function GetMatchingUsers($SearchString, $FieldName = NULL,
00378                               $SortFieldName = "UserName",
00379                               $ResultsStartAt = 0, $ReturnNumber = NULL)
00380     {
00381         # start with empty array (to prevent array errors)
00382         $ReturnValue = array();
00383 
00384         # if empty search string supplied, return nothing
00385         $TrimmedSearchString = trim($SearchString);
00386         if (empty($TrimmedSearchString))
00387         {
00388             return $ReturnValue;
00389         }
00390 
00391         # make sure ordering is done by user name if not specified
00392         $SortFieldName = empty($SortFieldName) ? "UserName" : $SortFieldName;
00393 
00394         # begin constructing the query
00395         $Query = "SELECT * FROM APUsers";
00396         $QueryOrderBy = " ORDER BY $SortFieldName";
00397         $QueryLimit = empty($ReturnNumber) ? "" : " LIMIT $ResultsStartAt, $ReturnNumber";
00398 
00399         # the Criteria Query will be used to get the total number of results without the
00400         # limit clause
00401         $CriteriaQuery = $Query;
00402 
00403         # if specific field comparison requested
00404         if (!empty($FieldName))
00405         {
00406             # append queries with criteria
00407             $Query .= " WHERE ".$FieldName." REGEXP '".addslashes($SearchString)."'";
00408             $CriteriaQuery = $Query;
00409         }
00410 
00411         # optimize for returning all users
00412         else if ($SearchString == ".*.")
00413         {
00414             # set field name to username - this would be the first field
00415             # returned by a field to field search using the above RegExp
00416             $FieldName = "UserName";
00417         }
00418 
00419         # add order by and limit to query for optimizing
00420         $Query .= $QueryOrderBy.$QueryLimit;
00421 
00422         # execute query...
00423         $this->DB->Query($Query);
00424 
00425         # ...and process query return
00426         while ($Record = $this->DB->FetchRow())
00427         {
00428             # if specific field or all users requested
00429             if (!empty($FieldName))
00430             {
00431                 # add user to return array
00432                 $ReturnValue[$Record["UserId"]] = $Record;
00433 
00434                 # add matching search field to return array
00435                 $ReturnValue[$Record["UserId"]]["APMatchingField"] = $FieldName;
00436             }
00437 
00438             else
00439             {
00440                 # for each user data field
00441                 foreach ($Record as $FName => $FValue)
00442                 {
00443                     # if search string appears in data field
00444                     if (strpos($Record[$FName], $SearchString) !== FALSE)
00445                     {
00446                         # add user to return array
00447                         $ReturnValue[$Record["UserId"]] = $Record;
00448 
00449                         # add matching search field to return array
00450                         $ReturnValue[$Record["UserId"]]["APMatchingField"] = $FName;
00451                     }
00452                 }
00453             }
00454         }
00455 
00456         # add matching user count
00457         $this->DB->Query($CriteriaQuery);
00458         $this->MatchingUserCount = $this->DB->NumRowsSelected();
00459 
00460         # return array of matching users to caller
00461         return $ReturnValue;
00462     }
00463 
00464     # check whether user name currently exists
00465     function UserNameExists($UserName)
00466     {
00467         # normalize user name
00468         $UserName = User::NormalizeUserName($UserName);
00469 
00470         # check whether user name is already in use
00471         $NameCount = $this->DB->Query(
00472                 "SELECT COUNT(*) AS NameCount FROM APUsers"
00473                     ." WHERE UserName = '".addslashes($UserName)."'",
00474                 "NameCount");
00475 
00476         # report to caller whether name exists
00477         return ($NameCount > 0);
00478     }
00479 
00480     # check whether e-mail address currently has account associated with it
00481     function EMailAddressIsInUse($Address)
00482     {
00483         # normalize address
00484         $UserName = User::NormalizeEMailAddress($Address);
00485 
00486         # check whether address is already in use
00487         $AddressCount = $this->DB->Query(
00488                 "SELECT COUNT(*) AS AddressCount FROM APUsers"
00489                     ." WHERE EMail = '".addslashes($Address)."'",
00490                 "AddressCount");
00491 
00492         # report to caller whether address is in use
00493         return ($AddressCount > 0);
00494     }
00495 
00501     public function GetNewestUsers($Limit = 5)
00502     {
00503         # assume no users will be found
00504         $Users = array();
00505 
00506         # fetch the newest users
00507         $this->DB->Query("SELECT *"
00508                 ." FROM APUsers"
00509                 ." ORDER BY CreationDate DESC"
00510                 ." LIMIT ".intval($Limit));
00511         $UserIds = $this->DB->FetchColumn("UserId");
00512 
00513         # for each user id found
00514         foreach ($UserIds as $UserId)
00515         {
00516             $Users[$UserId] = new SPTUser($UserId);
00517         }
00518 
00519         # return the newest users
00520         return $Users;
00521     }
00522 
00523     # ---- PRIVATE INTERFACE -------------------------------------------------
00524 
00525     var $DB;
00526     var $Session;
00527     var $SortFieldName;
00528     var $MatchingUserCount;
00529 
00530     # callback function for sorting users
00531     function CompareUsersForSort($UserA, $UserB)
00532     {
00533         return strcasecmp($UserA[$this->SortFieldName], $UserB[$this->SortFieldName]);
00534     }
00535 
00536 }