Search.php 88 KB

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