<?php

class HPSelectView extends Slot {

	var $SectionID = 4;
	var $ModuleID = 4;
	var $pages = array();
	var $reqfield = '<img src="/i/must.gif">&nbsp;';
	var $contenttype = array(
		0 => 'Subcategory',
		1 => 'Page',
		//2 => 'Dynamic Item',
	);
	var $colors = array(
		'red' => '#B00000',
		'yellow' => '#FF8C00',
		'green' => '#008000',
		'black' => '#000000',
	);
	var $check = array();
	var $menu_id = 0;
	var $default_page_array = array();

	function __construct($pquery) {
		parent::__construct($pquery);
	}

	function init() {
		global $TOOLS_PATH;
		switch(@$this->LocalTarget[0]) {
			default: 
				$this->pagetypes = $this->Action->Server->getGuide('pagetype');
				$this->pagetypes[0] = 'No Type';
				$this->Scheme = 'default';
			break;
			case 'Json':
				$this->pagetypes = $this->Action->Server->getGuide('pagetype');
				$this->pagetypes[0] = 'No Type';
				$this->Scheme = 'json';
			break;
		}
		if(!empty($this->Request)) {
			if($this->server_type=='dev' || $this->getRequestField('step')=='filter') {
				switch($this->getRequestField('step')) {
					case 'homepage': {
						if(!empty($this->Request['form']['homepage'])){
							$pages = $this->Action->Server->getGuide('page');
							if(isset($pages[$this->Request['form']['homepage']])){
								GLOBAL $Server, $REGISTRY;
								$REGISTRY['HomeTarget'] = $this->Request['form']['homepage'];
								$Server->saveRegistry();
								$this->Action->processEvent($this->SectionID, 'log', array('type' => 3, 'entity' => 6, 'event' => 12, 'value' => 'Change Home Target to Page "'.$pages[$this->Request['form']['homepage']].'" ['.$REGISTRY['HomeTarget'].']'), $this);
							}
						}
						header('Location: '.$this->Home.'/Registar/HPSelect'.$this->SID);
						break;
					}
					case 'filter':
						if(isset($this->Request['form']['pagetype'])) {
							$cookie = implode(',',array_keys($this->Request['form']['pagetype']));
							setcookie("pagetypes",$cookie,time()+86400*365,"/");
						}
						else setcookie("pagetypes",'',time()+86400*365,"/");
						header('Location: '.$this->Home.'/Registar/HPSelect'.$this->SID);
					break;
				}
			}
			else header('Location: '.$this->Home.'/Registar/HPSelect'.$this->SID);
		}
		$this->setSchemeTemplate($this->Scheme);
	}
	
	function fillElements() {
		switch($this->Scheme) {
			case 'json': $this->fillJson(); break;
			default: $this->fillSelect(); break;
		}
	}

	function getParents($id,$arr){
		$count=count($this->allPage);
		for($i=0;$i<$count;$i++){
			//if($this->allPage[$i]['parent']!=0){
				if($this->allPage[$i]['parent']==$id) $arr[]=$this->allPage[$i];
				if($this->allPage[$i]['id']==$id) $arr = $this->getParents($this->allPage[$i]['parent'],$arr);
			//}
		}
		return $arr;
	}

	function fillJson(){
		global $REGISTRY;//$REGISTRY['HomeTarget']
		switch($this->LocalTarget[1]){
			case 'getSavePosition':
				if(isset($this->LocalTarget[2])&&is_numeric($this->LocalTarget[2])){
//					$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, path,('now' - date_changed) as interval, sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6)  order by parent , sort_order ASC ");
					$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, path,TIMESTAMPDIFF(day,date_changed,NOW()) as 'interval', sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6)  order by parent , sort_order ASC ");
					$pagetypes = array();
					if(isset($_COOKIE['pagetypes'])) {
						$pagetypes = explode(',',$_COOKIE['pagetypes']);
					}
					else $pagetypes = array_keys($this->pagetypes);
					foreach($this->allPage as $key => $value) {
						if($value['is_describe']==1 && !in_array($value['controlid'],$pagetypes)) unset($this->allPage[$key]);
					}
					$this->allPage = array_values($this->allPage);
					$aParents = $this->getParents($this->LocalTarget[2],Array());
					$countParents=count($aParents);
				}
			//break;
			case 'getChild':
				if(isset($this->LocalTarget[2])&&(is_numeric($this->LocalTarget[2])||$this->LocalTarget[2]=='All')){
					if(!isset($this->allPage))
//						$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, path,('now' - date_changed) as interval, sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6)  order by parent , sort_order ASC ");
						$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, path, TIMESTAMPDIFF(day,date_changed,NOW()) as 'interval', sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6)  order by parent , sort_order ASC ");
					$pagetypes = array();
					if(isset($_COOKIE['pagetypes'])) {
						$pagetypes = explode(',',$_COOKIE['pagetypes']);
					}
					else $pagetypes = array_keys($this->pagetypes);
					foreach($this->allPage as $key => $value) {
						if($value['is_describe']==1 && !in_array($value['controlid'],$pagetypes)) unset($this->allPage[$key]);
					}
					$this->allPage = array_values($this->allPage);
					$users = $this->Db->SelectGuide('member g', array('g.id','g.username as name'),array(1 => 1));
					$select_servers=$this->Db->SelectAny("select path from preset");
					$countServers=count($select_servers);
					$hasCurServer='false';
					foreach($select_servers as $value)
						if($value['path']=='http://'.$_SERVER['HTTP_HOST'].'/') $hasCurServer='true';
					$servers_num = $this->Db->SelectAny('select m.id,p.preset,pr.name ,p.date_published,p.type from publish p,module m, preset pr where p.ownerid=m.id and p.date_published>=m.date_changed and p.preset=pr.id and  (p.type=3)');
					$pagesOnServers= Array();
					foreach($servers_num as $value){
						$times=explode('.',$value['date_published']);
						$pagesOnServers[$value['id']][$value['name']]=$times[0];
					}
					$cnt=0;
					$arrId = Array();
					$arrPath = Array();
					$count=count($this->allPage);
					$countParents=(isset($aParents))? count($aParents): 0;
					for($i=0;$i<$count;$i++){
						for($k=0;$k<$countParents;$k++)
							if($aParents[$k]['id']==$this->allPage[$i]['id'])
								$this->LocalTarget[2]=$aParents[$k]['parent'];
						if(($this->allPage[$i]['parent']==$this->LocalTarget[2]||$this->LocalTarget[2]=='All')&&$this->allPage[$i]['parent']!=0){
							$cnt++;
							$arrId[]=$this->allPage[$i]['id'];
						}
					}
					$arrIsChild=$this->is_child_arr($arrId);
					$this->TempFillEls['items'] = Array();
					$cntNow=0;
					for($i=0;$i<$count;$i++){
						for($k=0;$k<$countParents;$k++)
							if($aParents[$k]['id']==$this->allPage[$i]['id'])
								$this->LocalTarget[2]=$aParents[$k]['parent'];
						$arrPath[$this->allPage[$i]['id']]=(!isset($arrPath[$this->allPage[$i]['parent']]))? $this->getPath($this->allPage[$i]['id'],$this->allPage): $arrPath[$this->allPage[$i]['parent']].'/'.$this->allPage[$i]['path'];
						if(($this->allPage[$i]['parent']==$this->LocalTarget[2]||$this->LocalTarget[2]=='All')&&$this->allPage[$i]['parent']!=0){
							$cntNow++;
							$status=number_format(((count($this->TempFillEls['items'])+1)/$cnt)*100,0);
							$lock=!empty($this->allPage[$i]['access_flag']) &&$this->allPage[$i]['access_flag']!=$this->Action->Security->currentuser->id? true: false;
							$button='*';
							$lockLine= Array();
							if(!$lock){
								$button=(isset($arrIsChild[$this->allPage[$i]['id']])||$this->allPage[$i]['id']=='1'||$this->allPage[$i]['type']==3||$this->allPage[$i]['type']==6)? 'R': '';
								$button.=($this->allPage[$i]['is_describe']==0)? 'V':'';
								$button.=(!empty($this->allPage[$i]['access_flag']) &&$this->allPage[$i]['access_flag']==$this->Action->Security->currentuser->id)? '':'U';
								
							}else{
								$lockLine['time']=$this->getTime($this->allPage[$i]['date_locked']);
								$lockLine['username']=$users[$this->allPage[$i]['access_flag']];
							}
							$publishServers=(isset($pagesOnServers[$this->allPage[$i]['id']]))? count($pagesOnServers[$this->allPage[$i]['id']]):'0';
							$level=(count(explode('/',$arrPath[$this->allPage[$i]['id']]))-2)*20;
							$this->TempFillEls['items'][$this->allPage[$i]['id']]=array(
								'funcName' => 'pageControler.addItem',
								'id' => $this->allPage[$i]['id'],
								'name' => $this->allPage[$i]['name'],
								'parent' => $this->allPage[$i]['parent'],
								'bullet' => (isset($arrIsChild[$this->allPage[$i]['id']]))? '_plus'.($REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? '': '_home_page'): ($REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? ($this->allPage[$i]['is_describe']==0? '_green' : '') : '_home_page'),
								'radioChecked' => $REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? '': 'checked',
								'radioDisabled' => ($this->allPage[$i]['is_describe']==0)?  'disabled':(!empty($lockLine)? 'disabled' : ''),
								'path' => $arrPath[$this->allPage[$i]['id']],
								'level' => $level,
								'status' => $status,
								'all' => $cnt,
								'now' => $cntNow,
								'button' => $button,
								'hasServerInfo' => ($publishServers!=0)? 'true':'false',
								'lockLine' => (!empty($lockLine))? $lockLine['username'].'|'.$lockLine['time'] :'*',
								'is_child'=> isset($arrIsChild[$this->allPage[$i]['id']])? 'true':'false',
								'checkDisabled' => !empty($lockLine)? 'disabled' : '',
								'servers' => '[ '.$publishServers.' / '.$countServers.' ]',
								'colorServers' => !isset($pagesOnServers[$this->allPage[$i]['id']])? 'red':($hasCurServer? ($countServers-count($pagesOnServers[$this->allPage[$i]['id']])<=1? 'black':'blue'): ($countServers==count($pagesOnServers[$this->allPage[$i]['id']])? 'black':'blue')),
								'color' => $this->colors[$this->allPage[$i]['interval'] > 30? 'black' : ($this->allPage[$i]['interval'] > 14 && $this->allPage[$i]['interval'] <= 30? 'green' : ($this->allPage[$i]['interval'] > 7 && $this->allPage[$i]['interval'] <= 14? 'yellow' : 'red'))],
							);
							$this->TempFillEls['itemsfunc'][0]='';
						}
					}
				}
			break;
			case 'getServerInfo':
				if(isset($this->LocalTarget[2])&&is_numeric($this->LocalTarget[2])){
					$servers_num = $this->Db->SelectAny('select m.id,p.preset,pr.name ,p.date_published,p.type from publish p,module m, preset pr where p.ownerid=m.id and p.date_published>=m.date_changed and p.preset=pr.id and  (p.type=3) and m.id='.$this->LocalTarget[2]);
					foreach($servers_num as $value)
						$this->TempFillEls['serverInfo'][]=array(
							'funcName' => 'pageControler.addServerInfo',
							'idPage' => $this->LocalTarget[2],
							'serverName' => $value['name'],
							'time' => $this->getTime($value['date_published']),
						);
					$this->TempFillEls['serverinfofunc'][0]['idPage']=$this->LocalTarget[2];
				}
			break;
			default:break;
		}
	}
	

	function fillSelect() {
		$this->TempFillEls['pubBut'] = $this->server_type=='pro'? 'hidden' : 'visible';
		$pagetypes = array();
		if(isset($_COOKIE['pagetypes'])) {
			$pagetypes = explode(',',$_COOKIE['pagetypes']);
		}
		else $pagetypes = array_keys($this->pagetypes);
		$this->TempFillEls['filter_count'] = count($pagetypes);
		$this->TempFillEls['filter_all'] = count($this->pagetypes);
		$this->TempFillEls['disabled'] = count($pagetypes) > 0? '' : 'disabled';
		foreach($this->pagetypes as $key => $value) {
			$this->TempFillEls['pagetypes'][] = array(
				'check' => inputCheckbox('form[pagetype]['.$key.']',(in_array($key,$pagetypes)? TRUE : FALSE),'onclick="setPT(this)"'),
				'name' => $value,
			);
		}
		$this->setArrayPage();
	}

	function setArrayPage(){
		global $REGISTRY;
//		$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, path,('now' - date_changed) as interval, sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6) order by parent , sort_order ASC ");
		$this->allPage = $this->Db->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, path, TIMESTAMPDIFF(day,date_changed,NOW()) as 'interval', sort_order, controlid from module where name!='' and (type=1 or type=3 or type=6) order by parent , sort_order ASC ");
		$pagetypes = array();
		if(isset($_COOKIE['pagetypes'])) {
			$pagetypes = explode(',',$_COOKIE['pagetypes']);
		}
		else $pagetypes = array_keys($this->pagetypes);
		foreach($this->allPage as $key => $value) {
			if($value['is_describe']==1 && !in_array($value['controlid'],$pagetypes)) unset($this->allPage[$key]);
		}
		$this->allPage = array_values($this->allPage);
		$select_servers=$this->Db->SelectAny("select path from preset");
		$countServers=count($select_servers);
		$hasCurServer='false';
		foreach($select_servers as $value)
			if($value['path']=='http://'.$_SERVER['HTTP_HOST'].'/')
				$hasCurServer='true';
		$servers_num = $this->Db->SelectAny('select m.id,p.preset,pr.name ,p.date_published,p.type from publish p,module m, preset pr where p.ownerid=m.id and p.date_published>=m.date_changed and p.preset=pr.id and  (p.type=3)');
		$pagesOnServers= array();
		foreach($servers_num as $value){
			$times=explode('.',$value['date_published']);
			$pagesOnServers[$value['id']][$value['name']]=$times[0];
		}
		$users = $this->Db->SelectGuide('member g', array('g.id','g.username as name'),array(1 => 1));
		$count=count($this->allPage);
		$flagHP=false;
		for($i=0;$i < $count;$i++){
			if($REGISTRY['HomeTarget']==$this->allPage[$i]['id'])
				$flagHP=true;
			if($this->allPage[$i]['parent']==0){
				$is_child=$this->is_child($this->allPage[$i]['id']);
				$lock=!empty($this->allPage[$i]['access_flag']) &&$this->allPage[$i]['access_flag']!=$this->Action->Security->currentuser->id? true: false;
				$publishServers=(isset($pagesOnServers[$this->allPage[$i]['id']]))? count($pagesOnServers[$this->allPage[$i]['id']]):'0';
					//$this->TempFillEls['preload'][$this->allPage[$i]['id']]=array(
					//	'id' => $this->allPage[$i]['id'],
					//);
				
				$this->TempFillEls['idFirstLevel'][]=Array('id'=>$this->allPage[$i]['id']);
				$this->TempFillEls['pages'][$this->allPage[$i]['id']]=array(
					'funcName' => 'pageControler.addItem',
					'id' => $this->allPage[$i]['id'],
					'name' => $this->allPage[$i]['name'],
					'bullet' => ($is_child)? '_plus'.($REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? '': '_home_page'): ($REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? ($this->allPage[$i]['is_describe']==0? '_green' : '') : '_home_page'),
					'radioChecked' => $REGISTRY['HomeTarget']!=$this->allPage[$i]['id']? '': 'checked',
					'radioDisabled' => ($this->allPage[$i]['is_describe']==0)?  'disabled':($lock? 'disabled' : ''),
					'path' => '/'.$this->allPage[$i]['path'],
					'bR'=> ($is_child||$this->allPage[$i]['id']=='1'||$this->allPage[$i]['type']==3||$this->allPage[$i]['type']==6)? 'hidden': 'vissible',
					'bV' => ($this->allPage[$i]['is_describe']==0)? 'hidden':'vissible',
					'bU' => (!empty($this->allPage[$i]['access_flag']) &&$this->allPage[$i]['access_flag']==$this->Action->Security->currentuser->id)? 'vissible':'hidden',
					'addBut' => $this->server_type!='dev'? 'hidden' : 'visible',
					'is_child' => $is_child? 'true':'false',
					'cursor' => $is_child? 'pointer':'',
					'displayBut' =>  $lock? 'none': 'lock',
					'displayLockLine' => $lock? 'display': 'none',
					'checkDisabled' => $lock? 'disabled' : '',
					'time' => $lock? $this->getTime($this->allPage[$i]['date_locked']) : '',
					'username' => $lock?  $users[$this->allPage[$i]['access_flag']]: '',
					'countServers' => $countServers,
					'colorServers' => !isset($pagesOnServers[$this->allPage[$i]['id']])? 'red':($hasCurServer? ($countServers-count($pagesOnServers[$this->allPage[$i]['id']])<=1? 'black':'blue'): ($countServers==count($pagesOnServers[$this->allPage[$i]['id']])? 'black':'blue')),
					'publishServers' => $publishServers,
					'hasServerInfo' => ($publishServers!=0)? 'true':'false',
					'action' => ($is_child)? 'getChild': '',
					'color' => $this->colors[$this->allPage[$i]['interval'] > 30? 'black' : ($this->allPage[$i]['interval'] > 14 && $this->allPage[$i]['interval'] <= 30? 'green' : ($this->allPage[$i]['interval'] > 7 && $this->allPage[$i]['interval'] <= 14? 'yellow' : 'red'))],
				);
			}
		}
		if($flagHP)
			$this->TempFillEls['idHomePage'][0]=Array('idHP'=>$REGISTRY['HomeTarget']);
		//echo $REGISTRY['HomeTarget'];
		//exit;
	}

	function getPath($id,$arr,$path=Array()){
		foreach($arr as $value){
			if($value['id']==$id){
				$path[]=$value['path'];
				return $this->getPath($value['parent'],$arr,$path);
			}
		}
		return '/'.implode('/',array_reverse($path));
	}

	function getTime($str){
		$time=explode('.',$str);
		return $time[0];
	}

	function is_child($parent){
		$count = count($this->allPage);
		for($i=0;$i < $count;$i++)
			if($this->allPage[$i]['parent']==$parent) return true;
		return false;
	}

	function is_child_arr($arr){
		$count = count($this->allPage);
		$count_id=count($arr);
		$res = Array();
		for($i=0;$i < $count;$i++)
			for($k=0;$k<$count_id;$k++){
				if($this->allPage[$i]['parent']==$arr[$k]) $res[$arr[$k]]=true;
			}
		return $res;
	}
}
?>