<?php
class clsPermission extends clsItemDB 
{
    var $Inherited;

    function clsPermission($PermissionId=NULL)
    {        
        $this->clsItemDB();
        $this->tablename = GetTablePrefix()."Permissions";
        $this->BasePermission="GRANT";
        $this->id_field = "PermissionId";
        $this->NoResourceId = 1;
        $this->Inherited=FALSE;
        if($PermissionId)
           $this->LoadFromDatabase($PermissionId);
    }
    
    function LoadFromDatabase($Id)
    {
		global $Errors;
       
        if(!isset($Id))
        {
            $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
            return false;
        }        
        $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
        $result = $this->adodbConnection->Execute($sql);
        if ($result === false)
        {
            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
            return false;
        }

        $data = $result->fields;

        $this->SetFromArray($data);
        $this->Clean();
        return true;
    }
}

class clsPermList extends clsItemCollection
{
    var $CatId;
    var $GroupId;
    var $CatBranch;

    function clsPermList($CatId=NULL,$GroupId=NULL)
    {
      $this->clsItemCollection();
      $this->classname = "clsPermission";
      $this->SourceTable = GetTablePrefix()."Permissions";
      $this->Clear();      
      $this->GroupId = $GroupId;
      $this->CatId = $CatId;
    }

    function GetPermId($PermName)
    {
        $val = 0;
        $sql = "SELECT PermissionConfigId,PermissionName FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName='$PermName'";
        //echo $sql."<br>\n";
        $rs = $this->adodbConnection->Execute($sql);
        if($rs && !$rs->EOF)
            $val = $rs->fields["PermissionConfigId"];
        return $val;
    }

    function GetPermByName($Perm)
    {
        foreach($this->Items as $p)
        {
            if($p->Get("Permission")==$Perm && $p->Get("GroupId")==$this->GroupId)
            {
                return $p;
            }
        }
        return false;
    }

    function AddItemFromArray($data)
    {
    	global $objCatList;
    	
        $p = new clsPermission();

        foreach($data as $field => $value)
           $p->Set($field,$value);
        if($data["Type"]==0)
        {        
          if($p->Get("CatId") != $this->CatId)
          {   
              $p->Inherited = TRUE;
          }
          else
             $p->Inherited = FALSE;
        }
        array_push($this->Items,$p);
    }

    function LoadCategory($Id)
    {
        if($this->GroupId == NULL)
        {
            $sql = "SELECT * FROM ".$this->SourceTable." WHERE CatId=$Id AND Type=0 AND GroupId IS NULL";
        }
        else
          $sql = "SELECT * FROM ".$this->SourceTable." WHERE CatId=$Id AND Type=0 AND GroupId=".$this->GroupId;

        $rs = $this->adodbConnection->Execute($sql);
        while ($rs && !$rs->EOF) 
        {            
            $data = $rs->fields;
            $current = $this->GetPermByName($data["Permission"]);
            if(!is_object($current))
            {
               $this->AddItemFromArray($data);
            }
            unset($current);
            $rs->MoveNext();
        }
    }    

    function LoadPermTree($c)
    {        
        /* load all permissions for group on this category */
        global $objCatList;

        $this->CatId=$c->Get("CategoryId");        
        $cats = explode("|",substr($c->Get("ParentPath"),1,-1));
        if(is_array($cats))
        {             
          $cats = array_reverse($cats);  
          $cats[] = 0;
          $this->CatBranch = $cats;
          foreach($cats as $catid)
          { 
            $this->LoadCategory($catid);
          }        
        }
    }
    
    function GetDefinedCategory($Perm,$GroupId)
    {
    	$ret = "";
    	if(is_array($this->CatBranch))
    	{
          for($index=0;$index<count($this->CatBranch);$index++)	
          {
          	foreach($this->Items as $p)
          	{
          		if($p->Get("Permission")==$Perm)
          		{
          		  if($p->Get("Permission")==$Perm && $p->Get("GroupId")==$GroupId && 
          		     $p->Get("CatId")==$this->CatBranch[$index])
          		  {
          		     $ret = $this->CatBranch[$index];
          		     break;
          	  	  }
          		}
          	}
          	if(is_numeric($ret))
          	  break;
          }
    	}
    	return $ret;
    }


    function GetPermissionValue($PermName)
    {
      $p = $this->GetPermByName($PermName);
      if(!is_object($p))
      {
          $ret = NULL;
      }
      else
          $ret = $p->Get("PermissionValue");
      return $ret;
    }

    function LoadSystemPermissions()
    {
        $sql = "SELECT * FROM Permissions WHERE Type=1 AND GroupId=".$this->GroupId;
        $rs = $this->adodbConnection->Execute($sql);
        $this->clear();
        $this->CatId=NULL;
        while($rs && !$rs->EOF)
        {
            $data = $rs->fields;
            $this->AddItemFromArray($data);
        }
    }

    function Add_Permission($CategoryId,$GroupId,$PermName,$Value,$Type)
    {
        $p = new clsPermission();
        $p->Set(array("CatId","GroupId","Permission","PermissionValue","Type"),
                array($CategoryId,$GroupId,$PermName,$Value,$Type));
        $p->Create();
        array_push($this->Items,$p);
        return $p;
    }

    function Edit_Permission($PermissionId,$CategoryId,$GroupId,$PermName,$Value,$Type)
    {
        $p = $this->GetItem($PermissionId);
        if(is_object($p))
        {
         $p->Set(array("CatId","GroupId","Permission","PermissionValue","Type"),
                 array($CategoryId,$GroupId,$PermName,$Value,$Type));
         $p->Update();
        }
        return $p;
    }

    function Delete_Permission($PermissionId)
    {
        $p = $this->GetItem($PermissionId);
        if(is_object($p))
        {
            $p->Delete();
        }
    }

    function Copy_Permissions($SrcCat,$DestCat)
    {
       $sql = "DELETE FROM ".$this->SourceTable." WHERE CatId=$DestCat";
       $this->adodbConnection->Execute($sql);
       $sql = "SELECT * FROM ".$this->SourceTable." WHERE CatId=".$SrcCat;
       $rs = $this->adodbConnection->Execute($sql);
       while($rs && !$rs->EOF)
       {
           $data = $rs->fields;
           $this->Add_Permission($DestCat,$data["GroupId"],$data["Permission"],$data["PermissionValue"],$data["Type"]);
           $rs->MoveNext();
       }
    }

    function Delete_CatPerms($CatId)
    {
       $sql = "DELETE FROM ".$this->SourceTable." WHERE CatId=$CatId";
       $this->adodbConnection->Execute($sql);       
    }

    /* return an array of group ids which have access to permission $perm for a category*/
    function GetGroupPermList($c, $Perm, $AllGroups)
    {
        $ret = array();
        $this->Clear();        
        if(strlen($Perm) && count($AllGroups))
        {
           for($i=0;$i<count($AllGroups);$i++)
           {
               $this->CatId=$c->Get("CategoryId");
               $this->GroupId = $AllGroups[$i];
               $this->LoadPermTree($c);
               if($this->GetPermissionValue($Perm)==1)
               {               
                   $ret[] = $AllGroups[$i];
               }
           }
        }
        return $ret;
    }

    function GetAllViewPermGroups($c, $AllGroups)
    {
        $perms = array();
        $sql = "SELECT PermissionConfigId, PermissionName FROM ".GetTablePrefix()."PermissionConfig WHERE PermissionName LIKE '%.VIEW'";
        //echo $sql."<br>\n";
        $rs = $this->adodbConnection->Execute($sql);
        while($rs && !$rs->EOF)
        {
            $perms[$rs->fields["PermissionName"]] = $this->GetGroupPermList($c,$rs->fields["PermissionName"],$AllGroups);
            $rs->MoveNext();
        }
        return $perms;
    }
}

class clsPermCache extends clsItemDB 
{
    function clsPermCache($id=NULL)
    {
        $this->clsItemDB();
        $this->tablename = GetTablePrefix()."PermCache";
        $this->BasePermission="GRANT";
        $this->id_field = "PermCacheId";
        $this->NoResourceId = 1;

        if($id)
           $this->LoadFromDatabase($id);
    }
    
    function LoadFromDatabase($Id)
    {
		global $Errors;
       
        if(!isset($Id))
        {
            $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromDatabase");
            return false;
        }        
        $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ".$this->IdField()." = '%s'",$Id);
        $result = $this->adodbConnection->Execute($sql);
        if ($result === false)
        {
            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
            return false;
        }

        $data = $result->fields;

        $this->SetFromArray($data);
        $this->Clean();
        return true;
    }
}

class clsPermCacheList extends clsItemCollection 
{
    function clsPermCacheList()
    {
      $this->clsItemCollection();
      $this->classname = "clsPermCache";
      $this->SourceTable = GetTablePrefix()."PermCache";
      $this->Clear();   
    }

    function &GetPerm($CategoryId,$PermId)
    {
        $found = FALSE;
        foreach($this->Items as $p)
        {
          if($p->Get("CategoryId")==$CategoryId && $p->Get("PermId")==$PermId)
          {
              $found = TRUE;
              break;
          }
        }
        if(!$found)
        {
            $sql = "SELECT * FROM ".$this->SourceTable." WHERE CategoryId=$CategoryId AND PermId=$PermId";
            $rs = $this->adodbConnection->Execute($sql);
            if($rs && !$rs->EOF)
            {
                $data = $rs->fields;
                $p = $this->AddItemFromArray($data);
            }
            else
                $p = FALSE;
        }
        return $p;
    }

    function &AddPermCache($CatId,$PermId,$Acl,$Dacl)
    {
        if(strlen($Acl)>0 || strlen($Dacl)>0)
        {        
          $p = new $this->classname;
          $p->Set(array("CategoryId","PermId","ACL","DACL"),array($CatId,$PermId,$Acl,$Dacl));
          $p->Create();        
          return $p;
        }
        else
            return FALSE;
    }

    function EditPermCache($PermCacheId,$CatId,$PermId,$Acl,$Dacl)
    {
        if($PermCacheId)
        {        
          $p = $this->GetItem($PermCacheId);
          if(is_object($p))
          {
              $p->Set(array("CategoryId","PermId","ACL","DACL"),array($CatId,$PermId,$Acl,$Dacl));
              $p->Update();
          }
        }
    }

    function DeletePermCache($PermCacheId)
    {
        if($PermCacheId)
        {        
          $p = $this->GetItem($PermCacheId);
          if(is_object($p))
          {
              $p->Delete();
          }
        }
    }

    function DeleteCategory($CategoryId)
    {
        $this->adodbConnection->Execute("DELETE FROM ".$this->SourceTable." WHERE CategoryId=$CategoryId");
    }

    function CopyCategory($SourceCat,$DestCat)
    {
        $this->Clear();
        $this->Query_Item("SELECT * FROM ".$this->SourceTable." WHERE CategoryId=$SourceCat");
        if($this->NumItems()>0)
        {
            foreach($this->Items as $p)
            {
                $p->UnsetIdField();
                $p->Set("CategoryId",$DestCat);
                $p->Create();
            }
        }
    }
}
?>