Search.php 87 KB

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