Search.php 86 KB

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