Search.php 88 KB

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