PageRenderTime 82ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/forum/Sources/Search.php

https://github.com/leftnode/nooges.com
PHP | 2064 lines | 1620 code | 227 blank | 217 comment | 326 complexity | 75b58a541be1b184143474b02437da0e MD5 | raw file
  1. <?php
  2. /**********************************************************************************
  3. * Search.php *
  4. ***********************************************************************************
  5. * SMF: Simple Machines Forum *
  6. * Open-Source Project Inspired by Zef Hemel (zef@zefhemel.com) *
  7. * =============================================================================== *
  8. * Software Version: SMF 2.0 RC2 *
  9. * Software by: Simple Machines (http://www.simplemachines.org) *
  10. * Copyright 2006-2009 by: Simple Machines LLC (http://www.simplemachines.org) *
  11. * 2001-2006 by: Lewis Media (http://www.lewismedia.com) *
  12. * Support, News, Updates at: http://www.simplemachines.org *
  13. ***********************************************************************************
  14. * This program is free software; you may redistribute it and/or modify it under *
  15. * the terms of the provided license as published by Simple Machines LLC. *
  16. * *
  17. * This program is distributed in the hope that it is and will be useful, but *
  18. * WITHOUT ANY WARRANTIES; without even any implied warranty of MERCHANTABILITY *
  19. * or FITNESS FOR A PARTICULAR PURPOSE. *
  20. * *
  21. * See the "license.txt" file for details of the Simple Machines license. *
  22. * The latest version can always be found at http://www.simplemachines.org. *
  23. **********************************************************************************/
  24. if (!defined('SMF'))
  25. die('Hacking attempt...');
  26. /* These functions are here for searching, and they are:
  27. void PlushSearch1()
  28. - shows the screen to search forum posts (action=search), and uses the
  29. simple version if the simpleSearch setting is enabled.
  30. - uses the main sub template of the Search template.
  31. - uses the Search language file.
  32. - requires the search_posts permission.
  33. - decodes and loads search parameters given in the URL (if any).
  34. - the form redirects to index.php?action=search2.
  35. void PlushSearch2()
  36. - checks user input and searches the messages table for messages
  37. matching the query.
  38. - requires the search_posts permission.
  39. - uses the results sub template of the Search template.
  40. - uses the Search language file.
  41. - stores the results into the search cache.
  42. - show the results of the search query.
  43. array prepareSearchContext(bool reset = false)
  44. - callback function for the results sub template.
  45. - loads the necessary contextual data to show a search result.
  46. int searchSort(string $wordA, string $wordB)
  47. - callback function for usort used to sort the fulltext results.
  48. - passes sorting duty to the current API.
  49. */
  50. // This defines two version types for checking the API's are compatible with this version of SMF.
  51. $GLOBALS['search_versions'] = array(
  52. // This is the forum version but is repeated due to some people rewriting $forum_version.
  53. 'forum_version' => 'SMF 2.0 RC2',
  54. // This is the minimum version of SMF that an API could have been written for to work. (strtr to stop accidentally updating version on release)
  55. 'search_version' => strtr('SMF 2+0=Beta=2', array('+' => '.', '=' => ' ')),
  56. );
  57. // Ask the user what they want to search for.
  58. function PlushSearch1()
  59. {
  60. global $txt, $scripturl, $modSettings, $user_info, $context, $smcFunc, $sourcedir;
  61. // Is the load average too high to allow searching just now?
  62. if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
  63. fatal_lang_error('loadavg_search_disabled', false);
  64. loadLanguage('Search');
  65. // Don't load this in XML mode.
  66. if (!isset($_REQUEST['xml']))
  67. loadTemplate('Search');
  68. // Check the user's permissions.
  69. isAllowedTo('search_posts');
  70. // Link tree....
  71. $context['linktree'][] = array(
  72. 'url' => $scripturl . '?action=search',
  73. 'name' => $txt['search']
  74. );
  75. // This is hard coded maximum string length.
  76. $context['search_string_limit'] = 100;
  77. $context['require_verification'] = $user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']);
  78. if ($context['require_verification'])
  79. {
  80. require_once($sourcedir . '/Subs-Editor.php');
  81. $verificationOptions = array(
  82. 'id' => 'search',
  83. );
  84. $context['require_verification'] = create_control_verification($verificationOptions);
  85. $context['visual_verification_id'] = $verificationOptions['id'];
  86. }
  87. // If you got back from search2 by using the linktree, you get your original search parameters back.
  88. if (isset($_REQUEST['params']))
  89. {
  90. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  91. $context['search_params'] = array();
  92. foreach ($temp_params as $i => $data)
  93. {
  94. @list ($k, $v) = explode('|\'|', $data);
  95. $context['search_params'][$k] = $v;
  96. }
  97. if (isset($context['search_params']['brd']))
  98. $context['search_params']['brd'] = $context['search_params']['brd'] == '' ? array() : explode(',', $context['search_params']['brd']);
  99. }
  100. if (isset($_REQUEST['search']))
  101. $context['search_params']['search'] = un_htmlspecialchars($_REQUEST['search']);
  102. if (isset($context['search_params']['search']))
  103. $context['search_params']['search'] = htmlspecialchars($context['search_params']['search']);
  104. if (isset($context['search_params']['userspec']))
  105. $context['search_params']['userspec'] = htmlspecialchars($context['search_params']['userspec']);
  106. if (!empty($context['search_params']['searchtype']))
  107. $context['search_params']['searchtype'] = 2;
  108. if (!empty($context['search_params']['minage']))
  109. $context['search_params']['minage'] = (int) $context['search_params']['minage'];
  110. if (!empty($context['search_params']['maxage']))
  111. $context['search_params']['maxage'] = (int) $context['search_params']['maxage'];
  112. $context['search_params']['show_complete'] = !empty($context['search_params']['show_complete']);
  113. $context['search_params']['subject_only'] = !empty($context['search_params']['subject_only']);
  114. // Load the error text strings if there were errors in the search.
  115. if (!empty($context['search_errors']))
  116. {
  117. loadLanguage('Errors');
  118. $context['search_errors']['messages'] = array();
  119. foreach ($context['search_errors'] as $search_error => $dummy)
  120. {
  121. if ($search_error === 'messages')
  122. continue;
  123. $context['search_errors']['messages'][] = $txt['error_' . $search_error];
  124. }
  125. }
  126. // Find all the boards this user is allowed to see.
  127. $request = $smcFunc['db_query']('order_by_board_order', '
  128. SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
  129. FROM {db_prefix}boards AS b
  130. LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  131. WHERE {query_see_board}',
  132. array(
  133. )
  134. );
  135. $context['num_boards'] = $smcFunc['db_num_rows']($request);
  136. $context['boards_check_all'] = true;
  137. $context['categories'] = array();
  138. while ($row = $smcFunc['db_fetch_assoc']($request))
  139. {
  140. // This category hasn't been set up yet..
  141. if (!isset($context['categories'][$row['id_cat']]))
  142. $context['categories'][$row['id_cat']] = array(
  143. 'id' => $row['id_cat'],
  144. 'name' => $row['cat_name'],
  145. 'boards' => array()
  146. );
  147. // Set this board up, and let the template know when it's a child. (indent them..)
  148. $context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
  149. 'id' => $row['id_board'],
  150. 'name' => $row['name'],
  151. 'child_level' => $row['child_level'],
  152. 'selected' => (empty($context['search_params']['brd']) && (empty($modSettings['recycle_enable']) || $row['id_board'] != $modSettings['recycle_board']) && !in_array($row['id_board'], $user_info['ignoreboards'])) || (!empty($context['search_params']['brd']) && in_array($row['id_board'], $context['search_params']['brd']))
  153. );
  154. // If a board wasn't checked that probably should have been ensure the board selection is selected, yo!
  155. if (!$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] && (empty($modSettings['recycle_enable']) || $row['id_board'] != $modSettings['recycle_board']))
  156. $context['boards_check_all'] = false;
  157. }
  158. $smcFunc['db_free_result']($request);
  159. // Now, let's sort the list of categories into the boards for templates that like that.
  160. $temp_boards = array();
  161. foreach ($context['categories'] as $category)
  162. {
  163. $temp_boards[] = array(
  164. 'name' => $category['name'],
  165. 'child_ids' => array_keys($category['boards'])
  166. );
  167. $temp_boards = array_merge($temp_boards, array_values($category['boards']));
  168. // Include a list of boards per category for easy toggling.
  169. $context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
  170. }
  171. $max_boards = ceil(count($temp_boards) / 2);
  172. if ($max_boards == 1)
  173. $max_boards = 2;
  174. // Now, alternate them so they can be shown left and right ;).
  175. $context['board_columns'] = array();
  176. for ($i = 0; $i < $max_boards; $i++)
  177. {
  178. $context['board_columns'][] = $temp_boards[$i];
  179. if (isset($temp_boards[$i + $max_boards]))
  180. $context['board_columns'][] = $temp_boards[$i + $max_boards];
  181. else
  182. $context['board_columns'][] = array();
  183. }
  184. if (!empty($_REQUEST['topic']))
  185. {
  186. $context['search_params']['topic'] = (int) $_REQUEST['topic'];
  187. $context['search_params']['show_complete'] = true;
  188. }
  189. if (!empty($context['search_params']['topic']))
  190. {
  191. $context['search_params']['topic'] = (int) $context['search_params']['topic'];
  192. $context['search_topic'] = array(
  193. 'id' => $context['search_params']['topic'],
  194. 'href' => $scripturl . '?topic=' . $context['search_params']['topic'] . '.0',
  195. );
  196. $request = $smcFunc['db_query']('', '
  197. SELECT ms.subject
  198. FROM {db_prefix}topics AS t
  199. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  200. INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
  201. WHERE t.id_topic = {int:search_topic_id}
  202. AND {query_see_board}' . ($modSettings['postmod_active'] ? '
  203. AND t.approved = {int:is_approved_true}' : '') . '
  204. LIMIT 1',
  205. array(
  206. 'is_approved_true' => 1,
  207. 'search_topic_id' => $context['search_params']['topic'],
  208. )
  209. );
  210. if ($smcFunc['db_num_rows']($request) == 0)
  211. fatal_lang_error('topic_gone', false);
  212. list ($context['search_topic']['subject']) = $smcFunc['db_fetch_row']($request);
  213. $smcFunc['db_free_result']($request);
  214. $context['search_topic']['link'] = '<a href="' . $context['search_topic']['href'] . '">' . $context['search_topic']['subject'] . '</a>';
  215. }
  216. // Simple or not?
  217. $context['simple_search'] = isset($context['search_params']['advanced']) ? empty($context['search_params']['advanced']) : !empty($modSettings['simpleSearch']) && !isset($_REQUEST['advanced']);
  218. $context['page_title'] = $txt['set_parameters'];
  219. }
  220. // Gather the results and show them.
  221. function PlushSearch2()
  222. {
  223. global $scripturl, $modSettings, $sourcedir, $txt, $db_connection;
  224. global $user_info, $context, $options, $messages_request, $boards_can;
  225. global $excludedWords, $participants, $smcFunc, $search_versions, $searchAPI;
  226. if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
  227. fatal_lang_error('loadavg_search_disabled', false);
  228. // No, no, no... this is a bit hard on the server, so don't you go prefetching it!
  229. if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
  230. {
  231. ob_end_clean();
  232. header('HTTP/1.1 403 Forbidden');
  233. die;
  234. }
  235. $weight_factors = array(
  236. 'frequency',
  237. 'age',
  238. 'length',
  239. 'subject',
  240. 'first_message',
  241. 'sticky',
  242. );
  243. $weight = array();
  244. $weight_total = 0;
  245. foreach ($weight_factors as $weight_factor)
  246. {
  247. $weight[$weight_factor] = empty($modSettings['search_weight_' . $weight_factor]) ? 0 : (int) $modSettings['search_weight_' . $weight_factor];
  248. $weight_total += $weight[$weight_factor];
  249. }
  250. // Zero weight. Weightless :P.
  251. if (empty($weight_total))
  252. fatal_lang_error('search_invalid_weights');
  253. // These vars don't require an interface, they're just here for tweaking.
  254. $recentPercentage = 0.30;
  255. $humungousTopicPosts = 200;
  256. $maxMembersToSearch = 500;
  257. $maxMessageResults = empty($modSettings['search_max_results']) ? 0 : $modSettings['search_max_results'] * 5;
  258. // Start with no errors.
  259. $context['search_errors'] = array();
  260. // Number of pages hard maximum - normally not set at all.
  261. $modSettings['search_max_results'] = empty($modSettings['search_max_results']) ? 200 * $modSettings['search_results_per_page'] : (int) $modSettings['search_max_results'];
  262. // Maximum length of the string.
  263. $context['search_string_limit'] = 100;
  264. loadLanguage('Search');
  265. if (!isset($_REQUEST['xml']))
  266. loadTemplate('Search');
  267. //If we're doing XML we need to use the results template regardless really.
  268. else
  269. $context['sub_template'] = 'results';
  270. // Are you allowed?
  271. isAllowedTo('search_posts');
  272. require_once($sourcedir . '/Display.php');
  273. // Search has a special database set.
  274. db_extend('search');
  275. // Load up the search API we are going to use.
  276. $modSettings['search_index'] = empty($modSettings['search_index']) ? 'standard' : $modSettings['search_index'];
  277. if (!file_exists($sourcedir . '/SearchAPI-' . ucwords($modSettings['search_index']) . '.php'))
  278. fatal_lang_error('search_api_missing');
  279. loadClassFile('SearchAPI-' . ucwords($modSettings['search_index']) . '.php');
  280. // Create an instance of the search API and check it is valid for this version of SMF.
  281. $search_class_name = $modSettings['search_index'] . '_search';
  282. $searchAPI = new $search_class_name();
  283. if (!$searchAPI || ($searchAPI->supportsMethod('isValid') && !$searchAPI->isValid()) || $search_versions['forum_version'] < $searchAPI->min_smf_version || $search_versions['search_version'] > $searchAPI->version_compatible)
  284. {
  285. // Log the error.
  286. loadLanguage('Errors');
  287. log_error(sprintf($txt['search_api_not_compatible'], 'SearchAPI-' . ucwords($modSettings['search_index']) . '.php'), 'critical');
  288. loadClassFile('SearchAPI-Standard.php');
  289. $searchAPI = new standard_search();
  290. }
  291. // $search_params will carry all settings that differ from the default search parameters.
  292. // That way, the URLs involved in a search page will be kept as short as possible.
  293. $search_params = array();
  294. if (isset($_REQUEST['params']))
  295. {
  296. $temp_params = explode('|"|', base64_decode(strtr($_REQUEST['params'], array(' ' => '+'))));
  297. foreach ($temp_params as $i => $data)
  298. {
  299. @list ($k, $v) = explode('|\'|', $data);
  300. $search_params[$k] = $v;
  301. }
  302. if (isset($search_params['brd']))
  303. $search_params['brd'] = empty($search_params['brd']) ? array() : explode(',', $search_params['brd']);
  304. }
  305. // Store whether simple search was used (needed if the user wants to do another query).
  306. if (!isset($search_params['advanced']))
  307. $search_params['advanced'] = empty($_REQUEST['advanced']) ? 0 : 1;
  308. // 1 => 'allwords' (default, don't set as param) / 2 => 'anywords'.
  309. if (!empty($search_params['searchtype']) || (!empty($_REQUEST['searchtype']) && $_REQUEST['searchtype'] == 2))
  310. $search_params['searchtype'] = 2;
  311. // Minimum age of messages. Default to zero (don't set param in that case).
  312. if (!empty($search_params['minage']) || (!empty($_REQUEST['minage']) && $_REQUEST['minage'] > 0))
  313. $search_params['minage'] = !empty($search_params['minage']) ? (int) $search_params['minage'] : (int) $_REQUEST['minage'];
  314. // Maximum age of messages. Default to infinite (9999 days: param not set).
  315. if (!empty($search_params['maxage']) || (!empty($_REQUEST['maxage']) && $_REQUEST['maxage'] < 9999))
  316. $search_params['maxage'] = !empty($search_params['maxage']) ? (int) $search_params['maxage'] : (int) $_REQUEST['maxage'];
  317. // Searching a specific topic?
  318. if (!empty($_REQUEST['topic']))
  319. {
  320. $search_params['topic'] = (int) $_REQUEST['topic'];
  321. $search_params['show_complete'] = true;
  322. }
  323. elseif (!empty($search_params['topic']))
  324. $search_params['topic'] = (int) $search_params['topic'];
  325. if (!empty($search_params['minage']) || !empty($search_params['maxage']))
  326. {
  327. $request = $smcFunc['db_query']('', '
  328. SELECT ' . (empty($search_params['maxage']) ? '0, ' : 'IFNULL(MIN(id_msg), -1), ') . (empty($search_params['minage']) ? '0' : 'IFNULL(MAX(id_msg), -1)') . '
  329. FROM {db_prefix}messages
  330. WHERE 1=1' . ($modSettings['postmod_active'] ? '
  331. AND approved = {int:is_approved_true}' : '') . (empty($search_params['minage']) ? '' : '
  332. AND poster_time <= {int:timestamp_minimum_age}') . (empty($search_params['maxage']) ? '' : '
  333. AND poster_time >= {int:timestamp_maximum_age}'),
  334. array(
  335. 'timestamp_minimum_age' => empty($search_params['minage']) ? 0 : time() - 86400 * $search_params['minage'],
  336. 'timestamp_maximum_age' => empty($search_params['maxage']) ? 0 : time() - 86400 * $search_params['maxage'],
  337. 'is_approved_true' => 1,
  338. )
  339. );
  340. list ($minMsgID, $maxMsgID) = $smcFunc['db_fetch_row']($request);
  341. if ($minMsgID < 0 || $maxMsgID < 0)
  342. $context['search_errors']['no_messages_in_time_frame'] = true;
  343. $smcFunc['db_free_result']($request);
  344. }
  345. // Default the user name to a wildcard matching every user (*).
  346. if (!empty($search_params['userspec']) || (!empty($_REQUEST['userspec']) && $_REQUEST['userspec'] != '*'))
  347. $search_params['userspec'] = isset($search_params['userspec']) ? $search_params['userspec'] : $_REQUEST['userspec'];
  348. // If there's no specific user, then don't mention it in the main query.
  349. if (empty($search_params['userspec']))
  350. $userQuery = '';
  351. else
  352. {
  353. $userString = strtr($smcFunc['htmlspecialchars']($search_params['userspec'], ENT_QUOTES), array('&quot;' => '"'));
  354. $userString = strtr($userString, array('%' => '\%', '_' => '\_', '*' => '%', '?' => '_'));
  355. preg_match_all('~"([^"]+)"~', $userString, $matches);
  356. $possible_users = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $userString)));
  357. for ($k = 0, $n = count($possible_users); $k < $n; $k++)
  358. {
  359. $possible_users[$k] = trim($possible_users[$k]);
  360. if (strlen($possible_users[$k]) == 0)
  361. unset($possible_users[$k]);
  362. }
  363. // Create a list of database-escaped search names.
  364. $realNameMatches = array();
  365. foreach ($possible_users as $possible_user)
  366. $realNameMatches[] = $smcFunc['db_quote'](
  367. '{string:possible_user}',
  368. array(
  369. 'possible_user' => $possible_user
  370. )
  371. );
  372. // Retrieve a list of possible members.
  373. $request = $smcFunc['db_query']('', '
  374. SELECT id_member
  375. FROM {db_prefix}members
  376. WHERE {raw:match_possible_users}',
  377. array(
  378. 'match_possible_users' => 'real_name LIKE ' . implode(' OR real_name LIKE ', $realNameMatches),
  379. )
  380. );
  381. // Simply do nothing if there're too many members matching the criteria.
  382. if ($smcFunc['db_num_rows']($request) > $maxMembersToSearch)
  383. $userQuery = '';
  384. elseif ($smcFunc['db_num_rows']($request) == 0)
  385. {
  386. $userQuery = $smcFunc['db_quote'](
  387. 'm.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})',
  388. array(
  389. 'id_member_guest' => 0,
  390. 'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches),
  391. )
  392. );
  393. }
  394. else
  395. {
  396. $memberlist = array();
  397. while ($row = $smcFunc['db_fetch_assoc']($request))
  398. $memberlist[] = $row['id_member'];
  399. $userQuery = $smcFunc['db_quote'](
  400. '(m.id_member IN ({array_int:matched_members}) OR (m.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})))',
  401. array(
  402. 'matched_members' => $memberlist,
  403. 'id_member_guest' => 0,
  404. 'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches),
  405. )
  406. );
  407. }
  408. $smcFunc['db_free_result']($request);
  409. }
  410. // If the boards were passed by URL (params=), temporarily put them back in $_REQUEST.
  411. if (!empty($search_params['brd']) && is_array($search_params['brd']))
  412. $_REQUEST['brd'] = $search_params['brd'];
  413. // Ensure that brd is an array.
  414. if (!empty($_REQUEST['brd']) && !is_array($_REQUEST['brd']))
  415. $_REQUEST['brd'] = strpos($_REQUEST['brd'], ',') !== false ? explode(',', $_REQUEST['brd']) : array($_REQUEST['brd']);
  416. // Make sure all boards are integers.
  417. if (!empty($_REQUEST['brd']))
  418. foreach ($_REQUEST['brd'] as $id => $brd)
  419. $_REQUEST['brd'][$id] = (int) $brd;
  420. // Special case for boards: searching just one topic?
  421. if (!empty($search_params['topic']))
  422. {
  423. $request = $smcFunc['db_query']('', '
  424. SELECT b.id_board
  425. FROM {db_prefix}topics AS t
  426. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  427. WHERE t.id_topic = {int:search_topic_id}
  428. AND {query_see_board}' . ($modSettings['postmod_active'] ? '
  429. AND t.approved = {int:is_approved_true}' : '') . '
  430. LIMIT 1',
  431. array(
  432. 'search_topic_id' => $search_params['topic'],
  433. 'is_approved_true' => 1,
  434. )
  435. );
  436. if ($smcFunc['db_num_rows']($request) == 0)
  437. fatal_lang_error('topic_gone', false);
  438. $search_params['brd'] = array();
  439. list ($search_params['brd'][0]) = $smcFunc['db_fetch_row']($request);
  440. $smcFunc['db_free_result']($request);
  441. }
  442. // Select all boards you've selected AND are allowed to see.
  443. elseif ($user_info['is_admin'] && (!empty($search_params['advanced']) || !empty($_REQUEST['brd'])))
  444. $search_params['brd'] = empty($_REQUEST['brd']) ? array() : $_REQUEST['brd'];
  445. else
  446. {
  447. $see_board = empty($search_params['advanced']) ? 'query_wanna_see_board' : 'query_see_board';
  448. $request = $smcFunc['db_query']('', '
  449. SELECT b.id_board
  450. FROM {db_prefix}boards AS b
  451. WHERE {raw:boards_allowed_to_see}' . (empty($_REQUEST['brd']) ? (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
  452. AND b.id_board != {int:recycle_board_id}' : '') : '
  453. AND b.id_board IN ({array_int:selected_search_boards})'),
  454. array(
  455. 'boards_allowed_to_see' => $user_info[$see_board],
  456. 'selected_search_boards' => empty($_REQUEST['brd']) ? array() : $_REQUEST['brd'],
  457. 'recycle_board_id' => $modSettings['recycle_board'],
  458. )
  459. );
  460. $search_params['brd'] = array();
  461. while ($row = $smcFunc['db_fetch_assoc']($request))
  462. $search_params['brd'][] = $row['id_board'];
  463. $smcFunc['db_free_result']($request);
  464. // This error should pro'bly only happen for hackers.
  465. if (empty($search_params['brd']))
  466. $context['search_errors']['no_boards_selected'] = true;
  467. }
  468. if (count($search_params['brd']) != 0)
  469. {
  470. foreach ($search_params['brd'] as $k => $v)
  471. $search_params['brd'][$k] = (int) $v;
  472. // If we've selected all boards, this parameter can be left empty.
  473. $request = $smcFunc['db_query']('', '
  474. SELECT COUNT(*)
  475. FROM {db_prefix}boards',
  476. array(
  477. )
  478. );
  479. list ($num_boards) = $smcFunc['db_fetch_row']($request);
  480. $smcFunc['db_free_result']($request);
  481. if (count($search_params['brd']) == $num_boards)
  482. $boardQuery = '';
  483. elseif (count($search_params['brd']) == $num_boards - 1 && !empty($modSettings['recycle_board']) && !in_array($modSettings['recycle_board'], $search_params['brd']))
  484. $boardQuery = '!= ' . $modSettings['recycle_board'];
  485. else
  486. $boardQuery = 'IN (' . implode(', ', $search_params['brd']) . ')';
  487. }
  488. else
  489. $boardQuery = '';
  490. $search_params['show_complete'] = !empty($search_params['show_complete']) || !empty($_REQUEST['show_complete']);
  491. $search_params['subject_only'] = !empty($search_params['subject_only']) || !empty($_REQUEST['subject_only']);
  492. $context['compact'] = !$search_params['show_complete'];
  493. // Get the sorting parameters right. Default to sort by relevance descending.
  494. $sort_columns = array(
  495. 'relevance',
  496. 'num_replies',
  497. 'id_msg',
  498. );
  499. if (empty($search_params['sort']) && !empty($_REQUEST['sort']))
  500. list ($search_params['sort'], $search_params['sort_dir']) = array_pad(explode('|', $_REQUEST['sort']), 2, '');
  501. $search_params['sort'] = !empty($search_params['sort']) && in_array($search_params['sort'], $sort_columns) ? $search_params['sort'] : 'relevance';
  502. if (!empty($search_params['topic']) && $search_params['sort'] === 'num_replies')
  503. $search_params['sort'] = 'id_msg';
  504. // Sorting direction: descending unless stated otherwise.
  505. $search_params['sort_dir'] = !empty($search_params['sort_dir']) && $search_params['sort_dir'] == 'asc' ? 'asc' : 'desc';
  506. // Determine some values needed to calculate the relevance.
  507. $minMsg = (int) ((1 - $recentPercentage) * $modSettings['maxMsgID']);
  508. $recentMsg = $modSettings['maxMsgID'] - $minMsg;
  509. // *** Parse the search query
  510. // Unfortunately, searching for words like this is going to be slow, so we're blacklisting them.
  511. // !!! Setting to add more here?
  512. // !!! Maybe only blacklist if they are the only word, or "any" is used?
  513. $blacklisted_words = array('img', 'url', 'quote', 'www', 'http', 'the', 'is', 'it', 'are', 'if');
  514. // What are we searching for?
  515. if (empty($search_params['search']))
  516. {
  517. if (isset($_GET['search']))
  518. $search_params['search'] = un_htmlspecialchars($_GET['search']);
  519. elseif (isset($_POST['search']))
  520. $search_params['search'] = $_POST['search'];
  521. else
  522. $search_params['search'] = '';
  523. }
  524. // Nothing??
  525. if (!isset($search_params['search']) || $search_params['search'] == '')
  526. $context['search_errors']['invalid_search_string'] = true;
  527. // Too long?
  528. elseif ($smcFunc['strlen']($search_params['search']) > $context['search_string_limit'])
  529. {
  530. $context['search_errors']['string_too_long'] = true;
  531. $txt['error_string_too_long'] = sprintf($txt['error_string_too_long'], $context['search_string_limit']);
  532. }
  533. // Change non-word characters into spaces.
  534. $stripped_query = preg_replace('~(?:[\x0B\0' . ($context['utf8'] ? ($context['server']['complex_preg_chars'] ? '\x{A0}' : "\xC2\xA0") : '\xA0') . '\t\r\s\n(){}\\[\\]<>!@$%^*.,:+=`\~\?/\\\\]+|&(?:amp|lt|gt|quot);)+~' . ($context['utf8'] ? 'u' : ''), ' ', $search_params['search']);
  535. // Make the query lower case. It's gonna be case insensitive anyway.
  536. $stripped_query = un_htmlspecialchars($smcFunc['strtolower']($stripped_query));
  537. // This (hidden) setting will do fulltext searching in the most basic way.
  538. if (!empty($modSettings['search_simple_fulltext']))
  539. $stripped_query = strtr($stripped_query, array('"' => ''));
  540. $no_regexp = preg_match('~&#(?:\d{1,7}|x[0-9a-fA-F]{1,6});~', $stripped_query) === 1;
  541. // Extract phrase parts first (e.g. some words "this is a phrase" some more words.)
  542. preg_match_all('/(?:^|\s)([-]?)"([^"]+)"(?:$|\s)/', $stripped_query, $matches, PREG_PATTERN_ORDER);
  543. $phraseArray = $matches[2];
  544. // Remove the phrase parts and extract the words.
  545. $wordArray = explode(' ', preg_replace('~(?:^|\s)(?:[-]?)"(?:[^"]+)"(?:$|\s)~' . ($context['utf8'] ? 'u' : ''), ' ', $search_params['search']));
  546. // A minus sign in front of a word excludes the word.... so...
  547. $excludedWords = array();
  548. $excludedIndexWords = array();
  549. $excludedSubjectWords = array();
  550. $excludedPhrases = array();
  551. // .. first, we check for things like -"some words", but not "-some words".
  552. foreach ($matches[1] as $index => $word)
  553. if ($word === '-')
  554. {
  555. if (($word = trim($phraseArray[$index], '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
  556. $excludedWords[] = $word;
  557. unset($phraseArray[$index]);
  558. }
  559. // Now we look for -test, etc.... normaller.
  560. foreach ($wordArray as $index => $word)
  561. if (strpos(trim($word), '-') === 0)
  562. {
  563. if (($word = trim($word, '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
  564. $excludedWords[] = $word;
  565. unset($wordArray[$index]);
  566. }
  567. // The remaining words and phrases are all included.
  568. $searchArray = array_merge($phraseArray, $wordArray);
  569. // Trim everything and make sure there are no words that are the same.
  570. foreach ($searchArray as $index => $value)
  571. {
  572. if (($searchArray[$index] = trim($value, '-_\' ')) === '' || in_array($searchArray[$index], $blacklisted_words))
  573. unset($searchArray[$index]);
  574. // Don't allow very, very short words.
  575. elseif (strlen($value) < 2)
  576. {
  577. $context['search_errors']['search_string_small_words'] = true;
  578. unset($searchArray[$index]);
  579. }
  580. else
  581. $searchArray[$index] = $searchArray[$index];
  582. }
  583. $searchArray = array_slice(array_unique($searchArray), 0, 10);
  584. // Create an array of replacements for highlighting.
  585. $context['mark'] = array();
  586. foreach ($searchArray as $word)
  587. $context['mark'][$word] = '<strong class="highlight">' . $word . '</strong>';
  588. // Initialize two arrays storing the words that have to be searched for.
  589. $orParts = array();
  590. $searchWords = array();
  591. // Make sure at least one word is being searched for.
  592. if (empty($searchArray))
  593. $context['search_errors']['invalid_search_string'] = true;
  594. // All words/sentences must match.
  595. elseif (empty($search_params['searchtype']))
  596. $orParts[0] = $searchArray;
  597. // Any word/sentence must match.
  598. else
  599. foreach ($searchArray as $index => $value)
  600. $orParts[$index] = array($value);
  601. // Don't allow duplicate error messages if one string is too short.
  602. if (isset($context['search_errors']['search_string_small_words'], $context['search_errors']['invalid_search_string']))
  603. unset($context['search_errors']['invalid_search_string']);
  604. // Make sure the excluded words are in all or-branches.
  605. foreach ($orParts as $orIndex => $andParts)
  606. foreach ($excludedWords as $word)
  607. $orParts[$orIndex][] = $word;
  608. // Determine the or-branches and the fulltext search words.
  609. foreach ($orParts as $orIndex => $andParts)
  610. {
  611. $searchWords[$orIndex] = array(
  612. 'indexed_words' => array(),
  613. 'words' => array(),
  614. 'subject_words' => array(),
  615. 'all_words' => array(),
  616. );
  617. // Sort the indexed words (large words -> small words -> excluded words).
  618. if ($searchAPI->supportsMethod('searchSort'))
  619. usort($orParts[$orIndex], 'searchSort');
  620. foreach ($orParts[$orIndex] as $word)
  621. {
  622. $is_excluded = in_array($word, $excludedWords);
  623. $searchWords[$orIndex]['all_words'][] = $word;
  624. $subjectWords = text2words($word);
  625. if (!$is_excluded || count($subjectWords) === 1)
  626. {
  627. $searchWords[$orIndex]['subject_words'] = array_merge($searchWords[$orIndex]['subject_words'], $subjectWords);
  628. if ($is_excluded)
  629. $excludedSubjectWords = array_merge($excludedSubjectWords, $subjectWords);
  630. }
  631. else
  632. $excludedPhrases[] = $word;
  633. // Have we got indexes to prepare?
  634. if ($searchAPI->supportsMethod('prepareIndexes'))
  635. $searchAPI->prepareIndexes($word, $searchWords[$orIndex], $excludedIndexWords, $is_excluded);
  636. }
  637. // Search_force_index requires all AND parts to have at least one fulltext word.
  638. if (!empty($modSettings['search_force_index']) && empty($searchWords[$orIndex]['indexed_words']))
  639. {
  640. $context['search_errors']['query_not_specific_enough'] = true;
  641. break;
  642. }
  643. // Make sure we aren't searching for too many indexed words.
  644. else
  645. {
  646. $searchWords[$orIndex]['indexed_words'] = array_slice($searchWords[$orIndex]['indexed_words'], 0, 7);
  647. $searchWords[$orIndex]['subject_words'] = array_slice($searchWords[$orIndex]['subject_words'], 0, 7);
  648. }
  649. }
  650. // *** Spell checking
  651. $context['show_spellchecking'] = !empty($modSettings['enableSpellChecking']) && function_exists('pspell_new');
  652. if ($context['show_spellchecking'])
  653. {
  654. // Windows fix.
  655. ob_start();
  656. $old = error_reporting(0);
  657. pspell_new('en');
  658. $pspell_link = pspell_new($txt['lang_dictionary'], $txt['lang_spelling'], '', strtr($txt['lang_character_set'], array('iso-' => 'iso', 'ISO-' => 'iso')), PSPELL_FAST | PSPELL_RUN_TOGETHER);
  659. error_reporting($old);
  660. if (!$pspell_link)
  661. $pspell_link = pspell_new('en', '', '', '', PSPELL_FAST | PSPELL_RUN_TOGETHER);
  662. ob_end_clean();
  663. $did_you_mean = array('search' => array(), 'display' => array());
  664. $found_misspelling = false;
  665. foreach ($searchArray as $word)
  666. {
  667. if (empty($pspell_link))
  668. continue;
  669. $word = $word;
  670. // Don't check phrases.
  671. if (preg_match('~^\w+$~', $word) === 0)
  672. {
  673. $did_you_mean['search'][] = '"' . $word . '"';
  674. $did_you_mean['display'][] = '&quot;' . $smcFunc['htmlspecialchars']($word) . '&quot;';
  675. continue;
  676. }
  677. // For some strange reason spell check can crash PHP on decimals.
  678. elseif (preg_match('~\d~', $word) === 1)
  679. {
  680. $did_you_mean['search'][] = $word;
  681. $did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
  682. continue;
  683. }
  684. elseif (pspell_check($pspell_link, $word))
  685. {
  686. $did_you_mean['search'][] = $word;
  687. $did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
  688. continue;
  689. }
  690. $suggestions = pspell_suggest($pspell_link, $word);
  691. foreach ($suggestions as $i => $s)
  692. {
  693. // Search is case insensitive.
  694. if ($smcFunc['strtolower']($s) == $smcFunc['strtolower']($word))
  695. unset($suggestions[$i]);
  696. // Plus, don't suggest something the user thinks is rude!
  697. elseif ($suggestions[$i] != censorText($s))
  698. unset($suggestions[$i]);
  699. }
  700. // Anything found? If so, correct it!
  701. if (!empty($suggestions))
  702. {
  703. $suggestions = array_values($suggestions);
  704. $did_you_mean['search'][] = $suggestions[0];
  705. $did_you_mean['display'][] = '<em><strong>' . $smcFunc['htmlspecialchars']($suggestions[0]) . '</strong></em>';
  706. $found_misspelling = true;
  707. }
  708. else
  709. {
  710. $did_you_mean['search'][] = $word;
  711. $did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
  712. }
  713. }
  714. if ($found_misspelling)
  715. {
  716. // Don't spell check excluded words, but add them still...
  717. $temp_excluded = array('search' => array(), 'display' => array());
  718. foreach ($excludedWords as $word)
  719. {
  720. $word = $word;
  721. if (preg_match('~^\w+$~', $word) == 0)
  722. {
  723. $temp_excluded['search'][] = '-"' . $word . '"';
  724. $temp_excluded['display'][] = '-&quot;' . $smcFunc['htmlspecialchars']($word) . '&quot;';
  725. }
  726. else
  727. {
  728. $temp_excluded['search'][] = '-' . $word;
  729. $temp_excluded['display'][] = '-' . $smcFunc['htmlspecialchars']($word);
  730. }
  731. }
  732. $did_you_mean['search'] = array_merge($did_you_mean['search'], $temp_excluded['search']);
  733. $did_you_mean['display'] = array_merge($did_you_mean['display'], $temp_excluded['display']);
  734. $temp_params = $search_params;
  735. $temp_params['search'] = implode(' ', $did_you_mean['search']);
  736. if (isset($temp_params['brd']))
  737. $temp_params['brd'] = implode(',', $temp_params['brd']);
  738. $context['params'] = array();
  739. foreach ($temp_params as $k => $v)
  740. $context['did_you_mean_params'][] = $k . '|\'|' . $v;
  741. $context['did_you_mean_params'] = base64_encode(implode('|"|', $context['did_you_mean_params']));
  742. $context['did_you_mean'] = implode(' ', $did_you_mean['display']);
  743. }
  744. }
  745. // Let the user adjust the search query, should they wish?
  746. $context['search_params'] = $search_params;
  747. if (isset($context['search_params']['search']))
  748. $context['search_params']['search'] = $smcFunc['htmlspecialchars']($context['search_params']['search']);
  749. if (isset($context['search_params']['userspec']))
  750. $context['search_params']['userspec'] = $smcFunc['htmlspecialchars']($context['search_params']['userspec']);
  751. // Do we have captcha enabled?
  752. if ($user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']) && (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != $search_params['search']))
  753. {
  754. // If we come from another search box tone down the error...
  755. if (!isset($_REQUEST['search_vv']))
  756. $context['search_errors']['need_verification_code'] = true;
  757. else
  758. {
  759. require_once($sourcedir . '/Subs-Editor.php');
  760. $verificationOptions = array(
  761. 'id' => 'search',
  762. );
  763. $context['require_verification'] = create_control_verification($verificationOptions, true);
  764. if (is_array($context['require_verification']))
  765. {
  766. foreach ($context['require_verification'] as $error)
  767. $context['search_errors'][$error] = true;
  768. }
  769. // Don't keep asking for it - they've proven themselves worthy.
  770. else
  771. $_SESSION['ss_vv_passed'] = true;
  772. }
  773. }
  774. // *** Encode all search params
  775. // All search params have been checked, let's compile them to a single string... made less simple by PHP 4.3.9 and below.
  776. $temp_params = $search_params;
  777. if (isset($temp_params['brd']))
  778. $temp_params['brd'] = implode(',', $temp_params['brd']);
  779. $context['params'] = array();
  780. foreach ($temp_params as $k => $v)
  781. $context['params'][] = $k . '|\'|' . $v;
  782. $context['params'] = base64_encode(implode('|"|', $context['params']));
  783. // ... and add the links to the link tree.
  784. $context['linktree'][] = array(
  785. 'url' => $scripturl . '?action=search;params=' . $context['params'],
  786. 'name' => $txt['search']
  787. );
  788. $context['linktree'][] = array(
  789. 'url' => $scripturl . '?action=search2;params=' . $context['params'],
  790. 'name' => $txt['search_results']
  791. );
  792. // *** A last error check
  793. // One or more search errors? Go back to the first search screen.
  794. if (!empty($context['search_errors']))
  795. {
  796. $_REQUEST['params'] = $context['params'];
  797. return PlushSearch1();
  798. }
  799. // Spam me not, Spam-a-lot?
  800. if (empty($_SESSION['last_ss']) || $_SESSION['last_ss'] != $search_params['search'])
  801. spamProtection('search');
  802. // Store the last search string to allow pages of results to be browsed.
  803. $_SESSION['last_ss'] = $search_params['search'];
  804. // *** Reserve an ID for caching the search results.
  805. $query_params = array_merge($search_params, array(
  806. 'min_msg_id' => isset($minMsgID) ? (int) $minMsgID : 0,
  807. 'max_msg_id' => isset($maxMsgID) ? (int) $maxMsgID : 0,
  808. 'memberlist' => !empty($memberlist) ? $memberlist : array(),
  809. ));
  810. // Can this search rely on the API given the parameters?
  811. if ($searchAPI->supportsMethod('searchQuery', $query_params))
  812. {
  813. $participants = array();
  814. $searchArray = array();
  815. $num_results = $searchAPI->searchQuery($query_params, $searchWords, $excludedIndexWords, $participants, $searchArray);
  816. }
  817. // Update the cache if the current search term is not yet cached.
  818. else
  819. {
  820. $update_cache = empty($_SESSION['search_cache']) || ($_SESSION['search_cache']['params'] != $context['params']);
  821. if ($update_cache)
  822. {
  823. // Increase the pointer...
  824. $modSettings['search_pointer'] = empty($modSettings['search_pointer']) ? 0 : (int) $modSettings['search_pointer'];
  825. // ...and store it right off.
  826. updateSettings(array('search_pointer' => $modSettings['search_pointer'] >= 255 ? 0 : $modSettings['search_pointer'] + 1));
  827. // As long as you don't change the parameters, the cache result is yours.
  828. $_SESSION['search_cache'] = array(
  829. 'id_search' => $modSettings['search_pointer'],
  830. 'num_results' => -1,
  831. 'params' => $context['params'],
  832. );
  833. // Clear the previous cache of the final results cache.
  834. $smcFunc['db_search_query']('delete_log_search_results', '
  835. DELETE FROM {db_prefix}log_search_results
  836. WHERE id_search = {int:search_id}',
  837. array(
  838. 'search_id' => $_SESSION['search_cache']['id_search'],
  839. )
  840. );
  841. if ($search_params['subject_only'])
  842. {
  843. // We do this to try and avoid duplicate keys on databases not supporting INSERT IGNORE.
  844. $inserts = array();
  845. foreach ($searchWords as $orIndex => $words)
  846. {
  847. $subject_query_params = array();
  848. $subject_query = array(
  849. 'from' => '{db_prefix}topics AS t',
  850. 'inner_join' => array(),
  851. 'left_join' => array(),
  852. 'where' => array(),
  853. );
  854. if ($modSettings['postmod_active'])
  855. $subject_query['where'][] = 't.approved = {int:is_approved}';
  856. $numTables = 0;
  857. $prev_join = 0;
  858. $numSubjectResults = 0;
  859. foreach ($words['subject_words'] as $subjectWord)
  860. {
  861. $numTables++;
  862. if (in_array($subjectWord, $excludedSubjectWords))
  863. {
  864. $subject_query['left_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_words_' . $numTables . '_wild}' : '= {string:subject_words_' . $numTables . '}') . ' AND subj' . $numTables . '.id_topic = t.id_topic)';
  865. $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
  866. }
  867. else
  868. {
  869. $subject_query['inner_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.id_topic = ' . ($prev_join === 0 ? 't' : 'subj' . $prev_join) . '.id_topic)';
  870. $subject_query['where'][] = 'subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_words_' . $numTables . '_wild}' : '= {string:subject_words_' . $numTables . '}');
  871. $prev_join = $numTables;
  872. }
  873. $subject_query_params['subject_words_' . $numTables] = $subjectWord;
  874. $subject_query_params['subject_words_' . $numTables . '_wild'] = '%' . $subjectWord . '%';
  875. }
  876. if (!empty($userQuery))
  877. {
  878. if ($subject_query['from'] != '{db_prefix}messages AS m')
  879. {
  880. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_topic = t.id_topic)';
  881. }
  882. $subject_query['where'][] = $userQuery;
  883. }
  884. if (!empty($search_params['topic']))
  885. $subject_query['where'][] = 't.id_topic = ' . $search_params['topic'];
  886. if (!empty($minMsgID))
  887. $subject_query['where'][] = 't.id_first_msg >= ' . $minMsgID;
  888. if (!empty($maxMsgID))
  889. $subject_query['where'][] = 't.id_last_msg <= ' . $maxMsgID;
  890. if (!empty($boardQuery))
  891. $subject_query['where'][] = 't.id_board ' . $boardQuery;
  892. if (!empty($excludedPhrases))
  893. {
  894. if ($subject_query['from'] != '{db_prefix}messages AS m')
  895. {
  896. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  897. }
  898. $count = 0;
  899. foreach ($excludedPhrases as $phrase)
  900. {
  901. $subject_query['where'][] = 'm.subject NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:excluded_phrases_' . $count . '}';
  902. $subject_query_params['excluded_phrases_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
  903. }
  904. }
  905. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_results_subject',
  906. ($smcFunc['db_support_ignore'] ? '
  907. INSERT IGNORE INTO {db_prefix}log_search_results
  908. (id_search, id_topic, relevance, id_msg, num_matches)' : '') . '
  909. SELECT
  910. {int:id_search},
  911. t.id_topic,
  912. 1000 * (
  913. {int:weight_frequency} / (t.num_replies + 1) +
  914. {int:weight_age} * CASE WHEN t.id_first_msg < {int:min_msg} THEN 0 ELSE (t.id_first_msg - {int:min_msg}) / {int:recent_message} END +
  915. {int:weight_length} * CASE WHEN t.num_replies < {int:huge_topic_posts} THEN t.num_replies / {int:huge_topic_posts} ELSE 1 END +
  916. {int:weight_subject} +
  917. {int:weight_sticky} * t.is_sticky
  918. ) / {int:weight_total} AS relevance,
  919. ' . (empty($userQuery) ? 't.id_first_msg' : 'm.id_msg') . ',
  920. 1
  921. FROM ' . $subject_query['from'] . (empty($subject_query['inner_join']) ? '' : '
  922. INNER JOIN ' . implode('
  923. INNER JOIN ', $subject_query['inner_join'])) . (empty($subject_query['left_join']) ? '' : '
  924. LEFT JOIN ' . implode('
  925. LEFT JOIN ', $subject_query['left_join'])) . '
  926. WHERE ' . implode('
  927. AND ', $subject_query['where']) . (empty($modSettings['search_max_results']) ? '' : '
  928. LIMIT ' . ($modSettings['search_max_results'] - $numSubjectResults)),
  929. array_merge($subject_query_params, array(
  930. 'id_search' => $_SESSION['search_cache']['id_search'],
  931. 'weight_age' => $weight['age'],
  932. 'weight_frequency' => $weight['frequency'],
  933. 'weight_length' => $weight['length'],
  934. 'weight_sticky' => $weight['sticky'],
  935. 'weight_subject' => $weight['subject'],
  936. 'weight_total' => $weight_total,
  937. 'min_msg' => $minMsg,
  938. 'recent_message' => $recentMsg,
  939. 'huge_topic_posts' => $humungousTopicPosts,
  940. 'is_approved' => 1,
  941. ))
  942. );
  943. // If the database doesn't support IGNORE to make this fast we need to do some tracking.
  944. if (!$smcFunc['db_support_ignore'])
  945. {
  946. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  947. {
  948. // No duplicates!
  949. if (isset($inserts[$row[1]]))
  950. continue;
  951. foreach ($row as $key => $value)
  952. $inserts[$row[1]][] = (int) $row[$key];
  953. }
  954. $smcFunc['db_free_result']($ignoreRequest);
  955. $numSubjectResults = count($inserts);
  956. }
  957. else
  958. $numSubjectResults += $smcFunc['db_affected_rows']();
  959. if (!empty($modSettings['search_max_results']) && $numSubjectResults >= $modSettings['search_max_results'])
  960. break;
  961. }
  962. // If there's data to be inserted for non-IGNORE databases do it here!
  963. if (!empty($inserts))
  964. {
  965. $smcFunc['db_insert']('',
  966. '{db_prefix}log_search_results',
  967. array('id_search' => 'int', 'id_topic' => 'int', 'relevance' => 'int', 'id_msg' => 'int', 'num_matches' => 'int'),
  968. $inserts,
  969. array('id_search', 'id_topic')
  970. );
  971. }
  972. $_SESSION['search_cache']['num_results'] = $numSubjectResults;
  973. }
  974. else
  975. {
  976. $main_query = array(
  977. 'select' => array(
  978. 'id_search' => $_SESSION['search_cache']['id_search'],
  979. 'relevance' => '0',
  980. ),
  981. 'weights' => array(),
  982. 'from' => '{db_prefix}topics AS t',
  983. 'inner_join' => array(
  984. '{db_prefix}messages AS m ON (m.id_topic = t.id_topic)'
  985. ),
  986. 'left_join' => array(),
  987. 'where' => array(),
  988. 'group_by' => array(),
  989. 'parameters' => array(
  990. 'min_msg' => $minMsg,
  991. 'recent_message' => $recentMsg,
  992. 'huge_topic_posts' => $humungousTopicPosts,
  993. 'is_approved' => 1,
  994. ),
  995. );
  996. if (empty($search_params['topic']))
  997. {
  998. $main_query['select']['id_topic'] = 't.id_topic';
  999. $main_query['select']['id_msg'] = 'MAX(m.id_msg) AS id_msg';
  1000. $main_query['select']['num_matches'] = 'COUNT(*) AS num_matches';
  1001. $main_query['weights'] = array(
  1002. 'frequency' => 'COUNT(*) / (MAX(t.num_replies) + 1)',
  1003. 'age' => 'CASE WHEN MAX(m.id_msg) < {int:min_msg} THEN 0 ELSE (MAX(m.id_msg) - {int:min_msg}) / {int:recent_message} END',
  1004. 'length' => 'CASE WHEN MAX(t.num_replies) < {int:huge_topic_posts} THEN MAX(t.num_replies) / {int:huge_topic_posts} ELSE 1 END',
  1005. 'subject' => '0',
  1006. 'first_message' => 'CASE WHEN MIN(m.id_msg) = MAX(t.id_first_msg) THEN 1 ELSE 0 END',
  1007. 'sticky' => 'MAX(t.is_sticky)',
  1008. );
  1009. $main_query['group_by'][] = 't.id_topic';
  1010. }
  1011. else
  1012. {
  1013. // This is outrageous!
  1014. $main_query['select']['id_topic'] = 'm.id_msg AS id_topic';
  1015. $main_query['select']['id_msg'] = 'm.id_msg';
  1016. $main_query['select']['num_matches'] = '1 AS num_matches';
  1017. $main_query['weights'] = array(
  1018. 'age' => '((m.id_msg - t.id_first_msg) / CASE WHEN t.id_last_msg = t.id_first_msg THEN 1 ELSE t.id_last_msg - t.id_first_msg END)',
  1019. 'first_message' => 'CASE WHEN m.id_msg = t.id_first_msg THEN 1 ELSE 0 END',
  1020. );
  1021. $main_query['where'][] = 't.id_topic = {int:topic}';
  1022. $main_query['parameters']['topic'] = $search_params['topic'];
  1023. }
  1024. // *** Get the subject results.
  1025. $numSubjectResults = 0;
  1026. if (empty($search_params['topic']))
  1027. {
  1028. $inserts = array();
  1029. // Create a temporary table to store some preliminary results in.
  1030. $smcFunc['db_search_query']('drop_tmp_log_search_topics', '
  1031. DROP TABLE IF EXISTS {db_prefix}tmp_log_search_topics',
  1032. array(
  1033. 'db_error_skip' => true,
  1034. )
  1035. );
  1036. $createTemporary = $smcFunc['db_search_query']('create_tmp_log_search_topics', '
  1037. CREATE TEMPORARY TABLE {db_prefix}tmp_log_search_topics (
  1038. id_topic mediumint(8) unsigned NOT NULL default {string:string_zero},
  1039. PRIMARY KEY (id_topic)
  1040. ) TYPE=HEAP',
  1041. array(
  1042. 'string_zero' => '0',
  1043. 'db_error_skip' => true,
  1044. )
  1045. ) !== false;
  1046. // Clean up some previous cache.
  1047. if (!$createTemporary)
  1048. $smcFunc['db_search_query']('delete_log_search_topics', '
  1049. DELETE FROM {db_prefix}log_search_topics
  1050. WHERE id_search = {int:search_id}',
  1051. array(
  1052. 'search_id' => $_SESSION['search_cache']['id_search'],
  1053. )
  1054. );
  1055. foreach ($searchWords as $orIndex => $words)
  1056. {
  1057. $subject_query = array(
  1058. 'from' => '{db_prefix}topics AS t',
  1059. 'inner_join' => array(),
  1060. 'left_join' => array(),
  1061. 'where' => array(),
  1062. 'params' => array(),
  1063. );
  1064. $numTables = 0;
  1065. $prev_join = 0;
  1066. $count = 0;
  1067. foreach ($words['subject_words'] as $subjectWord)
  1068. {
  1069. $numTables++;
  1070. if (in_array($subjectWord, $excludedSubjectWords))
  1071. {
  1072. if ($subject_query['from'] != '{db_prefix}messages AS m')
  1073. {
  1074. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  1075. }
  1076. $subject_query['left_join'][] = '{db_prefix}log_search_subjects AS subj' . $numTables . ' ON (subj' . $numTables . '.word ' . (empty($modSettings['search_match_words']) ? 'LIKE {string:subject_not_' . $count . '}' : '= {string:subject_not_' . $count . '}') . ' AND subj' . $numTables . '.id_topic = t.id_topic)';
  1077. $subject_query['params']['subject_not_' . $count] = empty($modSettings['search_match_words']) ? '%' . $subjectWord . '%' : $subjectWord;
  1078. $subject_query['where'][] = '(subj' . $numTables . '.word IS NULL)';
  1079. $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:body_not_' . $count . '}';
  1080. $subject_query['params']['body_not_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($subjectWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $subjectWord), '\\\'') . '[[:>:]]';
  1081. }
  1082. else
  1083. {
  1084. $subject_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)';
  1085. $subject_query['where'][] = 'subj' . $numTables . '.word LIKE {string:subject_like_' . $count . '}';
  1086. $subject_query['params']['subject_like_' . $count++] = empty($modSettings['search_match_words']) ? '%' . $subjectWord . '%' : $subjectWord;
  1087. $prev_join = $numTables;
  1088. }
  1089. }
  1090. if (!empty($userQuery))
  1091. {
  1092. if ($subject_query['from'] != '{db_prefix}messages AS m')
  1093. {
  1094. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  1095. }
  1096. $subject_query['where'][] = '{raw:user_query}';
  1097. $subject_query['params']['user_query'] = $userQuery;
  1098. }
  1099. if (!empty($search_params['topic']))
  1100. {
  1101. $subject_query['where'][] = 't.id_topic = {int:topic}';
  1102. $subject_query['params']['topic'] = $search_params['topic'];
  1103. }
  1104. if (!empty($minMsgID))
  1105. {
  1106. $subject_query['where'][] = 't.id_first_msg >= {int:min_msg_id}';
  1107. $subject_query['params']['min_msg_id'] = $minMsgID;
  1108. }
  1109. if (!empty($maxMsgID))
  1110. {
  1111. $subject_query['where'][] = 't.id_last_msg <= {int:max_msg_id}';
  1112. $subject_query['params']['max_msg_id'] = $maxMsgID;
  1113. }
  1114. if (!empty($boardQuery))
  1115. {
  1116. $subject_query['where'][] = 't.id_board {raw:board_query}';
  1117. $subject_query['params']['board_query'] = $boardQuery;
  1118. }
  1119. if (!empty($excludedPhrases))
  1120. {
  1121. if ($subject_query['from'] != '{db_prefix}messages AS m')
  1122. {
  1123. $subject_query['inner_join'][] = '{db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)';
  1124. }
  1125. $count = 0;
  1126. foreach ($excludedPhrases as $phrase)
  1127. {
  1128. $subject_query['where'][] = 'm.subject NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:exclude_phrase_' . $count . '}';
  1129. $subject_query['where'][] = 'm.body NOT ' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:exclude_phrase_' . $count . '}';
  1130. $subject_query['params']['exclude_phrase_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($phrase, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $phrase), '\\\'') . '[[:>:]]';
  1131. }
  1132. }
  1133. // Nothing to search for?
  1134. if (empty($subject_query['where']))
  1135. continue;
  1136. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_topics', ($smcFunc['db_support_ignore'] ? ( '
  1137. INSERT IGNORE INTO {db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics
  1138. (' . ($createTemporary ? '' : 'id_search, ') . 'id_topic)') : '') . '
  1139. SELECT ' . ($createTemporary ? '' : $_SESSION['search_cache']['id_search'] . ', ') . 't.id_topic
  1140. FROM ' . $subject_query['from'] . (empty($subject_query['inner_join']) ? '' : '
  1141. INNER JOIN ' . implode('
  1142. INNER JOIN ', $subject_query['inner_join'])) . (empty($subject_query['left_join']) ? '' : '
  1143. LEFT JOIN ' . implode('
  1144. LEFT JOIN ', $subject_query['left_join'])) . '
  1145. WHERE ' . implode('
  1146. AND ', $subject_query['where']) . (empty($modSettings['search_max_results']) ? '' : '
  1147. LIMIT ' . ($modSettings['search_max_results'] - $numSubjectResults)),
  1148. $subject_query['params']
  1149. );
  1150. // Don't do INSERT IGNORE? Manually fix this up!
  1151. if (!$smcFunc['db_support_ignore'])
  1152. {
  1153. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1154. {
  1155. $ind = $createTemporary ? 0 : 1;
  1156. // No duplicates!
  1157. if (isset($inserts[$row[$ind]]))
  1158. continue;
  1159. $inserts[$row[$ind]] = $row;
  1160. }
  1161. $smcFunc['db_free_result']($ignoreRequest);
  1162. $numSubjectResults = count($inserts);
  1163. }
  1164. else
  1165. $numSubjectResults += $smcFunc['db_affected_rows']();
  1166. if (!empty($modSettings['search_max_results']) && $numSubjectResults >= $modSettings['search_max_results'])
  1167. break;
  1168. }
  1169. // Got some non-MySQL data to plonk in?
  1170. if (!empty($inserts))
  1171. {
  1172. $smcFunc['db_insert']('',
  1173. ('{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics'),
  1174. $createTemporary ? array('id_topic' => 'int') : array('id_search' => 'int', 'id_topic' => 'int'),
  1175. $inserts,
  1176. $createTemporary ? array('id_topic') : array('id_search', 'id_topic')
  1177. );
  1178. }
  1179. if ($numSubjectResults !== 0)
  1180. {
  1181. $main_query['weights']['subject'] = 'CASE WHEN MAX(lst.id_topic) IS NULL THEN 0 ELSE 1 END';
  1182. $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)';
  1183. if ($createTemporary)
  1184. $main_query['parameters']['id_search'] = $_SESSION['search_cache']['id_search'];
  1185. }
  1186. }
  1187. $indexedResults = 0;
  1188. // We building an index?
  1189. if ($searchAPI->supportsMethod('indexedWordQuery', $query_params))
  1190. {
  1191. $inserts = array();
  1192. $smcFunc['db_search_query']('drop_tmp_log_search_messages', '
  1193. DROP TABLE IF EXISTS {db_prefix}tmp_log_search_messages',
  1194. array(
  1195. 'db_error_skip' => true,
  1196. )
  1197. );
  1198. $createTemporary = $smcFunc['db_search_query']('create_tmp_log_search_messages', '
  1199. CREATE TEMPORARY TABLE {db_prefix}tmp_log_search_messages (
  1200. id_msg int(10) unsigned NOT NULL default {string:string_zero},
  1201. PRIMARY KEY (id_msg)
  1202. ) TYPE=HEAP',
  1203. array(
  1204. 'string_zero' => '0',
  1205. 'db_error_skip' => true,
  1206. )
  1207. ) !== false;
  1208. if (!$createTemporary)
  1209. $smcFunc['db_search_query']('delete_log_search_messages', '
  1210. DELETE FROM {db_prefix}log_search_messages
  1211. WHERE id_search = {int:id_search}',
  1212. array(
  1213. 'id_search' => $_SESSION['search_cache']['id_search'],
  1214. )
  1215. );
  1216. foreach ($searchWords as $orIndex => $words)
  1217. {
  1218. // Search for this word, assuming we have some words!
  1219. if (!empty($words['indexed_words']))
  1220. {
  1221. // Variables required for the search.
  1222. $search_data = array(
  1223. 'insert_into' => ($createTemporary ? 'tmp_' : '') . 'log_search_messages',
  1224. 'no_regexp' => $no_regexp,
  1225. 'max_results' => $maxMessageResults,
  1226. 'indexed_results' => $indexedResults,
  1227. 'params' => array(
  1228. 'id_search' => !$createTemporary ? $_SESSION['search_cache']['id_search'] : 0,
  1229. 'excluded_words' => $excludedWords,
  1230. 'user_query' => !empty($userQuery) ? $userQuery : '',
  1231. 'board_query' => !empty($boardQuery) ? $boardQuery : '',
  1232. 'topic' => !empty($search_params['topic']) ? $search_params['topic'] : 0,
  1233. 'min_msg_id' => !empty($minMsgID) ? $minMsgID : 0,
  1234. 'max_msg_id' => !empty($maxMsgID) ? $maxMsgID : 0,
  1235. 'excluded_phrases' => !empty($excludedPhrases) ? $excludedPhrases : array(),
  1236. 'excluded_index_words' => !empty($excludedIndexWords) ? $excludedIndexWords : array(),
  1237. 'excluded_subject_words' => !empty($excludedSubjectWords) ? $excludedSubjectWords : array(),
  1238. ),
  1239. );
  1240. $ignoreRequest = $searchAPI->indexedWordQuery($words, $search_data);
  1241. if (!$smcFunc['db_support_ignore'])
  1242. {
  1243. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1244. {
  1245. // No duplicates!
  1246. if (isset($inserts[$row[0]]))
  1247. continue;
  1248. $inserts[$row[0]] = $row;
  1249. }
  1250. $smcFunc['db_free_result']($ignoreRequest);
  1251. $indexedResults = count($inserts);
  1252. }
  1253. else
  1254. $indexedResults += $smcFunc['db_affected_rows']();
  1255. if (!empty($maxMessageResults) && $indexedResults >= $maxMessageResults)
  1256. break;
  1257. }
  1258. }
  1259. // More non-MySQL stuff needed?
  1260. if (!empty($inserts))
  1261. {
  1262. $smcFunc['db_insert']('',
  1263. '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_messages',
  1264. $createTemporary ? array('id_msg' => 'int') : array('id_msg' => 'int', 'id_search' => 'int'),
  1265. $inserts,
  1266. $createTemporary ? array('id_msg') : array('id_msg', 'id_search')
  1267. );
  1268. }
  1269. if (empty($indexedResults) && empty($numSubjectResults) && !empty($modSettings['search_force_index']))
  1270. {
  1271. $context['search_errors']['query_not_specific_enough'] = true;
  1272. $_REQUEST['params'] = $context['params'];
  1273. return PlushSearch1();
  1274. }
  1275. elseif (!empty($indexedResults))
  1276. {
  1277. $main_query['inner_join'][] = '{db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_messages AS lsm ON (lsm.id_msg = m.id_msg)';
  1278. if (!$createTemporary)
  1279. {
  1280. $main_query['where'][] = 'lsm.id_search = {int:id_search}';
  1281. $main_query['parameters']['id_search'] = $_SESSION['search_cache']['id_search'];
  1282. }
  1283. }
  1284. }
  1285. // Not using an index? All conditions have to be carried over.
  1286. else
  1287. {
  1288. $orWhere = array();
  1289. $count = 0;
  1290. foreach ($searchWords as $orIndex => $words)
  1291. {
  1292. $where = array();
  1293. foreach ($words['all_words'] as $regularWord)
  1294. {
  1295. $where[] = 'm.body' . (in_array($regularWord, $excludedWords) ? ' NOT' : '') . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:all_word_body_' . $count . '}';
  1296. if (in_array($regularWord, $excludedWords))
  1297. $where[] = 'm.subject NOT' . (empty($modSettings['search_match_words']) || $no_regexp ? ' LIKE ' : ' RLIKE ') . '{string:all_word_body_' . $count . '}';
  1298. $main_query['parameters']['all_word_body_' . $count++] = empty($modSettings['search_match_words']) || $no_regexp ? '%' . strtr($regularWord, array('_' => '\\_', '%' => '\\%')) . '%' : '[[:<:]]' . addcslashes(preg_replace(array('/([\[\]$.+*?|{}()])/'), array('[$1]'), $regularWord), '\\\'') . '[[:>:]]';
  1299. }
  1300. if (!empty($where))
  1301. $orWhere[] = count($where) > 1 ? '(' . implode(' AND ', $where) . ')' : $where[0];
  1302. }
  1303. if (!empty($orWhere))
  1304. $main_query['where'][] = count($orWhere) > 1 ? '(' . implode(' OR ', $orWhere) . ')' : $orWhere[0];
  1305. if (!empty($userQuery))
  1306. {
  1307. $main_query['where'][] = '{raw:user_query}';
  1308. $main_query['parameters']['user_query'] = $userQuery;
  1309. }
  1310. if (!empty($search_params['topic']))
  1311. {
  1312. $main_query['where'][] = 'm.id_topic = {int:topic}';
  1313. $main_query['parameters']['topic'] = $search_params['topic'];
  1314. }
  1315. if (!empty($minMsgID))
  1316. {
  1317. $main_query['where'][] = 'm.id_msg >= {int:min_msg_id}';
  1318. $main_query['parameters']['min_msg_id'] = $minMsgID;
  1319. }
  1320. if (!empty($maxMsgID))
  1321. {
  1322. $main_query['where'][] = 'm.id_msg <= {int:max_msg_id}';
  1323. $main_query['parameters']['max_msg_id'] = $maxMsgID;
  1324. }
  1325. if (!empty($boardQuery))
  1326. {
  1327. $main_query['where'][] = 'm.id_board {raw:board_query}';
  1328. $main_query['parameters']['board_query'] = $boardQuery;
  1329. }
  1330. }
  1331. // Did we either get some indexed results, or otherwise did not do an indexed query?
  1332. if (!empty($indexedResults) || !$searchAPI->supportsMethod('indexedWordQuery', $query_params))
  1333. {
  1334. $relevance = '1000 * (';
  1335. $new_weight_total = 0;
  1336. foreach ($main_query['weights'] as $type => $value)
  1337. {
  1338. $relevance .= $weight[$type] . ' * ' . $value . ' + ';
  1339. $new_weight_total += $weight[$type];
  1340. }
  1341. $main_query['select']['relevance'] = substr($relevance, 0, -3) . ') / ' . $new_weight_total . ' AS relevance';
  1342. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_results_no_index', ($smcFunc['db_support_ignore'] ? ( '
  1343. INSERT IGNORE INTO ' . '{db_prefix}log_search_results
  1344. (' . implode(', ', array_keys($main_query['select'])) . ')') : '') . '
  1345. SELECT
  1346. ' . implode(',
  1347. ', $main_query['select']) . '
  1348. FROM ' . $main_query['from'] . (empty($main_query['inner_join']) ? '' : '
  1349. INNER JOIN ' . implode('
  1350. INNER JOIN ', $main_query['inner_join'])) . (empty($main_query['left_join']) ? '' : '
  1351. LEFT JOIN ' . implode('
  1352. LEFT JOIN ', $main_query['left_join'])) . (!empty($main_query['where']) ? '
  1353. WHERE ' : '') . implode('
  1354. AND ', $main_query['where']) . (empty($main_query['group_by']) ? '' : '
  1355. GROUP BY ' . implode(', ', $main_query['group_by'])) . (empty($modSettings['search_max_results']) ? '' : '
  1356. LIMIT ' . $modSettings['search_max_results']),
  1357. $main_query['parameters']
  1358. );
  1359. // We love to handle non-good databases that don't support our ignore!
  1360. if (!$smcFunc['db_support_ignore'])
  1361. {
  1362. $inserts = array();
  1363. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1364. {
  1365. // No duplicates!
  1366. if (isset($inserts[$row[2]]))
  1367. continue;
  1368. foreach ($row as $key => $value)
  1369. $inserts[$row[2]][] = (int) $row[$key];
  1370. }
  1371. $smcFunc['db_free_result']($ignoreRequest);
  1372. // Now put them in!
  1373. if (!empty($inserts))
  1374. {
  1375. $query_columns = array();
  1376. foreach ($main_query['select'] as $k => $v)
  1377. $query_columns[$k] = 'int';
  1378. $smcFunc['db_insert']('',
  1379. '{db_prefix}log_search_results',
  1380. $query_columns,
  1381. $inserts,
  1382. array('id_search', 'id_topic')
  1383. );
  1384. }
  1385. $_SESSION['search_cache']['num_results'] += count($inserts);
  1386. }
  1387. else
  1388. $_SESSION['search_cache']['num_results'] = $smcFunc['db_affected_rows']();
  1389. }
  1390. // Insert subject-only matches.
  1391. if ($_SESSION['search_cache']['num_results'] < $modSettings['search_max_results'] && $numSubjectResults !== 0)
  1392. {
  1393. $usedIDs = array_flip(empty($inserts) ? array() : array_keys($inserts));
  1394. $ignoreRequest = $smcFunc['db_search_query']('insert_log_search_results_sub_only', ($smcFunc['db_support_ignore'] ? ( '
  1395. INSERT IGNORE INTO {db_prefix}log_search_results
  1396. (id_search, id_topic, relevance, id_msg, num_matches)') : '') . '
  1397. SELECT
  1398. {int:id_search},
  1399. t.id_topic,
  1400. 1000 * (
  1401. {int:weight_frequency} / (t.num_replies + 1) +
  1402. {int:weight_age} * CASE WHEN t.id_first_msg < {int:min_msg} THEN 0 ELSE (t.id_first_msg - {int:min_msg}) / {int:recent_message} END +
  1403. {int:weight_length} * CASE WHEN t.num_replies < {int:huge_topic_posts} THEN t.num_replies / {int:huge_topic_posts} ELSE 1 END +
  1404. {int:weight_subject} +
  1405. {int:weight_sticky} * t.is_sticky
  1406. ) / {int:weight_total} AS relevance,
  1407. t.id_first_msg,
  1408. 1
  1409. FROM {db_prefix}topics AS t
  1410. INNER JOIN {db_prefix}' . ($createTemporary ? 'tmp_' : '') . 'log_search_topics AS lst ON (lst.id_topic = t.id_topic)
  1411. ' . (empty($modSettings['search_max_results']) ? '' : '
  1412. LIMIT ' . ($modSettings['search_max_results'] - $_SESSION['search_cache']['num_results'])),
  1413. array(
  1414. 'id_search' => $_SESSION['search_cache']['id_search'],
  1415. 'weight_age' => $weight['age'],
  1416. 'weight_frequency' => $weight['frequency'],
  1417. 'weight_length' => $weight['frequency'],
  1418. 'weight_sticky' => $weight['frequency'],
  1419. 'weight_subject' => $weight['frequency'],
  1420. 'weight_total' => $weight_total,
  1421. 'min_msg' => $minMsg,
  1422. 'recent_message' => $recentMsg,
  1423. 'huge_topic_posts' => $humungousTopicPosts,
  1424. )
  1425. );
  1426. // Once again need to do the inserts if the database don't support ignore!
  1427. if (!$smcFunc['db_support_ignore'])
  1428. {
  1429. $inserts = array();
  1430. while ($row = $smcFunc['db_fetch_row']($ignoreRequest))
  1431. {
  1432. // No duplicates!
  1433. if (isset($usedIDs[$row[1]]))
  1434. continue;
  1435. $usedIDs[$row[1]] = true;
  1436. $inserts[] = $row;
  1437. }
  1438. $smcFunc['db_free_result']($ignoreRequest);
  1439. // Now put them in!
  1440. if (!empty($inserts))
  1441. {
  1442. $smcFunc['db_insert']('',
  1443. '{db_prefix}log_search_results',
  1444. array('id_search' => 'int', 'id_topic' => 'int', 'relevance' => 'float', 'id_msg' => 'int', 'num_matches' => 'int'),
  1445. $inserts,
  1446. array('id_search', 'id_topic')
  1447. );
  1448. }
  1449. $_SESSION['search_cache']['num_results'] += count($inserts);
  1450. }
  1451. else
  1452. $_SESSION['search_cache']['num_results'] += $smcFunc['db_affected_rows']();
  1453. }
  1454. else
  1455. $_SESSION['search_cache']['num_results'] = 0;
  1456. }
  1457. }
  1458. // *** Retrieve the results to be shown on the page
  1459. $participants = array();
  1460. $request = $smcFunc['db_search_query']('', '
  1461. SELECT ' . (empty($search_params['topic']) ? 'lsr.id_topic' : $search_params['topic'] . ' AS id_topic') . ', lsr.id_msg, lsr.relevance, lsr.num_matches
  1462. FROM {db_prefix}log_search_results AS lsr' . ($search_params['sort'] == 'num_replies' ? '
  1463. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = lsr.id_topic)' : '') . '
  1464. WHERE lsr.id_search = {int:id_search}
  1465. ORDER BY ' . $search_params['sort'] . ' ' . $search_params['sort_dir'] . '
  1466. LIMIT ' . (int) $_REQUEST['start'] . ', ' . $modSettings['search_results_per_page'],
  1467. array(
  1468. 'id_search' => $_SESSION['search_cache']['id_search'],
  1469. )
  1470. );
  1471. while ($row = $smcFunc['db_fetch_assoc']($request))
  1472. {
  1473. $context['topics'][$row['id_msg']] = array(
  1474. 'id' => $row['id_topic'],
  1475. 'relevance' => round($row['relevance'] / 10, 1) . '%',
  1476. 'num_matches' => $row['num_matches'],
  1477. 'matches' => array(),
  1478. );
  1479. // By default they didn't participate in the topic!
  1480. $participants[$row['id_topic']] = false;
  1481. }
  1482. $smcFunc['db_free_result']($request);
  1483. $num_results = $_SESSION['search_cache']['num_results'];
  1484. }
  1485. if (!empty($context['topics']))
  1486. {
  1487. // Create an array for the permissions.
  1488. $boards_can = array(
  1489. 'post_reply_own' => boardsAllowedTo('post_reply_own'),
  1490. 'post_reply_any' => boardsAllowedTo('post_reply_any'),
  1491. 'mark_any_notify' => boardsAllowedTo('mark_any_notify')
  1492. );
  1493. // How's about some quick moderation?
  1494. if (!empty($options['display_quick_mod']) && !empty($context['topics']))
  1495. {
  1496. $boards_can['lock_any'] = boardsAllowedTo('lock_any');
  1497. $boards_can['lock_own'] = boardsAllowedTo('lock_own');
  1498. $boards_can['make_sticky'] = boardsAllowedTo('make_sticky');
  1499. $boards_can['move_any'] = boardsAllowedTo('move_any');
  1500. $boards_can['move_own'] = boardsAllowedTo('move_own');
  1501. $boards_can['remove_any'] = boardsAllowedTo('remove_any');
  1502. $boards_can['remove_own'] = boardsAllowedTo('remove_own');
  1503. $boards_can['merge_any'] = boardsAllowedTo('merge_any');
  1504. $context['can_lock'] = in_array(0, $boards_can['lock_any']);
  1505. $context['can_sticky'] = in_array(0, $boards_can['make_sticky']) && !empty($modSettings['enableStickyTopics']);
  1506. $context['can_move'] = in_array(0, $boards_can['move_any']);
  1507. $context['can_remove'] = in_array(0, $boards_can['remove_any']);
  1508. $context['can_merge'] = in_array(0, $boards_can['merge_any']);
  1509. }
  1510. // What messages are we using?
  1511. $msg_list = array_keys($context['topics']);
  1512. // Load the posters...
  1513. $request = $smcFunc['db_query']('', '
  1514. SELECT id_member
  1515. FROM {db_prefix}messages
  1516. WHERE id_member != {int:no_member}
  1517. AND id_msg IN ({array_int:message_list})
  1518. LIMIT ' . count($context['topics']),
  1519. array(
  1520. 'message_list' => $msg_list,
  1521. 'no_member' => 0,
  1522. )
  1523. );
  1524. $posters = array();
  1525. while ($row = $smcFunc['db_fetch_assoc']($request))
  1526. $posters[] = $row['id_member'];
  1527. $smcFunc['db_free_result']($request);
  1528. if (!empty($posters))
  1529. loadMemberData(array_unique($posters));
  1530. // Get the messages out for the callback - select enough that it can be made to look just like Display.
  1531. $messages_request = $smcFunc['db_query']('', '
  1532. SELECT
  1533. m.id_msg, m.subject, m.poster_name, m.poster_email, m.poster_time, m.id_member,
  1534. m.icon, m.poster_ip, m.body, m.smileys_enabled, m.modified_time, m.modified_name,
  1535. 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,
  1536. first_mem.id_member AS first_member_id, IFNULL(first_mem.real_name, first_m.poster_name) AS first_member_name,
  1537. last_m.id_msg AS last_msg, last_m.poster_time AS last_poster_time, last_mem.id_member AS last_member_id,
  1538. 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,
  1539. t.id_topic, t.is_sticky, t.locked, t.id_poll, t.num_replies, t.num_views,
  1540. b.id_board, b.name AS board_name, c.id_cat, c.name AS cat_name
  1541. FROM {db_prefix}messages AS m
  1542. INNER JOIN {db_prefix}topics AS t ON (t.id_topic = m.id_topic)
  1543. INNER JOIN {db_prefix}boards AS b ON (b.id_board = t.id_board)
  1544. INNER JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
  1545. INNER JOIN {db_prefix}messages AS first_m ON (first_m.id_msg = t.id_first_msg)
  1546. INNER JOIN {db_prefix}messages AS last_m ON (last_m.id_msg = t.id_last_msg)
  1547. LEFT JOIN {db_prefix}members AS first_mem ON (first_mem.id_member = first_m.id_member)
  1548. LEFT JOIN {db_prefix}members AS last_mem ON (last_mem.id_member = first_m.id_member)
  1549. WHERE m.id_msg IN ({array_int:message_list})' . ($modSettings['postmod_active'] ? '
  1550. AND m.approved = {int:is_approved}' : '') . '
  1551. ORDER BY FIND_IN_SET(m.id_msg, {string:message_list_in_set})
  1552. LIMIT {int:limit}',
  1553. array(
  1554. 'message_list' => $msg_list,
  1555. 'is_approved' => 1,
  1556. 'message_list_in_set' => implode(',', $msg_list),
  1557. 'limit' => count($context['topics']),
  1558. )
  1559. );
  1560. // Note that the reg-exp slows things alot, but makes things make a lot more sense.
  1561. // If there are no results that means the things in the cache got deleted, so pretend we have no topics any more.
  1562. if ($smcFunc['db_num_rows']($messages_request) == 0)
  1563. $context['topics'] = array();
  1564. // If we want to know who participated in what then load this now.
  1565. if (!empty($modSettings['enableParticipation']) && !$user_info['is_guest'])
  1566. {
  1567. $result = $smcFunc['db_query']('', '
  1568. SELECT id_topic
  1569. FROM {db_prefix}messages
  1570. WHERE id_topic IN ({array_int:topic_list})
  1571. AND id_member = {int:current_member}
  1572. GROUP BY id_topic
  1573. LIMIT ' . count($participants),
  1574. array(
  1575. 'current_member' => $user_info['id'],
  1576. 'topic_list' => array_keys($participants),
  1577. )
  1578. );
  1579. while ($row = $smcFunc['db_fetch_assoc']($result))
  1580. $participants[$row['id_topic']] = true;
  1581. $smcFunc['db_free_result']($result);
  1582. }
  1583. }
  1584. // Now that we know how many results to expect we can start calculating the page numbers.
  1585. $context['page_index'] = constructPageIndex($scripturl . '?action=search2;params=' . $context['params'], $_REQUEST['start'], $num_results, $modSettings['search_results_per_page'], false);
  1586. // Consider the search complete!
  1587. if (!empty($modSettings['cache_enable']) && $modSettings['cache_enable'] >= 2)
  1588. cache_put_data('search_start:' . ($user_info['is_guest'] ? $user_info['ip'] : $user_info['id']), null, 90);
  1589. $context['key_words'] = &$searchArray;
  1590. // Setup the default topic icons... for checking they exist and the like!
  1591. $stable_icons = array('xx', 'thumbup', 'thumbdown', 'exclamation', 'question', 'lamp', 'smiley', 'angry', 'cheesy', 'grin', 'sad', 'wink', 'moved', 'recycled', 'wireless', 'clip');
  1592. $context['icon_sources'] = array();
  1593. foreach ($stable_icons as $icon)
  1594. $context['icon_sources'][$icon] = 'images_url';
  1595. $context['sub_template'] = 'results';
  1596. $context['page_title'] = $txt['search_results'];
  1597. $context['get_topics'] = 'prepareSearchContext';
  1598. $context['can_send_pm'] = allowedTo('pm_send');
  1599. $context['jump_to'] = array(
  1600. 'label' => addslashes(un_htmlspecialchars($txt['jump_to'])),
  1601. 'board_name' => addslashes(un_htmlspecialchars($txt['select_destination'])),
  1602. );
  1603. }
  1604. // Callback to return messages - saves memory.
  1605. // !!! Fix this, update it, whatever... from Display.php mainly.
  1606. function prepareSearchContext($reset = false)
  1607. {
  1608. global $txt, $modSettings, $scripturl, $user_info, $sourcedir;
  1609. global $memberContext, $context, $settings, $options, $messages_request;
  1610. global $boards_can, $participants, $smcFunc;
  1611. // Remember which message this is. (ie. reply #83)
  1612. static $counter = null;
  1613. if ($counter == null || $reset)
  1614. $counter = $_REQUEST['start'] + 1;
  1615. // If the query returned false, bail.
  1616. if ($messages_request == false)
  1617. return false;
  1618. // Start from the beginning...
  1619. if ($reset)
  1620. return @$smcFunc['db_data_seek']($messages_request, 0);
  1621. // Attempt to get the next message.
  1622. $message = $smcFunc['db_fetch_assoc']($messages_request);
  1623. if (!$message)
  1624. return false;
  1625. // Can't have an empty subject can we?
  1626. $message['subject'] = $message['subject'] != '' ? $message['subject'] : $txt['no_subject'];
  1627. $message['first_subject'] = $message['first_subject'] != '' ? $message['first_subject'] : $txt['no_subject'];
  1628. $message['last_subject'] = $message['last_subject'] != '' ? $message['last_subject'] : $txt['no_subject'];
  1629. // If it couldn't load, or the user was a guest.... someday may be done with a guest table.
  1630. if (!loadMemberContext($message['id_member']))
  1631. {
  1632. // Notice this information isn't used anywhere else.... *cough guest table cough*.
  1633. $memberContext[$message['id_member']]['name'] = $message['poster_name'];
  1634. $memberContext[$message['id_member']]['id'] = 0;
  1635. $memberContext[$message['id_member']]['group'] = $txt['guest_title'];
  1636. $memberContext[$message['id_member']]['link'] = $message['poster_name'];
  1637. $memberContext[$message['id_member']]['email'] = $message['poster_email'];
  1638. }
  1639. $memberContext[$message['id_member']]['ip'] = $message['poster_ip'];
  1640. // Do the censor thang...
  1641. censorText($message['body']);
  1642. censorText($message['subject']);
  1643. censorText($message['first_subject']);
  1644. censorText($message['last_subject']);
  1645. // Shorten this message if necessary.
  1646. if ($context['compact'])
  1647. {
  1648. // Set the number of characters before and after the searched keyword.
  1649. $charLimit = 40;
  1650. $message['body'] = strtr($message['body'], array("\n" => ' ', '<br />' => "\n"));
  1651. $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
  1652. $message['body'] = strip_tags(strtr($message['body'], array('</div>' => '<br />', '</li>' => '<br />')), '<br>');
  1653. if (strlen($message['body']) > $charLimit)
  1654. {
  1655. if (empty($context['key_words']))
  1656. $message['body'] = $smcFunc['strlen']($message['body']) > $charLimit ? $smcFunc['substr']($message['body'], 0, $charLimit) . '<strong>...</strong>' : $message['body'];
  1657. else
  1658. {
  1659. $matchString = '';
  1660. $force_partial_word = false;
  1661. foreach ($context['key_words'] as $keyword)
  1662. {
  1663. $keyword = preg_replace('~&amp;#(\d{1,7}|x[0-9a-fA-F]{1,6});~e', '$GLOBALS[\'smcFunc\'][\'entity_fix\'](\'\\1\')', strtr($keyword, array('\\\'' => '\'', '&' => '&amp;')));
  1664. if (preg_match('~[\'\.,/@%&;:(){}\[\]_\-+\\\\]$~', $keyword) != 0 || preg_match('~^[\'\.,/@%&;:(){}\[\]_\-+\\\\]~', $keyword) != 0)
  1665. $force_partial_word = true;
  1666. $matchString .= strtr(preg_quote($keyword, '/'), array('\*' => '.+?')) . '|';
  1667. }
  1668. $matchString = substr($matchString, 0, -1);
  1669. $message['body'] = un_htmlspecialchars(strtr($message['body'], array('&nbsp;' => ' ', '<br />' => "\n", '&#91;' => '[', '&#93;' => ']', '&#58;' => ':', '&#64;' => '@')));
  1670. if (empty($modSettings['search_method']) || $force_partial_word)
  1671. preg_match_all('/([^\s\W]{' . $charLimit . '}[\s\W]|[\s\W].{0,' . $charLimit . '}?|^)(' . $matchString . ')(.{0,' . $charLimit . '}[\s\W]|[^\s\W]{' . $charLimit . '})/is' . ($context['utf8'] ? 'u' : ''), $message['body'], $matches);
  1672. else
  1673. 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]{' . $charLimit . '})/is' . ($context['utf8'] ? 'u' : ''), $message['body'], $matches);
  1674. $message['body'] = '';
  1675. foreach ($matches[0] as $index => $match)
  1676. {
  1677. $match = strtr(htmlspecialchars($match, ENT_QUOTES), array("\n" => '<br />'));
  1678. $message['body'] .= '<strong>...</strong>&nbsp;' . $match . '&nbsp;<strong>...</strong><br />';
  1679. }
  1680. }
  1681. // Re-fix the international characters.
  1682. $message['body'] = preg_replace('~&amp;#(\d{1,7}|x[0-9a-fA-F]{1,6});~e', '$GLOBALS[\'smcFunc\'][\'entity_fix\'](\'\\1\')', $message['body']);
  1683. }
  1684. }
  1685. else
  1686. {
  1687. // Run UBBC interpreter on the message.
  1688. $message['body'] = parse_bbc($message['body'], $message['smileys_enabled'], $message['id_msg']);
  1689. }
  1690. // Sadly, we need to check the icon ain't broke.
  1691. if (empty($modSettings['messageIconChecks_disable']))
  1692. {
  1693. if (!isset($context['icon_sources'][$message['first_icon']]))
  1694. $context['icon_sources'][$message['first_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['first_icon'] . '.gif') ? 'images_url' : 'default_images_url';
  1695. if (!isset($context['icon_sources'][$message['last_icon']]))
  1696. $context['icon_sources'][$message['last_icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['last_icon'] . '.gif') ? 'images_url' : 'default_images_url';
  1697. if (!isset($context['icon_sources'][$message['icon']]))
  1698. $context['icon_sources'][$message['icon']] = file_exists($settings['theme_dir'] . '/images/post/' . $message['icon'] . '.gif') ? 'images_url' : 'default_images_url';
  1699. }
  1700. else
  1701. {
  1702. if (!isset($context['icon_sources'][$message['first_icon']]))
  1703. $context['icon_sources'][$message['first_icon']] = 'images_url';
  1704. if (!isset($context['icon_sources'][$message['last_icon']]))
  1705. $context['icon_sources'][$message['last_icon']] = 'images_url';
  1706. if (!isset($context['icon_sources'][$message['icon']]))
  1707. $context['icon_sources'][$message['icon']] = 'images_url';
  1708. }
  1709. $output = array_merge($context['topics'][$message['id_msg']], array(
  1710. 'is_sticky' => !empty($modSettings['enableStickyTopics']) && !empty($message['is_sticky']),
  1711. 'is_locked' => !empty($message['locked']),
  1712. 'is_poll' => $modSettings['pollMode'] == '1' && $message['id_poll'] > 0,
  1713. 'is_hot' => $message['num_replies'] >= $modSettings['hotTopicPosts'],
  1714. 'is_very_hot' => $message['num_replies'] >= $modSettings['hotTopicVeryPosts'],
  1715. 'posted_in' => !empty($participants[$message['id_topic']]),
  1716. 'views' => $message['num_views'],
  1717. 'replies' => $message['num_replies'],
  1718. 'can_reply' => in_array($message['id_board'], $boards_can['post_reply_any']) || in_array(0, $boards_can['post_reply_any']),
  1719. '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'],
  1720. 'first_post' => array(
  1721. 'id' => $message['first_msg'],
  1722. 'time' => timeformat($message['first_poster_time']),
  1723. 'timestamp' => forum_time(true, $message['first_poster_time']),
  1724. 'subject' => $message['first_subject'],
  1725. 'href' => $scripturl . '?topic=' . $message['id_topic'] . '.0',
  1726. 'link' => '<a href="' . $scripturl . '?topic=' . $message['id_topic'] . '.0">' . $message['first_subject'] . '</a>',
  1727. 'icon' => $message['first_icon'],
  1728. 'icon_url' => $settings[$context['icon_sources'][$message['first_icon']]] . '/post/' . $message['first_icon'] . '.gif',
  1729. 'member' => array(
  1730. 'id' => $message['first_member_id'],
  1731. 'name' => $message['first_member_name'],
  1732. 'href' => !empty($message['first_member_id']) ? $scripturl . '?action=profile;u=' . $message['first_member_id'] : '',
  1733. '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']
  1734. )
  1735. ),
  1736. 'last_post' => array(
  1737. 'id' => $message['last_msg'],
  1738. 'time' => timeformat($message['last_poster_time']),
  1739. 'timestamp' => forum_time(true, $message['last_poster_time']),
  1740. 'subject' => $message['last_subject'],
  1741. 'href' => $scripturl . '?topic=' . $message['id_topic'] . ($message['num_replies'] == 0 ? '.0' : '.msg' . $message['last_msg']) . '#msg' . $message['last_msg'],
  1742. '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>',
  1743. 'icon' => $message['last_icon'],
  1744. 'icon_url' => $settings[$context['icon_sources'][$message['last_icon']]] . '/post/' . $message['last_icon'] . '.gif',
  1745. 'member' => array(
  1746. 'id' => $message['last_member_id'],
  1747. 'name' => $message['last_member_name'],
  1748. 'href' => !empty($message['last_member_id']) ? $scripturl . '?action=profile;u=' . $message['last_member_id'] : '',
  1749. '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']
  1750. )
  1751. ),
  1752. 'board' => array(
  1753. 'id' => $message['id_board'],
  1754. 'name' => $message['board_name'],
  1755. 'href' => $scripturl . '?board=' . $message['id_board'] . '.0',
  1756. 'link' => '<a href="' . $scripturl . '?board=' . $message['id_board'] . '.0">' . $message['board_name'] . '</a>'
  1757. ),
  1758. 'category' => array(
  1759. 'id' => $message['id_cat'],
  1760. 'name' => $message['cat_name'],
  1761. 'href' => $scripturl . '#c' . $message['id_cat'],
  1762. 'link' => '<a href="' . $scripturl . '#c' . $message['id_cat'] . '">' . $message['cat_name'] . '</a>'
  1763. )
  1764. ));
  1765. determineTopicClass($output);
  1766. if ($output['posted_in'])
  1767. $output['class'] = 'my_' . $output['class'];
  1768. $body_highlighted = $message['body'];
  1769. $subject_highlighted = $message['subject'];
  1770. if (!empty($options['display_quick_mod']))
  1771. {
  1772. $started = $output['first_post']['member']['id'] == $user_info['id'];
  1773. $output['quick_mod'] = array(
  1774. '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']))),
  1775. 'sticky' => (in_array(0, $boards_can['make_sticky']) || in_array($output['board']['id'], $boards_can['make_sticky'])) && !empty($modSettings['enableStickyTopics']),
  1776. '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']))),
  1777. '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']))),
  1778. );
  1779. $context['can_lock'] |= $output['quick_mod']['lock'];
  1780. $context['can_sticky'] |= $output['quick_mod']['sticky'];
  1781. $context['can_move'] |= $output['quick_mod']['move'];
  1782. $context['can_remove'] |= $output['quick_mod']['remove'];
  1783. $context['can_merge'] |= in_array($output['board']['id'], $boards_can['merge_any']);
  1784. // If we've found a message we can move, and we don't already have it, load the destinations.
  1785. if ($options['display_quick_mod'] == 1 && !isset($context['move_to_boards']) && $context['can_move'])
  1786. {
  1787. require_once($sourcedir . '/Subs-MessageIndex.php');
  1788. $boardListOptions = array(
  1789. 'use_permissions' => true,
  1790. 'not_redirection' => true,
  1791. 'selected_board' => empty($_SESSION['move_to_topic']) ? null : $_SESSION['move_to_topic'],
  1792. );
  1793. $context['move_to_boards'] = getBoardList($boardListOptions);
  1794. }
  1795. }
  1796. foreach ($context['key_words'] as $query)
  1797. {
  1798. // Fix the international characters in the keyword too.
  1799. $query = strtr($smcFunc['htmlspecialchars']($query), array('\\\'' => '\''));
  1800. $body_highlighted = preg_replace('/((<[^>]*)|' . preg_quote(strtr($query, array('\'' => '&#039;')), '/') . ')/ie' . ($context['utf8'] ? 'u' : ''), "'\$2' == '\$1' ? stripslashes('\$1') : '<strong class=\"highlight\">\$1</strong>'", $body_highlighted);
  1801. $subject_highlighted = preg_replace('/(' . preg_quote($query, '/') . ')/i' . ($context['utf8'] ? 'u' : ''), '<strong class="highlight">$1</strong>', $subject_highlighted);
  1802. }
  1803. $output['matches'][] = array(
  1804. 'id' => $message['id_msg'],
  1805. 'attachment' => loadAttachmentContext($message['id_msg']),
  1806. 'alternate' => $counter % 2,
  1807. 'member' => &$memberContext[$message['id_member']],
  1808. 'icon' => $message['icon'],
  1809. 'icon_url' => $settings[$context['icon_sources'][$message['icon']]] . '/post/' . $message['icon'] . '.gif',
  1810. 'subject' => $message['subject'],
  1811. 'subject_highlighted' => $subject_highlighted,
  1812. 'time' => timeformat($message['poster_time']),
  1813. 'timestamp' => forum_time(true, $message['poster_time']),
  1814. 'counter' => $counter,
  1815. 'modified' => array(
  1816. 'time' => timeformat($message['modified_time']),
  1817. 'timestamp' => forum_time(true, $message['modified_time']),
  1818. 'name' => $message['modified_name']
  1819. ),
  1820. 'body' => $message['body'],
  1821. 'body_highlighted' => $body_highlighted,
  1822. 'start' => 'msg' . $message['id_msg']
  1823. );
  1824. $counter++;
  1825. return $output;
  1826. }
  1827. // This function compares the length of two strings plus a little.
  1828. function searchSort($a, $b)
  1829. {
  1830. global $searchAPI;
  1831. return $searchAPI->searchSort($a, $b);
  1832. }
  1833. ?>