<?php

/**------------------------------------------------
*
* Rooty, 2018 <rooty@rooty.me>
*
*
* This software is protected by copyright, please
* read the file COPYRIGHT.
* This program is distributed in the hope that it
* will be useful, but without any warranty; without
* even the implied warranty of merchantability or
* fitness for a particular purpose. Please
* read the file LICENCE.
*
* Fichier ModeliXeQware.php
*
*Ce fichier contient la classe ModeliXeQware
*(template du site)
*
* @author Rooty <www.rooty.me|rooty@rooty.me>
* @link www.rooty.me
* @since 2004/04/14
* @version 0.2
* @copyright Copyright &copy; 2004-2005, Initiance
* @package system_template
*/


/**
*
*/
include_once($GLOBALS["CONF_LIB_PATH"]."lib/system/system_template/modelixe.php");

/**
* @package system_template 
*/
class ModeliXeQware extends ModeliXe
{

    public $template;
    public $sessionParameter;

    public function __construct($template, $sessionParameter='', $templateFileParameter='', $cacheDelay='-1')
	{
//         parent::__construct($this->template, $this->sessionParameter, $this->templateFileParameter, $this->cacheDelay);
//         $this->template=$this->MxGetMain($this->template);
        $this->SetTemplate($template);
		$this->SetSessionParameter($sessionParameter);
		$this->SetTemplateFileParameter($templateFileParameter);
		$this->SetCacheDelay($cacheDelay);

		parent::__construct($this->template, $this->sessionParameter, $this->templateFileParameter, $this->cacheDelay);
		$this->SetMxOutputType("xhtml");
    }

    	/* Appel le contructeur parent... */
// 	function ModeliXeQware($template, $sessionParameter = '', $templateFileParameter = '', $cacheDelay = -1) {
// 		$template=$this->MxGetMain($template);
// // 		parent::ModeliXe($template, $sessionParameter, $templateFileParameter, $cacheDelay);
//         parent::__construct($template, $sessionParameter, $templateFileParameter, $cacheDelay);
// 		$this->SetMxOutputType("xhtml");
// 	}
    
    function SetTemplate($template)
    {
        $this->template = $this->MxGetMain($template);
    }
		
    function SetSessionParameter($sessionParameter)
    {
		$this->sessionParameter = $sessionParameter;
    }
		
    function SetTemplateFileParameter($templateFileParameter)
    {
		$this->templateFileParameter = $templateFileParameter;
    }
		
    function SetCacheDelay($cacheDelay){
		$this->cacheDelay = $cacheDelay;
    }

	function MxFormField($index, $type, $name, $value, $attribut = '', $placeholder = '', $special='')
	{
		//$name ="toto".$name;
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxFormField:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxFormField:".$index."<BR>";
		}
		if (isset($this->formField[$index]) || isset($this->formField[$this->relativePath.'.'.$index]))
		{
			return parent::MxFormField($index, $type, $name, $value, $attribut, $placeholder, $special);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:formField non déclaré", __line__, __file__);
		}
		return false;
	}

	function MxImage($index, $imag, $title = '', $attribut = '', $size = false)
	{
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxImage:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxImage:".$index."<BR>";
		}
		if (isset($this->image[$index]) || isset($this->image[$this->relativePath.'.'.$index]))
		{
			return $this->MxImagePrint($index, $imag, $title, $attribut, $size);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:image non déclaré", __line__, __file__);
		}
		return false;
	}

	function MxText($index, $att){
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxText:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxText:".$index."<BR>";
		}
		if (isset($this->text[$index]) || isset($this->text[$this->relativePath.'.'.$index]))
		{
			return parent::MxText($index, $att);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:text non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	function MxAttribut($index, $att){
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxAttribut:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxAttribut:".$index."<BR>";
		}
		if (isset($this->attribut[$index]) || isset($this->attribut[$this->relativePath.'.'.$index]))
		{
			return parent::MxAttribut($index, $att);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:attribut non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	function MxSelect($index, $name, $value, $arrayArg, $defaut = '', $multiple = '', $javascript = '', $attibutes = '')
	{
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxSelect:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxSelect:".$index."<BR>";
		}
		if (isset($this->select[$index]) || isset($this->select[$this->relativePath.'.'.$index]))
		{
			return parent::MxSelect($index, $name, $value, $arrayArg, $defaut, $multiple, $javascript, $attibutes);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:select non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	function MxUrl($index, $urlArg, $param = '', $noSid = false, $attribut = '')
	{
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxUrl:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxUrl:".$index."<BR>";
		}
		if (isset($this->select[$index]) || isset($this->select[$this->relativePath.'.'.$index]))
		{
			return parent::MxUrl($index, $urlArg, $param, $noSid, $attribut);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:select non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	function MxHidden ($index, $param){
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxHidden:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxHidden:".$index."<BR>";
		}
		if (isset($this->hidden[$index]) || isset($this->hidden[$this->relativePath.'.'.$index]))
		{
			return parent::MxHidden ($index, $param);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:select non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	function MxCheckerField($index, $type, $name, $value, $checked = false, $attribut = '')
	{
		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxCheckerField:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxCheckerField:".$index."<BR>";
		}
		if (isset($this->checker[$index]) || isset($this->checker[$this->relativePath.'.'.$index]))
		{
			return parent::MxCheckerField($index, $type, $name, $value, $checked, $attribut);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:select non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	function MxBloc($index, $mod, $value = '')
	{
		if( (strtolower($mod)=="appe") )
		{
			$valuePath=( $value!='')?$this->MxGetTemplate($value):'';
			$value=($valuePath==null)?$value:$valuePath;
		}

		if ($GLOBALS['CONF_MX_DOCUMENTOR'])
		{
			if ($this->adressSystem == 'relative')
			 echo "MxBloc:".$this->relativePath.'.'.$index."<BR>";
			else
			 echo "MxBloc:".$index."<BR>";
		}
		// ajout du style pour chaque ligne...
		if( (strtolower($mod)=="loop") && (function_exists("lineStyle")) )
			lineStyle($index);

		if (isset($this->father[$index]) || isset($this->father[$this->relativePath.'.'.$index]))
		{
			return parent::MxBloc($index, $mod, $value);
		}elseif($GLOBALS['CONF_MX_DEBUG']){
			addError(8, "ModeliXeQware", "MX:bloc non déclaré ".$index, __line__, __file__);
		}
		return false;
	}

	//Remplace le contenu des templates passés en arguments
	function MxReplace($path){
		if (! empty($this->sheetBuilding[$path])) $cible = $this->sheetBuilding[$path];
		else $cible = $this->templateContent[$path];

		//Remplacement de l'ensemble des attributs ModeliXe par les valeurs qui ont été instanciées ou leurs valeurs par défaut
		reset($this->attributArray);
// 		while (list($cle, $Fkey) = each($this->attributArray)){
		// PHP8.0
		foreach ($this->attributArray as $cle => $Fkey) {
		$Farray = &$this->$Fkey;

		if (is_array($Farray)){
			reset($Farray);
// 			while (list($Pkey, $value) = each($Farray)){
			// PHP8.0
			foreach ($Farray as $Pkey => $value) {
			if ($path == substr($Pkey, 0, strrpos($Pkey, '.'))) {
				if (isset($this->xPattern[$Fkey][$Pkey])){
				$pattern = $this->xPattern[$Fkey][$Pkey];
				$cible = str_replace($pattern, $value, $cible);
/* permet ainsi de tester si un Mx existe sur une boucle... */
//				unset($Farray[$Pkey]);
				$Farray[$Pkey]="";
				}
				}
			}
			}
		}

		//Remplacement de l'ensemble des balises ModeliXe par les valeurs qui ont été instanciées ou leurs valeurs par défaut
		reset($this->flagArray);
// 		while (list($cle, $Fkey) = each($this->flagArray)){
		// PHP8.0
		foreach ($this->flagArray as $cle => $Fkey) {
		$Farray = &$this->$Fkey;

		if (is_array($Farray)){
			reset($Farray);

// 			while (list($Pkey, $value) = each($Farray)){
			// PHP8.0
			foreach ($Farray as $Pkey => $value) {

			if ($path == substr($Pkey, 0, strrpos($Pkey, '.'))) {
				if (isset($this->xPattern[$Fkey][$Pkey])){
				$pattern = $this->xPattern[$Fkey][$Pkey];
				$cible = str_replace($pattern, $value, $cible);
/* permet ainsi de tester si un Mx existe sur une boucle... */
//				unset($Farray[$Pkey]);
				$Farray[$Pkey]="";
				}
				}
			}
			}
		}
		return $cible;
	}

/**
* Olivier <olivier@initiance.com>
* Permet de ne pas se servir des attributs des images...
* @todo vérifier si d'autres éléments se servent ou non des attributs supplémentaires et si on en a réellement besoin!
*/
    function MxImagePrint($index, $imag, $title = '', $attribut = '', $size = false)
    {
        if ($this->adressSystem == 'relative') $index = $this->relativePath.'.'.$index;
        $end = $this->outputSystem;

        if (($ima = '<img src="'.$imag.'"') && ! $size) {
/*            $size = @getimagesize($imag);*/
/*            $ima .= ' '.$size[3];*/
            }

        if ($title == 'no') $ima .= ' ';
        elseif ($title) $ima .= ' alt="'.$title.'" title="'.$title.'" ';
        else $ima .= ' alt="no title - source : '.basename($imag).'" ';

        if ($attribut) $ima .= $attribut;
        $ima .= ' '.$this->htmlAtt[$index].$end;
        $this->image[$index] = $ima;
    }

/**
* Olivier <olivier@initiance.com>
* Permet de récupérer une template spécifique pour un objet
* @param chaine chaine path vers la template
*/
    function MxGetTemplate($templatePath, $tplSearch="/default/")
    {
        //Récupération du nom de la page
        $pos=strrpos($templatePath,"/");
        $page=substr($templatePath,$pos);
        $pagename=str_replace(".mxt","",$page);

        //Vérification de l'existence de la page sous-forme(page-nid-oid.mxt)
        $newTemplatePath=str_replace($pagename,$pagename."-".nid()."-".oid(),$templatePath);
        if (file_exists($newTemplatePath))
        {
            //Affectation du template nid-oid
            return $newTemplatePath;
        } else {
            $newTemplatePath=str_replace($pagename,$pagename."-".oid(),$templatePath);
            if(file_exists($newTemplatePath))
            {
                //Affectation du template oid
                return $newTemplatePath;
            }
        }

        if(!file_exists($templatePath) && (strpos($templatePath, $tplSearch)===false))
        {
            $templatePath=$this->MxGetTemplate(str_replace("/".$GLOBALS['SYSTEM_TEMPLATE_DIR'], $tplSearch, $templatePath));
        }

        if(file_exists($templatePath))
        {
            return $templatePath;
        }else{
            return false;
        }
    }

/**
* Olivier <olivier@initiance.com>
* Permet de surchargé la template principale par celle de l'objet courant
* @param chaine chaine path vers la template
*/
    function MxGetMain($templatePath)
    {
        $mainPath=$GLOBALS["CONF_DATA_PATH"]."data/template/".$GLOBALS['SYSTEM_TEMPLATE_DIR']."main.mxt";
        if ( ($templatePath==$mainPath) && ($GLOBALS["SYSTEM_CONTROL"]->className!=null) ){
            $toTest=$GLOBALS["CONF_DATA_PATH"]."data/template/".$GLOBALS['SYSTEM_TEMPLATE_DIR']."object_coordination/".strtolower($GLOBALS["SYSTEM_CONTROL"]->className)."/main.mxt";
            $newTemplatePath=$this->MxGetTemplate($toTest, $GLOBALS['SYSTEM_TEMPLATE_DIR']);
            if ($newTemplatePath===false){
                $newTemplatePath=$templatePath;
            }
            $toTest=$this->MxGetTemplate($newTemplatePath);
            if (strpos($toTest, "main-".nid().".mxt")!==false)
                $GLOBALS['SYSTEM_TEMPLATE_MAIN']="main-".nid().".mxt";
            if (strpos($toTest, "main-".nid()."-".oid().".mxt")!==false)
                $GLOBALS['SYSTEM_TEMPLATE_MAIN']="main-".nid()."-".oid().".mxt";
            return $toTest;
        }else{
            return $this->MxGetTemplate($templatePath);
        }
    }

/**
* Olivier <olivier@initiance.com>
* Permet de surchargé la template principale par celle de l'objet courant
* @param chaine chaine path vers la template
*/
    function IsMxBloc($index){
        if ($this->adressSystem == 'relative') $index = $this->relativePath.'.'.$index;
        $fat = (isset($this->father[$index]))?$this->father[$index]:false;
        if (! $fat && $index != $this->absolutePath) return false;
        else return true;
    }

/**
* Olivier <olivier@initiance.com>
* erreur sur la var template dans le cas ou la compression est désactivée ou n'est pas valable...
* @param chaine chaine path vers la template
*/
    //Retourne le fichier de cache
    function MxGetCache()
    {
        /* ajout du support des sous-répertoires */
        $template = str_replace("/","%2F", $this->template);
        $cache_file = $this->mXCachePath.$this->mXUrlKey.'~'.$template;

        if (! $open = @fopen($cache_file, 'rb')) $this->ErrorTracker(5, 'Can\'t open the cache file on "<b>'.$cache_file.'</b>" path.', 'MxGetCache');
        if (! $read = @fread($open, filesize($cache_file))) $this->ErrorTracker(5, 'Can\'t read the cache file on "<b>'.$cache_file.'</b>" path.', 'MxGetCache', __FILE__, __LINE__);

        @fclose($open);

        //Parsing des paramètres de sessions
        $read = $this->MxSessionParameterParsing($read);

        //Si on cherche à mesurer les performances de ModeliXe
        if ($this->performanceTracer) {
            $read = str_replace('<mx:performanceTracer />', $this->GetExecutionTime().' [cache]', $read);
            }

        //Si il y a une gestion de la compression, envoie des en-têtes correspondantes
        $this->ErrorChecker();

        if ($this->mXoutput) return $read;
        else print($this->MxSetCompress($read));
        die();
    }

/**
* Olivier <olivier@initiance.com>
* erreur sur la var template dans le cas ou la compression est désactivée ou n'est pas valable...
* @param chaine chaine path vers la template
*/
    //Teste si le fichier de cache existe et son échéance
    function MxCheckCache() {
        /* ajout du support des sous-répertoires */
        $template = str_replace("/","%2F", $this->template);
        $cache_file = $this->mXCachePath.$this->mXUrlKey.'~'.$template;
        if (@is_file($cache_file)){
            if (($currentTime = filemtime($cache_file)) && (((time() - $currentTime) < $this->mXCacheDelay && filemtime($this->mXTemplatePath.$this->template) < $currentTime))) return true;
        } else return false;
    }
}

/**
* Pour les versions precedentes
* Permet de garder la compatibilité avec l'ancien nom de qware
*/
class ModeliXeGraniware extends ModelixeQware{
}
?>