<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/
setlocale(LC_CTYPE , "ru_RU.CP1251");

$mod_template="themes.tpl";

if (!$_GET['search']) $_GET['search']=$_GET['var3'];

//разделяем фразу на отдельные слова, выделяем у них корень и составляем поисковый запрос
$text_array=explode(" ", preg_replace('/[\s]+/',' ',trim($_GET['search'])));
$stemmer = new Stem_Ru();

//формируем условия для всех слов
foreach ($text_array as $val)
{
	$query_text.="+".$stemmer->stem_word($val)."* ";
}

//узнаем количество страниц
$count=Db::i()->selectCell("SELECT count(DISTINCT(ft.theme_id)) FROM ?_forum_posts fp JOIN ?_forum_themes ft ON fp.theme_id=ft.theme_id WHERE (MATCH(fp.user_name, fp.msg) AGAINST(? IN BOOLEAN MODE) OR MATCH(ft.subject) AGAINST(? IN BOOLEAN MODE)) { AND ft.forum_id=?}", $query_text, $query_text, (($forum_info['forum_id'])?$forum_info['forum_id']:DBSIMPLE_SKIP));
if ($count)
{
	if ($page < 1) $page = 1;
	if ($page>$total=ceil($count/LabConfig::$mcfg['forum_themes_at_page'])) $page=$total;
	
	//определяем с какой страницы запрашивать
	$start=($page-1)*LabConfig::$mcfg['forum_themes_at_page'];
	
	if (!$forum_info['forum_id']) $additional_fields=" ff.forum_id, ff.forum_name,";
	
	//все результаты поиска
	$result=Db::i()->select("SELECT ft.theme_id, $additional_fields IF(author_id, ua.login, author) as author, subject, ft.total_posts, IF(u.user_id, u.login, last_user) as last_user, ft.last_post
							FROM ?_forum_posts fp
							JOIN ?_forum_themes ft ON fp.theme_id=ft.theme_id
							JOIN ?_forum_forums ff ON ff.forum_id=ft.forum_id
							JOIN ?_users u ON ft.last_user_id=u.user_id
							JOIN ?_users ua ON ft.author_id=ua.user_id
							WHERE (MATCH(fp.user_name, fp.msg) AGAINST(? IN BOOLEAN MODE)
							OR MATCH(ft.subject) AGAINST(? IN BOOLEAN MODE))
							$forum_where
							GROUP BY ft.theme_id
							ORDER BY ft.last_post DESC
							LIMIT ?d, ?d", $query_text, $query_text, $start, LabConfig::$mcfg['forum_themes_at_page']);
	
	foreach($result as $tmp)
	{
		$tmp['subject_html']=getbb($tmp['subject'], 'nolinks');
		$themes[]=$tmp;
	}
	
	Tpl::i()->assign('themes', $themes);
	Tpl::i()->assign("current_page", $page);
	Tpl::i()->assign("total", $total);
}
else
{
	Tpl::i()->assign("no_result",1);
}

Tpl::i()->assign("forum_id", intval($forum_info['forum_id']));
