<?PHP

/**
* template and view parser
*/
class Template extends extender{

	/**
	* supply the template file
	* write the final template file
	* show the template file
	* @param String $template - template name what to use
	* 
	*/
	function __template($template){

		$sql = "is_first_page = 1";
		if($_GET['model'] && $_GET['page'])
			$sql = "name = '".$_GET['model']."' AND page = '".$_GET['page']."'";
		if($_GET['model'] && $_GET['show_page'])
			$sql = "name = '".$_GET['model']."' AND page = '".$_GET['page']."' AND id=(SELECT CASE WHEN model_id > 0 THEN model_id ELSE template_id END FROM menus WHERE short_name = '".$_GET['show_page']."' AND language = '".$_SESSION['language']."' LIMIT 1)";

		$row = $this->Sql->Query("SELECT template FROM templates WHERE ".$sql." AND page_position LIKE '%".$this->page_position."%' AND language = '".$_SESSION['language']."' AND LENGTH(template) > 0 ", true);

		if($this->Sql->Numrows > 0 && file_exists(_CurrentTemplate.'/'.$row[0]['template'].'.php')) $template = $row[0]['template'];

		$this->getTemplateFile($template);
	}


	private function getTemplateFile($template){

		require _CurrentTemplate.'/'.$template.'.php';
	}

	/**
	* replace data in string
	* @param String $content - {replace_tag}
	* @param Array $array - array('replace_tag' => 'replace_value')
	* @return string
	*/
	function replace($content, $array){

		$self = $this;

		$content = preg_replace_callback('/{([a-zA-Z0-9\_[:space:]_]+)}(.*?){\/\\1}/s', function( $matches ) use ( $array, $self ) {return $self->replaceMultiple($matches[2], $array[$matches[1]]);}, $content);
		$content = preg_replace_callback('/\{([a-zA-Z0-9\_[:space:]_]+)\((.*?)\)\}/s', function( $matches ) use ( $array, $self ) {return $self->replaceMethod($matches[1], $matches[2]);}, $content);
		$content = preg_replace_callback('/\{([a-zA-Z0-9\_[:space:]_]+)\=(.*?)\}/', function( $matches ) use ( $array ) {return ($array[$matches[1]] ? ($array[$matches[1]] == 'boolean' ? $matches[2] : $array[$matches[1]]) : '');}, $content);
		if(preg_match('/\{([a-zA-Z0-9\_[:space:]_]+)\((.*?)\)\:([a-zA-Z0-9\_[:space:]_]+)\((.*?)\)\}/i', $content))
			return preg_replace_callback('/\{([a-zA-Z0-9\_[:space:]_]+)\:([a-zA-Z0-9\_[:space:]_]+)\}/', function( $matches ) use ( $array ) {return $array[$matches[1]][$matches[2]];}, $content);
		return preg_replace_callback('/\{([a-zA-Z0-9\_[:space:]_]+)\}/', function( $matches ) use ( $array ) {return $array[$matches[1]];}, $content);
	}

	/**
	* preg replace execute callback - preg_replace('//e')
	* @param String $pattern - '/([a-zA-Z_]+)/s'
	* @param Array $array - array('match' => 'value')
	* @param String $content - html or string
	* @return String
	* @example $this->pregReplace('/([a-zA-Z_]+)/s', array('match' => $this->callback()), 'string');
	*/
	function pregReplace($pattern, $array, $content){

		return preg_replace_callback($pattern, function( $matches ) use ( $array ) {return $array[$matches[1]];}, $content);
	}

	private function replaceMultiple($content, $array){

		if($array[0]){

			$tmp_content = stripslashes($content);
			$content = '';
			foreach($array as $v){

				$content .= preg_replace_callback('/\{([a-zA-Z0-9\_[:space:]_]+)\}/', function( $matches ) use ( $v ) {return $v[$matches[1]];}, $tmp_content);
			}
			return $content;
		}
		return '';
	}

	private function replaceMethod($name, $value){

		if(method_exists($this, $name)){

			return $this->$name($value);
		}
	}
	/**
	* return specialcharacters for preg_replace
	* @param String $syntax - '/'
	* @return String
	*/
	function specialCharacter($syntax){

		return $syntax;
	}


	/**
	* require pageName
	* @param String $page - pageName
	* @param Array $variables = array() - it will pass thrue variables as $variableName
	*/
	function page($page, $variables = array()){

		if(preg_match('/\//i', $page)){

			list($model, $page) = explode('/', $page);
		}

		$model = $model ? $model : $this->model;
		$dir = $this->type == 'plugin' ? 'plugins' : 'models';

		if(is_Array($variables)){

			foreach($variables as $k => $v){

				$$k = $v;
			}
		}

		//PHP
		if(file_exists(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.php')){

			if($_GET['view'] == 'graphic') echo _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.php';

			require _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.php';
			return true;
		}
		if(file_exists(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.php')){

			if($_GET['view'] == 'graphic') echo _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.php';

			require _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.php';
			return true;
		}

		//HTML
		if(file_exists(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.html')){

			$this->getHtmlFile(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.html', $model.'.'.$page.'.'.$this->page_position.'.php');
			return true;
		}
		if(file_exists(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.html')){

			$this->getHtmlFile(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.html', $model.'.'.$page.'.'.$this->page_position.'.php');
			return true;
		}
	}
	/**
	* same as page, but it will return page file with full location
	* @param String $page
	*/
	function requirePage($page){

		if(preg_match('/\//i', $page)){

			list($model, $page) = explode('/', $page);
		}

		$model = $model ? $model : $this->model;
		$dir = $this->type == 'plugin' ? 'plugins' : 'models';

		//PHP
		if(file_exists(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.php')){

			if($_GET['view'] == 'graphic') echo _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.php';

			return _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$this->page_position.'/'.$page.'.php';
		}
		if(file_exists(_RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.php')){

			if($_GET['view'] == 'graphic') echo _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.php';

			return _RootFolder.'/app/'.$dir.'/'.$model.'/views/'.$page.'.php';
		}
	}

	private function getHtmlFile($html_file_source, $html_file_dest){

		if(!file_exists(_TmpBaseFolder.'/'.$html_file_dest) && file_exists($html_file_source)){

			$content = file_get_contents($html_file_source);
			$content = $this->parse_content($content);

			$this->callClass('File')->WriteFile($html_file_dest, $content, 0775, _TmpBaseFolder);
		}
		if(file_exists(_TmpBaseFolder.'/'.$html_file_dest) && file_exists($html_file_source)){

			if($this->callClass('File')->FileModificationTime(_TmpBaseFolder.'/'.$html_file_dest) < $this->callClass('File')->FileModificationTime($html_file_source)){

				$content = file_get_contents($html_file_source);
				$content = $this->parse_content($content);

				$this->callClass('File')->WriteFile($html_file_dest, $content, 0775, _TmpBaseFolder);
			}
		}

		if(file_exists(_TmpBaseFolder.'/'.$html_file_dest)){

			require  _TmpBaseFolder.'/'.$html_file_dest;
		}
	}

	/**
	* this is private
	*/
	function savePluginFile($name, $content){

		$content = preg_replace('/\[PLUGIN=(.*)\]/', '<? $this->callPlugin(\'\\1\'); ?>', $content);

		if(!is_dir(_RootFolder.'/tmp/pages'))
			mkdir(_RootFolder.'/tmp/pages');
		file_put_contents(_RootFolder.'/tmp/pages/'.$name.'.php', $content);

		return _RootFolder.'/tmp/pages/'.$name.'.php';
	}

	/**
	* it will call in template model _script.js file
	*/
	function script(){

		$dir = $this->type == 'plugin' ? 'plugins' : 'models';

		$models = array();
		if( is_array($this->modelPageList) ){

			foreach($this->modelPageList as $v){

				foreach($v as $v1){

					if( ($v1['is_static'] == true || ($v1['model'] == $_GET['model'] && $v1['page'] == $_GET['page']) || ($v1['is_first_page'] == true && !$_GET['model'])) && preg_match('/'.$this->page_position.'/i', $v1['page_position']) ){

						$models[$v1['model']] = $v1['model'];
					}
				}
			}
			foreach($models as $v){

				$file = _RootFolder.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/script.js';
				$file_url = _RootUrl.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/script.js';
				if(is_file($file)){

					echo '<script type="text/javascript" src="'.$file_url.'"></script>'."\n";
				}
				$file = _RootFolder.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/_script.js';
				$file_url = _RootUrl.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/_script.js';
				if(is_file($file)){

					echo '<script type="text/javascript" src="'.$file_url.'"></script>'."\n";
				}
			}
		}
		return '';
	}

	/**
	* it will call model _style.css file
	*/
	function css(){

		$dir = $this->type == 'plugin' ? 'plugins' : 'models';

		$models = array();
		if( is_array($this->modelPageList) ){

			foreach($this->modelPageList as $v){

				foreach($v as $v1){

					if( ($v1['is_static'] == true || ($v1['model'] == $_GET['model'] && $v1['page'] == $_GET['page']) || ($v1['is_first_page'] == true && !$_GET['model'])) && preg_match('/'.$this->page_position.'/i', $v1['page_position']) ){

						$models[$v1['model']] = $v1['model'];
					}
				}
			}
			foreach($models as $v){

				$file = _RootFolder.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/style.css';
				$file_url = _RootUrl.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/style.css';
				if(is_file($file)){

					echo '<link rel="stylesheet" href="'.$file_url.'" type="text/css"/>'."\n";
				}
				$file = _RootFolder.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/_style.css';
				$file_url = _RootUrl.'/app/'.$dir.'/'.$v.'/views'.(preg_match('/\/admin/i', $_SERVER['REQUEST_URI']) ? '/admin' : '').'/_style.css';
				if(is_file($file)){

					echo '<link rel="stylesheet" href="'.$file_url.'" type="text/css"/>'."\n";
				}
			}
		}
		return '';
	}
}

?>
