punbb/search.php
changeset 0 f9ffdbd96607
child 2 a8a21e1c7afa
equal deleted inserted replaced
-1:000000000000 0:f9ffdbd96607
       
     1 <?php
       
     2 /***********************************************************************
       
     3 
       
     4   Copyright (C) 2002-2005  Rickard Andersson (rickard@punbb.org)
       
     5 
       
     6   This file is part of PunBB.
       
     7 
       
     8   PunBB is free software; you can redistribute it and/or modify it
       
     9   under the terms of the GNU General Public License as published
       
    10   by the Free Software Foundation; either version 2 of the License,
       
    11   or (at your option) any later version.
       
    12 
       
    13   PunBB is distributed in the hope that it will be useful, but
       
    14   WITHOUT ANY WARRANTY; without even the implied warranty of
       
    15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
       
    16   GNU General Public License for more details.
       
    17 
       
    18   You should have received a copy of the GNU General Public License
       
    19   along with this program; if not, write to the Free Software
       
    20   Foundation, Inc., 59 Temple Place, Suite 330, Boston,
       
    21   MA  02111-1307  USA
       
    22 
       
    23 ************************************************************************/
       
    24 
       
    25 
       
    26 // The contents of this file are very much inspired by the file search.php
       
    27 // from the phpBB Group forum software phpBB2 (http://www.phpbb.com).
       
    28 
       
    29 
       
    30 define('PUN_ROOT', './');
       
    31 require PUN_ROOT.'include/common.php';
       
    32 
       
    33 
       
    34 // Load the search.php language file
       
    35 require PUN_ROOT.'lang/'.$pun_user['language'].'/search.php';
       
    36 
       
    37 
       
    38 if ($pun_user['g_read_board'] == '0')
       
    39 	message($lang_common['No view']);
       
    40 else if ($pun_user['g_search'] == '0')
       
    41 	message($lang_search['No search permission']);
       
    42 
       
    43 
       
    44 // Detect two byte character sets
       
    45 $multibyte = (isset($lang_common['lang_multibyte']) && $lang_common['lang_multibyte']) ? true : false;
       
    46 
       
    47 
       
    48 // Figure out what to do :-)
       
    49 if (isset($_GET['action']) || isset($_GET['search_id']))
       
    50 {
       
    51 	$action = (isset($_GET['action'])) ? $_GET['action'] : null;
       
    52 	$forum = (isset($_GET['forum'])) ? intval($_GET['forum']) : -1;
       
    53 	$sort_dir = (isset($_GET['sort_dir'])) ? (($_GET['sort_dir'] == 'DESC') ? 'DESC' : 'ASC') : 'DESC';
       
    54 	if (isset($search_id)) unset($search_id);
       
    55 
       
    56 	// If a search_id was supplied
       
    57 	if (isset($_GET['search_id']))
       
    58 	{
       
    59 		$search_id = intval($_GET['search_id']);
       
    60 		if ($search_id < 1)
       
    61 			message($lang_common['Bad request']);
       
    62 	}
       
    63 	// If it's a regular search (keywords and/or author)
       
    64 	else if ($action == 'search')
       
    65 	{
       
    66 		$keywords = (isset($_GET['keywords'])) ? strtolower(trim($_GET['keywords'])) : null;
       
    67 		$author = (isset($_GET['author'])) ? strtolower(trim($_GET['author'])) : null;
       
    68 
       
    69 		if (preg_match('#^[\*%]+$#', $keywords) || strlen(str_replace(array('*', '%'), '', $keywords)) < 3)
       
    70 			$keywords = '';
       
    71 
       
    72 		if (preg_match('#^[\*%]+$#', $author) || strlen(str_replace(array('*', '%'), '', $author)) < 3)
       
    73 			$author = '';
       
    74 
       
    75 		if (!$keywords && !$author)
       
    76 			message($lang_search['No terms']);
       
    77 
       
    78 		if ($author)
       
    79 			$author = str_replace('*', '%', $author);
       
    80 
       
    81 		$show_as = (isset($_GET['show_as'])) ? $_GET['show_as'] : 'posts';
       
    82 		$sort_by = (isset($_GET['sort_by'])) ? intval($_GET['sort_by']) : null;
       
    83 		$search_in = (!isset($_GET['search_in']) || $_GET['search_in'] == 'all') ? 0 : (($_GET['search_in'] == 'message') ? 1 : -1);
       
    84 	}
       
    85 	// If it's a user search (by id)
       
    86 	else if ($action == 'show_user')
       
    87 	{
       
    88 		$user_id = intval($_GET['user_id']);
       
    89 		if ($user_id < 2)
       
    90 			message($lang_common['Bad request']);
       
    91 	}
       
    92 	else
       
    93 	{
       
    94 		if ($action != 'show_new' && $action != 'show_24h' && $action != 'show_unanswered' && $action != 'show_subscriptions')
       
    95 			message($lang_common['Bad request']);
       
    96 	}
       
    97 
       
    98 
       
    99 	// If a valid search_id was supplied we attempt to fetch the search results from the db
       
   100 	if (isset($search_id))
       
   101 	{
       
   102 		$ident = ($pun_user['is_guest']) ? get_remote_address() : $pun_user['username'];
       
   103 
       
   104 		$result = $db->query('SELECT search_data FROM '.$db->prefix.'search_cache WHERE id='.$search_id.' AND ident=\''.$db->escape($ident).'\'') or error('Unable to fetch search results', __FILE__, __LINE__, $db->error());
       
   105 		if ($row = $db->fetch_assoc($result))
       
   106 		{
       
   107 			$temp = unserialize($row['search_data']);
       
   108 
       
   109 			$search_results = $temp['search_results'];
       
   110 			$num_hits = $temp['num_hits'];
       
   111 			$sort_by = $temp['sort_by'];
       
   112 			$sort_dir = $temp['sort_dir'];
       
   113 			$show_as = $temp['show_as'];
       
   114 
       
   115 			unset($temp);
       
   116 		}
       
   117 		else
       
   118 			message($lang_search['No hits']);
       
   119 	}
       
   120 	else
       
   121 	{
       
   122 		$keyword_results = $author_results = array();
       
   123 
       
   124 		// Search a specific forum?
       
   125 		$forum_sql = ($forum != -1 || ($forum == -1 && $pun_config['o_search_all_forums'] == '0')) ? ' AND t.forum_id = '.$forum : '';
       
   126 
       
   127 		if (!empty($author) || !empty($keywords))
       
   128 		{
       
   129 			// If it's a search for keywords
       
   130 			if ($keywords)
       
   131 			{
       
   132 				$stopwords = (array)@file(PUN_ROOT.'lang/'.$pun_user['language'].'/stopwords.txt');
       
   133 				$stopwords = array_map('trim', $stopwords);
       
   134 
       
   135 				// Are we searching for multibyte charset text?
       
   136 				if ($multibyte)
       
   137 				{
       
   138 					// Strip out excessive whitespace
       
   139 					$keywords = trim(preg_replace('#\s+#', ' ', $keywords));
       
   140 
       
   141 					$keywords_array = explode(' ', $keywords);
       
   142 				}
       
   143 				else
       
   144 				{
       
   145 					// Filter out non-alphabetical chars
       
   146 					$noise_match = array('^', '$', '&', '(', ')', '<', '>', '`', '\'', '"', '|', ',', '@', '_', '?', '%', '~', '[', ']', '{', '}', ':', '\\', '/', '=', '#', '\'', ';', '!', '¤');
       
   147 					$noise_replace = array(' ', ' ', ' ', ' ', ' ', ' ', ' ', '',  '',   ' ', ' ', ' ', ' ', '',  ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', '' ,  ' ', ' ', ' ', ' ',  ' ', ' ', ' ');
       
   148 					$keywords = str_replace($noise_match, $noise_replace, $keywords);
       
   149 
       
   150 					// Strip out excessive whitespace
       
   151 					$keywords = trim(preg_replace('#\s+#', ' ', $keywords));
       
   152 
       
   153 					// Fill an array with all the words
       
   154 					$keywords_array = explode(' ', $keywords);
       
   155 
       
   156 					if (empty($keywords_array))
       
   157 						message($lang_search['No hits']);
       
   158 
       
   159 					while (list($i, $word) = @each($keywords_array))
       
   160 					{
       
   161 						$num_chars = pun_strlen($word);
       
   162 
       
   163 						if ($num_chars < 3 || $num_chars > 20 || in_array($word, $stopwords))
       
   164 							unset($keywords_array[$i]);
       
   165 					}
       
   166 
       
   167 					// Should we search in message body or topic subject specifically?
       
   168 					$search_in_cond = ($search_in) ? (($search_in > 0) ? ' AND m.subject_match = 0' : ' AND m.subject_match = 1') : '';
       
   169 				}
       
   170 
       
   171 				$word_count = 0;
       
   172 				$match_type = 'and';
       
   173 				$result_list = array();
       
   174 				@reset($keywords_array);
       
   175 				while (list(, $cur_word) = @each($keywords_array))
       
   176 				{
       
   177 					switch ($cur_word)
       
   178 					{
       
   179 						case 'and':
       
   180 						case 'or':
       
   181 						case 'not':
       
   182 							$match_type = $cur_word;
       
   183 							break;
       
   184 
       
   185 						default:
       
   186 						{
       
   187 							// Are we searching for multibyte charset text?
       
   188 							if ($multibyte)
       
   189 							{
       
   190 								$cur_word = $db->escape('%'.str_replace('*', '', $cur_word).'%');
       
   191 								$cur_word_like = ($db_type == 'pgsql') ? 'ILIKE \''.$cur_word.'\'' : 'LIKE \''.$cur_word.'\'';
       
   192 
       
   193 								if ($search_in > 0)
       
   194 									$sql = 'SELECT id FROM '.$db->prefix.'posts WHERE message '.$cur_word_like;
       
   195 								else if ($search_in < 0)
       
   196 									$sql = 'SELECT p.id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id WHERE t.subject '.$cur_word_like.' GROUP BY p.id, t.id';
       
   197 								else
       
   198 									$sql = 'SELECT p.id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id WHERE p.message '.$cur_word_like.' OR t.subject '.$cur_word_like.' GROUP BY p.id, t.id';
       
   199 							}
       
   200 							else
       
   201 							{
       
   202 								$cur_word = str_replace('*', '%', $cur_word);
       
   203 								$sql = 'SELECT m.post_id FROM '.$db->prefix.'search_words AS w INNER JOIN '.$db->prefix.'search_matches AS m ON m.word_id = w.id WHERE w.word LIKE \''.$cur_word.'\''.$search_in_cond;
       
   204 							}
       
   205 
       
   206 							$result = $db->query($sql, true) or error('Unable to search for posts', __FILE__, __LINE__, $db->error());
       
   207 
       
   208 							$row = array();
       
   209 							while ($temp = $db->fetch_row($result))
       
   210 							{
       
   211 								$row[$temp[0]] = 1;
       
   212 
       
   213 								if (!$word_count)
       
   214 									$result_list[$temp[0]] = 1;
       
   215 								else if ($match_type == 'or')
       
   216 									$result_list[$temp[0]] = 1;
       
   217 								else if ($match_type == 'not')
       
   218 									$result_list[$temp[0]] = 0;
       
   219 							}
       
   220 
       
   221 							if ($match_type == 'and' && $word_count)
       
   222 							{
       
   223 								@reset($result_list);
       
   224 								while (list($post_id,) = @each($result_list))
       
   225 								{
       
   226 									if (!isset($row[$post_id]))
       
   227 										$result_list[$post_id] = 0;
       
   228 								}
       
   229 							}
       
   230 
       
   231 							++$word_count;
       
   232 							$db->free_result($result);
       
   233 
       
   234 							break;
       
   235 						}
       
   236 					}
       
   237 				}
       
   238 
       
   239 				@reset($result_list);
       
   240 				while (list($post_id, $matches) = @each($result_list))
       
   241 				{
       
   242 					if ($matches)
       
   243 						$keyword_results[] = $post_id;
       
   244 				}
       
   245 
       
   246 				unset($result_list);
       
   247 			}
       
   248 
       
   249 			// If it's a search for author name (and that author name isn't Guest)
       
   250 			if ($author && strcasecmp($author, 'Guest') && strcasecmp($author, $lang_common['Guest']))
       
   251 			{
       
   252 				switch ($db_type)
       
   253 				{
       
   254 					case 'pgsql':
       
   255 						$result = $db->query('SELECT id FROM '.$db->prefix.'users WHERE username ILIKE \''.$db->escape($author).'\'') or error('Unable to fetch users', __FILE__, __LINE__, $db->error());
       
   256 						break;
       
   257 
       
   258 					default:
       
   259 						$result = $db->query('SELECT id FROM '.$db->prefix.'users WHERE username LIKE \''.$db->escape($author).'\'') or error('Unable to fetch users', __FILE__, __LINE__, $db->error());
       
   260 						break;
       
   261 				}
       
   262 
       
   263 				if ($db->num_rows($result))
       
   264 				{
       
   265 					$user_ids = '';
       
   266 					while ($row = $db->fetch_row($result))
       
   267 						$user_ids .= (($user_ids != '') ? ',' : '').$row[0];
       
   268 
       
   269 					$result = $db->query('SELECT id FROM '.$db->prefix.'posts WHERE poster_id IN('.$user_ids.')') or error('Unable to fetch matched posts list', __FILE__, __LINE__, $db->error());
       
   270 
       
   271 					$search_ids = array();
       
   272 					while ($row = $db->fetch_row($result))
       
   273 						$author_results[] = $row[0];
       
   274 
       
   275 					$db->free_result($result);
       
   276 				}
       
   277 			}
       
   278 
       
   279 
       
   280 			if ($author && $keywords)
       
   281 			{
       
   282 				// If we searched for both keywords and author name we want the intersection between the results
       
   283 				$search_ids = array_intersect($keyword_results, $author_results);
       
   284 				unset($keyword_results, $author_results);
       
   285 			}
       
   286 			else if ($keywords)
       
   287 				$search_ids = $keyword_results;
       
   288 			else
       
   289 				$search_ids = $author_results;
       
   290 
       
   291 			$num_hits = count($search_ids);
       
   292 			if (!$num_hits)
       
   293 				message($lang_search['No hits']);
       
   294 
       
   295 
       
   296 			if ($show_as == 'topics')
       
   297 			{
       
   298 				$result = $db->query('SELECT t.id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND p.id IN('.implode(',', $search_ids).')'.$forum_sql.' GROUP BY t.id', true) or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   299 
       
   300 				$search_ids = array();
       
   301 				while ($row = $db->fetch_row($result))
       
   302 					$search_ids[] = $row[0];
       
   303 
       
   304 				$db->free_result($result);
       
   305 
       
   306 				$num_hits = count($search_ids);
       
   307 			}
       
   308 			else
       
   309 			{
       
   310 				$result = $db->query('SELECT p.id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND p.id IN('.implode(',', $search_ids).')'.$forum_sql, true) or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   311 
       
   312 				$search_ids = array();
       
   313 				while ($row = $db->fetch_row($result))
       
   314 					$search_ids[] = $row[0];
       
   315 
       
   316 				$db->free_result($result);
       
   317 
       
   318 				$num_hits = count($search_ids);
       
   319 			}
       
   320 		}
       
   321 		else if ($action == 'show_new' || $action == 'show_24h' || $action == 'show_user' || $action == 'show_subscriptions' || $action == 'show_unanswered')
       
   322 		{
       
   323 			// If it's a search for new posts
       
   324 			if ($action == 'show_new')
       
   325 			{
       
   326 				if ($pun_user['is_guest'])
       
   327 					message($lang_common['No permission']);
       
   328 
       
   329 				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.last_post>'.$pun_user['last_visit'].' AND t.moved_to IS NULL') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   330 				$num_hits = $db->num_rows($result);
       
   331 
       
   332 				if (!$num_hits)
       
   333 					message($lang_search['No new posts']);
       
   334 			}
       
   335 			// If it's a search for todays posts
       
   336 			else if ($action == 'show_24h')
       
   337 			{
       
   338 				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.last_post>'.(time() - 86400).' AND t.moved_to IS NULL') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   339 				$num_hits = $db->num_rows($result);
       
   340 
       
   341 				if (!$num_hits)
       
   342 					message($lang_search['No recent posts']);
       
   343 			}
       
   344 			// If it's a search for posts by a specific user ID
       
   345 			else if ($action == 'show_user')
       
   346 			{
       
   347 				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'posts AS p ON t.id=p.topic_id INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND p.poster_id='.$user_id.' GROUP BY t.id') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   348 				$num_hits = $db->num_rows($result);
       
   349 
       
   350 				if (!$num_hits)
       
   351 					message($lang_search['No user posts']);
       
   352 			}
       
   353 			// If it's a search for subscribed topics
       
   354 			else if ($action == 'show_subscriptions')
       
   355 			{
       
   356 				if ($pun_user['is_guest'])
       
   357 					message($lang_common['Bad request']);
       
   358 
       
   359 				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'subscriptions AS s ON (t.id=s.topic_id AND s.user_id='.$pun_user['id'].') INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1)') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   360 				$num_hits = $db->num_rows($result);
       
   361 
       
   362 				if (!$num_hits)
       
   363 					message($lang_search['No subscriptions']);
       
   364 			}
       
   365 			// If it's a search for unanswered posts
       
   366 			else
       
   367 			{
       
   368 				$result = $db->query('SELECT t.id FROM '.$db->prefix.'topics AS t INNER JOIN '.$db->prefix.'forums AS f ON f.id=t.forum_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND t.num_replies=0 AND t.moved_to IS NULL') or error('Unable to fetch topic list', __FILE__, __LINE__, $db->error());
       
   369 				$num_hits = $db->num_rows($result);
       
   370 
       
   371 				if (!$num_hits)
       
   372 					message($lang_search['No unanswered']);
       
   373 			}
       
   374 
       
   375 			// We want to sort things after last post
       
   376 			$sort_by = 4;
       
   377 
       
   378 			$search_ids = array();
       
   379 			while ($row = $db->fetch_row($result))
       
   380 				$search_ids[] = $row[0];
       
   381 
       
   382 			$db->free_result($result);
       
   383 
       
   384 			$show_as = 'topics';
       
   385 		}
       
   386 		else
       
   387 			message($lang_common['Bad request']);
       
   388 
       
   389 
       
   390 		// Prune "old" search results
       
   391 		$old_searches = array();
       
   392 		$result = $db->query('SELECT ident FROM '.$db->prefix.'online') or error('Unable to fetch online list', __FILE__, __LINE__, $db->error());
       
   393 
       
   394 		if ($db->num_rows($result))
       
   395 		{
       
   396 			while ($row = $db->fetch_row($result))
       
   397 				$old_searches[] = '\''.$db->escape($row[0]).'\'';
       
   398 
       
   399 			$db->query('DELETE FROM '.$db->prefix.'search_cache WHERE ident NOT IN('.implode(',', $old_searches).')') or error('Unable to delete search results', __FILE__, __LINE__, $db->error());
       
   400 		}
       
   401 
       
   402 		// Final search results
       
   403 		$search_results = implode(',', $search_ids);
       
   404 
       
   405 		// Fill an array with our results and search properties
       
   406 		$temp['search_results'] = $search_results;
       
   407 		$temp['num_hits'] = $num_hits;
       
   408 		$temp['sort_by'] = $sort_by;
       
   409 		$temp['sort_dir'] = $sort_dir;
       
   410 		$temp['show_as'] = $show_as;
       
   411 		$temp = serialize($temp);
       
   412 		$search_id = mt_rand(1, 2147483647);
       
   413 
       
   414 		$ident = ($pun_user['is_guest']) ? get_remote_address() : $pun_user['username'];
       
   415 
       
   416 		$db->query('INSERT INTO '.$db->prefix.'search_cache (id, ident, search_data) VALUES('.$search_id.', \''.$db->escape($ident).'\', \''.$db->escape($temp).'\')') or error('Unable to insert search results', __FILE__, __LINE__, $db->error());
       
   417 
       
   418 		if ($action != 'show_new' && $action != 'show_24h')
       
   419 		{
       
   420 			$db->end_transaction();
       
   421 			$db->close();
       
   422 
       
   423 			// Redirect the user to the cached result page
       
   424 			header('Location: search.php?search_id='.$search_id);
       
   425 			exit;
       
   426 		}
       
   427 	}
       
   428 
       
   429 
       
   430 	// Fetch results to display
       
   431 	if ($search_results != '')
       
   432 	{
       
   433 		switch ($sort_by)
       
   434 		{
       
   435 			case 1:
       
   436 				$sort_by_sql = ($show_as == 'topics') ? 't.poster' : 'p.poster';
       
   437 				break;
       
   438 
       
   439 			case 2:
       
   440 				$sort_by_sql = 't.subject';
       
   441 				break;
       
   442 
       
   443 			case 3:
       
   444 				$sort_by_sql = 't.forum_id';
       
   445 				break;
       
   446 
       
   447 			case 4:
       
   448 				$sort_by_sql = 't.last_post';
       
   449 				break;
       
   450 
       
   451 			default:
       
   452 				$sort_by_sql = ($show_as == 'topics') ? 't.posted' : 'p.posted';
       
   453 				break;
       
   454 		}
       
   455 
       
   456 		if ($show_as == 'posts')
       
   457 		{
       
   458 			$substr_sql = ($db_type != 'sqlite') ? 'SUBSTRING' : 'SUBSTR';
       
   459 			$sql = 'SELECT p.id AS pid, p.poster AS pposter, p.posted AS pposted, p.poster_id, '.$substr_sql.'(p.message, 1, 1000) AS message, t.id AS tid, t.poster, t.subject, t.last_post, t.last_post_id, t.last_poster, t.num_replies, t.forum_id FROM '.$db->prefix.'posts AS p INNER JOIN '.$db->prefix.'topics AS t ON t.id=p.topic_id WHERE p.id IN('.$search_results.') ORDER BY '.$sort_by_sql;
       
   460 		}
       
   461 		else
       
   462 			$sql = 'SELECT t.id AS tid, t.poster, t.subject, t.last_post, t.last_post_id, t.last_poster, t.num_replies, t.closed, t.forum_id FROM '.$db->prefix.'topics AS t WHERE t.id IN('.$search_results.') ORDER BY '.$sort_by_sql;
       
   463 
       
   464 
       
   465 		// Determine the topic or post offset (based on $_GET['p'])
       
   466 		$per_page = ($show_as == 'posts') ? $pun_user['disp_posts'] : $pun_user['disp_topics'];
       
   467 		$num_pages = ceil($num_hits / $per_page);
       
   468 
       
   469 		$p = (!isset($_GET['p']) || $_GET['p'] <= 1 || $_GET['p'] > $num_pages) ? 1 : $_GET['p'];
       
   470 		$start_from = $per_page * ($p - 1);
       
   471 
       
   472 		// Generate paging links
       
   473 		$paging_links = $lang_common['Pages'].': '.paginate($num_pages, $p, 'search.php?search_id='.$search_id);
       
   474 
       
   475 
       
   476 		$sql .= ' '.$sort_dir.' LIMIT '.$start_from.', '.$per_page;
       
   477 
       
   478 		$result = $db->query($sql) or error('Unable to fetch search results', __FILE__, __LINE__, $db->error());
       
   479 
       
   480 		$search_set = array();
       
   481 		while ($row = $db->fetch_assoc($result))
       
   482 			$search_set[] = $row;
       
   483 
       
   484 		$db->free_result($result);
       
   485 
       
   486 		$page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_search['Search results'];
       
   487 		require PUN_ROOT.'header.php';
       
   488 
       
   489 
       
   490 ?>
       
   491 <div class="linkst">
       
   492 	<div class="inbox">
       
   493 		<p class="pagelink"><?php echo $paging_links ?></p>
       
   494 	</div>
       
   495 </div>
       
   496 
       
   497 <?php
       
   498 
       
   499 		//Set background switching on for show as posts
       
   500 		$bg_switch = true;
       
   501 
       
   502 		if ($show_as == 'topics')
       
   503 		{
       
   504 
       
   505 ?>
       
   506 <div id="vf" class="blocktable">
       
   507 	<h2><span><?php echo $lang_search['Search results']; ?></span></h2>
       
   508 	<div class="box">
       
   509 		<div class="inbox">
       
   510 			<table cellspacing="0">
       
   511 			<thead>
       
   512 				<tr>
       
   513 					<th class="tcl" scope="col"><?php echo $lang_common['Topic']; ?></th>
       
   514 					<th class="tc2" scope="col"><?php echo $lang_common['Forum'] ?></th>
       
   515 					<th class="tc3" scope="col"><?php echo $lang_common['Replies'] ?></th>
       
   516 					<th class="tcr" scope="col"><?php echo $lang_common['Last post'] ?></th>
       
   517 				</tr>
       
   518 			</thead>
       
   519 			<tbody>
       
   520 <?php
       
   521 
       
   522 		}
       
   523 
       
   524 		// Fetch the list of forums
       
   525 		$result = $db->query('SELECT id, forum_name FROM '.$db->prefix.'forums') or error('Unable to fetch forum list', __FILE__, __LINE__, $db->error());
       
   526 
       
   527 		$forum_list = array();
       
   528 		while ($forum_list[] = $db->fetch_row($result))
       
   529 			;
       
   530 
       
   531 		// Finally, lets loop through the results and output them
       
   532 		for ($i = 0; $i < count($search_set); ++$i)
       
   533 		{
       
   534 			@reset($forum_list);
       
   535 			while (list(, $temp) = @each($forum_list))
       
   536 			{
       
   537 				if ($temp[0] == $search_set[$i]['forum_id'])
       
   538 					$forum = '<a href="viewforum.php?id='.$temp[0].'">'.pun_htmlspecialchars($temp[1]).'</a>';
       
   539 			}
       
   540 
       
   541 			if ($pun_config['o_censoring'] == '1')
       
   542 				$search_set[$i]['subject'] = censor_words($search_set[$i]['subject']);
       
   543 
       
   544 
       
   545 			if ($show_as == 'posts')
       
   546 			{
       
   547 				$icon = '<div class="icon"><div class="nosize">'.$lang_common['Normal icon'].'</div></div>'."\n";
       
   548 				$subject = '<a href="viewtopic.php?id='.$search_set[$i]['tid'].'">'.pun_htmlspecialchars($search_set[$i]['subject']).'</a>';
       
   549 
       
   550 				if (!$pun_user['is_guest'] && $search_set[$i]['last_post'] > $pun_user['last_visit'])
       
   551 					$icon = '<div class="icon inew"><div class="nosize">'.$lang_common['New icon'].'</div></div>'."\n";
       
   552 
       
   553 
       
   554 				if ($pun_config['o_censoring'] == '1')
       
   555 					$search_set[$i]['message'] = censor_words($search_set[$i]['message']);
       
   556 
       
   557 				$message = str_replace("\n", '<br />', pun_htmlspecialchars($search_set[$i]['message']));
       
   558 				$pposter = pun_htmlspecialchars($search_set[$i]['pposter']);
       
   559 
       
   560 				if ($search_set[$i]['poster_id'] > 1)
       
   561 					$pposter = '<strong><a href="profile.php?id='.$search_set[$i]['poster_id'].'">'.$pposter.'</a></strong>';
       
   562 
       
   563 				if (pun_strlen($message) >= 1000)
       
   564 					$message .= ' &hellip;';
       
   565 
       
   566 				$vtpost1 = ($i == 0) ? ' vtp1' : '';
       
   567 
       
   568 				// Switch the background color for every message.
       
   569 				$bg_switch = ($bg_switch) ? $bg_switch = false : $bg_switch = true;
       
   570 				$vtbg = ($bg_switch) ? ' rowodd' : ' roweven';
       
   571 
       
   572 
       
   573 ?>
       
   574 <div class="blockpost searchposts<?php echo $vtbg ?>">
       
   575 	<h2><?php echo $forum ?>&nbsp;&raquo;&nbsp;<?php echo $subject ?>&nbsp;&raquo;&nbsp;<a href="viewtopic.php?pid=<?php echo $search_set[$i]['pid'].'#p'.$search_set[$i]['pid'] ?>"><?php echo format_time($search_set[$i]['pposted']) ?></a></h2>
       
   576 	<div class="box">
       
   577 		<div class="inbox">
       
   578 			<div class="postleft">
       
   579 				<dl>
       
   580 					<dt><?php echo $pposter ?></dt>
       
   581 					<dd>Replies: <?php echo $search_set[$i]['num_replies'] ?></dd>
       
   582 					<dd><?php echo $icon; ?></dd>
       
   583 					<dd><p class="clearb"><a href="viewtopic.php?pid=<?php echo $search_set[$i]['pid'].'#p'.$search_set[$i]['pid'] ?>"><?php echo $lang_search['Go to post'] ?></a></p></dd>
       
   584 				</dl>
       
   585 			</div>
       
   586 			<div class="postright">
       
   587 				<div class="postmsg">
       
   588 					<p><?php echo $message ?></p>
       
   589 				</div>
       
   590 			</div>
       
   591 			<div class="clearer"></div>
       
   592 		</div>
       
   593 	</div>
       
   594 </div>
       
   595 <?php
       
   596 
       
   597 			}
       
   598 			else
       
   599 			{
       
   600 				$icon = '<div class="icon"><div class="nosize">'.$lang_common['Normal icon'].'</div></div>'."\n";
       
   601 
       
   602 				$icon_text = $lang_common['Normal icon'];
       
   603 				$item_status = '';
       
   604 				$icon_type = 'icon';
       
   605 
       
   606 
       
   607 				$subject = '<a href="viewtopic.php?id='.$search_set[$i]['tid'].'">'.pun_htmlspecialchars($search_set[$i]['subject']).'</a> <span class="byuser">'.$lang_common['by'].'&nbsp;'.pun_htmlspecialchars($search_set[$i]['poster']).'</span>';
       
   608 
       
   609 				if ($search_set[$i]['closed'] != '0')
       
   610 				{
       
   611 					$icon_text = $lang_common['Closed icon'];
       
   612 					$item_status = 'iclosed';
       
   613 				}
       
   614 
       
   615 				if (!$pun_user['is_guest'] && $search_set[$i]['last_post'] > $pun_user['last_visit'])
       
   616 				{
       
   617 					$icon_text .= ' '.$lang_common['New icon'];
       
   618 					$item_status .= ' inew';
       
   619 					$icon_type = 'icon inew';
       
   620 					$subject = '<strong>'.$subject.'</strong>';
       
   621 					$subject_new_posts = '<span class="newtext">[&nbsp;<a href="viewtopic.php?id='.$search_set[$i]['tid'].'&amp;action=new" title="'.$lang_common['New posts info'].'">'.$lang_common['New posts'].'</a>&nbsp;]</span>';
       
   622 				}
       
   623 				else
       
   624 					$subject_new_posts = null;
       
   625 
       
   626 				$num_pages_topic = ceil(($search_set[$i]['num_replies'] + 1) / $pun_user['disp_posts']);
       
   627 
       
   628 				if ($num_pages_topic > 1)
       
   629 					$subject_multipage = '[ '.paginate($num_pages_topic, -1, 'viewtopic.php?id='.$search_set[$i]['tid']).' ]';
       
   630 				else
       
   631 					$subject_multipage = null;
       
   632 
       
   633 				// Should we show the "New posts" and/or the multipage links?
       
   634 				if (!empty($subject_new_posts) || !empty($subject_multipage))
       
   635 				{
       
   636 					$subject .= '&nbsp; '.(!empty($subject_new_posts) ? $subject_new_posts : '');
       
   637 					$subject .= !empty($subject_multipage) ? ' '.$subject_multipage : '';
       
   638 				}
       
   639 
       
   640 ?>
       
   641 				<tr<?php if ($item_status != '') echo ' class="'.trim($item_status).'"'; ?>>
       
   642 					<td class="tcl">
       
   643 						<div class="intd">
       
   644 							<div class="<?php echo $icon_type ?>"><div class="nosize"><?php echo trim($icon_text) ?></div></div>
       
   645 							<div class="tclcon">
       
   646 								<?php echo $subject."\n" ?>
       
   647 							</div>
       
   648 						</div>
       
   649 					</td>
       
   650 					<td class="tc2"><?php echo $forum ?></td>
       
   651 					<td class="tc3"><?php echo $search_set[$i]['num_replies'] ?></td>
       
   652 					<td class="tcr"><?php echo '<a href="viewtopic.php?pid='.$search_set[$i]['last_post_id'].'#p'.$search_set[$i]['last_post_id'].'">'.format_time($search_set[$i]['last_post']).'</a> '.$lang_common['by'].'&nbsp;'.pun_htmlspecialchars($search_set[$i]['last_poster']) ?></td>
       
   653 				</tr>
       
   654 <?php
       
   655 
       
   656 			}
       
   657 		}
       
   658 
       
   659 		if ($show_as == 'topics')
       
   660 			echo "\t\t\t".'</tbody>'."\n\t\t\t".'</table>'."\n\t\t".'</div>'."\n\t".'</div>'."\n".'</div>'."\n\n";
       
   661 
       
   662 ?>
       
   663 <div class="<?php echo ($show_as == 'topics') ? 'linksb' : 'postlinksb'; ?>">
       
   664 	<div class="inbox">
       
   665 		<p class="pagelink"><?php echo $paging_links ?></p>
       
   666 	</div>
       
   667 </div>
       
   668 <?php
       
   669 
       
   670 		$footer_style = 'search';
       
   671 		require PUN_ROOT.'footer.php';
       
   672 	}
       
   673 	else
       
   674 		message($lang_search['No hits']);
       
   675 }
       
   676 
       
   677 
       
   678 $page_title = pun_htmlspecialchars($pun_config['o_board_title']).' / '.$lang_search['Search'];
       
   679 $focus_element = array('search', 'keywords');
       
   680 require PUN_ROOT.'header.php';
       
   681 
       
   682 ?>
       
   683 <div id="searchform" class="blockform">
       
   684 	<h2><span><?php echo $lang_search['Search'] ?></span></h2>
       
   685 	<div class="box">
       
   686 		<form id="search" method="get" action="search.php">
       
   687 			<div class="inform">
       
   688 				<fieldset>
       
   689 					<legend><?php echo $lang_search['Search criteria legend'] ?></legend>
       
   690 					<div class="infldset">
       
   691 						<input type="hidden" name="action" value="search" />
       
   692 						<label class="conl"><?php echo $lang_search['Keyword search'] ?><br /><input type="text" name="keywords" size="40" maxlength="100" /><br /></label>
       
   693 						<label class="conl"><?php echo $lang_search['Author search'] ?><br /><input id="author" type="text" name="author" size="25" maxlength="25" /><br /></label>
       
   694 						<p class="clearb"><?php echo $lang_search['Search info'] ?></p>
       
   695 					</div>
       
   696 				</fieldset>
       
   697 			</div>
       
   698 			<div class="inform">
       
   699 				<fieldset>
       
   700 					<legend><?php echo $lang_search['Search in legend'] ?></legend>
       
   701 					<div class="infldset">
       
   702 						<label class="conl"><?php echo $lang_search['Forum search'] ?>
       
   703 						<br /><select id="forum" name="forum">
       
   704 <?php
       
   705 
       
   706 if ($pun_config['o_search_all_forums'] == '1' || $pun_user['g_id'] < PUN_GUEST)
       
   707 	echo "\t\t\t\t\t\t\t".'<option value="-1">'.$lang_search['All forums'].'</option>'."\n";
       
   708 
       
   709 $result = $db->query('SELECT c.id AS cid, c.cat_name, f.id AS fid, f.forum_name, f.redirect_url FROM '.$db->prefix.'categories AS c INNER JOIN '.$db->prefix.'forums AS f ON c.id=f.cat_id LEFT JOIN '.$db->prefix.'forum_perms AS fp ON (fp.forum_id=f.id AND fp.group_id='.$pun_user['g_id'].') WHERE (fp.read_forum IS NULL OR fp.read_forum=1) AND f.redirect_url IS NULL ORDER BY c.disp_position, c.id, f.disp_position', true) or error('Unable to fetch category/forum list', __FILE__, __LINE__, $db->error());
       
   710 
       
   711 $cur_category = 0;
       
   712 while ($cur_forum = $db->fetch_assoc($result))
       
   713 {
       
   714 	if ($cur_forum['cid'] != $cur_category)	// A new category since last iteration?
       
   715 	{
       
   716 		if ($cur_category)
       
   717 			echo "\t\t\t\t\t\t\t".'</optgroup>'."\n";
       
   718 
       
   719 		echo "\t\t\t\t\t\t\t".'<optgroup label="'.pun_htmlspecialchars($cur_forum['cat_name']).'">'."\n";
       
   720 		$cur_category = $cur_forum['cid'];
       
   721 	}
       
   722 
       
   723 	echo "\t\t\t\t\t\t\t\t".'<option value="'.$cur_forum['fid'].'">'.pun_htmlspecialchars($cur_forum['forum_name']).'</option>'."\n";
       
   724 }
       
   725 
       
   726 ?>
       
   727 							</optgroup>
       
   728 						</select>
       
   729 						<br /></label>
       
   730 						<label class="conl"><?php echo $lang_search['Search in'] ?>
       
   731 						<br /><select id="search_in" name="search_in">
       
   732 							<option value="all"><?php echo $lang_search['Message and subject'] ?></option>
       
   733 							<option value="message"><?php echo $lang_search['Message only'] ?></option>
       
   734 							<option value="topic"><?php echo $lang_search['Topic only'] ?></option>
       
   735 						</select>
       
   736 						<br /></label>
       
   737 						<p class="clearb"><?php echo $lang_search['Search in info'] ?></p>
       
   738 					</div>
       
   739 				</fieldset>
       
   740 			</div>
       
   741 			<div class="inform">
       
   742 				<fieldset>
       
   743 					<legend><?php echo $lang_search['Search results legend'] ?></legend>
       
   744 					<div class="infldset">
       
   745 						<label class="conl"><?php echo $lang_search['Sort by'] ?>
       
   746 						<br /><select name="sort_by">
       
   747 							<option value="0"><?php echo $lang_search['Sort by post time'] ?></option>
       
   748 							<option value="1"><?php echo $lang_search['Sort by author'] ?></option>
       
   749 							<option value="2"><?php echo $lang_search['Sort by subject'] ?></option>
       
   750 							<option value="3"><?php echo $lang_search['Sort by forum'] ?></option>
       
   751 						</select>
       
   752 						<br /></label>
       
   753 						<label class="conl"><?php echo $lang_search['Sort order'] ?>
       
   754 						<br /><select name="sort_dir">
       
   755 							<option value="DESC"><?php echo $lang_search['Descending'] ?></option>
       
   756 							<option value="ASC"><?php echo $lang_search['Ascending'] ?></option>
       
   757 						</select>
       
   758 						<br /></label>
       
   759 						<label class="conl"><?php echo $lang_search['Show as'] ?>
       
   760 						<br /><select name="show_as">
       
   761 							<option value="topics"><?php echo $lang_search['Show as topics'] ?></option>
       
   762 							<option value="posts"><?php echo $lang_search['Show as posts'] ?></option>
       
   763 						</select>
       
   764 						<br /></label>
       
   765 						<p class="clearb"><?php echo $lang_search['Search results info'] ?></p>
       
   766 					</div>
       
   767 				</fieldset>
       
   768 			</div>
       
   769 			<p><input type="submit" name="search" value="<?php echo $lang_common['Submit'] ?>" accesskey="s" /></p>
       
   770 		</form>
       
   771 	</div>
       
   772 </div>
       
   773 <?php
       
   774 
       
   775 require PUN_ROOT.'footer.php';