<?php
include_once($TOOLS_PATH.'\Slot.functions.inc');
include_once($CORE_PATH.'\XTemplate.class.inc');

class Slot extends XTemplate {

	var $ModuleID = 1;
	var $SectionID = 1;
	var $Task;
	var $ID;
	var $CacheLife = 0;
	var $CacheGlobal = 0;
	var $Action;
	var $PreparedTemplates = array();
	var $UA = array();
	var $Home;
	var $sHome;

	var $TemplateContents = '';
	var $TemplateElements = array();
	var $TemplateFilledElements = array();
	var $TemplateFile = '';
	var $TemplatePath = array();
	var $Templates = array();

	var $Name = '';
	var $VName = '';
	var $Type = '';
	var $TemplateName = '';
	var $Properties = array();
	var $LoadFunction = 'templateFile';
	var $Reset = TRUE;
	var $Scheme = '';

	var $Ready = FALSE;
	var $Result = FALSE;
	var $Locate = TRUE;

	var $Target = array();
	var $LocalTarget = array();
	var $SID;

	var $language;
	var $LM;
	var $globalLangContent = array();
	var $localLangContent = array();

	var $debugID = 0;

	var $Request = array();

	var $DB;

	var $errors = array();

	var $month = array();
	var $day = array();
	var $year = array();

	var $server_type;

	var $useCache = FALSE;
//	var $useCache = TRUE;
	
	var $Cache = TRUE;
	var $Cached = FALSE;
	var $CacheInherit = TRUE;
	var $CacheKey = "";
	var $Pass = 0;
	var $Passing = FALSE;

	function __construct($pquery) {
		global $REGISTRY,$RequestBroker,$HOME_PATH,$DatabaseBroker,$CORE_PATH,$Server;
		eval(implode('',file($CORE_PATH.'\signature.inc')));
		$this->server_type = $signature['type'];
		$this->Home = 'https://'.$REGISTRY['Globals']['static']['serverPath'].$REGISTRY['Core']['WebRoot'];
//		$this->sHome = 'https://'.$REGISTRY['Globals']['static']['serverPath'].$REGISTRY['Core']['WebRoot'];
	$this->sHome = 'https://'.$REGISTRY['Globals']['static']['serverPath'].$REGISTRY['Core']['WebRoot'];
		$this->Action = $Server->getAction($this->SectionID);
		$this->Action->ModuleID = &$this->ModuleID;
		$this->LM = $_SESSION['LanguageManager'];
		$this->UA = $Server->getUserAgent();
		$this->language = &$this->LM->language;
		$this->SID = $this->getSID();
		$this->Name = $pquery['Name'];
		$this->Request = $RequestBroker->getRequestFor($this->Name);
		isset($pquery['Locate']) and $this->Locate = $pquery['Locate'];
		$this->globalLangContent = &$this->LM->globalContent;
		$this->VName = isset($pquery['VName'])? $pquery['VName'] : $this->Name;
		debug('Slot ('.$this->Name.')',"VName = '".$this->VName."'<br>");
		$this->Type = $pquery['Type'];
		if($this->TemplateName != $pquery['Template']) {
			$this->TemplateName = $pquery['Template'];
			$reset = TRUE;
		}
		!empty($pquery['Templates']) and $this->Templates = $pquery['Templates'];
		$this->Properties = $pquery['Properties'];
		$this->ID = !empty($this->Properties['id'])? $this->Properties['id'] : 0;
		$this->_ModuleID = !empty($this->Properties['moduleid'])? $this->Properties['moduleid'] : 0;
		$this->setSchemeTemplate(!empty($this->Properties['scheme'])? $this->Properties['scheme'] : 'default');
		$this->setTemplatePath();
		$this->Target = $pquery['Target'];
		$this->LocalTarget = empty($pquery['LocalTarget'])? array() : $pquery['LocalTarget'];
		$this->CacheTarget = $this->Target;
		$this->CacheInherit = !empty ($pquery["CacheInherit"]);
		$this->Cache = isset($pquery["Cache"])? $pquery["Cache"] : 1;
		$this->Ready = FALSE;
		$this->Result = FALSE;
		$this->TemplateFilledElements = array();
		$this->Reset = TRUE;
		$this->TempFillEls = &$this->TemplateFilledElements;
		$this->ImagePath = $REGISTRY['Core']['ImagePath'];
		$this->ImageWPath = $REGISTRY['Core']['ImageWPath'];
		$this->Db = $DatabaseBroker;
	}

	function authorizeMemberByCookie() {
		if($this->Name == 'Layout' and empty($this->Action->Security->currentuser->id)) {
			if(!empty($_COOKIE['bbuserid']) && !empty($_COOKIE['bbpassword'])) {
				$_user = $this->Action->Security->authorizeMemberByCookie(array('id' => $_COOKIE['bbuserid'],'passw' => $_COOKIE['bbpassword']));
				$user = $this->Action->VisualContent($_user,'0','cookie');
				if(!empty($user['_error'])) $this->Action->clearCookie();
				else $this->Action->set_Cookie($user);
			}
		}
	}

	function correctWords($array = array(),$HTML = false) {
		is_array($array) or $array = array();
		foreach($array as $key => $value)
			$array[$key] = is_array($value)? $this->correctWords($value) : $this->_replaceHTML($value,$HTML);
		return $array;
	}

	function _replaceHTML($value = '',$HTML = false) {
		if($HTML) {
			$value = eregi_replace("<p>","{p}",$value);
			$value = eregi_replace("<br>","{br}",$value);
		}
		$value = trim(strip_tags($value));
		if($HTML) {
			$value = eregi_replace("{p}","<p>",$value);
			$value = eregi_replace("{br}","<br>",$value);
		}
		return $value;
	}

	function getWordWrap($text,$cut,$break,$flag = false,$len = 0) {
		if(!$flag) {
			$text = eregi_replace("-| - "," - ",$text);
			$text = eregi_replace(",|, ",", ",$text);
		}
		$words = split(" ",$text);
		foreach($words as $key => $value) {
			if(strlen($value)>$len) $len = strlen($value);
			$words[$key] = $len > $cut? wordwrap($words[$key],$cut,"$break",1) : $words[$key];
		}
		$text = implode(" ",$words);
		$text = eregi_replace("\n","<br>",$text);
		return $text;
	}

	function getPageControl($self,$sort = '') {
		$per_page = isset($this->PreparedTemplates['pageRecordsQty'])? $this->PreparedTemplates['pageRecordsQty'] : 10;
		$num_rows = isset($this->PreparedTemplates['recordsTotal'])? $this->PreparedTemplates['recordsTotal'] : 0;
		$cur_page = isset($this->PreparedTemplates['curPageNumber'])? $this->PreparedTemplates['curPageNumber'] -1 : 0;
		if($this->PreparedTemplates['curPageNumber'] > $this->PreparedTemplates['pagesTotal'] && count($this->PreparedTemplates['curPage'])) header("Location: ".$self.$this->SID);
		$this->Action->Navigator($self,$per_page,$num_rows,$cur_page,$sort,$this);
		$this->TempFillEls['navbar'] = implode('<br>',$this->Action->navbar);
		$this->TempFillEls['pagecontrol'][] = array(
			'prev' => $this->Action->prev,
			'first' => $this->Action->first,
			'pager' => '<nobr>'.implode(' | ',$this->Action->pager).'</nobr>',
			'last' => $this->Action->last,
			'next' => $this->Action->next,
		);
		if(count($this->PreparedTemplates['curPage'])== 0) {
			if(!empty($this->PreparedTemplates['pagesTotal'])) header("Location: ".$self.$this->SID);
			else {
				$this->TempFillEls['navbar'] = $this->globalLangContent['message']['empty_page'];
				$this->TempFillEls['pagecontrol'] = array();
			}
		}
		else {
			if(empty($this->Action->pager)) $this->TempFillEls['pagecontrol'] = array();
			$this->TempFillEls['pagecontrol2'] = $this->TempFillEls['pagecontrol'];
		}
	}

	function getSID() {
		$SID = SID? SID : '';
		$SID = $this->UA['browser']=='ns'? (!empty($SID)? $SID.'&'.time() : time()) : $SID;
		$SID = !empty($_GET)? (!empty($SID)? '&'.$SID : '') : (!empty($SID)? '?'.$SID : '');
		return $SID;
	}

	function getRealValue($name) {
		return !empty($this->Request['form'])? $this->getRequestFormField($name) : $this->PreparedTemplates[$name];
	}

	function getRequestField($name) {
		return isset($this->Request[$name])? $this->Request[$name] : '';
	}

	function getRequestFormField($name,$id = false) {
		if($id) return isset($this->Request['form'][$name]['id'])? stripslashes($this->Request['form'][$name]['id']) : '';
		else return isset($this->Request['form'][$name])? stripslashes($this->Request['form'][$name]) : '';
	}

	function printError($error) {
		return isset($error)? '<br><span class="req_red">'.$error.' !</span>' : '';
	}

	function setSelected($name,$id = false) {
		return !empty($this->Request)? $this->getRequestFormField($name,$id) : (!empty($this->PreparedTemplates[$name])? ($id? $this->PreparedTemplates[$name]['id'] : $this->PreparedTemplates[$name]) : '');
	}

	function getSelect($name,$ext = false,$event = false) {
		return inputSelect('form['.$name.']'.($ext? $ext : ''),$this->{$name},
			$this->setSelected($name,$ext),$event? $event : '');
	}

	function getRadioSet($name,$array = array()) {
		foreach(radioButtons($this->{$name},'form['.$name.']',$this->setSelected($name)) as $value) $array[]['value'] = $value;
		return $array;
	}

	function correctSize($size) {
		return $this->UA['browser']=='ns'? ((int)$size <= 15? $size - 5 : $size - 10) : $size;
	}

	function getCheckbox($name) {
		return inputCheckbox('form['.$name.']',$this->setSelected($name));
	}

	function setBoxes($name,$guide = '') {
		foreach(checkBoxes($this->{($guide? $guide : $name)},'form['.$name.']',$this->setSelected($name)) as $key => $value)
			$column[$key % 2][]['value'] = $value.'<br>';
		$this->TempFillEls['first_'.$name] = $column[0];
		$this->TempFillEls['second_'.$name] = $column[1];
	}

	function setSchemeTemplate($scheme = 'default') {
		global $REGISTRY;
		$this->Scheme = $scheme;
		if(!empty($this->Templates[$this->Scheme])) {
			@$tFile = $this->Templates[$this->Scheme];
			$this->setTemplateFile('/'.$tFile);
		}
		else {
			$this->setTemplateFile($this->TemplateName);
		}
	}

	function init() {}

	function resetTemplate(&$content) {
		$this->Ready = FALSE;
		$this->TemplateContents = $content;
		!empty($content) and $this->setTemplateID();
		$this->retrieveTemplate();
		$this->setTemplate($this->TemplateContents);
//printArray($this->TemplateContents); exit;		
		$this->TemplateElements = &$this->getElements();
	}

	function render(&$reparse) {
		$this->PHP_SELF   = str_ireplace ("^\/".$this->language,"",getenv('REQUEST_URI')).$this->SID;
		$this->init();
		if($this->Reset or !empty($reparse)) {
			!empty($reparse) and $this->Passing = TRUE;
			!empty($reparse) and $this->Cache = 0;
			!empty($reparse) and debug("Slot(".$this->Name.").render","reparsing<br>");
			$this->resetTemplate($reparse);
		//print $this->Reset; printArray($this->TemplateElements); exit;			
			$this->Reset = FALSE;
		}
		$this->fillElements();
		$this->fillEnter();
		//if(empty($this->Ready)) echo "EMPTY!"; else echo "NOT EMPTY!";
		return empty($this->Ready)?
			$this->setResult($this->parseTemplate($this->TempFillEls)) : $this->Result;
	}

	function fillElements() {}

	function fillAuth() {
		$this->TempFillEls = array(
			'formaction' => $this->PHP_SELF,
			'hidden' => inputHidden('o',$this->Name),
			'username' => inputText('form[username]',$this->getRequestFormField('username'),$this->correctSize('46')),
			'passw' => inputPassword('form[password]',$this->getRequestFormField('password'),$this->correctSize('46')),
		);
		!empty($this->PreparedTemplates['_error']) and $this->errors['model'] = $this->globalLangContent['error_model'][$this->PreparedTemplates['_error']];
		if(count($this->errors) > 0) $this->errors['header'] = $this->globalLangContent['error_view']['header_error'];
		foreach($this->errors as $k => $v) $this->TempFillEls[$k.'_error'] = $k=='header'? '<strong>'.$v.'</strong><p>' : '<span class="req_red">'.$v.' !</span>';
	}

	function fillEnter() {
		global $REGISTRY;
		$this->TempFillEls['bgcolor'] = $this->Name == 'Layout' && count($REGISTRY['Request']['Target'])==1? '#E3E4E4' : '#FFFFFF';
	}

	function message($message,$info) {
		global $REGISTRY;
		$this->setResult(sprintf($REGISTRY['Messages']['Slot'][$message],$this->Name,$info));
	}

	function setTemplatePath($path = array()) { //var_dump($path);
		$this->TemplatePath = array_merge($path,templatePath(array($this->Name)));
	}

	function setTemplateFile($name) {
		debug("setTemplateFile","$name<br>");
		if ($this->TemplateFile != $name) {
			$this->Reset = TRUE;
			$this->TemplateFile = $name;
		}
		$this->setTemplateID($this->TemplateFile);
	}

	function retrieveTemplate() {
		if(!empty($this->TemplateContents) or !$this->{$this->LoadFunction}()) return;
		if($this->Type == 'npblock') $this->setResult($this->TemplateContents);
	}

	function setResult($result) {
		$this->Result = $result;
		$this->Ready = TRUE;
		return $result;
	}

	function templateFile() {
		global $REGISTRY;
		if(!empty($this->TemplateContents)) return TRUE;
		debug ("Slot (".$this->Name.")","Loading Template: ".$this->TemplateFile."<br>");
		if(!empty($this->TemplateFile)) {
			//print '<li>Layout - '.$this->VName.', Name - '.$this->TemplateFile.'<br>';
			if(empty($this->VName) && is_numeric($this->TemplateFile)) {
				$selected = $this->Db->SelectArray('layout',array('value'),array('id' => $this->TemplateFile));
				$this->TemplateContents = $selected[0]['value'];
				//print $this->TemplateContents;
				return TRUE;
			}
			else {
				debug ("Slot (".$this->Name.")","readCache Template File: ".$this->TemplateFile."<br>");
				$this->TemplateContents = readCacheFile($this->TemplateFile,$this->TemplatePath);
				if($this->TemplateContents) return TRUE;
				$this->message('TemplateFileNotExist',$this->TemplateFile);
				return FALSE;
			}
		}
		else debug("<br>");
		$this->message('TemplateNotSet',$this->TemplateName);
		return FALSE;
	}

	function _debugDummyContent() {
		if(is_array($this->TemplateElements)) {
			foreach($this->TemplateElements as $key => $value)
				if(is_array($value)) $this->_debugDummyContentRecursive($value,$this->TempFillEls[$key]);
				else $this->TempFillEls[$key] = $key.'_Content';
		}
	}

	function _debugDummyContentRecursive($from,&$to) {
		foreach($from as $key => $value) {
			for($i = 0; $i < 5; $i++) {
				if(is_array($value)) $this->_debugDummyContentRecursive($value,$to[$key]);
				elseif($value == "slot") $to[$key] = array('id' => $this->debugID++);
				else $to[$key] = $key."_Content$i-".rand(0,100);
				$filled[$i][$key] = $to[$key];
			}
		}
		$to = $filled;
	}
}
?>