<?php

// Devrai y avoir un page controlleur pr tout ce qui est page qui retourne du texte
// comme ca on peut assigner au pc une langue (unique)

/**
* This module contains classes for running a store.
* @module Cyma PHP MainLib
*/


/**
 * @class CubeRequestBase
 * @constructor
 * @param config_file {String} Config filepath
 */
class CubeRequestBase
{
	public $url = array();
	public $get = array();
	public $post = array();
	
	public function __construct(){
		$this->get_url = (isset($_GET['url'])) ? $_GET['url'] : '';
		$this->url = RealExplode('/', $this->get_url);
		$this->get = $_GET;
		$this->post = $_POST;
		$this->hash = sha1(implode('', array_merge(array('cube'),$_GET)));
	}
}

/**
 * @class CubeLangsBase
 * @constructor
 * @param config_file {String} Config filepath
 */
class CubeLangsBase
{
	private $lang_data = array();
	private $lang_defaut;
	public $is_multi;
	public $lang;
	
	public function __construct($config_file){
		$this->lang_data = array();
		foreach($config_file->getElements('lang') as $lg){
			if ( strlen($lg->getAttribute('weburl')) < 1 )
				$lg->setAttribute('weburl', $lg->getAttribute('id'));
			if ( strlen($lg->getAttribute('code')) < 1 )
				$lg->setAttribute('code', $lg->getAttribute('id'));
			$this->lang_data[$lg->getAttribute('id')] = $lg;
			if ( $lg->getAttribute('defaut') == '1' )
				$this->lang_defaut = $lg;
		}
		$this->lang = $this->lang_defaut;
		$this->is_multi = (sizeof($this->lang_data) > 1);
	}
	
	/**
	 * Get lang defaut id
	 *
	 * @method GetDefautId
	 * @return {String} Defaut Lang Id
	 */
	public function GetDefautId(){
		return $this->lang_defaut->getAttribute('id');
	}
	
	/**
	 * Set lang from id if exist
	 *
	 * @method SetLang
	 * @param lang_id {String} Lang Id
	 */
	public function SetLang($lang_id){
		if (isset($this->lang_data[$lang_id]))
			$this->lang = $this->lang_data[$lang_id];
	}
	
	/**
	 * Get lang id
	 *
	 * @method GetLangId
	 * @param [lang_id=false] {String} Lang Id
	 * @return {String} Current lang Id
	 */
	public function GetLangId($lang_id = false){
		if ( $lang_id == false ) return $this->lang->getAttribute('id');
		else return $this->lang_data[$lang_id]->getAttribute('id');
	}
	
	/**
	 * Get all langs ids
	 *
	 * @method GetAllIds
	 * @return {Array} All langs ids
	 */
	public function GetAllIds(){
		$ret = array();
		foreach($this->lang_data as $k=>$v) $ret[] = $k;
		return $ret;
	}
	
	/**
	 * Get lang node attribute value from name (and lang id)
	 *
	 * @method GetLangAtt
	 * @param att {String} Lang node attribute name
	 * @param [lang_id=null] {String} Lang id to get attribute value (defaut: current lang)
	 * @return {String} Lang node attribute value from current or specified lang id
	 */
	private function GetLangAtt($att, $lang_id = false){
		if ( !$lang_id ) return $this->lang->getAttribute($att);
		return $this->lang_data[$lang_id]->getAttribute($att);
	}
	
	/**
	 * Get lang name
	 *
	 * @method GetLangName
	 * @param [lang_id=null] {String} Lang id (defaut: current lang)
	 * @return {String} Lang name
	 */
	public function GetLangName($lang_id = false){
		return $this->GetLangAtt('name', $lang_id);
	}
	
	/**
	 * Get lang weburl
	 *
	 * @method GetLangWeburl
	 * @param [lang_id=null] {String} Lang id (defaut: current lang)
	 * @return {String} Lang weburl
	 */
	public function GetLangWeburl($lang_id = false){
		return $this->GetLangAtt('weburl', $lang_id);
	}

	/**
	 * Get lang code
	 *
	 * @method GetLangCode
	 * @param [lang_id=null] {String} Lang id (defaut: current lang)
	 * @return {String} Lang code
	 */
	public function GetLangCode($lang_id = false){
		return $this->GetLangAtt('code', $lang_id);
	}
}


class SiteBase
{
	// instance de la classe
    private static $instance;
	
	public $title = 'CUBE WebSite';
	public $icon = '';
	public $template = 'defaut';
	public $site_root = '';
	public $site_root_alt = '';
	public $img_root = 'img';
	public $img_mm_root = 'userimgs';
	public $img_fck_root = 'userimgsfck';
	public $imguser_root = 'content/userfiles';
	public $xslsConf = array();
	public $javascript = array();
	public $css = array();
	public $cssie = array();
	public $box = array();
	public $box_names_loaded = array();
	public $langDefaut = 'fr';
	public $lang = 'fr';
	public $langs = array();
	public $langfileloaded = '';
	public $langfile;
	public $lang_all;
	public $lang_name;
	public $lang_data;
	public $data; // computed lang xml files
	public $content;
	public $posline;
	public $kw;
	public $bodyclass;
	public $tw = array();
	public $cat;
	public $cat_lang;
	public $cat_name;
	public $params = array();
	private $xsl;
	public $nl_skin = 1;
	public $admin_lang = 'fr';
	public $xslvalues = array();
	public $xslvar = array();
	public $jsvar = array();
	public $dataLang = array();
	public $catLang = 'fr';
	public $catLangWu = 'fr';
	public $catsLang = array();
	public $catsLangWu = array();
	public $hasShop = false;
	public $shopConfig = array();
	public $mainCatNode = null;
	public $catNode = null;
	public $ccf = null;
	public $itemNode = null;
	public $cif = null;
	public $introSkipped = false;
	public $paramsUnused = array();
	public $paramsUsed = array();
	public $modules = array();

	/**
	 * @var CubeLangs Langs object
	 * @access public
	 */ 
	public $LG; 

	public $cubeType = 'webpage'; // devrai etre ds le page controller
	public $isMobile = false; // devrai etre ds le page controller
	
	private function __construct(){
		
	}
	
	/**
	 * La methode singleton
	 * @return SiteBase
	 */
	public static function singleton() {
		if (!isset(self::$instance)) {
			$c = __CLASS__;
			self::$instance = new $c;
			self::$instance->init();
		}

		return self::$instance;
	}
	
	protected function init(){

		$this->req = new CubeRequest();
		
		$this->ReadConfigFile();
		
		// seulement utile pr le front 
		// get params from url http://www.example.com/getA/getB/getC/getD.../getG
		// test alternate waye using index main dispatcher style
		// using $_GET['url']
		// foreach(array('A','B','C','D','E','F','G') as $v){
		// 	if(isset($_GET['get'.$v]) && !empty($_GET['get'.$v])) $this->params[] = $_GET['get'.$v];
		// 	else break;
		// }
		// $req = (isset($_GET['url'])) ? $_GET['url'] : '';
		$this->params = $this->req->url;
		// seulement utile pr le front
		// show offdata if website is off
		// bypass if cubeaction == 'admin' or if 'forceopen' is in url
		
		// depreced see below for new version
		// $xml = new CymaXml(XML_PATH.'general-infos-'.S()->LG->GetDefautId().'.xml');
		// $is_off = ($xml->getElementHtml('./text/item/activatesite') != '1');

		// this file is managed by lib module page-error-manager
		$is_off = ( is_file(CACHE_PATH.'offtoken') );

		// $in_cube = (isset($_GET['cubeaction']) && $_GET['cubeaction'] == 'admin');
		$in_cube = (isset($this->params[0]) && $this->params[0] == 'cube');
		// var_dump( $_GET['url'] );
		$force_open = ( in_array('forceopen', $this->params) );
		if ( $is_off && !CymaSession::Singleton()->exist('adminlog') && !$in_cube && !$force_open ) {
			echo file_get_contents( XML_PATH.'offdata' );
			exit;
		}
		
		// destroy session if 'cleansession' is in url
		if ( in_array('cleansession', $this->params) ){
			CymaSession::Singleton()->destroy();
		}
		
		// seulement utile pr le front
		// init content xml
		$this->content = new CymaXml();
	}
	
	/**
	 * TODO
	 * ca le fait pas cause le fichier congif est mal foutu
	 * d'un coté il y a les données fixes qui ne change pas qu'on soit sur mobile ou non et de l'autre les données qui peuvent varier suivant le support
	 * données variables : 
	 * css, js, (favico?) , (modules)
	 * d'ailleurs ces données (css, js, favico) ne sont lues que par le front en affichage html, si on renvoi du texte brut et/ou du xml ca ne sert a rien de les lire
	 */
	public function ReadConfigFile(){
		// todo check if mobile and if config-mobile.xml exit load it instead of defaut config file
		if (is_file(ROOT_PATH.'site'.DS.'mobile.config.xml')) {
			include LIB_PATH.'Mobile_Detect.php';
			$detect = new Mobile_Detect();
			$is_mobile = $detect->isMobile();
			//$is_mobile = true;
			if ( $is_mobile ){
				$config_file = new CymaXml(ROOT_PATH.'site'.DS.'mobile.config.xml');
				$this->isMobile = true;
				$this->cubeType = 'mobilepage';
			}
		}
		if ( !isset($config_file) ) {
			$config_file = new CymaXml(ROOT_PATH.'site'.DS.'config.xml');
		}
		$lib_config_file = new CymaXmlRead(LIB_PATH.'config.xml');
		// ca ok c tout le temps utile
		$this->title = $config_file->getElementHtml('nom');

		// ca c'est utile que ds le back office
		if ( strlen($config_file->getElementHtml('cubelang')) > 0 ) {
			$this->admin_lang = $config_file->getElementHtml('cubelang');
		}

		// ca c'est utile que ds le front en rendu html (comme le css et le js en fait)
		$this->icon = $config_file->getElementHtml('icon');
		
		// useless total
		$this->cssie = $config_file->getElementsHtml('cssie');
		
		// a appellé uniquement par le viewer html
		foreach($config_file->getElements('css') as $css){
			$is_asset = ($css->getAttribute('asset') == '1');
			$is_print = ($css->getAttribute('print') == '1');
			$this->css[] = array($css->nodeValue, $is_asset, $is_print);
		}

		// a appellé uniquement par le viewer html
		foreach($config_file->getElements('js') as $js){
			$is_asset = ($js->getAttribute('asset') == '1');
			$is_head = ($js->getAttribute('head') == '1');
			$this->javascript[] = array($js->nodeValue, $is_asset, $is_head);
		}

		// a appellé uniquement par le viewer html et/ou ds cubecache
		// if ( defined('IN_PROD') && IN_PROD ){
		// 	if ( CUBE_ACTION == 'site')
		// 		$this->changeJsUrls();
		// 	elseif ( CUBE_ACTION == 'cubecache')
		// 		$this->CreateCombinedJs();
		// }

		// je ne sais pas ce que c'est, a voir
		foreach($config_file->getElements('xsl') as $xsl){
			$is_asset = ($xsl->getAttribute('asset') == '1');
			$this->xslsConf[] = array($xsl->nodeValue, $is_asset);
		}

		// // new !!!!
		// foreach($config_file->getElements('module') as $module){
		// 	$module_name = $module->nodeValue;
		// 	$folder = ($module->getAttribute('asset') == '1') ? ASSET_PATH.'modules'.DS : ROOT_PATH.'site'.DS.'assets'.DS.'modules'.DS;
		// 	if ( is_file($folder.$module_name.'.php') ) {
		// 		require_once $folder.$module_name.'.php';
		// 	}
		// 	$this->modules[] = $module_name;
		// }

		// new  2!!!!
		// read basics modules from LIB_PATH/config.xml
		foreach($lib_config_file->getElements('module') as $module_node){
			$module_node->setAttribute('base', '1');
			CubeModules::_()->registerModule($module_node);
			// $module_name = $module_node->nodeValue;
			// $this->modules[$module_name] = new CubeModule($module_name, $module_node);
		}

		foreach($config_file->getElements('module') as $module_node){
			CubeModules::_()->registerModule($module_node);
			// $module_name = $module_node->nodeValue;
			// $this->modules[$module_name] = new CubeModule($module_name, $module_node);
		}

		// utile uniquement pr le controller qui parse du xsl
		foreach($config_file->getElements('box') as $b)
			$this->box[$b->getAttribute('id')] = explode(';', $b->nodeValue);
		
		// Ca c'est utile aussi	
		$this->LG = new CubeLangs($config_file);
		
		$this->shop_node = $config_file->getElement('shop');
		if ( $this->shop_node ){
			$this->hasShop = true;
			foreach($this->shop_node->childNodes as $sn){
				$o = array();
				foreach($sn->attributes as $k=>$v){
					$o[$v->name] = $v->value;
				}
				$this->shopConfig[$sn->nodeName] = (object)$o;
			}
		}

		// ca aussi c'est utile
		$this->sql_node = $config_file->getElement('sql');
		if ( $this->sql_node ){
			$this->hassql = true;
			foreach($this->sql_node->childNodes as $sn){
				$o = array();
				foreach($sn->attributes as $k=>$v){
					$o[$v->name] = $v->value;
				}
				$this->sqlConfig[$sn->nodeName] = (object)$o;
			}
		}

		$this->site_root = SITE_ROOT.'/';
		$this->site_root_alt = SITE_ROOT.'/';
	}
	
	// devrai se faire une bonne fois pr toute en ecrivant ca ds le cache avec un controller de hash pr voir si un fichier est modif tant k'on est pas en prod
	// $this->javascript = array(url, is_asset, is_in_head, is_cache)
	public function changeJsUrls(){
		$jss_head = false;
		$jss = false;
		$jss_http = array();
		foreach($this->javascript as $js){
			if ( strpos(' '.$js[0], 'http') && strpos($js[0], '://') ) {
				$jss_http[] = $js;	
			}
			elseif ( $js[2] == true ) {
				$jss_head = true;
			}
			else {
				$jss = true;
			}
		}
		$this->javascript = $jss_http;
		if ( $jss_head ) {
			$this->javascript[] = array('site-head.js', false, true, true);
		}
		if ( $jss ) {
			$this->javascript[] = array('site.js', false, false, true);
		}
		
	}
	
	// devrai pas etre la, devrai etre appellé par le viewer qui rend du html uniquement et/ou via cubecache pr la generation des fichiers ac le closure compiler
	// pas en prod : regen cyma.css et les js
	public function CreateCombinedJs(){
		var_dump('heeeeere');
		$force = 0;
		$jss = array();
		$jss_head = array();
		foreach($this->javascript as $js){
			if ( strpos(' '.$js[0], 'http') && strpos($js[0], '://') ) {
				continue;
			}
			
			$js_cache_file = CACHE_PATH.'js'.DS.$js[0];
			$js_cache_file = str_replace('/', DS, $js_cache_file);

			$js_file = ( $js[1] == true ) ? ASSET_PATH.$js[0] : ROOT_PATH.'site'.DS.'assets'.DS.$js[0];
			$js_file = str_replace('/', DS, $js_file);

			$last_crc = '';
			if ( is_file($js_cache_file.'.crc') ) {
				$last_crc = file_get_contents($js_cache_file.'.crc');
			}

			$current_crc = md5_file($js_file);

			

			if ( $js[2] == true ) {
				$jss_head[] = $js_cache_file;
			}
			elseif (strpos($js_file, '-min.js')) {
				$jss[] = $js_file;
				continue;
			}
			else {
				$jss[] = $js_cache_file;
			}

			// file not changed and not forced to reload so do nothing
			if ( is_file($js_cache_file) && $last_crc == $current_crc && !$force){
				continue;
			}
			var_dump(substr($js_cache_file, 0, strrpos($js_cache_file, DS)));
			CymaFile::CreateFolder(substr($js_cache_file, 0, strrpos($js_cache_file, DS)));

			var_dump($js_file);

			$cc_path = ASSET_PATH.'modules'.DS.'ccparser'.DS.'compiler.jar';

		    if ( is_file($cc_path) ) {
	    		$cmd = 'java -jar "'.$cc_path.'" --js "'.$js_file.'" --js_output_file "'.$js_cache_file.'"';

	    	    $cmd_out = shell_exec ( $cmd );
		    }
		    else {
		    	// try request mode
		    	// $ch = curl_init('http://closure-compiler.appspot.com/compile');
		    	$ch = curl_init('http://178.32.222.178/clients/tools/cc/cc.php');
		    	 
		    	curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		    	curl_setopt($ch, CURLOPT_POST, 1);
		    	// curl_setopt($ch, CURLOPT_POSTFIELDS, 'output_info=compiled_code&output_format=text&compilation_level=SIMPLE_OPTIMIZATIONS&js_code=' . urlencode(file_get_contents($js_file)));
		    	curl_setopt($ch, CURLOPT_POSTFIELDS, 'js_code=' . base64_encode(file_get_contents($js_file)));

		    	$output = curl_exec($ch);
		    	var_dump($cmd);
		    	var_dump($can_run);
		    	// curl_close($ch);

		    	file_put_contents($js_cache_file, $output);
		    }

			// var_dump($can_run);

			file_put_contents($js_cache_file.'.crc', $current_crc);
			
		}
		/*
		//var_dump($jss);
		$real_cache_path = CACHE_PATH.'site.js';
		$last_mod_saved = '0';
		if (is_file($real_cache_path.'.cache')) {
			$t = file($real_cache_path.'.cache', FILE_IGNORE_NEW_LINES);
			$last_mod_saved = $t[0];
		}
		//var_dump($last_mod_saved);
		//var_dump($md5);
		if ( $last_mod_saved != $md5 ) { // regenere js
		*/
			$data = array();
			foreach($jss as $js) {
				$data = array_merge($data, file($js),array("\r\n"));
			}
			file_put_contents(CACHE_PATH.'site.js', $data);
			$data = array();
			foreach($jss_head as $js) {
				$data = array_merge($data, file($js),array("\r\n"));
			}
			file_put_contents(CACHE_PATH.'site-head.js', $data);
			//var_dump(sizeof($data));
			// file_put_contents($real_cache_path.'.cache', $md5);
		// }
	}
	
	// todo should go in page controller
	public function GetLanFromUrl(){
		// if $this->LG->isMulti == true semble mieux approprié
		if ( sizeof($this->params)>0 ){
			foreach($this->LG->GetAllIds() as $lg_id){
				if ( in_array($this->LG->GetLangWeburl($lg_id), $this->params) ){
					$this->setLang($lg_id);
					// write cookie with current lang
					//var_dump('lang in url');
					setcookie('savlang', $this->LG->GetLangId(), time()+(3600*24*365), '/');
					return;
				}
			}
		}
		// nolang in url so check in cookie if there was a prefered language used before
		if ( isset($_COOKIE['savlang']) && strlen($_COOKIE['savlang']) > 0) {
			//var_dump('lang in cookie');
			//var_dump($_COOKIE['savlang']);
			$this->setLang($_COOKIE['savlang']);
			return;
		}
		//var_dump('find lang');
		$accepted = parseLanguageList();
		//var_dump($accepted);
		$available = parseLanguageList(implode(',',$this->LG->GetAllIds()));
		//var_dump($available);
		$matches = findMatches($accepted, $available);
		//var_dump($matches);
		if ( sizeof($matches) > 0 ){
			$ma = array_shift($matches);
			//var_dump($ma);
			$this->setLang($ma[0]);
			setcookie('savlang', $this->LG->GetLangId(), time()+(3600*24*365), '/');
		}
		// if no cookie check in header to detect best match language
		// write cookie with current lang
	}
	
	public function ChangeLang($lg){
		foreach($this->LG->GetAllIds() as $lg_id){
			if ( $this->LG->GetLangWeburl($lg_id) == $lg ) {
				$this->setLang($lg_id);
				break;
			}
		}
		$this->cat = new CymaXml(CACHE_PATH.'cache-'.$this->LG->GetLangId().'.xml');
	}
	
	public function InitSitePage(){
		
		// create posline element in content
		$this->posline = $this->content->createElement('posline','',$this->content);
		// create kw element in content
		$this->kw = $this->content->createElement('kw','',$this->content);
		// create bodyclass element in content
		$this->bodyclass = $this->content->createElement('bodyclass','',$this->content);
		
		$this->site_root = SITE_ROOT.'/';
		$this->site_root_alt = SITE_ROOT.'/';
		
		//$this->main_controller = new SiteMainController();
		
		$this->GetLanFromUrl();
		
		$this->cat = new CymaXml(CACHE_PATH.'cache-'.$this->LG->GetLangId().'.xml');
		
		$this->GetNodeFromUrl();
		
		
	}
	
	public function InitSiteCats(){
		$this->cat = new CymaXml(CACHE_PATH.'cache-'.S()->LG->GetLangId().'.xml');
	}
	
	public function InitAdminCats(){
		$this->cat = new CymaXml(ROOT_PATH.'site'.DS.'category.xml');
		$this->readCats();
	}
	
	public function GetNodeFromUrl(){
		$mainwu = implode('/', $this->params);
		$cat_selected = $this->cat->getElement('//cat[@mainwu="'.$mainwu.'"]');
		// si pas de cat select
		// chercher une categorie en reduisant l'url
		if ( !$cat_selected && sizeof($this->params)>1 ){
			$temp_params = $this->params;
			$unused_params = array();
			while(!$cat_selected && sizeof($temp_params)>1){
				$unused_params[] = array_pop($temp_params);
				$temp_mainwu = implode('/', $temp_params);
				$cat_selected = $this->cat->getElement('//cat[@mainwu="'.$temp_mainwu.'"]');
			}
			$this->paramsUnused = array_reverse($unused_params);
			$this->paramsUsed = $temp_params;
		}

		if ( !$cat_selected ) $cat_selected = $this->cat->getElement('//cat[@sitedefault="1"]');
		if ( !$cat_selected ) $cat_selected = $this->cat->getElement('//cat[@uid="site"]/cat[not(@display="hidden")]');
		if ( !$cat_selected ) exit;
		$redirect_url = '';
		if ( $cat_selected->getAttribute('display') == 'hidden' || $this->cat->getElement('./ancestor::cat[@display="hidden"]', $cat_selected) ){
			//var_dump('t');
			$redirect_url = '/'.$this->cat->getElement('./ancestor::cat[not(@display="hidden") and not(@nopage="1")]', $cat_selected)->getAttribute('mainwu');
		}
		// si la cat select n'a pas de page chercher : 
		
		
		if ( $cat_selected->getAttribute('nopage') == '1' || sizeof($this->paramsUnused) > 0 ){
			// un item dans la liste si la categorie a l'attribute listwu="1"
			if ( $cat_selected->getAttribute('listwu') == '1' ){
				// regarder si il y a un params qui correspond à l'url d'un item
				if ( sizeof($this->paramsUnused) > 0 ){
					$item_selected = $this->cat->getElement('./list/item[not(@display="hidden") and @weburl="'.$this->paramsUnused[0].'"]', $cat_selected);
					if ( $item_selected ) {
						$this->paramsUsed[] = array_pop($this->paramsUnused);
					}
				}
				if ( !isset($item_selected) || !$item_selected ){
					$item_selected = $this->cat->getElement('./list/item[not(@display="hidden")]', $cat_selected);
				}
				if ( sizeof($this->paramsUnused) > 0 ){
					$cat_selected = $this->cat->getElement('./cat[not(@display="hidden") and @weburl="'.$this->paramsUnused[0].'"]', $cat_selected);
					if ( $cat_selected ) {
						$this->paramsUsed[] = array_pop($this->paramsUnused);
					}
				}
			}
			elseif ( $item_selected = $this->cat->getElement('./list/item[not(@display="hidden") and @mainwu="'.$mainwu.'"]', $cat_selected) ){
				// regarder si il y a un params qui correspond à l'url d'un item
				$this->paramsUsed = array();
			}
			else {
				// une cat :
				// // 	dans les cat enfants
				if ( $t = $this->cat->getElement('.//cat[not(@display="hidden") and not(@nopage="1")]', $cat_selected) ){
					if ( $cat_selected->getAttribute('noredirect') != '1' ) $redirect_url = '/'.$t->getAttribute('mainwu');
					else $cat_selected = $t;
				}
				// 	ou dans les cats parents
				else {
					$t = $this->cat->getElement('./ancestor::cat[not(@display="hidden") and not(@nopage="1")]', $cat_selected);
					if ( $cat_selected->getAttribute('noredirect') != '1' ) $redirect_url = '/'.$t->getAttribute('mainwu');
					else $cat_selected = $t;
				}
			}
		}
		if ( $redirect_url ){
			header("HTTP/1.1 303 See Other");
			if ( isset($_GET['cubeaction']) && $_GET['cubeaction'] == 'ajaxpage' ){
				$redirect_url = '/ajaxpage'.$redirect_url;
			}
			header('Location: '.SITE_ROOT.$redirect_url);
		}
		//var_dump($cat_selected->getAttribute('uid'));
		$k = $this->cat->getElement('./seo/item', $cat_selected);
		if ( $k )  $k->setAttribute('currentseo','1');
		
		$cat_selected->setAttribute('finalcat','1');
		if ( isset($item_selected) && $item_selected ) {
			$item_selected->setAttribute('finalitem','1');
			$this->cif = $item_selected;
		}
		if ( DEBUG ) $this->cat->enr(LOG_PATH.'111.xml');
		if ( $cat_selected->hasAttribute('xsltemplate') )
			$this->setBox('bloccontent', $cat_selected->getAttribute('xsltemplate'));
		elseif ( $cat_selected->getAttribute('customcat') == '1' ){
			$dt = $cat_selected->parentNode;
			while($dt->getAttribute('customcat') == '1' && !$dt->hasAttribute('xsltemplate') ){
				$dt = $dt->parentNode;
			}
			//var_dump($dt->getAttribute('id'));
			if ( $dt->hasAttribute('xsltemplate') )
				$this->setBox('bloccontent', $dt->getAttribute('xsltemplate'));
			else $this->setBox('bloccontent', $dt->getAttribute('id'));
		}
		else $this->setBox('bloccontent', $cat_selected->getAttribute('id'));
		
			
		
		if ( strlen($cat_selected->getAttribute('maintemplate')) > 0 ){
			//var_dump($cat_selected->getAttribute('maintemplate'));
			$this->setTemplate($cat_selected->getAttribute('maintemplate'));
		}
		//$this->mainCatNode = $main_cat_selected;
		$this->catNode = $cat_selected;
		$this->ccf = $cat_selected;
		while($cat_selected->getAttribute('mc') != '1'){
			$cat_selected->setAttribute('catselected', '1');
			$this->mainCatNode = $cat_selected;
			$cat_selected = $cat_selected->parentNode;
		}
		
		// setup one cat founded
		// write seo node in writePage()
		// use lib template to create seo nodes (or current template seo if provided
		$this->setupSeo();
		
		
	}
	
	public function setupSeo(){
		// title
		$this->seoTitle = $this->cat->getElementHtml('//cat[@id="infos"]/text/item/titresite');
		$this->seoSiteName = $this->seoTitle;
		$detail_title = $this->cat->getElementHtml('./seo/item/seotitre', $this->catNode);
		if ( strlen($detail_title) == 0 && strlen($this->catNode->getAttribute('noseotitle')) == 0 )
			$detail_title = $this->catNode->getAttribute('name');
		if ( strlen($this->seoTitle) > 0 && strlen($detail_title) > 0 )
			$this->seoTitle = ' - '.$this->seoTitle;
		$this->seoTitle = $detail_title.$this->seoTitle;
		
		// keywords
		$kw = explode(',',$this->cat->getElementHtml('//cat[@id="infos"]/text/item/kwsite'));
		$kw = array_merge($kw,explode(',',$this->cat->getElementHtml('./seo/item/seokw', $this->catNode)));
		$kw = array_unique($kw);
		$this->seoKw = implode(',',$kw);
		
		$model_node = $this->cat->getElement('//model[@id="'.$this->catNode->getAttribute('model').'"]');
		// description
		$txt = $this->cat->getElementHtml('./seo/item/seodesc', $this->catNode);
		if ( strlen($txt) < 1 ){
			
			// get first input element with type=fck|bloc
			$inp = $this->cat->getElement('./box/template/tab/input[@seodesc="1"]', $model_node);
			if ( !$inp )
				$inp = $this->cat->getElement('./box[not(@multi="1") and not(@id="seo")]/template/tab/input[@type="fck" or @type="bloc"]', $model_node);
			//var_dump($inp->getAttribute('code'));
			if ( !$inp )
				$inp = $this->cat->getElementHtml('./box/template/tab/input[@type="fck" or @type="bloc"]', $model_node);
			if ( $inp ){
				$box_name = $inp->parentNode->parentNode->parentNode->getAttribute('id');
				$txt = $this->cat->getElementHtml('./'.$box_name.'/item/'.$inp->getAttribute('code'), $this->catNode);
			}
		}
		// add main site desc if txt empty
		$this->seoDesc = txtLineCut($txt, 200, 0);
		
		// thumbnail
		// 1. check if there is one in seo
		// 2. check input in model with att seothumb="1"
		// 3. check for first input[@type="videos" or @type="images"]
		// 3. check for first input[@type="videos" or @type="images"] in multi box
		$txt = $this->cat->getElementHtml('./seo/item/seothumb/i', $this->catNode);
		if ( strlen($txt) < 1 ){
			$inp = $this->cat->getElement('./box/template/tab/input[@seothumb="1"]', $model_node);
			if ( !$inp )
				$inp = $this->cat->getElement('./box[not(@multi="1") and not(@id="seo")]/template/tab/input[@type="videos" or @type="images"]', $model_node);
			if ( !$inp )
				$inp = $this->cat->getElementHtml('./box/template/tab/input[@type="videos" or @type="images"]', $model_node);
			if ( $inp ){
				$box_name = $inp->parentNode->parentNode->parentNode->getAttribute('id');
				$node_name = ($inp->getAttribute('type') == 'videos') ? 'v' : 'i';
				$txt_node = $this->cat->getElement('./'.$box_name.'/item/'.$inp->getAttribute('code').'/'.$node_name, $this->catNode);
				if ( $txt_node ){
					if ( $node_name == 'v' ) {
						$format = $inp->getAttribute('format');
						if ( strlen($format) < 1 ) $format = 'rcm_300_160';
						$txt = SITE_ROOT.'/cvii/'.$txt_node->getAttribute('vpr').'/'.$format.'/'.$txt_node->getAttribute('vid');
					}
					else {
						$format = $inp->getAttribute('format');
						if ( strlen($format) < 1 ) $format = 'rcm_300_200';
						$txt = SITE_ROOT.'/ci/'.$format.'/'.$txt_node->nodeValue;
					}
				}
			}
		}
		else $txt = SITE_ROOT.'/ci/rcm_300_200/'.$txt;
		$this->seoThumb = $txt;
		
		$this->seoUrl = SITE_ROOT.'/'.$this->catNode->getAttribute('mainwu');
	}
	
	public function resetPageSelected(){
		// TODO clean reset
		
	}
	
	public function readCats(){
		$cat_obj = new CymaCatFiller($this->cat, S()->LG->GetLangId());
		$this->cat = $cat_obj->CompleteAll();
		if ( DEBUG ) {
			// $this->cat->save(LOG_PATH.'0000.xml');
		}
	}
		
	public function setLang($lg){
		//if(isset($this->lang_data[$lg])) $this->lang = $lg;
		//$this->lang_all = array_merge( array($this->lang) , (array)explode(';',$this->lang_data[$this->lang]) );
		$this->LG->SetLang($lg);
	}
	
	public function setBox($key, $value){
		if(is_string($key) && strlen($key)>0){
			if( (is_string($value) && strlen($value)>0) || (is_array($value)) ){
				$this->box[$key] = (array)$value;
			}
		}
	}
	
	public function getBox(){
		return $this->box;
	}
	
	public function setTitle($title = ''){
		if(is_string($title) && strlen($title)>0){
			$this->title = $title;
		}
	}
	
	public function getTitle(){
		
	}
	
	public function setTemplate($template){
		//var_dump($template);
		if(is_string($template) && strlen($template)>0){
			$this->template = $template;
		}
	}
	
	public function getTemplate(){
		return $this->template;
	}
	
	public function clearJavascript(){
		$this->javascript = array();
	}
	
	public function addJavascript($javascript, $is_asset = false, $is_head = false){
		if( (is_string($javascript) && strlen($javascript)>0) ){
			$this->javascript[] = array($javascript, $is_asset, $is_head);
		}
	}
	
	public function getJavascript(){
		return $this->javascript;
	}
	
	public function clearCss($css){
		$this->css = array();
	}
	
	public function addCss($css, $is_asset = false, $is_print = false){
		if( (is_string($css) && strlen($css)>0) ){
			$this->css[] = array($this->css, $is_asset, $is_print);
		}
	}
	
	public function getCss(){
		return $this->css;
	}
	
	public function readBoxes(){
		//var_dump($this->template);
		$xsl_filepath = '';
		// on regarde d'abord ds les templates pr mobile
		if ( $this->isMobile ){
			// en 1er dans ROOT_PATH
			if ( is_file(ROOT_PATH.'site'.DS.'templates'.DS.'mobile.template-'.$this->template.'.xsl') )
				$xsl_filepath = ROOT_PATH.'site'.DS.'templates'.DS.'mobile.template-'.$this->template.'.xsl';
			// en 2e dans ASSET_PATH
			elseif ( is_file(ASSET_PATH.'templates'.DS.'pages'.DS.'mobile.template-'.$this->template.'.xsl') )
				$xsl_filepath = ASSET_PATH.'templates'.DS.'pages'.DS.'mobile.template-'.$this->template.'.xsl';
		}
		// si $xsl_filepath tjs vide on regarde d'abord ds les templates normaux
		if ( empty($xsl_filepath) ){
			// en 1er dans ROOT_PATH
			if ( is_file(ROOT_PATH.'site'.DS.'templates'.DS.'template-'.$this->template.'.xsl') )
				$xsl_filepath = ROOT_PATH.'site'.DS.'templates'.DS.'template-'.$this->template.'.xsl';
			// en 2e dans ASSET_PATH
			elseif ( is_file(ASSET_PATH.'templates'.DS.'pages'.DS.'template-'.$this->template.'.xsl') )
				$xsl_filepath = ASSET_PATH.'templates'.DS.'pages'.DS.'template-'.$this->template.'.xsl';
		}
		$xsl = new CymaXml($xsl_filepath);
		$xsllib = new CymaXml(ASSET_PATH.'lib.xsl');
		foreach($this->xslsConf as $conf_xsl_file){
			$fp = ROOT_PATH.'site'.DS.'templates'.DS.$conf_xsl_file[0];
			if ( $conf_xsl_file[1] == true ) $fp = ASSET_PATH.$conf_xsl_file[0];
			$dc = new CymaXml($fp);
			$r = $xsl->inject($xsl->documentElement->childNodes->item(2), $dc->documentElement->childNodes, 'before');
		}
		
		foreach( CubeModules::_()->getTemplatesXsls() as $tpl_xsl_file_path ){
			$dc = new CymaXml($tpl_xsl_file_path);
			$r = $xsl->inject($xsl->documentElement->childNodes->item(2), $dc->documentElement->childNodes, 'before');
		}
		
		$r = $xsl->inject($xsl->documentElement->childNodes->item(2), $xsllib->documentElement->childNodes, 'before');
		//var_dump($r);
		
		foreach($this->xslvar as $k=>$v){
			$e = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:variable');
			$e->setAttribute('name', $k);
			$e->setAttribute('select', "'".$v."'");
			$xsl->documentElement->insertBefore($e, $xsl->documentElement->childNodes->item(2));
		}
		//$xsl->documentElement->insertBefore($e, $xsl->documentElement->childNodes->item(2));
		$this->xsl = $xsl;
		$this->parseCubeElements($this->xsl);
		return $this->box_names_loaded;
	}
	
	public function LoadBoxFile($xsl_filepath){
		$xslbox = new CymaXml();
		try {
			$xslbox -> loadXML('<?xml version="1.0" encoding="UTF-8"?><xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">'.file_get_contents($xsl_filepath).'</xsl:stylesheet>');
		}
		catch (CymaErrorException $e){
			$e->displayFatalError();
		}
		$xslbox->documentElement->firstChild->setAttribute('mode', 'mainbox');
		
		return $xslbox;
	}
	
	public function parseCubeElements(&$xsl){
		while($b = $xsl->getElement('//boxtemplate')){
			$box_key = $b->getAttribute('name');
			$box_names = '';
			if(!isset($this->box[$box_key])) $box_names = array($box_key);
			elseif(is_array($this->box[$box_key])) $box_names = $this->box[$box_key];
			elseif(strlen($this->box[$box_key])>0) $box_names = array($this->box[$box_key]);
			else $box_names = array($box_key);
			$xslfounded = false;
			foreach($box_names as $filename){
				$e = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:apply-templates');
					
				$e->setAttribute('select', '/site/content/'.$filename); 
				$e->setAttribute('mode', 'mainbox'); 
				$b->parentNode->insertBefore($e, $b);
				
				$xsl_filepath = '';
				if ( $this->isMobile) {
					if ( is_file(ROOT_PATH.'site'.DS.'templates'.DS.'mobile.box.'.$filename.'.xsl') ){
						$xsl_filepath = ROOT_PATH.'site'.DS.'templates'.DS.'mobile.box.'.$filename.'.xsl';
					}
					elseif ( is_file(LIB_PATH.'assets'.DS.'templates'.DS.'pages'.DS.'box.mobile.'.$filename.'.xsl') ){
						$xsl_filepath = LIB_PATH.'assets'.DS.'templates'.DS.'pages'.DS.'box.mobile.'.$filename.'.xsl';
					}
				}
				if ( empty($xsl_filepath) ) {
					$xsl_filepath = ROOT_PATH.'site'.DS.'templates'.DS.'box.'.$filename.'.xsl';
					if(!is_file($xsl_filepath))
						$xsl_filepath = LIB_PATH.'assets'.DS.'templates'.DS.'pages'.DS.'box.'.$filename.'.xsl';
				}
				if(is_file($xsl_filepath)){
					$xslbox = $this->LoadBoxFile($xsl_filepath);
					$xsl->appendInnerHtml($xsl->documentElement, $xslbox->documentElement->childNodes);
				}
				$this->box_names_loaded[] = $filename;
			}
			$xsl->delElement($b);
		}
		CubeXsl::parse($xsl);
		return;
		while($d = $xsl->getElement('//cube')){
			if ( $d->getAttribute('type') == 'checkbox' ){
				$t = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:apply-templates');
				$t->setAttribute('select', $d->getAttribute('select').'/si');
				$t->setAttribute('mode', $d->getAttribute('mode').'sicheckboxft');
				$xsl->inject($d, $t, 'before');
				
				$dd = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:template');
				$dd->setAttribute('match', 'si');
				$dd->setAttribute('mode', $d->getAttribute('mode').'sicheckboxft');
				
				
				$dt = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:apply-templates');
				$dt->setAttribute('select', '$cr//*[@uid=current() and not(@display="hidden")]');
				$dt->setAttribute('mode', $d->getAttribute('mode'));
				$xsl->inject($dd, $dt);
				$xsl->inject($xsl->documentElement, $dd);
			}
			elseif ( $d->getAttribute('type') == 'menu' ){
				$t = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:apply-templates');
				$t->setAttribute('select', $d->getAttribute('select'));
				$t->setAttribute('mode', 'cubemenu');
				
				$tt = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:sort');
				$tt->setAttribute('select', '@w');
				$tt->setAttribute('data-type', 'number');
				$tt->setAttribute('order', 'descending');
				
				$xsl->inject($t, $tt);
				$xsl->inject($d, $t, 'before');
				
			}
			elseif ( $d->getAttribute('type') == 'gmap' ){
				$t = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:call-template');
				$t->setAttribute('name', 'cubegmap');
				
				$tt = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:with-param');
				$tt->setAttribute('name', 'node');
				$tt->setAttribute('select', $d->getAttribute('select'));
				$xsl->inject($t, $tt);
				
				$tt = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:with-param');
				$tt->setAttribute('name', 'width');
				$tt->setAttribute('select', "'".$d->getAttribute('w')."'");
				$xsl->inject($t, $tt);
				
				$tt = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:with-param');
				$tt->setAttribute('name', 'height');
				$tt->setAttribute('select', "'".$d->getAttribute('h')."'");
				$xsl->inject($t, $tt);
				
				$tt = $xsl->createElementNS('http://www.w3.org/1999/XSL/Transform','xsl:with-param');
				$tt->setAttribute('name', 'noprocessonload');
				$tt->setAttribute('select', "'".$d->getAttribute('noprocessonload')."'");
				$xsl->inject($t, $tt);
				
				$xsl->inject($d, $t, 'before');
				
			}
			else {
				/*
				$cube_module = $d->getAttribute('type');
				$cm_path = ASSET_PATH.'modules'.DS.$cube_module.DS.$cube_module.'.php';
				if ( !is_file($cm_path) ){
					continue;
				}
				require_once $cm_path;
				$cube_module::parseCubeNode($xsl, $d);
				*/
			}
			$xsl->delElement($d);
		}
		
		
	}
	
	// set header
	// set asset
	// set seo
	// set content
	// set alt langs cats
	// then transform everything into html via xsl
	public function displayPage(){
		$xmlok = new CymaXml();
		$xmlok->formatOutput = true;
		$xmlok_site = $xmlok->createElement('site', '', $xmlok);
		$cube_node = $xmlok->createElement('cube', '', $xmlok_site);
		$cube_node->setAttribute($this->cubeType, '1');
		$head = $xmlok->createElement('head', '', $xmlok_site);
		$head->setAttribute('siteroot', $this->site_root); // Website Root Url
		$head->setAttribute('ca', ASSETS_URL);
		$head->setAttribute('lang', $this->LG->GetLangId()); //$this->lang); // Page Language code (iso)
		$head->setAttribute('langcode', $this->LG->GetLangCode()); //$this->lang); // Page Language code (iso)
		$head->setAttribute('title', $this->title);
		$head->setAttribute('icon', $this->icon); // Favicon Name
		foreach($this->xslvalues as $k=>$v){
			$head->setAttribute($k, $v);
		}
		$siteroot_lg = ($this->LG->is_multi) ? $this->site_root.$this->LG->GetLangWeburl().'/' : $this->site_root;
		$head->setAttribute('siterootlg', $siteroot_lg); // Website Root Url with lang
		/* Fix for Apple mobile device smoothing images */
		if (isset($_SERVER['HTTP_USER_AGENT']))
		{
			$ua = strtolower($_SERVER['HTTP_USER_AGENT']);
			if (strpos($ua, 'ipad') !== false || strpos($ua, 'ipod') !== false ||strpos($ua, 'iphane') !== false)
			{
				$head->setAttribute('applefix', '1');
			}
		}
		/*
		$gnrl_node = $this->cat->getElement('//cat[@id="infos"]');
		$head->setAttribute('title', $this->cat->getElementHtml('./text/item/titresite', $gnrl_node));
		$head->setAttribute('seokw', $this->cat->getElementHtml('./text/item/kwsite', $gnrl_node));
		$head->setAttribute('seodesc', $this->cat->getElementHtml('./text/item/descriptionsite', $gnrl_node));
		*/
		$seo = $xmlok->createElement('seo', '', $head);
		$xmlok->createElement('title', $this->seoTitle, $seo);
		$xmlok->createElement('sitename', $this->seoSiteName, $seo);
		$xmlok->createElement('kw', $this->seoKw, $seo);
		$xmlok->createElement('desc', $this->seoDesc, $seo);
		$xmlok->createElement('thumb', $this->seoThumb, $seo);
		$xmlok->createElement('url', $this->seoUrl, $seo);
		
		foreach($this->jsvar as $k=>$v){
			$e = $xmlok->createElement('javascriptvar', '', $head);
			$e->setAttribute('name', $k);
			$e->setAttribute('value', $v);
		}
		
		foreach($this->javascript as $js){
			$js_filename = $js[0];
			// if filename is an url
			if ( !strpos( '-'.$js_filename, 'http://') ){
				// change directory seperator
				$js_filename = str_replace('/', DS, $js[0]);
				// get real filepath
				$js_path = ( isset($js[3]) && $js[3] == true ) ? CACHE_PATH : ( ( $js[1] ) ? ASSET_PATH : ROOT_PATH.'site'.DS.'assets' );
				$js_filepath = $js_path.DS.$js_filename;
				$js_filename = explode('/',$js[0]);
				$js_filename_last = sha1_file($js_filepath).array_pop($js_filename);
				$js_filename[] = $js_filename_last;
				$js_filename = implode('/', $js_filename);
			}
			$jsn = $xmlok->createElement('javascript', $js_filename , $head);
			//$jsn = $xmlok->createElement('javascript', $js[0], $head);
			if ( $js[1] ) $jsn->setAttribute('asset', '1');
			if ( $js[2] ) $jsn->setAttribute('head', '1');
			if ( isset($js[3]) && $js[3] == true ) $jsn->setAttribute('cache', '1');
		}
		
		foreach ( CubeModules::_()->getFrontJss() as $js_data ) {

			$jsn = $xmlok->createElement('javascript', $js_data[0] , $head);
			if ( $js_data[1] ) $jsn->setAttribute('asset', '1');
			// if ( $js_data[2] ) $jsn->setAttribute('head', '1');
			// if ( isset($js_data[3]) && $js_data[3] == true ) $jsn->setAttribute('cache', '1');
		}
		
		//$this->css[] = array('style-'.$this->lang.'.css', false);
		foreach($this->css as $css){
			$css_filename = $css[0];
			// if filename is an url
			if ( !strpos('-'.$css_filename,'http://') ){
				// change directory seperator
				$css_filename = str_replace('/', DS, $css[0]);
				// get real filepath
				$css_path = ( $css[1] ) ? ASSET_PATH : ROOT_PATH.'site'.DS.'assets';
				//$css_filepath = $css_path.DS.$css_filename;
				//$css_filename = sha1_file($css_filepath).$css[0];

				$css_filepath = $css_path.DS.$css_filename;
				$css_filename = explode('/',$css[0]);
				$css_filename_last = sha1_file($css_filepath).array_pop($css_filename);
				$css_filename[] = $css_filename_last;
				$css_filename = implode('/', $css_filename);
			}
			$cssn = $xmlok->createElement('css', $css_filename , $head);
			if ( $css[1] ) $cssn->setAttribute('asset', '1');
			if ( $css[2] ) $cssn->setAttribute('print', '1');
		}
		/*
		foreach($this->cssie as $cssie)
			$xmlok->createElement('cssie', $cssie, $head);
		
		*/
		$xmlok->createElement('content', $this->content->childNodes, $xmlok_site);
		//$xmlok->createElement('lg', $this->data->documentElement->childNodes, $xmlok_site);
		
		$tmc = $this->cat->getElements('//struct/cat');
		$xmlok->createElement('cats', $tmc, $xmlok_site);
		
		$lgd_node = $xmlok->createElement('langsdata', '', $xmlok_site);
		
		foreach($this->LG->GetAllIds() as $lg_id){
			$temp_cat = new CymaXml(CACHE_PATH.'cache-'.$lg_id.'.xml');
			$xmlok->createElement($lg_id, $temp_cat->getElement('//struct')->childNodes, $lgd_node);
		}
		
		if( (is_string($this->tw) && strlen($this->tw)>0) || (is_array($this->tw)) ){
			$xml = new DomDocument();
			$xml -> loadXML('<?xml version="1.0" encoding="UTF-8"?><site>'.implode('',(array)$this->tw).'</site>');
			$tnodes = $xml->documentElement->childNodes;
			foreach ($tnodes as $t){
				$nn = $xmlok->importNode($t,true);
				$xmlok->documentElement->appendChild($nn);
			}
		}
		
		
		     
		//parseCCss($this->site_root.'style.ccss');
		
		$funcs = array(
			'xslTxtLineCut',
			'xslNumberDate',
			'xslTxtMultiLine',
			'xslDisplayPrice',
			'getDateFormated',
			'rawDecode',
			'getRealPrice',
			'getRealUnitPrice',
			'xslSum',
			'xslIsEmpty',
			'xslWriteMail',
			'xslImg',
		);

		$xslt = new XSLTProcessor();
		$xslt -> registerPHPFunctions($funcs);
		$xslt -> importStylesheet( $this->xsl );
		$final_html = str_replace(array("</li>\n","\n<!--ib","\n<div class=\"griditem"),array("</li>","<!--ib","<div class=\"griditem"),$xslt -> transformToXml( $xmlok ));
		echo $final_html;

		if ( $this->ccf->getAttribute('nopagecache') != '1' ) {
			$hash = md5(implode('', array_merge(array('cube'),$_GET)));
			CymaFile::CreateFolder(CACHE_PATH.'cachemanager');
			file_put_contents(CACHE_PATH.'cachemanager'.DS.$hash, $final_html);
		}

		if(DEBUG) {
			$xsl = new CymaXml();
			$xsl->formatOutput = true;
			$xsl->loadXML($this->xsl->saveXML());
			echo '<div><h2>boxes</h2><textarea style="width:500px;height:100px;">'.implode("\r\n", $this->box_names_loaded).'</textarea></div>';
			echo '<div><h2>xml</h2><textarea style="width:800px;height:300px;">'.$xmlok->saveXML().'</textarea></div>';
			echo '<div><h2>xsl</h2><textarea style="width:800px;height:300px;">'.htmlentities($xsl->saveXML(), ENT_NOQUOTES, 'UTF-8').'</textarea></div>';
			echo '<div><h2>xsl cats</h2><textarea style="width:800px;height:300px;">'.$this->cat->saveXML().'</textarea></div>';
			echo '<div><h2>result</h2><textarea style="width:800px;height:300px;">'.htmlentities($xslt -> transformToXml( $xmlok ), ENT_NOQUOTES, 'UTF-8').'</textarea></div>';
			echo '<div><h2>result</h2><textarea style="width:800px;height:300px;">'.$xslt -> transformToXml( $xmlok ).'</textarea></div>';
		}
		
	}
	
	
	public function displayNewsletter($source=false){
		$source_d = true;
		$xmlok = new CymaXml();
		$xmlok->formatOutput = true;
		$xmlok_site = $xmlok->createElement('site');
		$head = $xmlok->createElement('head');
		$xmlok->createElement('title', $this->title, $head);
		$xmlok->createElement('icon', $this->icon, $head);
		$xmlok->createElement('root', $this->site_root, $head);
		$xmlok->createElement('imgpath', $this->site_root.'site/imgs/', $head);
		$xmlok->createElement('imguserpath', $this->site_root.$this->imguser_root.'/', $head);
		$xmlok->createElement('lang', $this->lang, $head);
		if($source) $xmlok->createElement('source', 'yes', $head);
		$xmlok_site->appendChild($head);
		$xmlok->appendChild($xmlok_site);
		
		$tnodes = $this->content->childNodes;
		foreach ($tnodes as $t){
			$nn = $xmlok->importNode($t,true);
			$xmlok->documentElement->appendChild($nn);
		}
		//$xmlok->createElement('lg', $this->data->documentElement->childNodes, $xmlok->documentElement);
		
		
		$funcs = array(
			'xslTxtLineCut',
			'xslNumberDate',
			'rawDecode'
		);
		
		$xsl = new CymaXml(ROOT_PATH.'site'.DS.'templates'.DS.'newsletter-template-'.$this->nl_skin.'.xsl');
		$xslt = new XSLTProcessor();
		$xslt -> registerPHPFunctions($funcs);
		$xslt -> importStylesheet( $xsl );
		if($source){
			$out = $xslt -> transformToDoc( $xmlok );
			$out->formatOutput = true;
			return "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\r\n".$out->saveXML($out->documentElement);
		}
		else return $xslt -> transformToXml( $xmlok );

		if(DEBUG) {
			$xsl->formatOutput = true;
			$this->cat->formatOutput = true;
			echo '<div><h2>xml</h2><textarea style="width:500px;height:300px;">'.$xmlok->saveXML().'</textarea></div>';
			echo '<div><h2>xsl</h2><textarea style="width:500px;height:300px;">'.$xsl->saveXML().'</textarea></div>';
			echo '<div><h2>xsl</h2><textarea style="width:500px;height:300px;">'.$this->cat->saveXML().'</textarea></div>';
			echo '<div><h2>result</h2><textarea style="width:500px;height:300px;">'.$xslt -> transformToXml( $xmlok ).'</textarea></div>';
		}
		
	}	
}


class SiteUser
{
	private $main_file;
	private $lang_files = null;
	private $lang_file = null;
	private $lang_id;
	private $lang_weburl;
	
	public function __construct( $category_file, $lang_id ){
		$this->main_file = $category_file;
		$this->lang_id = $lang_id;
		$this->lang_weburl = S()->LG->GetLangWeburl($lang_id);
	}
	
	public function CompleteAll(){

	}
}

$local_hook_file_path = ROOT_PATH.'site'.DS.'assets'.DS.'site.php';
if ( is_file($local_hook_file_path) ) {
	require_once $local_hook_file_path;
}
else {
	class CubeRequest extends CubeRequestBase {}

	class CubeLangs extends CubeLangsBase {}

	class Site extends SiteBase {}
}


?>