<?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;
        GetModuleArray();
        if($id)
        {
            if(!$expanded)
            {            
              $this->LoadFromDatabase($id);            
            }
            else
                $this->LoadExpanded($id);
        }
    }

    function LoadExpanded($id)
    {
        global $objModules;
        $pre = GetTablePrefix();
        $reltable = $this->tablename;
        
        // ==== build sql depending on modules installed: begin ====
		$prefix = GetTablePrefix();
		$modules = $objModules->GetModuleList();
		$sql_source = $objModules->ExecuteFunction('GetModuleInfo', 'rel_list');
		
		$sql_templates['ItemName'] = 'IFNULL('.$prefix."%s.%s,' ')";
		$sql_templates['TableJoin'] = 'LEFT JOIN '.$prefix."%1\$s ON ".$prefix."%1\$s.ResourceId = rel.TargetId"; 
		$sql_templates['TargetName'] = "IF(rel.TargetType = %s, '%s', %s)";
		
		$sql = 	"SELECT TRIM(CONCAT(%s)) AS ItemName, %s AS ItemType,".
				GetELT('rel.Type+1', Array('la_Text_OneWay','la_Text_Reciprocal')).' AS RelationType,'.
				"RelationshipId, rel.Priority AS Priority, rel.Type as Type, rel.Enabled as Enabled,".
				"rel.TargetId, rel.TargetType, rel.SourceId, rel.SourceType,".
				GetELT('rel.Enabled+1', Array('la_Text_Disabled','la_Text_Enabled')).' AS Status '.
				'FROM '.$reltable.' AS rel %s WHERE rel.RelationshipId = '.$id;
		
		$sql_parts = Array();
		$sql_parts['TargetName'] = "''";
		foreach($modules as $module)
		{
			$sql_parts['ItemName'][] = sprintf($sql_templates['ItemName'], $sql_source[$module]['MainTable'], $sql_source[$module]['ItemNameField']);
			$sql_parts['TableJoin'][] = sprintf($sql_templates['TableJoin'], $sql_source[$module]['MainTable']);
			
			$sql_parts['TargetName'] = sprintf(	$sql_templates['TargetName'], 
												$sql_source[$module]['TargetType'], 
												admin_language($sql_source[$module]['ItemNamePhrase']),
												$sql_parts['TargetName']);
		}
		$sql = sprintf($sql, implode(', ',$sql_parts['ItemName']), $sql_parts['TargetName'], implode(' ',$sql_parts['TableJoin']));
		// ==== build sql depending on modules installed: end ====
        
        //echo "SQL: ".$sql.'<br>';
        
        $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 IF EXISTS $edit_table";
        $this->adodbConnection->Execute($sql);
    }

    function CopyFromEditTable($ResourceId)
    {
        global $objSession;
		$GLOBALS['_CopyFromEditTable']=1;
        
        $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 IF EXISTS $edit_table");
		unset($GLOBALS['_CopyFromEditTable']);
    }	
    
}

?>