<?php
// +------------------------------------------------------------------------+
// | PHP Melody version 1.6.6 ( www.phpsugar.com )
// +------------------------------------------------------------------------+
// | PHP Melody IS NOT FREE SOFTWARE
// | If you have downloaded this software from a website other
// | than www.phpsugar.com or if you have received
// | this software from someone who is not a representative of
// | phpSugar, you are involved in an illegal activity.
// | ---
// | In such case, please contact: support@phpsugar.com.
// +------------------------------------------------------------------------+
// | Developed by: phpSugar (www.phpsugar.com) / support@phpsugar.com
// | Copyright: (c) 2004-2011 PhpSugar.com. All rights reserved.
// +------------------------------------------------------------------------+

session_start();
require('config.php');
require_once('include/functions.php');
require_once('include/user_functions.php');
require_once('include/islogged.php');

$page = $_GET['page'];

if(empty($page) || !is_numeric($page) || $page == '')
	$page = 1;

$limit = _BROWSER_PAGE;
$from = $page * $limit - ($limit);
$total_results = 0;
$search_types = array('default', 'user');
$num_res = 0;

if((isset($_GET['btn']) && trim($_GET['btn']) != '') || (empty($_GET['btn']) && trim($_GET['keywords']) != ''))
{
	if (isset($_GET['t']) && in_array($_GET['t'], $search_types))
	{
		$search_type = $_GET['t'];
	}
	
	// cleanup search phrase
	$searchstring = trim($_GET['keywords']);
	$searchstring = urldecode($searchstring);
	$searchstring = str_replace(array("%", ","), '', $searchstring);
	$searchstring = substr($searchstring, 0, 80); // limit search phrase
	$searchstring = htmlspecialchars($searchstring, ENT_NOQUOTES);
	$searchstring = secure_sql($searchstring);
	
	// break search phrase into terms
	$terms = explode(' ', $searchstring);
	
	switch ($search_type)
	{
		default:
		case 'default':
			
			// update hits for this search pharse
			if ($page == 1)
			{
				$sql = "SELECT COUNT(*) as total 
						FROM pm_searches 
						WHERE string = '". $searchstring ."'";
				$result = @mysql_query($sql);
				$row = @mysql_fetch_assoc($result);
				@mysql_free_result($sql_string_check);
				
				if ($row['total'] > 0)
				{
					@mysql_query("UPDATE pm_searches SET hits=hits+1 WHERE string = '".$searchstring."'");
				}
				else
				{
					@mysql_query("INSERT INTO pm_searches SET string = '".$searchstring."', hits = '1'");
				}				
			}
			
			// Search DB (title and artist) using full-text index
			$sql = "SELECT SQL_CALC_FOUND_ROWS uniq_id, category, artist, video_title, site_views, featured, MATCH(artist, video_title) AGAINST ('$searchstring') AS score 
					FROM pm_videos 
			        WHERE MATCH(artist, video_title) AGAINST ('$searchstring')
					ORDER BY score DESC 
					LIMIT ".$from.", ".$limit;

			$result = @mysql_query($sql);
			
			// get total found rows
			$sql = "SELECT FOUND_ROWS()";
			$result2 = mysql_query($sql);
			$num_res = mysql_fetch_array($result2);
			$num_res = (int) $num_res[0];
			$total_results = $num_res;
			
			if ($num_res == 0 && (strlen($searchstring) >= 2))
			{
				// backup mode
				$where = '';
				$and = '';
				$terms = explode(' ', $searchstring);
				$limit_terms = 10; // limit query terms
				$searched_terms = 0;
				
				foreach ($terms as $k => $term)
				{
					$term = trim($term, "\"'\n\r.,-_()[]{} ");
					
					if (strlen($term) >= 2)
					{
						$where .= "{$and} ((video_title LIKE '%".$term."%') OR (artist LIKE '%".$term."%') OR (description LIKE '%".$term."%')) ";
						$and = ' AND ';
						$searched_terms++;
					}
					
					if ($searched_terms >= $limit_terms)
					{
						break;
					}
				}
				
				if (count($terms) > 1)
				{
					$where .= " OR ((video_title LIKE '%".$searchstring."%') OR (artist LIKE '%".$searchstring."%') OR (description LIKE '%".$searchstring."%'))";
				}
				
				$sql = "SELECT SQL_CALC_FOUND_ROWS uniq_id, category, artist, video_title, site_views, featured 
						FROM pm_videos
						WHERE ". $where ." 
						   OR uniq_id IN ( 
						   		SELECT uniq_id 
								FROM pm_tags 
								WHERE tag LIKE '". $searchstring ."')  
						LIMIT ".$from.", ".$limit;
				$result = @mysql_query($sql);
				
				// get total found rows
				$sql = "SELECT FOUND_ROWS()";
				$result2 = mysql_query($sql);
				$num_res = mysql_fetch_array($result2);
				$num_res = (int) $num_res[0];
				$total_results = $num_res;
			}
			
		break;
		
		case 'user':
			
			if (username_to_id($searchstring) > 0)
			{
				$sql = "SELECT COUNT(*) as total  
						 FROM pm_videos
						WHERE submitted = '". $searchstring ."' 
						ORDER BY id DESC";
				$result = mysql_query($sql);
				$row = mysql_fetch_assoc($result);
				$total_results = $row['total'];
				mysql_free_result($result);
				$result = false;
				
				if ($total_results > 0)
				{
					$sql = "SELECT uniq_id, category, artist, video_title, site_views, featured  
							FROM pm_videos
							WHERE submitted = '". $searchstring ."' 
							ORDER BY id DESC  
							LIMIT ".$from.", ".$limit;
					$result = mysql_query($sql);
				}
			}
			else 
			{
				$result = false;
			}
			
		break;
		
	} // end switch
	
	$j = 0; 
	$item = '';

	if ($total_results > 0)
	{
		while ($row = mysql_fetch_array($result)) 
		{ 
			// ** Mark as new ** //
			$sql_date = date('Y-m-d', $row['added']);
			$date_diff = round( abs(strtotime(date('Y-m-d'))-strtotime($sql_date)) / 86400, 0 );
		
		$item .= '<li class="item column">';
		$item .= '<a class="row-img" href="'. makevideolink($row['uniq_id'], $row['artist'], $row['video_title']) .'">';
		$item .= '<img src="'.show_thumb($row['uniq_id']).'"  alt="'. fewchars($row['video_title'], 20) .'" /></a>';
		$item .= '<div class="top-list-info-box"> <span>'. fewchars($row['artist'], 20) .'</span><span><a href="'. makevideolink($row['uniq_id'], $row['artist'], $row['video_title']) .'">'. fewchars($row['video_title'], 20) .'.</a></span>';
		$item .= '<span class="view-count">'. pm_number_format($row['site_views']) .'  views </span></div><div class="tag"></div>';
		$item .= '</li>';
		
		}
		mysql_free_result($result);
	}
	else
	{
		$err = "<center><br><b>".$lang['search_results_msg1']."</b></center>";
	}
}
else
{
	$err = '<center><br><b>'.$lang['search_results_msg2'].'</b></center>';
}

// generate pagination
$uri = $_SERVER['REQUEST_URI'];
$uri = explode('?', $uri);
if (strlen($uri[1]) == 0)
{
	$uri[1] ='keywords='. $_GET['keywords'] .'&btn=Search';
}


$filename = ('' != $_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF']) : 'search.php';

$pagination = generate_smart_pagination($page, $total_results, $limit, 1, $filename, $uri[1], 0);	

// define meta tags & common variables
$meta_title = _SITENAME.' - '.$lang['search_results'];
$meta_description = '';
// end

$smarty->assign('error_msg', $err);
$smarty->assign('searchstring', htmlspecialchars($_GET['keywords']));
$smarty->assign('results', $item);
$smarty->assign('pagination', $pagination);
// --- DEFAULT SYSTEM FILES - DO NOT REMOVE --- //
$smarty->assign('meta_title', $meta_title);
$smarty->assign('meta_description', $meta_description);
$smarty->assign('template_dir', $template_f);
$smarty->display('search.tpl');
?>