<?php
/** 
* @package	uForum 
* @file		search.php
* @version	$Id$ 
* @copyright	2007-2010 (c) PioDer <pioder@wp.pl>
* @link    		http://www.pioder.pl/
* @license	see LICENSE.txt
**/
define('IN_uF', true);
//include files
require('./config.php');
require('./includes/constants.php');
require('./includes/db.php');
require('./includes/errors.php');
//connect to database
DataBase::db_connect();
require('./includes/sessions.php');
require('./includes/classes/class_user.php');
require('./common.php');
require('./includes/misc_functions.php');
require('./includes/classes/class_forum.php');
require('./includes/classes/class_topic.php');
require('./includes/classes/secure.php');
$default_lang = DefaultLang();
require('./lngs/'.$default_lang.'/main.php');
$start = TimeGeneration();
$default_skin = ViewSkinName();
SessDelInvalid();	
SessRegister();
SessDeleteOld();	

if (!isset($_GET['content']))
{
	header('Location: search.php?content=posts');
}

//
//generate output pages
//
if ($_SESSION['uid']>0)
{
	$limiter = $userdata['limit_ftid'];
}
else
{
	$limiter = $forum_config['limit_ftid'];
}
if ($_GET['content'] == 'userposts' || $_GET['content'] == 'lastposts')
{
	if (isset($_GET['page'])&&($_GET['page']!=1))
	{
		if (!is_numeric($_GET['page']))
		{
			die('Hacking attempt');
		}
		$value = ($_GET['page']-1)*$limiter;
		$limit = 'LIMIT '.$value . ', '.$limiter;
		$page = $_GET['page'];
	}
	else
	{
		$limit = 'LIMIT 0, '.$limiter;
		$page=1;
	}
}
else
{
	if (isset($_POST['page'])&&($_POST['page']!=1))
	{
		if (!is_numeric($_POST['page']))
		{
			die('Hacking attempt');
		}
		$value = ($_POST['page']-1)*$limiter;
		$limit = 'LIMIT '.$value . ', '.$limiter;
		$page = $_POST['page'];
	}
	else
	{
		$limit = 'LIMIT 0, '.$limiter;
		$page=1;
	}	
}


//
//end generating pages
//

if ((isset($_POST['keywords'])) || ($_GET['content']=='lastposts') || ($_GET['content']=='userposts'))
{
	$errors = true;
	switch($_GET['content'])
	{
		case 'lastposts':
		{
			if ($_SESSION['uid']>0)
			{
				$time = $_SERVER['REQUEST_TIME']-129600;
				$sql = "SELECT  COUNT(`t_id`) as `cnt` FROM ".TOPICS_TABLE." WHERE lastpost_time>$time";
				$count = DataBase::fetch(DataBase::sql_query($sql,GENERAL,'Could not obtain count amout of topics'));
				$count = $count['cnt'];
				$count = ceil($count / $limiter);
				if ($count==0)
				{
					$count +=1;
				}
				if(isset($_GET['page']) && ($_GET['page']>$count))
				{
					message_forum($lng['invalidpage'],'index.php');
				}
				$sql = "SELECT ".TOPICS_TABLE.".*, ".USERS_TABLE.".*, ".TOPICS_TABLE.".posts AS posts
				 FROM ".TOPICS_TABLE."
				  LEFT JOIN ".USERS_TABLE." ON ".TOPICS_TABLE.".author = ".USERS_TABLE.".u_id
				   WHERE lastpost_time>$time
				    ORDER BY  `sticky` DESC, `lastpost_time` DESC $limit";
				$errors = false;
				$window_title = $lng['showlastposts'];
				$navigator_title = '<a href="'.$_SERVER['REQUEST_URI'].'" class="navigator">'.$lng['showlastposts'];
				break;
			}
			else
			{
				message_forum($lng['youarenotlogd'],'login.php?mode=login');
				break;
			}
		}
		case 'userposts':
		{
			if (isset($_GET['u']))
			{
				$count = DataBase::fetch(DataBase::sql_query("SELECT COUNT(`t_id`) as `t_id` 
				FROM ".TOPICS_TABLE." WHERE `author`='".intval($_GET['u'])."'",GENERAL,'Could not obtain count amout of topics'));
				$count = $count['t_id'];
				$count = ceil($count / $limiter);
				if ($count==0)
				{
					$count +=1;
				}
				if(isset($_GET['page']) && ($_GET['page']>$count))
				{
					message_forum($lng['invalidpage'],'index.php');
				}
				$sql = "SELECT ".TOPICS_TABLE.".*, ".USERS_TABLE.".* FROM ".TOPICS_TABLE." LEFT JOIN ".USERS_TABLE." ON ".TOPICS_TABLE.".author = ".USERS_TABLE.".u_id WHERE `u_id`='".intval($_GET['u'])."' ORDER BY  `sticky` DESC, `lastpost_time` DESC $limit;";
				$errors = false;
				$window_title = $lng['view_user_topics'];
				$navigator_title = '<a href="'.$_SERVER['REQUEST_URI'].'" class="navigator">'.$lng['view_user_topics'];
				break;
			}
			else
			{
				message_forum($lng['no_user'],'index.php');
				break;
			}
		}
		case 'posts':
		{
			if(strlen(trim($_POST['keywords']))>=3)
			{
				$keyword = explode(' ', strip_tags(addslashes($_POST['keywords'])));
				$like_where = ' `text` LIKE \'%'.$keyword[0].'%\'';
				for($i=1; $i<count($keyword);$i++)
				{
					$like_where .=' OR `text` LIKE \'%'.$keyword[$i].'%\'';
				}
				$sql = "SELECT  ".POSTS_TABLE.".t_id, ".POSTS_TABLE.".text
				 FROM ".TOPICS_TABLE."
				  LEFT JOIN ".POSTS_TABLE." ON ".POSTS_TABLE.".t_id = ".TOPICS_TABLE.".t_id
				   WHERE $like_where GROUP BY `t_id`";
				$count = DataBase::sql_query($sql,GENERAL,'Could not obtain count amout of topics');
				$count = DataBase::num_rows($count);//$count['count'];
				$count = ceil($count / $limiter);
				if ($count==0)
				{
					$count +=1;
				}
				if(isset($_GET['page']) && ($_GET['page']>$count))
				{
					message_forum($lng['invalidpage'],'index.php');
				}
				$sql = "SELECT ".TOPICS_TABLE.".*, ".USERS_TABLE.".*, ".POSTS_TABLE.".*, ".TOPICS_TABLE.".posts AS posts
				 FROM ".TOPICS_TABLE."
				  LEFT JOIN ".USERS_TABLE." ON ".TOPICS_TABLE.".author = ".USERS_TABLE.".u_id
				   LEFT JOIN ".POSTS_TABLE." ON ".POSTS_TABLE.".t_id = ".TOPICS_TABLE.".t_id
				    WHERE $like_where
				     ORDER BY `sticky` DESC, `lastpost_time` DESC $limit;";
			     
				$window_title = $lng['search_results'];
				$navigator_title = '<a href="'.$_SERVER['REQUEST_URI'].'" class="navigator">'.$lng['search_results'];
				$errors = false;
				
			}
			else
			{
				message_forum($lng['too_short_keywords'],'search.php?content=posts');
			}
			break;
		}
	}
	if (!$errors)
	{
		//add skin variables
		$skin = array(
		'lposts'=>$lng['posts'],
		'llastposts'=>$lng['lastpost'],
		'lposts'=>$lng['posts'],
		'lauthor'=>$lng['author'],
		'llastpost'=>$lng['lastpost'],
		'ltopicname'=>$lng['ltopicname'],
		'lang'=> $default_lang
		);
		$skin = array_push_assoc($skin,GenerateHeader($window_title,$navigator_title));
		require('./skins/'.$default_skin.'/overall_header.tpl');
		require('./skins/'.$default_skin.'/forum_body.tpl'); 
		$query = DataBase::sql_query($sql,GENERAL, 'Could not obtain topics information');
		$value = DataBase::num_rows($query);
		if ($value>0)
		{
			$isset_topics = array();
			while($record = DataBase::fetch($query))
			{
				if (!in_array($record['t_id'], $isset_topics))
				{
					$last_post = explode(':', $record['lastpost']);
					$skin = array(
					't_id'=>$record['t_id'],
					'fname'=>($record['sticky']=='1') ? '<b>'.$lng['sticky'].'</b>'.$record['name'] : $record['name'],
					'author'=>Topic::TopicAuthor($record['author']),
					'new_post'=>Topic::LastPostImg(),
					'tposts'=>$record['posts'],
					'lastpost'=>Topic::LastPostInTopic($record['t_id'])
					);
					require('./skins/'.$default_skin.'/forum_forum_add.tpl');
					array_push($isset_topics, $record['t_id']);
				}	
			}
		}
		else 
		{
			echo '<tr><td width="'.TABLES_WIDTH.'" colspan="10" height="19" class="fitem"><p class="fstandard" align="center">'.$lng['nopost'].'!</p></td></tr>';
		}
		$skin = array( 
		'option_pages' => ListPages($page, $count),
		'lwith' => $lng['with'],
		'lpage' => $lng['page'],
		'lpages' => $count,
		);
		
		if ($_GET['content']=='posts')
		{
			$skin['keywords'] = $_POST['keywords'];
		}
		
		require('./skins/'.$default_skin.'/search_end_body.tpl');
		
		 
	} 	
}
else
{
	$skin = array(
	'mainpage'=>$lng['lsearch'],
	'lsubmit'=>$lng['search'],
	'lreset'=>$lng['reset'],
	'insert_keywords'=>$lng['insert_keywords']
	);
	$window_title = $lng['lsearch'];
	$navigator_title =  '<a href="'.$_SERVER['REQUEST_URI'].'" class="navigator">'.$lng['lsearch'];
	$skin = array_push_assoc($skin,GenerateHeader($window_title,$navigator_title));
	require('./skins/'.$default_skin.'/overall_header.tpl');
	require('./skins/'.$default_skin.'/search_body.tpl');
}
if ($_SESSION['uid']>0)
{
	if(RANK=='2')
	{
		$skin['pa_link']='<a href="admin/index.php" class="fsmall"><b>'.$lng['pa_link'].'</b></a>';
	}
	else
	{
		$skin['pa_link']='';
	}
}
else
{
	$skin['pa_link']='';
}
$stop = TimeGeneration();
$skin['queries'] =  ShowQueries($start, $stop);
require('./skins/'.$default_skin.'/overall_footer.tpl');
?>