Search.php 88 KB

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