<?php

class LogsHandler extends Handler{

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

	function clearErrors($request = array()){
		global $REGISTRY, $ROOT_PATH;
		$selected = $this->DB->SelectArray('error','*',array(),'hits desc');
		$this->DB->begin();
		foreach ($selected as $err_str){
			$path = trim(preg_replace("/#.*/","",$err_str['path']));
			$path = preg_replace("/\/$/","",$path);
			$path = preg_replace("/\?.*/","",$path);
			$path = preg_replace("/[\(\)]/","",$path);
			$found = false;
			if (!(preg_match('/^http:\/\//i',$path) or preg_match('/^https:\/\//i',$path))){
				foreach ($REGISTRY['VirtualSlotTarget']['main'] as $item => $values)
					if (eregi("\/?".$path."$",$item)) {$found = true;	break;}
				if (!$found) if(file_exists($ROOT_PATH.$path)) $found = true;
				if ($found) $this->DB->delete('error',array('id' => $err_str['id']));
			}
		}
		$this->DB->commit();
		return $request;
	}

	function selectLogFilters($request = array()) {
		$selected = $this->DB->SelectArray(array('log l,logtype lt,logentity let,logevent lev'),array('distinct l.type as type_id,lt.name as type,l.entity as entity_id,let.name as entity,l.event as event_id,lev.name as event'),array('l.type' => 'lt.id','l.entity' => 'let.id','l.event' => 'lev.id'),array('l.type asc','l.event asc','l.entity asc'));
		$users = $this->DB->SelectArray(array('member m'),array('id as user_id, username as user'),array(),array('id'));
		$ent = $this->DB->SelectAny('select distinct object, entity as ent_id from log where object is not null and object != 0');
		if (!empty($ent)) foreach ($ent as $k => $v) $ent_obj[$v['ent_id']][$v['object']] = $v['object'];
		foreach($selected as $key => $value) {
			$Logs['types'][$value['type_id']]['type'] = $value['type'];
			$Logs['types'][$value['type_id']]['entities'][$value['entity_id']] = array(
				'ent_name' => $value['entity'],
				'ids' => (empty($ent_obj[$value['entity_id']]) ? '' : $ent_obj[$value['entity_id']])
			);
			$Logs['types'][$value['type_id']]['events'][$value['event_id']] = $value['event'];
		}
		foreach($users as $key => $value) {
			$Logs['users'][$value['user_id']] = $value['user'];;
		}
		return $Logs;
	}

	function selectLogs($request = array()){
		if(empty($request['fields'])) $request['fields']='l.id,l.date,l.object,le.name as entity,l.event,l.type,l.value,m.username as member';
		if(empty($request['sortColumn'])) { $request['sortColumn']='l.date'; $request['sortType']='desc';}
		if(!empty($request['additional'])){
			$additional=$this->DB->SelectAny($request['additional']['query']);
			if (!empty($additional)) foreach ($additional as $k => $v) $lids[] = $v['id'];
		}
//printArray($lids);
		$request['conditions']['l.member']=array('='=>'m.id');
		$request['conditions']['l.entity']=array('='=>'le.id');
		if (!empty($lids))$request['conditions']['l.id'] = array('in' => $lids);
		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','log l','logentity le'),'count(*) as qty',$request['conditions'],0,0,0,array(),'CND_COMPLEX',$rels);
		$request['recordsTotal']=$selected[0]['qty'];
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		if ($request['curPageNumber'] > $request['pagesTotal']) $request['curPageNumber']=1;
		$request['curPage']=$this->DB->SelectArray(Array('member m','log l','logentity le'),$request['fields'],$request['conditions'],$this->getOrderBy($request),$this->getLimit($request),0,array(),'CND_COMPLEX',$rels);
		$exist = array();
		$page_arr=$this->DB->SelectAny('select id,is_describe from module');
		if (!empty($page_arr)) foreach ($page_arr as $k => $v){
			$pages[$v['id']] = $v['is_describe'];
			$exist['page'][] = $v['id'];
		}
		$exist['meta & js zones'] = $exist['page'];
		$menu_arr=$this->DB->SelectAny('select id,type from menu');
		if (!empty($menu_arr)) foreach ($menu_arr as $k => $v){
			$menu[$v['id']] = $v['type'];
			$exist['menu'][] = $v['id'];
		}
		$preset_arr=$this->DB->SelectAny('select id,ownerid from preset');
		if (!empty($preset_arr)) foreach ($preset_arr as $k => $v){
			$presets[$v['id']] = $v['ownerid'];
			$exist['preset'][] = $v['id'];
		}
		$presetgr_arr=$this->DB->SelectAny('select id from presetgroup');
		if (!empty($presetgr_arr)) foreach ($presetgr_arr as $k => $v) $exist['presetgroup'][] = $v['id'];
		$user_arr=$this->DB->SelectAny('select id from member');
		if (!empty($user_arr)) foreach ($user_arr as $k => $v) $exist['user'][] = $v['id'];
		$layout_arr=$this->DB->SelectAny('select id from layout');
		if (!empty($layout_arr)) foreach ($layout_arr as $k => $v) $exist['layout'][] = $v['id'];
		$templ_arr=$this->DB->SelectAny('select id from template');
		if (!empty($templ_arr)) foreach ($templ_arr as $k => $v) $exist['template'][] = $v['id'];		
		foreach ($request['curPage'] as $key => $value){
			if (!empty($exist[$value['entity']]) && !in_array($value['object'],$exist[$value['entity']])) {$value['object'] = 0; $request['curPage'][$key]['object'] = 0;}
			if (($value['entity'] == 'page' or $value['entity'] == 'meta & js zones') && $value['object'] != 0)
				$request['curPage'][$key]['page_path'] = ($pages[$value['object']]==1) ? $this->path_sticker($value['object']) : ' ';
			if ($value['entity'] == 'preset' && $value['object'] != 0)
				$request['curPage'][$key]['presetgroup'] = $presets[$value['object']];
			if ($value['entity'] == 'menu' && $value['object'] != 0)
				$request['curPage'][$key]['menutype'] = $menu[$value['object']];
		}
//printArray($request);
		return $request;
	}

	function selectLogsErrors($request = array()){
		global $REGISTRY;
		if(empty($request['curPageNumber'])) $request['curPageNumber']=1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty']=50;
		$selected=$this->DB->SelectAny('SELECT * FROM error ORDER BY '.$request['order'].' '.$request['direction']);
		$request['recordsTotal']=count($selected);
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		$request['curPage'] = array_slice($selected,($request['curPageNumber']-1)*$request['pageRecordsQty'],$request['pageRecordsQty']);
		return $request;
	}

	function selectLogsMenus($request = array()){
		global $REGISTRY;
		if(empty($request['curPageNumber'])) $request['curPageNumber']=1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty']=50;
		$selected=$this->DB->SelectAny('SELECT m.id, me.id AS id_menu, m.name, me.name AS menu_name, me.type FROM module m, modulemenulineitem mml, menu me WHERE (m.is_describe = 1) AND (mml.ownerid = m.id) AND (me.id = mml.menu) ORDER BY '.($request['order'] == 'id' || $request['order'] == 'name' ? $request['order'].' '.$request['direction'].',' : '').' m.parent, m.sort_order, me.type');
		$allMenus=Array();
		foreach($selected as $key => $value) {
			$path = ' ';
			foreach($REGISTRY['VirtualSlotTarget']['main'] as $path => $handler) {
				if($handler == 'DescribeView:object?id='.$value['id']) {
					$allMenus[$value['id']]['path'] = $path;
				}
				$allMenus[$value['id']]['id'] = $value['id'];
				$allMenus[$value['id']]['name'] = $value['name'];
				$allMenus[$value['id']]['menu'.$value['type']] = $value['menu_name'];
				$allMenus[$value['id']]['id_menu'.$value['type']] = $value['id_menu'];
			}
		}
		switch ($request['order']){
			case 'path': {
				$allMenus = sortAssocArrayBy($allMenus, ($request['direction'] == 'ASC' ? true : false), 'path', 'string');
				break;
			}
			case 'sitemap': case 'left': case 'tabs': case 'right': case 'bottom': {
				$menutypes = $this->DB->SelectAny('SELECT * FROM menutype');
				$temp = array();
				foreach($menutypes as $value)
					$temp[$value['name']] = $value['id'];
				$menutypes = $temp;
				$allMenus = sortAssocArrayBy($allMenus, ($request['direction'] == 'ASC' ? true : false), 'menu'.$menutypes[$request['order']], 'string');
				break;
			}
		}
		$request['recordsTotal'] = count($allMenus);
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = array_slice($allMenus, ($request['curPageNumber'] - 1) * $request['pageRecordsQty'], $request['pageRecordsQty']);
		return $request;
	}

	function selectLogsLayouts($request = array()){
		global $REGISTRY;
		if(empty($request['curPageNumber'])) $request['curPageNumber']=1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty']=50;
		$selected=$this->DB->SelectAny('select  m.id, m.name, l.name as layout from module m, layout l where m.is_describe=1 and m.layout=l.id order by l.id, m.parent, m.sort_order');
		$request['recordsTotal']=count($selected);
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		$request['curPage']=$this->DB->SelectAny('select m.id, m.name, l.id as layout_id, l.name as layout from module m, layout l where m.is_describe=1 and m.layout=l.id'.($request['order'] == 'path' ? '' : ' order by '.$request['order'].' '.$request['direction'].', m.parent, m.sort_order LIMIT '.$request['pageRecordsQty'].' OFFSET '.($request['curPageNumber']-1)*$request['pageRecordsQty']));
		foreach($request['curPage'] as $key => $value) {
			foreach($REGISTRY['VirtualSlotTarget']['main'] as $path => $handler)
				if($handler == 'DescribeView:object?id='.$value['id'])
					$request['curPage'][$key]['path'] = $path;
			if(empty($request['curPage'][$key]['path']) || $request['curPage'][$key]['path'] == '?')
				$request['curPage'][$key]['path'] = ' ';
		}
		if ($request['order'] == 'path'){
			$request['curPage'] = sortArrayBy($request['curPage'], ($request['direction'] == 'ASC' ? true : false), 'path', 'string');
			$request['curPage'] = array_slice($request['curPage'], ($request['curPageNumber'] - 1) * $request['pageRecordsQty'], $request['pageRecordsQty']);
		}
		return $request;
	}

	function selectLogsTemplates($request = array()){
		global $REGISTRY;
		$report = array();
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 50;
		$selected = $this->DB->SelectAny('SELECT tg.id, tg.name, m.id AS id_page, m.name AS page_name FROM module m, template tg, moduletemplate mt WHERE (mt.template = tg.id) AND (mt.ownerid = m.id) ORDER BY '.$request['order'].' '.$request['direction']);
		foreach($selected as $key => $value) {
			$path = '&nbsp;';
			$report[$value['id']]['id'] = $value['id'];
			$report[$value['id']]['page_name'][] = $value['page_name'];
			$report[$value['id']]['id_page'][] = $value['id_page'];
			$report[$value['id']]['name'] = $value['name'];
			foreach($REGISTRY['VirtualSlotTarget']['main'] as $path => $handler) 
				if($handler == 'DescribeView:object?id='.$value['id_page']) 
					$report[$value['id']]['path'][] = $path;
		}
		$request['recordsTotal']=count($report);
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = array_slice($report, ($request['curPageNumber'] - 1) * $request['pageRecordsQty'], $request['pageRecordsQty']);
		return $request;
	}

	function selectLogsJS($request = array()){
		global $REGISTRY;
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty']))$request['pageRecordsQty'] = 50;
		$js_arr = array();
		//---- pages ----
		$query = "SELECT c.ownerid, c.value, m.name FROM content c, module m WHERE (m.id = c.ownerid) AND (m.is_describe = 1) AND (c.value LIKE '%<script%' OR c.value LIKE '%<SCRIPT%') ORDER BY m.parent, m.sort_order";	
		$selected = $this->DB->SelectAny($query);
		foreach ($selected as $value){
			$p_arr = split('>', $value['value']);
			foreach ($p_arr as $p_row)
				if (preg_match ("/<script.*src.*/i", $p_row, $jsp_arr)){
					$js_arr[$value['ownerid']]['name'] = $value['name'];
					foreach ($jsp_arr as $jsp_row){
						$jsp_row = stripslashes($jsp_row);
						$jsp_row = preg_replace("/\'/", "\"", $jsp_row);
						$jsp_row = preg_replace("/&#39;/", "\"", $jsp_row);
						$js_arr[$value['ownerid']]['js'][] = preg_replace("/.*src[\s]*=[\s]*\"([^\"]*)\".*/i","\\1", $jsp_row);
					}
				}
		}
		// meta
		$query = "SELECT j.ownerid, j.value, m.name FROM modulejszone j, module m WHERE (m.id = j.ownerid) AND (m.is_describe = 1) AND (j.value LIKE '%<script%' OR j.value LIKE '%<SCRIPT%') ORDER BY m.parent, m.sort_order";	
		$selected = $this->DB->SelectAny($query);
		foreach ($selected as $value){
			$j_arr = split('>', $value['value']);
			foreach ($j_arr as $j_row)
				if (preg_match ("/<script.*src.*/i", $j_row, $jsj_arr)){
					$js_arr[$value['ownerid']]['name'] = $value['name'];
					foreach ($jsj_arr as $jsj_row){
						$jsp_row = stripslashes($jsp_row);
						$jsj_row = preg_replace("/\'/", "\"", $jsj_row);
						$jsj_row = preg_replace("/&#39;/", "\"", $jsj_row);
						$js_arr[$value['ownerid']]['meta'][] = preg_replace("/.*src[\s]*=[\s]*\"([^\"]*)\".*/i","\\1", $jsj_row);
					}
				}
		}
		foreach($js_arr as $id => $value) {
			$js_arr[$id]['id'] = $id;
			foreach($REGISTRY['VirtualSlotTarget']['main'] as $path => $handler)
				if($handler == 'DescribeView:object?id='.$id)
					$js_arr[$id]['path'] = $path;
			if (!isset($js_arr[$id]['path']))
				$js_arr[$id]['path'] = '&nbsp;';
		}
		$type = $request['order'] == 'id' ? 'number' : 'string';
		$js_arr = sortAssocArrayBy($js_arr, ($request['direction'] == 'ASC' ? true : false), $request['order'], $type);
		$request['recordsTotal'] = count($js_arr);
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$request['curPage'] = array_slice($js_arr, ($request['curPageNumber'] - 1) * $request['pageRecordsQty'], $request['pageRecordsQty']);
		return $request;
	}
	
	function selectPublishTypes($request = array()) {
		$selected = $this->DB->SelectAny('SELECT * FROM publish_type');
		$types = array();
		$count = count($selected);
		for ($i = 0; $i < $count; $i++)
			$types[$selected[$i]['name']] = $selected[$i]['number'];
		return $types;
	}
	
	function selectUnusedObjects($request = array()){
		GLOBAL $REGISTRY, $ROOT_PATH;
		$result = array();
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 50;
		//printArray($request['files']);
		switch($request['type']){
			default: case 'files':
				$used = array();
				// pages
				$selected = $this->DB->SelectAny('SELECT ownerid, value FROM content WHERE value IS NOT NULL ORDER BY ownerid;');
				if(!empty($selected)){
					$count = count($selected);
					for ($i = 0; $i < $count; $i++) {
						if ($selected[$i]['value'] == '') continue;
						$page_links = $this->linksArray($selected[$i]['value']);
						foreach ($page_links as $link)
							if (in_array($link, $request['files'])) $used['files'][] = $link;
					}
				}
				// layouts
				$selected = $this->DB->SelectAny("SELECT id, name, value FROM layout WHERE value IS NOT NULL");
				if(!empty($selected) && sizeof($selected)) {
					foreach($selected as $value) {
						$layout_links = $this->linksArray($value['value']);
						foreach($layout_links as $link) {
							if(in_array($link,$request['files'])) $used['files'][] = $link;
							else if(preg_match('/{.*}.*/',$link)) {
								$link = preg_quote($link,"/");
								$link = preg_replace('/\\\{.*\\\}/','.*',$link);
								if(strlen($link) > 4) {
									foreach($request['files'] as $file)
										if(preg_match('/'.$link.'/i',$file)) $used['files'][] = $file;
								}
							}
						}
					}
				}
				// templates
				$selected=$this->DB->SelectAny('SELECT value FROM templateitem WHERE value IS NOT NULL;');
				if(!empty($selected))
					foreach ($selected as $template) {
						if ($template['value'] == '') continue;
						$templ_links = $this->linksArray($template['value']);
						foreach ($templ_links as $link)
							if (in_array($link,$request['files'])) $used['files'][] = $link;
					}
				// menus
				$selected=$this->DB->SelectAny('SELECT path FROM menulineitem WHERE is_external = 0 and ownerid != 2 and path IS NOT NULL;');
				if(!empty($selected))
					foreach ($selected as $menuitem)
						if (in_array($menuitem['path'],$request['files'])) $used['files'][] = $menuitem['path'];
				// jszone
				$selected=$this->DB->SelectAny('SELECT value FROM modulejszone WHERE value IS NOT NULL;');
				if(!empty($selected))
					foreach ($selected as $js) {
						if ($js['value'] == '') continue;
						$js_links = $this->linksArray($js['value']);
						foreach ($js_links as $link)
							if (in_array($link,$request['files'])) $used['files'][] = $link;
					}
				if (!empty($used['files']))
					foreach ($request['files'] as $key => $file)
						if (in_array($file,$used['files'])) unset($request['files'][$key]);
					$result = $request['files'];
			break;
			case 'menus':
				$selected = $this->DB->SelectAny('SELECT id, name, type FROM menu WHERE (type != 5) AND id NOT IN(SELECT me.id FROM module m, modulemenulineitem mml, menu me WHERE (m.is_describe = 1) AND (mml.ownerid = m.id) AND (me.id = mml.menu) GROUP BY me.id) ORDER BY '.$request['order'].' '.$request['direction']);
				if(!empty($selected)) $result = $selected;
				$selected = $this->DB->SelectAny('SELECT id, name FROM menutype');
				$menutypes = array();
				foreach($selected as $value) $menutypes[$value['id']] = ucfirst($value['name']);
				$count = count($result);
				for ($i = 0; $i < $count; $i++) $result[$i]['type'] = $menutypes[$result[$i]['type']];
			break;
			case 'layouts':
				$selected = $this->DB->SelectAny('SELECT id, name FROM layout WHERE id NOT IN (SELECT layout FROM module WHERE (is_describe = 1) GROUP BY layout) ORDER BY '.$request['order'].' '.$request['direction']);
				if(!empty($selected)) $result = $selected;
			break;
			case 'templates':
				$selected = $this->DB->SelectAny('SELECT id, name FROM template WHERE id NOT IN (SELECT template FROM moduletemplate GROUP BY template) ORDER BY '.$request['order'].' '.$request['direction']);
				if(!empty($selected)) $result = $selected;
			break;
		}
		$request['recordsTotal'] = count($result);
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		$request['curPage'] = array_slice($result,($request['curPageNumber']-1)*$request['pageRecordsQty'],$request['pageRecordsQty']);echo date('Y-m-d H:i:s', time()).'<br>';
		return $request;
	}
	
	function selectFoldersDefaultPages($request = array()) {
		if(empty($request['curPageNumber']))
			$request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty']))
			$request['pageRecordsQty'] = 50;
		$result = array();
		$selected = $this->DB->SelectAny('SELECT id, name, path, parent, default_page FROM module WHERE (is_describe = 0) AND (default_page > 0)'.($request['order'] == 'page_name' ? '' : ' ORDER BY '.$request['order'].' '.$request['direction']));
		foreach($selected as $key => $value){
			$page = $this->DB->SelectAny('SELECT id, name, path, parent FROM module WHERE id = '.$value['default_page']);
			if(empty($page))
				continue;
			$result[$key] = array(
				'id' => $value['id'],
				'name' => $value['name'],
				'path' => $value['path'],
			);
			$parent = $value['parent'];
			while ($parent){
				$sel = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.$parent);
				if(empty($sel)) break;
				else{
					$result[$key]['path'] = $sel[0]['path'].'/'.$result[$key]['path'];
					$parent = $sel[0]['parent'];
				}
			}
			$result[$key]['default_page'] = array(
				'id' => $page[0]['id'],
				'name' => $page[0]['name'],
				'path' => $page[0]['path'],
			);
			$parent = $page[0]['parent'];
			while ($parent){
				$sel = $this->DB->SelectAny('SELECT path, parent FROM module WHERE id = '.$parent);
				if(empty($sel)) break;
				else{
					$result[$key]['default_page']['path'] = $sel[0]['path'].'/'.$result[$key]['default_page']['path'];
					$parent = $sel[0]['parent'];
				}
			}
		}
		if ($request['order'] == 'page_name')
			$result = sortMultiStagedAssocArrayBy($result, ($request['direction'] == 'ASC' ? true : false), array('default_page', 'name',), 'string');
		if(empty($result)){
			$request['recordsTotal'] = 0;
			$request['pagesTotal'] = 0;
			$request['curPage'] = array();
		}
		else{
			$request['recordsTotal'] = count($result);
			$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
			$request['curPage'] = array_slice($result, ($request['curPageNumber'] - 1) * $request['pageRecordsQty'], $request['pageRecordsQty']);
		}
		return $request;
	}
	
	function selectOffermatica($request = array()){
		global $REGISTRY;
		$result = array(); $layouts = array('script'=>'','div'=>'','call'=>'');
		if(empty($request['curPageNumber'])) $request['curPageNumber']=1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty']=50;
		switch ($request['type']){
			default: case 'pages':
				$scripts_js = $this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as jszone FROM modulejszone j, module m WHERE j.ownerid=m.id and m.type NOT IN (7,2) and (j.value ilike '%/mbox.js%')");
				$divs_js = $this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as jszone FROM modulejszone j, module m WHERE j.ownerid=m.id and m.type NOT IN (7,2) and (j.value similar to '%<(div|DIV) +(class|CLASS) *= *(\"|\')*mbox%')");
				$call_js = $this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as jszone FROM modulejszone j, module m WHERE j.ownerid=m.id and m.type NOT IN (7,2) and (j.value similar to '%mboxCreate%')");
				$scripts_p = $this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as cont FROM content c, module m WHERE c.ownerid=m.id and m.type NOT IN (7,2) and (c.value ilike '%/mbox.js%')");
				$divs_p = $this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as cont FROM content c, module m WHERE c.ownerid=m.id and m.type NOT IN (7,2) and (c.value similar to '%<(div|DIV) +(class|CLASS) *= *(\"|\')*mbox%')");
				$call_p = $this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as cont FROM content c, module m WHERE c.ownerid=m.id and m.type NOT IN (7,2) and (c.value similar to '%mboxCreate%')");
				foreach ($scripts_js as $key => $val) $scripts[$val['id']] = $val;
				foreach ($scripts_p as $key => $val) if (array_key_exists($val['id'], $scripts)) $scripts[$val['id']]['cont'] = true; else $scripts[$val['id']] = $val;
				foreach ($divs_js as $key => $val) $divs[$val['id']] = $val;
				foreach ($divs_p as $key => $val) if (array_key_exists($val['id'], $divs)) $divs[$val['id']]['cont'] = true; else $divs[$val['id']] = $val;
				foreach ($call_js as $key => $val) $call[$val['id']] = $val;
				foreach ($call_p as $key => $val) if (array_key_exists($val['id'], $call)) $call[$val['id']]['cont'] = true; else $call[$val['id']] = $val;
			break;
			case 'layouts':
				$selected = $this->DB->SelectAny("SELECT id, name, value FROM layout WHERE value IS NOT NULL");
				if(!empty($selected) && sizeof($selected)) {
					foreach($selected as $value) {
						if(preg_match("~\/mbox(_rc)?\.js~i",$$value['value'])) $layouts['script'] .= "'".$$value['name']."',";
						if(preg_match("~div\s+class\s*=\s*(\"|\')*mbox~i",$$value['value'])) $layouts['div'] .= "'".$$value['name']."',";
						if(preg_match("~mboxCreate~i",$$value['value'])) $layouts['call'] .= "'".$$value['name']."',";
					}
				}
				if($layouts['script']!='') $scripts=$this->DB->SelectAny("SELECT distinct l.id, l.name, 'true' as cont FROM layout l WHERE l.name in (".substr($layouts['script'],0,strlen($layouts['script'])-1).")");
				if($layouts['div']!='') $divs=$this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as cont FROM layout l, module m WHERE l.id=m.layout and l.name in (".substr($layouts['div'],0,strlen($layouts['div'])-1).")");
				if($layouts['call']!='') $call=$this->DB->SelectAny("SELECT distinct m.id, m.name, 'true' as cont FROM layout l, module m WHERE l.id=m.layout and l.name in (".substr($layouts['call'],0,strlen($layouts['call'])-1).")");
				$path = '/Registar/LayoutManager/Update/';
			break;
			case 'templates':
				$scripts = $this->DB->SelectAny("SELECT distinct tg.id, tg.name, 'true' as cont	FROM template tg, templateitem t WHERE t.ownerid=tg.id and (t.value ilike '%/mbox.js%')");
				$divs = $this->DB->SelectAny("SELECT distinct tg.id, tg.name, 'true' as cont FROM template tg, templateitem t WHERE t.ownerid=tg.id and (t.value similar to '%<(div|DIV) +(class|CLASS) *= *(\"|\')*mbox%')");
				$call = $this->DB->SelectAny("SELECT distinct tg.id, tg.name, 'true' as cont FROM template tg, templateitem t WHERE t.ownerid=tg.id and (t.value similar to '%mboxCreate%')");
				$path = '/Registar/TemplateManager/Update/';
			break;
			case 'default_js':
				$scripts = $this->DB->SelectAny("SELECT id, 'true' as cont  FROM modulejszone WHERE ownerid=30 and value ilike '%/mbox.js%'");
				$divs = $this->DB->SelectAny("SELECT id, 'true' as cont FROM modulejszone WHERE ownerid=30 and value similar to '%<(div|DIV) +(class|CLASS) *= *(\"|\')*mbox%'");
				$call = $this->DB->SelectAny("SELECT id, 'true' as cont FROM modulejszone WHERE ownerid=30 and value similar to '%mboxCreate%'");
				$path = '/Registar/ScriptEditor';
			break;
		}
		if (!empty($scripts))
			foreach ($scripts as $value)
				$result[$value['id']] = array(
					'id' => ($request['type']=='default_js') ? '' : $value['id'],
					'name' => ($request['type']=='default_js') ? 'Default JS-Zones Editor' : $value['name'],
					'path' => ($request['type']=='pages') ? $this->path_sticker($value['id']) : (($request['type']=='default_js')? $path : $path.$value['id']),
					'script' => true,
					'jszone_s' => (isset($value['jszone'])) ? $value['jszone'] : null,
					'cont_s' => (isset($value['cont'])) ? $value['cont'] : null
				);
		if (!empty($divs))
			foreach ($divs as $value){
				if (!array_key_exists($value['id'], $result))
					$result[$value['id']] = array(
						'id' => ($request['type']=='default_js') ? '' : $value['id'],
						'name' => ($request['type']=='default_js') ? 'Default JS-Zones Editor' : $value['name'],
						'path' => ($request['type']=='pages') ? $this->path_sticker($value['id']) : (($request['type']=='default_js')? $path : $path.$value['id'])
					);
				$result[$value['id']]['div'] = true;
				$result[$value['id']]['jszone_d'] = (isset($value['jszone'])) ? $value['jszone'] : null;
				$result[$value['id']]['cont_d'] = (isset($value['cont'])) ? $value['cont'] : null;
			}
		if (!empty($call))
			foreach ($call as $value){
				if (!array_key_exists($value['id'], $result))
					$result[$value['id']] = array(
						'id' => ($request['type']=='default_js') ? '' : $value['id'],
						'name' => ($request['type']=='default_js') ? 'Default JS-Zones Editor' : $value['name'],
						'path' => ($request['type']=='pages') ? $this->path_sticker($value['id']) : (($request['type']=='default_js')? $path : $path.$value['id'])
					);
				$result[$value['id']]['call'] = true;
				$result[$value['id']]['jszone_c'] = (isset($value['jszone'])) ? $value['jszone'] : null;
				$result[$value['id']]['cont_c'] = (isset($value['cont'])) ? $value['cont'] : null;
			}
		$result = sortAssocArrayBy($result, ($request['direction'] == 'ASC' ? true : false), $request['order'], ($request['order'] == 'id' ? 'number' : 'string'));
		$request['recordsTotal']=count($result);
		$request['pagesTotal'] = ceil($request['recordsTotal']/$request['pageRecordsQty']);
		$request['curPage'] = array_slice($result,($request['curPageNumber']-1)*$request['pageRecordsQty'],$request['pageRecordsQty']);
		return $request;
	}
	
	function selectLogsPackages($request = array()){
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 50;
		$selected = $this->DB->SelectAny('SELECT count(id) AS count FROM package');
		$request['recordsTotal'] = $selected[0]['count'];
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$selected = $this->DB->SelectAny('SELECT id, name, actioned, date_changed, comment FROM package ORDER BY '.$request['order'].' '.$request['direction'].' LIMIT '.$request['pageRecordsQty'].' OFFSET '.(($request['curPageNumber'] - 1) * $request['pageRecordsQty']));
		$count = count($selected);
		for ($i = 0; $i < $count; $i++){
			$date_changed = explode('.', $selected[$i]['date_changed']);
			$selected[$i]['date_changed'] = $date_changed[0];
			$publish = $this->DB->SelectAny('SELECT id, type, successful, host, date_published, userid FROM packagepublish WHERE ownerid = '.$selected[$i]['id'].' ORDER BY date_published ASC');
			$selected[$i]['publish'] = $publish;
			foreach($selected[$i]['publish'] as $key => $value){
				$date_published = explode('.', $value['date_published']);
				$selected[$i]['publish'][$key]['date_published'] = $date_published[0];
				$selected[$i]['publish'][$key]['hostpath'] = $this->getHostPath(array('type' => $value['type'], 'host' => $value['host'],));
				$selected[$i]['publish'][$key]['username'] = $this->getUserName(array('type' => $value['type'], 'userid' => $value['userid'],));
			}
		}
		$request['curPage'] = $selected;
		return $request;
	}
	
	function selectLogsDeletedObjectsProcessings($request = array()) {
		if(empty($request['curPageNumber'])) $request['curPageNumber'] = 1;
		if(empty($request['pageRecordsQty'])) $request['pageRecordsQty'] = 50;
		$selected = $this->DB->SelectAny('SELECT count(id) AS count FROM deletedprocessing');
		$request['recordsTotal'] = $selected[0]['count'];
		$request['pagesTotal'] = ceil($request['recordsTotal'] / $request['pageRecordsQty']);
		$query = 'SELECT id, host, userid, date_processed, successful, type FROM deletedprocessing'.($request['order'] == 'user' ? '' : ' ORDER BY '.$request['order'].' '.$request['direction']).' LIMIT '.$request['pageRecordsQty'].' OFFSET '.(($request['curPageNumber'] - 1) * $request['pageRecordsQty']);
		$selected = $this->DB->SelectAny($query);
		$count = count($selected);
		for ($i = 0; $i < $count; $i++){
			$date_processed = explode('.', $selected[$i]['date_processed']);
			$selected[$i]['date_processed'] = $date_processed[0];
			$selected[$i]['hostpath'] = $this->getHostPath(array('type' => $selected[$i]['type'], 'host' => $selected[$i]['host'],));
			$selected[$i]['username'] = $this->getUserName(array('type' => $selected[$i]['type'], 'userid' => $selected[$i]['userid'],));
		}
		$request['curPage'] = $request['order'] == 'user' ? sortArrayBy($selected, ($request['direction'] == 'ASC' ? true : false), 'username', 'string') : $selected;
		return $request;
	}
	
	function createDeletedProcessing(){
		$deletedprocessing = new DeletedProcessing();
		$deletedprocessing->report = new ObjectsList();
		$deletedprocessing->report->type = new DeletedProcessingReport();
		return $deletedprocessing;
	}
	
	function openDeletedObjectsProcessing($request = array()) {
		if(empty($request['id'])){
			$request['_error'] = 'Deleted objects processing ID is not specified';
			return $request;
		}
		$selected = $this->DB->SelectAny('SELECT id FROM deletedprocessing WHERE id = '.$request['id'].' LIMIT 1');
		if (empty($selected)){
			$request['_error'] = 'Deleted objects processing with such ID doec not exist';
			return $request;
		}
		$deletedprocessing = $this->createDeletedProcessing();
		$deletedprocessing->id = $request['id'];
		$this->DB->initObject($deletedprocessing);
		$deletedprocessing->hostpath = $this->getHostPath(array('type' => $deletedprocessing->type, 'host' => $deletedprocessing->host,));
		$deletedprocessing->username = $this->getUserName(array('type' => $deletedprocessing->type, 'userid' => $deletedprocessing->userid,));
		return $deletedprocessing;
	}
	
	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 selectReportTypes($request = array()){
		$selected = $this->DB->SelectAny('SELECT number, name FROM reporttype');
		$types = array();
		foreach($selected as $value)
			$types[$value['number']] = $value['name'];
		return $types;
	}
	
	function linksArray($text){
		GLOBAL $REGISTRY;
		$links_array = array();
		$patterns = array(
			"/.*window\.open[\s]*\([\s]*\"([^\"]*)\".*/i",
			"/.*window\.location[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*document\.location[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*location\.href[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*location\.pathname[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*url[\s]*\([\s]*\"?[\s]*([^\"]*)\"?\).*/i",
			"/.*url[\s]*=[\s]*\"?[\s]*([^\"]*)\"?.*/i",
			"/.*background[^-\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*href[\s]*=[\s]*\"([^\"]*)\".*/i",
			"/.*src[\s]*=[\s]*\"([^\"]*)\".*/i"
		);
		$text = preg_replace("~'~", "\"", $text);
		$text = preg_replace("~&#39;~", "\"", $text);
		$text = preg_replace("~&quot;~", "\"", $text);
		$text = preg_replace("/%20/", " ", $text);
		$text = preg_replace("/<!--.*?-->/s", " ", $text);
		$text_arr = explode('>', $text);
		$count = count($text_arr);
		for ($i = 0; $i < $count; $i++){
			if (preg_match("/window\.open\(.*/i",$text_arr[$i], $l_arr) or preg_match("/[window|document]+\.location.*/i",$text_arr[$i], $l_arr)
			or preg_match("/location\.[href|pathname]+.*/i",$text_arr[$i], $l_arr)
			or preg_match("/url.*/i",$text_arr[$i], $l_arr) or preg_match("/background[\s]*=.*/i",$text_arr[$i], $l_arr)
			or preg_match("/src.*/i",$text_arr[$i], $l_arr) or preg_match("/href.*/i",$text_arr[$i], $l_arr)){
				$c = count($l_arr);
				for ($j = 0; $j < $c; $j++){
					$link = preg_replace($patterns, "\\1", $l_arr[$j]);
					$link = preg_replace('/#.*/', '', $link);
					if (preg_match('/{.*}.*/', $link))
						foreach ($REGISTRY['Globals']['static'] as $key => $reg)
							if(!array($reg)) $link = preg_replace('/{'.$key.':static}/i', $reg, $link);
					if ($link != '' && $link != '#' && !in_array($link, $links_array)) $links_array[] = $link;
				}
			}
		}//printArray($links_array);
		return $links_array;
	}
	
	function path_sticker($id){
		global $DatabaseBroker, $Paths;
		if(empty($Paths)) {
			$query = 'SELECT id, path, parent FROM module';
			$selected = $DatabaseBroker->SelectAny($query);
			foreach($selected as $value)
				$Paths[$value['id']] = array(
					'path' => $value['path'],
					'parent' => $value['parent'],
				);
		}
		$p = '';
		while(1){
			if(empty($Paths[$id])) return null;
			if(empty($Paths[$id]['parent'])) return '/'.$Paths[$id]['path'].$p;
			$p = '/'.$Paths[$id]['path'].$p;
			$id = $Paths[$id]['parent'];
		}
	}

}
?>