<?php

class clsImage extends clsParsedItem
{
	var $Pending;
	
	function clsImage($id=NULL)
	{	
        global $objSession;

        $this->clsParsedItem();
        $this->tablename = GetTablePrefix()."Images";
        $this->Pending = FALSE;
        $this->id_field = "ImageId";
        $this->type=-30;
        $this->TagPrefix = "image";
        $this->NoResourceId=1;
        if($id)
			$this->LoadFromDatabase($id); 
        //$this->SetDebugLevel(0);
	}
		
	function GetFileName($thumb = 0)
	{
		global $pathtoroot;

		if($thumb)
		{
			$p = $this->Get("ThumbPath");
		}
		else
		{
		  $p = $this->Get("LocalPath");		  
		  if(!strlen($p) && $this->Get("SameImages"))
		  {
		  	$p = $this->Get("ThumbPath");
		  }
		}
		
		if(strlen($p))
		{
			$parts = pathinfo($pathtoroot.$p);
			$filename = $parts["basename"];
		}
		else
			$filename = "";
		
		return $filename;
	}
		
	function GetImageDir()
	{
		global $pathtoroot;
		
		$p = $this->Get("ThumbPath");
		if(strlen($p))
		{
			$parts = pathinfo($pathtoroot.$p);
			$d = $parts["dirname"]."/";
		}
  	  
		if($this->Pending)
		  $d .= "pending/";
		  
		return $d;  
	}
	
	
	function Delete()
	{	        	
        $this->DeleteLocalImage();
        parent::Delete();
	}
		
	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 ImageId = '%s'",$Id);

        $result = $this->adodbConnection->Execute($sql);
        if ($result === false || $result->EOF)
        {
            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromDatabase");
            return false;
        }
        
		$data = $result->fields;
       
        $this->SetFromArray($data);
        $this->Clean();
        return true;
    }

	function LoadFromResource($Id,$ImageIndex)
    {
        global $Errors;

        if(!isset($Id) || !isset($ImageIndex))
        {
            $Errors->AddError("error.AppError",NULL,'Internal error: LoadFromDatabase id',"",get_class($this),"LoadFromResource");
            return false;
        }

        $sql = sprintf("SELECT * FROM ".$this->tablename." WHERE ResourceId = '%s'AND ImageIndex = '%s'",$Id,$ImageIndex);

        $result = $this->adodbConnection->Execute($sql);
        if ($result === false || $result->EOF)
        {
//            $Errors->AddError("error.DatabaseError",NULL,$this->adodbConnection->ErrorMsg(),"",get_class($this),"LoadFromResource");
            return false;
        }

		$data = $result->fields;

        $this->SetFromArray($data);

        return true;
    }

    function LocalImageExists()
    {
        global $objConfig, $pathtoroot;
        $result=FALSE;
        if($this->Get("LocalImage")==1 && $this->Get("SameImages")==0)
        {        
          //$imagepath = $pathtoroot.$this->Get("LocalPath");
          $imagepath = $this->GetImageDir().$this->GetFileName();
          
//          echo "PATH: ".$this->GetImageDir()."; FILE: ".$this->GetFileName()."<BR>";
          
          if(strlen($imagepath)>0)
          {
             $result = file_exists($imagepath);
          }
        }
       return $result;
    }

    function LocalThumbExists()
    {
        $result=FALSE;
        global $objConfig, $pathtoroot;

        if($this->Get("LocalThumb")==1)
        {        
          //$imagepath = $pathtoroot.$this->Get("ThumbPath");   
          $imagepath = $this->GetImageDir().$this->GetFileName(1);       
          if(strlen($imagepath)>0)
          {
             $result = file_exists($imagepath);
          }
        }
       return $result;
    }

    
    function DeleteLocalImage($Thumb=TRUE,$Full=TRUE)
    {
        global $pathtoroot;
        
        if($Full)
        {
          if($this->LocalImageExists())
          {
            $filename = $this->GetImageDir().$this->GetFileName(); 
//            echo "FULL: $filename<BR>\n"; 
            @unlink($filename);
          }
        }
        
        if($Thumb)
        {
          if($this->LocalThumbExists())
          {
            $filename  = $this->GetImageDir().$this->GetFileName(1);
//             echo "THUMB: $filename<BR>\n";
            @unlink($filename);
          }
        }
    }

    function StoreUploadedImage($file, $rewrite_name=1,$DestDir,$IsThumb=0,$IsUpload=TRUE)
    {   
        /* move the uploaded image to its final location and update the LocalPath property */
        /* returns the destination filename on success */
        global $objConfig,$pathtoroot;

        $Dest_Dir = $DestDir;
        if($this->Pending)
          $Dest_Dir .= "pending/";
          
        if(((int)$file["error"]==0) && (substr($file["type"],0,6)=="image/"))
        {        
          $parts = pathinfo($file["name"]);
          $ext = strtolower($parts["extension"]);
		
		  if((int)$_GLOBALS["debuglevel"])
			echo "Processing ".$file["tmp_name"]."<br>\n";

          if($rewrite_name==1)
          {

            if($IsThumb)
                $filename = "th_";
            $filename .= $this->Get("ResourceId")."_".$this->Get("ImageIndex").".".$ext;
          }
          else
          {
            $filename = $file["name"];
          }
          $destination = $pathtoroot.$Dest_Dir.$filename;
		  if((int)$_GLOBALS["debuglevel"])
			echo $file["tmp_name"]."=>".$destination."<br>\n";
          if(IsUpload==TRUE)
          {          
            $result = @move_uploaded_file($file["tmp_name"],$destination);
          }
          else
              $result = copy($file["tmp_name"],$destination);
          if($result)
          {  
             return $Dest_Dir.$filename;
          }
          else
            return "";
        }
        else
            return "";
    }
    
    function CopyToPending()
    {
    	global $pathtoroot;
    	
    	$ThumbPath = (strlen($this->Get("ThumbPath"))>0) ? $pathtoroot.$this->Get("ThumbPath") : '';
        $FullPath =	strlen($this->Get("LocalPath")) ? $pathtoroot.$this->Get("LocalPath") : '';
        
        $dest = $this->GetImageDir()."pending/";
        
        
//        echo "DESTIN DIR: $dest<BR>";
//        echo "THUMB PATH: $ThumbPath <BR>";
        
        if(strlen($ThumbPath))
        {
          if(file_exists($ThumbPath))
          {
        	$p = pathinfo($ThumbPath);
        	$d = $dest.$p["basename"];
        	if(file_exists($d))
        		unlink($d);
        	copy($ThumbPath,$d);
          }
        } 
             
        
        if(strlen($FullPath))
        {
          if(file_exists($FullPath))
          {
        	$p = pathinfo($FullPath);
        	$d = $dest.$p["basename"];
        	if(file_exists($d))
        	  unlink($d);   
        	copy($FullPath,$d);        	
          }
        }        
    }
    
    function CopyFromPending()
    {
    	global $pathtoroot,$pathchar;
    	
        $ThumbPath = $this->Get("ThumbPath");
        $FullPath = $this->Get("LocalPath");
        
//        $src = $this->GetImageDir()."pending/"; 
        $src = $this->GetImageDir(); 
              
        if(strlen($ThumbPath))
        {
          if(strpos($ThumbPath,"pending/"))
          {	
            if(file_exists($pathtoroot.$ThumbPath))
            {
          		$path = pathinfo($pathtoroot.$ThumbPath);
        		$p = explode("/",$ThumbPath);
        		unset($p[count($p)-2]);
        	
        		$d = $pathtoroot.implode("/",$p);
        		
        		if(file_exists($d))
        	  		unlink($d);
        	
    	    	copy($pathtoroot.$ThumbPath,$d);
        	
        		unlink($pathtoroot.$ThumbPath);
            }

          }
        }
        if(strlen($FullPath))
        {
          if(file_exists($pathtoroot.$FullPath))
          {
            if(strpos($FullPath,"pending/"))
            {	          	
	         	$path = pathinfo($pathtoroot.$FullPath);
    	    	$p = explode("/",$FullPath);
        		unset($p[count($p)-2]);
        	
	        	$d = $pathtoroot.implode("/",$p);

	        	if(file_exists($d))
    	    	  unlink($d);
    	    	copy($pathtoroot.$FullPath,$d);        	
        		unlink($pathtoroot.$FullPath);
            }
          }
        }            	
    }
    
    function DeleteFromPending()
    {
        $ThumbPath = $pathtoroot.$this->Get("ThumbPath");
        $FullPath = $pathtoroot.$this->Get("LocalPath");
        
        $src = $this->GetImageDir()."pending/";
        $p = pathinfo($ThumbPath);
        $d = $src.$p["basename"];
		if(file_exists($d))
		  @unlink($d);

        $p = pathinfo($FullPath);
        $d = $src.$p["basename"];
		if(file_exists($d))
		  @unlink($d);		  
    }

    function RenameFiles($OldResId,$NewResId)
    {
        global $pathtoroot;

        if($this->Pending)
        {
        	$ThumbPath = $this->GetImageDir().$this->GetFileName(TRUE);
        }
        else
        	$ThumbPath = $pathtoroot.$this->Get("ThumbPath");
        $parts = pathinfo($ThumbPath);
        $ext = $parts["extension"];
        $pending="";
        if($this->Pending)
        {
          $pending="pending/";
          $FullPath = $this->GetImageDir().$this->GetFileName(FALSE);
        }
        else
          $FullPath = $pathtoroot.$this->Get("LocalPath");
          
        $NewThumb = $pathtoroot."kernel/images/".$pending."th_$NewResId_".$this->Get("ImageIndex").".$ext";
        $NewFull = $pathtoroot."kernel/images/".$pending."$NewResId_".$this->Get("ImageIndex").".$ext";
        if(file_exists($ThumbPath))
        {
          @rename($ThumbPath,$NewThumb);          
        }
        
        if(file_exists($FullPath))
        {
        	@rename($FullPath,$NewFull);
        }
        
    }

    function ReplaceImageFile($file)
    {
        global $objConfig;

        if($file["error"]==0)
        {        
          $this->DeleteLocalImage();
          move_uploaded_file($file,$this->Get("LocalPath"));
        }
    }

    function FullURL($ForceNoThumb=FALSE,$Default="kernel/images/noimage.gif")
    {
        global $rootURL, $objConfig,$pathtoroot;

        if($this->Get("SameImages") && !$ForceNoThumb)
            return $this->ThumbURL();

        if(strlen($this->Get("Url")))
            return $this->Get("Url");
        if($this->Get("LocalImage")=="1")
        {
        	$url = $this->Get("LocalPath");        	
            //$url = $this->GetImageDir().$this->GetFileName();
            if(file_exists($pathtoroot.$url))
            {            
              if(strlen($url))
              {                          	
                $url = $rootURL.$url;
                return $url;                
              }
              else
              {
              	if(strlen($Default))
                	$url = $rootURL.$Default;
                return $url;
              }
            }
            else
            {
              if(strlen($Default))	
              {
              	return $rootURL.$Default;
              }
              else
              	return "";
            }
        }
        else
        {
          if(strlen($Default))
          {
            return $rootURL.$Default;
          }
          else 
            return "";
        }
    }

    function ThumbURL()
    {
        global $rootURL, $pathtoroot, $objConfig;

        if(strlen($this->Get("ThumbUrl")))
            return $this->Get("ThumbUrl");

        if($this->Get("LocalThumb")=="1")
        {
            $url = $this->Get("ThumbPath");
            //$url = $this->GetImageDir().$this->GetFileName();
            if(file_exists($pathtoroot.$url))
            {            
              if(strlen($url))
              {            
                $url = $rootURL.$url;
              }
              else
                $url = $rootURL."kernel/images/noimage.gif";
              return $url;
            }
            else
              return $rootURL."kernel/images/noimage.gif";
        }
        else
          return $rootURL."kernel/images/noimage.gif";
    }

    function ParseObject($element)
    {    
        $extra_attribs = ExtraAttributes($element->attributes);
        if(strtolower($element->name)==$this->TagPrefix)
        {          
            $field = strtolower($element->attributes["_field"]);          
            switch($field)
            {  
            case "name":
                $ret = $this->Get("Name");
                break;
            case "alt":
                $ret = $this->Get("AltName");
                break;
            case "full_url":
                $ret = $this->FullURL();
                break;
            case "thumb_url":
                $ret = $this->ThumbURL();
                break;
            }
        }
        else
            $ret = $element->Execute();
        return $ret;
    }

    function parsetag($tag)
    {
        if(is_object($tag))
        {        
            $tagname = $tag->name;
        }
        else
            $tagname = $tag;
        switch($tagname)
        {
          case "image_name":
            $ret = $this->Get("Name");
            break;
          case "image_alt":            
            $ret = $this->Get("AltName");
            break;
          case "image_url":
            $ret = $this->FullURL();
            break;
          case "thumb_url":
            $ret = $this->ThumbURL();
            break;
        }
        return $ret;
    }

    //Changes priority
    function MoveUp()
    {
        $this->Increment("Priority");
    }

    function MoveDown()
    {
         $this->Decrement("Priority");
    }

    function GetMaxPriority()
    {
        $SourceId = $this->Get("ResourceId");
        $sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
        $result = $this->adodbConnection->Execute($sql);
        return $result->fields["p"];
    }

    function GetMinPriority()
    {
        $SourceId = $this->Get("ResourceId");
        $sql = "SELECT MIN(Priority) as p from ".$this->tablename."WHERE ResourceId=$SourceId";
        $result = $this->adodbConnection->Execute($sql);
        return $result->fields["p"];
    }

    function UpdatePriority()
    {
      $SourceId = $this->Get("ResourceId");
      $sql = "SELECT MAX(Priority) as p from ".$this->tablename."WHERE ReourceId=$SourceId";
      $result = $this->adodbConnection->Execute($sql);
      $this->Set("Priority", $result->fields["p"]+1);
    }
}

class clsImageList extends clsItemCollection
{
    var $Page;
    var $PerPageVar;

    function clsImageList()
    {
        $this->clsItemCollection();
        $this->PerPageVar = "Perpage_Images";
        $this->SourceTable = GetTablePrefix()."Images";
        $this->classname = "clsImage";
    }

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

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

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


      $this->QueryItemCount=TableCount("Images",$where,0);
      //echo $this->QueryItemCount."<br>\n";
      if(strlen(trim($orderBy))>0)
      {
        $orderBy = "Priority DESC, ".$orderBy;
      }
      else
        $orderBy = "Priority DESC";

     return $this->Query_Images($where,$orderBy,$limit);
    }

    function Query_Images($whereClause,$orderByClause=NULL,$limit=NULL)
    {
        global $objSession, $Errors;

        $sql = "SELECT * FROM ".$this->SourceTable;

        if(isset($whereClause))
            $sql = sprintf('%s WHERE %s',$sql,$whereClause);
        if(isset($orderByClause) && strlen(trim($orderByClause))>0)
            $sql = sprintf('%s ORDER BY %s',$sql,$orderByClause);
        if(isset($limit) && strlen(trim($limit)))
            $sql .= " ".$limit;
        //echo $sql;
        return $this->Query_Item($sql);
    }

    function &Add($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
                 $Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
                 $SameImages=0, $ImageId=-999)
    {
		if($DefaultImg==1)
		{
    		$sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=$ResourceId";
    		$this->adodbConnection->Execute($sql);
		}    	
		
        $img = new clsImage();
        $img->tablename = $this->SourceTable;
        $img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
                        "Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
                  array($Name,$Alt,$ResourceId,$LocalImage,$LocalThumb,
                        $Url,$ThumbUrl,$Enabled,$Priority,$DefaultImg,$ImageIndex,$SameImages));
                        
        if ($ImageId != -999)
        {
        	$img->Set("ImageId", $ImageId); 
        }

        if((int)$ImageIndex==0)        
            $img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
        $img->Create();
        array_push($this->Items,$img);
        return $img;
    }
                 

    function Edit($ImageId,$Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,  
                  $Url, $ThumbUrl, $Enabled=1, $Priority=0, $DefaultImg=0, $ImageIndex=0,
                  $SameImages=0)
    {
        $img = $this->GetItem($ImageId);
        
        if((int)$ImageIndex==0)
             $ImageIndex = $img->Get("ImageIndex");
             
        if(!strlen($ThumbUrl) && !$LocalThumb)
            $ThumbUrl = $img->Get("ThumbUrl");
            
        $img->Set(array("Name","AltName","ResourceId","LocalImage","LocalThumb",
                        "Url","ThumbUrl","Enabled","Priority","DefaultImg","ImageIndex","SameImages"),
                  array($Name, $Alt, $ResourceId, $LocalImage, $LocalThumb,
                        $Url, $ThumbUrl, $Enabled, $Priority, $DefaultImg, $ImageIndex,$SameImages));
                        
        if((int)$ImageIndex==0)        
            $img->Set("ImageIndex",$this->GetNextImageIndex($ResourceId));
            
        $img->Update();
        
        if($DefaultImg==1)
        {
            $sql = "UPDATE ".$this->SourceTable." SET DefaultImg=0 WHERE ResourceId=".$ResourceId." AND ImageId !=$ImageId";
            $this->adodbConnection->Execute($sql);
        }
        array_push($this->Items,$img);
        
        return $img;
    }

    function Delete_Image($ImageId)
    {
        $i = $this->GetItem($ImageId);
        $i->Delete();
    }

    function DeleteResource($ResourceId)
    {
        $this->Clear();
        $images = $this->Query_Images("ResourceId=".$ResourceId);
        if(is_array($images))
        {
          foreach($images as $i)
          {
            $i->Delete();
          }
        }
    }
    
    function LoadResource($ResourceId)
    {
        $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId";
        $this->Query_Item($sql);
    }

    function CopyResource($SourceId,$DestId)
    {    	
    	global $pathtoroot;
    	
        $this->Clear();
        $this->LoadResource($SourceId);
        foreach($this->Items as $i)
        {
           if($i->Get("LocalThumb"))
           {
           	 $f = $pathtoroot.$i->Get("ThumbPath");
           	 if(file_exists($f))
           	 {
           	 	$p = pathinfo($f);
           	 	$dir = $p["dirname"];
           	 	$ext = $p["extension"];
           	 	$newfile = $dir."/th_".$DestId."_".$i->Get("ImageIndex").".".$ext;
           	 	if(file_exists($newfile))
           	 	  @unlink($newfile);
//           	 	echo $f." -> ".$newfile;  
           	 	copy($f,$newfile);  
           	 }           	 	
           }	
           if($i->Get("LocalImage"))
           {
           	 $f = $pathtoroot.$i->Get("LocalPath");
           	 if(file_exists($f))
           	 {
           	 	$p = pathinfo($f);
           	 	$dir = $p["dirname"];
           	 	$ext = $p["extension"];
           	 	$newfile = $dir."/".$DestId."_".$i->Get("ImageIndex").".".$ext;
           	 	if(file_exists($newfile))
           	 	  @unlink($newfile);
           	 	  
//           	 	echo $f." -> ".$newfile;
           	 	copy($f,$newfile);  
           	 }           	 	           	
           }
        }        
        parent::CopyResource($SourceId,$DestId);        
        $this->Clear();
        $this->LoadResource($DestId);
        foreach($this->Items as $img)
        {
        	if($img->Get("LocalThumb"))
        	{
        		$f = str_replace("th_$SourceId","th_$DestId",$img->Get("ThumbPath"));
        		$img->Set("ThumbPath",$f);
        	}	
        	if($img->Get("LocalImage"))
        	{
        		$f = str_replace("/".$SourceId."_","/".$DestId."_",$img->Get("LocalPath"));
        		$img->Set("LocalPath",$f);
        	}
        	$img->Update();
        }
    }

    function GetImageByResource($ResourceId,$Index)
    {
      $found=FALSE;
      if($this->NumItems()>0)
      {
        foreach($this->Items as $i)
        {
            if($i->Get("ResourceID")==$ResourceId and ($i->Get("ImageIndex")==$Index))
            {
                $found=TRUE;
                break;
            }
          }
        }
        if(!$found)
        {
            $i = NULL;
            $i = new clsImage();
            if($i->LoadFromResource($ResourceId,$Index))
            {
              array_push($this->Items, $i);
            }
            else
                unset($i);
        }
        if(is_object($i))
        {
          return $i;
        }
        else
            return FALSE;
    }

    function &GetDefaultImage($ResourceId)
    {
        $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND DefaultImg=1";
        $rs = $this->adodbConnection->Execute($sql);
        if($rs && ! $rs->EOF)
        {
            $data = $rs->fields;
            $img= new clsImage();
            $img->SetFromArray($data);
            $img->Clean();            
            return $img;
        }
        else
            return FALSE;

    }
    function HandleImageUpload($FILE,$ResourceId,$RelatedTo,$DestDir, $Name="",$AltName="",$IsThumb=0)
    {
      global $objConfig;

      $img = $this->GetImageByResource($ResourceId,$RelatedTo);

      if(is_object($img) && $RelatedTo>0)
      {
        $img->Set("LocalImage",1);
        $img->Set("Name",$Name);
        $img->Set("AltName",$AltName);
        $img->Set("IsThumbnail",$IsThumb);
        $dest =  $img->StoreUploadedImage($FILE,1,$DestDir);
        if(strlen($dest))
        {        
          $img->Set("Url", $objConfig->Get("Site_Path").$dest);
          $img->Update();
        }
      }
      else
      {
          $img=$this->NewLocalImage($ResourceId,$RelatedTo,$Name,$AltName,$IsThumb,$FILE,$DestDir);
      }
      return $img;
    }

    function GetResourceImages($ResourceId)
    {
        $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
        $rs = $this->adodbConnection->Execute($sql);
        while($rs && !$rs->EOF)
        {
            $img = new clsImage();
            $img->LoadFromResource($ResourceId,$rs->fields["RelatedTo"]);
            array_push($this->Images,$img);
            $rs->MoveNext();
        }
    }

    function GetResourceThumbnail($ResourceId)
    {
        $found=FALSE;
        foreach($this->Images as $img)
        {
            if($img->Get("ResourceId")==$ResourceId && $img->Get("IsThumbnail")==1)
            {
                $found=TRUE;
                break;
            }
        }
        if($found)
        {
          return $img;
        }
        else
            return FALSE;
    }

    function &GetImageByName($ResourceId,$name)
    {
        $found = FALSE;
        foreach($this->Items as $img)
        {
            if($img->Get("ResourceId")==$ResourceId && $img->Get("Name")==$name)
            {
                $found=TRUE;
                break;
            }
        }
        if($found)
        {
            return $img;
        }
        else
        {
          $sql = "SELECT * FROM ".$this->SourceTable." WHERE ResourceId=$ResourceId AND Name LIKE '$name'";
          //echo $sql;
          $rs = $this->adodbConnection->Execute($sql);
          if($rs && !$rs->EOF)
          {
            $img = $this->AddItemFromArray($rs->fields);            
            return $img;
          }
          else
              return FALSE;
        }
    }
    
    function CopyToPendingFiles()
    {
       $sql = "SELECT * FROM ".$this->SourceTable;
       $this->Clear();
       $this->Query_Item($sql);
       foreach($this->Items as $i)
       {
       	  if(strlen($i->Get("LocalImage")) || strlen($i->Get("LocalThumb")))
       	  {
       	  	 $i->CopyToPending();
       	  }
       }
    }

    function CopyFromPendingFiles($edit_table)
    {
       $sql = "SELECT * FROM ".$edit_table;
       $this->Clear();
       $this->Query_Item($sql);
       foreach($this->Items as $i)
       {
       	  
       	  ## Delete original Images
       	  $OrgImage = new clsImage($i->Get("ImageId"));
       	  $OrgImage->DeleteLocalImage();
       	
       	 if($i->Get("LocalImage") || $i->Get("LocalThumb"))
       	 {
       	  	$i->CopyFromPending();
       	  	 
       	  	$t = $i->Get("LocalPath");       	  	 
       	  	$p = pathinfo($t);
       	  	$p_arr = explode("/", $p['dirname']);
       	  	if (eregi("pending", $p_arr[count($p_arr)-1]))
     		{
     		 	unset($p_arr[count($p_arr)-1]);
     		 	$p['dirname'] = implode("/", $p_arr);
     			$LocalPath = $p['dirname']."/".$p['basename'];     			
     			$i->Set("LocalPath", $LocalPath); 	
     		} 
     		 
       	  	$t = $i->Get("ThumbPath");       	  	  
       	  	$p = pathinfo($t);
       	  	 
       	  	$p_arr = explode("/", $p['dirname']);
       	  	if (eregi("pending", $p_arr[count($p_arr)-1]))
     		{
     		 	unset($p_arr[count($p_arr)-1]);
     		 	$p['dirname'] = implode("/", $p_arr);
     			$ThumbPath = $p['dirname']."/".$p['basename'];     			
     			$i->Set("ThumbPath", $ThumbPath); 	
     		 }        	  	 
       	  	 
       	  	 $i->tablename = $edit_table;
       	  	 
       	  	 $update = 1;       	  	 
       	  }
       	 
       	 ## Empty the fields if are not used
       	 if (!$i->Get("LocalImage"))
	     {
	       	$i->Set("LocalPath", "");
	     	$update = 1;
	     }
	     
       	 if (!$i->Get("LocalThumb"))
       	 {
       	 	$i->Set("ThumbPath", "");
       	   	$update = 1;	
       	 }
       	  	
       	 if ($update)
       	 	$i->Update();  
       	 
       }
    }    
    
    function DeletePendingFiles($edit_table)
    {
       $sql = "SELECT * FROM ".$edit_table;
       $this->Clear();
       $this->Query_Item($sql);
       foreach($this->Items as $i)
       {
     	  	$i->DeleteFromPending();
       }
    }    	
    
    function CopyToEditTable($idfield, $idlist)
    {
        global $objSession;

        $edit_table = $objSession->GetEditTable($this->SourceTable);
        @$this->adodbConnection->Execute("DROP TABLE $edit_table");
        if(is_array($idlist))
        {
          $list = implode(",",$idlist);
        }
        else
             $list  = $idlist;
        $query = "SELECT * FROM ".$this->SourceTable." WHERE $idfield IN ($list)";
        $insert = "CREATE TABLE ".$edit_table." ".$query;
        if($objSession->HasSystemPermission("DEBUG.LIST"))
            echo htmlentities($insert,ENT_NOQUOTES)."<br>\n";
        $this->adodbConnection->Execute($insert);        
        $this->SourceTable = $edit_table;
        $this->CopyToPendingFiles();
                
        $this->UpdateFilenamesToPendings();
    }    
    
    function UpdateFilenamesToPendings()
    {
    	global $objSession;
    	
    	$edit_table = $this->SourceTable;
    	
    	$sql = "SELECT * FROM ".$edit_table."  WHERE (LocalPath!='' AND LocalPath IS NOT NULL) OR (ThumbPath!='' AND ThumbPath IS NOT NULL)";
       	$this->Clear();
       	$this->Query_Item($sql);

       	foreach($this->Items as $i)
       	{
       		$set = "";
       		$ImageId = $i->Get("ImageId");
       		
       		## Update Local Image Path -> add "pending/" to PATH
       		if (strlen($i->Get("LocalPath")))
       		{
       			$p = pathinfo($i->Get("LocalPath"));       			
     			if (!eregi("/pending $", $p['dirname']))
     			{
     				$LocalPath = $p['dirname']."/pending/".$p['basename'];     			
     				$set = "SET LocalPath='$LocalPath'";	
     			}  
       		}
       		
//       		echo "LocalImage: ".$i->Get("LocalImage").", PATH: ".$i->Get("LocalPath")."<BR>";
       		
       		## Update Local Thumb Path -> add "pending/" to PATH
       		if (strlen($i->Get("ThumbPath")))
       		{
     			$p = pathinfo($i->Get("ThumbPath"));       			
     			if (!eregi("/pending $", $p['dirname']))
     			{
     				$LocalThumb = $p['dirname']."/pending/".$p['basename'];
     				if (strlen($set))
     					$set.= ", ThumbPath='$LocalThumb'";	
     				else
     					$set = "SET ThumbPath='$LocalThumb'";	
     			}   		    			
       		}
       		
//       		echo "LocalThumb: ".$i->Get("LocalThumb").", PATH: ".$i->Get("ThumbPath")."<BR>";
       		
       		if (strlen($set))
       		{
       			$sql = "UPDATE $edit_table $set WHERE ImageId=$ImageId";
       			if($objSession->HasSystemPermission("DEBUG.LIST"))
            		echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
        		$this->adodbConnection->Execute($sql);        
       		}
       	}	
    }
    
    function CopyFromEditTable($idfield)
    {    	
        global $objSession;        
        
        $edit_table = $objSession->GetEditTable($this->SourceTable);
        $dummy =& $this->GetDummy();
        if( !$dummy->TableExists($edit_table) )
        {
        	echo 'ERROR: Table "<b>'.$edit_table.'</b>" missing (class: <b>'.get_class($this).'</b>)<br>';	
        	//exit;
        	return;
        }
        
        $rs = $this->adodbConnection->Execute("SELECT * FROM $edit_table WHERE ResourceId=0");
        while($rs && !$rs->EOF)
        {
        	$id = $rs->fields["ImageId"];
        	if($id>0)
        	{
        		$img = $this->GetItem($id);
        		$img->Delete();
        	}
        	$rs->MoveNext();
        }
        $this->adodbConnection->Execute("DELETE FROM $edit_table WHERE ResourceId=0");
        $this->CopyFromPendingFiles($edit_table);
        parent::CopyFromEditTable($idfield);
    }    
    
    function PurgeEditTable($idfield)
    {
      global $objSession;

      $edit_table = $objSession->GetEditTable($this->SourceTable);
	  $this->DeletePendingFiles($edit_table);
      @$this->adodbConnection->Execute("DROP TABLE $edit_table");
    }    
    
    function GetNextImageIndex($ResourceId)
    {
        $sql = "SELECT MAX(ImageIndex) as MaxVal FROM ".$this->SourceTable." WHERE ResourceId=".$ResourceId;
        $rs = $this->adodbConnection->Execute($sql);
        if($rs)
        {
            $val = (int)$rs->fields["MaxVal"];
            $val++;
        }
        return $val;
    }

    function GetMaxPriority($ResourceId)
    {     
      $sql = "SELECT MAX(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
      $result = $this->adodbConnection->Execute($sql);
      return $result->fields["p"];
    }

    function GetMinPriority($ResourceId)
    {
        $sql = "SELECT MIN(Priority) as p from ".$this->SourceTable."WHERE ResourceId=$ResourceId";
        $result = $this->adodbConnection->Execute($sql);
        return $result->fields["p"];
    }

} /*clsImageList*/

?>