PageRenderTime 59ms CodeModel.GetById 9ms RepoModel.GetById 1ms app.codeStats 0ms

/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
  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 . '%' : $subjectWord;
  1128. $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
  1129. $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:body_not_' . $count . '}';
  1130. $subject_query['params']['body_not_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($subjectWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $subjectWord), '\\\'') . '[[:>:]]';
  1131. }
  1132. else
  1133. {
  1134. $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)';
  1135. $subject_query['where'][] = 'subj' . $numTables . '.word LIKE {string:subject_like_' . $count . '}';
  1136. $subject_query['params']['subject_like_' . $count++] = empty($modSettings['search_match_words']) ? '%' . $subjectWord . '%' : $subjectWord;
  1137. $prev_join = $numTables;
  1138. }
  1139. }
  1140. if (!empty($userQuery))
  1141. {
  1142. if ($subject_query['from'] != '{db_prefix}messages AS m')
  1143. {
  1144. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  1145. }
  1146. $subject_query['where'][] = '{raw:user_query}';
  1147. $subject_query['params']['user_query'] = $userQuery;
  1148. }
  1149. if (!empty($search_params['topic']))
  1150. {
  1151. $subject_query['where'][] = 't.id_topic = {int:topic}';
  1152. $subject_query['params']['topic'] = $search_params['topic'];
  1153. }
  1154. if (!empty($minMsgID))
  1155. {
  1156. $subject_query['where'][] = 't.id_first_msg >= {int:min_msg_id}';
  1157. $subject_query['params']['min_msg_id'] = $minMsgID;
  1158. }
  1159. if (!empty($maxMsgID))
  1160. {
  1161. $subject_query['where'][] = 't.id_last_msg <= {int:max_msg_id}';
  1162. $subject_query['params']['max_msg_id'] = $maxMsgID;
  1163. }
  1164. if (!empty($boardQuery))
  1165. {
  1166. $subject_query['where'][] = 't.id_board {raw:board_query}';
  1167. $subject_query['params']['board_query'] = $boardQuery;
  1168. }
  1169. if (!empty($excludedPhrases))
  1170. {
  1171. if ($subject_query['from'] != '{db_prefix}messages AS m')
  1172. {
  1173. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  1174. }
  1175. $count = 0;
  1176. foreach ($excludedPhrases as $phrase)
  1177. {
  1178. $subject_query['where'][] = 'm.subject NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:exclude_phrase_' . $count . '}';
  1179. $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:exclude_phrase_' . $count . '}';
  1180. $subject_query['params']['exclude_phrase_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
  1181. }
  1182. }
  1183. call_integration_hook('integrate_subject_search_query', array($subject_query));
  1184. // Nothing to search for?
  1185. if (empty($subject_query['where']))
  1186. continue;
  1187. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_topics', ($smcFunc['db_support_ignore'] ? ( '
  1188. INSERT IGNORE INTO {db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics
  1189. (' . ($createTemporary ? '' : 'id_search, ') . 'id_topic)') : '') . '
  1190. SELECT ' . ($createTemporary ? '' : $_SESSION['search_cache']['id_search'] . ', ') . 't.id_topic
  1191. FROM ' . $subject_query['from'] . (empty($subject_query['inner_join']) ? '' : '
  1192. INNER JOIN ' . implode('
  1193. INNER JOIN ', $subject_query['inner_join'])) . (empty($subject_query['left_join']) ? '' : '
  1194. LEFT JOIN ' . implode('
  1195. LEFT JOIN ', $subject_query['left_join'])) . '
  1196. WHERE ' . implode('
  1197. AND ', $subject_query['where']) . (empty($modSettings['search_max_results']) ? '' : '
  1198. LIMIT ' . ($modSettings['search_max_results'] - $numSubjectResults)),
  1199. $subject_query['params']
  1200. );
  1201. // Don't do INSERT IGNORE? Manually fix this up!
  1202. if (!$smcFunc['db_support_ignore'])
  1203. {
  1204. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1205. {
  1206. $ind = $createTemporary ? 0 : 1;
  1207. // No duplicates!
  1208. if (isset($inserts[$row[$ind]]))
  1209. continue;
  1210. $inserts[$row[$ind]] = $row;
  1211. }
  1212. $smcFunc['db_free_result']($ignoreRequest);
  1213. $numSubjectResults = count($inserts);
  1214. }
  1215. else
  1216. $numSubjectResults += $smcFunc['db_affected_rows']();
  1217. if (!empty($modSettings['search_max_results']) && $numSubjectResults >= $modSettings['search_max_results'])
  1218. break;
  1219. }
  1220. // Got some non-MySQL data to plonk in?
  1221. if (!empty($inserts))
  1222. {
  1223. $smcFunc['db_insert']('',
  1224. ('{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics'),
  1225. $createTemporary ? array('id_topic' => 'int') : array('id_search' => 'int', 'id_topic' => 'int'),
  1226. $inserts,
  1227. $createTemporary ? array('id_topic') : array('id_search', 'id_topic')
  1228. );
  1229. }
  1230. if ($numSubjectResults !== 0)
  1231. {
  1232. $main_query['weights']['subject']['search'] = 'CASE WHEN MAX(lst.id_topic) IS NULL THEN 0 ELSE 1 END';
  1233. $main_query['left_join'][] = '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics AS lst ON (' . ($createTemporary ? '' : 'lst.id_search = {int:id_search} AND ') . 'lst.id_topic = t.id_topic)';
  1234. if (!$createTemporary)
  1235. $main_query['parameters']['id_search'] = $_SESSION['search_cache']['id_search'];
  1236. }
  1237. }
  1238. $indexedResults = 0;
  1239. // We building an index?
  1240. if ($searchAPI->supportsMethod('indexedWordQuery', $query_params))
  1241. {
  1242. $inserts = array();
  1243. $smcFunc['db_search_query']('drop_tmp_log_search_messages', '
  1244. DROP TABLE IF EXISTS {db_prefix}tmp_log_search_messages',
  1245. array(
  1246. 'db_error_skip' => true,
  1247. )
  1248. );
  1249. $createTemporary = $smcFunc['db_search_query']('create_tmp_log_search_messages', '
  1250. CREATE TEMPORARY TABLE {db_prefix}tmp_log_search_messages (
  1251. id_msg int(10) unsigned NOT NULL default {string:string_zero},
  1252. PRIMARY KEY (id_msg)
  1253. ) TYPE=HEAP',
  1254. array(
  1255. 'string_zero' => '0',
  1256. 'db_error_skip' => true,
  1257. )
  1258. ) !== false;
  1259. // Clear, all clear!
  1260. if (!$createTemporary)
  1261. $smcFunc['db_search_query']('delete_log_search_messages', '
  1262. DELETE FROM {db_prefix}log_search_messages
  1263. WHERE id_search = {int:id_search}',
  1264. array(
  1265. 'id_search' => $_SESSION['search_cache']['id_search'],
  1266. )
  1267. );
  1268. foreach ($searchWords as $orIndex => $words)
  1269. {
  1270. // Search for this word, assuming we have some words!
  1271. if (!empty($words['indexed_words']))
  1272. {
  1273. // Variables required for the search.
  1274. $search_data = array(
  1275. 'insert_into' => ($createTemporary ? 'tmp_' : '') . 'log_search_messages',
  1276. 'no_regexp' => $no_regexp,
  1277. 'max_results' => $maxMessageResults,
  1278. 'indexed_results' => $indexedResults,
  1279. 'params' => array(
  1280. 'id_search' => !$createTemporary ? $_SESSION['search_cache']['id_search'] : 0,
  1281. 'excluded_words' => $excludedWords,
  1282. 'user_query' => !empty($userQuery) ? $userQuery : '',
  1283. 'board_query' => !empty($boardQuery) ? $boardQuery : '',
  1284. 'topic' => !empty($search_params['topic']) ? $search_params['topic'] : 0,
  1285. 'min_msg_id' => !empty($minMsgID) ? $minMsgID : 0,
  1286. 'max_msg_id' => !empty($maxMsgID) ? $maxMsgID : 0,
  1287. 'excluded_phrases' => !empty($excludedPhrases) ? $excludedPhrases : array(),
  1288. 'excluded_index_words' => !empty($excludedIndexWords) ? $excludedIndexWords : array(),
  1289. 'excluded_subject_words' => !empty($excludedSubjectWords) ? $excludedSubjectWords : array(),
  1290. ),
  1291. );
  1292. $ignoreRequest = $searchAPI->indexedWordQuery($words, $search_data);
  1293. if (!$smcFunc['db_support_ignore'])
  1294. {
  1295. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1296. {
  1297. // No duplicates!
  1298. if (isset($inserts[$row[0]]))
  1299. continue;
  1300. $inserts[$row[0]] = $row;
  1301. }
  1302. $smcFunc['db_free_result']($ignoreRequest);
  1303. $indexedResults = count($inserts);
  1304. }
  1305. else
  1306. $indexedResults += $smcFunc['db_affected_rows']();
  1307. if (!empty($maxMessageResults) && $indexedResults >= $maxMessageResults)
  1308. break;
  1309. }
  1310. }
  1311. // More non-MySQL stuff needed?
  1312. if (!empty($inserts))
  1313. {
  1314. $smcFunc['db_insert']('',
  1315. '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_messages',
  1316. $createTemporary ? array('id_msg' => 'int') : array('id_msg' => 'int', 'id_search' => 'int'),
  1317. $inserts,
  1318. $createTemporary ? array('id_msg') : array('id_msg', 'id_search')
  1319. );
  1320. }
  1321. if (empty($indexedResults) && empty($numSubjectResults) && !empty($modSettings['search_force_index']))
  1322. {
  1323. $context['search_errors']['query_not_specific_enough'] = true;
  1324. $_REQUEST['params'] = $context['params'];
  1325. return action_plushsearch1();
  1326. }
  1327. elseif (!empty($indexedResults))
  1328. {
  1329. $main_query['inner_join'][] = '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_messages AS lsm ON (lsm.id_msg = m.id_msg)';
  1330. if (!$createTemporary)
  1331. {
  1332. $main_query['where'][] = 'lsm.id_search = {int:id_search}';
  1333. $main_query['parameters']['id_search'] = $_SESSION['search_cache']['id_search'];
  1334. }
  1335. }
  1336. }
  1337. // Not using an index? All conditions have to be carried over.
  1338. else
  1339. {
  1340. $orWhere = array();
  1341. $count = 0;
  1342. foreach ($searchWords as $orIndex => $words)
  1343. {
  1344. $where = array();
  1345. foreach ($words['all_words'] as $regularWord)
  1346. {
  1347. $where[] = 'm.body' . (in_array($regularWord, $excludedWords) ? ' NOT' : '') . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:all_word_body_' . $count . '}';
  1348. if (in_array($regularWord, $excludedWords))
  1349. $where[] = 'm.subject NOT' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:all_word_body_' . $count . '}';
  1350. $main_query['parameters']['all_word_body_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($regularWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $regularWord), '\\\'') . '[[:>:]]';
  1351. }
  1352. if (!empty($where))
  1353. $orWhere[] = count($where) > 1 ? '(' . implode(' AND ', $where) . ')' : $where[0];
  1354. }
  1355. if (!empty($orWhere))
  1356. $main_query['where'][] = count($orWhere) > 1 ? '(' . implode(' OR ', $orWhere) . ')' : $orWhere[0];
  1357. if (!empty($userQuery))
  1358. {
  1359. $main_query['where'][] = '{raw:user_query}';
  1360. $main_query['parameters']['user_query'] = $userQuery;
  1361. }
  1362. if (!empty($search_params['topic']))
  1363. {
  1364. $main_query['where'][] = 'm.id_topic = {int:topic}';
  1365. $main_query['parameters']['topic'] = $search_params['topic'];
  1366. }
  1367. if (!empty($minMsgID))
  1368. {
  1369. $main_query['where'][] = 'm.id_msg >= {int:min_msg_id}';
  1370. $main_query['parameters']['min_msg_id'] = $minMsgID;
  1371. }
  1372. if (!empty($maxMsgID))
  1373. {
  1374. $main_query['where'][] = 'm.id_msg <= {int:max_msg_id}';
  1375. $main_query['parameters']['max_msg_id'] = $maxMsgID;
  1376. }
  1377. if (!empty($boardQuery))
  1378. {
  1379. $main_query['where'][] = 'm.id_board {raw:board_query}';
  1380. $main_query['parameters']['board_query'] = $boardQuery;
  1381. }
  1382. }
  1383. call_integration_hook('integrate_main_search_query', array($main_query));
  1384. // Did we either get some indexed results, or otherwise did not do an indexed query?
  1385. if (!empty($indexedResults) || !$searchAPI->supportsMethod('indexedWordQuery', $query_params))
  1386. {
  1387. $relevance = '1000 * (';
  1388. $new_weight_total = 0;
  1389. foreach ($main_query['weights'] as $type => $value)
  1390. {
  1391. $relevance .= $weight[$type];
  1392. if (!empty($value['search']))
  1393. $relevance .= ' * ' . $value['search'];
  1394. $relevance .= ' + ';
  1395. $new_weight_total += $weight[$type];
  1396. }
  1397. $main_query['select']['relevance'] = substr($relevance, 0, -3) . ') / ' . $new_weight_total . ' AS relevance';
  1398. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_results_no_index', ($smcFunc['db_support_ignore'] ? ( '
  1399. INSERT IGNORE INTO ' . '{db_prefix}log_search_results
  1400. (' . implode(', ', array_keys($main_query['select'])) . ')') : '') . '
  1401. SELECT
  1402. ' . implode(',
  1403. ', $main_query['select']) . '
  1404. FROM ' . $main_query['from'] . (empty($main_query['inner_join']) ? '' : '
  1405. INNER JOIN ' . implode('
  1406. INNER JOIN ', $main_query['inner_join'])) . (empty($main_query['left_join']) ? '' : '
  1407. LEFT JOIN ' . implode('
  1408. LEFT JOIN ', $main_query['left_join'])) . (!empty($main_query['where']) ? '
  1409. WHERE ' : '') . implode('
  1410. AND ', $main_query['where']) . (empty($main_query['group_by']) ? '' : '
  1411. GROUP BY ' . implode(', ', $main_query['group_by'])) . (empty($modSettings['search_max_results']) ? '' : '
  1412. LIMIT ' . $modSettings['search_max_results']),
  1413. $main_query['parameters']
  1414. );
  1415. // We love to handle non-good databases that don't support our ignore!
  1416. if (!$smcFunc['db_support_ignore'])
  1417. {
  1418. $inserts = array();
  1419. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1420. {
  1421. // No duplicates!
  1422. if (isset($inserts[$row[2]]))
  1423. continue;
  1424. foreach ($row as $key => $value)
  1425. $inserts[$row[2]][] = (int) $row[$key];
  1426. }
  1427. $smcFunc['db_free_result']($ignoreRequest);
  1428. // Now put them in!
  1429. if (!empty($inserts))
  1430. {
  1431. $query_columns = array();
  1432. foreach ($main_query['select'] as $k => $v)
  1433. $query_columns[$k] = 'int';
  1434. $smcFunc['db_insert']('',
  1435. '{db_prefix}log_search_results',
  1436. $query_columns,
  1437. $inserts,
  1438. array('id_search', 'id_topic')
  1439. );
  1440. }
  1441. $_SESSION['search_cache']['num_results'] += count($inserts);
  1442. }
  1443. else
  1444. $_SESSION['search_cache']['num_results'] = $smcFunc['db_affected_rows']();
  1445. }
  1446. // Insert subject-only matches.
  1447. if ($_SESSION['search_cache']['num_results'] < $modSettings['search_max_results'] && $numSubjectResults !== 0)
  1448. {
  1449. $relevance = '1000 * (';
  1450. foreach ($weight_factors as $type => $value)
  1451. if (isset($value['results']))
  1452. {
  1453. $relevance .= $weight[$type];
  1454. if (!empty($value['results']))
  1455. $relevance .= ' * ' . $value['results'];
  1456. $relevance .= ' + ';
  1457. }
  1458. $relevance = substr($relevance, 0, -3) . ') / ' . $weight_total . ' AS relevance';
  1459. $usedIDs = array_flip(empty($inserts) ? array() : array_keys($inserts));
  1460. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_results_sub_only', ($smcFunc['db_support_ignore'] ? ( '
  1461. INSERT IGNORE INTO {db_prefix}log_search_results
  1462. (id_search, id_topic, relevance, id_msg, num_matches)') : '') . '
  1463. SELECT
  1464. {int:id_search},
  1465. t.id_topic,
  1466. ' . $relevance . ',
  1467. t.id_first_msg,
  1468. 1
  1469. FROM {db_prefix}topics AS t
  1470. INNER JOIN {db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics AS lst ON (lst.id_topic = t.id_topic)'
  1471. . ($createTemporary ? '' : ' WHERE lst.id_search = {int:id_search}')
  1472. . (empty($modSettings['search_max_results']) ? '' : '
  1473. LIMIT ' . ($modSettings['search_max_results'] - $_SESSION['search_cache']['num_results'])),
  1474. array(
  1475. 'id_search' => $_SESSION['search_cache']['id_search'],
  1476. 'min_msg' => $minMsg,
  1477. 'recent_message' => $recentMsg,
  1478. 'huge_topic_posts' => $humungousTopicPosts,
  1479. )
  1480. );
  1481. // Once again need to do the inserts if the database don't support ignore!
  1482. if (!$smcFunc['db_support_ignore'])
  1483. {
  1484. $inserts = array();
  1485. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1486. {
  1487. // No duplicates!
  1488. if (isset($usedIDs[$row[1]]))
  1489. continue;
  1490. $usedIDs[$row[1]] = true;
  1491. $inserts[] = $row;
  1492. }
  1493. $smcFunc['db_free_result']($ignoreRequest);
  1494. // Now put them in!
  1495. if (!empty($inserts))
  1496. {
  1497. $smcFunc['db_insert']('',
  1498. '{db_prefix}log_search_results',
  1499. array('id_search' => 'int', 'id_topic' => 'int', 'relevance' => 'float', 'id_msg' => 'int', 'num_matches' => 'int'),
  1500. $inserts,
  1501. array('id_search', 'id_topic')
  1502. );
  1503. }
  1504. $_SESSION['search_cache']['num_results'] += count($inserts);
  1505. }
  1506. else
  1507. $_SESSION['search_cache']['num_results'] += $smcFunc['db_affected_rows']();
  1508. }
  1509. elseif ($_SESSION['search_cache']['num_results'] == -1)
  1510. $_SESSION['search_cache']['num_results'] = 0;
  1511. }
  1512. }
  1513. // *** Retrieve the results to be shown on the page
  1514. $participants = array();
  1515. $request = $smcFunc['db_search_query']('', '
  1516. SELECT ' . (empty($search_params['topic']) ? 'lsr.id_topic' : $search_params['topic'] . ' AS id_topic') . ', lsr.id_msg, lsr.relevance, lsr.num_matches
  1517. FROM {db_prefix}log_search_results AS lsr' . ($search_params['sort'] == 'num_replies' ? '
  1518. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = lsr.id_topic)' : '') . '
  1519. WHERE lsr.id_search = {int:id_search}
  1520. ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
  1521. LIMIT ' . (int) $_REQUEST['start'] . ', ' . $modSettings['search_results_per_page'],
  1522. array(
  1523. 'id_search' => $_SESSION['search_cache']['id_search'],
  1524. )
  1525. );
  1526. while ($row = $smcFunc['db_fetch_assoc']($request))
  1527. {
  1528. $context['topics'][$row['id_msg']] = array(
  1529. 'relevance' => round($row['relevance'] / 10, 1) . '%',
  1530. 'num_matches' => $row['num_matches'],
  1531. 'matches' => array(),
  1532. );
  1533. // By default they didn't participate in the topic!
  1534. $participants[$row['id_topic']] = false;
  1535. }
  1536. $smcFunc['db_free_result']($request);
  1537. $num_results = $_SESSION['search_cache']['num_results'];
  1538. }
  1539. if (!empty($context['topics']))
  1540. {
  1541. // Create an array for the permissions.
  1542. $boards_can = boardsAllowedTo(array('post_reply_own', 'post_reply_any', 'mark_any_notify'), true, false);
  1543. // How's about some quick moderation?
  1544. if (!empty($options['display_quick_mod']))
  1545. {
  1546. $boards_can = array_merge($boards_can, boardsAllowedTo(array('lock_any', 'lock_own', 'make_sticky', 'move_any', 'move_own', 'remove_any', 'remove_own', 'merge_any'), true, false));
  1547. $context['can_lock'] = in_array(0, $boards_can['lock_any']);
  1548. $context['can_sticky'] = in_array(0, $boards_can['make_sticky']) && !empty($modSettings['enableStickyTopics']);
  1549. $context['can_move'] = in_array(0, $boards_can['move_any']);
  1550. $context['can_remove'] = in_array(0, $boards_can['remove_any']);
  1551. $context['can_merge'] = in_array(0, $boards_can['merge_any']);
  1552. }
  1553. // What messages are we using?
  1554. $msg_list = array_keys($context['topics']);
  1555. // Load the posters...
  1556. $request = $smcFunc['db_query']('', '
  1557. SELECT id_member
  1558. FROM {db_prefix}messages
  1559. WHERE id_member != {int:no_member}
  1560. AND id_msg IN ({array_int:message_list})
  1561. LIMIT ' . count($context['topics']),
  1562. array(
  1563. 'message_list' => $msg_list,
  1564. 'no_member' => 0,
  1565. )
  1566. );
  1567. $posters = array();
  1568. while ($row = $smcFunc['db_fetch_assoc']($request))
  1569. $posters[] = $row['id_member'];
  1570. $smcFunc['db_free_result']($request);
  1571. if (!empty($posters))
  1572. loadMemberData(array_unique($posters));
  1573. call_integration_hook('integrate_search_message_list', array($msg_list, $posters));
  1574. // Get the messages out for the callback - select enough that it can be made to look just like Display.
  1575. $messages_request = $smcFunc['db_query']('', '
  1576. SELECT
  1577. m.id_msg, m.subject, m.poster_name, m.poster_email, m.poster_time, m.id_member,
  1578. m.icon, m.poster_ip, m.body, m.smileys_enabled, m.modified_time, m.modified_name,
  1579. first_m.id_msg AS first_msg, first_m.subject AS first_subject, first_m.icon AS first_icon, first_m.poster_time AS first_poster_time,
  1580. first_mem.id_member AS first_member_id, IFNULL(first_mem.real_name, first_m.poster_name) AS first_member_name,
  1581. last_m.id_msg AS last_msg, last_m.poster_time AS last_poster_time, last_mem.id_member AS last_member_id,
  1582. IFNULL(last_mem.real_name, last_m.poster_name) AS last_member_name, last_m.icon AS last_icon, last_m.subject AS last_subject,
  1583. t.id_topic, t.is_sticky, t.locked, t.id_poll, t.num_replies, t.num_views,
  1584. b.id_board, b.name AS board_name, c.id_cat, c.name AS cat_name
  1585. FROM {db_prefix}messages AS m
  1586. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  1587. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  1588. INNER JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  1589. INNER JOIN {db_prefix}messages AS first_m ON (first_m.id_msg = t.id_first_msg)
  1590. INNER JOIN {db_prefix}messages AS last_m ON (last_m.id_msg = t.id_last_msg)
  1591. LEFT JOIN {db_prefix}members AS first_mem ON (first_mem.id_member = first_m.id_member)
  1592. LEFT JOIN {db_prefix}members AS last_mem ON (last_mem.id_member = first_m.id_member)
  1593. WHERE m.id_msg IN ({array_int:message_list})' . ($modSettings['postmod_active'] ? '
  1594. AND m.approved = {int:is_approved}' : '') . '
  1595. ORDER BY FIND_IN_SET(m.id_msg, {string:message_list_in_set})
  1596. LIMIT {int:limit}',
  1597. array(
  1598. 'message_list' => $msg_list,
  1599. 'is_approved' => 1,
  1600. 'message_list_in_set' => implode(',', $msg_list),
  1601. 'limit' => count($context['topics']),
  1602. )
  1603. );
  1604. // If there are no results that means the things in the cache got deleted, so pretend we have no topics anymore.
  1605. if ($smcFunc['db_num_rows']($messages_request) == 0)
  1606. $context['topics'] = array();
  1607. // If we want to know who participated in what then load this now.
  1608. if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest'])
  1609. {
  1610. $result = $smcFunc['db_query']('', '
  1611. SELECT id_topic
  1612. FROM {db_prefix}messages
  1613. WHERE id_topic IN ({array_int:topic_list})
  1614. AND id_member = {int:current_member}
  1615. GROUP BY id_topic
  1616. LIMIT ' . count($participants),
  1617. array(
  1618. 'current_member' => $user_info['id'],
  1619. 'topic_list' => array_keys($participants),
  1620. )
  1621. );
  1622. while ($row = $smcFunc['db_fetch_assoc']($result))
  1623. $participants[$row['id_topic']] = true;
  1624. $smcFunc['db_free_result']($result);
  1625. }
  1626. }
  1627. // Now that we know how many results to expect we can start calculating the page numbers.
  1628. $context['page_index'] = constructPageIndex($scripturl . '?action=search2;params=' . $context['params'], $_REQUEST['start'], $num_results, $modSettings['search_results_per_page'], false);
  1629. // Consider the search complete!
  1630. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  1631. cache_put_data('search_start:' . ($user_info['is_guest'] ? $user_info['ip'] : $user_info['id']), null, 90);
  1632. $context['key_words'] = &$searchArray;
  1633. // Setup the default topic icons... for checking they exist and the like!
  1634. $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'poll', 'moved', 'recycled', 'wireless', 'clip');
  1635. $context['icon_sources'] = array();
  1636. foreach ($stable_icons as $icon)
  1637. $context['icon_sources'][$icon] = 'images_url';
  1638. $context['sub_template'] = 'results';
  1639. $context['page_title'] = $txt['search_results'];
  1640. $context['get_topics'] = 'prepareSearchContext';
  1641. $context['jump_to'] = array(
  1642. 'label' => addslashes(un_htmlspecialchars($txt['jump_to'])),
  1643. 'board_name' => addslashes(un_htmlspecialchars($txt['select_destination'])),
  1644. );
  1645. }
  1646. /**
  1647. * Allows to search through personal messages.
  1648. * ?action=pm;sa=search
  1649. * What it does:
  1650. * - shows the screen to search pm's (?action=pm;sa=search)
  1651. * - uses the search sub template of the PersonalMessage template.
  1652. * - decodes and loads search parameters given in the URL (if any).
  1653. * - the form redirects to index.php?action=pm;sa=search2.
  1654. */
  1655. function MessageSearch()
  1656. {
  1657. global $context, $txt, $scripturl, $modSettings, $smcFunc;
  1658. if (isset($_REQUEST['params']))
  1659. {
  1660. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  1661. $context['search_params'] = array();
  1662. foreach ($temp_params as $i => $data)
  1663. {
  1664. @list ($k, $v) = explode('|\'|', $data);
  1665. $context['search_params'][$k] = $v;
  1666. }
  1667. }
  1668. if (isset($_REQUEST['search']))
  1669. $context['search_params']['search'] = un_htmlspecialchars($_REQUEST['search']);
  1670. if (isset($context['search_params']['search']))
  1671. $context['search_params']['search'] = htmlspecialchars($context['search_params']['search']);
  1672. if (isset($context['search_params']['userspec']))
  1673. $context['search_params']['userspec'] = htmlspecialchars($context['search_params']['userspec']);
  1674. if (!empty($context['search_params']['searchtype']))
  1675. $context['search_params']['searchtype'] = 2;
  1676. if (!empty($context['search_params']['minage']))
  1677. $context['search_params']['minage'] = (int) $context['search_params']['minage'];
  1678. if (!empty($context['search_params']['maxage']))
  1679. $context['search_params']['maxage'] = (int) $context['search_params']['maxage'];
  1680. $context['search_params']['show_complete'] = !empty($context['search_params']['show_complete']);
  1681. $context['search_params']['subject_only'] = !empty($context['search_params']['subject_only']);
  1682. // Create the array of labels to be searched.
  1683. $context['search_labels'] = array();
  1684. $searchedLabels = isset($context['search_params']['labels']) && $context['search_params']['labels'] != '' ? explode(',', $context['search_params']['labels']) : array();
  1685. foreach ($context['labels'] as $label)
  1686. {
  1687. $context['search_labels'][] = array(
  1688. 'id' => $label['id'],
  1689. 'name' => $label['name'],
  1690. 'checked' => !empty($searchedLabels) ? in_array($label['id'], $searchedLabels) : true,
  1691. );
  1692. }
  1693. // Are all the labels checked?
  1694. $context['check_all'] = empty($searchedLabels) || count($context['search_labels']) == count($searchedLabels);
  1695. // Load the error text strings if there were errors in the search.
  1696. if (!empty($context['search_errors']))
  1697. {
  1698. loadLanguage('Errors');
  1699. $context['search_errors']['messages'] = array();
  1700. foreach ($context['search_errors'] as $search_error => $dummy)
  1701. {
  1702. if ($search_error === 'messages')
  1703. continue;
  1704. $context['search_errors']['messages'][] = $txt['error_' . $search_error];
  1705. }
  1706. }
  1707. $context['simple_search'] = isset($context['search_params']['advanced']) ? empty($context['search_params']['advanced']) : !empty($modSettings['simpleSearch']) && !isset($_REQUEST['advanced']);
  1708. $context['page_title'] = $txt['pm_search_title'];
  1709. $context['sub_template'] = 'search';
  1710. $context['linktree'][] = array(
  1711. 'url' => $scripturl . '?action=pm;sa=search',
  1712. 'name' => $txt['pm_search_bar_title'],
  1713. );
  1714. }
  1715. /**
  1716. * Actually do the search of personal messages and show the results
  1717. * ?action=pm;sa=search2
  1718. * What it does:
  1719. * - checks user input and searches the pm table for messages matching the query.
  1720. * - uses the search_results sub template of the PersonalMessage template.
  1721. * - show the results of the search query.
  1722. */
  1723. function MessageSearch2()
  1724. {
  1725. global $scripturl, $modSettings, $user_info, $context, $txt;
  1726. global $memberContext, $smcFunc;
  1727. if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
  1728. fatal_lang_error('loadavg_search_disabled', false);
  1729. // @todo For the moment force the folder to the inbox.
  1730. // @todo Maybe set the inbox based on a cookie or theme setting?
  1731. $context['folder'] = 'inbox';
  1732. // Some useful general permissions.
  1733. $context['can_send_pm'] = allowedTo('pm_send');
  1734. // Some hardcoded veriables that can be tweaked if required.
  1735. $maxMembersToSearch = 500;
  1736. // Extract all the search parameters.
  1737. $search_params = array();
  1738. if (isset($_REQUEST['params']))
  1739. {
  1740. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  1741. foreach ($temp_params as $i => $data)
  1742. {
  1743. @list ($k, $v) = explode('|\'|', $data);
  1744. $search_params[$k] = $v;
  1745. }
  1746. }
  1747. $context['start'] = isset($_GET['start']) ? (int) $_GET['start'] : 0;
  1748. // Store whether simple search was used (needed if the user wants to do another query).
  1749. if (!isset($search_params['advanced']))
  1750. $search_params['advanced'] = empty($_REQUEST['advanced']) ? 0 : 1;
  1751. // 1 => 'allwords' (default, don't set as param) / 2 => 'anywords'.
  1752. if (!empty($search_params['searchtype']) || (!empty($_REQUEST['searchtype']) && $_REQUEST['searchtype'] == 2))
  1753. $search_params['searchtype'] = 2;
  1754. // Minimum age of messages. Default to zero (don't set param in that case).
  1755. if (!empty($search_params['minage']) || (!empty($_REQUEST['minage']) && $_REQUEST['minage'] > 0))
  1756. $search_params['minage'] = !empty($search_params['minage']) ? (int) $search_params['minage'] : (int) $_REQUEST['minage'];
  1757. // Maximum age of messages. Default to infinite (9999 days: param not set).
  1758. if (!empty($search_params['maxage']) || (!empty($_REQUEST['maxage']) && $_REQUEST['maxage'] < 9999))
  1759. $search_params['maxage'] = !empty($search_params['maxage']) ? (int) $search_params['maxage'] : (int) $_REQUEST['maxage'];
  1760. $search_params['subject_only'] = !empty($search_params['subject_only']) || !empty($_REQUEST['subject_only']);
  1761. $search_params['show_complete'] = !empty($search_params['show_complete']) || !empty($_REQUEST['show_complete']);
  1762. // Default the user name to a wildcard matching every user (*).
  1763. if (!empty($search_params['userspec']) || (!empty($_REQUEST['userspec']) && $_REQUEST['userspec'] != '*'))
  1764. $search_params['userspec'] = isset($search_params['userspec']) ? $search_params['userspec'] : $_REQUEST['userspec'];
  1765. // This will be full of all kinds of parameters!
  1766. $searchq_parameters = array();
  1767. // If there's no specific user, then don't mention it in the main query.
  1768. if (empty($search_params['userspec']))
  1769. $userQuery = '';
  1770. else
  1771. {
  1772. $userString = strtr($smcFunc['htmlspecialchars']($search_params['userspec'], ENT_QUOTES), array('&quot;' => '"'));
  1773. $userString = strtr($userString, array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_'));
  1774. preg_match_all('~"([^"]+)"~', $userString, $matches);
  1775. $possible_users = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $userString)));
  1776. for ($k = 0, $n = count($possible_users); $k < $n; $k++)
  1777. {
  1778. $possible_users[$k] = trim($possible_users[$k]);
  1779. if (strlen($possible_users[$k]) == 0)
  1780. unset($possible_users[$k]);
  1781. }
  1782. // Who matches those criteria?
  1783. // @todo This doesn't support sent item searching.
  1784. $request = $smcFunc['db_query']('', '
  1785. SELECT id_member
  1786. FROM {db_prefix}members
  1787. WHERE real_name LIKE {raw:real_name_implode}',
  1788. array(
  1789. 'real_name_implode' => '\'' . implode('\' OR real_name LIKE \'', $possible_users) . '\'',
  1790. )
  1791. );
  1792. // Simply do nothing if there're too many members matching the criteria.
  1793. if ($smcFunc['db_num_rows']($request) > $maxMembersToSearch)
  1794. $userQuery = '';
  1795. elseif ($smcFunc['db_num_rows']($request) == 0)
  1796. {
  1797. $userQuery = 'AND pm.id_member_from = 0 AND (pm.from_name LIKE {raw:guest_user_name_implode})';
  1798. $searchq_parameters['guest_user_name_implode'] = '\'' . implode('\' OR pm.from_name LIKE \'', $possible_users) . '\'';
  1799. }
  1800. else
  1801. {
  1802. $memberlist = array();
  1803. while ($row = $smcFunc['db_fetch_assoc']($request))
  1804. $memberlist[] = $row['id_member'];
  1805. $userQuery = 'AND (pm.id_member_from IN ({array_int:member_list}) OR (pm.id_member_from = 0 AND (pm.from_name LIKE {raw:guest_user_name_implode})))';
  1806. $searchq_parameters['guest_user_name_implode'] = '\'' . implode('\' OR pm.from_name LIKE \'', $possible_users) . '\'';
  1807. $searchq_parameters['member_list'] = $memberlist;
  1808. }
  1809. $smcFunc['db_free_result']($request);
  1810. }
  1811. // Setup the sorting variables...
  1812. // @todo Add more in here!
  1813. $sort_columns = array(
  1814. 'pm.id_pm',
  1815. );
  1816. if (empty($search_params['sort']) && !empty($_REQUEST['sort']))
  1817. list ($search_params['sort'], $search_params['sort_dir']) = array_pad(explode('|', $_REQUEST['sort']), 2, '');
  1818. $search_params['sort'] = !empty($search_params['sort']) && in_array($search_params['sort'], $sort_columns) ? $search_params['sort'] : 'pm.id_pm';
  1819. $search_params['sort_dir'] = !empty($search_params['sort_dir']) && $search_params['sort_dir'] == 'asc' ? 'asc' : 'desc';
  1820. // Sort out any labels we may be searching by.
  1821. $labelQuery = '';
  1822. if ($context['folder'] == 'inbox' && !empty($search_params['advanced']) && $context['currently_using_labels'])
  1823. {
  1824. // Came here from pagination? Put them back into $_REQUEST for sanitization.
  1825. if (isset($search_params['labels']))
  1826. $_REQUEST['searchlabel'] = explode(',', $search_params['labels']);
  1827. // Assuming we have some labels - make them all integers.
  1828. if (!empty($_REQUEST['searchlabel']) && is_array($_REQUEST['searchlabel']))
  1829. {
  1830. foreach ($_REQUEST['searchlabel'] as $key => $id)
  1831. $_REQUEST['searchlabel'][$key] = (int) $id;
  1832. }
  1833. else
  1834. $_REQUEST['searchlabel'] = array();
  1835. // Now that everything is cleaned up a bit, make the labels a param.
  1836. $search_params['labels'] = implode(',', $_REQUEST['searchlabel']);
  1837. // No labels selected? That must be an error!
  1838. if (empty($_REQUEST['searchlabel']))
  1839. $context['search_errors']['no_labels_selected'] = true;
  1840. // Otherwise prepare the query!
  1841. elseif (count($_REQUEST['searchlabel']) != count($context['labels']))
  1842. {
  1843. $labelQuery = '
  1844. AND {raw:label_implode}';
  1845. $labelStatements = array();
  1846. foreach ($_REQUEST['searchlabel'] as $label)
  1847. $labelStatements[] = $smcFunc['db_quote']('FIND_IN_SET({string:label}, pmr.labels) != 0', array(
  1848. 'label' => $label,
  1849. ));
  1850. $searchq_parameters['label_implode'] = '(' . implode(' OR ', $labelStatements) . ')';
  1851. }
  1852. }
  1853. // Unfortunately, searching for words like this is going to be slow, so we're blacklisting them.
  1854. $blacklisted_words = array('quote', 'the', 'is', 'it', 'are', 'if');
  1855. // What are we actually searching for?
  1856. $search_params['search'] = !empty($search_params['search']) ? $search_params['search'] : (isset($_REQUEST['search']) ? $_REQUEST['search'] : '');
  1857. // If we ain't got nothing - we should error!
  1858. if (!isset($search_params['search']) || $search_params['search'] == '')
  1859. $context['search_errors']['invalid_search_string'] = true;
  1860. // Change non-word characters into spaces.
  1861. $stripped_query = preg_replace('~(?:[\x0B\0\x{A0}\t\r\s\n(){}\\[\\]<>!@$%^*.,:+=`\~\?/\\\\]+|&(?:amp|lt|gt|quot);)+~u', ' ', $search_params['search']);
  1862. // Make the query lower case since it will case insensitive anyway.
  1863. $stripped_query = un_htmlspecialchars($smcFunc['strtolower']($stripped_query));
  1864. // Extract phrase parts first (e.g. some words "this is a phrase" some more words.)
  1865. preg_match_all('/(?:^|\s)([-]?)"([^"]+)"(?:$|\s)/', $stripped_query, $matches, PREG_PATTERN_ORDER);
  1866. $phraseArray = $matches[2];
  1867. // Remove the phrase parts and extract the words.
  1868. $wordArray = preg_replace('~(?:^|\s)(?:[-]?)"(?:[^"]+)"(?:$|\s)~u', ' ', $search_params['search']);
  1869. $wordArray = explode(' ', $smcFunc['htmlspecialchars'](un_htmlspecialchars($wordArray), ENT_QUOTES));
  1870. // A minus sign in front of a word excludes the word.... so...
  1871. $excludedWords = array();
  1872. // Check for things like -"some words", but not "-some words".
  1873. foreach ($matches[1] as $index => $word)
  1874. {
  1875. if ($word === '-')
  1876. {
  1877. if (($word = trim($phraseArray[$index], '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
  1878. $excludedWords[] = $word;
  1879. unset($phraseArray[$index]);
  1880. }
  1881. }
  1882. // Now we look for -test, etc
  1883. foreach ($wordArray as $index => $word)
  1884. {
  1885. if (strpos(trim($word), '-') === 0)
  1886. {
  1887. if (($word = trim($word, '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
  1888. $excludedWords[] = $word;
  1889. unset($wordArray[$index]);
  1890. }
  1891. }
  1892. // The remaining words and phrases are all included.
  1893. $searchArray = array_merge($phraseArray, $wordArray);
  1894. // Trim everything and make sure there are no words that are the same.
  1895. foreach ($searchArray as $index => $value)
  1896. {
  1897. // Skip anything thats close to empty.
  1898. if (($searchArray[$index] = trim($value, '-_\' ')) === '')
  1899. unset($searchArray[$index]);
  1900. // Skip blacklisted words. Make sure to note we skipped them as well
  1901. elseif (in_array($searchArray[$index], $blacklisted_words))
  1902. {
  1903. $foundBlackListedWords = true;
  1904. unset($searchArray[$index]);
  1905. }
  1906. $searchArray[$index] = $smcFunc['strtolower'](trim($value));
  1907. if ($searchArray[$index] == '')
  1908. unset($searchArray[$index]);
  1909. else
  1910. {
  1911. // Sort out entities first.
  1912. $searchArray[$index] = $smcFunc['htmlspecialchars']($searchArray[$index]);
  1913. }
  1914. }
  1915. $searchArray = array_slice(array_unique($searchArray), 0, 10);
  1916. // Create an array of replacements for highlighting.
  1917. $context['mark'] = array();
  1918. foreach ($searchArray as $word)
  1919. $context['mark'][$word] = '<strong class="highlight">' . $word . '</strong>';
  1920. // This contains *everything*
  1921. $searchWords = array_merge($searchArray, $excludedWords);
  1922. // Make sure at least one word is being searched for.
  1923. if (empty($searchArray))
  1924. $context['search_errors']['invalid_search_string'] = true;
  1925. // Sort out the search query so the user can edit it - if they want.
  1926. $context['search_params'] = $search_params;
  1927. if (isset($context['search_params']['search']))
  1928. $context['search_params']['search'] = $smcFunc['htmlspecialchars']($context['search_params']['search']);
  1929. if (isset($context['search_params']['userspec']))
  1930. $context['search_params']['userspec'] = $smcFunc['htmlspecialchars']($context['search_params']['userspec']);
  1931. // Now we have all the parameters, combine them together for pagination and the like...
  1932. $context['params'] = array();
  1933. foreach ($search_params as $k => $v)
  1934. $context['params'][] = $k . '|\'|' . $v;
  1935. $context['params'] = base64_encode(implode('|"|', $context['params']));
  1936. // Compile the subject query part.
  1937. $andQueryParts = array();
  1938. foreach ($searchWords as $index => $word)
  1939. {
  1940. if ($word == '')
  1941. continue;
  1942. if ($search_params['subject_only'])
  1943. $andQueryParts[] = 'pm.subject' . (in_array($word, $excludedWords) ? ' NOT' : '') . ' LIKE {string:search_' . $index . '}';
  1944. else
  1945. $andQueryParts[] = '(pm.subject' . (in_array($word, $excludedWords) ? ' NOT' : '') . ' LIKE {string:search_' . $index . '} ' . (in_array($word, $excludedWords) ? 'AND pm.body NOT' : 'OR pm.body') . ' LIKE {string:search_' . $index . '})';
  1946. $searchq_parameters['search_' . $index] = '%' . strtr($word, array('_' => '\\_', '%' => '\\%')) . '%';
  1947. }
  1948. $searchQuery = ' 1=1';
  1949. if (!empty($andQueryParts))
  1950. $searchQuery = implode(!empty($search_params['searchtype']) && $search_params['searchtype'] == 2 ? ' OR ' : ' AND ', $andQueryParts);
  1951. // Age limits?
  1952. $timeQuery = '';
  1953. if (!empty($search_params['minage']))
  1954. $timeQuery .= ' AND pm.msgtime < ' . (time() - $search_params['minage'] * 86400);
  1955. if (!empty($search_params['maxage']))
  1956. $timeQuery .= ' AND pm.msgtime > ' . (time() - $search_params['maxage'] * 86400);
  1957. // If we have errors - return back to the first screen...
  1958. if (!empty($context['search_errors']))
  1959. {
  1960. $_REQUEST['params'] = $context['params'];
  1961. return MessageSearch();
  1962. }
  1963. // Get the amount of results.
  1964. $request = $smcFunc['db_query']('', '
  1965. SELECT COUNT(*)
  1966. FROM {db_prefix}pm_recipients AS pmr
  1967. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  1968. WHERE ' . ($context['folder'] == 'inbox' ? '
  1969. pmr.id_member = {int:current_member}
  1970. AND pmr.deleted = {int:not_deleted}' : '
  1971. pm.id_member_from = {int:current_member}
  1972. AND pm.deleted_by_sender = {int:not_deleted}') . '
  1973. ' . $userQuery . $labelQuery . $timeQuery . '
  1974. AND (' . $searchQuery . ')',
  1975. array_merge($searchq_parameters, array(
  1976. 'current_member' => $user_info['id'],
  1977. 'not_deleted' => 0,
  1978. ))
  1979. );
  1980. list ($numResults) = $smcFunc['db_fetch_row']($request);
  1981. $smcFunc['db_free_result']($request);
  1982. // Get all the matching messages... using standard search only (No caching and the like!)
  1983. // @todo This doesn't support sent item searching yet.
  1984. $request = $smcFunc['db_query']('', '
  1985. SELECT pm.id_pm, pm.id_pm_head, pm.id_member_from
  1986. FROM {db_prefix}pm_recipients AS pmr
  1987. INNER JOIN {db_prefix}personal_messages AS pm ON (pm.id_pm = pmr.id_pm)
  1988. WHERE ' . ($context['folder'] == 'inbox' ? '
  1989. pmr.id_member = {int:current_member}
  1990. AND pmr.deleted = {int:not_deleted}' : '
  1991. pm.id_member_from = {int:current_member}
  1992. AND pm.deleted_by_sender = {int:not_deleted}') . '
  1993. ' . $userQuery . $labelQuery . $timeQuery . '
  1994. AND (' . $searchQuery . ')
  1995. ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
  1996. LIMIT ' . $context['start'] . ', ' . $modSettings['search_results_per_page'],
  1997. array_merge($searchq_parameters, array(
  1998. 'current_member' => $user_info['id'],
  1999. 'not_deleted' => 0,
  2000. ))
  2001. );
  2002. $foundMessages = array();
  2003. $posters = array();
  2004. $head_pms = array();
  2005. while ($row = $smcFunc['db_fetch_assoc']($request))
  2006. {
  2007. $foundMessages[] = $row['id_pm'];
  2008. $posters[] = $row['id_member_from'];
  2009. $head_pms[$row['id_pm']] = $row['id_pm_head'];
  2010. }
  2011. $smcFunc['db_free_result']($request);
  2012. // Find the real head pms!
  2013. if ($context['display_mode'] == 2 && !empty($head_pms))
  2014. {
  2015. $request = $smcFunc['db_query']('', '
  2016. SELECT MAX(pm.id_pm) AS id_pm, pm.id_pm_head
  2017. FROM {db_prefix}personal_messages AS pm
  2018. INNER JOIN {db_prefix}pm_recipients AS pmr ON (pmr.id_pm = pm.id_pm)
  2019. WHERE pm.id_pm_head IN ({array_int:head_pms})
  2020. AND pmr.id_member = {int:current_member}
  2021. AND pmr.deleted = {int:not_deleted}
  2022. GROUP BY pm.id_pm_head
  2023. LIMIT {int:limit}',
  2024. array(
  2025. 'head_pms' => array_unique($head_pms),
  2026. 'current_member' => $user_info['id'],
  2027. 'not_deleted' => 0,
  2028. 'limit' => count($head_pms),
  2029. )
  2030. );
  2031. $real_pm_ids = array();
  2032. while ($row = $smcFunc['db_fetch_assoc']($request))
  2033. $real_pm_ids[$row['id_pm_head']] = $row['id_pm'];
  2034. $smcFunc['db_free_result']($request);
  2035. }
  2036. // Load the users...
  2037. $posters = array_unique($posters);
  2038. if (!empty($posters))
  2039. loadMemberData($posters);
  2040. // Sort out the page index.
  2041. $context['page_index'] = constructPageIndex($scripturl . '?action=pm;sa=search2;params=' . $context['params'], $_GET['start'], $numResults, $modSettings['search_results_per_page'], false);
  2042. $context['message_labels'] = array();
  2043. $context['message_replied'] = array();
  2044. $context['personal_messages'] = array();
  2045. if (!empty($foundMessages))
  2046. {
  2047. // Now get recipients (but don't include bcc-recipients for your inbox, you're not supposed to know :P!)
  2048. $request = $smcFunc['db_query']('', '
  2049. SELECT
  2050. pmr.id_pm, mem_to.id_member AS id_member_to, mem_to.real_name AS to_name,
  2051. pmr.bcc, pmr.labels, pmr.is_read
  2052. FROM {db_prefix}pm_recipients AS pmr
  2053. LEFT JOIN {db_prefix}members AS mem_to ON (mem_to.id_member = pmr.id_member)
  2054. WHERE pmr.id_pm IN ({array_int:message_list})',
  2055. array(
  2056. 'message_list' => $foundMessages,
  2057. )
  2058. );
  2059. while ($row = $smcFunc['db_fetch_assoc']($request))
  2060. {
  2061. if ($context['folder'] == 'sent' || empty($row['bcc']))
  2062. $recipients[$row['id_pm']][empty($row['bcc']) ? 'to' : 'bcc'][] = empty($row['id_member_to']) ? $txt['guest_title'] : '<a href="' . $scripturl . '?action=profile;u=' . $row['id_member_to'] . '">' . $row['to_name'] . '</a>';
  2063. if ($row['id_member_to'] == $user_info['id'] && $context['folder'] != 'sent')
  2064. {
  2065. $context['message_replied'][$row['id_pm']] = $row['is_read'] & 2;
  2066. $row['labels'] = $row['labels'] == '' ? array() : explode(',', $row['labels']);
  2067. // This is a special need for linking to messages.
  2068. foreach ($row['labels'] as $v)
  2069. {
  2070. if (isset($context['labels'][(int) $v]))
  2071. $context['message_labels'][$row['id_pm']][(int) $v] = array('id' => $v, 'name' => $context['labels'][(int) $v]['name']);
  2072. // Here we find the first label on a message - for linking to posts in results
  2073. if (!isset($context['first_label'][$row['id_pm']]) && !in_array('-1', $row['labels']))
  2074. $context['first_label'][$row['id_pm']] = (int) $v;
  2075. }
  2076. }
  2077. }
  2078. // Prepare the query for the callback!
  2079. $request = $smcFunc['db_query']('', '
  2080. SELECT pm.id_pm, pm.subject, pm.id_member_from, pm.body, pm.msgtime, pm.from_name
  2081. FROM {db_prefix}personal_messages AS pm
  2082. WHERE pm.id_pm IN ({array_int:message_list})
  2083. ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
  2084. LIMIT ' . count($foundMessages),
  2085. array(
  2086. 'message_list' => $foundMessages,
  2087. )
  2088. );
  2089. $counter = 0;
  2090. while ($row = $smcFunc['db_fetch_assoc']($request))
  2091. {
  2092. // If there's no message subject, use the default.
  2093. $row['subject'] = $row['subject'] == '' ? $txt['no_subject'] : $row['subject'];
  2094. // Load this posters context info, if it ain't there then fill in the essentials...
  2095. if (!loadMemberContext($row['id_member_from'], true))
  2096. {
  2097. $memberContext[$row['id_member_from']]['name'] = $row['from_name'];
  2098. $memberContext[$row['id_member_from']]['id'] = 0;
  2099. $memberContext[$row['id_member_from']]['group'] = $txt['guest_title'];
  2100. $memberContext[$row['id_member_from']]['link'] = $row['from_name'];
  2101. $memberContext[$row['id_member_from']]['email'] = '';
  2102. $memberContext[$row['id_member_from']]['show_email'] = showEmailAddress(true, 0);
  2103. $memberContext[$row['id_member_from']]['is_guest'] = true;
  2104. }
  2105. // Censor anything we don't want to see...
  2106. censorText($row['body']);
  2107. censorText($row['subject']);
  2108. // Parse out any BBC...
  2109. $row['body'] = parse_bbc($row['body'], true, 'pm' . $row['id_pm']);
  2110. // Highlight the hits
  2111. foreach ($searchArray as $query)
  2112. {
  2113. // Fix the international characters in the keyword too.
  2114. $query = un_htmlspecialchars($query);
  2115. $query = trim($query, "\*+");
  2116. $query = strtr($smcFunc['htmlspecialchars']($query), array('\\\'' => '\''));
  2117. $body_highlighted = preg_replace('/((<[^>]*)|' . preg_quote(strtr($query, array('\'' => '&#039;')), '/') . ')/ieu', "'\$2' == '\$1' ? stripslashes('\$1') : '<strong class=\"highlight\">\$1</strong>'", $row['body']);
  2118. $subject_highlighted = preg_replace('/(' . preg_quote($query, '/') . ')/iu', '<strong class="highlight">$1</strong>', $row['subject']);
  2119. }
  2120. $href = $scripturl . '?action=pm;f=' . $context['folder'] . (isset($context['first_label'][$row['id_pm']]) ? ';l=' . $context['first_label'][$row['id_pm']] : '') . ';pmid=' . ($context['display_mode'] == 2 && isset($real_pm_ids[$head_pms[$row['id_pm']]]) ? $real_pm_ids[$head_pms[$row['id_pm']]] : $row['id_pm']) . '#msg' . $row['id_pm'];
  2121. $context['personal_messages'][] = array(
  2122. 'id' => $row['id_pm'],
  2123. 'member' => &$memberContext[$row['id_member_from']],
  2124. 'subject' => $subject_highlighted,
  2125. 'body' => $body_highlighted,
  2126. 'time' => timeformat($row['msgtime']),
  2127. 'recipients' => &$recipients[$row['id_pm']],
  2128. 'labels' => &$context['message_labels'][$row['id_pm']],
  2129. 'fully_labeled' => count($context['message_labels'][$row['id_pm']]) == count($context['labels']),
  2130. 'is_replied_to' => &$context['message_replied'][$row['id_pm']],
  2131. 'href' => $href,
  2132. 'link' => '<a href="' . $href . '">' . $subject_highlighted . '</a>',
  2133. 'counter' => ++$counter,
  2134. );
  2135. }
  2136. $smcFunc['db_free_result']($request);
  2137. }
  2138. // Finish off the context.
  2139. $context['page_title'] = $txt['pm_search_title'];
  2140. $context['sub_template'] = 'search_results';
  2141. $context['menu_data_' . $context['pm_menu_id']]['current_area'] = 'search';
  2142. $context['linktree'][] = array(
  2143. 'url' => $scripturl . '?action=pm;sa=search',
  2144. 'name' => $txt['pm_search_bar_title'],
  2145. );
  2146. }
  2147. /**
  2148. * Callback to return messages - saves memory.
  2149. * @todo Fix this, update it, whatever... from Display.controller.php mainly.
  2150. * Note that the call to loadAttachmentContext() doesn't work:
  2151. * this function doesn't fulfill the pre-condition to fill $attachments global...
  2152. * So all it does is to fallback and return.
  2153. *
  2154. * What it does:
  2155. * - callback function for the results sub template.
  2156. * - loads the necessary contextual data to show a search result.
  2157. *
  2158. * @param $reset = false
  2159. * @return array
  2160. */
  2161. function prepareSearchContext($reset = false)
  2162. {
  2163. global $txt, $modSettings, $scripturl, $user_info;
  2164. global $memberContext, $context, $settings, $options, $messages_request;
  2165. global $boards_can, $participants, $smcFunc;
  2166. // Remember which message this is. (ie. reply #83)
  2167. static $counter = null;
  2168. if ($counter == null || $reset)
  2169. $counter = $_REQUEST['start'] + 1;
  2170. // If the query returned false, bail.
  2171. if ($messages_request == false)
  2172. return false;
  2173. // Start from the beginning...
  2174. if ($reset)
  2175. return @$smcFunc['db_data_seek']($messages_request, 0);
  2176. // Attempt to get the next message.
  2177. $message = $smcFunc['db_fetch_assoc']($messages_request);
  2178. if (!$message)
  2179. return false;
  2180. // Can't have an empty subject can we?
  2181. $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
  2182. $message['first_subject'] = $message['first_subject'] != '' ? $message['first_subject'] : $txt['no_subject'];
  2183. $message['last_subject'] = $message['last_subject'] != '' ? $message['last_subject'] : $txt['no_subject'];
  2184. // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
  2185. if (!loadMemberContext($message['id_member']))
  2186. {
  2187. // Notice this information isn't used anywhere else.... *cough guest table cough*.
  2188. $memberContext[$message['id_member']]['name'] = $message['poster_name'];
  2189. $memberContext[$message['id_member']]['id'] = 0;
  2190. $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
  2191. $memberContext[$message['id_member']]['link'] = $message['poster_name'];
  2192. $memberContext[$message['id_member']]['email'] = $message['poster_email'];
  2193. }
  2194. $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
  2195. // Do the censor thang...
  2196. censorText($message['body']);
  2197. censorText($message['subject']);
  2198. censorText($message['first_subject']);
  2199. censorText($message['last_subject']);
  2200. // Shorten this message if necessary.
  2201. if ($context['compact'])
  2202. {
  2203. // Set the number of characters before and after the searched keyword.
  2204. $charLimit = 50;
  2205. $message['body'] = strtr($message['body'], array("\n" => ' ', '<br />' => "\n"));
  2206. $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
  2207. $message['body'] = strip_tags(strtr($message['body'], array('</div>' => '<br />', '</li>' => '<br />')), '<br>');
  2208. if ($smcFunc['strlen']($message['body']) > $charLimit)
  2209. {
  2210. if (empty($context['key_words']))
  2211. $message['body'] = $smcFunc['substr']($message['body'], 0, $charLimit) . '<strong>...</strong>';
  2212. else
  2213. {
  2214. $matchString = '';
  2215. $force_partial_word = false;
  2216. foreach ($context['key_words'] as $keyword)
  2217. {
  2218. $keyword = un_htmlspecialchars($keyword);
  2219. $keyword = preg_replace('~(&amp;#(\d{1,7}|x[0-9a-fA-F]{1,6});)~e', 'entity_fix__callback', strtr($keyword, array('\\\'' => '\'', '&' => '&amp;')));
  2220. if (preg_match('~[\'\.,/@%&;:(){}\[\]_\-+\\\\]$~', $keyword) != 0 || preg_match('~^[\'\.,/@%&;:(){}\[\]_\-+\\\\]~', $keyword) != 0)
  2221. $force_partial_word = true;
  2222. $matchString .= strtr(preg_quote($keyword, '/'), array('\*' => '.+?')) . '|';
  2223. }
  2224. $matchString = un_htmlspecialchars(substr($matchString, 0, -1));
  2225. $message['body'] = un_htmlspecialchars(strtr($message['body'], array('&nbsp;' => ' ', '<br />' => "\n", '&#91;' => '[', '&#93;' => ']', '&#58;' => ':', '&#64;' => '@')));
  2226. if (empty($modSettings['search_method']) || $force_partial_word)
  2227. preg_match_all('/([^\s\W]{' . $charLimit . '}[\s\W]|[\s\W].{0,' . $charLimit . '}?|^)(' . $matchString . ')(.{0,' . $charLimit . '}[\s\W]|[^\s\W]{0,' . $charLimit . '})/isu', $message['body'], $matches);
  2228. else
  2229. preg_match_all('/([^\s\W]{' . $charLimit . '}[\s\W]|[\s\W].{0,' . $charLimit . '}?[\s\W]|^)(' . $matchString . ')([\s\W].{0,' . $charLimit . '}[\s\W]|[\s\W][^\s\W]{0,' . $charLimit . '})/isu', $message['body'], $matches);
  2230. $message['body'] = '';
  2231. foreach ($matches[0] as $index => $match)
  2232. {
  2233. $match = strtr(htmlspecialchars($match, ENT_QUOTES), array("\n" => '&nbsp;'));
  2234. $message['body'] .= '<strong>......</strong>&nbsp;' . $match . '&nbsp;<strong>......</strong>';
  2235. }
  2236. }
  2237. // Re-fix the international characters.
  2238. $message['body'] = preg_replace('~(&amp;#(\d{1,7}|x[0-9a-fA-F]{1,6});)~e', 'entity_fix__callback', $message['body']);
  2239. }
  2240. }
  2241. else
  2242. {
  2243. // Run BBC interpreter on the message.
  2244. $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
  2245. }
  2246. // Make sure we don't end up with a practically empty message body.
  2247. $message['body'] = preg_replace('~^(?:&nbsp;)+$~', '', $message['body']);
  2248. // Sadly, we need to check that the icon is not broken.
  2249. if (!empty($modSettings['messageIconChecks_enable']))
  2250. {
  2251. if (!isset($context['icon_sources'][$message['first_icon']]))
  2252. $context['icon_sources'][$message['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['first_icon'] . '.png') ? 'images_url' : 'default_images_url';
  2253. if (!isset($context['icon_sources'][$message['last_icon']]))
  2254. $context['icon_sources'][$message['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['last_icon'] . '.png') ? 'images_url' : 'default_images_url';
  2255. if (!isset($context['icon_sources'][$message['icon']]))
  2256. $context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.png') ? 'images_url' : 'default_images_url';
  2257. }
  2258. else
  2259. {
  2260. if (!isset($context['icon_sources'][$message['first_icon']]))
  2261. $context['icon_sources'][$message['first_icon']] = 'images_url';
  2262. if (!isset($context['icon_sources'][$message['last_icon']]))
  2263. $context['icon_sources'][$message['last_icon']] = 'images_url';
  2264. if (!isset($context['icon_sources'][$message['icon']]))
  2265. $context['icon_sources'][$message['icon']] = 'images_url';
  2266. }
  2267. // Do we have quote tag enabled?
  2268. $quote_enabled = empty($modSettings['disabledBBC']) || !in_array('quote', explode(',', $modSettings['disabledBBC']));
  2269. $output = array_merge($context['topics'][$message['id_msg']], array(
  2270. 'id' => $message['id_topic'],
  2271. 'is_sticky' => !empty($modSettings['enableStickyTopics']) && !empty($message['is_sticky']),
  2272. 'is_locked' => !empty($message['locked']),
  2273. 'is_poll' => $modSettings['pollMode'] == '1' && $message['id_poll'] > 0,
  2274. 'is_hot' => $message['num_replies'] >= $modSettings['hotTopicPosts'],
  2275. 'is_very_hot' => $message['num_replies'] >= $modSettings['hotTopicVeryPosts'],
  2276. 'posted_in' => !empty($participants[$message['id_topic']]),
  2277. 'views' => $message['num_views'],
  2278. 'replies' => $message['num_replies'],
  2279. 'can_reply' => in_array($message['id_board'], $boards_can['post_reply_any']) || in_array(0, $boards_can['post_reply_any']),
  2280. 'can_quote' => (in_array($message['id_board'], $boards_can['post_reply_any']) || in_array(0, $boards_can['post_reply_any'])) && $quote_enabled,
  2281. 'can_mark_notify' => in_array($message['id_board'], $boards_can['mark_any_notify']) || in_array(0, $boards_can['mark_any_notify']) && !$context['user']['is_guest'],
  2282. 'first_post' => array(
  2283. 'id' => $message['first_msg'],
  2284. 'time' => timeformat($message['first_poster_time']),
  2285. 'timestamp' => forum_time(true, $message['first_poster_time']),
  2286. 'subject' => $message['first_subject'],
  2287. 'href' => $scripturl . '?topic=' . $message['id_topic'] . '.0',
  2288. 'link' => '<a href="' . $scripturl . '?topic=' . $message['id_topic'] . '.0">' . $message['first_subject'] . '</a>',
  2289. 'icon' => $message['first_icon'],
  2290. 'icon_url' => $settings[$context['icon_sources'][$message['first_icon']]] . '/post/' . $message['first_icon'] . '.png',
  2291. 'member' => array(
  2292. 'id' => $message['first_member_id'],
  2293. 'name' => $message['first_member_name'],
  2294. 'href' => !empty($message['first_member_id']) ? $scripturl . '?action=profile;u=' . $message['first_member_id'] : '',
  2295. 'link' => !empty($message['first_member_id']) ? '<a href="' . $scripturl . '?action=profile;u=' . $message['first_member_id'] . '" title="' . $txt['profile_of'] . ' ' . $message['first_member_name'] . '">' . $message['first_member_name'] . '</a>' : $message['first_member_name']
  2296. )
  2297. ),
  2298. 'last_post' => array(
  2299. 'id' => $message['last_msg'],
  2300. 'time' => timeformat($message['last_poster_time']),
  2301. 'timestamp' => forum_time(true, $message['last_poster_time']),
  2302. 'subject' => $message['last_subject'],
  2303. 'href' => $scripturl . '?topic=' . $message['id_topic'] . ($message['num_replies'] == 0 ? '.0' : '.msg' . $message['last_msg']) . '#msg' . $message['last_msg'],
  2304. 'link' => '<a href="' . $scripturl . '?topic=' . $message['id_topic'] . ($message['num_replies'] == 0 ? '.0' : '.msg' . $message['last_msg']) . '#msg' . $message['last_msg'] . '">' . $message['last_subject'] . '</a>',
  2305. 'icon' => $message['last_icon'],
  2306. 'icon_url' => $settings[$context['icon_sources'][$message['last_icon']]] . '/post/' . $message['last_icon'] . '.png',
  2307. 'member' => array(
  2308. 'id' => $message['last_member_id'],
  2309. 'name' => $message['last_member_name'],
  2310. 'href' => !empty($message['last_member_id']) ? $scripturl . '?action=profile;u=' . $message['last_member_id'] : '',
  2311. 'link' => !empty($message['last_member_id']) ? '<a href="' . $scripturl . '?action=profile;u=' . $message['last_member_id'] . '" title="' . $txt['profile_of'] . ' ' . $message['last_member_name'] . '">' . $message['last_member_name'] . '</a>' : $message['last_member_name']
  2312. )
  2313. ),
  2314. 'board' => array(
  2315. 'id' => $message['id_board'],
  2316. 'name' => $message['board_name'],
  2317. 'href' => $scripturl . '?board=' . $message['id_board'] . '.0',
  2318. 'link' => '<a href="' . $scripturl . '?board=' . $message['id_board'] . '.0">' . $message['board_name'] . '</a>'
  2319. ),
  2320. 'category' => array(
  2321. 'id' => $message['id_cat'],
  2322. 'name' => $message['cat_name'],
  2323. 'href' => $scripturl . '#c' . $message['id_cat'],
  2324. 'link' => '<a href="' . $scripturl . '#c' . $message['id_cat'] . '">' . $message['cat_name'] . '</a>'
  2325. )
  2326. ));
  2327. determineTopicClass($output);
  2328. if ($output['posted_in'])
  2329. $output['class'] = 'my_' . $output['class'];
  2330. $body_highlighted = $message['body'];
  2331. $subject_highlighted = $message['subject'];
  2332. if (!empty($options['display_quick_mod']))
  2333. {
  2334. $started = $output['first_post']['member']['id'] == $user_info['id'];
  2335. $output['quick_mod'] = array(
  2336. 'lock' => in_array(0, $boards_can['lock_any']) || in_array($output['board']['id'], $boards_can['lock_any']) || ($started && (in_array(0, $boards_can['lock_own']) || in_array($output['board']['id'], $boards_can['lock_own']))),
  2337. 'sticky' => (in_array(0, $boards_can['make_sticky']) || in_array($output['board']['id'], $boards_can['make_sticky'])) && !empty($modSettings['enableStickyTopics']),
  2338. 'move' => in_array(0, $boards_can['move_any']) || in_array($output['board']['id'], $boards_can['move_any']) || ($started && (in_array(0, $boards_can['move_own']) || in_array($output['board']['id'], $boards_can['move_own']))),
  2339. 'remove' => in_array(0, $boards_can['remove_any']) || in_array($output['board']['id'], $boards_can['remove_any']) || ($started && (in_array(0, $boards_can['remove_own']) || in_array($output['board']['id'], $boards_can['remove_own']))),
  2340. );
  2341. $context['can_lock'] |= $output['quick_mod']['lock'];
  2342. $context['can_sticky'] |= $output['quick_mod']['sticky'];
  2343. $context['can_move'] |= $output['quick_mod']['move'];
  2344. $context['can_remove'] |= $output['quick_mod']['remove'];
  2345. $context['can_merge'] |= in_array($output['board']['id'], $boards_can['merge_any']);
  2346. $context['can_markread'] = $context['user']['is_logged'];
  2347. $context['qmod_actions'] = array('remove', 'lock', 'sticky', 'move', 'markread');
  2348. call_integration_hook('integrate_quick_mod_actions_search');
  2349. }
  2350. foreach ($context['key_words'] as $query)
  2351. {
  2352. // Fix the international characters in the keyword too.
  2353. $query = un_htmlspecialchars($query);
  2354. $query = trim($query, "\*+");
  2355. $query = strtr($smcFunc['htmlspecialchars']($query), array('\\\'' => '\''));
  2356. $body_highlighted = preg_replace('/((<[^>]*)|' . preg_quote(strtr($query, array('\'' => '&#039;')), '/') . ')/ieu', "'\$2' == '\$1' ? stripslashes('\$1') : '<strong class=\"highlight\">\$1</strong>'", $body_highlighted);
  2357. $subject_highlighted = preg_replace('/(' . preg_quote($query, '/') . ')/iu', '<strong class="highlight">$1</strong>', $subject_highlighted);
  2358. }
  2359. $output['matches'][] = array(
  2360. 'id' => $message['id_msg'],
  2361. 'attachment' => loadAttachmentContext($message['id_msg']),
  2362. 'alternate' => $counter % 2,
  2363. 'member' => &$memberContext[$message['id_member']],
  2364. 'icon' => $message['icon'],
  2365. 'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.png',
  2366. 'subject' => $message['subject'],
  2367. 'subject_highlighted' => $subject_highlighted,
  2368. 'time' => timeformat($message['poster_time']),
  2369. 'timestamp' => forum_time(true, $message['poster_time']),
  2370. 'counter' => $counter,
  2371. 'modified' => array(
  2372. 'time' => timeformat($message['modified_time']),
  2373. 'timestamp' => forum_time(true, $message['modified_time']),
  2374. 'name' => $message['modified_name']
  2375. ),
  2376. 'body' => $message['body'],
  2377. 'body_highlighted' => $body_highlighted,
  2378. 'start' => 'msg' . $message['id_msg']
  2379. );
  2380. $counter++;
  2381. call_integration_hook('integrate_search_message_context', array($counter, $output));
  2382. return $output;
  2383. }
  2384. /**
  2385. * This function compares the length of two strings plus a little.
  2386. * What it does:
  2387. * - callback function for usort used to sort the fulltext results.
  2388. * - passes sorting duty to the current API.
  2389. *
  2390. * @param string $a
  2391. * @param string $b
  2392. * @return int
  2393. */
  2394. function searchSort($a, $b)
  2395. {
  2396. global $searchAPI;
  2397. return $searchAPI->searchSort($a, $b);
  2398. }