All pastes #453884 Raw Edit

nuvolona

public text v1 · immutable
·published 2007-04-23 08:48 UTC
rendered paste body
<?php
//-- mod : calendar ------------------------------------------------------------
/***************************************************************************
 *                                search.php
 *                            -------------------
 *   begin                : Saturday, Feb 13, 2001
 *   copyright            : (C) 2001 The phpBB Group
 *   email                : support@phpbb.com
 *
 *   $Id: search.php,v 1.72.2.16 2005/03/15 18:34:34 acydburn Exp $
 *
 *
 ***************************************************************************/

/***************************************************************************
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 ***************************************************************************/

define('IN_PHPBB', true);
$phpbb_root_path = './';
include($phpbb_root_path . 'extension.inc');
include($phpbb_root_path . 'common.'.$phpEx);
include($phpbb_root_path . 'includes/bbcode.'.$phpEx);
include($phpbb_root_path . 'includes/functions_search.'.$phpEx);
// RegMod-Begin
include($phpbb_root_path . 'includes/functions_regmod.'.$phpEx);
// RegMod-End
//
// Start session management
//
$userdata = session_pagestart($user_ip, PAGE_SEARCH);
init_userprefs($userdata);
//
// End session management
//

//<!-- BEGIN Unread Post Information to Database Mod --> 

if($userdata['upi2db_access']) 
{ 
    $params = array('always_read' => 'always_read', 't' => 't', 'f' => 'f', 'p' => 'p', 's' => 's', 'mar_topic_id' => 'mar_topic_id', 'mar' => 'mar', 'do' => 'do', 'search_mode' => 'search_id', 'tt' => 'tt'); 
    while( list($var, $param) = @each($params) ) 
    { 
       if ( !empty($HTTP_POST_VARS[$param]) || !empty($HTTP_GET_VARS[$param]) ) 
       { 
          $$var = ( !empty($HTTP_POST_VARS[$param]) ) ? $HTTP_POST_VARS[$param] : $HTTP_GET_VARS[$param]; 
       } 
       else 
       { 
          $$var = ''; 
       } 
    } 
    
	$unread = unread(); 

    if($always_read || $do || ($mar && !empty($mar_topic_id))) 
    { 
        if($always_read) 
        { 
            $mark_read_text = always_read($t, $always_read, $unread); 
        } 
        if($do) 
        { 
            $mark_read_text = set_unread($t, $f, $p, $unread, $do, $tt); 
        } 
       if($mar && !empty($mar_topic_id)) 
        { 
            search_mark_as_read($mar_topic_id); 
            $mark_read_text =  $lang['upi2db_submit_topic_mark_read']; 
       } 
       $template->assign_vars(array( 
          'META' => '<meta http-equiv="refresh" content="3;url=' . append_sid("search.$phpEx?search_id=$search_mode&s=$s") . '">') 
       ); 
    
       $message = $mark_read_text . '<br /><br />' . sprintf($lang['Click_return_search'], '<a href="' . append_sid("search.$phpEx?search_id=$search_mode&s=$s") . '">', '</a> '); 
       message_die(GENERAL_MESSAGE, $message); 
    } 
    $count_new_posts = count($unread['new_posts']); 
    $count_edit_posts = count($unread['edit_posts']); 
    $count_always_read = count($unread['always_read']['topics']); 
    $count_mark_unread = count($unread['mark_posts']); 
} 
//<!-- END Unread Post Information to Database Mod --> 

// CrackerTracker v5.x
if ( isset($HTTP_POST_VARS['mode']) || isset($HTTP_GET_VARS['mode']) || !empty($HTTP_GET_VARS['search_id']) || isset($HTTP_POST_VARS['search_id']) || isset($HTTP_GET_VARS['search_keywords']) || isset($HTTP_POST_VARS['show_results']) )
{
	include_once($phpbb_root_path . 'ctracker/classes/class_ct_userfunctions.' . $phpEx);
	$search_system = new ct_userfunctions();
	$search_system->search_handler();
	unset($search_system);
}

//
// Define initial vars
//
if ( isset($HTTP_POST_VARS['mode']) || isset($HTTP_GET_VARS['mode']) )
{
	$mode = ( isset($HTTP_POST_VARS['mode']) ) ? $HTTP_POST_VARS['mode'] : $HTTP_GET_VARS['mode'];
}
else
{
	$mode = '';
}
    //
    // CrackerTracker Flood Protection Engine (Search)
    //
      $ctracker_validation = $HTTP_POST_VARS['ctracker_validation'];

      if (($ctracker_validation != $ctrack_forumid) and ($mode == 'results'))
      {
        // Oha its a Worm. Let's kill it. May the force be with CrackerTracker.
        require($phpbb_root_path . "ctracker/realtime_flood_protect." . $phpEx);
      }
    //
    // End CrackerTracker Flood Protection Engine
    //
if ( isset($HTTP_POST_VARS['search_keywords']) || isset($HTTP_GET_VARS['search_keywords']) )
{
	$search_keywords = ( isset($HTTP_POST_VARS['search_keywords']) ) ? $HTTP_POST_VARS['search_keywords'] : $HTTP_GET_VARS['search_keywords'];
}
else
{
	$search_keywords = '';
}

if ( isset($HTTP_POST_VARS['search_author']) || isset($HTTP_GET_VARS['search_author']))
{
	$search_author = ( isset($HTTP_POST_VARS['search_author']) ) ? $HTTP_POST_VARS['search_author'] : $HTTP_GET_VARS['search_author'];
	$search_author = phpbb_clean_username($search_author);
}
else
{
	$search_author = '';
}

$search_id = ( isset($HTTP_GET_VARS['search_id']) ) ? $HTTP_GET_VARS['search_id'] : '';

if (isset($HTTP_POST_VARS['show_results']) || isset($HTTP_GET_VARS['show_results']))
{
	$show_results = (isset($HTTP_POST_VARS['show_results'])) ? $HTTP_POST_VARS['show_results'] : $HTTP_GET_VARS['show_results'];
}
else
{
	$show_results = 'posts';
}
$show_results = ($show_results == 'topics') ? 'topics' : 'posts';

if (isset($HTTP_POST_VARS['is_ajax']) || isset($HTTP_GET_VARS['is_ajax']))
{
	$is_ajax = (isset($HTTP_POST_VARS['is_ajax'])) ? intval($HTTP_POST_VARS['is_ajax']) : intval($HTTP_GET_VARS['is_ajax']);
}
else
{
	$is_ajax = 0;
}
// start mod save posts as drafts ... if user clicked to see his drafts and posts or topics, set search_id to egosearch and set show_results correctly
if( $search_id == 'egosearch_by_topic' || $search_id == 'egosearch_by_post' )
{
	$show_results = ( $search_id == 'egosearch_by_topic' ) ? 'topics' : 'posts';
	$search_id = 'egosearch';
}
// end mod save posts as drafts

if (isset($HTTP_POST_VARS['search_terms']) || isset($HTTP_GET_VARS['search_terms']))
{
	$search_terms = (isset($HTTP_POST_VARS['search_terms'])) ? $HTTP_POST_VARS['search_terms'] : $HTTP_GET_VARS['search_terms'];
}
else
{
	$search_terms = 'any';
}
$search_terms = ($search_terms == 'all') ? 1 : 0;

if (isset($HTTP_POST_VARS['search_fields']) || isset($HTTP_GET_VARS['search_fields']))
{
	$search_fields = (isset($HTTP_POST_VARS['search_fields'])) ? $HTTP_POST_VARS['search_fields'] : $HTTP_GET_VARS['search_fields'];
}
else
{
	$search_fields = 'all';
}
$search_fields = ($search_fields == 'all') ? 1 : 0;

if (isset($HTTP_POST_VARS['return_chars']) || isset($HTTP_GET_VARS['return_chars']))
{
	$return_chars = (isset($HTTP_POST_VARS['return_chars'])) ? intval($HTTP_POST_VARS['return_chars']) : intval($HTTP_GET_VARS['return_chars']);
}
else
{
	$return_chars = 200;
}

if (isset($HTTP_POST_VARS['search_cat']) || isset($HTTP_GET_VARS['search_cat']))
{
	$search_cat = (isset($HTTP_POST_VARS['search_cat'])) ? intval($HTTP_POST_VARS['search_cat']) : intval($HTTP_GET_VARS['search_cat']);
}
else
{
	$search_cat = -1;
}

if (isset($HTTP_POST_VARS['search_forum']) || isset($HTTP_GET_VARS['search_forum']))
{
	$search_forum = (isset($HTTP_POST_VARS['search_forum'])) ? intval($HTTP_POST_VARS['search_forum']) : intval($HTTP_GET_VARS['search_forum']);
}
else
{
	$search_forum = -1;
}

if (isset($HTTP_POST_VARS['sort_by']) || isset($HTTP_GET_VARS['sort_by']))
{
	$sort_by = (isset($HTTP_POST_VARS['sort_by'])) ? intval($HTTP_POST_VARS['sort_by']) : intval($HTTP_GET_VARS['sort_by']);
}
else
{
	$sort_by = 0;
}

if (isset($HTTP_POST_VARS['sort_dir']) || isset($HTTP_GET_VARS['sort_dir']))
{
	$sort_dir = (isset($HTTP_POST_VARS['sort_dir'])) ? $HTTP_POST_VARS['sort_dir'] : $HTTP_GET_VARS['sort_dir'];
}
else
{
	$sort_dir =  'DESC';
}
$sort_dir = ($sort_dir == 'ASC') ? 'ASC' : 'DESC';

if ( !empty($HTTP_POST_VARS['search_time']) || !empty($HTTP_GET_VARS['search_time']))
{
	$search_time = time() - ( ( ( !empty($HTTP_POST_VARS['search_time']) ) ? intval($HTTP_POST_VARS['search_time']) : intval($HTTP_GET_VARS['search_time']) ) * 86400 );
	$topic_days = (!empty($HTTP_POST_VARS['search_time'])) ? intval($HTTP_POST_VARS['search_time']) : intval($HTTP_GET_VARS['search_time']);
}
else
{
	$search_time = 0;
	$topic_days = 0;
}

// Start View All Posts Sorted By Time MOD
if ( !empty($HTTP_GET_VARS['sort_time']) || !empty($HTTP_POST_VARS['sort_time']) )
{
	$sort_time = ( !empty($HTTP_GET_VARS['sort_time']) ) ? intval($HTTP_GET_VARS['sort_time']) : intval($HTTP_POST_VARS['sort_time']);
	$sort_time = time() - $sort_time;
}

else
{
	$sort_time = 0;
}
// End View All Posts Sorted By Time MOD 

if (isset($HTTP_POST_VARS['start']) || isset($HTTP_GET_VARS['start']))
{
	$start = (isset($HTTP_POST_VARS['start'])) ? intval($HTTP_POST_VARS['start']) : intval($HTTP_GET_VARS['start']);
}
else
{
	$start = 0;
}

$start = ($start < 0) ? 0 : $start;

$sort_by_types = array($lang['Sort_Time'], $lang['Sort_Post_Subject'], $lang['Sort_Topic_Title'], $lang['Sort_Author'], $lang['Sort_Forum']);

// Start Advanced IP Tools Pack MOD
$search_ip = '';

// For security reasons, we need to make sure the IP lookup is coming from an admin or mod.
if ( ($userdata['user_level'] == ADMIN) || ($userdata['user_level'] == MOD) )
{
	if ( !empty($HTTP_POST_VARS['search_ip']) || !empty($HTTP_GET_VARS['search_ip']) )
	{
		$ip_address = ( !empty($HTTP_POST_VARS['search_ip']) ) ? $HTTP_POST_VARS['search_ip'] : $HTTP_GET_VARS['search_ip'];
		$ip_address = htmlspecialchars($ip_address);
		$ip_address = str_replace("'", "''", $ip_address);
		$ip_pieces = explode('.', $ip_address);
		$ip_pieces_count = count($ip_pieces) - 1;

			for ($i = 0; $i <= $ip_pieces_count; $i++)
			{
				$search_ip .= ( $ip_pieces[$i] == '*' ) ? '%' : sprintf('%02x', $ip_pieces[$i]);
			}
			
	}

	else
	{
		$search_ip = '';
	}
}
// End Advanced IP Tools Pack MOD

//
// encoding match for workaround
//
$multibyte_charset = 'utf-8, big5, shift_jis, euc-kr, gb2312';

//
// Begin core code
//
if ( $mode == 'searchuser' )
{
	//
	// This handles the simple windowed user search functions called from various other scripts
	//
	if ( isset($HTTP_POST_VARS['search_username']) || isset($HTTP_GET_VARS['search_username']) )
	{
		username_search((!empty($HTTP_POST_VARS['search_username'])) ? $HTTP_POST_VARS['search_username'] : $HTTP_GET_VARS['search_username']);
	}
	else
	{
		username_search('');
	}

	exit;
}
else if ( $search_keywords != '' || $search_author != '' || $search_id || $sort_time )
{
// start mod save posts as drafts (and end mod too)...added the draft_on variable in the next line so that if the user clicks to after page 1 of list and then goes back to page 1 the draft lists will appear
	$store_vars = array('search_results', 'total_match_count', 'split_search', 'sort_by', 'sort_dir', 'show_results', 'return_chars', 'draft_on');
	$search_results = '';

	//
	// Search ID Limiter, decrease this value if you experience further timeout problems with searching forums
	$limiter = 5000;
	$current_time = time();

	//
	// Cycle through options ...
	//
	if ( $search_id == 'newposts' || $search_id == 'upi2db' || $search_id == 'newtopics' || $search_id == 'egosearch' || $search_id == 'unanswered' || $search_keywords != '' || $search_author != '' || $search_ip != '' || $sort_time  || $search_id == 'usertopics' || $search_id == 'egotopicsearch')
	{
		//
		// Flood control
		//
		$where_sql = ($userdata['user_id'] == ANONYMOUS) ? "se.session_ip = '$user_ip'" : 'se.session_user_id = ' . $userdata['user_id'];
		$sql = 'SELECT MAX(sr.search_time) AS last_search_time
			FROM ' . SEARCH_TABLE . ' sr, ' . SESSIONS_TABLE . " se
			WHERE sr.session_id = se.session_id
				AND $where_sql";
		if ($result = $db->sql_query($sql))
		{
			if ($row = $db->sql_fetchrow($result))
			{
				if (intval($row['last_search_time']) > 0 && ($current_time - intval($row['last_search_time'])) < intval($board_config['search_flood_interval']))
				{
					if ($is_ajax)
					{
						$result_ar = array(
							'search_id' => 0,
							'results' => 0,
							'keywords' => ''
						);
						AJAX_message_die($result_ar);
					}
					else
					{
						message_die(GENERAL_MESSAGE, $lang['Search_Flood_Error']);
					}
				}
			}
		}
		if ( $search_id == 'newposts' || $search_id == 'upi2db' || $search_id == 'newtopics' || $search_id == 'egosearch' || $search_id == 'usertopics' || $search_id == 'egotopicsearch' || ( $search_author != '' && $search_keywords == '' ) || $search_ip != '' || $sort_time  )
		{
			if ( $search_id == 'newposts' || $search_id == 'upi2db' )
			{
				if ( $userdata['session_logged_in'] )
				{
//<!-- BEGIN Unread Post Information to Database Mod -->	
					if( !$userdata['upi2db_access'] || $search_id == 'newposts')
					$sql = "SELECT post_id 
						FROM " . POSTS_TABLE . " 
						WHERE post_time >= " . $userdata['user_lastvisit'] . " AND post_draft = 0";
						// start mod save posts as drafts (and end mod too)...added constraint in the preceding line that post_draft be 0 so that draftws wouldn't get included
				}
					else
					{   
						if( $search_id == 'upi2db') 
						{
							switch($s) 
                            { 
						        case 'perm': 
                           	   	$sql_where = ( count($unread['always_read']['topics']) == 0 ) ? 0 : implode(',', $unread['always_read']['topics']); 
                           	   	break; 

                        	   	case 'new': 
                           	   	$sql_where = ( count($unread['new_posts']) == 0 ) ? 0 : implode(',', $unread['new_posts']); 
                           	   	$sql_where2 = ( count($unread['edit_posts']) == 0 ) ? 0 : implode(',', $unread['edit_posts']); 
                           	   	break; 

                        	   	case 'mark': 
                           	   	$sql_where = ( count($unread['mark_posts']) == 0 ) ? 0 : implode(',', $unread['mark_posts']); 
                           	   	$sql_where2 = 0; 
                           	   	break;
                            } 
							
   							if( $search_id == 'upi2db' && $s == 'perm')
   							{
       							$sql = "SELECT post_id 
    							    FROM " . POSTS_TABLE . " 
    							    WHERE topic_id IN (" . $sql_where . ")";
   							}
							if( $search_id == 'upi2db' && $s != 'perm')
   							{
       							$sql = "SELECT post_id 
       								FROM " . POSTS_TABLE . " 
       								WHERE (post_id IN (" . $sql_where .") OR post_id IN (" . $sql_where2 ."))";
   							}
							if(empty($sql_where) && empty($sql_where2))
							{
							    redirect(append_sid("index.$phpEx", true)); 
							}
						}
					}
//<!-- END Unread Post Information to Database Mod -->
				}
				else
				{
					redirect(append_sid("login.$phpEx?redirect=search.$phpEx&search_id=newposts", true));
				}
//<!-- BEGIN Unread Post Information to Database Mod -->
				if($search_id == 'upi2db' && $s == 'mark')
				{
				    $show_results = 'posts';
				}
				else
				{
				    $show_results = 'topics';
				}
//<!-- END Unread Post Information to Database Mod -->

				$show_results = 'topics';
				$sort_by = 0;
				$sort_dir = 'DESC';
			}

			// Start Advanced IP Tools Pack MOD
			else if ($search_ip != '')
			{
				$sql = "SELECT post_id 
					FROM " . POSTS_TABLE . " 
					WHERE poster_ip LIKE '$search_ip'";
				
				$show_results = 'posts';
				$sort_by = 0;
				$sort_dir = 'DESC';
			}
			//End Advanced IP Tools Pack MOD

			// Start View All Posts Sorted By Time MOD
			else if ( $sort_time )
			{
				$sql = 'SELECT post_id 
					FROM ' . POSTS_TABLE . " 
					WHERE post_time >= $sort_time";
					
				$show_results = 'topics';
				$sort_by = 0;
				$sort_dir = 'DESC';
			}
			// End View All Posts Sorted By Time MOD
// Topics a user has started MOD, By Manipe (Begin)
			else if ( $search_id == 'egotopicsearch' )
			{
				if ( $userdata['session_logged_in'] )
				{
					$sql = "SELECT p.post_id
						FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t
						WHERE t.topic_poster = " . $userdata['user_id'] . " AND
							p.post_id = t.topic_first_post_id";
				}
				else
				{
					redirect(append_sid("login.$phpEx?redirect=search.$phpEx&search_id=egotopicsearch", true));
				}

				$show_results = 'topics';
				$sort_by = 0;
				$sort_dir = 'DESC';
			}
			else if ( $search_id == 'usertopics' )
			{
				$user = ( !empty($HTTP_GET_VARS['user']) ) ? intval($HTTP_GET_VARS['user']) : '0';
				$sql = "SELECT p.post_id
					FROM " . POSTS_TABLE . " p, " . TOPICS_TABLE . " t
					WHERE t.topic_poster = " . $user . " AND
                    p.post_draft = 0 AND
					p.post_id = t.topic_first_post_id";

				$show_results = 'topics';
				$sort_by = 0;
				$sort_dir = 'DESC';
			}
else if ( $search_id == 'newtopics' )
{
	if ( $userdata['session_logged_in'] )
	{
		$sql = "SELECT topic_first_post_id AS post_id
			FROM " . TOPICS_TABLE . " 
			WHERE topic_time >= " . $userdata['user_lastvisit'];
	}
	else
	{
		redirect(append_sid("login.$phpEx?redirect=search.$phpEx&search_id=newtopics", true));
	}

	$show_results = 'topics';
	$sort_by = 0;
	$sort_dir = 'DESC';
}
// Topics a user has started MOD, By Manipe (End)
			else if ( $search_id == 'egosearch' )
			{
				// start mod save posts as drafts ... set $draft_on to true if this is egosearch (since we show drafts only for egosearch)...
				$draft_on = true;
				// end mod save posts as drafts
				if ( $userdata['session_logged_in'] )
				{
					$sql = "SELECT post_id 
						FROM " . POSTS_TABLE . " 
						WHERE poster_id = " . $userdata['user_id'] . "
						AND post_draft = 0";
						// start mod save posts as drafts (and end mod too)...added a constraint in preceding line that post_draft be 0 so that drafts wouldn't get included
				}
				else
				{
					redirect(append_sid("login.$phpEx?redirect=search.$phpEx&search_id=egosearch", true));
				}

				// start mod save posts as drafts (and end mod too)...deleted the line that set $show_results to 'topics' because $show_results is now set earlier on if this is an egosearch
				$sort_by = 0;
				$sort_dir = 'DESC';
			}
			else
			{
				$search_author = str_replace('*', '%', trim($search_author));

				if( ( strpos($search_author, '%') !== false ) && ( strlen(str_replace('%', '', $search_author)) < $board_config['search_min_chars'] ) )
				{
					$search_author = '';
				}
				
				$sql = "SELECT user_id
					FROM " . USERS_TABLE . "
					WHERE username LIKE '" . str_replace("\'", "''", $search_author) . "'";
				if ( !($result = $db->sql_query($sql)) )
				{
					message_die(GENERAL_ERROR, "Couldn't obtain list of matching users (searching for: $search_author)", "", __LINE__, __FILE__, $sql);
				}

				$matching_userids = '';
				if ( $row = $db->sql_fetchrow($result) )
				{
					do
					{
						$matching_userids .= ( ( $matching_userids != '' ) ? ', ' : '' ) . $row['user_id'];
					}
					while( $row = $db->sql_fetchrow($result) );
				}
				else
				{
					message_die(GENERAL_MESSAGE, $lang['No_search_match']);
				}

				$sql = "SELECT post_id 
					FROM " . POSTS_TABLE . " 
					WHERE poster_id IN ($matching_userids)";
				
				if ($search_time)
				{
					$sql .= " AND post_time >= " . $search_time;
				}
			}

			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain matched posts list', '', __LINE__, __FILE__, $sql);
			}

			$search_ids = array();
			while( $row = $db->sql_fetchrow($result) )
			{
				$search_ids[] = $row['post_id'];
			}
			$db->sql_freeresult($result);

			$total_match_count = count($search_ids);

		}
		else if ( $search_keywords != '' )
		{
			$stopword_array = @file($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/search_stopwords.txt'); 
			$synonym_array = @file($phpbb_root_path . 'language/lang_' . $board_config['default_lang'] . '/search_synonyms.txt'); 

			$split_search = array();
			$stripped_keywords = stripslashes($search_keywords);
			$split_search = ( !strstr($multibyte_charset, $lang['ENCODING']) ) ?  split_words(clean_words('search', $stripped_keywords, $stopword_array, $synonym_array), 'search') : split(' ', $search_keywords);	
			unset($stripped_keywords);


			$search_msg_only = ( !$search_fields ) ? "AND m.title_match = 0" : ( ( strstr($multibyte_charset, $lang['ENCODING']) ) ? '' : '' );

			$word_count = 0;
			$current_match_type = 'or';

			$word_match = array();
			$result_list = array();

			for($i = 0; $i < count($split_search); $i++)
			{
				if ( strlen(str_replace(array('*', '%'), '', trim($split_search[$i]))) < $board_config['search_min_chars'] )
				{
					$split_search[$i] = '';
					continue;
				}

				switch ( $split_search[$i] )
				{
					case 'and':
						$current_match_type = 'and';
						break;

					case 'or':
						$current_match_type = 'or';
						break;

					case 'not':
						$current_match_type = 'not';
						break;

					default:
						if ( !empty($search_terms) )
						{
							$current_match_type = 'and';
						}

						if ( !strstr($multibyte_charset, $lang['ENCODING']) )
						{
							$match_word = str_replace('*', '%', $split_search[$i]);
							$sql = "SELECT m.post_id 
								FROM " . SEARCH_WORD_TABLE . " w, " . SEARCH_MATCH_TABLE . " m 
								WHERE w.word_text LIKE '$match_word' 
									AND m.word_id = w.word_id 
									AND w.word_common <> 1 
									$search_msg_only";
						}
						else
						{
							$match_word =  addslashes('%' . str_replace('*', '', $split_search[$i]) . '%');
							$search_msg_only = ( $search_fields ) ? "OR post_subject LIKE '$match_word'" : '';
							$sql = "SELECT post_id
								FROM " . POSTS_TEXT_TABLE . "
								WHERE post_text LIKE '$match_word'
								$search_msg_only";
						}
						if ( !($result = $db->sql_query($sql)) )
						{
							message_die(GENERAL_ERROR, 'Could not obtain matched posts list', '', __LINE__, __FILE__, $sql);
						}

						$row = array();
						while( $temp_row = $db->sql_fetchrow($result) )
						{
							$row[$temp_row['post_id']] = 1;

							if ( !$word_count )
							{
								$result_list[$temp_row['post_id']] = 1;
							}
							else if ( $current_match_type == 'or' )
							{
								$result_list[$temp_row['post_id']] = 1;
							}
							else if ( $current_match_type == 'not' )
							{
								$result_list[$temp_row['post_id']] = 0;
							}
						}

						if ( $current_match_type == 'and' && $word_count )
						{
							@reset($result_list);
							while( list($post_id, $match_count) = @each($result_list) )
							{
								if ( !$row[$post_id] )
								{
									$result_list[$post_id] = 0;
								}
							}
						}

						$word_count++;

						$db->sql_freeresult($result);
					}
			}

			@reset($result_list);

			$search_ids = array();
			while( list($post_id, $matches) = each($result_list) )
			{
				if ( $matches )
				{
					$search_ids[] = $post_id;
				}
			}	
			
			unset($result_list);
			$total_match_count = count($search_ids);
		}

		// BEGIN Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
		// Turned off for all ADMIN users, they get
		// to see everything no matter what the
		// post levels are set to. This initial
		// block of code is just to get the array
		// filled, we'll check it again later.
		$prohibited_forums = array();
		if ($userdata['user_level'] <> ADMIN)
		{
			// No need to query the entire database, check to
			// see if the user has selected a single forum or
			// a single category to search, limit forums checked
			// to just the ones needed...
			if ( $search_forum != -1 )
			{
				$extra_sql = " AND f.forum_id = $search_forum ";
			}

			if ( $search_cat != -1 )
			{
				$extra_sql = " AND f.cat_id = $search_cat ";
			}

			$sql = 'SELECT  forum_id
				,       min_posts_to_view
				,       max_posts_to_view
				FROM    ' . FORUMS_TABLE . ' f
				WHERE   1 = 1 ' .
					$extra_sql;

			if ( !( $result = $db->sql_query($sql) ) )
			{
				message_die(GENERAL_ERROR, 'DEBUG: Unable to query forum view post limits');
			}

			// Build an array of TRUE / FALSE values to check later
			while ($row = $db->sql_fetchrow($result))
			{
				// Reverse the return code as we're looking for PROHIBITED
				// forums, rather than allowed in this case.
				$prohibited_forums[$row['forum_id']] = !(phpbbdoctor_post_count_auth($row['min_posts_to_view'], $row['max_posts_to_view']));
			}
			$db->sql_freeresult($result);
		}
		// END Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)

		//
		// If user is logged in then we'll check to see which (if any) private
		// forums they are allowed to view and include them in the search.
		//
		// If not logged in we explicitly prevent searching of private forums
		//
		$auth_sql = '';
		if ( $search_forum != -1 )
		{
			$is_auth = auth(AUTH_ALL, $search_forum, $userdata);

			// BEGIN Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
			// if ( !$is_auth['auth_read'] )
			if ( !$is_auth['auth_read'] || ( $prohibited_forums[$search_forum] == TRUE ) )
			// END Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
			{
				message_die(GENERAL_MESSAGE, $lang['No_searchable_forums']);
			}

			$auth_sql = "f.forum_id = $search_forum";
		}
		else
		{
			$is_auth_ary = auth(AUTH_ALL, AUTH_LIST_ALL, $userdata); 

			if ( $search_cat != -1 )
			{
				$auth_sql = "f.cat_id = $search_cat";
			}

			$ignore_forum_sql = '';
			while( list($key, $value) = each($is_auth_ary) )
			{
				// BEGIN Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
				// if ( !$value['auth_read'] )
				if ( !$value['auth_read'] || ( $prohibited_forums[$key] == TRUE ) )
				// END Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
				{
					$ignore_forum_sql .= ( ( $ignore_forum_sql != '' ) ? ', ' : '' ) . $key;
				}
			}

			if ( $ignore_forum_sql != '' )
			{
				$auth_sql .= ( $auth_sql != '' ) ? " AND f.forum_id NOT IN ($ignore_forum_sql) " : "f.forum_id NOT IN ($ignore_forum_sql) ";
			}
		}

		//
		// Author name search 
		//
		if ( $search_author != '' )
		{
			$search_author = str_replace('*', '%', trim($search_author));

			if( ( strpos($search_author, '%') !== false ) && ( strlen(str_replace('%', '', $search_author)) < $board_config['search_min_chars'] ) )
			{
				$search_author = '';
			}
		}

		if ( $total_match_count )
		{
			if ( $show_results == 'topics' )
			{
				//
				// This one is a beast, try to seperate it a bit (workaround for connection timeouts)
				//
				$search_id_chunks = array();
				$count = 0;
				$chunk = 0;

				if (count($search_ids) > $limiter)
				{
					for ($i = 0; $i < count($search_ids); $i++) 
					{
						if ($count == $limiter)
						{
							$chunk++;
							$count = 0;
						}
					
						$search_id_chunks[$chunk][$count] = $search_ids[$i];
						$count++;
					}
				}
				else
				{
					$search_id_chunks[0] = $search_ids;
				}

				$search_ids = array();

				for ($i = 0; $i < count($search_id_chunks); $i++)
				{
					$where_sql = '';

					if ( $search_time )
					{
						$where_sql .= ( $search_author == '' && $auth_sql == ''  ) ? " AND post_time >= $search_time " : " AND p.post_time >= $search_time ";
					}
	
					if ( $search_author == '' && $auth_sql == '' )
					{
						$sql = "SELECT topic_id 
							FROM " . POSTS_TABLE . "
							WHERE post_id IN (" . implode(", ", $search_id_chunks[$i]) . ") 
							$where_sql 
							GROUP BY topic_id";
					}
					else
					{
						$from_sql = POSTS_TABLE . " p"; 

						if ( $search_author != '' )
						{
							$from_sql .= ", " . USERS_TABLE . " u";
	//start mod save posts as drafts (and end mod too)...in the following line, added constraint that post_draft be 0						
						$where_sql .= " AND u.user_id = p.poster_id AND u.username LIKE '$search_author' AND p.post_draft = 0";
						}

						if ( $auth_sql != '' )
						{
							$from_sql .= ", " . FORUMS_TABLE . " f";
							$where_sql .= " AND f.forum_id = p.forum_id AND $auth_sql";
						}

						$sql = "SELECT p.topic_id 
							FROM $from_sql 
							WHERE p.post_id IN (" . implode(", ", $search_id_chunks[$i]) . ") 
								$where_sql 
							GROUP BY p.topic_id";
					}

					if ( !($result = $db->sql_query($sql)) )
					{
						message_die(GENERAL_ERROR, 'Could not obtain topic ids', '', __LINE__, __FILE__, $sql);
					}

					while ($row = $db->sql_fetchrow($result))
					{
						$search_ids[] = $row['topic_id'];
					}
					$db->sql_freeresult($result);
				}

				$total_match_count = sizeof($search_ids);
		
			}
			else if ( $search_author != '' || $search_time || $auth_sql != '' )
			{
				$search_id_chunks = array();
				$count = 0;
				$chunk = 0;

				if (count($search_ids) > $limiter)
				{
					for ($i = 0; $i < count($search_ids); $i++) 
					{
						if ($count == $limiter)
						{
							$chunk++;
							$count = 0;
						}
					
						$search_id_chunks[$chunk][$count] = $search_ids[$i];
						$count++;
					}
				}
				else
				{
					$search_id_chunks[0] = $search_ids;
				}

				$search_ids = array();

				for ($i = 0; $i < count($search_id_chunks); $i++)
				{
					$where_sql = ( $search_author == '' && $auth_sql == '' ) ? 'post_id IN (' . implode(', ', $search_id_chunks[$i]) . ')' : 'p.post_id IN (' . implode(', ', $search_id_chunks[$i]) . ')';
					$select_sql = ( $search_author == '' && $auth_sql == '' ) ? 'post_id' : 'p.post_id';
					$from_sql = (  $search_author == '' && $auth_sql == '' ) ? POSTS_TABLE : POSTS_TABLE . ' p';

					if ( $search_time )
					{
						$where_sql .= ( $search_author == '' && $auth_sql == '' ) ? " AND post_time >= $search_time " : " AND p.post_time >= $search_time";
					}

					if ( $auth_sql != '' )
					{
						$from_sql .= ", " . FORUMS_TABLE . " f";
						$where_sql .= " AND f.forum_id = p.forum_id AND $auth_sql";
					}

					if ( $search_author != '' )
					{
						$from_sql .= ", " . USERS_TABLE . " u";
//start mod save posts as drafts (and end mod too)...in the following line, added constraint that post_draft be 0
						
						$where_sql .= " AND u.user_id = p.poster_id AND u.username LIKE '$search_author' AND p.post_draft = 0";
					}

					$sql = "SELECT " . $select_sql . " 
						FROM $from_sql 
						WHERE $where_sql";
					if ( !($result = $db->sql_query($sql)) )
					{
						message_die(GENERAL_ERROR, 'Could not obtain post ids', '', __LINE__, __FILE__, $sql);
					}

					while( $row = $db->sql_fetchrow($result) )
					{
						$search_ids[] = $row['post_id'];
					}
					$db->sql_freeresult($result);
				}

				$total_match_count = count($search_ids);
			}
		}
		else if ( $search_id == 'unanswered' )
		{
			if ( $auth_sql != '' )
			{
				$sql = "SELECT t.topic_id, f.forum_id
					FROM " . TOPICS_TABLE . "  t, " . FORUMS_TABLE . " f
					WHERE t.topic_replies = 0 
						AND t.forum_id = f.forum_id
						AND t.topic_moved_id = 0
						AND $auth_sql";
			}
			else
			{
				$sql = "SELECT topic_id 
					FROM " . TOPICS_TABLE . "  
					WHERE topic_replies = 0 
						AND topic_moved_id = 0";
			}
				
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain post ids', '', __LINE__, __FILE__, $sql);
			}

			$search_ids = array();
			while( $row = $db->sql_fetchrow($result) )
			{
				$search_ids[] = $row['topic_id'];
			}
			$db->sql_freeresult($result);

			$total_match_count = count($search_ids);

			//
			// Basic requirements
			//
			$show_results = 'topics';
			$sort_by = 0;
			$sort_dir = 'DESC';
		}
		else if ($is_ajax)
		{
			$result_ar = array(
				'search_id' => 0,
				'results' => 0,
				'keywords' => ''
			);
			AJAX_message_die($result_ar);
		}
		else
		{
			// start mod save posts as drafts (and end mod too)...added the check that skips the no match message if there are drafts to be shown
			if(!$draft_on)
			{
				track_search($userdata['user_id'], $user_ip, time(), $search_keywords, $search_author, $HTTP_SERVER_VARS['HTTP_REFERER'], '1', $search_terms, $search_fields, $return_chars, $search_cat, $search_forum, $sort_by, $sort_dir);
				message_die(GENERAL_MESSAGE, $lang['No_search_match']);
			}
		}

		//
		// Delete old data from the search result table
		//
		$sql = 'DELETE FROM ' . SEARCH_TABLE . '
			WHERE search_time < ' . ($current_time - (int) $board_config['session_length']);
		if ( !$result = $db->sql_query($sql) )
		{
			message_die(GENERAL_ERROR, 'Could not delete old search id sessions', '', __LINE__, __FILE__, $sql);
		}

		//
		// Store new result data
		//
		$search_results = implode(', ', $search_ids);
		$per_page = ( $show_results == 'posts' ) ? $board_config['posts_per_page'] : $board_config['topics_per_page'];

		//
		// Combine both results and search data (apart from original query)
		// so we can serialize it and place it in the DB
		//
		$store_search_data = array();

		//
		// Limit the character length (and with this the results displayed at all following pages) to prevent
		// truncated result arrays. Normally, search results above 12000 are affected.
		// - to include or not to include
		/*
		$max_result_length = 60000;
		if (strlen($search_results) > $max_result_length)
		{
			$search_results = substr($search_results, 0, $max_result_length);
			$search_results = substr($search_results, 0, strrpos($search_results, ','));
			$total_match_count = count(explode(', ', $search_results));
		}
		*/

		for($i = 0; $i < count($store_vars); $i++)
		{
			$store_search_data[$store_vars[$i]] = $$store_vars[$i];
		}

		$result_array = serialize($store_search_data);
		unset($store_search_data);

		mt_srand ((double) microtime() * 1000000);
		$search_id = mt_rand();

		$sql = "UPDATE " . SEARCH_TABLE . " 
			SET search_id = $search_id, search_time = $current_time, search_array = '" . str_replace("\'", "''", $result_array) . "'
			WHERE session_id = '" . $userdata['session_id'] . "'";
		if ( !($result = $db->sql_query($sql)) || !$db->sql_affectedrows() )
		{
			$sql = "INSERT INTO " . SEARCH_TABLE . " (search_id, session_id, search_time, search_array) 
				VALUES($search_id, '" . $userdata['session_id'] . "', $current_time, '" . str_replace("\'", "''", $result_array) . "')";
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not insert search results', '', __LINE__, __FILE__, $sql);
			}
		}
	}
	else
	{
		$search_id = intval($search_id);
		if ( $search_id )
		{
			$sql = "SELECT search_array 
				FROM " . SEARCH_TABLE . " 
				WHERE search_id = $search_id || $search_ip != '' 
					AND session_id = '". $userdata['session_id'] . "'";
			if ( !($result = $db->sql_query($sql)) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain search results', '', __LINE__, __FILE__, $sql);
			}

			if ( $row = $db->sql_fetchrow($result) )
			{
				$search_data = unserialize($row['search_array']);
				for($i = 0; $i < count($store_vars); $i++)
				{
					$$store_vars[$i] = $search_data[$store_vars[$i]];
				}
			}
		}
	}

	//
	// Insert into search phrase table
	//
	track_search($userdata['user_id'], $user_ip, time(), $search_keywords, $search_author, $HTTP_SERVER_VARS['HTTP_REFERER'], '0', $search_terms, $search_fields, $return_chars, $search_cat, $search_forum, $sort_by, $sort_dir);
	//
	// Look up data ...
	//
//-- mod : IP Country Flag II ----------------------------------------------
// add , u.user_cf_iso3661_1
	// start mod save posts as drafts (and end mod too)...added $draft_on part of next line so that it will execute the next piece of code if we are supposed to show drafts even when there are no search matches
	if ( $search_results != '' || $draft_on )
	{
//-- mod : calendar ------------------------------------------------------------
//-- add
		$user->set();
		$calendar_api->set();
		$calendar_front_title = new front_calendar();
//-- fin mod : calendar --------------------------------------------------------
		if ( $show_results == 'posts' )
		{
			$sql = "SELECT pt.post_text, pt.bbcode_uid, pt.post_subject, p.*, f.forum_id, f.forum_name, t.*, u.username, u.user_id, u.user_cf_iso3661_1, u.user_sig, u.user_sig_bbcode_uid, u.user_level  
				FROM " . FORUMS_TABLE . " f, " . TOPICS_TABLE . " t, " . USERS_TABLE . " u, " . POSTS_TABLE . " p, " . POSTS_TEXT_TABLE . " pt 
				WHERE p.post_id IN ($search_results)
					AND pt.post_id = p.post_id
					AND f.forum_id = p.forum_id
					AND p.topic_id = t.topic_id
					AND p.poster_id = u.user_id";
		}
//-- end mod : IP Country Flag II ----------------------------------------------
		else
//-- mod : IP Country Flag II ----------------------------------------------
// add , u.user_cf_iso3661_1 AND , u2.user_cf_iso3661_1 as user2flag
		{
			$sql = "SELECT t.*, f.forum_id, f.forum_name, u.username, u.user_id, u.user_cf_iso3661_1, u.user_level, u2.username as user2, u2.user_id as id2, u2.user_cf_iso3661_1 as user2flag, u2.user_level as user_level2, p.post_username, p2.post_username AS post_username2, p2.post_time, pt.bbcode_uid 
				FROM " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f, " . USERS_TABLE . " u, " . POSTS_TABLE . " p, " . POSTS_TABLE . " p2, " . USERS_TABLE . " u2, " . POSTS_TEXT_TABLE . " pt
				WHERE t.topic_id IN ($search_results) 
					AND t.topic_poster = u.user_id
					AND f.forum_id = t.forum_id 
					AND p.post_id = t.topic_first_post_id
					AND p2.post_id = t.topic_last_post_id
					AND t.topic_first_post_id = pt.post_id
					AND u2.user_id = p2.poster_id";
		}
//-- end mod : IP Country Flag II ----------------------------------------------

//-- mod : rank color system ---------------------------------------------------
//-- add
		$sql = str_replace(', u.user_id', ', u.user_id, u.user_level, u.user_color, u.user_group_id', $sql);

		if ($show_results == 'topics')
		{
			$sql = str_replace(', u2.user_id as id2', ', u2.user_id as id2, u2.user_level as level2, u2.user_color as color2, u2.user_group_id as group_id2', $sql);
		}
//-- fin mod : rank color system -----------------------------------------------
		$per_page = ( $show_results == 'posts' ) ? $board_config['posts_per_page'] : $board_config['topics_per_page'];

		$sql .= " ORDER BY ";
		switch ( $sort_by )
		{
			case 1:
				$sql .= ( $show_results == 'posts' ) ? 'pt.post_subject' : 't.topic_title';
				break;
			case 2:
				$sql .= 't.topic_title';
				break;
			case 3:
				$sql .= 'u.username';
				break;
			case 4:
				$sql .= 'f.forum_id';
				break;
			default:
				$sql .= ( $show_results == 'posts' ) ? 'p.post_time' : 'p2.post_time';
				break;
		}
		$sql .= " $sort_dir LIMIT $start, " . $per_page;

		// start mod save posts as drafts ...skip the actual search query if this is a search that is supposed to show drafts and there are no regular search results
//-- mod : IP Country Flag II ----------------------------------------------
// add , u.user_cf_iso3661_1
		if ( $search_results != '' )
		{
			if ( !$result = $db->sql_query($sql) )
			{
				message_die(GENERAL_ERROR, 'Could not obtain search results', '', __LINE__, __FILE__, $sql);
			}

//<!-- Begin Unread Post Information to Database Mod	-->        
        $searchset = array();
		$searchset_gae = array(); 
        $searchset_gan = array(); 
        $searchset_ae = array(); 
        $searchset_an = array(); 
        $searchset_se = array(); 
        $searchset_sn = array(); 
        $searchset_e = array(); 
        $searchset_n = array();
	
        while( $row = $db->sql_fetchrow($result) )
        {
        	if($userdata['upi2db_access']) 
        	{
        	    if($board_config['upi2db_edit_topic_first']) 
        	    {
    			    if(isset($unread['edit_topics']) && in_array($row['topic_id'], $unread['edit_topics']) && $row['topic_type'] == POST_GLOBAL_ANNOUNCE) 
               		{ 
                  	    $searchset_gae[] = $row; 
               		} 
               		elseif($row['topic_type'] == POST_GLOBAL_ANNOUNCE) 
               		{ 
                  	    $searchset_gan[] = $row; 
                    } 
                    elseif(isset($unread['edit_topics']) && in_array($row['topic_id'], $unread['edit_topics']) && $row['topic_type'] == POST_ANNOUNCE) 
                    { 
                        $searchset_ae[] = $row; 
                    } 
                    elseif($row['topic_type'] == POST_ANNOUNCE) 
                    { 
                        $searchset_an[] = $row; 
                    } 
                    elseif(isset($unread['edit_topics']) && in_array($row['topic_id'], $unread['edit_topics']) && $row['topic_type'] == POST_STICKY) 
                    { 
                        $searchset_se[] = $row; 
                    } 
                    elseif($row['topic_type'] == POST_STICKY) 
                    { 
                        $searchset_sn[] = $row; 
                    } 
                    elseif(isset($unread['edit_topics']) && in_array($row['topic_id'], $unread['edit_topics']) && $row['topic_type'] != POST_GLOBAL_ANNOUNCE && $row['topic_type'] != POST_ANNOUNCE && $row['topic_type'] != POST_STICKY)
            		{
            		    $searchset_e[] = $row;
            		}
					elseif($row['topic_type'] != POST_GLOBAL_ANNOUNCE && $row['topic_type'] != POST_ANNOUNCE && $row['topic_type'] != POST_STICKY)
            		{
            		    $searchset_n[] = $row;
            		}
            	}
            	else
            	{
            	    if($row['topic_type'] == POST_GLOBAL_ANNOUNCE)
    				{
    				    $searchset_gan[] = $row;
    				}
    				elseif($row['topic_type'] == POST_ANNOUNCE)
    				{
    				    $searchset_an[] = $row;
    				}
    				elseif($row['topic_type'] == POST_STICKY)
    				{
    				    $searchset_sn[] = $row;
    				}
            		elseif($row['topic_type'] != POST_GLOBAL_ANNOUNCE && $row['topic_type'] != POST_ANNOUNCE && $row['topic_type'] != POST_STICKY)
            		{
            		    $searchset_n[] = $row;
            		}
            	}
			}
			else
			{
			    $searchset[] = $row;
			} 
	    }
		if($userdata['upi2db_access']) 
        {
            if($board_config['upi2db_edit_topic_first']) 
            {
                $searchset = array_merge($searchset_gae, $searchset_gan, $searchset_ae, $searchset_an, $searchset_se, $searchset_sn, $searchset_e, $searchset_n);
    		}
    		else
    		{
    		    $searchset = array_merge($searchset_gan, $searchset_an, $searchset_sn, $searchset_n);
    		}
		}
        	
//<!-- END Unread Post Information to Database Mod	-->

			$db->sql_freeresult($result);
		}
		// end mod save posts as drafts		
		
		//
		// Define censored word matches
		//
		$orig_word = array();
		$replacement_word = array();
		obtain_word_list($orig_word, $replacement_word);

		if ($is_ajax == 1)
		{
			$result_ar = array(
				'search_id' => ($total_match_count == 1) ? $searchset[0]['topic_id'] : $search_id,
				'results' => $total_match_count,
				'keywords' => $search_keywords
			);
			AJAX_message_die($result_ar);
		}
		else if ($is_ajax == 2)
		{
			$result_title = '';
			$max_results = ($total_match_count < 10) ? $total_match_count : 10;

			$search_result_text = ($total_match_count == 1) ? $lang['AJAX_quick_search_result'] : sprintf($lang['AJAX_quick_search_results'], $total_match_count);
			for ($sr = 0; $sr < $max_results; $sr++)
			{
				$result_title .= '<a href="'.append_sid("viewtopic.$phpEx?".POST_TOPIC_URL."=".$searchset[$sr]['topic_id']."&highlight=$search_keywords").'">'.$searchset[$sr]['topic_title'].'</a><br />';
			}

			$result_ar = array(
				'results' => $result_title,
				'error_msg' => $search_result_text
			);
			AJAX_message_die($result_ar);
		}
		//
		// Output header
		//
		$page_title = $lang['Search'];
		include($phpbb_root_path . 'includes/page_header.'.$phpEx);
		// start mod save posts as drafts...show all drafts at the top of the search results page when a user searches for all of his or her posts (egosearch)...
		if ( $draft_on && $start == 0 )
		{
			$sql = "SELECT p.post_id, p.post_time, pt.post_subject, t.topic_title, f.forum_name
				FROM " . POSTS_TABLE . " p , " . POSTS_TEXT_TABLE . " pt, " . TOPICS_TABLE . " t, " . FORUMS_TABLE . " f
				WHERE p.post_draft = 1
				AND pt.post_id = p.post_id
				AND p.poster_id = ".$userdata['user_id']."
				AND p.topic_id = t.topic_id
				AND f.forum_id = p.forum_id
				ORDER BY p.post_time";

			$result = $db->sql_query($sql);

			if( !$result )
			{
				message_die(GENERAL_ERROR, "Couldn't obtain draft posts from database", "", __LINE__, __FILE__, $sql);
			}

			$draft_posts = $db->sql_fetchrowset($result);
			$db->sql_freeresult($result);
			$total_draft_posts = count($draft_posts);
			
			// ok, done collecting all draft posts...now let's find the draft pms
			$sql = "SELECT privmsgs_id, privmsgs_subject, privmsgs_date
				FROM " . PRIVMSGS_TABLE . "
				WHERE privmsgs_type = " . PRIVMSGS_DRAFT_MAIL . "
				AND privmsgs_from_userid = ".$userdata['user_id']."
				ORDER BY privmsgs_date";

			$result = $db->sql_query($sql);

			if( !$result )
			{
				message_die(GENERAL_ERROR, "Couldn't obtain draft posts from database", "", __LINE__, __FILE__, $sql);
			}

			$draft_pms = $db->sql_fetchrowset($result);	
			$db->sql_freeresult($result);
			
			if ( !$draft_posts || !$draft_pms )
			{
				$drafts = ( $draft_posts ) ? $draft_posts : $draft_pms;
			}
			else
			{
				$drafts = array_merge($draft_posts,$draft_pms);
			}
			
			$total_drafts = count($drafts);
			
			// cut this all off if there are no regular search matches and no drafts
			if( $search_results == '' && $total_drafts == 0 )
			{
				message_die(GENERAL_MESSAGE, $lang['No_search_match']);
			}
			
			if ( $total_drafts > 0 )
			{
			$template->assign_block_vars('switch_show_drafts', array());
			$template->assign_block_vars("draft", array());
				for($i = 0; $i < $total_drafts; $i++)
				{
					$row_class = ( !($i % 2) ) ? $theme['td_class1'] : $theme['td_class2'];
					// now set variables, but variables are different depending on if draft post or draft pm so treat differently...
					if ( $i < $total_draft_posts )
					{
						$draft_time = create_date($board_config['default_dateformat'], $drafts[$i]['post_time'], $board_config['board_timezone']);
						$draft_subject = ( $drafts[$i]['post_subject'] ) ? $drafts[$i]['post_subject'] : $drafts[$i]['topic_title'];
						$draft_topic = $drafts[$i]['topic_title'];
						$draft_forum = $drafts[$i]['forum_name'];
						$draft_url = append_sid("posting.$phpEx?mode=draft&amp;" . POST_POST_URL . "=".$drafts[$i]['post_id']."");
					}
					else
					{
						$draft_time = create_date($board_config['default_dateformat'], $drafts[$i]['privmsgs_date'], $board_config['board_timezone']);
						$draft_subject = $drafts[$i]['privmsgs_subject'];
						$draft_topic = $drafts[$i]['privmsgs_subject'];
						$draft_forum = $lang['Private_Messages'];
						$draft_url = append_sid("privmsg.$phpEx?mode=draft&amp;" . POST_POST_URL . "=".$drafts[$i]['privmsgs_id']."");

					}
				$template->assign_block_vars("draft.draft_topics", array(
					"ROW_CLASS" => $row_class,
					"DRAFT_POST_TIME" =>  $draft_time,
					"DRAFT_POST_SUBJECT" =>  $draft_subject,
					"DRAFT_POST_TOPIC" =>  $draft_topic,
					"DRAFT_POST_FORUM" =>  $draft_forum,
					"DRAFT_POST_LOC" => $draft_url)
				);
				}
			}
		}
		// end mod save posts as drafts	

		if ( $show_results == 'posts' )
		{
			$template->set_filenames(array(
				'body' => 'search_results_posts.tpl')
			);
		}
		else
		{
			$template->set_filenames(array(
				'body' => 'search_results_topics.tpl')
			);
		}
		make_jumpbox('viewforum.'.$phpEx);

		// start mod save posts as drafts (and end mod too)...added drafts to the match count and added text for draft posts in the next two blocks of code
		$total_match_count = $total_match_count + $total_drafts;
		$l_search_matches = ( $total_match_count == 1 ) ? sprintf($lang['Found_search_match'], $total_match_count) : sprintf($lang['Found_search_matches'], $total_match_count);
		( $show_results == 'topics' ) ? $real_posts = $lang['Topics_you_have_posted_to'] : $real_posts = $lang['Your_posts'];
		
		$template->assign_vars(array(
			'L_SEARCH_MATCHES' => $l_search_matches,
			'L_DRAFT_POSTS' => $lang['Draft_posts'],
			'L_REAL_POSTS' => $real_posts,
			'L_DRAFT_POST_TIME' =>  $lang['Draft_post_time'],
			'L_DRAFT_POST_SUBJECT' =>  $lang['Draft_post_subject'],
			'L_DRAFT_POST_TOPIC' =>  $lang['Draft_post_topic'],
			'L_DRAFT_POST_FORUM' => $lang['Draft_post_forum'], 
			'L_TOPIC' => $lang['Topic'])
		);

		$highlight_active = '';
		$highlight_match = array();
		for($j = 0; $j < count($split_search); $j++ )
		{
			$split_word = $split_search[$j];

			if ( $split_word != 'and' && $split_word != 'or' && $split_word != 'not' )
			{
				$highlight_match[] = '#\b(' . str_replace("*", "([\w]+)?", $split_word) . ')\b#is';
				$highlight_active .= " " . $split_word;

				for ($k = 0; $k < count($synonym_array); $k++)
				{ 
					list($replace_synonym, $match_synonym) = split(' ', trim(strtolower($synonym_array[$k]))); 

					if ( $replace_synonym == $split_word )
					{
						$highlight_match[] = '#\b(' . str_replace("*", "([\w]+)?", $replace_synonym) . ')\b#is';
						$highlight_active .= ' ' . $match_synonym;
					}
				} 
			}
		}

		$highlight_active = urlencode(trim($highlight_active));

		$tracking_topics = ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_t']) ) ? unserialize($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_t']) : array();
		$tracking_forums = ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f']) ) ? unserialize($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f']) : array();

		if ($show_results == 'posts')
		{
			if ($search_forum == -1)
			{
				$is_auth_ary = auth(AUTH_ALL, AUTH_LIST_ALL, $userdata);
			}
			else
			{
				$is_auth = auth(AUTH_ALL, $search_forums, $userdata);
			}
		}

		for($i = 0; $i < count($searchset); $i++)
		{
			// www.phpBB-SEO.com SEO TOOLKIT BEGIN
			if ( !isset($phpbb_seo->seo_url['forum'][$searchset[$i]['forum_id']]) ) {
				$phpbb_seo->seo_url['forum'][$searchset[$i]['forum_id']] = $phpbb_seo->format_url($searchset[$i]['forum_name'], $phpbb_seo->seo_static['forum']);
			}
			// www.phpBB-SEO.com SEO TOOLKIT END

			// CrackerTracker v5.x
			$sucheck = strtolower($highlight_active);
			$sucheck = str_replace($ct_rules, '*', $sucheck);
			if($sucheck != $highlight_active)
			{
			  $highlight_active = '';
			}
			$forum_url = append_sid("viewforum.$phpEx?" . POST_FORUM_URL . '=' . $searchset[$i]['forum_id']);
	  		$topic_url = append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . '=' . $searchset[$i]['topic_id'] . "&amp;lighter=$highlight_active");

         	$post_url = append_sid("viewtopic.$phpEx?" . POST_POST_URL . '=' . $searchset[$i]['post_id'] . "&amp;highlight=$highlight_active") . '#' . $searchset[$i]['post_id'];

            $post_date = create_date2($board_config['default_dateformat'], $searchset[$i]['post_time'], $board_config['board_timezone']);

			$message = $searchset[$i]['post_text'];
			$topic_title = $searchset[$i]['topic_title'];
			$topic_raw_title = $topic_title;
			// mod topic description code moved a few lines down
			$forum_id = $searchset[$i]['forum_id'];
			$topic_id = $searchset[$i]['topic_id'];
			// mod topic description mod add
			$showdesc = check_descperm ( TRUE );
			$topic_desc = ( $showdesc ) ? fetch_desc( $searchset[$i]['topic_description'], $searchset[$i]['bbcode_uid'] ) : '';
			$topic_tool = ( show_tooltip ( $searchset[$i]['forum_id'], $searchset[$i]['topic_id'] ) ) ? topic_tooltip ( $searchset[$i]['topic_id'] ) : '';
			// mod topic description mod end

			if ( $show_results == 'posts' )
			{
				if ($search_forum == -1)
				{
					$is_auth = $is_auth_ary[$forum_id];
				}
				if ( isset($return_chars) )
				{
					$bbcode_uid = $searchset[$i]['bbcode_uid'];

					//
					// If the board has HTML off but the post has HTML
					// on then we process it, else leave it alone
					//
					if ( $return_chars != -1 )
					{
						$message = strip_tags($message);
						$message = preg_replace("/\[.*?:$bbcode_uid:?.*?\]/si", '', $message);
						$message = preg_replace('/\[url\]|\[\/url\]/si', '', $message);
						$message = ( strlen($message) > $return_chars ) ? substr($message, 0, $return_chars) . ' ...' : $message;
					}
					else
					{
						if ( !$board_config['allow_html'] )
						{
							if ( $postrow[$i]['enable_html'] )
							{
								$message = preg_replace('#(<)([\/]?.*?)(>)#is', '&lt;\\2&gt;', $message);
							}
						}

						if ( $bbcode_uid != '' )
						{
							$message = ( $board_config['allow_bbcode'] ) ? bbencode_second_pass($message, $bbcode_uid) : preg_replace('/\:[0-9a-z\:]+\]/si', ']', $message);
						}

						$message = make_clickable($message);

						if ( $highlight_active )
						{
							if ( preg_match('/<.*>/', $message) )
							{
								$message = preg_replace($highlight_match, '<!-- #sh -->\1<!-- #eh -->', $message);

								$end_html = 0;
								$start_html = 1;
								$temp_message = '';
								$message = ' ' . $message . ' ';

								while( $start_html = strpos($message, '<', $start_html) )
								{
									$grab_length = $start_html - $end_html - 1;
									$temp_message .= substr($message, $end_html + 1, $grab_length);

									if ( $end_html = strpos($message, '>', $start_html) )
									{
										$length = $end_html - $start_html + 1;
										$hold_string = substr($message, $start_html, $length);

										if ( strrpos(' ' . $hold_string, '<') != 1 )
										{
											$end_html = $start_html + 1;
											$end_counter = 1;

											while ( $end_counter && $end_html < strlen($message) )
											{
												if ( substr($message, $end_html, 1) == '>' )
												{
													$end_counter--;
												}
												else if ( substr($message, $end_html, 1) == '<' )
												{
													$end_counter++;
												}

												$end_html++;
											}

											$length = $end_html - $start_html + 1;
											$hold_string = substr($message, $start_html, $length);
											$hold_string = str_replace('<!-- #sh -->', '', $hold_string);
											$hold_string = str_replace('<!-- #eh -->', '', $hold_string);
										}
										else if ( $hold_string == '<!-- #sh -->' )
										{
											$hold_string = str_replace('<!-- #sh -->', '<span style="color:#' . $theme['fontcolor3'] . '"><b>', $hold_string);
										}
										else if ( $hold_string == '<!-- #eh -->' )
										{
											$hold_string = str_replace('<!-- #eh -->', '</b></span>', $hold_string);
										}

										$temp_message .= $hold_string;

										$start_html += $length;
									}
									else
									{
										$start_html = strlen($message);
									}
								}

								$grab_length = strlen($message) - $end_html - 1;
								$temp_message .= substr($message, $end_html + 1, $grab_length);

								$message = trim($temp_message);
							}
							else
							{
								$message = preg_replace($highlight_match, '<span style="color:#' . $theme['fontcolor3'] . '"><b>\1</b></span>', $message);
							}
						}
					}

					if ( count($orig_word) )
					{
						$topic_title = preg_replace($orig_word, $replacement_word, $topic_title);
						$topic_raw_title = preg_replace($orig_word, $replacement_word, $topic_raw_title);
						$post_subject = ( $searchset[$i]['post_subject'] != "" ) ? preg_replace($orig_word, $replacement_word, $searchset[$i]['post_subject']) : '';

						$message = preg_replace($orig_word, $replacement_word, $message);
					}
					else
					{
						$post_subject = $searchset[$i]['post_subject'];
					}

					if ($board_config['allow_smilies'] && $searchset[$i]['enable_smilies'])
					{
						$message = smilies_pass($message);
					}

		            $message = word_wrap_pass($message);
					$message = str_replace("\n", '<br />', $message);

				}
				// Start add - User Class Mod
				switch ( $searchset[$i]['user_level'] )
				{
					case ADMIN:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ($searchset[$i]['user_id'] == 2) ? ' style="color: #' . $theme['color_founder'] . '"' : ' style="color: #' . $theme['color_admin'] . '"';
						break;
					case MAIN_MOD:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_main_mod'] . '"';
						break;
					case MOD:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_mod'] . '"';
						break;
					case SUPPORT:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_support'] . '"';
						break;
					case VIP:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_vip'] . '"';
						break;
					case BOT:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_bot'] . '"';
						break;
					case USER:
						$post_username_color = '<strong>' . $searchset[$i]['post_username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_user'] . '"';
						break;
					default:
						$post_username_color = $searchset[$i]['post_username'];
						$style_color = '';
						break;
				}
				// End add - User Class Mod

				$is_firstpost = ($searchset[$i]['post_id'] == $searchset[$i]['topic_first_post_id']) ? 1 : 0;
				$edit_url = '';
				$edit_img = '';
				if ($can_edit = ($is_auth['auth_mod'] || (($searchset[$i]['user_id'] == $userdata['user_id'] && ($searchset[$i]['topic_status'] != TOPIC_LOCKED)) && $is_auth['auth_edit'])))
				{
					$raw_message = $searchset[$i]['post_text'];
					if (!empty($bbcode_uid))
					{
						$raw_message = preg_replace('#\:(([a-z0-9]:)?)'. $bbcode_uid .'#s', '', $raw_message);
					}
				
					$raw_message = str_replace('<', '&lt;', $raw_message);
					$raw_message = str_replace('>', '&gt;', $raw_message);
					$raw_message = str_replace('<br />', "\n", $raw_message);
					
					$edit_url = append_sid("posting.$phpEx?mode=editpost&amp;". POST_POST_URL ."=". $searchset[$i]['post_id']);
					$edit_img = '<a id="editimg_'. $searchset[$i]['post_id'] .'" onclick="return AJAXPostEdit('. $searchset[$i]['post_id'] .');" href="'. $edit_url .'"><img src="'. $images['icon_edit'] .'" alt="'. $lang['Edit_delete_post'] .'" title="'. $lang['Edit_delete_post'] .'" border="0" align="right" /></a><br />';
				}
//-- mod : rank color system ---------------------------------------------------
//-- delete
/*-MOD
//-- mod : IP Country Flag II ---------------------------------------------- 
				if ( $searchset[$i]['user_id'] == ANONYMOUS )
				{
					$poster_ipcf = '<img src="images/flags/small/' . $lang['IPCF_Guest'] . '.png" width="14" height="9" border="0" alt="' . $lang['IP2Country']['Guest'] . '" title="' . $lang['IP2Country']['Guest'] . '" /> ';
				}
				else
				{
					$poster_ipcf = '<img src="images/flags/small/' . $searchset[$i]['user_cf_iso3661_1'] . '.png" width="14" height="9" border="0" alt="' . $lang['IP2Country'][$searchset[$i]['user_cf_iso3661_1']] . '" title="' . $lang['IP2Country'][$searchset[$i]['user_cf_iso3661_1']] . '" /> ';
				}
//-- end mod : IP Country Flag II ------------------------------------------- 
				$poster = ( $searchset[$i]['user_id'] != ANONYMOUS ) ? '<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . "=" . $searchset[$i]['user_id']) . '">' : '';
MOD-*/
//-- add
				$style_color = $rcs->get_colors($searchset[$i]);
				$poster = ($searchset[$i]['user_id'] != ANONYMOUS) ? '<a href="' . $get->url('profile', array('mode' => 'viewprofile', POST_USERS_URL => $searchset[$i]['user_id']), true) . '"' . $style_color . '>' : '';
//-- fin mod : rank color system -----------------------------------------------
				$poster .= ( $searchset[$i]['user_id'] != ANONYMOUS ) ? $searchset[$i]['username'] : ( ( $searchset[$i]['post_username'] != "" ) ? $post_username_color : $lang['Guest'] );
				$poster .= ( $searchset[$i]['user_id'] != ANONYMOUS ) ? '</a>' : '';

//<!-- BEGIN Unread Post Information to Database Mod -->	
			if( !$userdata['upi2db_access'])
			{
//<!-- END Unread Post Information to Database Mod -->

				if ( $userdata['session_logged_in'] && $searchset[$i]['post_time'] > $userdata['user_lastvisit'] )
				{
					if ( !empty($tracking_topics[$topic_id]) && !empty($tracking_forums[$forum_id]) )
					{
						$topic_last_read = ( $tracking_topics[$topic_id] > $tracking_forums[$forum_id] ) ? $tracking_topics[$topic_id] : $tracking_forums[$forum_id];
					}
					else if ( !empty($tracking_topics[$topic_id]) || !empty($tracking_forums[$forum_id]) )
					{
						$topic_last_read = ( !empty($tracking_topics[$topic_id]) ) ? $tracking_topics[$topic_id] : $tracking_forums[$forum_id];
					}

					if ( $searchset[$i]['post_time'] > $topic_last_read )
					{
						$mini_post_img = $images['icon_minipost_new'];
						$mini_post_alt = $lang['New_post'];
					}
					else
					{
						$mini_post_img = $images['icon_minipost'];
						$mini_post_alt = $lang['Post'];
					}
				}
				else
				{
					$mini_post_img = $images['icon_minipost'];
					$mini_post_alt = $lang['Post'];
				}

				// Start Smilies Invasion Mod
        if ( $board_config['allow_smilies'] )
        {
          $topic_title = smilies_pass($topic_title);
				  $searchset[$i]['forum_name'] = smilies_pass($searchset[$i]['forum_name']);
				  $post_subject = smilies_pass($post_subject);
        }
        // End Smilies Invasion Mod
//<!-- BEGIN Unread Post Information to Database Mod -->	
                $folder_image = $images['folder'];
			    $folder_alt = ( $searchset[$i]['topic_status'] == TOPIC_LOCKED ) ? $lang['Topic_locked'] : $lang['No_new_posts'];
			
			}
            else
			{
				search_calc_unread2($unread, $topic_id, $searchset, $i, $mini_post_img, $mini_post_alt, $unread_color, $folder_image, $folder_alt);
			}

        	if($userdata['upi2db_access'])
        	{
       		    if($s == "mark")
				{
				    $post_id = $searchset[$i]['post_id'];
				    $mark_topic_unread = '<a href="' . append_sid("search.$phpEx?search_id=upi2db&amp;s=mark&amp;t=$topic_id&amp;f=$forum_id&amp;p=$post_id&amp;do=unmark_post&amp;s=$s") . '"><img src="' . $images['unmark_img'] . '" alt="' . $lang['upi2db_unmark_post'] . '" title="' . $lang['upi2db_unmark_post'] . '" border="0" /></a>';
        	    }
			}
//<!-- END Unread Post Information to Database Mod	-->
				$template->assign_block_vars("searchresults", array( 
                    'TOPIC_TITLE' => $topic_title,
// mod topic mod add
					'TOPIC_DESC' => $topic_desc,
					'TOPIC_TOOLTIP' => $topic_tool,
// mod topic mod end
					'FORUM_NAME' => $searchset[$i]['forum_name'],
					'POST_SUBJECT' => (empty($post_subject)) ? $lang['No_subject'] : $post_subject,
					'POST_RAW_SUBJECT' => $post_raw_subject,
					'POST_DATE' => $post_date,
					'POSTER_NAME' => $poster,
//-- mod : IP Country Flag II ----------------------------------------------
					'POSTER_FLAG' => $poster_ipcf,
//-- end mod : IP Country Flag II ------------------------------------------
					'TOPIC_REPLIES' => $searchset[$i]['topic_replies'],
					'TOPIC_VIEWS' => $searchset[$i]['topic_views'],
					'MESSAGE' => $message,
					'MINI_POST_IMG' => $mini_post_img,

//<!-- BEGIN Unread Post Information to Database Mod -->
					'TOPIC_FOLDER_IMG' => $folder_image,
					'UNREAD_COLOR' => $unread_color,
					'UNREAD_IMG' => $mark_topic_unread,
//<!-- END Unread Post Information to Database Mod --> 

					'L_MINI_POST_ALT' => $mini_post_alt,

//<!-- BEGIN Unread Post Information to Database Mod -->
					'L_TOPIC_FOLDER_ALT' => $folder_alt,
//<!-- END Unread Post Information to Database Mod --> 

					'RAW_MESSAGE' => $raw_message,
					'U_POST_ID' => $searchset[$i]['post_id'],
					'U_EDIT_POST' => $edit_url,
					'U_EDIT_IMG' => $edit_img,
					'S_AJAX_EDIT_TITLE' => ($can_edit) ? 'ondblclick="AJAXTitleEdit('. $searchset[$i]['post_id'] .', '. $is_firstpost .');"' : '',
					'U_POST' => $post_url,
					'U_TOPIC' => $topic_url,
					'U_FORUM' => $forum_url)
				);
//-- mod : calendar ------------------------------------------------------------
//-- add
				if ( $searchset[$i]['post_id'] == $searchset[$i]['topic_first_post_id'] )
				{
					$calendar_front_title->topic_title('searchresults', $searchset[$i]['topic_calendar_time'], $searchset[$i]['topic_calendar_duration']);
				}
//-- fin mod : calendar --------------------------------------------------------
				if ($can_edit)
				{
					$template->assign_block_vars('searchresults.can_edit', array());
				}
				$template->assign_var('RETURN_CHARS', $return_chars);
			}
			else
			{
				$message = '';

				if ( count($orig_word) )
				{
					$topic_title = preg_replace($orig_word, $replacement_word, $searchset[$i]['topic_title']);
					$topic_raw_title = preg_replace($orig_word, $replacement_word, $topic_raw_title);
				}

				$topic_type = $searchset[$i]['topic_type'];

				if ($topic_type == POST_ANNOUNCE)
				{
					$topic_type = $lang['Topic_Announcement'] . ' ';
				}
				else if ($topic_type == POST_STICKY)
				{
					$topic_type = $lang['Topic_Sticky'] . ' ';
				}
				else
				{
					$topic_type = '';
				}
// Event Registration Begin
				if( ( $searchset[$i]['topic_reg']) && check_reg_active($topic_id) )
				{
					$regoption_array = array();
					if( $userdata['user_id'] )
					{
						$sql = "SELECT registration_status FROM ".REGISTRATION_TABLE." WHERE topic_id = $topic_id AND registration_user_id =".$userdata['user_id'];
						if ( !($result = $db->sql_query($sql)) )
						{
							message_die(GENERAL_ERROR, 'Could not obtain forums information', '', __LINE__, __FILE__, $sql);
						}
		
						if( $regrow = $db->sql_fetchrow($result) )
						{
							$status = $regrow['registration_status'];
							if( $status == REG_OPTION1 )
							{
								$topic_type .= '<span class="genoption1">&#149;</span>' . ' ';
							}
							else if( $status == REG_OPTION2 )
							{
								$topic_type .= '<span class="genoption2">&#149;</span>' . ' ';
							}
							else if( $status == REG_OPTION3 )
							{
								$topic_type .= '<span class="genoption3">&#149;</span>' . ' ';
							}
							else
							{
								$topic_type .= '<span class="genoption0">&#149;</span>' . ' ';
							}
						}
						else if( empty($regrow) && $searchset[$i]['topic_reg'] )
						{
							$topic_type .= '<span class="genoption0">&#149;</span>' . ' ';
						}
						else
						{
							$topic_type .= '';
						}
		
						$db->sql_freeresult($result);
					}
					else
					{
						$topic_type .= $lang['Topic_RegLogin'] . ' ';
					}
		
					$sql = "SELECT u.username, u.user_id, u.user_cf_iso3661_1, r.registration_time, r.registration_confirm_time, r.registration_status FROM ".REGISTRATION_TABLE." r, ".USERS_TABLE." u WHERE r.topic_id=$topic_id AND r.registration_user_id = u.user_id ORDER BY registration_status,registration_time";
		
					if ( !($result = $db->sql_query($sql)) )
					{
						message_die(GENERAL_ERROR, "Could not obtain registration data for this topic", '', __LINE__, __FILE__, $sql);
					}
//-- end mod : IP Country Flag II ----------------------------------------------
					$reg_info = $db->sql_fetchrowset($result);
		
					$db->sql_freeresult($result);
					$numregs = count($reg_info);
					$option1_count = 0;
					$option2_count = 0;
					$option3_count = 0;
		
					for( $u = 0; $u < $numregs; $u ++ )
					{
						if( $reg_info[$u]['registration_status'] == REG_OPTION1 )
						{
							$option1_count ++;
						}
						else if( $reg_info[$u]['registration_status'] == REG_OPTION2 )
						{
							$option2_count++;
						}
						else if( $reg_info[$u]['registration_status'] == REG_OPTION3 )
						{
							$option3_count ++;
						}
					}
		
					if (true === check_option_exists($topic_id,1))
					{
						$option1_count = '<span class="genoption1">'.(0+$option1_count).'</span>';
						array_push($regoption_array, $option1_count);
					}
					if (true === check_option_exists($topic_id,2))
					{
						$option2_count = '<span class="genoption2">'.(0+$option2_count).'</span>';
						array_push($regoption_array, $option2_count);
					}
					if (true === check_option_exists($topic_id,3))
					{
						$option3_count = '<span class="genoption3">'.(0+$option3_count).'</span>';
						array_push($regoption_array, $option3_count);
					}
					$regoptions_count = count($regoption_array);
		
					$v = 0;
					$regoptions = '';
					while ( $v < $regoptions_count-1 )
					{
						$regoptions .= $regoption_array[$v].'-';
						$v++;
					}
					$regoptions .= array_pop($regoption_array);
				}
// Event Registration End

				if ( $searchset[$i]['topic_vote'] )
				{
					$topic_type .= $lang['Topic_Poll'] . ' ';
				}

				$views = $searchset[$i]['topic_views'];
				$replies = $searchset[$i]['topic_replies'];

				if ( ( $replies + 1 ) > $board_config['posts_per_page'] )
				{
					$total_pages = ceil( ( $replies + 1 ) / $board_config['posts_per_page'] );
					$goto_page = ' [ <img src="' . $images['icon_gotopost'] . '" alt="' . $lang['Goto_page'] . '" title="' . $lang['Goto_page'] . '" />' . $lang['Goto_page'] . ': ';

					$times = 1;
					for($j = 0; $j < $replies + 1; $j += $board_config['posts_per_page'])
					{
						$goto_page .= '<a href="' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=" . $topic_id . "&amp;start=$j") . '">' . $times . '</a>';
						if ( $times == 1 && $total_pages > 4 )
						{
							$goto_page .= ' ... ';
							$times = $total_pages - 3;
							$j += ( $total_pages - 4 ) * $board_config['posts_per_page'];
						}
						else if ( $times < $total_pages )
						{
							$goto_page .= ', ';
						}
						$times++;
					}
					$goto_page .= ' ] ';
				}
				else
				{
					$goto_page = '';
				}

				if ( $searchset[$i]['topic_status'] == TOPIC_MOVED )
				{
					$topic_type = $lang['Topic_Moved'] . ' ';
					$topic_id = $searchset[$i]['topic_moved_id'];
					$folder_image = '<img src="' . $images['folder'] . '" alt="' . $lang['No_new_posts'] . '" />';
					$newest_post_img = '';
				}
				else
				{
					if ( $searchset[$i]['topic_status'] == TOPIC_LOCKED )
					{
						$folder = $images['folder_locked'];
						$folder_new = $images['folder_locked_new'];
					}
					else if ( $searchset[$i]['topic_type'] == POST_ANNOUNCE )
					{
						$folder = $images['folder_announce'];
						$folder_new = $images['folder_announce_new'];
					}
					else if ( $searchset[$i]['topic_type'] == POST_STICKY )
					{
						$folder = $images['folder_sticky'];
						$folder_new = $images['folder_sticky_new'];
					}
//-- mod : Calendar Topic Folder--------------------------------------------------------------------
//-- add
					else if (!empty($searchset[$i]['topic_calendar_time']))
					{
						$folder = $images['folder_calendar'];
						$folder_new = $images['folder_calendar_new'];
					}
//-- fin mod : Calendar Topic Folder ---------------------------------------------------------------
					else
					{
						if ( $replies >= $board_config['hot_threshold'] )
						{
							$folder = $images['folder_hot'];
							$folder_new = $images['folder_hot_new'];
						}
						else
						{
							$folder = $images['folder'];
							$folder_new = $images['folder_new'];
						}
					}

					if ( $userdata['session_logged_in'] )
					{
//<!-- BEGIN Unread Post Information to Database Mod -->	
					  if( !$userdata['upi2db_access'])
					  {
//<!-- END Unread Post Information to Database Mod -->
						if ( $searchset[$i]['post_time'] > $userdata['user_lastvisit'] ) 
						{
							if ( !empty($tracking_topics) || !empty($tracking_forums) || isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f_all']) )
							{

								$unread_topics = true;

								if ( !empty($tracking_topics[$topic_id]) )
								{
									if ( $tracking_topics[$topic_id] > $searchset[$i]['post_time'] )
									{
										$unread_topics = false;
									}
								}

								if ( !empty($tracking_forums[$forum_id]) )
								{
									if ( $tracking_forums[$forum_id] > $searchset[$i]['post_time'] )
									{
										$unread_topics = false;
									}
								}

								if ( isset($HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f_all']) )
								{
									if ( $HTTP_COOKIE_VARS[$board_config['cookie_name'] . '_f_all'] > $searchset[$i]['post_time'] )
									{
										$unread_topics = false;
									}
								}

								if ( $unread_topics )
								{
									$folder_image = $folder_new;
									$folder_alt = $lang['New_posts'];
									$newest_post_img = '<a href="' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;view=newest") . '"><img src="' . $images['icon_newest_reply'] . '" alt="' . $lang['View_newest_post'] . '" title="' . $lang['View_newest_post'] . '" border="0" /></a> ';
								}
								else
								{
									$folder_alt = ( $searchset[$i]['topic_status'] == TOPIC_LOCKED ) ? $lang['Topic_locked'] : $lang['No_new_posts'];
									$folder_image = $folder;
									$folder_alt = $folder_alt;
									$newest_post_img = '';
								}

							}
							else if ( $searchset[$i]['post_time'] > $userdata['user_lastvisit'] ) 
							{
								$folder_image = $folder_new;
								$folder_alt = $lang['New_posts'];
								$newest_post_img = '<a href="' . append_sid("viewtopic.$phpEx?" . POST_TOPIC_URL . "=$topic_id&amp;view=newest") . '"><img src="' . $images['icon_newest_reply'] . '" alt="' . $lang['View_newest_post'] . '" title="' . $lang['View_newest_post'] . '" border="0" /></a> ';
							}
							else 
							{
								$folder_image = $folder;
								$folder_alt = ( $searchset[$i]['topic_status'] == TOPIC_LOCKED ) ? $lang['Topic_locked'] : $lang['No_new_posts'];
								$newest_post_img = '';
							}
						}
						else
						{
							$folder_image = $folder;
							$folder_alt = ( $searchset[$i]['topic_status'] == TOPIC_LOCKED ) ? $lang['Topic_locked'] : $lang['No_new_posts'];
							$newest_post_img = '';
						}
//<!-- BEGIN Unread Post Information to Database Mod -->
					}
					else
					{	
   					    search_calc_unread($unread, $topic_id, $searchset, $i, $folder_new, $folder, $newest_post_img, $topic_type, $folder_image, $folder_alt);
   					}
//<!-- END Unread Post Information to Database Mod -->
					}
					else
					{
						$folder_image = $folder;
						$folder_alt = ( $searchset[$i]['topic_status'] == TOPIC_LOCKED ) ? $lang['Topic_locked'] : $lang['No_new_posts'];
						$newest_post_img = '';
					}
				}


				// Start add - User Class Mod
				switch ( $searchset[$i]['user_level'] )
				{
					case ADMIN:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ($searchset[$i]['user_id'] == 2) ? ' style="color: #' . $theme['color_founder'] . '"' : ' style="color: #' . $theme['color_admin'] . '"';
						break;
					case MAIN_MOD:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_main_mod'] . '"';
						break;
					case MOD:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_mod'] . '"';
						break;
					case SUPPORT:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_support'] . '"';
						break;
					case VIP:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_vip'] . '"';
						break;
					case BOT:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_bot'] . '"';
						break;
					case USER:
						$username_color = '<strong>' . $searchset[$i]['username'] . '</strong>';
						$style_color = ' style="color: #' . $theme['color_user'] . '"';
						break;
					default:
						$username_color = $searchset[$i]['username'];
						$style_color = '';
						break;
				}
				switch ( $searchset[$i]['user_level2'] )
				{
					case ADMIN:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ($searchset[$i]['id2'] == 2) ? ' style="color: #' . $theme['color_founder'] . '"' : ' style="color: #' . $theme['color_admin'] . '"';
						break;
					case MAIN_MOD:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ' style="color: #' . $theme['color_main_mod'] . '"';
						break;
					case MOD:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ' style="color: #' . $theme['color_mod'] . '"';
						break;
					case SUPPORT:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ' style="color: #' . $theme['color_support'] . '"';
						break;
					case VIP:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ' style="color: #' . $theme['color_vip'] . '"';
						break;
					case BOT:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ' style="color: #' . $theme['color_bot'] . '"';
						break;
					case USER:
						$username_color2 = '<strong>' . $searchset[$i]['user2'] . '</strong>';
						$style_color2 = ' style="color: #' . $theme['color_user'] . '"';
						break;
					default:
						$username_color2 = $searchset[$i]['user2'];
						$style_color2 = '';
						break;
				}
				// End add - User Class Mod
//-- mod : rank color system ---------------------------------------------------
//-- delete
/*-MOD
//-- mod : IP Country Flag II ---------------------------------------------- 
				if ( $searchset[$i]['user_id'] == ANONYMOUS )
				{
					$author_ipcf = '<img src="images/flags/small/' . $lang['IPCF_Guest'] . '.png" width="14" height="9" border="0" alt="' . $lang['IP2Country']['Guest'] . '" title="' . $lang['IP2Country']['Guest'] . '" /> ';
				}
				else
				{
					$author_ipcf = '<img src="images/flags/small/' . $searchset[$i]['user_cf_iso3661_1'] . '.png" width="14" height="9" border="0" alt="' . $lang['IP2Country'][$searchset[$i]['user_cf_iso3661_1']] . '" title="' . $lang['IP2Country'][$searchset[$i]['user_cf_iso3661_1']] . '" /> ';
				}
//-- end mod : IP Country Flag II ---------------------------------------------- 
				$topic_author = ( $searchset[$i]['user_id'] != ANONYMOUS ) ? '<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . '=' . $searchset[$i]['user_id']) . '">' : '';
MOD-*/
//-- add
				$topic_author_color = $rcs->get_colors($searchset[$i]);
				$topic_author = ($searchset[$i]['user_id'] != ANONYMOUS) ? '<a href="' . $get->url('profile', array('mode' => 'viewprofile', POST_USERS_URL => $searchset[$i]['user_id']), true) . '"' . $topic_author_color . '>' : '';
//-- fin mod : rank color system -----------------------------------------------
				$topic_author .= ( $searchset[$i]['user_id'] != ANONYMOUS ) ? $username_color : ( ( $searchset[$i]['post_username'] != '' ) ? $searchset[$i]['post_username'] : $lang['Guest'] );

				$topic_author .= ( $searchset[$i]['user_id'] != ANONYMOUS ) ? '</a>' : '';

                $first_post_time = create_date2($board_config['default_dateformat'], $searchset[$i]['topic_time'], $board_config['board_timezone']);

                $last_post_time = create_date2($board_config['default_dateformat'], $searchset[$i]['post_time'], $board_config['board_timezone']);

//-- mod : rank color system ---------------------------------------------------
//-- delete
/*-MOD
//-- mod : IP Country Flag II ---------------------------------------------- 
				if ( $searchset[$i]['id2'] == ANONYMOUS )
				{
					$last_post_author_ipcf = '<img src="images/flags/small/' . $lang['IPCF_Guest'] . '.png" width="14" height="9" border="0" alt="' . $lang['IP2Country']['Guest'] . '" title="' . $lang['IP2Country']['Guest'] . '" /> ';
				}
				else
				{
					$last_post_author_ipcf = '<img src="images/flags/small/' . $searchset[$i]['user2flag'] . '.png" width="14" height="9" border="0" alt="' . $lang['IP2Country'][$searchset[$i]['user2flag']] . '" title="' . $lang['IP2Country'][$searchset[$i]['user2flag']] . '" /> ';
				}
//-- end mod : IP Country Flag II ----------------------------------------------
				$last_post_author = ( $searchset[$i]['id2'] == ANONYMOUS ) ? ( ($searchset[$i]['post_username2'] != '' ) ? $searchset[$i]['post_username2'] . ' ' : $lang['Guest'] . ' ' ) : '<a href="' . append_sid("profile.$phpEx?mode=viewprofile&amp;" . POST_USERS_URL . '='  . $searchset[$i]['id2']) . '">' . $searchset[$i]['user2'] . '</a>';
MOD-*/
//-- add
				$last_post_author_color = $rcs->get_colors($searchset[$i], '', false, 'group_id2', 'color2', 'level2');
				$last_post_author = ($searchset[$i]['id2'] == ANONYMOUS) ? (($searchset[$i]['post_username2'] != '') ? $searchset[$i]['post_username2'] : $lang['Guest']) : '<a href="' . $get->url('profile', array('mode' => 'viewprofile', POST_USERS_URL => $searchset[$i]['id2']), true) . '"' . $last_post_author_color . '>' . $searchset[$i]['user2'] . '</a>';
//-- fin mod : rank color system -----------------------------------------------

				$last_post_url = '<a href="' . append_sid("viewtopic.$phpEx?"  . POST_POST_URL . '=' . $searchset[$i]['topic_last_post_id']) . '#' . $searchset[$i]['topic_last_post_id'] . '"><img src="' . $images['icon_latest_reply'] . '" alt="' . $lang['View_latest_post'] . '" title="' . $lang['View_latest_post'] . '" border="0" /></a>';

//<!-- BEGIN Unread Post Information to Database Mod -->    
            if($userdata['upi2db_access']) 
            {    
               $mark_always_read = mark_always_read($searchset[$i]['topic_type'], $topic_id, $forum_id, 'search', 'icon', $unread, $start, $folder_image, $search_mode, $s); 
            } 
            else 
            {    
               $mark_always_read = '<img src="' . $folder_image . '" alt="' . $folder_alt . '" title="' . $folder_alt . '" border="0" />'; 
            } 
            $tt = $searchset[$i]['topic_type']; 
//<!-- END Unread Post Information to Database Mod -->

            	$post_raw_subject = $post_subject;
				// Start Smilies Invasion Mod
        if ( $board_config['allow_smilies'] )
        {
				  $searchset[$i]['forum_name'] = smilies_pass($searchset[$i]['forum_name']);
				  $topic_title = smilies_pass($topic_title);
        }
        // End Smilies Invasion Mod
				$mark_link_start = ($userdata['session_logged_in']) ? '<a onclick="return AJAXMarkTopic('. $topic_id .');" href="#">' : '';
				$mark_link_end = ($userdata['session_logged_in']) ? '</a>' : '';
				$this_auth = ($search_forums == -1) ? $is_auth : $is_auth_ary[$forum_id];
				$can_edit = ($this_auth['auth_mod'] || ((($searchset[$i]['topic_poster'] == $userdata['user_id']) && ($searchset[$i]['topic_status'] != TOPIC_LOCKED)) && $this_auth['auth_edit']));
				$template->assign_block_vars('searchresults', array( 
					'FORUM_NAME' => $searchset[$i]['forum_name'],
					'FORUM_ID' => $forum_id,
					'TOPIC_ID' => $topic_id,
					'TOPIC_FIRST_POST_ID' => $searchset[$i]['topic_first_post_id'],
					'FOLDER' => $folder_image,
					'NEWEST_POST_IMG' => $newest_post_img, 
					'TOPIC_FOLDER_IMG' => $folder_image,
//-- mod : hypercell class -----------------------------------------------------
//-- add
					'HYPERCELL_CLASS' => get_hypercell_class($searchset[$i]['topic_status'], ($folder_image == $folder_new), $searchset[$i]['topic_type'], $replies),
//-- fin mod : hypercell class ------------------------------------------------- 
					'GOTO_PAGE' => $goto_page,
					'REPLIES' => $replies,
					'TOPIC_TITLE' => $topic_title,
					'TOPIC_RAW_TITLE' => $topic_raw_title,
// mod topic description mod add
					'TOPIC_DESC' => ( $topic_desc != '' ) ? '<br />' . $topic_desc : '',
					'TOPIC_TOOLTIP' => $topic_tool,
// mod topic mod end
					'TOPIC_TYPE' => $topic_type,
// RegMod-Begin
                    'REG_OPTIONS' => $regoptions,
// RegMod-End


					'VIEWS' => $views,
					'TOPIC_AUTHOR' => $topic_author,
//-- mod : IP Country Flag II ----------------------------------------------
					'AUTHOR_FLAG' => $author_ipcf,
//-- end mod : IP Country Flag II ------------------------------------------ 
					'FIRST_POST_TIME' => $first_post_time, 
					'LAST_POST_TIME' => $last_post_time,
					'LAST_POST_AUTHOR' => $last_post_author,
//-- mod : IP Country Flag II ----------------------------------------------
					'LAST_POST_AUTHOR_FLAG' => $last_post_author_ipcf,
//-- end mod : IP Country Flag II ------------------------------------------
					'LAST_POST_IMG' => $last_post_url,

//<!-- BEGIN Unread Post Information to Database Mod -->					
					'NO_AGM' => ($tt == POST_STICKY || $tt == POST_ANNOUNCE || $tt == POST_GLOBAL_ANNOUNCE || $s == 'perm') ? 'disabled' : '',
//<!-- END Unread Post Information to Database Mod -->

					'L_TOPIC_FOLDER_ALT' => $folder_alt,
					'S_MARK_LINK_START' => $mark_link_start,
					'S_MARK_LINK_END' => $mark_link_end,
					'S_AJAX_EDIT_TITLE' => ($can_edit) ? ' ondblclick="AJAXTitleEdit('. $searchset[$i]['topic_first_post_id'] .', 0)"' : '', 

//<!-- BEGIN Unread Post Information to Database Mod -->	
					'U_MARK_ALWAYS_READ' => $mark_always_read,
//<!-- END Unread Post Information to Database Mod -->

					'U_VIEW_FORUM' => $forum_url, 
					'U_VIEW_TOPIC' => $topic_url)
				);

//<!-- BEGIN Unread Post Information to Database Mod  --> 
                if( $userdata['upi2db_access'] ) 
                { 
                    $template->assign_block_vars('searchresults.switch_upi2db_on', array()); 
                } 
//<!-- END Unread Post Information to Database Mod  -->

//-- mod : calendar ------------------------------------------------------------
//-- add
				$calendar_front_title->topic_title('searchresults', $searchset[$i]['topic_calendar_time'], $searchset[$i]['topic_calendar_duration']);
//-- fin mod : calendar --------------------------------------------------------
				if ($can_edit)
				{
					$template->assign_block_vars('searchresults.can_edit_title', array());
				}
// RegMod-Begin
	                        if( ( $searchset[$i]['topic_reg'] ) && check_reg_active($topic_id) )
	                        {
	                               $template->assign_block_vars('searchresults.display_reg', array());
	                        }
// RegMod-End


			}
		}

		$base_url = "search.$phpEx?search_id=$search_id";

		$template->assign_vars(array(
			'PAGINATION' => generate_pagination($base_url, $total_match_count, $per_page, $start),
			'PAGE_NUMBER' => sprintf($lang['Page_of'], ( floor( $start / $per_page ) + 1 ), ceil( $total_match_count / $per_page )), 

			'L_AUTHOR' => $lang['Author'],
			'L_MESSAGE' => $lang['Message'],
			'L_FORUM' => $lang['Forum'],
			'L_TOPICS' => $lang['Topics'],
			'L_REPLIES' => $lang['Replies'],
			'L_VIEWS' => $lang['Views'],
			'L_POSTS' => $lang['Posts'],

//<!-- BEGIN Unread Post Information to Database Mod -->
            'L_MAR' => $lang['upi2db_search_mark_read'], 
			'L_SUBMIT_MARK_READ' => $lang['upi2db_submit_mark_read'],
            'S_POST_ACTION' => append_sid("search.$phpEx?search_id=". $search_mode . "&s=" . $s),
			'L_UNMARK_ALL' => $lang['Unmark_all'],
			'L_MARK_ALL' => $lang['Mark_all'],
            'L_SUBMIT_MARK_READ' => $lang['upi2db_submit_mark_read'],
//<!-- END Unread Post Information to Database Mod -->

			'L_LASTPOST' => $lang['Last_Post'], 
			'L_POSTED' => $lang['Posted'], 
			'L_SUBJECT' => $lang['Subject'],
			'L_FULL_EDIT' => $lang['Full_edit'],
			'L_SAVE_CHANGES' => $lang['Save_changes'],
			'L_CANCEL' => $lang['Cancel'],

			'L_GOTO_PAGE' => $lang['Goto_page'])
		);

//<!-- BEGIN Unread Post Information to Database Mod  --> 
        if( !$userdata['upi2db_access'] ) 
        { 
            $template->assign_block_vars('switch_upi2db_off', array()); 
        } 
//<!-- END Unread Post Information to Database Mod  -->

		$template->pparse('body');

		include($phpbb_root_path . 'includes/page_tail.'.$phpEx);
	}
	else if ($is_ajax)
	{
		$result_ar = array(
			'search_id' => 0,
			'results' => 0,
			'keywords' => ''
		);
		AJAX_message_die($result_ar);
	}
	else
	{
		message_die(GENERAL_MESSAGE, $lang['No_search_match']);
	}
}

//
// Search forum
//
$sql = "SELECT c.cat_title, c.cat_id, f.forum_name, f.forum_id, f.min_posts_to_view, f.max_posts_to_view, f.forum_parent  
	FROM " . CATEGORIES_TABLE . " c, " . FORUMS_TABLE . " f
	WHERE f.cat_id = c.cat_id 
	ORDER BY c.cat_order, f.forum_order";

$result = $db->sql_query($sql);
if ( !$result )
{
	message_die(GENERAL_ERROR, 'Could not obtain forum_name/forum_id', '', __LINE__, __FILE__, $sql);
}

$is_auth_ary = auth(AUTH_ALL, AUTH_LIST_ALL, $userdata);

$s_forums = '';
$list = array();
while( $row = $db->sql_fetchrow($result) )
{
	if ( $is_auth_ary[$row['forum_id']]['auth_read'] )
	{
		$list[] = $row;
	}
}

for( $i = 0; $i < count($list); $i++ )
{
	if( !$list[$i]['forum_parent'] )
	{
		$row = $list[$i];
		// BEGIN Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
		// $s_forums .= '<option value="' . $row['forum_id'] . '">' . $row['forum_name'] . '</option>';
		if (phpbbdoctor_post_count_auth($row['min_posts_to_view'], $row['max_posts_to_view']))
		{
			$s_forums .= '<option value="' . $row['forum_id'] . '">' . $row['forum_name'] . '</option>';
		}
		// END Forum Auth by Post Count 1.0.0 (www.phpBBDoctor.com)
		if ( empty($list_cat[$row['cat_id']]) )
		{
			$list_cat[$row['cat_id']] = $row['cat_title'];
		}
		$parent_id = $row['forum_id'];
		for( $j = 0; $j < count($list); $j++ )
		{
			if( $list[$j]['forum_parent'] == $parent_id )
			{
				$row = $list[$j];
				$s_forums .= '<option value="' . $row['forum_id'] . '">-- ' . $row['forum_name'] . '</option>';
			}
		}
	}
}

if ( $s_forums != '' )
{
	$s_forums = '<option value="-1">' . $lang['All_available'] . '</option>' . $s_forums;

	//
	// Category to search
	//
	$s_categories = '<option value="-1">' . $lang['All_available'] . '</option>';
	while( list($cat_id, $cat_title) = @each($list_cat))
	{
		$s_categories .= '<option value="' . $cat_id . '">' . $cat_title . '</option>';
	}
}
else
{
	message_die(GENERAL_MESSAGE, $lang['No_searchable_forums']);
}

//
// Number of chars returned
//
$s_characters = '<option value="-1">' . $lang['All_available'] . '</option>';
$s_characters .= '<option value="0">0</option>';
$s_characters .= '<option value="25">25</option>';
$s_characters .= '<option value="50">50</option>';

for($i = 100; $i < 1100 ; $i += 100)
{
	$selected = ( $i == 200 ) ? ' selected="selected"' : '';
	$s_characters .= '<option value="' . $i . '"' . $selected . '>' . $i . '</option>';
}

//
// Sorting
//
$s_sort_by = "";
for($i = 0; $i < count($sort_by_types); $i++)
{
	$s_sort_by .= '<option value="' . $i . '">' . $sort_by_types[$i] . '</option>';
}

//
// Search time
//
$previous_days = array(0, 1, 7, 14, 30, 90, 180, 364);
$previous_days_text = array($lang['All_Posts'], $lang['1_Day'], $lang['7_Days'], $lang['2_Weeks'], $lang['1_Month'], $lang['3_Months'], $lang['6_Months'], $lang['1_Year']);

$s_time = '';
for($i = 0; $i < count($previous_days); $i++)
{
	$selected = ( $topic_days == $previous_days[$i] ) ? ' selected="selected"' : '';
	$s_time .= '<option value="' . $previous_days[$i] . '"' . $selected . '>' . $previous_days_text[$i] . '</option>';
}

//
// Output the basic page
//
$page_title = $lang['Search'];
include($phpbb_root_path . 'includes/page_header.'.$phpEx);

$template->set_filenames(array(
	'body' => 'search_body.tpl')
);
make_jumpbox('viewforum.'.$phpEx);

$template->assign_vars(array(
	'L_SEARCH_QUERY' => $lang['Search_query'], 
	'L_SEARCH_OPTIONS' => $lang['Search_options'], 
	'L_SEARCH_KEYWORDS' => $lang['Search_keywords'], 
	'L_SEARCH_KEYWORDS_EXPLAIN' => $lang['Search_keywords_explain'], 
	'L_SEARCH_AUTHOR' => $lang['Search_author'],
	'L_SEARCH_AUTHOR_EXPLAIN' => $lang['Search_author_explain'],
	// Start Advanced IP Tools Pack MOD
	'L_SEARCH_IP' => $lang['Search_ip'],
	'L_SEARCH_IP_EXPLAIN' => $lang['Search_ip_explain'],
	// End Advanced IP Tools Pack MOD 
	'L_SEARCH_ANY_TERMS' => $lang['Search_for_any'],
	'L_SEARCH_ALL_TERMS' => $lang['Search_for_all'], 
	'L_SEARCH_MESSAGE_ONLY' => $lang['Search_msg_only'], 
	'L_SEARCH_MESSAGE_TITLE' => $lang['Search_title_msg'], 
	'L_CATEGORY' => $lang['Category'], 
	'L_RETURN_FIRST' => $lang['Return_first'],
	'L_CHARACTERS' => $lang['characters_posts'], 
	'L_SORT_BY' => $lang['Sort_by'],
	'L_SORT_ASCENDING' => $lang['Sort_Ascending'],
	'L_SORT_DESCENDING' => $lang['Sort_Descending'],
	'L_SEARCH_PREVIOUS' => $lang['Search_previous'], 
	'L_DISPLAY_RESULTS' => $lang['Display_results'], 
	'L_FORUM' => $lang['Forum'],
	'L_TOPICS' => $lang['Topics'],
	'L_POSTS' => $lang['Posts'],
    'CTVALID' => $ctrack_forumid,

	'S_SEARCH_ACTION' => append_sid("search.$phpEx?mode=results"),
	'S_CHARACTER_OPTIONS' => $s_characters,
	'S_FORUM_OPTIONS' => $s_forums, 
	'S_CATEGORY_OPTIONS' => $s_categories, 
	'S_TIME_OPTIONS' => $s_time, 
	'S_SORT_OPTIONS' => $s_sort_by,
	'S_HIDDEN_FIELDS' => '')
);

$template->pparse('body');

include($phpbb_root_path . 'includes/page_tail.'.$phpEx);

?>