PageRenderTime 54ms CodeModel.GetById 18ms RepoModel.GetById 1ms app.codeStats 0ms

/php/Sources/Search.php

https://github.com/dekoza/openshift-smf-2.0.7
PHP | 2105 lines | 1656 code | 233 blank | 216 comment | 332 complexity | 0d6f657c7e11fc144a11e8c5a391ce18 MD5 | raw file
Possible License(s): BSD-3-Clause

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

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

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