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