Search.php 88 KB

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