Search.php 87 KB

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