Search.php 86 KB

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