<?php

class clsRelationship extends clsItemDB
{
    var $expanded;

    function clsRelationship($id=NULL,$expanded=FALSE)
    {
        $this->clsItemDB();
        $this->tablename = GetTablePrefix()."Relationship";
        $this->id_field = "RelationshipId";
        $this->NoResourceId = 1;
        $this->expanded=FALSE;
        if($id)
        {
            if(!$expanded)
            {            
              $this->LoadFromDatabase($id);            
            }
            else
                $this->LoadExpanded($id);
        }
    }

    function LoadExpanded($id)
    {
        $pre = GetTablePrefix();
        $reltable = $this->tablename;
        $sql = "SELECT trim(concat(ifnull(".$pre."Category.name,' '), ifnull(".$pre."Link.name,' '),ifnull(".$pre."News.title,' '), ifnull(".$pre."Topic.TopicText,' '))) as ItemName,";
        $sql .=" ELT(rel.targettype, '".admin_language("la_Text_Category")."' ,'".admin_language("la_Text_Article");
        $sql .="' ,'".admin_language("la_Text_Topic")."','".admin_language("la_Text_Link")."') as ItemType,";
        $sql .=" ELT(rel.type+1,'".admin_language("la_Text_OneWay")."','".admin_language("la_Text_Reciprocal")."') as RelationType,";
        $sql .=" RelationshipId, rel.TargetId,rel.TargetType,rel.SourceId,rel.SourceType, rel.Type, rel.Enabled, rel.Priority, ";
        $sql .=" ELT(rel.enabled+1,'Disabled','Enabled') as Status FROM ".$reltable." as rel ";
        $sql .=" LEFT JOIN ".$pre."Category ON ".$pre."Category.ResourceId=rel.TargetId ";
        $sql .="LEFT JOIN ".$pre."Link ON ".$pre."Link.ResourceId=rel.TargetId ";
        $sql .="LEFT JOIN ".$pre."News ON ".$pre."News.ResourceId=rel.TargetId ";
        $sql .="LEFT JOIN ".$pre."Topic ON ".$pre."Topic.ResourceId=rel.TargetId ";
        $sql .="WHERE rel.RelationshipId=".$id;
        
        $rs=$this->adodbConnection->Execute($sql);        
        if($rs && !$rs->EOF)
        {
            $data = $rs->fields;
            $this->SetFromArray($data);
            $this->Clean();
            $this->expanded=TRUE;
            return TRUE;
        }
        else
            return FALSE;
    }    

    function LoadFromDatabase($id)
    {
        $table = $this->tablename;
        $sql = "SELECT * FROM $table";
        $sql .= " WHERE ".$this->id_field."=".$id;
       
        $rs=$this->adodbConnection->execute($sql);
        if($rs && !$rs->EOF)
        {
            $data = $rs->fields;
            $this->SetFromArray($data);
            $this->Clean();
            $this->expanded=FALSE;
            return TRUE;            
        }
        else
            return FALSE;
    }

    function GetTargetItemData()
    {
    	global $objItemTypes;
    	
        /*returns the table row in an array for the item this relationship points to */
        $type=$this->Get("TargetType");

        $Item = $objItemTypes->GetItem($type);
        $table = $Item->Get("SourceTable");
        $titlefield = $Item->Get("TitleField");             
		        
        if(strlen($table))
        {
            $sql = "SELECT * FROM ".GetTablePrefix().$table." WHERE ResourceId=".$this->Get("TargetId");

            $rs = $this->adodbConnection->execute($sql);
            if($rs)
            {            
              $res = $rs->fields;
              $res["SourceTable"]=$table;
              $res["TitleField"]=$titlefield;
              return $res;
            }
            else
                return FALSE;
        }
        else
            return FALSE;
    }

    function Admin_Icon()
    {        
        global $imagesURL;
        
        $type = "reciprocal";
        if($this->Get("Type")==0)
        {
            $type = "one-way";
        }
        $icon = $imagesURL."/itemicons/icon16_relation_".$type;
        if($this->Get("Enabled")!=1)
        {                
            $icon .= "_disabled";
        }
        $icon .= ".gif";
        return $icon;
    }

    function parse_template()
    {
        $item = $this->GetTargetItemData();
        $type=$this->Get("TargetType");

        switch($type)
        {
          case 1:
            $c = new clsCategory(); 
            $t = "cat_relate_element";
            break;
          case 2:
            $c = new clsNews();
            $t = "innews/news_relate_element";
            break;
          case 3:
            $c = new clsTopic();
            $t="inbulletin/bb_relate_element";
            break;
          case 4:
            $c = new clsLink();  
            $t="inlink/link_relate_element";
            break;
          case 5:
            $c = new clsSurvey();  
            $t="insurvey/s_relate_element";
            break;
          default: 
              $c=NULL;
        }
        if(is_object($c))
        {       
          foreach($item as $key=>$value)
          {
             $c->Set($key,$value);
          }
          $o = $c->parse_template(parse($t)); 
        }
        return $o;        
    }

    function &GetTargetItemClass()
    {
        global $objItemTypes;

        $objType = $objItemTypes->GetItem($this->Get("TargetType"));
        $classname = $objType->Get("ClassName");
        if(strlen($classname))
        {        
          $c = new $classname;
        }
        else
            $c = NULL;
        if(is_object($c))
        {       
            $c->LoadFromResourceId($this->Get("TargetId"));
        }
        return $c; 
    }

    function &GetSourceItemClass()
    {
        global $objItemTypes;

        $objType = $objItemTypes->GetItem($this->Get("SourceType"));
        $classname = $objType->Get("ClassName");

        if(strlen($classname))
        {        
          $c = new $classname;
        }
        else
            $c = NULL;
        if(is_object($c))
        {       
            $c->LoadFromResourceId($this->Get("SourceId"));
        }
        return $c;        
    }

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

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

} /*clsRelationship*/

class clsRelationshipList extends clsItemCollection
{
    var $Page;
    var $PerPage;
	
    function clsRelationshipList($CategoryId=-1,$ItemId=-1)
    {
        $this->clsItemCollection();
        $this->classname="clsRelationship";
        $this->SourceTable = GetTablePrefix()."Relationship";
        $this->Page=1;
        $this->PerPage=20;
        $this->AdminSearchFields = array("ItemName","ItemType","RelationType","Status");
        $this->TargetItems = new clsItemCollection();       
        $this->TargetItems->classname="clsItemDB";
        
    }

    function GetNumPages()
    {
        global $objConfig;
        
        return ceil($this->NumItems()/$this->PerPage);
    }

    function GetAdminPageLinkList($link_template,$url)
    {
        global $objConfig, $bb_var_list_update, $var_list_update, $var_list;
                          
        $NumPages = $this->GetNumPages();
        $o = "";
        if($this->Page>1)
        {
          $prev_url = $url."?env=".BuildEnv()."&lpn=".$this->Page-1;
          $o = "<A HREF=\"$prev_url\"><<</A>";
        }
        
        for($p=1;$p<=$NumPages;$p++)
        {
            $t = admintemplate($link_template);
            if($p!=$this->Page)
            {                
                $href = $url."?env=".BuildEnv()."&lpn=".$p;
                $o = "-<A HREF=\"$href\">$p</A>-";
            }
            else
            {
                $o .= "<SPAN class=\"CURRENT_PAGE\">$p</SPAN>";
            }
        }
        if($this->Page<$NumPages)
        {
          $next_url = $url."?env=".BuildEnv()."&lpn=".$this->Page+1;
        }

        return $o;        
    }

    function GetLimitSQL()
    {
      if($this->Page<1)
         $this->Page=1;

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

    function LoadRelated($where,$orderBy,$custom_sql = null)
    {
       global $objSession;

       $sql = isset($custom_sql) ? sprintf($custom_sql,$this->SourceTable) : "SELECT * FROM ".$this->SourceTable;
	   
       if(strlen(trim($orderBy))>0)
       {      
           $orderBy = "Priority, ".$orderBy;
       }
       else
           $orderBy = "Priority ";
       
      if(strlen($where))
          $sql = sprintf('%s WHERE %s',$sql,$where);    
                  
      $sql = sprintf('%s ORDER BY %s',$sql,$orderBy);
      $sql .= " ".$this->GetLimitSQL();
      if($objSession->HasSystemPermission("DEBUG.LIST"))
          echo htmlentities($sql,ENT_NOQUOTES)."<br>\n";
      return $this->Query_Item($sql);
    }

    function CountRelated($where)
    {
        $res = 0;
        $sql = "SELECT count(*) as mycount from ".$this->SourceTable." WHERE $where ";
        $rs = $this->adodbConnection->Execute($sql);
        if($rs && !$rs->EOF)
            $res = $rs->fields["mycount"];
        return $res;
    }
    
    function Add($SourceId,$SourceType,$TargetId,$TargetType,
    		 $Priority=0,$Enabled=1,$Type=0, $RelationId = -999)
    {
      $r = new clsRelationship();
      $r->Set(array("SourceId","SourceType","TargetId","TargetType","Priority","Type","Enabled"),
              array($SourceId,$SourceType,$TargetId,$TargetType,$Priority,$Type,$Enabled));
              
      if ($RelationId != -999)
      {
			$r->Set("RelationshipId", $RelationId); 
      }
              
      $r->tablename = $this->SourceTable;
      $r->Create();
      return $r;
    }
    
    function CopyToResource($OldSource,$NewSource)
    {
      $this->Clear();
      $sql = "SELECT * FROM ".$this->SourceTable." WHERE SourceId=$OldSource";
      $this->Query_Item($sql);
     
      if($this->NumItems()>0)
      {
          foreach($this->Items as $i)
          {
          	  $i->UnsetIdField();
              $i->Set("SourceId",$NewSource);
              $i->Create();
          }
      }
    }
    
    function PurgeEditTable($idfield = "")
    {
    	global $objSession;
    	
    	$edit_table = $objSession->GetEditTable($this->SourceTable);
        $idlist = array();
        $sql = "DROP TABLE $edit_table";
        $this->adodbConnection->Execute($sql);
    }

    function CopyFromEditTable($ResourceId)
    {
        global $objSession;
        
        $edit_table = $objSession->GetEditTable($this->SourceTable);
        $idlist = array();
        $sql = "SELECT * FROM $edit_table WHERE SourceId='$ResourceId'";
        
        $this->Clear();
        $rs = $this->adodbConnection->Execute($sql);
        while($rs && !$rs->EOF)
        {
            $data = $rs->fields;
            $c = $this->AddItemFromArray($data);            
            $c->Dirty();                       
            
            if($data["RelationshipId"]>0)
            {            	
                $c->Update();
            }
            else
            {
                $c->UnsetIdField();
                $c->Create();
            }
            $idlist[] = $c->Get("RelationshipId");
            $rs->MoveNext();
        }
        
        if(count($idlist)>0)
        {
            $sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$ResourceId AND RelationshipId NOT IN (".implode(",",$idlist).")";
        }
        else
        {
           $sql = "DELETE FROM ".GetTablePrefix()."Relationship WHERE SourceId=$ResourceId";
        }
        
        if((int)$GLOBALS["debuglevel"])
            echo $sql."<br>\n";        
            
        $this->adodbConnection->Execute($sql);
//        $this->adodbConnection->Execute("DROP TABLE $edit_table");
    }	
    
}

?>