PageRenderTime 58ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/forum/Sources/Search.php

https://github.com/leftnode/nooges.com
PHP | 2064 lines | 1620 code | 227 blank | 217 comment | 326 complexity | 75b58a541be1b184143474b02437da0e MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**********************************************************************************
  3. * Search.php *
  4. ***********************************************************************************
  5. * SMF: Simple Machines Forum *
  6. * Open-Source Project Inspired by Zef Hemel (zef@zefhemel.com) *
  7. * =============================================================================== *
  8. * Software Version: SMF 2.0 RC2 *
  9. * Software by: Simple Machines (http://www.simplemachines.org) *
  10. * Copyright 2006-2009 by: Simple Machines LLC (http://www.simplemachines.org) *
  11. * 2001-2006 by: Lewis Media (http://www.lewismedia.com) *
  12. * Support, News, Updates at: http://www.simplemachines.org *
  13. ***********************************************************************************
  14. * This program is free software; you may redistribute it and/or modify it under *
  15. * the terms of the provided license as published by Simple Machines LLC. *
  16. * *
  17. * This program is distributed in the hope that it is and will be useful, but *
  18. * WITHOUT ANY WARRANTIES; without even any implied warranty of MERCHANTABILITY *
  19. * or FITNESS FOR A PARTICULAR PURPOSE. *
  20. * *
  21. * See the "license.txt" file for details of the Simple Machines license. *
  22. * The latest version can always be found at http://www.simplemachines.org. *
  23. **********************************************************************************/
  24. if (!defined('SMF'))
  25. die('Hacking attempt...');
  26. /* These functions are here for searching, and they are:
  27. void PlushSearch1()
  28. - shows the screen to search forum posts (action=search), and uses the
  29. simple version if the simpleSearch setting is enabled.
  30. - uses the main sub template of the Search template.
  31. - uses the Search language file.
  32. - requires the search_posts permission.
  33. - decodes and loads search parameters given in the URL (if any).
  34. - the form redirects to index.php?action=search2.
  35. void PlushSearch2()
  36. - checks user input and searches the messages table for messages
  37. matching the query.
  38. - requires the search_posts permission.
  39. - uses the results sub template of the Search template.
  40. - uses the Search language file.
  41. - stores the results into the search cache.
  42. - show the results of the search query.
  43. array prepareSearchContext(bool reset = false)
  44. - callback function for the results sub template.
  45. - loads the necessary contextual data to show a search result.
  46. int searchSort(string $wordA, string $wordB)
  47. - callback function for usort used to sort the fulltext results.
  48. - passes sorting duty to the current API.
  49. */
  50. // This defines two version types for checking the API's are compatible with this version of SMF.
  51. $GLOBALS['search_versions'] = array(
  52. // This is the forum version but is repeated due to some people rewriting $forum_version.
  53. 'forum_version' => 'SMF 2.0 RC2',
  54. // This is the minimum version of SMF that an API could have been written for to work. (strtr to stop accidentally updating version on release)
  55. 'search_version' => strtr('SMF 2+0=Beta=2', array('+' => '.', '=' => ' ')),
  56. );
  57. // Ask the user what they want to search for.
  58. function PlushSearch1()
  59. {
  60. global $txt, $scripturl, $modSettings, $user_info, $context, $smcFunc, $sourcedir;
  61. // Is the load average too high to allow searching just now?
  62. if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
  63. fatal_lang_error('loadavg_search_disabled', false);
  64. loadLanguage('Search');
  65. // Don't load this in XML mode.
  66. if (!isset($_REQUEST['xml']))
  67. loadTemplate('Search');
  68. // Check the user's permissions.
  69. isAllowedTo('search_posts');
  70. // Link tree....
  71. $context['linktree'][] = array(
  72. 'url' => $scripturl . '?action=search',
  73. 'name' => $txt['search']
  74. );
  75. // This is hard coded maximum string length.
  76. $context['search_string_limit'] = 100;
  77. $context['require_verification'] = $user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']);
  78. if ($context['require_verification'])
  79. {
  80. require_once($sourcedir . '/Subs-Editor.php');
  81. $verificationOptions = array(
  82. 'id' => 'search',
  83. );
  84. $context['require_verification'] = create_control_verification($verificationOptions);
  85. $context['visual_verification_id'] = $verificationOptions['id'];
  86. }
  87. // If you got back from search2 by using the linktree, you get your original search parameters back.
  88. if (isset($_REQUEST['params']))
  89. {
  90. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  91. $context['search_params'] = array();
  92. foreach ($temp_params as $i => $data)
  93. {
  94. @list ($k, $v) = explode('|\'|', $data);
  95. $context['search_params'][$k] = $v;
  96. }
  97. if (isset($context['search_params']['brd']))
  98. $context['search_params']['brd'] = $context['search_params']['brd'] == '' ? array() : explode(',', $context['search_params']['brd']);
  99. }
  100. if (isset($_REQUEST['search']))
  101. $context['search_params']['search'] = un_htmlspecialchars($_REQUEST['search']);
  102. if (isset($context['search_params']['search']))
  103. $context['search_params']['search'] = htmlspecialchars($context['search_params']['search']);
  104. if (isset($context['search_params']['userspec']))
  105. $context['search_params']['userspec'] = htmlspecialchars($context['search_params']['userspec']);
  106. if (!empty($context['search_params']['searchtype']))
  107. $context['search_params']['searchtype'] = 2;
  108. if (!empty($context['search_params']['minage']))
  109. $context['search_params']['minage'] = (int) $context['search_params']['minage'];
  110. if (!empty($context['search_params']['maxage']))
  111. $context['search_params']['maxage'] = (int) $context['search_params']['maxage'];
  112. $context['search_params']['show_complete'] = !empty($context['search_params']['show_complete']);
  113. $context['search_params']['subject_only'] = !empty($context['search_params']['subject_only']);
  114. // Load the error text strings if there were errors in the search.
  115. if (!empty($context['search_errors']))
  116. {
  117. loadLanguage('Errors');
  118. $context['search_errors']['messages'] = array();
  119. foreach ($context['search_errors'] as $search_error => $dummy)
  120. {
  121. if ($search_error === 'messages')
  122. continue;
  123. $context['search_errors']['messages'][] = $txt['error_' . $search_error];
  124. }
  125. }
  126. // Find all the boards this user is allowed to see.
  127. $request = $smcFunc['db_query']('order_by_board_order', '
  128. SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
  129. FROM {db_prefix}boards AS b
  130. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  131. WHERE {query_see_board}',
  132. array(
  133. )
  134. );
  135. $context['num_boards'] = $smcFunc['db_num_rows']($request);
  136. $context['boards_check_all'] = true;
  137. $context['categories'] = array();
  138. while ($row = $smcFunc['db_fetch_assoc']($request))
  139. {
  140. // This category hasn't been set up yet..
  141. if (!isset($context['categories'][$row['id_cat']]))
  142. $context['categories'][$row['id_cat']] = array(
  143. 'id' => $row['id_cat'],
  144. 'name' => $row['cat_name'],
  145. 'boards' => array()
  146. );
  147. // Set this board up, and let the template know when it's a child. (indent them..)
  148. $context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
  149. 'id' => $row['id_board'],
  150. 'name' => $row['name'],
  151. 'child_level' => $row['child_level'],
  152. 'selected' => (empty($context['search_params']['brd']) && (empty($modSettings['recycle_enable']) || $row['id_board'] != $modSettings['recycle_board']) && !in_array($row['id_board'], $user_info['ignoreboards'])) || (!empty($context['search_params']['brd']) && in_array($row['id_board'], $context['search_params']['brd']))
  153. );
  154. // If a board wasn't checked that probably should have been ensure the board selection is selected, yo!
  155. if (!$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] && (empty($modSettings['recycle_enable']) || $row['id_board'] != $modSettings['recycle_board']))
  156. $context['boards_check_all'] = false;
  157. }
  158. $smcFunc['db_free_result']($request);
  159. // Now, let's sort the list of categories into the boards for templates that like that.
  160. $temp_boards = array();
  161. foreach ($context['categories'] as $category)
  162. {
  163. $temp_boards[] = array(
  164. 'name' => $category['name'],
  165. 'child_ids' => array_keys($category['boards'])
  166. );
  167. $temp_boards = array_merge($temp_boards, array_values($category['boards']));
  168. // Include a list of boards per category for easy toggling.
  169. $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
  170. }
  171. $max_boards = ceil(count($temp_boards) / 2);
  172. if ($max_boards == 1)
  173. $max_boards = 2;
  174. // Now, alternate them so they can be shown left and right ;).
  175. $context['board_columns'] = array();
  176. for ($i = 0; $i < $max_boards; $i++)
  177. {
  178. $context['board_columns'][] = $temp_boards[$i];
  179. if (isset($temp_boards[$i + $max_boards]))
  180. $context['board_columns'][] = $temp_boards[$i + $max_boards];
  181. else
  182. $context['board_columns'][] = array();
  183. }
  184. if (!empty($_REQUEST['topic']))
  185. {
  186. $context['search_params']['topic'] = (int) $_REQUEST['topic'];
  187. $context['search_params']['show_complete'] = true;
  188. }
  189. if (!empty($context['search_params']['topic']))
  190. {
  191. $context['search_params']['topic'] = (int) $context['search_params']['topic'];
  192. $context['search_topic'] = array(
  193. 'id' => $context['search_params']['topic'],
  194. 'href' => $scripturl . '?topic=' . $context['search_params']['topic'] . '.0',
  195. );
  196. $request = $smcFunc['db_query']('', '
  197. SELECT ms.subject
  198. FROM {db_prefix}topics AS t
  199. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  200. INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
  201. WHERE t.id_topic = {int:search_topic_id}
  202. AND {query_see_board}' . ($modSettings['postmod_active'] ? '
  203. AND t.approved = {int:is_approved_true}' : '') . '
  204. LIMIT 1',
  205. array(
  206. 'is_approved_true' => 1,
  207. 'search_topic_id' => $context['search_params']['topic'],
  208. )
  209. );
  210. if ($smcFunc['db_num_rows']($request) == 0)
  211. fatal_lang_error('topic_gone', false);
  212. list ($context['search_topic']['subject']) = $smcFunc['db_fetch_row']($request);
  213. $smcFunc['db_free_result']($request);
  214. $context['search_topic']['link'] = '<a href="' . $context['search_topic']['href'] . '">' . $context['search_topic']['subject'] . '</a>';
  215. }
  216. // Simple or not?
  217. $context['simple_search'] = isset($context['search_params']['advanced']) ? empty($context['search_params']['advanced']) : !empty($modSettings['simpleSearch']) && !isset($_REQUEST['advanced']);
  218. $context['page_title'] = $txt['set_parameters'];
  219. }
  220. // Gather the results and show them.
  221. function PlushSearch2()
  222. {
  223. global $scripturl, $modSettings, $sourcedir, $txt, $db_connection;
  224. global $user_info, $context, $options, $messages_request, $boards_can;
  225. global $excludedWords, $participants, $smcFunc, $search_versions, $searchAPI;
  226. if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
  227. fatal_lang_error('loadavg_search_disabled', false);
  228. // No, no, no... this is a bit hard on the server, so don't you go prefetching it!
  229. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  230. {
  231. ob_end_clean();
  232. header('HTTP/1.1 403 Forbidden');
  233. die;
  234. }
  235. $weight_factors = array(
  236. 'frequency',
  237. 'age',
  238. 'length',
  239. 'subject',
  240. 'first_message',
  241. 'sticky',
  242. );
  243. $weight = array();
  244. $weight_total = 0;
  245. foreach ($weight_factors as $weight_factor)
  246. {
  247. $weight[$weight_factor] = empty($modSettings['search_weight_' . $weight_factor]) ? 0 : (int) $modSettings['search_weight_' . $weight_factor];
  248. $weight_total += $weight[$weight_factor];
  249. }
  250. // Zero weight. Weightless :P.
  251. if (empty($weight_total))
  252. fatal_lang_error('search_invalid_weights');
  253. // These vars don't require an interface, they're just here for tweaking.
  254. $recentPercentage = 0.30;
  255. $humungousTopicPosts = 200;
  256. $maxMembersToSearch = 500;
  257. $maxMessageResults = empty($modSettings['search_max_results']) ? 0 : $modSettings['search_max_results'] * 5;
  258. // Start with no errors.
  259. $context['search_errors'] = array();
  260. // Number of pages hard maximum - normally not set at all.
  261. $modSettings['search_max_results'] = empty($modSettings['search_max_results']) ? 200 * $modSettings['search_results_per_page'] : (int) $modSettings['search_max_results'];
  262. // Maximum length of the string.
  263. $context['search_string_limit'] = 100;
  264. loadLanguage('Search');
  265. if (!isset($_REQUEST['xml']))
  266. loadTemplate('Search');
  267. //If we're doing XML we need to use the results template regardless really.
  268. else
  269. $context['sub_template'] = 'results';
  270. // Are you allowed?
  271. isAllowedTo('search_posts');
  272. require_once($sourcedir . '/Display.php');
  273. // Search has a special database set.
  274. db_extend('search');
  275. // Load up the search API we are going to use.
  276. $modSettings['search_index'] = empty($modSettings['search_index']) ? 'standard' : $modSettings['search_index'];
  277. if (!file_exists($sourcedir . '/SearchAPI-' . ucwords($modSettings['search_index']) . '.php'))
  278. fatal_lang_error('search_api_missing');
  279. loadClassFile('SearchAPI-' . ucwords($modSettings['search_index']) . '.php');
  280. // Create an instance of the search API and check it is valid for this version of SMF.
  281. $search_class_name = $modSettings['search_index'] . '_search';
  282. $searchAPI = new $search_class_name();
  283. if (!$searchAPI || ($searchAPI->supportsMethod('isValid') && !$searchAPI->isValid()) || $search_versions['forum_version'] < $searchAPI->min_smf_version || $search_versions['search_version'] > $searchAPI->version_compatible)
  284. {
  285. // Log the error.
  286. loadLanguage('Errors');
  287. log_error(sprintf($txt['search_api_not_compatible'], 'SearchAPI-' . ucwords($modSettings['search_index']) . '.php'), 'critical');
  288. loadClassFile('SearchAPI-Standard.php');
  289. $searchAPI = new standard_search();
  290. }
  291. // $search_params will carry all settings that differ from the default search parameters.
  292. // That way, the URLs involved in a search page will be kept as short as possible.
  293. $search_params = array();
  294. if (isset($_REQUEST['params']))
  295. {
  296. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  297. foreach ($temp_params as $i => $data)
  298. {
  299. @list ($k, $v) = explode('|\'|', $data);
  300. $search_params[$k] = $v;
  301. }
  302. if (isset($search_params['brd']))
  303. $search_params['brd'] = empty($search_params['brd']) ? array() : explode(',', $search_params['brd']);
  304. }
  305. // Store whether simple search was used (needed if the user wants to do another query).
  306. if (!isset($search_params['advanced']))
  307. $search_params['advanced'] = empty($_REQUEST['advanced']) ? 0 : 1;
  308. // 1 => 'allwords' (default, don't set as param) / 2 => 'anywords'.
  309. if (!empty($search_params['searchtype']) || (!empty($_REQUEST['searchtype']) && $_REQUEST['searchtype'] == 2))
  310. $search_params['searchtype'] = 2;
  311. // Minimum age of messages. Default to zero (don't set param in that case).
  312. if (!empty($search_params['minage']) || (!empty($_REQUEST['minage']) && $_REQUEST['minage'] > 0))
  313. $search_params['minage'] = !empty($search_params['minage']) ? (int) $search_params['minage'] : (int) $_REQUEST['minage'];
  314. // Maximum age of messages. Default to infinite (9999 days: param not set).
  315. if (!empty($search_params['maxage']) || (!empty($_REQUEST['maxage']) && $_REQUEST['maxage'] < 9999))
  316. $search_params['maxage'] = !empty($search_params['maxage']) ? (int) $search_params['maxage'] : (int) $_REQUEST['maxage'];
  317. // Searching a specific topic?
  318. if (!empty($_REQUEST['topic']))
  319. {
  320. $search_params['topic'] = (int) $_REQUEST['topic'];
  321. $search_params['show_complete'] = true;
  322. }
  323. elseif (!empty($search_params['topic']))
  324. $search_params['topic'] = (int) $search_params['topic'];
  325. if (!empty($search_params['minage']) || !empty($search_params['maxage']))
  326. {
  327. $request = $smcFunc['db_query']('', '
  328. SELECT ' . (empty($search_params['maxage']) ? '0, ' : 'IFNULL(MIN(id_msg), -1), ') . (empty($search_params['minage']) ? '0' : 'IFNULL(MAX(id_msg), -1)') . '
  329. FROM {db_prefix}messages
  330. WHERE 1=1' . ($modSettings['postmod_active'] ? '
  331. AND approved = {int:is_approved_true}' : '') . (empty($search_params['minage']) ? '' : '
  332. AND poster_time <= {int:timestamp_minimum_age}') . (empty($search_params['maxage']) ? '' : '
  333. AND poster_time >= {int:timestamp_maximum_age}'),
  334. array(
  335. 'timestamp_minimum_age' => empty($search_params['minage']) ? 0 : time() - 86400 * $search_params['minage'],
  336. 'timestamp_maximum_age' => empty($search_params['maxage']) ? 0 : time() - 86400 * $search_params['maxage'],
  337. 'is_approved_true' => 1,
  338. )
  339. );
  340. list ($minMsgID, $maxMsgID) = $smcFunc['db_fetch_row']($request);
  341. if ($minMsgID < 0 || $maxMsgID < 0)
  342. $context['search_errors']['no_messages_in_time_frame'] = true;
  343. $smcFunc['db_free_result']($request);
  344. }
  345. // Default the user name to a wildcard matching every user (*).
  346. if (!empty($search_params['userspec']) || (!empty($_REQUEST['userspec']) && $_REQUEST['userspec'] != '*'))
  347. $search_params['userspec'] = isset($search_params['userspec']) ? $search_params['userspec'] : $_REQUEST['userspec'];
  348. // If there's no specific user, then don't mention it in the main query.
  349. if (empty($search_params['userspec']))
  350. $userQuery = '';
  351. else
  352. {
  353. $userString = strtr($smcFunc['htmlspecialchars']($search_params['userspec'], ENT_QUOTES), array('&quot;' => '"'));
  354. $userString = strtr($userString, array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_'));
  355. preg_match_all('~"([^"]+)"~', $userString, $matches);
  356. $possible_users = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $userString)));
  357. for ($k = 0, $n = count($possible_users); $k < $n; $k++)
  358. {
  359. $possible_users[$k] = trim($possible_users[$k]);
  360. if (strlen($possible_users[$k]) == 0)
  361. unset($possible_users[$k]);
  362. }
  363. // Create a list of database-escaped search names.
  364. $realNameMatches = array();
  365. foreach ($possible_users as $possible_user)
  366. $realNameMatches[] = $smcFunc['db_quote'](
  367. '{string:possible_user}',
  368. array(
  369. 'possible_user' => $possible_user
  370. )
  371. );
  372. // Retrieve a list of possible members.
  373. $request = $smcFunc['db_query']('', '
  374. SELECT id_member
  375. FROM {db_prefix}members
  376. WHERE {raw:match_possible_users}',
  377. array(
  378. 'match_possible_users' => 'real_name LIKE ' . implode(' OR real_name LIKE ', $realNameMatches),
  379. )
  380. );
  381. // Simply do nothing if there're too many members matching the criteria.
  382. if ($smcFunc['db_num_rows']($request) > $maxMembersToSearch)
  383. $userQuery = '';
  384. elseif ($smcFunc['db_num_rows']($request) == 0)
  385. {
  386. $userQuery = $smcFunc['db_quote'](
  387. 'm.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})',
  388. array(
  389. 'id_member_guest' => 0,
  390. 'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches),
  391. )
  392. );
  393. }
  394. else
  395. {
  396. $memberlist = array();
  397. while ($row = $smcFunc['db_fetch_assoc']($request))
  398. $memberlist[] = $row['id_member'];
  399. $userQuery = $smcFunc['db_quote'](
  400. '(m.id_member IN ({array_int:matched_members}) OR (m.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})))',
  401. array(
  402. 'matched_members' => $memberlist,
  403. 'id_member_guest' => 0,
  404. 'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches),
  405. )
  406. );
  407. }
  408. $smcFunc['db_free_result']($request);
  409. }
  410. // If the boards were passed by URL (params=), temporarily put them back in $_REQUEST.
  411. if (!empty($search_params['brd']) && is_array($search_params['brd']))
  412. $_REQUEST['brd'] = $search_params['brd'];
  413. // Ensure that brd is an array.
  414. if (!empty($_REQUEST['brd']) && !is_array($_REQUEST['brd']))
  415. $_REQUEST['brd'] = strpos($_REQUEST['brd'], ',') !== false ? explode(',', $_REQUEST['brd']) : array($_REQUEST['brd']);
  416. // Make sure all boards are integers.
  417. if (!empty($_REQUEST['brd']))
  418. foreach ($_REQUEST['brd'] as $id => $brd)
  419. $_REQUEST['brd'][$id] = (int) $brd;
  420. // Special case for boards: searching just one topic?
  421. if (!empty($search_params['topic']))
  422. {
  423. $request = $smcFunc['db_query']('', '
  424. SELECT b.id_board
  425. FROM {db_prefix}topics AS t
  426. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  427. WHERE t.id_topic = {int:search_topic_id}
  428. AND {query_see_board}' . ($modSettings['postmod_active'] ? '
  429. AND t.approved = {int:is_approved_true}' : '') . '
  430. LIMIT 1',
  431. array(
  432. 'search_topic_id' => $search_params['topic'],
  433. 'is_approved_true' => 1,
  434. )
  435. );
  436. if ($smcFunc['db_num_rows']($request) == 0)
  437. fatal_lang_error('topic_gone', false);
  438. $search_params['brd'] = array();
  439. list ($search_params['brd'][0]) = $smcFunc['db_fetch_row']($request);
  440. $smcFunc['db_free_result']($request);
  441. }
  442. // Select all boards you've selected AND are allowed to see.
  443. elseif ($user_info['is_admin'] && (!empty($search_params['advanced']) || !empty($_REQUEST['brd'])))
  444. $search_params['brd'] = empty($_REQUEST['brd']) ? array() : $_REQUEST['brd'];
  445. else
  446. {
  447. $see_board = empty($search_params['advanced']) ? 'query_wanna_see_board' : 'query_see_board';
  448. $request = $smcFunc['db_query']('', '
  449. SELECT b.id_board
  450. FROM {db_prefix}boards AS b
  451. WHERE {raw:boards_allowed_to_see}' . (empty($_REQUEST['brd']) ? (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  452. AND b.id_board != {int:recycle_board_id}' : '') : '
  453. AND b.id_board IN ({array_int:selected_search_boards})'),
  454. array(
  455. 'boards_allowed_to_see' => $user_info[$see_board],
  456. 'selected_search_boards' => empty($_REQUEST['brd']) ? array() : $_REQUEST['brd'],
  457. 'recycle_board_id' => $modSettings['recycle_board'],
  458. )
  459. );
  460. $search_params['brd'] = array();
  461. while ($row = $smcFunc['db_fetch_assoc']($request))
  462. $search_params['brd'][] = $row['id_board'];
  463. $smcFunc['db_free_result']($request);
  464. // This error should pro'bly only happen for hackers.
  465. if (empty($search_params['brd']))
  466. $context['search_errors']['no_boards_selected'] = true;
  467. }
  468. if (count($search_params['brd']) != 0)
  469. {
  470. foreach ($search_params['brd'] as $k => $v)
  471. $search_params['brd'][$k] = (int) $v;
  472. // If we've selected all boards, this parameter can be left empty.
  473. $request = $smcFunc['db_query']('', '
  474. SELECT COUNT(*)
  475. FROM {db_prefix}boards',
  476. array(
  477. )
  478. );
  479. list ($num_boards) = $smcFunc['db_fetch_row']($request);
  480. $smcFunc['db_free_result']($request);
  481. if (count($search_params['brd']) == $num_boards)
  482. $boardQuery = '';
  483. elseif (count($search_params['brd']) == $num_boards - 1 && !empty($modSettings['recycle_board']) && !in_array($modSettings['recycle_board'], $search_params['brd']))
  484. $boardQuery = '!= ' . $modSettings['recycle_board'];
  485. else
  486. $boardQuery = 'IN (' . implode(', ', $search_params['brd']) . ')';
  487. }
  488. else
  489. $boardQuery = '';
  490. $search_params['show_complete'] = !empty($search_params['show_complete']) || !empty($_REQUEST['show_complete']);
  491. $search_params['subject_only'] = !empty($search_params['subject_only']) || !empty($_REQUEST['subject_only']);
  492. $context['compact'] = !$search_params['show_complete'];
  493. // Get the sorting parameters right. Default to sort by relevance descending.
  494. $sort_columns = array(
  495. 'relevance',
  496. 'num_replies',
  497. 'id_msg',
  498. );
  499. if (empty($search_params['sort']) && !empty($_REQUEST['sort']))
  500. list ($search_params['sort'], $search_params['sort_dir']) = array_pad(explode('|', $_REQUEST['sort']), 2, '');
  501. $search_params['sort'] = !empty($search_params['sort']) && in_array($search_params['sort'], $sort_columns) ? $search_params['sort'] : 'relevance';
  502. if (!empty($search_params['topic']) && $search_params['sort'] === 'num_replies')
  503. $search_params['sort'] = 'id_msg';
  504. // Sorting direction: descending unless stated otherwise.
  505. $search_params['sort_dir'] = !empty($search_params['sort_dir']) && $search_params['sort_dir'] == 'asc' ? 'asc' : 'desc';
  506. // Determine some values needed to calculate the relevance.
  507. $minMsg = (int) ((1 - $recentPercentage) * $modSettings['maxMsgID']);
  508. $recentMsg = $modSettings['maxMsgID'] - $minMsg;
  509. // *** Parse the search query
  510. // Unfortunately, searching for words like this is going to be slow, so we're blacklisting them.
  511. // !!! Setting to add more here?
  512. // !!! Maybe only blacklist if they are the only word, or "any" is used?
  513. $blacklisted_words = array('img', 'url', 'quote', 'www', 'http', 'the', 'is', 'it', 'are', 'if');
  514. // What are we searching for?
  515. if (empty($search_params['search']))
  516. {
  517. if (isset($_GET['search']))
  518. $search_params['search'] = un_htmlspecialchars($_GET['search']);
  519. elseif (isset($_POST['search']))
  520. $search_params['search'] = $_POST['search'];
  521. else
  522. $search_params['search'] = '';
  523. }
  524. // Nothing??
  525. if (!isset($search_params['search']) || $search_params['search'] == '')
  526. $context['search_errors']['invalid_search_string'] = true;
  527. // Too long?
  528. elseif ($smcFunc['strlen']($search_params['search']) > $context['search_string_limit'])
  529. {
  530. $context['search_errors']['string_too_long'] = true;
  531. $txt['error_string_too_long'] = sprintf($txt['error_string_too_long'], $context['search_string_limit']);
  532. }
  533. // Change non-word characters into spaces.
  534. $stripped_query = preg_replace('~(?:[\x0B\0' . ($context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0') . '\t\r\s\n(){}\\[\\]<>!@$%^*.,:+=`\~\?/\\\\]+|&(?:amp|lt|gt|quot);)+~' . ($context['utf8'] ? 'u' : ''), ' ', $search_params['search']);
  535. // Make the query lower case. It's gonna be case insensitive anyway.
  536. $stripped_query = un_htmlspecialchars($smcFunc['strtolower']($stripped_query));
  537. // This (hidden) setting will do fulltext searching in the most basic way.
  538. if (!empty($modSettings['search_simple_fulltext']))
  539. $stripped_query = strtr($stripped_query, array('"' => ''));
  540. $no_regexp = preg_match('~&#(?:\d{1,7}|x[0-9a-fA-F]{1,6});~', $stripped_query) === 1;
  541. // Extract phrase parts first (e.g. some words "this is a phrase" some more words.)
  542. preg_match_all('/(?:^|\s)([-]?)"([^"]+)"(?:$|\s)/', $stripped_query, $matches, PREG_PATTERN_ORDER);
  543. $phraseArray = $matches[2];
  544. // Remove the phrase parts and extract the words.
  545. $wordArray = explode(' ', preg_replace('~(?:^|\s)(?:[-]?)"(?:[^"]+)"(?:$|\s)~' . ($context['utf8'] ? 'u' : ''), ' ', $search_params['search']));
  546. // A minus sign in front of a word excludes the word.... so...
  547. $excludedWords = array();
  548. $excludedIndexWords = array();
  549. $excludedSubjectWords = array();
  550. $excludedPhrases = array();
  551. // .. first, we check for things like -"some words", but not "-some words".
  552. foreach ($matches[1] as $index => $word)
  553. if ($word === '-')
  554. {
  555. if (($word = trim($phraseArray[$index], '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
  556. $excludedWords[] = $word;
  557. unset($phraseArray[$index]);
  558. }
  559. // Now we look for -test, etc.... normaller.
  560. foreach ($wordArray as $index => $word)
  561. if (strpos(trim($word), '-') === 0)
  562. {
  563. if (($word = trim($word, '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
  564. $excludedWords[] = $word;
  565. unset($wordArray[$index]);
  566. }
  567. // The remaining words and phrases are all included.
  568. $searchArray = array_merge($phraseArray, $wordArray);
  569. // Trim everything and make sure there are no words that are the same.
  570. foreach ($searchArray as $index => $value)
  571. {
  572. if (($searchArray[$index] = trim($value, '-_\' ')) === '' || in_array($searchArray[$index], $blacklisted_words))
  573. unset($searchArray[$index]);
  574. // Don't allow very, very short words.
  575. elseif (strlen($value) < 2)
  576. {
  577. $context['search_errors']['search_string_small_words'] = true;
  578. unset($searchArray[$index]);
  579. }
  580. else
  581. $searchArray[$index] = $searchArray[$index];
  582. }
  583. $searchArray = array_slice(array_unique($searchArray), 0, 10);
  584. // Create an array of replacements for highlighting.
  585. $context['mark'] = array();
  586. foreach ($searchArray as $word)
  587. $context['mark'][$word] = '<strong class="highlight">' . $word . '</strong>';
  588. // Initialize two arrays storing the words that have to be searched for.
  589. $orParts = array();
  590. $searchWords = array();
  591. // Make sure at least one word is being searched for.
  592. if (empty($searchArray))
  593. $context['search_errors']['invalid_search_string'] = true;
  594. // All words/sentences must match.
  595. elseif (empty($search_params['searchtype']))
  596. $orParts[0] = $searchArray;
  597. // Any word/sentence must match.
  598. else
  599. foreach ($searchArray as $index => $value)
  600. $orParts[$index] = array($value);
  601. // Don't allow duplicate error messages if one string is too short.
  602. if (isset($context['search_errors']['search_string_small_words'], $context['search_errors']['invalid_search_string']))
  603. unset($context['search_errors']['invalid_search_string']);
  604. // Make sure the excluded words are in all or-branches.
  605. foreach ($orParts as $orIndex => $andParts)
  606. foreach ($excludedWords as $word)
  607. $orParts[$orIndex][] = $word;
  608. // Determine the or-branches and the fulltext search words.
  609. foreach ($orParts as $orIndex => $andParts)
  610. {
  611. $searchWords[$orIndex] = array(
  612. 'indexed_words' => array(),
  613. 'words' => array(),
  614. 'subject_words' => array(),
  615. 'all_words' => array(),
  616. );
  617. // Sort the indexed words (large words -> small words -> excluded words).
  618. if ($searchAPI->supportsMethod('searchSort'))
  619. usort($orParts[$orIndex], 'searchSort');
  620. foreach ($orParts[$orIndex] as $word)
  621. {
  622. $is_excluded = in_array($word, $excludedWords);
  623. $searchWords[$orIndex]['all_words'][] = $word;
  624. $subjectWords = text2words($word);
  625. if (!$is_excluded || count($subjectWords) === 1)
  626. {
  627. $searchWords[$orIndex]['subject_words'] = array_merge($searchWords[$orIndex]['subject_words'], $subjectWords);
  628. if ($is_excluded)
  629. $excludedSubjectWords = array_merge($excludedSubjectWords, $subjectWords);
  630. }
  631. else
  632. $excludedPhrases[] = $word;
  633. // Have we got indexes to prepare?
  634. if ($searchAPI->supportsMethod('prepareIndexes'))
  635. $searchAPI->prepareIndexes($word, $searchWords[$orIndex], $excludedIndexWords, $is_excluded);
  636. }
  637. // Search_force_index requires all AND parts to have at least one fulltext word.
  638. if (!empty($modSettings['search_force_index']) && empty($searchWords[$orIndex]['indexed_words']))
  639. {
  640. $context['search_errors']['query_not_specific_enough'] = true;
  641. break;
  642. }
  643. // Make sure we aren't searching for too many indexed words.
  644. else
  645. {
  646. $searchWords[$orIndex]['indexed_words'] = array_slice($searchWords[$orIndex]['indexed_words'], 0, 7);
  647. $searchWords[$orIndex]['subject_words'] = array_slice($searchWords[$orIndex]['subject_words'], 0, 7);
  648. }
  649. }
  650. // *** Spell checking
  651. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  652. if ($context['show_spellchecking'])
  653. {
  654. // Windows fix.
  655. ob_start();
  656. $old = error_reporting(0);
  657. pspell_new('en');
  658. $pspell_link = pspell_new($txt['lang_dictionary'], $txt['lang_spelling'], '', strtr($txt['lang_character_set'], array('iso-' => 'iso', 'ISO-' => 'iso')), PSPELL_FAST | PSPELL_RUN_TOGETHER);
  659. error_reporting($old);
  660. if (!$pspell_link)
  661. $pspell_link = pspell_new('en', '', '', '', PSPELL_FAST | PSPELL_RUN_TOGETHER);
  662. ob_end_clean();
  663. $did_you_mean = array('search' => array(), 'display' => array());
  664. $found_misspelling = false;
  665. foreach ($searchArray as $word)
  666. {
  667. if (empty($pspell_link))
  668. continue;
  669. $word = $word;
  670. // Don't check phrases.
  671. if (preg_match('~^\w+$~', $word) === 0)
  672. {
  673. $did_you_mean['search'][] = '"' . $word . '"';
  674. $did_you_mean['display'][] = '&quot;' . $smcFunc['htmlspecialchars']($word) . '&quot;';
  675. continue;
  676. }
  677. // For some strange reason spell check can crash PHP on decimals.
  678. elseif (preg_match('~\d~', $word) === 1)
  679. {
  680. $did_you_mean['search'][] = $word;
  681. $did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
  682. continue;
  683. }
  684. elseif (pspell_check($pspell_link, $word))
  685. {
  686. $did_you_mean['search'][] = $word;
  687. $did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
  688. continue;
  689. }
  690. $suggestions = pspell_suggest($pspell_link, $word);
  691. foreach ($suggestions as $i => $s)
  692. {
  693. // Search is case insensitive.
  694. if ($smcFunc['strtolower']($s) == $smcFunc['strtolower']($word))
  695. unset($suggestions[$i]);
  696. // Plus, don't suggest something the user thinks is rude!
  697. elseif ($suggestions[$i] != censorText($s))
  698. unset($suggestions[$i]);
  699. }
  700. // Anything found? If so, correct it!
  701. if (!empty($suggestions))
  702. {
  703. $suggestions = array_values($suggestions);
  704. $did_you_mean['search'][] = $suggestions[0];
  705. $did_you_mean['display'][] = '<em><strong>' . $smcFunc['htmlspecialchars']($suggestions[0]) . '</strong></em>';
  706. $found_misspelling = true;
  707. }
  708. else
  709. {
  710. $did_you_mean['search'][] = $word;
  711. $did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
  712. }
  713. }
  714. if ($found_misspelling)
  715. {
  716. // Don't spell check excluded words, but add them still...
  717. $temp_excluded = array('search' => array(), 'display' => array());
  718. foreach ($excludedWords as $word)
  719. {
  720. $word = $word;
  721. if (preg_match('~^\w+$~', $word) == 0)
  722. {
  723. $temp_excluded['search'][] = '-"' . $word . '"';
  724. $temp_excluded['display'][] = '-&quot;' . $smcFunc['htmlspecialchars']($word) . '&quot;';
  725. }
  726. else
  727. {
  728. $temp_excluded['search'][] = '-' . $word;
  729. $temp_excluded['display'][] = '-' . $smcFunc['htmlspecialchars']($word);
  730. }
  731. }
  732. $did_you_mean['search'] = array_merge($did_you_mean['search'], $temp_excluded['search']);
  733. $did_you_mean['display'] = array_merge($did_you_mean['display'], $temp_excluded['display']);
  734. $temp_params = $search_params;
  735. $temp_params['search'] = implode(' ', $did_you_mean['search']);
  736. if (isset($temp_params['brd']))
  737. $temp_params['brd'] = implode(',', $temp_params['brd']);
  738. $context['params'] = array();
  739. foreach ($temp_params as $k => $v)
  740. $context['did_you_mean_params'][] = $k . '|\'|' . $v;
  741. $context['did_you_mean_params'] = base64_encode(implode('|"|', $context['did_you_mean_params']));
  742. $context['did_you_mean'] = implode(' ', $did_you_mean['display']);
  743. }
  744. }
  745. // Let the user adjust the search query, should they wish?
  746. $context['search_params'] = $search_params;
  747. if (isset($context['search_params']['search']))
  748. $context['search_params']['search'] = $smcFunc['htmlspecialchars']($context['search_params']['search']);
  749. if (isset($context['search_params']['userspec']))
  750. $context['search_params']['userspec'] = $smcFunc['htmlspecialchars']($context['search_params']['userspec']);
  751. // Do we have captcha enabled?
  752. if ($user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']) && (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != $search_params['search']))
  753. {
  754. // If we come from another search box tone down the error...
  755. if (!isset($_REQUEST['search_vv']))
  756. $context['search_errors']['need_verification_code'] = true;
  757. else
  758. {
  759. require_once($sourcedir . '/Subs-Editor.php');
  760. $verificationOptions = array(
  761. 'id' => 'search',
  762. );
  763. $context['require_verification'] = create_control_verification($verificationOptions, true);
  764. if (is_array($context['require_verification']))
  765. {
  766. foreach ($context['require_verification'] as $error)
  767. $context['search_errors'][$error] = true;
  768. }
  769. // Don't keep asking for it - they've proven themselves worthy.
  770. else
  771. $_SESSION['ss_vv_passed'] = true;
  772. }
  773. }
  774. // *** Encode all search params
  775. // All search params have been checked, let's compile them to a single string... made less simple by PHP 4.3.9 and below.
  776. $temp_params = $search_params;
  777. if (isset($temp_params['brd']))
  778. $temp_params['brd'] = implode(',', $temp_params['brd']);
  779. $context['params'] = array();
  780. foreach ($temp_params as $k => $v)
  781. $context['params'][] = $k . '|\'|' . $v;
  782. $context['params'] = base64_encode(implode('|"|', $context['params']));
  783. // ... and add the links to the link tree.
  784. $context['linktree'][] = array(
  785. 'url' => $scripturl . '?action=search;params=' . $context['params'],
  786. 'name' => $txt['search']
  787. );
  788. $context['linktree'][] = array(
  789. 'url' => $scripturl . '?action=search2;params=' . $context['params'],
  790. 'name' => $txt['search_results']
  791. );
  792. // *** A last error check
  793. // One or more search errors? Go back to the first search screen.
  794. if (!empty($context['search_errors']))
  795. {
  796. $_REQUEST['params'] = $context['params'];
  797. return PlushSearch1();
  798. }
  799. // Spam me not, Spam-a-lot?
  800. if (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != $search_params['search'])
  801. spamProtection('search');
  802. // Store the last search string to allow pages of results to be browsed.
  803. $_SESSION['last_ss'] = $search_params['search'];
  804. // *** Reserve an ID for caching the search results.
  805. $query_params = array_merge($search_params, array(
  806. 'min_msg_id' => isset($minMsgID) ? (int) $minMsgID : 0,
  807. 'max_msg_id' => isset($maxMsgID) ? (int) $maxMsgID : 0,
  808. 'memberlist' => !empty($memberlist) ? $memberlist : array(),
  809. ));
  810. // Can this search rely on the API given the parameters?
  811. if ($searchAPI->supportsMethod('searchQuery', $query_params))
  812. {
  813. $participants = array();
  814. $searchArray = array();
  815. $num_results = $searchAPI->searchQuery($query_params, $searchWords, $excludedIndexWords, $participants, $searchArray);
  816. }
  817. // Update the cache if the current search term is not yet cached.
  818. else
  819. {
  820. $update_cache = empty($_SESSION['search_cache']) || ($_SESSION['search_cache']['params'] != $context['params']);
  821. if ($update_cache)
  822. {
  823. // Increase the pointer...
  824. $modSettings['search_pointer'] = empty($modSettings['search_pointer']) ? 0 : (int) $modSettings['search_pointer'];
  825. // ...and store it right off.
  826. updateSettings(array('search_pointer' => $modSettings['search_pointer'] >= 255 ? 0 : $modSettings['search_pointer'] + 1));
  827. // As long as you don't change the parameters, the cache result is yours.
  828. $_SESSION['search_cache'] = array(
  829. 'id_search' => $modSettings['search_pointer'],
  830. 'num_results' => -1,
  831. 'params' => $context['params'],
  832. );
  833. // Clear the previous cache of the final results cache.
  834. $smcFunc['db_search_query']('delete_log_search_results', '
  835. DELETE FROM {db_prefix}log_search_results
  836. WHERE id_search = {int:search_id}',
  837. array(
  838. 'search_id' => $_SESSION['search_cache']['id_search'],
  839. )
  840. );
  841. if ($search_params['subject_only'])
  842. {
  843. // We do this to try and avoid duplicate keys on databases not supporting INSERT IGNORE.
  844. $inserts = array();
  845. foreach ($searchWords as $orIndex => $words)
  846. {
  847. $subject_query_params = array();
  848. $subject_query = array(
  849. 'from' => '{db_prefix}topics AS t',
  850. 'inner_join' => array(),
  851. 'left_join' => array(),
  852. 'where' => array(),
  853. );
  854. if ($modSettings['postmod_active'])
  855. $subject_query['where'][] = 't.approved = {int:is_approved}';
  856. $numTables = 0;
  857. $prev_join = 0;
  858. $numSubjectResults = 0;
  859. foreach ($words['subject_words'] as $subjectWord)
  860. {
  861. $numTables++;
  862. if (in_array($subjectWord, $excludedSubjectWords))
  863. {
  864. $subject_query['left_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_words_' . $numTables . '_wild}' : '= {string:subject_words_' . $numTables . '}') . ' AND subj' . $numTables . '.id_topic = t.id_topic)';
  865. $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
  866. }
  867. else
  868. {
  869. $subject_query['inner_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.id_topic = ' . ($prev_join === 0 ? 't' : 'subj' . $prev_join) . '.id_topic)';
  870. $subject_query['where'][] = 'subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_words_' . $numTables . '_wild}' : '= {string:subject_words_' . $numTables . '}');
  871. $prev_join = $numTables;
  872. }
  873. $subject_query_params['subject_words_' . $numTables] = $subjectWord;
  874. $subject_query_params['subject_words_' . $numTables . '_wild'] = '%' . $subjectWord . '%';
  875. }
  876. if (!empty($userQuery))
  877. {
  878. if ($subject_query['from'] != '{db_prefix}messages AS m')
  879. {
  880. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_topic = t.id_topic)';
  881. }
  882. $subject_query['where'][] = $userQuery;
  883. }
  884. if (!empty($search_params['topic']))
  885. $subject_query['where'][] = 't.id_topic = ' . $search_params['topic'];
  886. if (!empty($minMsgID))
  887. $subject_query['where'][] = 't.id_first_msg >= ' . $minMsgID;
  888. if (!empty($maxMsgID))
  889. $subject_query['where'][] = 't.id_last_msg <= ' . $maxMsgID;
  890. if (!empty($boardQuery))
  891. $subject_query['where'][] = 't.id_board ' . $boardQuery;
  892. if (!empty($excludedPhrases))
  893. {
  894. if ($subject_query['from'] != '{db_prefix}messages AS m')
  895. {
  896. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  897. }
  898. $count = 0;
  899. foreach ($excludedPhrases as $phrase)
  900. {
  901. $subject_query['where'][] = 'm.subject NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:excluded_phrases_' . $count . '}';
  902. $subject_query_params['excluded_phrases_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
  903. }
  904. }
  905. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_results_subject',
  906. ($smcFunc['db_support_ignore'] ? '
  907. INSERT IGNORE INTO {db_prefix}log_search_results
  908. (id_search, id_topic, relevance, id_msg, num_matches)' : '') . '
  909. SELECT
  910. {int:id_search},
  911. t.id_topic,
  912. 1000 * (
  913. {int:weight_frequency} / (t.num_replies + 1) +
  914. {int:weight_age} * CASE WHEN t.id_first_msg < {int:min_msg} THEN 0 ELSE (t.id_first_msg - {int:min_msg}) / {int:recent_message} END +
  915. {int:weight_length} * CASE WHEN t.num_replies < {int:huge_topic_posts} THEN t.num_replies / {int:huge_topic_posts} ELSE 1 END +
  916. {int:weight_subject} +
  917. {int:weight_sticky} * t.is_sticky
  918. ) / {int:weight_total} AS relevance,
  919. ' . (empty($userQuery) ? 't.id_first_msg' : 'm.id_msg') . ',
  920. 1
  921. FROM ' . $subject_query['from'] . (empty($subject_query['inner_join']) ? '' : '
  922. INNER JOIN ' . implode('
  923. INNER JOIN ', $subject_query['inner_join'])) . (empty($subject_query['left_join']) ? '' : '
  924. LEFT JOIN ' . implode('
  925. LEFT JOIN ', $subject_query['left_join'])) . '
  926. WHERE ' . implode('
  927. AND ', $subject_query['where']) . (empty($modSettings['search_max_results']) ? '' : '
  928. LIMIT ' . ($modSettings['search_max_results'] - $numSubjectResults)),
  929. array_merge($subject_query_params, array(
  930. 'id_search' => $_SESSION['search_cache']['id_search'],
  931. 'weight_age' => $weight['age'],
  932. 'weight_frequency' => $weight['frequency'],
  933. 'weight_length' => $weight['length'],
  934. 'weight_sticky' => $weight['sticky'],
  935. 'weight_subject' => $weight['subject'],
  936. 'weight_total' => $weight_total,
  937. 'min_msg' => $minMsg,
  938. 'recent_message' => $recentMsg,
  939. 'huge_topic_posts' => $humungousTopicPosts,
  940. 'is_approved' => 1,
  941. ))
  942. );
  943. // If the database doesn't support IGNORE to make this fast we need to do some tracking.
  944. if (!$smcFunc['db_support_ignore'])
  945. {
  946. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  947. {
  948. // No duplicates!
  949. if (isset($inserts[$row[1]]))
  950. continue;
  951. foreach ($row as $key => $value)
  952. $inserts[$row[1]][] = (int) $row[$key];
  953. }
  954. $smcFunc['db_free_result']($ignoreRequest);
  955. $numSubjectResults = count($inserts);
  956. }
  957. else
  958. $numSubjectResults += $smcFunc['db_affected_rows']();
  959. if (!empty($modSettings['search_max_results']) && $numSubjectResults >= $modSettings['search_max_results'])
  960. break;
  961. }
  962. // If there's data to be inserted for non-IGNORE databases do it here!
  963. if (!empty($inserts))
  964. {
  965. $smcFunc['db_insert']('',
  966. '{db_prefix}log_search_results',
  967. array('id_search' => 'int', 'id_topic' => 'int', 'relevance' => 'int', 'id_msg' => 'int', 'num_matches' => 'int'),
  968. $inserts,
  969. array('id_search', 'id_topic')
  970. );
  971. }
  972. $_SESSION['search_cache']['num_results'] = $numSubjectResults;
  973. }
  974. else
  975. {
  976. $main_query = array(
  977. 'select' => array(
  978. 'id_search' => $_SESSION['search_cache']['id_search'],
  979. 'relevance' => '0',
  980. ),
  981. 'weights' => array(),
  982. 'from' => '{db_prefix}topics AS t',
  983. 'inner_join' => array(
  984. '{db_prefix}messages AS m ON (m.id_topic = t.id_topic)'
  985. ),
  986. 'left_join' => array(),
  987. 'where' => array(),
  988. 'group_by' => array(),
  989. 'parameters' => array(
  990. 'min_msg' => $minMsg,
  991. 'recent_message' => $recentMsg,
  992. 'huge_topic_posts' => $humungousTopicPosts,
  993. 'is_approved' => 1,
  994. ),
  995. );
  996. if (empty($search_params['topic']))
  997. {
  998. $main_query['select']['id_topic'] = 't.id_topic';
  999. $main_query['select']['id_msg'] = 'MAX(m.id_msg) AS id_msg';
  1000. $main_query['select']['num_matches'] = 'COUNT(*) AS num_matches';
  1001. $main_query['weights'] = array(
  1002. 'frequency' => 'COUNT(*) / (MAX(t.num_replies) + 1)',
  1003. 'age' => 'CASE WHEN MAX(m.id_msg) < {int:min_msg} THEN 0 ELSE (MAX(m.id_msg) - {int:min_msg}) / {int:recent_message} END',
  1004. 'length' => 'CASE WHEN MAX(t.num_replies) < {int:huge_topic_posts} THEN MAX(t.num_replies) / {int:huge_topic_posts} ELSE 1 END',
  1005. 'subject' => '0',
  1006. 'first_message' => 'CASE WHEN MIN(m.id_msg) = MAX(t.id_first_msg) THEN 1 ELSE 0 END',
  1007. 'sticky' => 'MAX(t.is_sticky)',
  1008. );
  1009. $main_query['group_by'][] = 't.id_topic';
  1010. }
  1011. else
  1012. {
  1013. // This is outrageous!
  1014. $main_query['select']['id_topic'] = 'm.id_msg AS id_topic';
  1015. $main_query['select']['id_msg'] = 'm.id_msg';
  1016. $main_query['select']['num_matches'] = '1 AS num_matches';
  1017. $main_query['weights'] = array(
  1018. 'age' => '((m.id_msg - t.id_first_msg) / CASE WHEN t.id_last_msg = t.id_first_msg THEN 1 ELSE t.id_last_msg - t.id_first_msg END)',
  1019. 'first_message' => 'CASE WHEN m.id_msg = t.id_first_msg THEN 1 ELSE 0 END',
  1020. );
  1021. $main_query['where'][] = 't.id_topic = {int:topic}';
  1022. $main_query['parameters']['topic'] = $search_params['topic'];
  1023. }
  1024. // *** Get the subject results.
  1025. $numSubjectResults = 0;
  1026. if (empty($search_params['topic']))
  1027. {
  1028. $inserts = array();
  1029. // Create a temporary table to store some preliminary results in.
  1030. $smcFunc['db_search_query']('drop_tmp_log_search_topics', '
  1031. DROP TABLE IF EXISTS {db_prefix}tmp_log_search_topics',
  1032. array(
  1033. 'db_error_skip' => true,
  1034. )
  1035. );
  1036. $createTemporary = $smcFunc['db_search_query']('create_tmp_log_search_topics', '
  1037. CREATE TEMPORARY TABLE {db_prefix}tmp_log_search_topics (
  1038. id_topic mediumint(8) unsigned NOT NULL default {string:string_zero},
  1039. PRIMARY KEY (id_topic)
  1040. ) TYPE=HEAP',
  1041. array(
  1042. 'string_zero' => '0',
  1043. 'db_error_skip' => true,
  1044. )
  1045. ) !== false;
  1046. // Clean up some previous cache.
  1047. if (!$createTemporary)
  1048. $smcFunc['db_search_query']('delete_log_search_topics', '
  1049. DELETE FROM {db_prefix}log_search_topics
  1050. WHERE id_search = {int:search_id}',
  1051. array(
  1052. 'search_id' => $_SESSION['search_cache']['id_search'],
  1053. )
  1054. );
  1055. foreach ($searchWords as $orIndex => $words)
  1056. {
  1057. $subject_query = array(
  1058. 'from' => '{db_prefix}topics AS t',
  1059. 'inner_join' => array(),
  1060. 'left_join' => array(),
  1061. 'where' => array(),
  1062. 'params' => array(),
  1063. );
  1064. $numTables = 0;
  1065. $prev_join = 0;
  1066. $count = 0;
  1067. foreach ($words['subject_words'] as $subjectWord)
  1068. {
  1069. $numTables++;
  1070. if (in_array($subjectWord, $excludedSubjectWords))
  1071. {
  1072. if ($subject_query['from'] != '{db_prefix}messages AS m')
  1073. {
  1074. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  1075. }
  1076. $subject_query['left_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_not_' . $count . '}' : '= {string:subject_not_' . $count . '}') . ' AND subj' . $numTables . '.id_topic = t.id_topic)';
  1077. $subject_query['params']['subject_not_' . $count] = empty($modSettings['search_match_words']) ? '%' . $subjectWord . '%' : $subjectWord;
  1078. $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
  1079. $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:body_not_' . $count . '}';
  1080. $subject_query['params']['body_not_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($subjectWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $subjectWord), '\\\'') . '[[:>:]]';
  1081. }
  1082. else
  1083. {
  1084. $subject_q

Large files files are truncated, but you can click here to view the full file