<?php
/* =============================================================== *\
|		Module name:      Search									|
|																	|
\* =============================================================== */

if (!defined('IN_SITE')){
     die('Hacking attempt!');
}
define('SEARCH_TYPE', 0); //0--Normal Search | 1--Fulltext Search

//Module language
$Func->import_module_language("home/lang_article". PHP_EX);

//Call global functions --------------
$HomeGlobal->cat_menu();
$HomeGlobal->show_poll();
$HomeGlobal->show_logos();
$HomeGlobal->show_events();
$HomeGlobal->show_news_picture();
$HomeGlobal->show_global_hotarticles();
$HomeGlobal->show_latest_box();
//------------------------------------

$Search = new Search;

class Search
{
	var $filter		= array();
	var $page		= 1;

	function Search(){
		global $Info, $Func;

		$act	= $Func->get_vars('act', 1);

		switch ($act){
			case "advance":
				$Info->tpl_main		= "search_form";
				$this->view_search_form();
				break;
			default:
				$Info->tpl_main		= "search";
				$this->get_filter();
				$this->do_search();
		}
	}

	function get_filter(){
		global $Template, $Info, $Func;

		$this->filter['url_append']		= $Info->option['short_url_enabled'] ? '?' : '';

		//Keyword
		$this->filter['keyword']		= htmlspecialchars($Func->get_request('s_keyword', ''));
		if ( !empty($this->filter['keyword']) ){
			$this->filter['url_append']	.= '&s_keyword='. $this->filter['keyword'];
		}

		//Match
		$this->filter['match']		= htmlspecialchars($Func->get_request('s_match', ''));
		if ( !empty($this->filter['match']) ){
			$this->filter['url_append']	.= '&s_match='. $this->filter['match'];
		}

		//Search IN
		$this->filter['in']		= htmlspecialchars($Func->get_request('s_in', ''));
		if ( !empty($this->filter['in']) ){
			$this->filter['url_append']	.= '&s_in='. $this->filter['in'];
		}

		//Cat
		$this->filter['cat_id']			= intval($Func->get_request('s_cat_id', 0));
		if ( $this->filter['cat_id'] ){
			$this->filter['url_append']	.= '&s_cat_id='. $this->filter['cat_id'];
		}

		//Date from
		$this->filter['date_from']		= htmlspecialchars($Func->get_request('s_date_from', ''));
		if ( !empty($this->filter['date_from']) ){
			$this->filter['url_append']	.= '&s_date_from='. $this->filter['date_from'];
		}

		//Date to
		$this->filter['date_to']		= htmlspecialchars($Func->get_request('s_date_to', ''));
		if ( !empty($this->filter['date_to']) ){
			$this->filter['url_append']	.= '&s_date_to='. $this->filter['date_to'];
		}

		//Day
		$this->filter['day']			= intval($Func->get_request('s_day', 0));
		if ( ($this->filter['day'] > 31) || ($this->filter['day'] < 0) ){
			$this->filter['day']	= 0;
		}
		if ( $this->filter['day'] ){
			$this->filter['url_append']	.= '&s_day='. $this->filter['day'];
		}

		//Month
		$this->filter['month']			= intval($Func->get_request('s_month', 0));
		if ( ($this->filter['month'] > 12) || ($this->filter['month'] < 0) ){
			$this->filter['month']	= 0;
		}
		if ( $this->filter['month'] ){
			$this->filter['url_append']		.= '&s_month=' . $this->filter['month'];
		}

		//Year
		$this->filter['year']			= intval($Func->get_request('s_year', 0));
		if ( ($this->filter['year'] > 2030) || ($this->filter['year'] < 1970) ){
			$this->filter['year']	= 0;
		}
		if ( $this->filter['year'] ){
			$this->filter['url_append']		.= '&s_year=' . $this->filter['year'];
		}

		if ( !$this->filter['year'] ){
			$this->filter['month']	= 0;
			$this->filter['day']	= 0;
		}
		else if ( !$this->filter['month'] ){
			$this->filter['day']	= 0;
		}

		$this->page			= intval($Func->get_request("page", 1, 'GET'));

		$Template->set_vars(array(
			"SEARCH_KEYWORD"		=> $this->filter['keyword'],
			"SEARCH_MATCH"			=> $this->filter['match'],
			"SEARCH_IN"				=> $this->filter['in'],
			"SEARCH_CAT_ID"			=> $this->filter['cat_id'],
			"SEARCH_DATE_FROM"		=> $this->filter['date_from'],
			"SEARCH_DATE_TO"		=> $this->filter['date_to'],
			"SEARCH_DAY"			=> $this->filter['day'],
			"SEARCH_MONTH"			=> $this->filter['month'],
			"SEARCH_YEAR"			=> $this->filter['year'],
		));
	}

	function view_search_form(){
		global $DB, $Template, $Lang;

		$this->get_all_cats();
		$this->set_all_cats(0, 0);

		$Template->set_vars(array(
			"L_SEARCH_IN"			=> $Lang->data['search_in'],
			"L_SEARCH_IN_ALL"		=> $Lang->data['search_in_all'],
			"L_SEARCH_IN_TITLE"		=> $Lang->data['search_in_title'],
			"L_SEARCH_IN_CONTENT"	=> $Lang->data['search_in_content'],
			"L_SEARCH_MATCH_WORDS"	=> $Lang->data['search_match_words'],
			"L_SEARCH_MATCH_PHRASE"	=> $Lang->data['search_match_phrase'],
			"L_SEARCH_CAT"			=> $Lang->data['search_cat'],
			"L_SEARCH_CAT_ALL"		=> $Lang->data['search_cat_all'],
			"L_SEARCH_DATE"			=> $Lang->data['search_date'],
			"L_DATE_FROM"			=> $Lang->data['search_date_from'],
			"L_DATE_TO"				=> $Lang->data['search_date_to'],
			"L_BUTTON_SEARCH"		=> $Lang->data['button_search'],
		));
	}

	function do_search(){
		global $Lang, $Func, $Info, $DB, $Template, $HomeGlobal;

		$date_format		= $Info->option['full_date_time_format'];
		$timezone			= $Info->option['timezone'] * 3600;
		$itemperpage		= $Info->option['limit_home_news'];
		$group_by			= "";

		//Filter ----------------------------------------
		$where_sql	= ' WHERE A.enabled='. SYS_ENABLED .' AND A.posted_date<='. CURRENT_TIME;
		if ( !empty($this->filter['keyword']) ){
			if ( SEARCH_TYPE == 1 ){
				if ( $this->filter['match'] == 'words' ){
					//Search for words
					$keyword	= str_replace(' ', '*', $this->filter['keyword']);
				}
				else{
					//Search for exact phrase
					$keyword	= $this->filter['keyword'];
				}

				//Fulltext search
				if ( $this->filter['in'] == 'title' ){ //Search in Title only
					$where_sql	.= " AND (MATCH (A.title) AGAINST ('". $keyword ."'))";
				}
				else if ( $this->filter['in'] == 'content' ){ //Search in Content only
					$where_sql	= ", ". $DB->prefix ."article_page_content AS P ". $where_sql ." AND A.article_id=P.article_id AND (MATCH (P.content_detail) AGAINST ('". $keyword ."'))";
					$group_by	= " GROUP BY A.article_id";
				}
				else{ //Search in all fields
					$where_sql	= ", ". $DB->prefix ."article_page_content AS P ". $where_sql ." AND A.article_id=P.article_id AND ((MATCH (A.title, A.content_desc) AGAINST ('". $keyword ."')) OR (MATCH (P.author, P.content_detail) AGAINST ('". $keyword ."')))";
					$group_by	= " GROUP BY A.article_id";
				}
			}
			else{
				if ( $this->filter['match'] == 'words' ){
					//Search for words
					$keyword	= str_replace(' ', '%', $this->filter['keyword']);
				}
				else{
					//Search for exact phrase
					$keyword	= $this->filter['keyword'];
				}
				$keyword	= str_replace('*', '%', $keyword);

				//Normal search
				if ( $this->filter['in'] == 'title' ){ //Search in Title only
					$where_sql	.= " AND (A.title LIKE '%". $keyword ."%')";
				}
				else if ( $this->filter['in'] == 'content' ){ //Search in Content only
					$where_sql	= ", ". $DB->prefix ."article_page_content AS P ". $where_sql ." AND A.article_id=P.article_id AND (P.content_detail LIKE '%". $keyword ."%')";
					$group_by	= " GROUP BY A.article_id";
				}
				else{ //Search in all fields
					$where_sql	= ", ". $DB->prefix ."article_page_content AS P ". $where_sql ." AND A.article_id=P.article_id AND (A.title LIKE '%". $keyword ."%' OR A.content_desc LIKE '%". $keyword ."%' OR P.author LIKE '%". $keyword ."%' OR P.content_detail LIKE '%". $keyword ."%')";
					$group_by	= " GROUP BY A.article_id";
				}
			}
		}
		if ( $this->filter['cat_id'] ){
			$where_sql	.= " AND A.cat_id=". $this->filter['cat_id'];
		}
		if ( !empty($this->filter['date_from']) ){
			$date_from	= $Func->string_to_date($this->filter['date_from'], 0, 0, 1);
			$where_sql	.= " AND A.posted_date>=". $date_from;
		}
		if ( !empty($this->filter['date_to']) ){
			$date_to	= $Func->string_to_date($this->filter['date_to'], 23, 59, 59);
			$where_sql	.= " AND A.posted_date<=". $date_to;
		}

		if ( $this->filter['year'] && $this->filter['month'] && $this->filter['day'] ){
			$start_time		= mktime(0, 0, 0, $this->filter['month'], $this->filter['day'], $this->filter['year']) - $Info->option['timezone']*3600;
			$end_time		= mktime(23, 59, 59, $this->filter['month'], $this->filter['day'], $this->filter['year']) - $Info->option['timezone']*3600;
			$where_sql	.= " AND A.posted_date>=$start_time AND A.posted_date<=$end_time";
		}
		else if ( $this->filter['year'] && $this->filter['month'] ){
			$day_count	= 28;
			for ($i=31; $i>=28; $i++){
				if ( checkdate($this->filter['month'], $i, $this->filter['year']) ){
					$day_count	= $i;
					break;
				}
			}
			$start_time		= mktime(0, 0, 0, $this->filter['month'], 1, $this->filter['year']) - $Info->option['timezone']*3600;
			$end_time		= mktime(23, 59, 59, $this->filter['month'], $day_count, $this->filter['year']) - $Info->option['timezone']*3600;
			$where_sql	.= " AND A.posted_date>=$start_time AND A.posted_date<=$end_time";
		}
		else if ( $this->filter['year'] ){
			$start_time		= mktime(0, 0, 0, 1, 1, $this->filter['year']) - $Info->option['timezone']*3600;
			$end_time		= mktime(23, 59, 59, 12, 31, $this->filter['year']) - $Info->option['timezone']*3600;
			$where_sql	.= " AND A.posted_date>=$start_time AND A.posted_date<=$end_time";
		}
		//-----------------------------------------------

		//Count total pages -----------------------------
		$where_sql		.= sizeof($HomeGlobal->disabled_cats) ? " AND A.cat_id NOT IN (". implode(",", $HomeGlobal->disabled_cats) .")" : "";
		$DB->query('SELECT count(distinct A.article_id) AS total FROM '. $DB->prefix .'article AS A '. $where_sql);
		if ( $DB->num_rows() ){
			$result		= $DB->fetch_array();
			$pageshow	= $Func->pagination($result['total'], $itemperpage, $this->page, $Func->compile_url(array('mod' => MOD_SEARCH)) . $this->filter['url_append']);
		}
		else{
			$pageshow['page']	= "";
			$pageshow['start']	= 0;
		}
		$DB->free_result();
		//-----------------------------------------------

		//Get articles
		$DB->query('SELECT A.article_id, A.cat_id, A.thumb_small, A.title, A.content_desc, A.content_url, A.posted_date, A.article_type, A.archived FROM '. $DB->prefix .'article AS A '. $where_sql .' '. $group_by .' ORDER BY A.posted_date DESC LIMIT '. $pageshow['start'] .','. $itemperpage);
		$article_count	= $DB->num_rows();
		$article_data	= $DB->fetch_all_array();
		$DB->free_result();

		for ($i=0; $i<$article_count; $i++){
			$code_path	= "";
			$HomeGlobal->get_code_path($code_path, $article_data[$i]['cat_id']);
			if ( $article_data[$i]['article_type'] == SYS_ARTICLE_LINK ){
				$u_view		= $article_data[$i]['content_url'];
			}
			else{
				if ( $article_data[$i]['archived'] == SYS_ARCHIVED ){
					//Archived article
					$u_view		= $Func->compile_url(array('mod' => MOD_ARCHIVE, 'act' => 'view', 'article' => $article_data[$i]['article_id']));
				}
				else{
					$u_view		= $Func->compile_url(array('mod' => MOD_ARTICLE, 'cat' => $code_path, 'article' => $article_data[$i]['article_id']));
				}

				//Highlight
				if ( !empty($this->filter['keyword']) ){
					$u_view		.= $Info->option['short_url_enabled'] ? '?highlight='. urlencode($this->filter['keyword']) .'&match='. $this->filter['match'] : '&highlight='. $this->filter['keyword'] .'&match='. $this->filter['match'];
				}
			}

			$title	= $Func->highlight_text(html_entity_decode($article_data[$i]['title']), $this->filter['keyword'], $this->filter['match']);
			$title	= $Func->make_article_link($title, $article_data[$i]['article_type'], $u_view, 'mtitle');
			//Archived article
			if ( $article_data[$i]['archived'] == SYS_ARCHIVED ){
				$title	= '<font class="archive">['. $Lang->data['general_archive'] .']</font> '. $title;
			}

			$Template->set_block_vars("articlerow", array(
				'DATE'			=> $Func->translate_date(gmdate($date_format, $article_data[$i]['posted_date'] + $timezone)),
				'THUMB_SMALL'	=> !empty($article_data[$i]['thumb_small']) ? '<img src="'. $Func->get_article_dir($article_data[$i]['posted_date'], $article_data[$i]['article_id']) .'/'. $article_data[$i]['thumb_small'] .'" alt="" title="'. $article_data[$i]['title'] .'" hspace="5" vspace="5" border="0" align="left">' : '',
				'TITLE'			=> $title,
				'PREVIEW'		=> $Func->highlight_text(html_entity_decode($article_data[$i]['content_desc']), $this->filter['keyword'], $this->filter['match']),
//				'U_VIEW'		=> $Func->compile_url(array('mod' => MOD_ARTICLE, 'cat' => $code_path, 'article' => $article_data[$i]['article_id'])),
			));
		}

		$Template->set_vars(array(
			"PAGE_OUT"			=> $pageshow['page'],
			'L_SEARCH_RESULT'	=> $this->filter['keyword'] ? sprintf($Lang->data['search_result'], $this->filter['keyword']) : $Lang->data['search_result2'],
		));
	}

	function get_all_cats(){
		global $DB, $Func, $HomeGlobal;

		$where_sql		= sizeof($HomeGlobal->disabled_cats) ? " WHERE cat_id NOT IN (". implode(",", $HomeGlobal->disabled_cats) .")" : "";
		$DB->query("SELECT * FROM ". $DB->prefix ."article_category ". $where_sql ." ORDER BY cat_order ASC");
		$this->cat_count = $DB->num_rows();
		$this->cat_data  = $DB->fetch_all_array();
		$DB->free_result();
	}

	function set_all_cats($parent_id, $except_cid, $level=0, $url_append = "", $symbol="|-- ", $prefix="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;"){
		global $Session, $Template, $Func, $Info, $Lang;

		if ($level){
			$str_prefix	= "";
			for ($i=0; $i<$level; $i++){
				$str_prefix	.= $prefix;
			}
		}
		else{
			$str_prefix	= "";
		}

		for ($i=0; $i<$this->cat_count; $i++){
			if ( ($parent_id == $this->cat_data[$i]['cat_parent_id']) && ($except_cid != $this->cat_data[$i]['cat_id']) && empty($this->cat_data[$i]['redirect_url']) ){
				$counter	= ($this->cat_data[$i]['article_counter'] || $this->cat_data[$i]['children_counter'])  ?  'true' : 'false';
				$Template->set_block_vars("catrow", array(
					'ID'				=> $this->cat_data[$i]['cat_id'],
					'ORDER'				=> $this->cat_data[$i]['cat_order'],
					'CODE'				=> $this->cat_data[$i]['cat_code'],
					'NAME'				=> $this->cat_data[$i]['cat_name'],
					'ARTICLE_COUNTER'	=> $this->cat_data[$i]['article_counter'],
					'SUBCAT_COUNTER'	=> $this->cat_data[$i]['article_counter'],
					'PREFIX'			=> $str_prefix .$symbol,
				));
				$this->set_all_cats($this->cat_data[$i]['cat_id'], $except_cid, $level+1, $url_append, $symbol, $prefix);
			}
		}
	}
}

?>