<?php
// +------------------------------------------------------------------------+
// | PHP Melody version 1.6.7 ( 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');
require_once('include/article_functions.php');

if ( ! _MOD_ARTICLE)
{
	header("Location: ". _URL ."/index.". _FEXT);
	exit();
}

$page 	 = (int) $_GET['page'];
$cat_tag = trim($_GET['c']);		//	category tag, not ID
$tag 	 = urldecode($_GET['tag']);	//	safe tag
$keyword = urldecode($_GET['keywords']);

$cid	 	= 0;
$articles 	= array();
$categories = array();
$total_items = 0;
$show_popular = ($_GET['show'] == 'popular') ? 1 : 0;

if ($page == 0)
{
	$page = 1;
}

$limit = $config['browse_articles'];
$from = $page * $limit - ($limit);

//	get categories
$categories = art_get_categories();

//	get articles
if($cat_tag != '')
{
	$cid = 0;
	if (is_array($categories))
	foreach ($categories as $id => $cat_arr)
	{
		if ($cat_arr['tag'] == $cat_tag)
		{
			$cid = $cat_arr['id'];
			break;
		}
	}
	
	if ($cid > 0)
	{
		$articles = art_load_articles($from, $limit, $cid);
		
		$total_items = $categories[$cid]['total_articles'];
	}
	else
	{ 
		$articles = art_load_articles($from, $limit);
		$total_items = $config['total_articles'];
	}
}
else if ($tag != '' || $keyword != '')
{
	$ids = array();
	
	if ($keyword != '')
	{
		$keyword = str_replace( array("%", ">", "<"), '', $keyword);
		$keyword = trim($keyword);
		$keyword = secure_sql($keyword);
		
		$where = '';
		$and = '';
		$terms = explode(' ', $keyword);
		$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} ((title LIKE '%".$term."%') OR (content LIKE '%".$term."%')) ";
				$and = ' AND ';
				$searched_terms++;
			}
			
			if ($searched_terms >= $limit_terms)
			{
				break;
			}
		}
		
		if (count($terms) > 1)
		{
			$where .= " OR ((title LIKE '%".$keyword."%') OR (content LIKE '%".$keyword."%'))";
		}
		
		$sql = "SELECT id, title, content, category, status, date, author, allow_comments, comment_count, views 
				FROM art_articles 
				WHERE ". $where;
	}
	else
	{
		$tag = safe_tag($tag);
		$tag = secure_sql($tag);
	
		$sql = "SELECT id, article_id, tag, safe_tag 
				FROM art_tags 
				WHERE safe_tag LIKE '". $tag ."'";	
	}
	
	$result = @mysql_query($sql);
	
	if ( ! $result)
	{
		$articles = array('type' => 'error', 'msg' => '<center><br><b>'.$lang['search_results_msg1'].'</b></center>');
	}
	else
	{
		$total_results = @mysql_num_rows($result);
		if ($total_results)
		{
			while ($row = mysql_fetch_assoc($result))
			{
				$ids[] = ($tag != '') ? $row['article_id'] : $row['id'];
			}

			mysql_free_result($result);
		
			$articles =  art_load_articles($from, $limit, '', 0, $ids);
			
			$ids = implode(', ', $ids);
			
			//	Count total items;
			$sql = "SELECT COUNT(*) as total 
							FROM art_articles 
							WHERE status = '1' 
							  AND id IN (". $ids .")";
			$result = @mysql_query($sql);
			$row = @mysql_fetch_assoc($result);
			@mysql_free_result($result);
			
			$total_items = ($row['total']) ? $row['total'] : 0;
			
		}
		else
		{	
			$articles = array('type' => 'error', 'msg' => '<center><br><b>'.$lang['search_results_msg1'].'</b></center>');
		}
	}
}
else
{
	if ($show_popular)
	{
		$ids = array();
		$sql = "SELECT id FROM art_articles 
				ORDER BY views DESC 
				LIMIT 0, 30";
		$result = @mysql_query($sql);
	
		if ( ! $result)
		{
			$articles = array('type' => 'error', 'msg' => '<center><br><b>'.$lang['search_results_msg1'].'</b></center>');
		}
		else
		{
			$total_items = mysql_num_rows($result);
			
			while ($row = mysql_fetch_assoc($result))
			{
				$ids[] = $row['id'];
			}

			mysql_free_result($result);
		
			$articles =  art_load_articles($from, $limit, '', 0, $ids, 'views');
		}
	}
	else
	{
		// default
		$articles = art_load_articles($from, $limit);
		$total_items = count_entries('art_articles', 'status', '1');	
	}
}

if ('' != $articles['type'])
{
	$articles = $articles['msg'];
}
else
{
	foreach ($articles as $id => $article)
	{
		//	Handle excerpt
		$pieces = array();
		$pieces = explode('<hr>', $article['content']);
		$pieces[0] = rtrim($pieces[0], "\n\r\t ");

		if (strtolower(substr($pieces[0], strlen($pieces[0]) - 5)) == '<div>')
		{
			$pieces[0] = substr($pieces[0], 0, -5);
		}
		
		$articles[$id]['content'] = $pieces[0];
		
		$articles[$id]['date'] = date('M j, Y', $article['date']);
		
		unset($pieces);

		//	Handle article categories - make links
		$pieces = explode(',', $article['category']);
		foreach ($pieces as $k => $cat_id)
		{
			$name = $categories[$cat_id]['name'];
			
			$articles[$id]['pretty_cats'][$name] = $categories[$cat_id]['link'];
		}
	}
}

// generate smart pagination
$uri = '';
if ( ! strpos($_SERVER['REQUEST_URI'], '?'))
{
	$uri = ('' != $_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : 'article.php';
	$uri .= '?';
	
	if($cat_tag != '')	$uri .= '&c='	 . $cat_tag;
	if($page)			$uri .= '&page=' . $page;
	if($tag != '')		$uri .= '&tag='	 . $tag;
}
else
{
	$uri = $_SERVER['REQUEST_URI'];
}

$uri = explode('?', $uri); 
$filename = ('' != $_SERVER['PHP_SELF']) ? basename($_SERVER['PHP_SELF']) : 'article.php';

if(!is_numeric($_GET['page']))
{
	$uri[1] = str_replace("page=".$_GET['page'], "page=1", $uri[1]);
}

if (_SEOMOD && $keyword == '')
{
	$uri[1] = '';
	$filename = $_SERVER['REQUEST_URI'];

	if($filename == '')
	{
		$filename = 'index-'. $page .'.'. _FEXT;
	}
	else
	{
		if(strpos($filename, "/", 0) !== FALSE)
		{
			$temp = explode("/", $filename);
			$filename = $temp[count($temp)-1];
		}
		
		if ($filename == '' || strpos($_SERVER['REQUEST_URI'], '/tag/') !== false)
		{
			$filename = $_SERVER['REQUEST_URI'];
		}
	}
}

if ($keyword == '')
{
	$pagination = art_pagination($page, $total_items, $limit, 1, $filename, $uri[1], _SEOMOD);
}
else	//	ignore SEOMOD when searching
{
	$pagination = art_pagination($page, $total_items, $limit, 1, $filename, $uri[1], 0);
}

//	Some HTML 
$total_pages = ceil($total_items / $limit);
$page_count_info = sprintf($lang['page'], $page)." ".$total_pages;
if($total_pages == 0)
{
	$page_count_info = $lang['browse_page11'];
}
$video_categories = list_categories(0, '');
$article_categories = art_html_list_categories($cid, $categories, array('max_levels' => 1));

if($config['show_tags'] == 1)
{
	$tag_cloud = art_tag_cloud(0, $config['tag_cloud_limit'], $config['shuffle_tags']);
	$smarty->assign('tags', $tag_cloud);
	$smarty->assign('show_tags', 1);
}

//	meta title
$meta_title = '';

if ($cid > 0)
{
	$meta_title .= $categories[$cid]['name'];
	$article_h2 = $categories[$cid]['name'];
}
else if ($tag != '' || $keyword != '')
{
	$meta_title = _SITENAME;
	$meta_title .= ' - ';
	$meta_title .= ($tag != '') ? urldecode($_GET['tag']) : $lang['search_results'];
	$meta_title = specialchars($meta_title, 1); 
	
	$article_h2 = ($tag != '') ? $lang['search_results'] . ': ' . urldecode($_GET['tag']) : $lang['search_results'];
	$article_h2 = specialchars($article_h2, 1); 
}
else
{
	$meta_title .= _SITENAME;
	if ($show_popular)
	{
		$article_h2 = $lang['articles_mostread'];
	}
	else
	{
		$article_h2 = $lang['articles_latest'];	
	}
}


//	browsing style
if ($cid > 0)
{
	$browsing_style = 'category';
} 
else if ($tag != '' || $keyword != '')
{
	$browsing_style = 'search';
}
else 
{
	$browsing_style = 'default';
}

//	assign values to template
$smarty->assign('browsing_style', $browsing_style); 
$smarty->assign('total_results', $total_results); 
$smarty->assign('articles', $articles);
$smarty->assign('categories', $categories);	 
$smarty->assign('article_categories', $article_categories); 
$smarty->assign('list_categories', $video_categories); 
$smarty->assign('pagination', $pagination);
$smarty->assign('page_count_info', $page_count_info); 
$smarty->assign('cat_id', $cid); 
// --- DEFAULT SYSTEM FILES - DO NOT REMOVE --- //
$smarty->assign('meta_title', $meta_title);
$smarty->assign('article_h2', $article_h2);
$smarty->assign('meta_description', '');
$smarty->assign('template_dir', $config['template_f']); 
$smarty->display('article_browse.tpl');
?>