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