Search.php 87 KB

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