<?php

class MenuHandler extends Handler{

	function __construct(){
		parent::__construct('MenuHandler');
	}

	function selectPages($request=array()) {

	}

	function getLock($request = array()){
		empty($request['menu']) and $request['menu'] = 0;
		empty($request['member']) and $request['member'] = 0;
		if(!empty($request['member']) && !empty($request['menu'])) {
			$query='select m.id, m.access_flag, m.date_locked, u.username from menu m, member u where m.id='.$request['menu'].' and m.access_flag=u.id';
			$selected = $this->DB->SelectAny($query);
		}
		return !empty($selected[0])? $selected[0] : array();
	}

	function makeLock($request = array()) {
		empty($request['menu']) and $request['menu'] = 0;
		empty($request['member']) and $request['member'] = 0;
		if(!empty($request['member']) && !empty($request['menu'])) {
			$this->DB->begin();
			$this->DB->update('menu',array('access_flag' => $request['member'],'date_locked' => 'now()'),array('id' => $request['menu']),0);
			$this->setLogEvent(3,10,3,'Lock Menu ['.$request['menu'].']',$request['menu']);
			$this->DB->commit();
		}
		return $request;
	}

	function unLock($request = array()) {
		empty($request['menu']) and $request['menu'] = 0;
		empty($request['member']) and $request['member'] = 0;
		if(!empty($request['member']) && !empty($request['menu'])) {
			$this->DB->begin();
			$this->DB->update('menu',array('access_flag' => '0'),array('id' => $request['menu']));
			$this->setLogEvent(3,10,4,'UnLock Menu ['.$request['menu'].']',$request['menu']);
			$this->DB->commit();
		}
		return $request;
	}

	function createMenu() {
		$menu = new Menu();
		$menu->menulineitems = new ObjectsList();
		$menu->menulineitems->type = new MenuLineItem();
		//$menu->menulineitems->type->menu = new Menu();
		return $menu;
	}

	function selectMenus($request = array()) {
//		$result = $this->DB->SelectAny('SELECT id, name, type, date_changed, (\'now\'::date - date_changed::date) AS unmodified, access_flag, date_locked FROM menu ORDER BY id');
		$result = $this->DB->SelectAny('SELECT id, name, type, date_changed, TIMESTAMPDIFF(day,date_changed,NOW()) AS unmodified, access_flag, date_locked FROM menu ORDER BY id');
		$presets = array();
		$selected = $this->DB->SelectAny('SELECT id, name FROM preset');
		$presets_count = count($selected);
		for ($i = 0; $i < $presets_count; $i++) $presets[$selected[$i]['id']] = $selected[$i]['name'];
		$packages = array();
		$hostpaths = array();
		$usernames = array();
		$count = count($result);
		for($i = 0; $i < $count; $i++){
			$date_changed = explode('.', $result[$i]['date_changed']);
			$result[$i]['date_changed'] = $date_changed[0];
			$date_locked = explode('.', $result[$i]['date_locked']);
			$result[$i]['date_locked'] = $date_locked[0];
			$result[$i]['username'] = $result[$i]['access_flag'] ? $this->getUserName(array('type' => 1, 'userid' => $result[$i]['access_flag'])) : '';
			$result[$i]['publish'] = array();
			$query = 'SELECT packagepublish.id, packagepublish.ownerid as package_id, packagepublish.host, packagepublish.userid, packagepublish.date_published FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.date_published > \''.$result[$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 2 AND packageitem.object = \''.$result[$i]['id'].'\') ORDER BY packagepublish.date_published DESC';
			$packagepublish = $this->DB->SelectAny($query);
			$presets_unique = array();
			$c = count($packagepublish);
			$index = 0;
			for ($j = 0; $j < $c; $j++){
				if(isset($presets_unique[$packagepublish[$j]['host']])) continue;
				$presets_unique[$packagepublish[$j]['host']] = true;
				$result[$i]['publish'][$index] = $packagepublish[$j];
				$date_published = explode ('.', $packagepublish[$j]['date_published']);
				$result[$i]['publish'][$index]['date_published'] = $date_published[0];
				if(!isset($packages[$packagepublish[$j]['package_id']])){
					$sel = $this->DB->SelectAny('SELECT name FROM package WHERE id = '.$packagepublish[$j]['package_id'].' LIMIT 1');
					$packages[$packagepublish[$j]['package_id']] = empty($sel) ? '[deleted]' : $sel[0]['name'];
				}
				$result[$i]['publish'][$index]['package_name'] = $packages[$packagepublish[$j]['package_id']];
				if(!isset($hostpaths[$packagepublish[$j]['host']])){
					$sel = $this->DB->SelectAny('SELECT name FROM preset WHERE id = '.$packagepublish[$j]['host'].' LIMIT 1');
					$hostpaths[$packagepublish[$j]['host']] = empty($sel) ? '[unknown]' : $sel[0]['name'];
				}
				$result[$i]['publish'][$index]['hostpath'] = $hostpaths[$packagepublish[$j]['host']];
				if(!isset($usernames[$packagepublish[$j]['userid']])){
					$sel = $this->DB->SelectAny('SELECT username FROM member WHERE id = '.$packagepublish[$j]['userid'].' LIMIT 1');
					$usernames[$packagepublish[$j]['userid']] = empty($sel) ? '[unknown]' : $sel[0]['username'];
				}
				$result[$i]['publish'][$index]['username'] = $usernames[$packagepublish[$j]['userid']];
				$index++;
			}
			$result[$i]['published_count'] = count($result[$i]['publish']).'/'.$presets_count;
		}
		return $result;
	}

	// Content Handler has copy
	function openMenu($request = array('id' => 2)) {
		$selected = $this->DB->SelectArray(array('menulineitem'),'*',array('ownerid' => $request['id']),'parent, sort_order ASC');
		if(!empty($selected)) $menuTree = $this->makeMenuTree($selected,0);
		return $menuTree;
	}

	function getMenu($request = array('id' => 2)) {
		global $TOOLS_PATH;
		if(!empty($request['undo'])) {
			$Undo_field= array('type' => 2,'id' => $request['id'],'undo' => 0,'version' => $request['undo']);
			include($TOOLS_PATH.'\undo.php');
			$menu = $print_arr;
		}
		else {
			$menu = $this->createMenu();
			empty($request['id']) and $request['id'] = 0;
			$menu->id = $request['id'];
			//$selected = $this->DB->SelectArray(array('menulineitem'),'*',array('ownerid' => $menu->id),'parent, sort_order ASC');
			$this->DB->initObject($menu);
		}
		$menulineitems = array();
		uasort($menu->menulineitems->data,'by_parent');
		foreach((!empty($menu->menulineitems->data)? $menu->menulineitems->data : array()) as $value)
			$menulineitems[] = $value;
		$menu->menulineitems->data = $menulineitems;
		$menulineitems = array();
		uasort($menu->menulineitems->data,'by_index');
		foreach((!empty($menu->menulineitems->data)? $menu->menulineitems->data : array()) as $value)
			$menulineitems[] = $value;
		$menu->menulineitems->data = $menulineitems;
		return $menu;
	}

	function selectMenuPub($request = array()){
		$result = array();
//		$selected = $this->DB->SelectAny('select id, (\'now\'::date - date_changed::date) as interval from menu order by id');
//		$selected = $this->DB->SelectAny('select id, TIMESTAMPDIFF(day,date_changed,NOW()) as \'interval\' from menu order by id');
		$servers_num = $this->DB->SelectAny('select count(*) from preset');
		$servers = $this->DB->SelectAny('select ftp_host from preset');
		$serverspub = $this->DB->SelectAny('select p.ownerid, ps.name, ps.ftp_host, p.date_published from publish p, preset ps, menu m where p.preset=ps.id and p.type = 2 and p.ownerid = m.id and p.date_published > m.date_changed order by p.ownerid');
		//printArray($servers);
		if(!empty($servers_num)) $result['servers_num'] = $servers_num[0]['count'];
			else $result['servers_num'] = 0;
		if(!empty($selected)) foreach($selected as $value){
			$value['serverspub']['num'] = 0;
			$self = false;
			foreach($serverspub as $k => $v){
				if($v['ownerid'] == $value['id']){
					$value['serverspub']['num']++;
					$value['serverspub'][] = array('name' => $v['name'], 'date' => preg_replace('/\..*/','',$v['date_published']));
					if ($_SERVER['HTTP_HOST'] == $v['ftp_host']) $self = true;
				}
			}
			if ($value['serverspub']['num'] == 0){
				$value['serverspub']['color'] = 'red';
			}elseif ((($value['serverspub']['num'] == $servers_num[0]['count']-1) && !$self && in_array($_SERVER['HTTP_HOST'],$servers)) || ($value['serverspub']['num'] == $servers_num[0]['count'])){
				$value['serverspub']['color'] = 'black';
			}else
				$value['serverspub']['color'] = 'blue';
			$result[$value['id']] = $value;
		}
		return $result;
	}

	function saveMenu($request = array()) {
		global $TOOLS_PATH;
		$this->undo = '';
		$menu = new Menu();
		$this->parseRequest($request,$menu);
		$this->DB->begin();
		if(!empty($menu->id)) {
			$Undo_field= array('type' => 2,'id' => $menu->id,'undo' => 1);
			include($TOOLS_PATH.'\undo.php');
			$this->undo = $undo_handler->arr_obj;
		}
		if(!empty($menu->id)) $this->DB->delete('menulineitem',array('ownerid' => $menu->id));
		if(empty($menu->id)) {
			$menu->uid = $this->getUID('menu');
			$menu->date_created = 'now';
		}
		$menu->access_flag = 0;
		if(!empty($request['duplicate_id'])) $this->DB->update('menu',array('access_flag' => 0),array('id' => $request['duplicate_id']));
		$menu->date_changed = 'now';
		if(empty($menu->id)) $this->setLogEvent(3,10,11,'Add Menu "'.$menu->name.'"');
		else $this->setLogEvent(3,10,12,'Edit Menu "'.$menu->name.'" ['.$menu->id.']',$menu->id);
		$this->DB->processObject($menu,'save',array(),array(),TRUE);
		if(empty($menu->uid)) {
			$selected = $this->DB->SelectAny('SELECT uid FROM menu WHERE id = '.$menu->id.' LIMIT 1');
			if(!empty($selected) && $selected[0]['uid']) $this->DB->delete('deleted', array('uid' => $selected[0]['uid'], 'type' => 2));
		}
		else $this->DB->delete('deleted', array('uid' => $menu->uid, 'type' => 2));
		$menulineitems = array();
		uasort($request['menulineitems'],'by_parent');
		foreach((!empty($request['menulineitems'])? $request['menulineitems'] : array()) as $value)
			$menulineitems[] = $value;
		$request['menulineitems'] = $menulineitems;
		$menuTree = $this->makeMenuTree($menulineitems,0);
		$this->saveMenuLineItems($menuTree,$menu->id,0);
		// comments
		$menucomment= new MenuComment();
		$menucomment->version = 1;
		$menucomment->value = 'Menu has been created';
		$selected = $this->DB->SelectAny("select version from menucomment where ownerid = ".$menu->id." order by date desc LIMIT 1 OFFSET 0");
		if(!empty($selected[0]['version'])) {
			$menucomment->version=++$selected[0]['version'];
			$menucomment->value = (!empty($request['_undo_'])? 'Menu has been undone up to '.$request['_undo_']." version<br>\r\n" : '').htmlspecialchars($request['comment']);
		}
		$menucomment->ownerid = $menu->id;
		$menucomment->member = $request['id_user'];
		$menucomment->date = 'now';
		$this->DB->processObject($menucomment,'save',array(),array(),TRUE);
		if(!empty($request['_undo_'])) $this->setLogEvent(3,10,10,'Menu "'.$menu->name.'" ['.$menu->id.'] has been undone up to '.$request['_undo_'].' version',$menu->id);
		$this->DB->commit();
		if($this->DB->good && !empty($this->undo)) $undo_handler->GetArrayInFile($this->undo,'Undo_object', $ROOT_PATH."/undo/".$pub_type[0]['name'].'/'.$Undo_field['id'].'/'.($menucomment->version>1? $menucomment->version-1 : 1).".inc");
		return $menu;
	}

	function saveMenuLineItems($array = array(),$ownerid = 0,$parent = 0,$subitems = array()) {
		foreach($array as $key => $value) {
			$mli = new MenuLineItem();
			$mli->id = '';
			$mli->ownerid = $ownerid;
			$mli->parent = $parent;
			$mli->anchor = $value['anchor'];
			$mli->target = $value['target'];
			$mli->is_external = $value['is_external'];
			$mli->sort_order = $value['sort_order'];
			$mli->path = $value['path'];
			$mli->name = $value['label'];
			$mli->label = $value['label'];
			$mli->object = $value['object'];
			$this->DB->processObject($mli,'save',array(),array(),TRUE);
			if(!empty($value['subcat'])) $this->saveMenuLineItems($value['subcat'],$ownerid,$mli->id);
		}
	}

	function deleteMenu($request = array()) {
		$menu = new Menu();
		$this->parseRequest($request,$menu);
		$this->DB->begin();
		$this->DB->initObject($menu);
		$this->DB->delete('menulineitem',array('ownerid' => $menu->id));
		$this->DB->delete('modulemenulineitem',array('menu' => $menu->id));
		$presets = $this->DB->SelectGuide(array('preset g'),'*',array());
		foreach($presets as $prekey => $prevalue)
			$this->DB->insert('deleted',array('uid' => $menu->uid,'preset' => $prekey,'type' => 2));
		$this->DB->processObject($menu,'delete',array(),array(),TRUE);
		$this->DB->delete('menucomment',array('ownerid' => $menu->id));
		$this->setLogEvent(3,10,13,'Delete Menu "'.$menu->name.'" ['.$menu->id.']',$menu->id);
		//publish
		$this->DB->delete('publish',array('ownerid' => $menu->id,'type' => 2));
		//inpublish
		$this->DB->delete('inpublish',array('ownerid' => $menu->id,'type' => 2));
		$this->DB->commit();
		return $menu;
	}

	// Content Handler has copy
	function makeMenuTree($array,$parent = 0,$tree = array()) {
		foreach($array as $value) {
			if($value['parent'] == $parent) {
				$tree[$value['id']] = array(
					'name' => $value['name'],
					'label' => $value['label'],
					'path' => $value['path'],
					'sort_order' => $value['sort_order'],
					'object' => $value['object'],
					'parent' => $value['parent'],
					'target' => $value['target'],
					'ownerid' => empty($value['ownerid'])? '' : $value['ownerid'],
					'is_external' => $value['is_external'],
					'anchor' => $value['anchor'],
					'subcat' => $this->makeMenuTree($array,$value['id'])
				);
			}
		}
		return $tree;
	}

	function selectMenuComments($request = array()){
		if(empty($request['fields'])) $request['fields']='mm.type,mmc.*,m.username as member';
		if(empty($request['sortColumn'])) { $request['sortColumn']='mmc.version'; $request['sortType']='desc';}
		//$request['conditions']['canceled']=array('='=>0);
		$request['conditions']['m.id']=array('='=>'mmc.member');
		$request['conditions']['mm.id']=array('='=>'mmc.ownerid');
		$request['conditions']['mmc.ownerid']=array('='=>$request[1]);
		foreach($request['conditions'] as $k=>$v) $rels[]='and';
		if(empty($request['curPageNumber'])) $request['curPageNumber']=1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty']=10;
		$selected=$this->DB->SelectArray(Array('member m','menucomment mmc','menu mm'),'count(*) as qty',$request['conditions'],0,0,0,array(),'CND_COMPLEX',$rels);
		$request['recordsTotal']=$selected[0]['qty'];
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		$request['curPage']=$this->DB->SelectArray(Array('member m','menucomment mmc','menu mm'),$request['fields'],$request['conditions'],$this->getOrderBy($request),$this->getLimit($request),0,array(),'CND_COMPLEX',$rels);
		return $request;
	}

	function getHostPath($request = array()){
		$selected = $this->DB->SelectAny('SELECT '.($request['type'] == 1 ? 'name' : 'host').' AS hostpath FROM '.($request['type'] == 1 ? 'preset' : 'publisher').' WHERE id = '.$request['host'].' LIMIT 1');
		$hostpath = empty($selected) ? '[undefined]' : $selected[0]['hostpath'];
		return $hostpath;
	}

	function getUserName($request = array()){
		$selected = $this->DB->SelectAny('SELECT username FROM '.($request['type'] == 1 ? 'member' : 'publisher_user').' WHERE id = '.$request['userid'].' LIMIT 1');
		$username = empty($selected) ? '[undefined]' : $selected[0]['username'];
		return $username;
	}


	function selectFirstLevelPages($pagesTree = array()) {
		global $REGISTRY;
		$colors = array(
			'red' => '#DC143C',
			'yellow' => '#FF8C00',
			'green' => '#006400',
			'black' => '#000000',
			'blue' => '#4169E1',
		);
//		$pagesTree['allPage'] = $this->DB->SelectAny('SELECT id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path, (\'now\' - date_changed) AS interval, sort_order, controlid FROM module WHERE name != \'\' AND (type=1 or type=3 or type=6 or type=8) ORDER BY parent, sort_order ASC');
		$pagesTree['allPage'] = $this->DB->SelectAny('SELECT id, name, type, access_flag, parent, is_describe, date_locked, date_changed, path, TIMESTAMPDIFF(day,date_changed,NOW()) AS \'interval\', sort_order, controlid FROM module WHERE name != \'\' AND (type=1 or type=3 or type=6 or type=8) ORDER BY parent, sort_order ASC');
		$pagetypes = array();
		if(isset($_COOKIE['pagetypes'])) $pagetypes = explode(',',$_COOKIE['pagetypes']);
		else $pagetypes = array_keys($pagetypes);
		//$count = count($pagesTree['allPage']);
		//for ($i = 0; $i < $count; $i++)
		//	if($this->allPage[$i]['is_describe'] && !in_array($this->allPage[$i]['controlid'], $pagetypes))
		//		unset($this->allPage[$i]);
		$pagesTree['allPage'] = array_values($pagesTree['allPage']);
		$select_servers = $this->DB->SelectAny('SELECT path FROM preset');
		$hasCurServer = 'false';
		$countServers = count($select_servers);
		$pubBut = $pagesTree['server_type'] == 'pro' ? 'hidden' : 'visible';
		$isDev = $pagesTree['server_type'] == 'dev' ? true : false;
		for ($i = 0; $i < $countServers; $i++)
			if($select_servers[$i]['path'] == 'http://'.$_SERVER['HTTP_HOST'].'/')
				$hasCurServer = 'true';
		$users = $this->DB->SelectGuide('member g', array('g.id', 'g.username as name'), array(1 => 1));
		$pubBut = $pagesTree['server_type'] == 'pro' ? 'hidden' : 'visible';
		$isDev = $pubBut = $pagesTree['server_type'] == 'dev' ? true : false;
		$count = count($pagesTree['allPage']);
		$flagHP = false;
		for($i = 0; $i < $count; $i++) {
			$isHP = false;
			if($REGISTRY['HomeTarget'] == $pagesTree['allPage'][$i]['id']){
				$flagHP = true;
				$isHP = true;
			}
			if(!empty($pagesTree['allPage'][$i]['parent'])) continue;
			$selected = $this->DB->SelectAny('SELECT packagepublish.id FROM packagepublish WHERE ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 3 AND packageitem.object = \''.$pagesTree['allPage'][$i]['id'].'\') LIMIT 1');
			if(empty($selected)) {
				$hasServerInfo = false;
				$publishServers = 0;
			}
			else {
				$hasServerInfo = true;
				$publishServers = $this->DB->SelectAny('SELECT count(preset.id) AS count FROM preset WHERE preset.id IN (SELECT DISTINCT packagepublish.host FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.host = preset.id AND packagepublish.date_published > \''.$pagesTree['allPage'][$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 3 AND packageitem.object = \''.$pagesTree['allPage'][$i]['id'].'\'))');
				$publishServers = empty($publishServers) ? 0 : $publishServers[0]['count'];
			}
			$is_child = $this->is_child($pagesTree['allPage'][$i]['id'],$pagesTree);
			$lock = empty($pagesTree['allPage'][$i]['access_flag']) ||$pagesTree['allPage'][$i]['access_flag'] == $pagesTree['currentuser_id'] ? false : true;
			//$pagesTree['allPage']['idFirstLevel'][] = Array('id' => $pagesTree['allPage'][$i]['id']);
			if(preg_match("/^(subdomains)/i", $pagesTree['allPage'][$i]['path']) && $pagesTree['allPage'][$i]['type']==8) $pagesTree['allPage'][$i]['sub'] = 1;
			else $pagesTree['allPage'][$i]['sub'] = 0;
			$pagesTree['pages'][$pagesTree['allPage'][$i]['id']] = array(
				'funcName' => 'pageControler.addItem',
				'id' => $pagesTree['allPage'][$i]['id'],
				'name' => $pagesTree['allPage'][$i]['name'],
				'sort' => $pagesTree['allPage'][$i]['sort_order'],
				'bullet' => $is_child? '_plus'.($isHP? '_home_page' : ($pagesTree['allPage'][$i]['sub']? '_black' : '')) : ($isHP? '_home_page' : ($pagesTree['allPage'][$i]['is_describe']==0? ($pagesTree['allPage'][$i]['sub']? '_black' : '_green') : ($pagesTree['allPage'][$i]['sub']? '_1a' : ''))),
				'radioChecked' => $isHP ? 'checked': '',
				'radioDisabled' => $pagesTree['allPage'][$i]['is_describe'] == 0?  'disabled' : ($lock ? 'disabled' : ''),
				'path' => '/'.$pagesTree['allPage'][$i]['path'],
				'bR'=> ($is_child || $pagesTree['allPage'][$i]['id'] == '1' || $pagesTree['allPage'][$i]['type'] == 3 || $pagesTree['allPage'][$i]['type'] == 6 || $isHP) ? 'hidden': 'visible',
				'bV' => $pagesTree['allPage'][$i]['is_describe'] == 0 ? 'hidden' : 'visible',
				'bU' => (!empty($pagesTree['allPage'][$i]['access_flag']) && $pagesTree['allPage'][$i]['access_flag'] == $pagesTree['currentuser_id']) ? 'visible':'hidden',
				'bD' => $pagesTree['allPage'][$i]['type']==8? 'hidden' : 'visible',
				'pubBut' => $pubBut,
				'countServers' => $countServers,
				'colorServers' => $publishServers == 0 ? $colors['red'] : ($publishServers < $countServers ? $colors['blue'] : $colors['green']),
				'publishServers' => $publishServers,
				'hasServerInfo' => $hasServerInfo ? 'true' : 'false',
				'action' => $is_child ? 'getChild': '',
				'color' => $colors[$pagesTree['allPage'][$i]['interval'] > 30? 'black' : ($pagesTree['allPage'][$i]['interval'] > 14 && $pagesTree['allPage'][$i]['interval'] <= 30? 'green' : ($pagesTree['allPage'][$i]['interval'] > 7 && $pagesTree['allPage'][$i]['interval'] <= 14? 'yellow' : 'red'))],
			);
			if($is_child){
				$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['is_child'] = 'true';
				$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['cursor'] = 'pointer';
			}
			else $pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['is_child'] = 'false';
			if($isDev){
				if($lock){
					$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['displayBut'] = 'none';
					$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['displayLockLine'] = 'block';
					$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['checkDisabled'] = 'disabled';
				}
				else{
					$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['displayBut'] = 'block';
					$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['displayLockLine'] = 'none';
				}
			}
			else{
				$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['displayBut'] = 'none';
				$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['displayLockLine'] = 'none';
			}
			if($lock){
				$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['time'] = $this->getTime($pagesTree['allPage'][$i]['date_locked']);
				$pagesTree['pages'][$pagesTree['allPage'][$i]['id']]['username'] = $users[$pagesTree['allPage'][$i]['access_flag']];
			}
		}
		if($flagHP) $pagesTree['idHomePage'][0] = Array('idHP' => $REGISTRY['HomeTarget']);
		return $pagesTree;
	}

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


	function getChild($pagesTreeJSON = array()){
		global $REGISTRY;
		$colors = array(
			'red' => '#DC143C',
			'yellow' => '#FF8C00',
			'green' => '#006400',
			'black' => '#000000',
			'blue' => '#4169E1',
		);
//		$pagesTreeJSON['getChild'] = $this->DB->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, date_changed, 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");
		$pagesTreeJSON['getChild'] = $this->DB->SelectAny("select id, name, type, access_flag, parent, is_describe, date_locked, date_changed, 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");
		$pagetypes = array();
		if(isset($_COOKIE['pagetypes'])) {
			$pagetypes = explode(',',$_COOKIE['pagetypes']);
		}
		else $pagetypes = array_keys($pagesTreeJSON['getChild']);
		foreach($pagesTreeJSON['getChild'] as $key => $value) {
			if($value['is_describe']==1 && !in_array($value['controlid'],$pagetypes)) unset($pagesTreeJSON['getChild'][$key]);
		}
		$pagesTreeJSON['getChild'] = array_values($pagesTreeJSON['getChild']);
		$aParents = $this->getParents($pagesTreeJSON['LocalTarget2'],Array(),$pagesTreeJSON);
		$countParents=count($aParents);
		$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';
		$cnt=0;
		$arrId = Array();
		$arrPath = Array();
		$count=count($pagesTreeJSON['getChild']);
		$countParents=(isset($aParents))? count($aParents): 0;
		for($i=0;$i<$count;$i++){
			for($k=0;$k<$countParents;$k++)
				if($aParents[$k]['id']==$pagesTreeJSON['getChild'][$i]['id'])
					$pagesTreeJSON['LocalTarget2']=$aParents[$k]['parent'];
					if(($pagesTreeJSON['getChild'][$i]['parent']==$pagesTreeJSON['LocalTarget2']||$pagesTreeJSON['LocalTarget2']=='All')&&$pagesTreeJSON['getChild'][$i]['parent']!=0){
						$cnt++;
						$arrId[]=$pagesTreeJSON['getChild'][$i]['id'];
					}
		}
		$arrIsChild = $this->is_child_arr($arrId,$pagesTreeJSON);
		$pagesTreeJSON['items'] = Array();
		$cntNow=0;
		for($i=0;$i<$count;$i++){
			for($k=0;$k<$countParents;$k++)
				if($aParents[$k]['id']==$pagesTreeJSON['getChild'][$i]['id'])
					$pagesTreeJSON['LocalTarget2']=$aParents[$k]['parent'];
			$arrPath[$pagesTreeJSON['getChild'][$i]['id']]=(!isset($arrPath[$pagesTreeJSON['getChild'][$i]['parent']]))? $this->getPath($pagesTreeJSON['getChild'][$i]['id'],$pagesTreeJSON['getChild']): $arrPath[$pagesTreeJSON['getChild'][$i]['parent']].'/'.$pagesTreeJSON['getChild'][$i]['path'];
			if(($pagesTreeJSON['getChild'][$i]['parent']==$pagesTreeJSON['LocalTarget2']||$pagesTreeJSON['LocalTarget2']=='All')&&$pagesTreeJSON['getChild'][$i]['parent']!=0){
				$cntNow++;
				$status=number_format(((count($pagesTreeJSON['items'])+1)/$cnt)*100,0);
				$lock=!empty($pagesTreeJSON['getChild'][$i]['access_flag']) &&$pagesTreeJSON['getChild'][$i]['access_flag']!=$pagesTreeJSON['currentuser_id']? true: false;
				$button='*';
				$lockLine= Array();
				if(!$lock){
					$button=(isset($arrIsChild[$pagesTreeJSON['getChild'][$i]['id']])||$pagesTreeJSON['getChild'][$i]['id']=='1'||$pagesTreeJSON['getChild'][$i]['type']==3||$pagesTreeJSON['getChild'][$i]['type']==6)? 'R': '';
					$button.=($pagesTreeJSON['getChild'][$i]['is_describe']==0)? 'V':'';
					$button.=(!empty($pagesTreeJSON['getChild'][$i]['access_flag']) &&$pagesTreeJSON['getChild'][$i]['access_flag']==$pagesTreeJSON['currentuser_id'])? '':'U';
     			}else{
					$lockLine['time']=$this->getTime($pagesTreeJSON['getChild'][$i]['date_locked']);
					$lockLine['username']=$users[$pagesTreeJSON['getChild'][$i]['access_flag']];
				}
				$selected = $this->DB->SelectAny('SELECT packagepublish.id FROM packagepublish WHERE ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 3 AND packageitem.object = \''.$pagesTreeJSON['getChild'][$i]['id'].'\') LIMIT 1');
				if(empty($selected)) {
					$hasServerInfo = false;
					$publishServers = 0;
				}
				else {
					$hasServerInfo = true;
					$publishServers = $this->DB->SelectAny('SELECT count(preset.id) AS count FROM preset WHERE preset.id IN (SELECT DISTINCT packagepublish.host FROM packagepublish WHERE packagepublish.type = 1 AND packagepublish.successful = 1 AND packagepublish.host = preset.id AND packagepublish.date_published > \''.$pagesTreeJSON['getChild'][$i]['date_changed'].'\' AND packagepublish.ownerid IN (SELECT DISTINCT packageitem.ownerid FROM packageitem WHERE packageitem.type = 3 AND packageitem.object = \''.$pagesTreeJSON['getChild'][$i]['id'].'\'))');
					$publishServers = empty($publishServers) ? 0 : $publishServers[0]['count'];
				}
				$level=(count(explode('/',$arrPath[$pagesTreeJSON['getChild'][$i]['id']]))-2)*20;
				if($pagesTreeJSON['server_type']!='dev') {
					$button='*';
					$lockLine = array();
				}
				$pagesTreeJSON['items'][$pagesTreeJSON['getChild'][$i]['id']]=array(
					//'pubBut' => $this->server_type=='pro'? 'hidden' : 'visible',
					//'funcName' => 'pageControler.addItem',
					'id' => $pagesTreeJSON['getChild'][$i]['id'],
					'sort' => $pagesTreeJSON['getChild'][$i]['sort_order'],
					'name' => $pagesTreeJSON['getChild'][$i]['name'],
					'parent' => $pagesTreeJSON['getChild'][$i]['parent'],
					'bullet' => (isset($arrIsChild[$pagesTreeJSON['getChild'][$i]['id']]))? '_plus'.($REGISTRY['HomeTarget']!=$pagesTreeJSON['getChild'][$i]['id']? '': '_home_page'): ($REGISTRY['HomeTarget']!=$pagesTreeJSON['getChild'][$i]['id']? ($pagesTreeJSON['getChild'][$i]['is_describe']==0? '_green' : '') : '_home_page'),
					'radioChecked' => $REGISTRY['HomeTarget']!=$pagesTreeJSON['getChild'][$i]['id']? '': 'checked',
					'radioDisabled' => ($pagesTreeJSON['getChild'][$i]['is_describe']==0)?  'disabled':(!empty($lockLine)? 'disabled' : ''),
					'path' => $arrPath[$pagesTreeJSON['getChild'][$i]['id']],
					'level' => $level,
					'status' => $status,
					'all' => $cnt,
					'now' => $cntNow,
					'button' => $button,
					'hasServerInfo' => $hasServerInfo ? 'true' : 'false',
					'lockLine' => (!empty($lockLine))? $lockLine['username'].'|'.$lockLine['time'] :'*',
					'is_child'=> isset($arrIsChild[$pagesTreeJSON['getChild'][$i]['id']])? 'true':'false',
					'checkDisabled' => !empty($lockLine)? 'disabled' : '',
					'servers' => '['.$publishServers.'/'.$countServers.']',
					'colorServers' => $publishServers == 0 ? $colors['red'] : ($publishServers < $countServers ? $colors['blue'] : $colors['green']),
					'color' => $colors[$pagesTreeJSON['getChild'][$i]['interval'] > 30? 'black' : ($pagesTreeJSON['getChild'][$i]['interval'] > 14 && $pagesTreeJSON['getChild'][$i]['interval'] <= 30? 'green' : ($pagesTreeJSON['getChild'][$i]['interval'] > 7 && $pagesTreeJSON['getChild'][$i]['interval'] <= 14? 'yellow' : 'red'))]
					);

			}
		}
 		return $pagesTreeJSON;
	}

	function is_child_arr($arr,$pagesTreeJSON){
		$count = count($pagesTreeJSON['getChild']);
		$count_id=count($arr);
		$res = Array();
		for($i=0;$i < $count;$i++)
			for($k=0;$k<$count_id;$k++){
				if($pagesTreeJSON['getChild'][$i]['parent']==$arr[$k]) $res[$arr[$k]]=true;
			}
		return $res;
	}

	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 getParents($id,$arr,$pagesTreeJSON){
		$count=count($pagesTreeJSON['getChild']);
		for($i=0;$i<$count;$i++){
			if($pagesTreeJSON['getChild'][$i]['parent']==$id) $arr[]=$pagesTreeJSON['getChild'][$i];
			if($pagesTreeJSON['getChild'][$i]['id']==$id) $arr = $this->getParents($pagesTreeJSON['getChild'][$i]['parent'],$arr,$pagesTreeJSON);
		}
		return $arr;
	}

	function getServerInfo($pagesTreeJSON = array()){
		$selected = $this->DB->SelectAny('SELECT DISTINCT packageitem.ownerid AS package_id, package.name AS package_name, packagepublish.id, packagepublish.type, packagepublish.host, packagepublish.userid, packagepublish.date_published, packagepublish.successful FROM packagepublish, packageitem LEFT JOIN package ON (package.id = packageitem.ownerid AND package.actioned = 1) WHERE packageitem.type = 3 AND packageitem.object = \''.$pagesTreeJSON['LocalTarget2'].'\' AND packagepublish.ownerid = packageitem.ownerid ORDER BY packagepublish.date_published DESC');
		$pagesTreeJSON['count'] = count($selected);
		$count = $pagesTreeJSON['count'];
		for ($i = 0; $i < $count; $i++){
			$username = $this->DB->SelectAny('SELECT username FROM '.($selected[$i]['type'] == 1 ? 'member' : 'publisher_user').' WHERE id = '.$selected[$i]['userid'].' LIMIT 1');
			$hostpath = $this->DB->SelectAny('SELECT '.($selected[$i]['type'] == 1 ? 'name' : 'host').' AS hostpath FROM '.($selected[$i]['type'] == 1 ? 'preset' : 'publisher').' WHERE id = '.$selected[$i]['host'].' LIMIT 1');
			$pagesTreeJSON['serverInfo'][$i]=array(
				'funcName' => 'pageControler.addServerInfo',
				'idPage' => $pagesTreeJSON['LocalTarget2'],
				'packageId' => $selected[$i]['package_id'],
				'packageName' => $selected[$i]['package_name'],
				'publishType' => $selected[$i]['type'] == 1 ? 'up' : 'down',
				'serverName' => empty($hostpath) ? '<unknown>' : $hostpath[0]['hostpath'],
				'userName' => empty($username) ? '<unknown>' : $username[0]['username'],
				'time' => $this->getTime($selected[$i]['date_published']),
				'successful' => $selected[$i]['successful'] == 1 ? 'tick_green' : 'cross_red',
			);
		}
		//$pagesTreeJSON['serverinfofunc'][0]['idPage'] = $pagesTreeJSON['LocalTarget2'];
		return $pagesTreeJSON;
	}

    function getMenuXHR ($request = array('id' => 2)){
		/*global $TOOLS_PATH;
		if(!empty($request['undo'])) {
			$Undo_field= array('type' => 2,'id' => $request['id'],'undo' => 0,'version' => $request['undo']);
			include($TOOLS_PATH.'/undo.php');
			$menu = $print_arr;
		}
		else {
			$menu = $this->createMenu();
			empty($request['id']) and $request['id'] = 0;
			$menu->id = $request['id'];
			//$selected = $this->DB->SelectArray(array('menulineitem'),'*',array('ownerid' => $menu->id),'parent, sort_order ASC');
			$this->DB->initObject($menu);
		}
		$menulineitems = array();
		uasort($menu->menulineitems->data,'by_parent');
		foreach((!empty($menu->menulineitems->data)? $menu->menulineitems->data : array()) as $value)
			$menulineitems[] = $value;
		$menu->menulineitems->data = $menulineitems;
		$menulineitems = array();
		uasort($menu->menulineitems->data,'by_index');
		foreach((!empty($menu->menulineitems->data)? $menu->menulineitems->data : array()) as $value)
			$menulineitems[] = $value;
		$menu->menulineitems->data = $menulineitems;


		return $menu; */
		return array();
    }


}
?>