<?php

RegisterPrefix("clsPortalUser","user","kernel/include/portaluser.php");

class clsPortalUser extends clsItem  
{
    var $Vars;               //contains the PersistantSessionData for the user
    var $VarsLoaded;        
    var $PrimeGroup;

    function clsPortalUser($UserId=NULL)
    {
 //     $this->clsParsedItem();
        $this->clsItem();
        $this->tablename=GetTablePrefix()."PortalUser";
        $this->type=6;
        $this->BasePermission="USER";
        $this->id_field = "PortalUserId";
        $this->TagPrefix="user";

        $this->Vars = Array();
        $this->VarsLoaded = FALSE;
        $this->debuglevel = 0;
        if(isset($UserId))
            $this->LoadFromDatabase($UserId);
    }

    function Delete()
    {
        global $objGroups, $objFavorites;

        $g = $objGroups->GetPersonalGroup($this->Get("Login"));
        if(is_object($g))
            $g->Delete();
        $objFavorites->DeleteUser($this->Get("PortalUserId")); //delete favorites
        parent::Delete();
    }

    function RemoveFromAllGroups()
    {
        $sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortaluserId=".$this->Get("PortalUserId");
        $this->adodbConnection->Execute($sql);	
    }   
    
    function RemoveFromGroup($GroupId)
    {
        $sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortaluserId=".$this->Get("PortalUserId");
        $sql .= " AND GroupId=$GroupId";
        $this->adodbConnection->Execute($sql);	      	
    }
    
    function PrimaryGroup($ReturnField = "GroupId")
    {
      global $objGroups;

      $ret = "";

      if(!is_object($this->PrimeGroup))
      {
         if((int)$this->Get("GroupId")>0)
         {
             $this->PrimeGroup =& $objGroups->GetItem($this->Get("GroupId"));
         }
         else
         {                  
             $this->PrimeGroup = new clsPortalGroup();
             $sql = "SELECT * FROM ".GetTablePrefix()."UserGroup INNER JOIN ".GetTablePrefix()."PortalGroup ON (".GetTablePrefix()."UserGroup.GroupId=".GetTablePrefix()."PortalGroup.GroupId) WHERE PrimaryGroup = 1 AND PortalUserId=".$this->Get("PortalUserId");
             //echo $sql;
             $rs = $this->adodbConnection->Execute($sql);

             if($rs && !$rs->EOF)
                 $this->PrimeGroup->SetFromArray($rs->fields);
         }
      }
      $ret = $this->PrimeGroup->Get($ReturnField);
      return $ret;
    }
    
    function SetPrimaryGroup($GroupId)
    {
      if($this->IsInGroup($GroupId))
      {
      	$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PrimaryGroup=0 WHERE PortalUserId=".$this->Get("PortalUserId");
      	$this->adodbConnection->Execute($sql);
      	$sql = "UPDATE ".GetTablePrefix()."UserGroup SET PrimaryGroup=1 WHERE GroupId=$GroupId AND PortalUserId=".$this->Get("PortalUserId");
      	$this->adodbConnection->Execute($sql);
      }
    }

    function GetGroupList()
    {
        $ret = array();
        $sql = "SELECT GroupId FROM %sUserGroup WHERE PortalUserId = %s ORDER BY PrimaryGroup";
        $sql = sprintf($sql, GetTablePrefix(), $this->Get("PortalUserId"));
        $ret = $this->adodbConnection->GetCol($sql);
        return $ret;
    }
    
    function IsInGroup($GroupId)
    {
      $groups = $this->GetGroupList();
      if( $groups === false ) return false;
      return in_array($GroupId, $groups) ? true : false;
    }
	
	function GetPersonalGroup($CreateIfMissing = FALSE)
	{
	  global $objGroups;

	  $n = "_".$this->Get("Login");
	  $g = $objGroups->GetItemByField("Name",$n);
	  if(!is_object($g) && $CreateIfMissing)
	    $g = $this->CreatePersonalGroup();
	  return $g;
	}

    function CreatePersonalGroup()
    {
        global $objGroups;

        $Description = $this->Get("FirstName")." ".$this->Get("LastName");
        $CreatedOn=time();
		$n = "_".$this->Get("Login");
        $g = $objGroups->Add_Group($n, $Description, $CreatedOn, 1, 0);
		$g->Set("Personal",1);
		$g->Set("System",0);
		$g->Set("Enabled",1);
		$g->Update();
        if(is_object($g))
          $g->AddUser($this->Get("PortalUserId"));
        return $g;
    }

    function Validate()
    {
        global $Errors;

        $dataValid = true;
        if(!strlen($this->Get("Login")))
        {
            $Errors->AddError("error.fieldIsRequired",'Login',"","",get_class($this),"Validate");
            $dataValid = false;
        }
                
        if(!strlen($this->Get("Email")))
        {
            $Errors->AddError("error.fieldIsRequired",'Email',"","",get_class($this),"Validate");
            $dataValid = false;
        }
        
		return $dataValid;
    }

	function Approve()
	{
	  $this->Set("Status", 1);
	  $this->Update();
      $this->SendUserEventMail("USER.APPROVE",$this->Get("PortalUserId"));
      $this->SendAdminEventMail("USER.APPROVE");
	}

    function Deny($IsBanned = 0)
    {
        $this->Set( Array('Status','IsBanned'), Array(0,$IsBanned) );
        $this->Update();
        $this->SendUserEventMail("USER.DENY",$this->Get("PortalUserId"));
        $this->SendAdminEventMail("USER.DENY");
    }

	function HasSystemPermission($PermissionName)
    {
	    global $objGroups;

		  $GroupList = $this->GetGroupList();		  
  	      for($i=0;$i<count($GroupList);$i++)
		  {
               $g = $objGroups->GetItem($GroupList[$i]);
               $value = $g->HasSystemPermission($PermissionName);
		       if($value != -1)
                 break;
		  }
		return $value;
    }
  
    function LoadPersistantVars()
    {
    	global $objConfig;

    	unset($this->Vars);
        $this->Vars = Array();
        $user_id = $this->HasField('PortalUserId') ? $this->Get('PortalUserId') : 0;
        
        $sql = "SELECT VariableName, VariableValue FROM ".GetTablePrefix()."PersistantSessionData WHERE PortalUserId = ".(int)$user_id." ORDER BY PortalUserId ASC";
        $result = $this->adodbConnection->Execute($sql);
        while ($result && !$result->EOF)
        {
          $data = $result->fields;
          $this->Vars[$data["VariableName"]] =  $data["VariableValue"];
          
          if( basename($_SERVER['PHP_SELF']) != 'edit_config.php' )
          {
          	$objConfig->Set($data["VariableName"], $data["VariableValue"], 1, 1);
          }
          $result->MoveNext();
        }
        $this->VarsLoaded = TRUE;
    }
	
    function SetPersistantVariable($variableName, $variableValue)
	{
	  global $objConfig;

      if(!$this->VarsLoaded)
          $this->LoadPersistantVars();
	  $userid = $this->Get("PortalUserId");  
      $objConfig->Set($variableName,$variableValue,1);
      $fields = array_keys($this->Vars);
          
      if(strlen($variableValue)>0)
      {                 
          if(in_array($variableName,$fields))
          {
              $sql = "UPDATE ".GetTablePrefix()."PersistantSessionData SET VariableValue='$variableValue' WHERE VariableName='$variableName' AND PortalUserId=$userid";
          }
          else
              $sql = "INSERT INTO ".GetTablePrefix()."PersistantSessionData (VariableName,VariableValue,PortalUserId) VALUES ('$variableName','$variableValue',$userid)";
      }
      else
        $sql = "DELETE FROM ".GetTablePrefix()."PersistantSessionData  WHERE VariableName='$variableName' AND PortalUserId=$userid"; 
      
      $this->Vars[$variableName] = $variableValue;
      
//      echo "<BR>SQL: $sql<BR>";
      
      $this->adodbConnection->Execute($sql);
	}

	function GetPersistantVariable($variableName)
	{
        global $objConfig, $objSession;
          
        if(!$this->VarsLoaded)
        {
            $this->LoadPersistantVars();
        }

        $fields = array_keys($this->Vars);
                
        if(in_array($variableName,$fields))
        {
            $val = $this->Vars[$variableName];
        }
        else
        {
          	if( $this->UniqueId() == $objSession->Get('PortalUserId') )
          	{
        		$val =  $objConfig->Get($variableName);
          	}
          	else
          	{
          		$val = '';
          	}
        }
        
        return $val;
	}    

    function GetAllPersistantVars()
    {
        if(!$this->VarsLoaded)
        {
            $this->LoadPersistantVars();
        }
        return $this->Vars;
    }

	function GetIcon()
	{	
	}

    function StatusIcon()
    {
        global $imagesURL;

        $url = $imagesURL."/itemicons/icon16_user";
        if($this->Get("Status")==0)
        {
            $url .= "_disabled";
        }
        else
          if($this->Get("Status")==2)
          {        
            $url .= "_pending";
          }
        $url .= ".gif";
        return $url;
    }

    function IsFriend($UserId)
    {
        $ftable = GetTablePrefix()."Favorites";
        $sql = "SELECT count(*) as FriendCount FROM $ftable WHERE PortalUserId=$UserId AND ResourceId=";
        $sql .=$this->Get("ResourceId")." AND ItemTypeId=6";
        $rs = $this->adodbConnection->Execute($sql);
        if($rs && !$rs->EOF)
            return ($rs->fields["FriendCount"]>0);
        return FALSE;
    }

    function GetUserTime($timestamp)
    {
        if(is_numeric($this->Get("tz")))
        {
            return GetLocalTime($timestamp,$this->Get("tz"));
        }
        else
            return GetLocalTime($timestamp);
    }

    function ParseObject($element)
    { 
        global $objConfig, $objUsers, $objCatList,$objSession, $var_list_update, $var_list, $m_var_list_update;
        //echo "<PRE>"; print_r($element); echo "</pre>";
        //echo "Tag Prefix: ".$this->TagPrefix." Element: ".$element->name."<br>";
        $this->clsPortalUser();
        if (strtolower($element->name) == 'touser') {
        	$this->TagPrefix = "touser";
        }
        
        $extra_attribs = ExtraAttributes($element->attributes);
        if(strtolower($element->name)==$this->TagPrefix)
        {   
            $field = strtolower($element->attributes["_field"]); 
            if(substr($field,0,3)=="pp_")
            {
                $perm = $objSession->GetPersistantVariable($field);
                if($perm)
                {                
                    $field = substr($field,3);
                }
                else
                    $field = "";
            }
            switch($field)
            {     
            	/*
            	@field:user.login
            	@description:User's login name
            	*/
            case "username":
            case "login":
                $ret = $this->Get("Login");
            break;
			case "firstname":
				$ret = $this->Get("FirstName");
			break;
			case "lastname":
				$ret = $this->Get("LastName");
			break;            
            case "password":
            	/*
            	@field:user.password            
            	@description:User password
            	*/
                $ret = $objSession->Get("password");
                $objSession->Set("password", '');
            break;
			case "email":
			  $ret = $this->Get("Email");
			break;  
			case "street":
			  $ret = $this->Get("Street");
			break;
			case "city":
			  $ret = $this->Get("City");
			break;
			case "state":
			  $ret = $this->Get("State");
			break;
			case "zip":
			  $ret = $this->Get("Zip");
			break;
			case "phone":
			  $ret = $this->Get("Phone");
			break;      
			case "country":
			  $ret = $this->Get("Country");
			break;
            case "primarygroup":
              /*
              @field:user.primarygroup
              @description:Parses a field from the user's primary group
              @attrib:_groupfield::group field name to parse, defaults to group name
              */
              $groupfield = $element->attributes["_groupfield"];
              if(!strlen($groupfield))
                  $groupfield="Name";
              $ret = $this->PrimaryGroup($groupfield);
            break;
            case "date":    
            	/*
  				@field:user.date
  				@description:Returns the date/time the user was created
  				@attrib:_tz:bool:Convert the date to the user's local time
  				@attrib:_part::Returns part of the date.  The following options are available: month,day,year,time_24hr,time_12hr
            	*/                            
                $d = $this->Get("CreatedOn");
                if($element->attributes["_tz"])
                {
                    $d = GetLocalTime($d,$objSession->Get("tz"));
                }

                $part = strtolower($element->attributes["_part"]);
                if(strlen($part))
                {
                    $ret = ExtractDatePart($part,$d);
                }
                else
                {                
                  if($d<=0)
                  {                  
                    $ret = "";
                  }
                  else
                    $ret = LangDate($d);
                }
            break;  
            case "dob":
            	/*
  				@field:user.dob
  				@description:Returns the date/time of the users date of birth
  				@attrib:_tz:bool:Convert the date to the user's local time
  				@attrib:_part::Returns part of the date.  The following options are available: month,day,year,time_24hr,time_12hr
            	*/                
                $d = $this->Get("dob");
                if($element->attributes["_tz"])
                {
                    $d = GetLocalTime($d,$objSession->Get("tz"));
                }
                $part = strtolower($element->attributes["_part"]);
                if(strlen($part))
                {
                    $ret = ExtractDatePart($part,$d);
                }
                else
                {                
//                  if($d<=0)
//                  {                  
//                    $ret = "";
//                  }
//                  else
                    $ret = LangDate($d);
                }
            break;  

            case "modified":
            	/*
  				@field:user.modified
  				@description:Returns the date/time the user was last modified
  				@attrib:_tz:bool:Convert the date to the user's local time
  				@attrib:_part::Returns part of the date.  The following options are available: month,day,year,time_24hr,time_12hr
            	*/                
                $d = $this->Get("Modified");
                if($d<=0)
                    $d = $this->Get("CreatedOn");

                if($element->GetAttributeByName('_tz'))
                {
                    $d = GetLocalTime($d,$objSession->Get("tz"));
                }
                
                $part = strtolower($element->GetAttributeByName('_part'));                 
                if(strlen($part))
                {
                     $ret = ExtractDatePart($part,$d);
                }
                else
                {                
                   if($d<=0)
                   {                  
                     $ret = "";
                   }
                   else
                     $ret = LangDate($d);
                }
            break;
            
            case 'send_pm_link':
            	$var_list_update['t'] = $element->GetAttributeByName('_Template');
            	$ret = GetIndexURL(2)."?env=".BuildEnv()."&ToUser=".$this->Get('Login');
            	break;
            	
            case "profile_link":
            	/*
            	@field:user.profile_link
            	@description:Create a link to the user's profile
            	@attrib:_template:tpl:template the link should point to
            	*/
                $t = $element->attributes["_template"];
                if(strlen($t))
                {                
                    $var_list_update["t"] = $t;
                }
                else
                    $var_list_update["t"] = $var_list["t"];
                $ret = GetIndexURL(2)."?env=" . BuildEnv()."&UserId=".$this->Get("PortalUserId");
            break;
            case "add_friend_link":
                /*
                @field:user.add_friend_link
                @description:link to add a user to the friends list
                @attrib:_template:tpl:Template link shoukd point to
				*/
                if($element->attributes["_force"] || !$this->IsFriend($objSession->Get("PortalUserId")) && 
                   $this->Get("PortalUserId") != $objSession->Get("PortalUserId"))
                {                
                    $t = $element->attributes["_template"];
                    if(strlen($t))
                    {                
                        $var_list_update["t"] = $t;
                    }
                    else
                        $var_list_update["t"] = $var_list["t"];
                    $action = "m_add_friend";
                    $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=".$action."&UserId=".$this->Get("PortalUserId");
                }
                else
                    $ret = "";
            break;
            case "del_friend_link":
                /*
                @field:user.del_friend_link
                @description:link to remove a user from the friends list
                @attrib:_template:tpl:Template link shoukd point to
				*/            
                if($element->attributes["_force"] || $this->IsFriend($objSession->Get("PortalUserId")) && 
                   $this->Get("PortalUserId") != $objSession->Get("PortalUserId"))
                {                
                  $t = $element->attributes["_template"];
                  if(strlen($t))
                  {                
                    $var_list_update["t"] = $t;
                  }
                  else
                    $var_list_update["t"] = $var_list["t"];
                  $action = "m_del_friend";
                  $ret = GetIndexURL(2)."?env=" . BuildEnv()."&Action=".$action."&UserId=".$this->Get("PortalUserId");
                }
                else
                    $ret = "";
            break;
            case "icon":
                $ret = $this->GetIcon();
            break;    
            case "image":
            	/*
 				@field:user.image
 				@description:Return an image associated with the user
  				@attrib:_default:bool:If true, will return the default image if the requested image does not exist
  				@attrib:_name::Return the image with this name
  				@attrib:_thumbnail:bool:If true, return the thumbnail version of the image
  				@attrib:_imagetag:bool:If true, returns a complete image tag. exta html attributes are passed to the image tag
               */    
               $avatar = $element->attributes["_avatar"];         
               $default = $element->attributes["_primary"];
               $name = $element->attributes["_name"];
               if ($avatar) 
               {
               		$img = $this->GetAvatarImage();
               }
               elseif(strlen($name))
               {
                   $img = $this->GetImageByName($name);
                  // echo "<PRE>";print_r($img); echo "</PRE>";
               }
               elseif ($default) 
           	   {
                 	$img = $this->GetDefaultImage();
           	   }
               
               if($img)
               {
                   if($element->attributes["_thumbnail"])
                   {                        
                     $url = $img->parsetag("thumb_url");
                   }
                   else
                     $url = $img->parsetag("image_url");                   
               }
               else
               {
                  $url = $element->attributes["_defaulturl"];
               }

               if($element->attributes["_imagetag"])
               {
                   if(strlen($url))
                   {                        
                     $ret = "<IMG src=\"$url\" $extra_attribs >";
                   }
                   else
                       $ret = "";
               }
               else
                   $ret = $url;
            break;

            case "custom":                
                /*
                @field:cat.custom
                @description:Returns a custom field
  				@attrib:_customfield::field name to return
  				@attrib:_default::default value
  				*/             
                $field =  $element->attributes["_customfield"]; 
                $default = $element->attributes["
                "];
                $ret = $this->GetPersistantVariable($field);
                if(!strlen($ret))
                    $ret = $this->GetCustomFieldValue($field,$default);
            break;
            default:
            	$ret = "Undefined:".$element->name;
            	break;            
            }
        }
        else
        {
            $ret = $this->parsetag($element->name);        
        }
        
        return $ret;
    }

    function parsetag($tag)
    {	
        global $m_var_list_update, $var_list_update, $var_list, $objConfig;
        if(is_object($tag))
        {        
            $tagname = $tag->name;
        }
        else
            $tagname = $tag;            
            
        switch($tagname)
        {	
		case "user_id":
            return $this->Get("ResourceId");
            break;
		case "user_login":
			return $this->Get("Login");
			break;
        case "user_group":
            return $this->Get("PrimaryGroupName");
            break;
		case "user_firstname":
			return $this->Get("FirstName");
			break;
		case "user_lastname":
			return $this->Get("LastName");
			break;
		case "user_email":
			return $this->Get("Email");
			break;
        case "user_date":
			return LangDate($this->Get("CreatedOn"));
			break;
        case "user_time":
			return LangTime($this->Get("CreatedOn"));
			break;
        case "user_dob":
			return LangDate($this->Get("dob"));
			break;

		case "user_password":
			return $this->Get("Password");
			break;
		case "user_phone":
			return $this->Get("Phone");
			break;	
		case "user_street":
			return $this->Get("Street");
			break;	
		case "user_city":
			return $this->Get("City");
			break;	
		case "user_state":
			return $this->Get("State");
			break;	
		case "user_zip":
			return $this->Get("Zip");
			break;	
		case "user_country":
			return $this->Get("Country");
			break;
		case "user_resourceid":
			return $this->Get("ResourceId");
			break;	
		case "user_icon":
			return $this->GetIcon();
		break;
		case "user_profile_link":
			$var_list_update["t"] = "user_profile";
			$m_var_list_update["action"] = $this->Get("UserId");
			$ret = GetIndexURL(2)."?env=" . BuildEnv();
			unset($m_var_list_update["action"], $var_list_update["t"]);
			return $ret;
			break;
        case "user_messages":
            return $this->NewMessages();
            break;
        case "user_messages_link":
			$var_list_update["t"] = "inbulletin/bb_private_msg_list";
			return GetIndexURL(2)."?env=" . BuildEnv();
			unset($var_list_update);
			break;
		default:
				return "Undefined:$tagname";
			break;
        }
    }    

} /* class clsPortalUser*/


class clsUserManager extends clsItemList //clsItemCollection
{
	/*this class wraps common user-related functions */
   // var $Page;

	function clsUserManager()
	{
      $this->clsItemCollection(); // clsItemList() // need to use this, but double limit clause being created (normal+default 0,100)
      $this->classname = "clsPortalUser";
      $this->SetTable('live', GetTablePrefix().'PortalUser');
	  $this->Page = isset($_GET['lpn']) ? $_GET['lpn'] : 1;
	  $this->EnablePaging = true;
  	  $this->PerPageVar = "Perpage_User";      
      $this->AdminSearchFields = array("Login","FirstName","LastName","Email","Street","City", "State","Zip","Country","Phone");
	}

    function GetPageLinkList($dest_template=NULL,$link_template=NULL,$page = "")
    {
        global $objConfig, $m_var_list_update, $var_list_update, $var_list;

        if(!strlen($page))
            $page = GetIndexURL(2);
        $NumPages = $this->GetNumPages($objConfig->Get("Perpage_Topics"));
        if(strlen($dest_template)>0)
        {
            $var_list_update["t"]=$dest_template;
        }
        else
        {
            $var_list_update["t"] = $var_list["t"];            
        }
        $o = "";
        if($this->Page>1)
        {
          $m_var_list_update["p"]=$this->Page-1;
          $prev_url = $page."?env=".BuildEnv();
        }
        if($this->Page<$NumPages)
        {
          $m_var_list_update["p"]=$this->Page+1;
          $next_url = $page."?env=".BuildEnv();
        }
        
        for($p=1;$p<=$NumPages;$p++)
        {
            $t = template($link_template);
            if($p!=$this->Page)
            {
                $m_var_list_update["p"]=$p;
                $href = $page."?env=".BuildEnv();
                $t = str_replace("<%page_link%>", $href, $t);
                $t = str_replace("<%page_number%>",$p,$t);
                $t = str_replace("<%prev_url%>",$prev_url,$t);
                $t = str_replace("<%next_url%>",$next_url,$t);
                $o .= $t;
            }
            else
            {
                $o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
            }
        }
        return $o;
    }


    function GetUser($ID)
    {
        $u =  $this->GetItem($ID);
        return $u;
    }

 	function GetUserName($Id)
	{
	    $rs = $this->adodbConnection->Execute("SELECT Login from ".$this->SourceTable." where PortalUserId=$Id");
		return $rs->fields["Login"];
	}

	function GetUserId($Login)
	{
	    $rs = $this->adodbConnection->Execute("SELECT PortalUserId from ".$this->SourceTable." where Login LIKE '$Login'");
		return $rs->fields["PortalUserId"];
	}


	function GetTotalUsers()
	{
	  return $this->UserCount("1");
	}


	function GetLatestUser()
	{
  	  global $Errors;

	  $sql = "SELECT max(CreatedOn) as LastDate FROM ".$this->SourceTable;
	  $result = $this->adodbConnection->Execute($sql);
	  if ($result === false || !is_object($result))
          {
            $Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
            return false;
          }
	  $sql = "SELECT PortalUserId FROM ".$this->SourceTable." WHERE CreatedOn >= ".$result->fields["LastDate"];
	  $result = $this->adodbConnection->Execute($sql);
	  if (!rs || $rs->EOF)
          {
            $Errors->AddError("error.DatabaseError",NULL,$adodbConnection->ErrorMsg(),"",get_class($this),"GetLatestUser");
            return false;
          }
          $u = $this->GetUser($result->fields["PortalUserId"]);
	  return $u;
	}

	function &Add_User($Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="", $Status=2, 
                      $Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0, $ip="", $CheckBanned=FALSE)
	{
		$u = new clsPortalUser(NULL);
		$u->tablename = $this->SourceTable;
        //echo "Creating User..<br>\n";
		$u->Set(array("Login", "Password", "FirstName", "LastName", "Email", "Status", 
                      "Phone","Street", "City", "State", "Zip", "Country", "CreatedOn","dob"), 
                array($Login, $Password, $FirstName, $LastName, $Email, $Status,  
                      $Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn, $dob));
	    
	    $BrokenRule = $CheckBanned ? $u->CheckBanned() : false;
	    if(!$BrokenRule)	
	    {	                 	     
		  $u->Create();
  		  return $u;
	    }
		return $BrokenRule;	    
		/*md5($Password)*/
	}

	function &Edit_User($UserId, $Login, $Password, $Email, $CreatedOn, $FirstName="", $LastName="",  
                       $Status=2, $Phone="", $Street="", $City="", $State="", $Zip="", $Country="", $dob=0, $MinPwResetDelay=300)
	{        
		//echo "<font color=\"red\">Editing User: [$UserId]</font><br>";
		
		$u =& $this->GetItem($UserId);
		
        if(!$CreatedOn)
            $CreatedOn = $u->Get("CreatedOn");
        
//        $u->debuglevel=1;  
          
		if (is_object($u))
		{
			$IsBanned = $u->Get('IsBanned');
			if($Status == 1) $IsBanned = 0;
			$u->Set(array("Login", "FirstName", "LastName", "Email", "Status", 
                          "Phone",  "Street", "City", "State", "Zip", "Country", "CreatedOn","dob","IsBanned", "MinPwResetDelay"), 
                    array($Login, $FirstName, $LastName, $Email, $Status, 
                          $Phone, $Street, $City, $State, $Zip, $Country, $CreatedOn,$dob,$IsBanned,$MinPwResetDelay));
			if(strlen($Password))
			  $u->Set("Password",$Password);   
			$u->Update();
		}
        return $u;		
	}

	function Delete_User($UserId)
	{
		$u = $this->GetItemByField("ResourceId",$UserId);
		if(is_object($u))
		{
		  $u->RemoveFromAllGroups();	
		  $u->Delete();
		}
	}


    function LoadUsers($where = "",$orderBy = "")
    {
        global $objConfig;

        $this->Clear();
        if($this->Page<1)
            $this->Page=1;

        if(is_numeric($objConfig->Get("Perpage_Users")))
        {
            $Start = ($this->Page-1)*$objConfig->Get("Perpage_Users");
            $limit = "LIMIT ".$Start.",".$objConfig->Get("Perpage_Users");
        }
        else
            $limit = NULL;

        $where = trim($where);
        $orderBy = trim($orderBy);
        if(!strlen($where))
            $where = "1";

        $this->QueryItemCount=TableCount($this->SourceTable,$where,0);

        if($this->QueryItemCount>0)
        {
            if ($orderBy!="")
            {
                $this->Query_PortalUser($where,$orderBy,$limit);
            }
            else
            {
                $this->Query_PortalUser($where,"Login DESC",$limit);
            }
        }
    }

    function Query_PortalUser($whereClause,$orderByClause="", $limitClause="")
    {
        global $m_var_list,$Errors, $objSession;

        $resultSet = array();

        $utable = $this->SourceTable;
        $gtable = GetTablePrefix()."UserGroup";
        $sql = "SELECT * FROM $utable LEFT JOIN $gtable ON ($utable.PortalUserId=$gtable.PortalUserId)";
        
        if(isset($whereClause))
            $sql = sprintf('%s WHERE %s',$sql,$whereClause);

        if(isset($orderByClause))
          if(strlen(trim($orderByClause))>0)
            $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);

        if(isset($limitClause))
            $sql = sprintf('%s %s',$sql,$limitClause);
        
        return $this->Query_Item($sql);
    }

    function Query_GroupPortalUser($whereClause,$orderByClause)
    {
        global $m_var_list,$objSession,$Errors;

        $resultSet = array();


        $table = $this->SourceTable;
        $sql = "SELECT * FROM $table LEFT JOIN ".GetTablePrefix()."UserGroup USING (PortalUserId) ";

        if(isset($whereClause))
            $sql = sprintf('%s WHERE %s',$sql,$whereClause);

        if(isset($orderByClause))
            $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
	
        return $this->query_item($sql);
    }

    function UserCount($whereClause)
    {
        $count = TableCount($this->SourceTable,$whereClause,0);
        return $count;
    }

    function CountActive()
    {
        return $this->UserCount("Status=1");
    }

    function CountPending()
    {
        return $this->UserCount("Status=2");
    }
    
    function CountDisabled()
    {
        return $this->UserCount("Status=0");
    }
    
    function CopyFromEditTable($idfield)
    {
        global $objSession;
		$GLOBALS['_CopyFromEditTable']=1;

        $edit_table = $objSession->GetEditTable($this->SourceTable);        
        $sql = "SELECT * FROM $edit_table";
        $rs = $this->adodbConnection->Execute($sql);
        
        //echo $sql."<BR>";
        
        while($rs && !$rs->EOF)
        {
            $data = $rs->fields;            
            $c = new $this->classname;
            $c->SetFromArray($data);
            $c->idfield = $idfield;
            $c->Dirty();
            if($c->Get($idfield)<1)
            {
               $old_id = $c->Get($idfield);
               $c->UnsetIdField();
               $c->Create();
               $sql = "UPDATE ".GetTablePrefix()."UserGroup SET PortalUserId=".$c->Get("PortalUserId");
               $sql .=" WHERE PortalUserId=0";
               $this->adodbConnection->Execute($sql);
            }
            else
              $c->Update();              
            unset($c);            
            $rs->MoveNext();
        }                
        @$this->adodbConnection->Execute("DROP TABLE IF EXISTS $edit_table");          
		unset($GLOBALS['_CopyFromEditTable']);
    }
    
    function PurgeEditTable()
    {
    	parent::PurgeEditTable();
    	$sql = "DELETE FROM ".GetTablePrefix()."UserGroup WHERE PortalUserId=0";
    	$this->adodbConnection->Execute($sql);
    }    	
} /*clsUserManager*/
?>