Search.php 87 KB

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