PageRenderTime 53ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/sources/controllers/Search.controller.php

https://github.com/Arantor/Elkarte
PHP | 2714 lines | 2084 code | 316 blank | 314 comment | 449 complexity | a6b622757d4dd792cfd1f3065020c231 MD5 | raw file
Possible License(s): BSD-3-Clause, LGPL-3.0

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

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

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