<?php

class ContentHandler extends Handler{

	var $module;
	var $modules = array();
	var $max = 0;

	function __construct(){
		//$this->Handler('ContentHandler');
		parent::__construct('ContentHandler');
	}

	function openCity($request = array()) {
		$city = array();
		$city = $this->DB->SelectAny('select * from city where name_in_url=\''.$request['name'].'\'');
		if(!empty($city)) {
			$state = $this->DB->SelectArray('state','*',array('id' => $city[0]['state']));
			$city[0]['state'] = $state[0];
		}
		return $city;
	}

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

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

	function makeUnLockObjects($request = array()) {
		$this->DB->begin();
		$types = array(
			'6' => array('table' => 'module','name' => 'pages'),
			'8' => array('table' => 'layout','name' => 'layouts'),
			'9' => array('table' => 'template','name' => 'templates'),
			'10' => array('table' => 'menu','name' => 'menus'),
			'5' => array('table' => 'preset','name' => 'presets'),
			'13' => array('table' => 'presetgroup','name' => 'preset groups'),
			'14' => array('table' => 'package','name' => 'packages'),
			'17' => array('table' => 'enginepacket','name' => 'engine packets'),
			'18' => array('table' => 'subdomain','name' => 'subdomains'),
			'19' => array('table' => 'importedfeed','name' => 'imported feeds'),
			'20' => array('table' => 'city','name' => 'cities'),
			'21' => array('table' => 'feed','name' => 'feeds'),
			'22' => array('table' => 'product','name' => 'products'),
		);
		if($this->Security->currentuser->role->id==3) {
			$this->DB->update($types[$request['type']]['table'],array('access_flag' => 0),array(1 => 1));
			$this->setLogEvent(3,$request['type'],4,'UnLock all '.$types[$request['type']]['name']);
		} else {
			$this->DB->update($types[$request['type']]['table'],array('access_flag' => 0),array('access_flag' => $this->Security->currentuser->id));
			$this->setLogEvent(3,$request['type'],4,'UnLock all own '.$types[$request['type']]['name']);
		}
		$this->DB->commit();
		return $request;
	}

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

	function selectPagesSiteMap($request = array(),$pagesTree = array()) {
		$selected = $this->DB->SelectAny('select m.id, m.type, m.parent as ownerid, m.name, m.path, m.sort_order from module m    
										  where m.type = 1  order by m.parent, m.sort_order ASC');
		foreach($selected  as $key => $value) {
			$categ = $this->DB->SelectAny("select id from category where sys_name like '".$value['path']."'");
			if (isset($categ[0]['id'])) unset ($selected[$key]);
		}
		return $selected;
	}
	
	function selectPages($request = array(),$pagesTree = array()) {
		//$servers_num = $this->DB->SelectAny('select count(*) from preset');
		//$servers = $this->DB->SelectAny('select ftp_host from preset');
		//$selected = $this->DB->SelectAny('select m.id, m.type, m.parent, m.name, m.path, m.sort_order, m.is_describe, m.date_changed,(\'now\'::date - m.date_changed::date) as interval, m.access_flag, m.date_locked, m.param_name, m.param_value, u.username, p.ownerid, to_char(p.date_published,\'YYYY-MM-DD HH24:MI:SS\') as date_published, p.preset, ps.name as ps_name, ps.ftp_host from module m LEFT JOIN member u ON u.id=m.access_flag LEFT JOIN publish p ON p.type = 3 and p.ownerid = m.id and p.date_published > m.date_changed LEFT JOIN preset ps ON p.preset=ps.id where m.type in (1,3,6,8,9) order by m.parent, m.sort_order ASC');
		$selected = $this->DB->SelectAny('select m.id, m.type, m.parent, m.name, m.path, m.sort_order, m.is_describe, m.date_changed, TIMESTAMPDIFF(day,m.date_changed,NOW()) as \'interval\', m.access_flag, m.date_locked, m.param_name, m.param_value, u.username, p.ownerid,  CONCAT(p.date_published,FORMAT(\'YYYY-MM-DD HH24:MI:SS\',2)) as date_published, p.preset, ps.name as ps_name, ps.ftp_host from module m LEFT JOIN member u ON u.id=m.access_flag LEFT JOIN publish p ON p.type = 3 and p.ownerid = m.id and p.date_published > m.date_changed LEFT JOIN preset ps ON p.preset=ps.id where m.type in (1,3,6,8,9) order by m.parent, m.sort_order ASC');
		if(!empty($selected)) {
			$count = count($selected);
			for($i = 0;$i < $count; $i++) {
				$value = $selected[$i];
				$pagesTree[$value['parent']][$value['id']]['id'] = $value['id'];
				$pagesTree[$value['parent']][$value['id']]['type'] = $value['type'];
				$pagesTree[$value['parent']][$value['id']]['parent'] = $value['parent'];
				$pagesTree[$value['parent']][$value['id']]['name'] = $value['name'];
				$pagesTree[$value['parent']][$value['id']]['path'] = $value['path'];
				$pagesTree[$value['parent']][$value['id']]['sort_order'] = $value['sort_order'];
				$pagesTree[$value['parent']][$value['id']]['is_describe'] = $value['is_describe'];
			}
		}
		return $pagesTree;
	}
	
	
	function getFullChart($request = array('parent' => 1),$chart = array()) {
		global $Server;
		$producthandler = $Server->getHandler(23);
		return $producthandler->getFullChart($request = array('parent' => 1),$chart = array());
	}
	
	function makePagesTree($array = array(),$parent = 0,$root = 0,$tree = array()) {
		foreach($array as $value) {
			if($value['parent'] == $parent) {
				$tree[$value['id']] = array(
					'id' => $value['id'],
					'url' => $this->getParentUrl($value['parent'],$array,array($value['id'] => $value['path'])),
				);
				$tree = mergeArrays($tree,$this->makePagesTree($array,$value['id'],1));
			}
		}
		return $tree;
	}

	function getParentUrl($id,$array,$sys_name = array(),$url = array()) {
		foreach($array as $key => $value) {
			if($value['id'] == $id) {
				if($value['parent']!=0) $url = $this->getParentUrl($value['parent'],$array);
				$url[$value['id']] = trim($value['path']);
			}
		}
		if(!empty($sys_name)) $url = mergeArrays($url,$sys_name);
		return $url;
	}

	function openGuideLI($request = array()) {
		$li = array();
		$li = $this->DB->SelectArray($request['guide'],'*',array('ownerid' => $request['ownerid']));
		return $li;
	}

	function saveGuideLI($request = array()) {
		$li = array();
		if(!empty($request['class'])) {
			$li = new $request['class']();
			$return = $this->DB->SelectSingle(array($request['class']),'id',array('ownerid' => $request['ownerid'],'lang' => $request['lang']));
			if(!empty($return)) {
				$li->id = $return;
				$this->DB->initObject($li);
			}
			else $li->id = '';
			$li->ownerid = $request['ownerid'];
			$li->lang = $request['langid'];
			$li->name = $request['name'];
			$this->DB->processObject($li);
		}
		$this->DB->commit();
		return $li;
	}

	function openSection($request = array()) {
		$module = $this->createModule();
		$this->parseRequest($request,$module);
		$this->DB->initObject($module);
		return $module;
	}

	function openSectionAdmin($request = array()) {
		global $TOOLS_PATH;
		if(!empty($request['undo'])) {
			$Undo_field= array('type' => 3,'id' => $request['id'],'undo' => 0,'version' => $request['undo']);
			include($TOOLS_PATH.'\undo.php');
			$selected = $this->DB->SelectAny('SELECT path FROM module WHERE id = '.$request['id'].' LIMIT 1');
			$print_arr['old_url'] = @$selected[0]['path'];
			return $print_arr;
		}
		$module = $this->createModule();
		$this->parseRequest($request,$module);
		$this->DB->initObject($module);
		if(empty($request['copy'])){
			uasort($module->contents->data,'by_index');
			$module->contents->data = array_values($module->contents->data);
		}
		else {
			$copy = $this->createModule();
			$this->parseRequest(array('id' => $request['copy']), $copy);
			$this->DB->initObject($copy);
			uasort($copy->contents->data, 'by_index');
			$copy->contents->data = array_values($copy->contents->data);
			$vars = get_object_vars($copy);
			foreach($vars as $key => $value)
				if(gettype($value) == 'object') $module->{$key} = $copy->{$key};
			$module->is_describe = $copy->is_describe;
			$module->default_page = $copy->default_page;
			$module->controlid = $copy->controlid;
		}
		foreach((!empty($module->customerreviewitems->data)? $module->customerreviewitems->data : array()) as $key => $value) {
			if($value->moduletype != 1) unset($module->customerreviewitems->data[$key]);
		}
		if(!empty($module->customerreviewitems->data)) $module->customerreviewitems->data = array_values($module->customerreviewitems->data);
		if(!empty($module->customerreviewitems->data)) {
			usort($module->customerreviewitems->data,'by_index');
			$module->customerreviewitems->data = array_values($module->customerreviewitems->data);
		}
		return $module;
	}

	function sortPages($request = array()) {
		$this->DB->begin();
		foreach($request as $key => $value) {
			$this->DB->update('module',array('sort_order' => (intval($value['sort_order1']) > 0? intval($value['sort_order1']) : 1)),array('id' => $key));
		}
		$this->setLogEvent(3,6,15,'Sort pages');
		$this->DB->commit();
		return array();
	}

	function deleteSection($request = array()) {
		global $Server, $REGISTRY;
		$module = $this->createModule();
		$module->id = $request['id'];
		$this->DB->initObject($module);
		$selected = $this->DB->SelectAny("select id from module where parent = ".$module->id." or bc_parent = ".$module->id);
		if(!empty($selected)) {
			$this->DB->good = FALSE;
			$module->_error = 'The page(subcategory) is not a subject removals as is the parent or breadcrumbs parent for other pages';
			return $module;
		}
		$this->DB->begin();
		$selected = $this->DB->SelectAny('select m.id,m.parent,m.path,m.sys_name from module m where m.type in (1,3,6) order by m.parent');
		if(!empty($selected)) $pagesTree = $this->makePagesTree($selected,0);
		$slot = $module->is_describe==2? '?'.$module->param_name.'='.$module->param_value : $module->path;
		foreach($pagesTree as $key => $value) {
			if($key == $module->parent->id) {
				if(count($value['url']) > 1) {
					$i = 0;
					$urls = array();
					foreach($value['url'] as $id => $url) {
						$urls[$i] = $url;
						$i++;
					}
					$value['url'] = $urls;
				}
				$slot = implode('/',$value['url']).($module->is_describe==2? '?'.$module->param_name.'='.$module->param_value : '/'.$module->path);
			}
		}
		//module
		//content
		//modulejszone
		$module->access_flag = 0;
		$presets = $this->DB->SelectGuide(array('preset g'),'*',array());
		foreach($presets as $prekey => $prevalue) $this->DB->insert('deleted',array('uid' => $module->uid,'preset' => $prekey,'type' => 3));
		$this->setLogEvent(3,6,13,'Delete page "'.$module->name.'" ('.$module->path.') ['.$module->id.']',$module->id);
		$this->DB->processObject($module,'delete',array(),array(),TRUE);
		$this->DB->delete('changedurl', array('ownerid' => $module->id));
		//modulemenulineitem
		$this->DB->delete('modulemenulineitem',array('ownerid' => $module->id));
		//meta
		$this->DB->delete('meta',array('ownerid' => $module->id,'moduletype' => 1));
		//menulineitem 1,2
		$this->DB->delete('menulineitem',array('object' => $module->id));
		//menulineitem other
//		$this->DB->query('delete from "menulineitem" where path=\'/'.$slot.'\'');
		$this->DB->query('delete from menulineitem where path=\'/'.$slot.'\'');
		//moduletemplate
		$this->DB->delete('moduletemplate',array('ownerid' => $module->id));
		//modulecomment
		$this->DB->delete('modulecomment',array('ownerid' => $module->id));
		//moduleimportedfeed
		$this->DB->delete('moduleimportedfeed',array('ownerid' => $module->id));
		$this->DB->commit();
		//$this->DB->rollback();
		if($this->DB->good) {
			foreach($REGISTRY['VirtualSlotTarget']['main'] as $path => $handler) {
				if(($handler == 'DescribeView:object?id='.$module->id || strstr($handler, '?dir='.$module->id)) && $module->id!=1) {
					unset($REGISTRY['VirtualSlotTarget'][''][$path]);
					unset($REGISTRY['VirtualSlotTarget']['main'][$path]);
				}
			}
			ksort($REGISTRY['VirtualSlotTarget']['']);
			ksort($REGISTRY['VirtualSlotTarget']['main']);
			$Server->saveRegistry();
		}
		return $module;
	}

	function saveSection($request) {
		global $Server, $REGISTRY, $TOOLS_PATH;
		$this->undo = '';
		$module = $this->createModule();
		$module->modulejszones = array();
		$this->parseRequest($request,$module);
		if(!$module->is_describe) {
			$module->contents->data = array();
			$module->layout->id = 0;
			$module->controlid = 0;
		}
		if($module->is_describe==2) $module->path = ' ';
		else $module->path = strtolower($module->path);
		$selected = $this->DB->SelectAny('SELECT id FROM module WHERE lower(path) = \''.$module->path.'\' AND parent = '.$module->parent->id.(empty($module->id)? '' : ' AND id != '.$module->id));
		if(!empty($selected)) {
			$this->DB->good = FALSE;
			$module->_error = 'Page with such path already exists';
			return $module;
		}
		$this->DB->begin();
		$changed_url = false;
		// Ã±Ã®Ã§Ã¤Ã Ã­Ã¨Ã¥ Ã¯Ã°Ã¥Ã¤Ã»Ã¤Ã³Ã¹Ã¥Ã© Ã¢Ã¥Ã°Ã±Ã¨Ã¨ / Ã¯Ã°Ã®Ã¢Ã¥Ã°ÃªÃ  Ã­Ã  Ã¨Ã§Ã¬Ã¥Ã­Ã¥Ã­Ã¨Ã¥ Ã³Ã°Ã«Ã 
		if(!empty($module->id)) {
			$selected = $this->DB->SelectAny('SELECT type, path FROM module WHERE id = '.$module->id.' LIMIT 1');
			if(!empty($selected)){
				if($selected[0]['path'] != '' && $selected[0]['path'] != $module->path && in_array($selected[0]['type'], array(1, 3, 6, 8))) $changed_url = true;
				$Undo_field= array('type' => 3,'id' => $module->id,'undo' => 1);
				include($TOOLS_PATH.'\undo.php');
				$this->undo = $undo_handler->arr_obj;
			}
		}
		if(empty($module->id)) {
			$module->uid = $this->getUID('module');
			$max = $this->DB->SelectSingle(array('module'),'max(sort_order)',array('parent' => $module->parent->id));
			$module->sort_order = $max+10;
			$module->date_created = 'now';
		}
		else {
			$parent = $this->DB->SelectSingle(array('module'),'parent',array('id' => $module->id));
			if($parent==$module->parent->id) $module->sort_order = $this->DB->SelectSingle(array('module'),'sort_order',array('id' => $module->id));
			else {
				$max = $this->DB->SelectSingle(array('module'),'max(sort_order)',array('parent' => $module->parent->id));
				$module->sort_order = $max+10;
			}
		}
		$module->access_flag = 0;
		if(!empty($request['duplicate_id'])) $this->DB->update('module',array('access_flag' => 0),array('id' => $request['duplicate_id']));
		$module->date_changed = 'now';
		if(isset($request['autochange']) && $request['autochange']=='true') $old_slot = $this->getPagePath($module->id);
		if(!empty($request['_undo_']) || !empty($request['duplicate_id']) || !empty($request['copy'])) {
			if($module->is_describe) {
				if(!empty($request['_undo_'])) $old_obj = $this->openSectionAdmin(array('id' => $request['id'],'undo' => $request['_undo_']));
				else if(!empty($request['duplicate_id'])) $old_obj = $this->openSectionAdmin(array('id' => $request['duplicate_id']));
				else if(!empty($request['copy'])) $old_obj = $this->openSectionAdmin(array('id' => $request['copy']));
				$module->modulejszones = new ObjectsList();
				$module->modulejszones->type = new ModuleJSZone();
				if(is_array($old_obj)) {
					$count = count($old_obj['modulejszones']);
					for($i=0;$i<$count;$i++) {
						$copy_obj = $module->modulejszones->type;
						$module->modulejszones->data[] = $this->parseRequest($old_obj['modulejszones'][$i],clone $copy_obj);
					}
				}
				if(is_object($old_obj)) {
					foreach($old_obj->modulejszones->data as $idx => $js) {
						$module->modulejszones->data[] = clone $js;
					}
				}
			}
		}
		if(empty($module->id)) $this->setLogEvent(3,6,11,'Add page "'.$module->name.'" ('.$module->path.')');
		else {
			if($module->type->id == 5) $this->setLogEvent(3,6,12,'Edit Default page',10);
			else $this->setLogEvent(3,6,12,'Edit page "'.$module->name.'" ('.$module->path.') ['.$module->id.']',$module->id);
		}
		$this->DB->processObject($module, 'save', array(), array(), TRUE);
//exit;		
		if(empty($module->uid)) {
			$selected = $this->DB->SelectAny('SELECT uid FROM module WHERE id = '.$module->id.' LIMIT 1');
			if(!empty($selected) && !empty($selected[0]['uid'])) $this->DB->delete('deleted', array('uid' => $selected[0]['uid'], 'type' => 3));
		}
		else $this->DB->delete('deleted', array('uid' => $module->uid, 'type' => 3));
		if($changed_url){
			$selected = $this->DB->SelectAny('SELECT id FROM preset');
			$count = count($selected);
			for ($i = 0; $i < $count; $i++){
				$record_exists = $this->DB->SelectAny('SELECT id FROM changedurl WHERE ownerid = '.$module->id.' AND preset = '.$selected[$i]['id'].' LIMIT 1');
				if(empty($record_exists)) $this->DB->insert('changedurl', array('ownerid' => $module->id, 'preset' => $selected[$i]['id']));
			}
		}
		$result=$this->DB->SelectAny('select * from moduletemplate where ownerid='.$module->id);
		$arr_tmpl_old=array();
		foreach($result as $ind => $val) $arr_tmpl_old[]=$val['template'];
		$arr_tmpl_old=array_unique($arr_tmpl_old);
		$new_template=array();
		foreach($module->contents->data as $ind => $val){
			preg_match_all('~{Template\*([\da-z\-_]+)\*(\d+)\*(\d+)\*(\d+)}~is',$val->value,$arr_tmpl);
			foreach($arr_tmpl[2] as $ind2 => $val2) $new_template[]=$val2;
		}
		$new_template=array_unique($new_template);
		$arr_del=array_diff($arr_tmpl_old,$new_template) ;
		foreach($new_template as $ind => $val){
			foreach($arr_tmpl_old as $ind_ => $val_){
				if($val_==$val){
					unset($new_template[$ind]);
					continue;
				}
			}
		}
		if(!empty($new_template)) foreach($new_template as $val) $this->DB->insert('moduletemplate',array('template' => $val, 'ownerid' => $module->id));
		if(!empty($arr_del)) foreach($arr_del as $val) $this->DB->delete('moduletemplate',array('template' => $val, 'ownerid' => $module->id));
		$importedfeeds = array();
		$feeds = array();
		foreach($module->contents->data as $ind => $val){
			preg_match_all('~{ImportedFeed\*([\da-z\-_]+)\*(\d+)\*(\d+)\*(\d+)}~is', $val->value, $arr_tmpl);
			foreach($arr_tmpl[2] as $ind2 => $val2) $importedfeeds[] = $val2;
			preg_match_all('~{Feed\*([\da-z\-_]+)\*(\d+)\*(\d+)\*(\d+)}~is', $val->value, $arr_tmpl);
			foreach($arr_tmpl[2] as $ind2 => $val2) $feeds[] = $val2;
		}
		if(empty($importedfeeds)) $this->DB->delete('moduleimportedfeed', array('ownerid' => $module->id));
		else {
			$importedfeeds = array_unique($importedfeeds);
			$this->DB->query('DELETE FROM moduleimportedfeed WHERE ownerid = '.$module->id.' AND importedfeed NOT IN ('.implode(', ', $importedfeeds).')');
			$selected = $this->DB->SelectAny('SELECT importedfeed FROM moduleimportedfeed WHERE ownerid = '.$module->id);
			foreach($selected as $value)
				if(($key = array_search($value['importedfeed'], $importedfeeds)) !== false) unset($importedfeeds[$key]);
			foreach($importedfeeds as $value) $this->DB->insert('moduleimportedfeed', array('importedfeed' => $value, 'ownerid' => $module->id));
		}
		if(empty($feeds)) $this->DB->delete('modulefeed', array('ownerid' => $module->id));
		else {
			$feeds = array_unique($feeds);
			$this->DB->query('DELETE FROM modulefeed WHERE ownerid = '.$module->id.' AND feed NOT IN ('.implode(', ', $feeds).')');
			$selected = $this->DB->SelectAny('SELECT feed FROM modulefeed WHERE ownerid = '.$module->id);
			foreach($selected as $value)
				if(($key = array_search($value['feed'], $feeds)) !== false) unset($feeds[$key]);
			foreach($feeds as $value) $this->DB->insert('modulefeed', array('feed' => $value, 'ownerid' => $module->id));
		}
		$meta = $this->createMeta();
		$this->DB->delete('meta',array('ownerid' => $module->id,'moduletype' => 1));
		if($module->is_describe) {
			if(!empty($request['meta']) && is_array($request['meta']))
				foreach($request['meta'] as $key => $value) {
					$meta->ownerid = $meta->module = $module->id;
					$meta->moduletype = 1;
					$meta->value = $value;
					switch($key) {
						case 'title': $meta->metatype = 1; $meta->sort_order = 1; break;
						case 'description': $meta->metatype = 2; $meta->sort_order = 2; break;
						case 'keywords': $meta->metatype = 3; $meta->sort_order = 3; break;
					}
					$this->DB->processObject($meta,'save',array(),array(),TRUE);
					$meta->id = '';
				}
		}
		$slot = $this->getPagePath($module->id);
		//print '<li>Slot - '.$slot;
		if(!empty($module->id)) $this->DB->delete('modulemenulineitem',array('ownerid' => $module->id));
		if($module->is_describe) {
			if(!empty($request['menu']) && is_array($request['menu'])){
				$mli = new ModuleMenuLineItem();
				foreach($request['menu'] as $key => $value) {
					if(!empty($value)) {
						$mli->id = '';
						$mli->ownerid = $module->id;
						$mli->menu = $value;
						$this->DB->processObject($mli,'save',array(),array(),TRUE);
					}
				}
				$mli->id = '';
				$mli->ownerid = 1;
				$mli->menu = 1;
				$this->DB->processObject($mli,'save',array(),array(),TRUE);
			}
		}
		$modulecomment= new ModuleComment();
		$modulecomment->version = 1;
		$modulecomment->value = 'Page has been created';
		$selected = $this->DB->SelectAny("select version from modulecomment where ownerid = ".$module->id." order by date desc LIMIT 1 OFFSET 0");
		if(!empty($selected[0]['version'])) {
			$modulecomment->version=++$selected[0]['version'];
			$modulecomment->value = (!empty($request['_undo_'])? 'Page has been undone up to '.$request['_undo_']." version<br>\r\n" : '').htmlspecialchars($request['comment']);
		}
		$modulecomment->ownerid = $module->id;
		$modulecomment->member = empty($request['id_user']) ? $this->Security->currentuser->id : $request['id_user'];
		$modulecomment->date = 'now';
		$this->DB->processObject($modulecomment,'save',array(),array(),TRUE);
		if(!empty($request['_undo_'])) {
			if($module->type->id == 5) $this->setLogEvent(3,6,10,'Default Page has been undone up to '.$request['_undo_'].' version',10);
			else $this->setLogEvent(3,6,10,'Page "'.$module->name.'" ('.$module->path.') ['.$module->id.'] has been undone up to '.$request['_undo_'].' version',$module->id);
		}
		if(!$module->is_describe) {
			$this->DB->query('update module set default_page=\'0\' where default_page='.$module->id);
		}
		$this->DB->commit();
		$class = "DescribeView:object";
		if($this->DB->good) {
			if(!$module->is_exsearch) {
				//1. no follow no index
				//	Ã³ Ã±Ã²Ã°Ã Ã­Ã¨Ã¶Ã» Ã¨ Ã³ Ã¤Ã¥Ã´Ã®Ã«Ã²Ã­Ã®Ã© Ã±Ã²Ã°Ã Ã­Ã¨Ã¶Ã» Ã¤Ã«Ã¿ Ã¯Ã Ã¯ÃªÃ¨, Ã²Ã®Ã«Ã¼ÃªÃ® Ã¥Ã±Ã«Ã¨ Ã±Ã²Ã°Ã Ã­Ã¨Ã¶Ã  Ã±Ã°Ã Ã¡Ã®Ã²Ã Ã«Ã  ÃªÃ Ãª Ã¤Ã¥Ã´Ã®Ã«Ã²Ã­Ã Ã¿
				//2. sitemap
				//	Ã¯Ã°Ã¨ Ã±Ã®ÃµÃ°Ã Ã­Ã¥Ã­Ã¨Ã¨ Ã¨Ã§ÃªÃ«Ã¾Ã·Ã¨Ã²Ã¼ Ã¨Ã§ xml, Ã¯Ã°Ã¨ Ã£Ã¥Ã­Ã¥Ã°Ã Ã¶Ã¨Ã¨ Ã­Ã¥ Ã£Ã¥Ã­Ã¥Ã°Ã¨Ã²Ã¼ Ã¨ Ã¯Ã°Ã¨ Ã°Ã³Ã·Ã­Ã®Ã¬ Ã°Ã¥Ã¤Ã ÃªÃ²Ã¨Ã°Ã®Ã¢Ã Ã­Ã¨Ã¨ Ã­Ã¥ Ã¤Ã Ã²Ã¼ Ã±Ã®ÃµÃ°Ã Ã­Ã¨Ã²Ã¼ - Ã¯Ã® Ã®Ã¸Ã¨Ã¡ÃªÃ¥
			}
			foreach($REGISTRY['VirtualSlotTarget']['main'] as $path => $handler) {
				if(($handler == 'DescribeView:object?id='.$module->id || strstr($handler, '?dir='.$module->id)) && $module->id!=1) {
					unset($REGISTRY['VirtualSlotTarget'][''][$path]);
					unset($REGISTRY['VirtualSlotTarget']['main'][$path]);
				}				
				if($path == '/'.$module->path)
				{
			        $query = explode('?',$handler);
					if (isset($query[0]) && $query[0] != "DescribeView:object")
					{
						$class = $query[0];
					}
				}				
			}						
			if($module->is_describe) {
				switch($module->id){ 
					case 1:
						$REGISTRY['default_layout'] = $module->layout->id;
						$REGISTRY['VirtualSlotTarget'][''][''] = $module->layout->id;
						$REGISTRY['VirtualSlotTarget']['']['/'] = $module->layout->id;
						$REGISTRY['VirtualSlotTarget']['main'][''] = 'DescribeView:object?id='.$module->id;
						$REGISTRY['VirtualSlotTarget']['main']['/'] = 'DescribeView:object?id='.$module->id;
						break;
					case 10:
						$REGISTRY['VirtualSlotTarget']['']['?'] = $module->layout->id;
						$REGISTRY['VirtualSlotTarget']['main']['?'] = 'DescribeView:object?id='.$module->id;
						break;
					default:
						$REGISTRY['VirtualSlotTarget'][''][$slot] = $module->layout->id;
						$REGISTRY['VirtualSlotTarget']['main'][$slot] =  $class.'?id='.$module->id; //'DescribeView:object?id='.$module->id;
						break;
				}
			}
			else if(!empty($module->default_page)) $REGISTRY['VirtualSlotTarget']['main'][$slot] = 'DescribeView:object?id='.$module->default_page.'?dir='.$module->id;
			$REGISTRY['VirtualSlotTarget']['main']['?'] = 'DescribeView:object?id=10';
			ksort($REGISTRY['VirtualSlotTarget']['']);
			ksort($REGISTRY['VirtualSlotTarget']['main']);
			$Server->saveRegistry();
			// Ã±Ã®ÃµÃ°Ã Ã­Ã¥Ã­Ã¨Ã¥ Ã¯Ã°Ã¥Ã¤Ã»Ã¤Ã³Ã¹Ã¥Ã© Ã¢Ã¥Ã°Ã±Ã¨Ã¨
			if(!empty($this->undo)) {
				$undo_handler->GetArrayInFile($this->undo, "Undo_object", $ROOT_PATH."/undo/".$pub_type[0]['name']."/".$Undo_field['id']."/".($modulecomment->version>1? $modulecomment->version-1 : 1).".inc");
			}
			// Autochange URL
			if(isset($request['autochange']) && $request['autochange'] == 'true') {
				include($TOOLS_PATH.'\autochangeURL.inc');
				//print '<li>OLD SLOT - '.$old_slot;
				//print '<li>NEW SLOT - '.$slot;
				autochangeURL($old_slot, $slot, (is_object($this->Security) ? $this->Security->currentuser->id : $this->currentuser->id));
				$this->setLogEvent(3, 6, 9, 'Allover content Autochange URL from "'.$old_slot.'" to "'.$slot.'" complete', $module->id);
				$this->DB->commit();
			}
//			clearCacheByURL($slot);		
			clearCacheByURL( ($slot=="/home"?"":$slot)  );		
			clearCacheByURL("/sitemap");
		}
//exit;
		return $module;
	}
	
	function getPagePath($id){
		if($id == 1) return '';
		$selected = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.$id.' LIMIT 1');
		if(empty($selected)) return false;
		$path = '/'.$selected[0]['path'];
		$parent = $selected[0]['parent'];
		while($parent){
			$selected = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.$parent.' LIMIT 1');
			if(empty($selected)) break;
			$path = '/'.$selected[0]['path'].$path;
			$parent = $selected[0]['parent'];
		}
		return $path;
	}

	function saveMetaInfo($request = array()) {
		global $Server, $REGISTRY, $TOOLS_PATH, $ROOT_PATH;
		$this->undo = '';
		$meta = $this->createMeta();
		$js = new ModuleJSZone();
		$this->DB->begin();
		$Undo_field= array('type' => 3,'id' => $request['ownerid'],'undo' => 1);
		include($TOOLS_PATH.'\undo.php');
		$this->undo = $undo_handler->arr_obj;
		$this->DB->delete('meta',array('ownerid' => $request['ownerid'],'moduletype' => $request['moduletype']));
		foreach($request['meta'] as $key => $value) {
			$meta->ownerid = $request['ownerid'];
			$meta->moduletype->id = $request['moduletype'];
			$meta->module->id = $request['ownerid'];
			$meta->value = $value;
			switch($key) {
				case 'title': $meta->metatype->id = 1; $meta->sort_order = 1; break;
				case 'description': $meta->metatype->id = 2; $meta->sort_order = 2; break;
				case 'keywords': $meta->metatype->id = 3; $meta->sort_order = 3; break;
			}
			$this->DB->processObject($meta,'save',array(),array(),TRUE);
			$meta->id = '';
		}
		$this->DB->delete('modulejszone',array('ownerid' => $request['ownerid']));
		foreach($request['js'] as $key => $value) {
			if(!empty($value)) {
				$js->ownerid = $request['ownerid'];
				$js->value = $value;
				$js->use_default = 0;
				switch($key) {
					case 'head':
						$js->type = 1;
						!empty($request['js']['head_use_default']) and $js->use_default = $request['js']['head_use_default'];
					break;
					case 'body_before':
						$js->type = 2;
						!empty($request['js']['before_use_default']) and $js->use_default = $request['js']['before_use_default'];
					break;
					case 'body_after':
						$js->type = 3;
						!empty($request['js']['after_use_default']) and $js->use_default = $request['js']['after_use_default'];
					break;
				}
				if($key!='head_use_default'
					&& $key!='before_use_default'
						&& $key!='after_use_default')
							$this->DB->processObject($js,'save',array(),array(),TRUE);
				$js->id = '';
			}
		}
		//$this->DB->rollback();
		if(!empty($meta->module->id)){
			$modulecomment= new ModuleComment();
			$modulecomment->version = 1;
			$modulecomment->value = 'Meta Information & JS-Zones has been created';
			$selected = $this->DB->SelectAny("select version from modulecomment where ownerid = ".$meta->module->id." order by date desc LIMIT 1 OFFSET 0");
			if(!empty($selected[0]['version'])) {
				$modulecomment->version=++$selected[0]['version'];
				$modulecomment->value = !empty($request['_undo_'])? 'Meta Information & JS-Zones has been undone up to '.$request['_undo_']." version<br>\r\n" : 'Meta Information & JS-Zones has been changes';
			}
			$modulecomment->ownerid = $meta->module->id;
			$modulecomment->member = $Server->getHandler(3)->currentuser->id;
			$modulecomment->date = 'now';
			$this->DB->processObject($modulecomment,'save',array(),array(),TRUE);
			if(!empty($request['_undo_']))
				$this->setLogEvent(3,6,10,'Meta Information & JS-Zones has been undone up to '.$request['_undo_'].' version',30);
			if(!empty($this->undo)) {
				$undo_handler->GetArrayInFile($this->undo, "Undo_object", $ROOT_PATH."/undo/".$pub_type[0]['name']."/".$Undo_field['id']."/".($modulecomment->version>1? $modulecomment->version-1 : 1).".inc");
			}
			$module = new Module();
			$module->id = $meta->module->id;
			$this->DB->initObject($module);
			$module->date_changed = 'now';
			$module->access_flag = 0;
			$this->DB->processObject($module,'save',array(),array(),TRUE);
			$this->setLogEvent(3, 12, 12, 'Edit meta information & js zones for page "'.$module->name.'" ['.$request['ownerid'].']', $request['ownerid']);
		}
		else {
			$modulecomment= new ModuleComment();
			$modulecomment->version = 1;
			$modulecomment->value = 'Default JS-Zones has been created';
			$selected = $this->DB->SelectAny("select version from modulecomment where ownerid = 30 order by date desc LIMIT 1 OFFSET 0");
			if(!empty($selected[0]['version'])) {
				$modulecomment->version=++$selected[0]['version'];
				$modulecomment->value = (!empty($request['_undo_'])? 'Default JS-Zones has been undone up to '.$request['_undo_']." version<br>\r\n" : '').htmlspecialchars($request['comment']);
			}
			$modulecomment->ownerid = 30;
			$modulecomment->member = $Server->getHandler(3)->currentuser->id;
			$modulecomment->date = 'now';
			$this->DB->processObject($modulecomment,'save',array(),array(),TRUE);
			if(!empty($request['_undo_']))
				$this->setLogEvent(3,6,10,'Default JS-Zones has been undone up to '.$request['_undo_'].' version',30);
			$this->setLogEvent(3, 12, 12, 'Edit Default JS-Zones', $request['ownerid']);
			if(!empty($this->undo)) {
				$undo_handler->GetArrayInFile($this->undo, "Undo_object", $ROOT_PATH."/undo/".$pub_type[0]['name']."/".$Undo_field['id']."/".($modulecomment->version>1? $modulecomment->version-1 : 1).".inc");
			}
			$module = new Module();
			$module->id = $request['ownerid'];
			$this->DB->initObject($module);
			$module->date_changed = 'now';
			$module->access_flag = 0;
			$this->DB->processObject($module,'save',array(),array(),TRUE);
		}
		$this->DB->commit();
		clearCache();
		return $meta;
	}

	function getMetaInfo($request = array('module' => 1,'item' => 1),$MetaInfo = array()) {
		empty($request['module']) and $request['module'] = 1;
		empty($request['item'])and $request['item'] = 1;
		$MetaInfo = array();
		$selected = $this->DB->SelectList('id', 'meta', 'id', array('ownerid' => $request['item'], 'moduletype' => $request['module']), 'sort_order');
		if(!empty($selected)){
			foreach($selected as $value) {
				$meta = $this->createMeta();
				$meta->id = $value;
				$this->DB->initObject($meta);
				$MetaInfo[] = $meta;
			}
		}
		else if($request['module'] != 1) $MetaInfo = $this->getMetaInfo(array());
		return $MetaInfo;
	}

	function getMetaInfoAdmin($request = array('module' => 1, 'item' => 1, 'undo' => 0), $MetaInfo = array()) {
		global $TOOLS_PATH;
		empty($request['module']) and $request['module'] = 1;
		empty($request['item'])and $request['item'] = 1;
		if(!empty($request['undo'])) {
			$Undo_field= array('type' => 3,'id' => $request['item'],'undo' => 0,'version' => $request['undo']);
			include($TOOLS_PATH.'\undo.php');
			$i = 0;
			foreach($print_arr['metas'] as $key => $value) {
				$MetaInfo[$i] = $this->createMeta();
				$value['module'] = array('id' => $value['module']);
				$this->parseRequest($value, $MetaInfo[$i]);
				$i++;
			}
		}
		else {
			$selected = $this->DB->SelectList('id', 'meta', 'id', array('ownerid' => empty($request['copy']) ? $request['item'] : $request['copy'], 'moduletype' => $request['module']), 'sort_order');
			if(!empty($selected)){
				foreach($selected as $value) {
					$meta = $this->createMeta();
					$meta->id = $value;
					$this->DB->initObject($meta);
					$MetaInfo[] = $meta;
				}
			}
		}
		return $MetaInfo;
	}

	function getJSZone($request = array('class' => 'Module','module' => 1,'type' => 1,'undo' => 0)) {
		return $this->getJSAdmin($request);
	}

	function getJSAdmin($request = array('class' => 'Module','module' => 1,'type' => 1,'undo' => 0),$JSInfo = array()) { 
		global $TOOLS_PATH;
		empty($request['module']) and $request['module'] = 1;
		empty($request['class']) and $request['class'] = 'Module';
		if(!empty($request['undo'])) {
			$Undo_field= array('type' => 3,'id' => $request['module'],'undo' => 0,'version' => $request['undo']);
			include($TOOLS_PATH.'\undo.php');
			foreach($print_arr['modulejszones'] as $key => $value) {
				$js = new ModuleJSZone();
				$this->parseRequest($value,$js);
				$JSInfo[] = $js;
			}
		}
		else {
			$selected = $this->DB->SelectList('id',strtolower($request['class']).'jszone','id',array('ownerid' => $request['module']),'id');
			if(!empty($selected)){
				$class = $request['class'].'JSZone';
				foreach($selected as $value) {
					$js = new $class();
					$js->type = new JSZone();
					$js->id = $value;
					$this->DB->initObject($js);
					$JSInfo[] = $js;
				}
			}
		}
		return $JSInfo;
	}

	function getPageMenuLineitems($request = array(),$MenuInfo = array()) {
		global $TOOLS_PATH;
		if(!empty($request['undo'])) {
			$Undo_field= array('type' => 3,'id' => $request['id'],'undo' => 0,'version' => $request['undo']);
			include($TOOLS_PATH.'\undo.php');
			foreach($print_arr['menu'] as $key => $value) {
				switch($value['menu']['type']) {
					case 1: $MenuInfo['sitemap'] = $value['menu']['id']; break;
					case 3: $MenuInfo['bottom'] = $value['menu']['id']; break;
					case 4: $MenuInfo['left'] = $value['menu']['id']; break;
					case 6: $MenuInfo['right'] = $value['menu']['id']; break;
					case 7: $MenuInfo['tabs'] = $value['menu']['id']; break;
				}
			}
			empty($MenuInfo['sitemap']) and $MenuInfo['sitemap'] = 0;
			empty($MenuInfo['bottom']) and $MenuInfo['bottom'] = 0;
			empty($MenuInfo['left']) and $MenuInfo['left'] = 0;
			empty($MenuInfo['right']) and $MenuInfo['right'] = 0;
			empty($MenuInfo['tabs']) and $MenuInfo['tabs'] = 0;
		}
		else {
			$id = empty($request['copy']) ? $request['id'] : $request['copy'];
			$selected = $this->DB->SelectSingle(array('modulemenulineitem mli','menu m'),'m.id',array('mli.ownerid' => $id,'m.type' => 1,'mli.menu' => 'm.id'));
			$MenuInfo['sitemap'] = empty($selected)? 0 : $selected;
			$selected = $this->DB->SelectSingle(array('modulemenulineitem mli','menu m'),'m.id',array('mli.ownerid' => $id,'m.type' => 3,'mli.menu' => 'm.id'));
			$MenuInfo['bottom'] = empty($selected)? 0 : $selected;
			$selected = $this->DB->SelectSingle(array('modulemenulineitem mli','menu m'),'m.id',array('mli.ownerid' => $id,'m.type' => 4,'mli.menu' => 'm.id'));
			$MenuInfo['left'] = empty($selected)? 0 : $selected;
			$selected = $this->DB->SelectSingle(array('modulemenulineitem mli','menu m'),'m.id',array('mli.ownerid' => $id,'m.type' => 6,'mli.menu' => 'm.id'));
			$MenuInfo['right'] = empty($selected)? 0 : $selected;
			$selected = $this->DB->SelectSingle(array('modulemenulineitem mli','menu m'),'m.id',array('mli.ownerid' => $id,'m.type' => 7,'mli.menu' => 'm.id'));
			$MenuInfo['tabs'] = empty($selected)? 0 : $selected;
		}
		return $MenuInfo;
	}

	function getModules($request = array()) {
		if(empty($this->modules)) {
			$this->modules = array();
			foreach($this->Server->LM->Modules as $key => $value) {
				$this->modules[$key] = new Module();
				$this->modules[$key]->id = $key;
				$this->DB->initObject($this->modules[$key]);
				if($key > $this->max) $this->max = $key;
			}
		}
		return $this->modules;
	}

	function selectModuleComments($request = array()){
		if(empty($request['fields'])) $request['fields']='mc.*,m.username as member';
		if(empty($request['sortColumn'])) { $request['sortColumn']='mc.version'; $request['sortType']='desc';}
		//$request['conditions']['canceled']=array('='=>0);
		$request['conditions']['m.id']=array('='=>'mc.member');
		$request['conditions']['mc.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','modulecomment mc'),'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','modulecomment mc'),$request['fields'],$request['conditions'],$this->getOrderBy($request),$this->getLimit($request),0,array(),'CND_COMPLEX',$rels);
		return $request;
	}

	function selectFullPublishComments($request = array()){
		if(empty($request['fields'])) $request['fields']='fpc.*,m.username as member';
		if(empty($request['sortColumn'])) { $request['sortColumn']='fpc.version'; $request['sortType']='desc';}
		//$request['conditions']['canceled']=array('='=>0);
		$request['conditions']['m.id']=array('='=>'fpc.member');
		//$request['conditions']['fpc.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','fullpublishcomment fpc'),'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','fullpublishcomment fpc'),$request['fields'],$request['conditions'],$this->getOrderBy($request),$this->getLimit($request),0,array(),'CND_COMPLEX',$rels);
		return $request;
	}

	function makeTree($array,$parent = 0,$tree = array()) {
		foreach($array[$parent] as $value) {
			$tree[$value['id']]['name'] = $value['name'];
			$tree[$value['id']]['path'] = $value['path'];
			$tree[$value['id']]['sort_order'] = $value['sort_order'];
			if(!empty($array[$value['id']])) $tree[$value['id']]['subcat'] = $this->makeTree($array,$value['id']);
		}
		unset($array[$parent]);
		return $tree;
	}

	function selectLayouts($request=array(),$Layouts = array()) {
		global $Server;
		$layouts = $Server->getGuide('layout');
		foreach($layouts as $key => $value) {
			$layout = array();
			$layout['id'] = $key;
			$types = $this->DB->SelectArray(array('layoutcontenttype lct, contenttype ct'),'ct.id,ct.sort_order',array('lct.ownerid' => $key,'lct.type' => 'ct.id'));
			$count = count($types);
			$layout['contenttypes'] = array();
			for($i = 0; $i < $count; $i++)
				$layout['contenttypes'][]['type'] = array(
					'id' => $types[$i]['id'],
					'sort_order' => $types[$i]['sort_order'],
				);
			$Layouts[] = $layout;
		}
		return $Layouts;
	}

	function saveComment($request){
		global $REGISTRY, $Server;
		$modulecomment= new ModuleComment();
		$modulecomment->version = 1;
		$this->DB->begin();
		$selected = $this->DB->SelectAny("select version from modulecomment where ownerid = ".$request['id']." order by version DESC  LIMIT 1 OFFSET 0");
		if(!empty($selected)) {
			$modulecomment->version=++$selected[0]['version'];
		}
		$modulecomment->value = $request['comment'];
		$modulecomment->member = $request['id_user'];
		$modulecomment->ownerid = $request['id'];;
		$modulecomment->date = 'now';
		$this->DB->processObject($modulecomment,'save',array(),array(),TRUE);
		$this->DB->commit();
	}

	function lookMenu($request = array('module' => 1,'type' => 4)) {
		empty($request['module']) and $request['module'] = 0;
		empty($request['type']) and $request['type'] = 0;
		$menu = $this->DB->SelectSingle(array('modulemenulineitem mli','menu m'),'m.id',array('mli.ownerid' => $request['module'],'mli.menu' => 'm.id','m.type' => $request['type']),'parent, sort_order ASC');
		if(!empty($menu)) return $this->openMenu(array('id' => $menu));
		else return array();
	}
// Menu Handler has copy
	function selectMenus($request = array('type' => 0)) {
		$selected = $this->DB->SelectGuide(array('menu g'),'*',array('type' => $request['type']));
		return $selected;
	}
// Menu 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;
	}
// Menu 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' => $value['ownerid'],
					'is_external' => $value['is_external'],
					'anchor' => $value['anchor'],
					'subcat' => $this->makeMenuTree($array,$value['id'])
				);
			}
		}
		return $tree;
	}

	function createModule() {
		$module = new Module();
		$module->parent = new Module();
		$module->bc_parent = new Module();
		$module->layout = new Layout();
		//$module->layout->contenttypes = new ObjectsList();
		//$module->layout->contenttypes->type = new LayoutContentType();
		$module->type = new ModuleType();
		$module->contents = new ObjectsList();
		$module->contents->type = new Content();
		$module->modulejszones = new ObjectsList();
		$module->modulejszones->type = new ModuleJSZone();
		$module->customerreviewitems = new ObjectsList();
		$module->customerreviewitems->type = new CustomerReviewItem();
		//$module->menu = new ObjectsList();
		//$module->menu->type = new ModuleMenuLineItem();
		//$module->menu->type->menu = new Menu();
		//$module->menu->type->menu->menulineitems = new ObjectsList();
		//$module->menu->type->menu->menulineitems->type = new MenuLineItem();
		return $module;
	}

	function createMeta() {
		$meta = new Meta();
		$meta->module = new Module();
		$meta->moduletype = new ModuleType();
		$meta->metatype = new MetaType();
		return $meta;
	}

	function saveFullPublishComments($request = array('id' => 1)) {
		global $TOOLS_PATH, $ROOT_PATH;
		//$Undo_field= array('type' => 0,'id' => 'dafault','undo' => 1);
		//include($TOOLS_PATH.'/undo.php');
		//$this->undo = $undo_handler->arr_obj;
		$fullpubcomment= new FullPublishComment();
		$fullpubcomment->version = 1;
		$fullpubcomment->value = 'Full Site Copy has been created';
		$selected = $this->DB->SelectAny("select version from fullpublishcomment order by date desc LIMIT 1 OFFSET 0");
		if(!empty($selected[0]['version'])) {
			$fullpubcomment->version=++$selected[0]['version'];
			$fullpubcomment->value = (!empty($request['_undo_'])? 'Full Site Copy has been undone up to '.$request['_undo_']." version<br>\r\n" : '').htmlspecialchars($request['comment']);
		}
		//$fullpubcomment->ownerid = $template->id;
		$fullpubcomment->member = $request['id_user'];
		$fullpubcomment->date = 'now';
		$this->DB->processObject($fullpubcomment,'save',array(),array(),TRUE);
		$this->DB->commit();
		//if($this->DB->good) $undo_handler->GetArrayInFile($this->undo,'Undo_object', $ROOT_PATH."/undo/".$pub_type[0]['name']."/".($csscomment->version-1).".inc");
		return $request;
	}
	
	function openproduct() {
		global $Server;
		$selectaccess = $this->DB->SelectSingle(array('parentitem','product'),'product.id',array('itemtype' => 6 ,'parentitem.id' => 'product.item'));
		$handler = $Server->getHandler(23);	
		$product = new Product();
		$product->item = new ParentItem();
		$product->item->itemtype = new ItemType();
		$product->id=$selectaccess;
		$this->DB->initObject($product);
		return $product;

	}
	
	function getAdminNews($request) {
		if(empty($request['sortColumn'])) {
			$request['sortColumn'] = 'date';
			$request['sortType'] = 'asc';
		}
	        $request['sortColumn'] = 'date';
	        $request['sortType'] = 'desc';
		foreach($request['conditions'] as $k=>$v) $rels[$k]=$v;
		empty($request['curPageNumber']) and $request['curPageNumber'] = 1;
		empty($request['pageRecordsQty']) and $request['pageRecordsQty'] = 1;
		//$request['recordsTotal'] = $this->DB->SelectSingle('news','count(*)');
		$request['recordsTotal'] = $this->DB->SelectSingle('news','count(*)', isset($rels)?$rels:array() );
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $this->DB->SelectList('id','news','id', isset($rels)?$rels:array(),$this->getOrderBy($request),$this->getLimit($request));
		foreach($request['curPage'] as $key => $value) {
			$request['curPage'][$key] = $this->createStory();
			$request['curPage'][$key]->id = $value;
			$this->DB->initObject($request['curPage'][$key]);
		}
		return $request;
	}
	
	function getNews($request) { 
		if(empty($request['sortColumn'])) {
			$request['sortColumn'] = 'date';
			$request['sortType'] = 'asc';
		}
        $request['sortColumn'] = 'date';
        $request['sortType'] = 'desc';
        $conditions = '';
  		foreach($request['conditions'] as $k => $v) $conditions .= ' '.$k." = ".$v.' and';
  		$conditions = substr($conditions, 0, -3);
		empty($request['curPageNumber']) and $request['curPageNumber'] = 1;
		empty($request['pageRecordsQty']) and $request['pageRecordsQty'] = 1;
		
		$request['recordsTotal'] = $this->DB->SelectAny('select max(num) as recordsTotal from ((select count(*) as num from news where '.$conditions.' and type = 1) union (select count(*) as num from news where '.$conditions.' and type = 2) ) as foo');
		$request['recordsTotal'] = $request['recordsTotal'][0]['recordsTotal'];
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);

		$limit = $this->getLimit($request);
		if($limit) $limit = ' limit '.$limit[0].', '.$limit[1];
		
//		$curPage = $this->DB->SelectAny('select id from ((select id from news where '.$conditions.' and type = 1 order by date desc  '.$limit.') union (select id from news where '.$conditions.' and type = 2  order by dateto desc '.$limit.') ) as foo');
		$curPage = $this->DB->SelectAny('select id from ((select id,date as datedif from news where '.$conditions.' and type = 1 order by date desc  '.$limit.') union (select id,CASE WHEN DATEDIFF(dateto, CURDATE()) > 0 THEN 1/DATEDIFF(dateto, CURDATE()) ELSE DATEDIFF(dateto, CURDATE()) END as datedif     from news where '.$conditions.' and type = 2  order by datedif desc '.$limit.') ) as foo');
		foreach($curPage as $key => $value)		$request['curPage'][] = $value['id'];
		foreach($request['curPage'] as $key => $value) {
			$request['curPage'][$key] = $this->createStory();
			$request['curPage'][$key]->id = $value;
			$this->DB->initObject($request['curPage'][$key]);
		}
		return $request;
	}

	function getFeatures($request) {
		if(empty($request['sortColumn'])) {
			$request['sortColumn'] = 'date';
			$request['sortType'] = 'asc';
		}
	        $request['sortColumn'] = 'date';
	        $request['sortType'] = 'desc';
		empty($request['curPageNumber']) and $request['curPageNumber'] = 1;
		empty($request['pageRecordsQty']) and $request['pageRecordsQty'] = 1;
		$request['recordsTotal'] = $this->DB->SelectSingle('features','count(*)');
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $this->DB->SelectList('id','features','id',array(),$this->getOrderBy($request),$this->getLimit($request));
		foreach($request['curPage'] as $key => $value) {
			$request['curPage'][$key] = $this->createFeature();
			$request['curPage'][$key]->id = $value;
			$this->DB->initObject($request['curPage'][$key]);
		}
		return $request;
	}

	function getReviews($request) {
		if(empty($request['sortColumn'])) {
			$request['sortColumn'] = 'date';
			$request['sortType'] = 'asc';
		}
        $request['sortColumn'] = 'date';
        $request['sortType'] = 'desc';
		empty($request['curPageNumber']) and $request['curPageNumber'] = 1;
		empty($request['pageRecordsQty']) and $request['pageRecordsQty'] = 1;
		$request['recordsTotal'] = $this->DB->SelectSingle('reviews','count(*)');
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $this->DB->SelectList('id','reviews','id',array(),$this->getOrderBy($request),$this->getLimit($request));
		foreach($request['curPage'] as $key => $value) {
			$request['curPage'][$key] = $this->createReview();
			$request['curPage'][$key]->id = $value;
			$this->DB->initObject($request['curPage'][$key]);
		}
		return $request;
	}
	
	function getVideo($request) {
		if(empty($request['sortColumn'])) {
			$request['sortColumn'] = 'date';
			$request['sortType'] = 'asc';
		}
        $request['sortColumn'] = 'date';
        $request['sortType'] = 'desc';
		empty($request['curPageNumber']) and $request['curPageNumber'] = 1;
		empty($request['pageRecordsQty']) and $request['pageRecordsQty'] = 1;
		$request['recordsTotal'] = $this->DB->SelectSingle('video','count(*)');
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = $this->DB->SelectList('id','video','id',array(),$this->getOrderBy($request),$this->getLimit($request));
		foreach($request['curPage'] as $key => $value) {
			$request['curPage'][$key] = $this->createVideo();
			$request['curPage'][$key]->id = $value;
			$this->DB->initObject($request['curPage'][$key]);
		}
		return $request;
	}

	function getlistFeatures($request = array()) {
		$selected = $this->DB->SelectAny("select id from features order by date desc limit 3");
		$request = array('features' => array());
		foreach((!empty($selected)? $selected : array()) as $key => $value) {
			$news = new Features();
			$news->story_langs = new ObjectsList();
			$news->story_langs->type = new Features_Lang();
			$news->id = $value['id'];
			$this->DB->initObject($news);
			$request['features'][] = $news;
		}
		return $request;
	}

	function getlistReviews($request = array()) {
		$selected = $this->DB->SelectAny("select id from reviews order by date desc limit 3");
		$request = array('reviews' => array());
		foreach((!empty($selected)? $selected : array()) as $key => $value) {
			$news = new Reviews();
			$news->story_langs = new ObjectsList();
			$news->story_langs->type = new Reviews_Lang();
			$news->id = $value['id'];
			$this->DB->initObject($news);
			$request['reviews'][] = $news;
		}
		return $request;
	}
	
	
	function createStory() {
		$story = new News();
		$story->story_langs = new ObjectsList();
		$story->story_langs->type = new News_Lang();
		$story->files = new ObjectsList();
		$story->files->type = new NewsFile();
		
		$story->links = new ObjectsList();
		$story->links->type = new NewsLinks();
		
		return $story;
	}

	function createFeature() {
		$story = new Features();
		$story->story_langs = new ObjectsList();
		$story->story_langs->type = new Features_Lang();
		$story->files = new ObjectsList();
		$story->files->type = new FeaturesFile();
		return $story;
	}

	function createReview() {
		$story = new Reviews();
		$story->story_langs = new ObjectsList();
		$story->story_langs->type = new Reviews_Lang();
		$story->files = new ObjectsList();
		$story->files->type = new ReviewsFile();
		return $story;
	}

	function createVideo() {
		$story = new Video();
		$story->story_langs = new ObjectsList();
		$story->story_langs->type = new Video_Lang();
		$story->files = new ObjectsList();
		$story->files->type = new VideoFile();
		return $story;
	}
	
	function openURL($request) {
		$this->story = $this->createStory();
		$this->parseRequest($request,$this->story);
		$record = $this->DB->SelectAny("select id from news where url_name like '".$request['url_name']."'");
		if(!empty($record)) {
			$this->story->id = $record[0]['id'];
			$this->DB->initObject($this->story);
		}
		if(empty($this->story->story_langs->data)) $this->story->_error = '5';
		return $this->story;
	}

	
	function openStory($request) {
		$this->story = $this->createStory();
		$this->parseRequest($request,$this->story);
		$this->DB->initObject($this->story);
		if(empty($this->story->story_langs->data)) $this->story->_error = '5';
        
		return $this->story;
	}

	function openFeature($request) {
		$this->story = $this->createFeature();
		$this->parseRequest($request,$this->story);
		$this->DB->initObject($this->story);
		if(empty($this->story->story_langs->data)) $this->story->_error = '5';
		return $this->story;
	}
	
	function openReview($request) {
		$this->story = $this->createReview();
		$this->parseRequest($request,$this->story);
		$this->DB->initObject($this->story);
		if(empty($this->story->story_langs->data)) $this->story->_error = '5';
		return $this->story;
	}

	function openVideo($request) {
		$this->story = $this->createVideo();
		$this->parseRequest($request,$this->story);
		$this->DB->initObject($this->story);
		if(empty($this->story->story_langs->data)) $this->story->_error = '5';
        
		return $this->story;
	}
	
	function saveNews($request) {  //printArray($request);
		if(!empty($request['id'])) {
			$old_product = new News();
			$old_product->files = new ObjectsList();
			$old_product->files->type = new NewsFile();
			$old_product->id = $request['id'];
			$this->DB->initObject($old_product);
		}
		$this->story = $this->createStory();
		if(!empty($request['id'])) {
			$this->story->files = clone $old_product->files;
			foreach($old_product->files->data as $value) {
				$this->story->_files[] = array(
					'imagetype' => $value->imagetype,
					'filetype' => $value->filetype,
					'date_uploaded' => $value->date_uploaded,
					'image_link' => $value->image_link,
					'number' => $value->number,
				);
			}
		}
		$this->parseRequest($request,$this->story);
		if(!empty($request['image']) && !empty($request['image'][1]['_tmp_name']) ) $this->saveImages($this->story, $request, 3);		
		$this->DB->processObject($this->story);
		$this->DB->commit();
		//clearCacheByURL( "/about-company/news/".$request['url_name']);
		clearCache();
		return $this->story;
	}

	function saveFeature($request) {
		if(!empty($request['id'])) {
			$old_product = new Features();
			$old_product->files = new ObjectsList();
			$old_product->files->type = new FeaturesFile();
			$old_product->id = $request['id'];
			$this->DB->initObject($old_product);
		}
		$this->story = $this->createFeature();
		if(!empty($request['id'])) {
			$this->story->files = clone $old_product->files;
			foreach($old_product->files->data as $value) {
				$this->story->_files[] = array(
					'imagetype' => $value->imagetype,
					'filetype' => $value->filetype,
					'date_uploaded' => $value->date_uploaded,
					'image_link' => $value->image_link,
					'number' => $value->number,
				);
			}
		}
		$this->parseRequest($request,$this->story);
		if(!empty($request['image'])) $this->saveFeatureImages($this->story, $request, 3);		
		$this->DB->processObject($this->story);
		$this->DB->commit();
		//clearCache();
		return $this->story;
	}

	function saveReview($request) {
		if(!empty($request['id'])) {
			$old_product = new Reviews();
			$old_product->files = new ObjectsList();
			$old_product->files->type = new ReviewsFile();
			$old_product->id = $request['id'];
			$this->DB->initObject($old_product);
		}
		$this->story = $this->createReview();
		if(!empty($request['id'])) {
			$this->story->files = clone $old_product->files;
			foreach($old_product->files->data as $value) {
				$this->story->_files[] = array(
					'imagetype' => $value->imagetype,
					'filetype' => $value->filetype,
					'date_uploaded' => $value->date_uploaded,
					'image_link' => $value->image_link,
					'number' => $value->number,
				);
			}
		}
		$this->parseRequest($request,$this->story);
		if(!empty($request['image'])) $this->saveReviewImages($this->story, $request, 3);		
		$this->DB->processObject($this->story);
		$this->DB->commit();
		//clearCache();
		return $this->story;
	}

	function saveVideo($request) { //printArray($request);exit;
		if(!empty($request['id'])) {
			$old_product = new Video();
			$old_product->files = new ObjectsList();
			$old_product->files->type = new VideoFile();
			$old_product->id = $request['id'];
			$this->DB->initObject($old_product);
		}
		$this->story = $this->createVideo();
		if(!empty($request['id'])) {
			$this->story->files = clone $old_product->files;
			foreach($old_product->files->data as $value) {
				$this->story->_files[] = array(
					'imagetype' => $value->imagetype,
					'filetype' => $value->filetype,
					'date_uploaded' => $value->date_uploaded,
					'image_link' => $value->image_link,
					'number' => $value->number,
				);
			}
		}
		$this->parseRequest($request,$this->story);
		//if(!empty($request['image'])) $this->saveVideoImages($this->story, $request, 3);		
		$this->DB->processObject($this->story);
		$this->DB->commit();
		clearCache();		
		return $this->story;
	}

	
	function deleteStory($request) {
		$this->story = $this->createStory();
		$this->parseRequest($request,$this->story);
		$this->DB->processObject($this->story,'delete');
		$this->DB->commit();
		return $this->story;
	}

	function deleteFeature($request) {
		$this->story = $this->createFeature();
		$this->parseRequest($request,$this->story);
		$this->DB->processObject($this->story,'delete');
		$this->DB->commit();
		return $this->story;
	}

	function deleteVideo($request) {
		$this->story = $this->createVideo();
		$this->parseRequest($request,$this->story);
		$this->DB->processObject($this->story,'delete');
		$this->DB->commit();
		return $this->story;
	}

	function deleteReview($request) {
		$this->story = $this->createReview();
		$this->parseRequest($request,$this->story);
		$this->DB->processObject($this->story,'delete');
		$this->DB->commit();
		return $this->story;
	}
	
	function saveImages($object,$request = array(),$type = 3) {
		$images = array();
		$col = $type==3? 'image' : '3d';
		if(empty($object->files->data)) {
			$i = 1;
			foreach($request[$col] as $key => $value) {
				$images[$key] = new NewsFile();
				$images[$key]->number = $i;
				$images[$key]->filetype = $type;
				$images[$key]->date_uploaded = 'now';
				$images[$key]->imagetype = !empty($value['image_type'])? $value['image_type'] : ' ';
				$images[$key]->sort_order = $i;
				$i++;
			}
		} else {
			foreach($object->files->data as $key => $value) {
				if($value->filetype == $type) {
					if(!empty($request[$col][$value->number])) {
						$images[$value->number] = clone $value;
						unset($object->files->data[$key]);
					}
					else unset($object->files->data[$key]);
				}
			}
		}
		empty($request[$col]) and $request[$col] = array();
		$count = !empty($request[$col])? array_max(array_keys($request[$col])) : 0;
		for($i = 1; $i <= $count; $i++) {
			if(!empty($request[$col][$i])) {
				if(!empty($request[$col][$i]['_tmp_name'])) {
					if(!empty($images[$i])) $images[$i]->date_uploaded = 'now';
					else {
						$images[$i] = new NewsFile();
						$images[$i]->number = $i;
						$images[$i]->sort_order = $i;
						$images[$i]->filetype = $type;
						$images[$i]->date_uploaded = 'now';
						$images[$i]->imagetype = !empty($request[$col][$i]['image_type'])? $request[$col][$i]['image_type'] : ' ';
					}
				}
			}  else if(!empty($images[$i])) unset($images[$i]);
		}
		$i = 1;
		foreach($images as $key => $value) {
			$value->number = $value->sort_order = $i;
			$object->files->data[] = clone $value;
			$i++;
		}
	}

	function saveVideoImages($object,$request = array(),$type = 3) {
		$images = array();
		$col = $type==3? 'image' : '3d';
		if(empty($object->files->data)) {
			$i = 1;
			foreach($request[$col] as $key => $value) {
				$images[$key] = new VideoFile();
				$images[$key]->number = $i;
				$images[$key]->filetype = $type;
				$images[$key]->date_uploaded = 'now';
				$images[$key]->imagetype = !empty($value['image_type'])? $value['image_type'] : ' ';
				$images[$key]->sort_order = $i;
				$i++;
			}
		} else {
			foreach($object->files->data as $key => $value) {
				if($value->filetype == $type) {
					if(!empty($request[$col][$value->number])) {
						$images[$value->number] = clone $value;
						unset($object->files->data[$key]);
					}
					else unset($object->files->data[$key]);
				}
			}
		}
		empty($request[$col]) and $request[$col] = array();
		$count = !empty($request[$col])? array_max(array_keys($request[$col])) : 0;
		for($i = 1; $i <= $count; $i++) {
			if(!empty($request[$col][$i])) {
				if(!empty($request[$col][$i]['_tmp_name'])) {
					if(!empty($images[$i])) $images[$i]->date_uploaded = 'now';
					else {
						$images[$i] = new VideoFile();
						$images[$i]->number = $i;
						$images[$i]->sort_order = $i;
						$images[$i]->filetype = $type;
						$images[$i]->date_uploaded = 'now';
						$images[$i]->imagetype = !empty($request[$col][$i]['image_type'])? $request[$col][$i]['image_type'] : ' ';
					}
				}
			}  else if(!empty($images[$i])) unset($images[$i]);
		}
		$i = 1;
		foreach($images as $key => $value) {
			$value->number = $value->sort_order = $i;
			$object->files->data[] = clone $value;
			$i++;
		}
	}
	
	function saveFeatureImages($object,$request = array(),$type = 3) {
		$images = array();
		$col = $type==3? 'image' : '3d';
		if(empty($object->files->data)) {
			$i = 1;
			foreach($request[$col] as $key => $value) {
				$images[$key] = new FeaturesFile();
				$images[$key]->number = $i;
				$images[$key]->filetype = $type;
				$images[$key]->date_uploaded = 'now';
				$images[$key]->imagetype = !empty($value['image_type'])? $value['image_type'] : ' ';
				$images[$key]->sort_order = $i;
				$i++;
			}
		} else {
			foreach($object->files->data as $key => $value) {
				if($value->filetype == $type) {
					if(!empty($request[$col][$value->number])) {
						$images[$value->number] = clone $value;
						unset($object->files->data[$key]);
					}
					else unset($object->files->data[$key]);
				}
			}
		}
		empty($request[$col]) and $request[$col] = array();
		$count = !empty($request[$col])? array_max(array_keys($request[$col])) : 0;
		for($i = 1; $i <= $count; $i++) {
			if(!empty($request[$col][$i])) {
				if(!empty($request[$col][$i]['_tmp_name'])) {
					if(!empty($images[$i])) $images[$i]->date_uploaded = 'now';
					else {
						$images[$i] = new FeaturesFile();
						$images[$i]->number = $i;
						$images[$i]->sort_order = $i;
						$images[$i]->filetype = $type;
						$images[$i]->date_uploaded = 'now';
						$images[$i]->imagetype = !empty($request[$col][$i]['image_type'])? $request[$col][$i]['image_type'] : ' ';
					}
				}
			}  else if(!empty($images[$i])) unset($images[$i]);
		}
		$i = 1;
		foreach($images as $key => $value) {
			$value->number = $value->sort_order = $i;
			$object->files->data[] = clone $value;
			$i++;
		}
	}	
	
	
	function saveReviewImages($object,$request = array(),$type = 3) {
		$images = array();
		$col = $type==3? 'image' : '3d';
		if(empty($object->files->data)) {
			$i = 1;
			foreach($request[$col] as $key => $value) {
				$images[$key] = new ReviewsFile();
				$images[$key]->number = $i;
				$images[$key]->filetype = $type;
				$images[$key]->date_uploaded = 'now';
				$images[$key]->imagetype = !empty($value['image_type'])? $value['image_type'] : ' ';
				$images[$key]->sort_order = $i;
				$i++;
			}
		} else {
			foreach($object->files->data as $key => $value) {
				if($value->filetype == $type) {
					if(!empty($request[$col][$value->number])) {
						$images[$value->number] = clone $value;
						unset($object->files->data[$key]);
					}
					else unset($object->files->data[$key]);
				}
			}
		}
		empty($request[$col]) and $request[$col] = array();
		$count = !empty($request[$col])? array_max(array_keys($request[$col])) : 0;
		for($i = 1; $i <= $count; $i++) {
			if(!empty($request[$col][$i])) {
				if(!empty($request[$col][$i]['_tmp_name'])) {
					if(!empty($images[$i])) $images[$i]->date_uploaded = 'now';
					else {
						$images[$i] = new ReviewsFile();
						$images[$i]->number = $i;
						$images[$i]->sort_order = $i;
						$images[$i]->filetype = $type;
						$images[$i]->date_uploaded = 'now';
						$images[$i]->imagetype = !empty($request[$col][$i]['image_type'])? $request[$col][$i]['image_type'] : ' ';
					}
				}
			}  else if(!empty($images[$i])) unset($images[$i]);
		}
		$i = 1;
		foreach($images as $key => $value) {
			$value->number = $value->sort_order = $i;
			$object->files->data[] = clone $value;
			$i++;
		}
	}	

	function addSubscribe($request) {
		$selected = $this->DB->SelectAny("select id from subscribe where email like '".$request[0]['email']."'");
		if (!isset($selected[0]))		
		{
			$obj = (object)0;
			$this->DB->getID('subscribe', array('name' => $request[0]['name'], 'email' => $request[0]['email'] ), $obj);
		}
		return $request;
	}

}
?>