Search.php 88 KB

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