<?PHP

/**
 * class for building html pages from templates
 * 
 * tokens can be in the form :
 * 
 * 1. singleton tokens 
 * example: {tokenname}  
 *  
 * 2. recursive tokens (tokens enclosed by HTML comment tags, containing other singleton tokens
 * <--! tokanname begin --> {token1} {token2} <--! tokanname end --> 
 * 
 * 
 * tokens are replace by parseTokens($data) function
 * 
 * special tokens:
 * {tokenname_dt} = timestamp token converted to datetime based on string 
 * {tokenname_d}  = timestamp token converted to date string 
 * {tokenname_t}  = timestamp token converted to time string 
 * {_ic_} = internal counter token
 * 
 * 
 */


class my_tt
{
  public $fn = '';
  private $templatebody = '';
  public $output = '';
  
  private $tokens = false;
  
  public $clearunparsedtags = true;
  public $unparsedtagsreplacement = '';

  public $datetimeformatstring = "d-m-Y H:i:s";
  public $dateformatstring = "d-m-Y";
  public $timeformatstring = "H:i:s";
  
  function loadTemplateFile($fn)
  {
    
		if ((!$fn) )
    {
     return false; 
    }

		if (file_exists($fn))
      $this->templatebody = @file_get_contents($fn);      
    else if (file_exists(getcwd()."/".$fn))
      $this->templatebody = @file_get_contents(getcwd()."/".$fn);      
    else return false;
    
    if ((!$this->templatebody) or (strlen($this->templatebody) < 1) )
      return false;

    $this->output = $this->templatebody;

    return true;       
  }
  
  
  function my_tt($fn)
  {
    
		if ($this->loadTemplateFile($fn))
			$this->extractTokens();
  else
    throw new Exception("Cannot open template $fn");
	}
  
  function doClearUnparsedTags()
	{
    $this->output = preg_replace('/\(\%(.*?)\%\)/is',$this->unparsedtagsreplacement,$this->output);  
    // staro: $this->output = preg_replace("/\{[^\s](.*)[^\s]%\)/i",$this->unparsedtagsreplacement,$this->output);
  }                       
  
  
	function extractTokens()
  {
		unset ($this->tokens);
		$this->tokens = array();
    
		preg_match_all("/<!-- ([^\"]*) begin -->(.*?)<!-- ([^\"]*) end -->/is",$this->templatebody,$token_bodies);
		//preg_match_all("/<!-- ([^\"]*) begin -->/is",$this->templatebody,$token_names);

		if ( (is_array($token_bodies)) && (isset($token_bodies[3])) )
			{
				$token_names =  $token_bodies[3];
				$token_bodies = $token_bodies[2];
				foreach ($token_bodies as $k => $v)
				{
					$this->tokens[$token_names[$k]] = $v;
				}
			}

		return (sizeof($this->tokens) > 0);
  }
  
  function _replaceOneTokenPlaceholderWithValue(&$tokentext,$n,$v) 
  {
      if ( ! stristr($n,"_dt_") === false)
      {
        if ($v > 0) // show datetime only if its valid
          $tokentext = str_replace("{".$n."}",date($this->datetimeformatstring,$v),$tokentext);                                                
      }
      else if ( ! stristr($n,"_d_") === false)
      {
        if ($v > 0) // show date only if its valid
          $tokentext = str_replace("{%".$n."%}",date($this->dateformatstring,$v),$tokentext);                                                
      }
      else if ( ! stristr($n,"_t_") === false)
      {
        if ($v > 0) // show time only if its valid
          $tokentext = str_replace("{".$n."}",date($this->timeformatstring,$v),$tokentext);                                                
      }          
      else  
        $tokentext = str_replace("{".$n."}",$v,$tokentext);        
  
  }
   
   
  function parseOneToken($tagname,$tagvalue)
  {
		if (is_array($tagvalue))
    {
			$output = '';
			$internalcounter = 1;
			$tmp = '';
			$tokentext = ( (isset($this->tokens[$tagname])) && (strlen($this->tokens[$tagname])>0) ) ? $this->tokens[$tagname] : ' ';
      
			foreach ($tagvalue as $names => $values)
      {
        
				if (is_array($values))
        {
          $tmp = $tokentext;           
          
          foreach ($values as $n => $v)
            {              
              $this->_replaceOneTokenPlaceholderWithValue($tmp,$n,$v);
              /*
              if ( ! stristr($n,"_dt_") === false)
              {
                if ($v > 0) // show datetime only if its valid
                  $tokentext = str_replace("{".$n."}",date($this->datetimeformatstring,$v),$tokentext);                                                
              }
              else if ( ! stristr($n,"_d_") === false)
              {
                if ($v > 0) // show date only if its valid
                  $tokentext = str_replace("{".$n."}",date($this->dateformatstring,$v),$tokentext);                                                
              }
              else if ( ! stristr($n,"_t_") === false)
              {
                if ($v > 0) // show time only if its valid
                  $tokentext = str_replace("{".$n."}",date($this->timeformatstring,$v),$tokentext);                                                
              }          
              else  
                $tokentext = str_replace("{".$n."}",$v,$tokentext);   
              */   
            }
            $output .= $tmp;            
        }
        else
        {
            $this->_replaceOneTokenPlaceholderWithValue($tokentext,$names,$values);
        }        

      }
      
			if (isset($values) && (is_array($values)))
      {      
      $output = str_replace("{_ic_}",$internalcounter++,$output);                                            
      }
      else
        $output = $tokentext;
            
      // now replace that instead of token in output text
      
      $this->output = preg_replace("/<!-- ".$tagname." begin -->(.*?)<!-- ".$tagname." end -->/is",$output,$this->output);
    }
    else 
    {
      if ( ! stristr($tagname,"_ts") === false)
      {
        if ($tagvalue > 0) // show date only if its valid
          $this->output = str_replace("{".$tagname."}",date("d-m-Y H:i:s",$tagvalue),$this->output);        
      }  
      else    
        $this->output = str_replace("{".$tagname."}",$tagvalue,$this->output);

    }
  }      
  
  function parseTokens($data)
  {
		if ((isset($data)) && (is_array($data)) && (sizeof($data)>0) )
    {    
			foreach ($data as $k => $v)
        $this->parseOneToken($k,$v);
    }
  }
  
  function replaceCompleteCommentToken($tokenname, $value = "&nbsp;")
  {
      $this->output = preg_replace("/<!-- ".$tokenname." begin -->(.*?)<!-- ".$tokenname." end -->/is",$value,$this->output);  
  }
  
	function show()
	{
		if ($this->clearunparsedtags)
			$this->doClearUnparsedTags();
    print($this->output);
  }
  
  
} // class end
?>