Passed
Push — release-2.1 ( 942d5c...bce556 )
by Mathias
49s
created

highlight()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 9
Code Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 2
eloc 5
c 1
b 0
f 0
nc 2
nop 2
dl 0
loc 9
rs 10
1
<?php
2
3
/**
4
 * Handle all of the searching from here.
5
 *
6
 * Simple Machines Forum (SMF)
7
 *
8
 * @package SMF
9
 * @author Simple Machines http://www.simplemachines.org
10
 * @copyright 2019 Simple Machines and individual contributors
11
 * @license http://www.simplemachines.org/about/smf/license.php BSD
12
 *
13
 * @version 2.1 RC2
14
 */
15
16
if (!defined('SMF'))
17
	die('No direct access...');
18
19
// This defines two version types for checking the API's are compatible with this version of SMF.
20
$GLOBALS['search_versions'] = array(
21
	// @todo Probably unnecessary now that we use a constant instead of global $forum_version
22
	'forum_version' => SMF_FULL_VERSION,
23
	// 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)
24
	'search_version' => strtr('SMF 2+1=Alpha=1', array('+' => '.', '=' => ' ')),
25
);
26
27
/**
28
 * Ask the user what they want to search for.
29
 * What it does:
30
 * - shows the screen to search forum posts (action=search)
31
 * - uses the main sub template of the Search template.
32
 * - uses the Search language file.
33
 * - requires the search_posts permission.
34
 * - decodes and loads search parameters given in the URL (if any).
35
 * - the form redirects to index.php?action=search2.
36
 */
37
function PlushSearch1()
38
{
39
	global $txt, $scripturl, $modSettings, $user_info, $context, $smcFunc, $sourcedir;
40
41
	// Is the load average too high to allow searching just now?
42
	if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
43
		fatal_lang_error('loadavg_search_disabled', false);
44
45
	loadLanguage('Search');
46
	// Don't load this in XML mode.
47
	if (!isset($_REQUEST['xml']))
48
	{
49
		loadTemplate('Search');
50
		loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
51
	}
52
53
	// Check the user's permissions.
54
	isAllowedTo('search_posts');
55
56
	// Link tree....
57
	$context['linktree'][] = array(
58
		'url' => $scripturl . '?action=search',
59
		'name' => $txt['search']
60
	);
61
62
	// This is hard coded maximum string length.
63
	$context['search_string_limit'] = 100;
64
65
	$context['require_verification'] = $user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']);
66
	if ($context['require_verification'])
67
	{
68
		require_once($sourcedir . '/Subs-Editor.php');
69
		$verificationOptions = array(
70
			'id' => 'search',
71
		);
72
		$context['require_verification'] = create_control_verification($verificationOptions);
73
		$context['visual_verification_id'] = $verificationOptions['id'];
74
	}
75
76
	// If you got back from search2 by using the linktree, you get your original search parameters back.
77
	if (isset($_REQUEST['params']))
78
	{
79
		// Due to IE's 2083 character limit, we have to compress long search strings
80
		$temp_params = base64_decode(str_replace(array('-', '_', '.'), array('+', '/', '='), $_REQUEST['params']));
81
		// Test for gzuncompress failing
82
		$temp_params2 = @gzuncompress($temp_params);
83
		$temp_params = explode('|"|', !empty($temp_params2) ? $temp_params2 : $temp_params);
84
85
		$context['search_params'] = array();
86
		foreach ($temp_params as $i => $data)
87
		{
88
			@list ($k, $v) = explode('|\'|', $data);
89
			$context['search_params'][$k] = $v;
90
		}
91
		if (isset($context['search_params']['brd']))
92
			$context['search_params']['brd'] = $context['search_params']['brd'] == '' ? array() : explode(',', $context['search_params']['brd']);
93
	}
94
95
	if (isset($_REQUEST['search']))
96
		$context['search_params']['search'] = un_htmlspecialchars($_REQUEST['search']);
97
98
	if (isset($context['search_params']['search']))
99
		$context['search_params']['search'] = $smcFunc['htmlspecialchars']($context['search_params']['search']);
100
	if (isset($context['search_params']['userspec']))
101
		$context['search_params']['userspec'] = $smcFunc['htmlspecialchars']($context['search_params']['userspec']);
102
	if (!empty($context['search_params']['searchtype']))
103
		$context['search_params']['searchtype'] = 2;
104
	if (!empty($context['search_params']['minage']))
105
		$context['search_params']['minage'] = (int) $context['search_params']['minage'];
106
	if (!empty($context['search_params']['maxage']))
107
		$context['search_params']['maxage'] = (int) $context['search_params']['maxage'];
108
109
	$context['search_params']['show_complete'] = !empty($context['search_params']['show_complete']);
110
	$context['search_params']['subject_only'] = !empty($context['search_params']['subject_only']);
111
112
	// Load the error text strings if there were errors in the search.
113
	if (!empty($context['search_errors']))
114
	{
115
		loadLanguage('Errors');
116
		$context['search_errors']['messages'] = array();
117
		foreach ($context['search_errors'] as $search_error => $dummy)
118
		{
119
			if ($search_error === 'messages')
120
				continue;
121
122
			if ($search_error == 'string_too_long')
123
				$txt['error_string_too_long'] = sprintf($txt['error_string_too_long'], $context['search_string_limit']);
124
125
			$context['search_errors']['messages'][] = $txt['error_' . $search_error];
126
		}
127
	}
128
129
	// Find all the boards this user is allowed to see.
130
	$request = $smcFunc['db_query']('order_by_board_order', '
131
		SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
132
		FROM {db_prefix}boards AS b
133
			LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
134
		WHERE {query_see_board}
135
			AND redirect = {string:empty_string}',
136
		array(
137
			'empty_string' => '',
138
		)
139
	);
140
	$context['num_boards'] = $smcFunc['db_num_rows']($request);
141
	$context['boards_check_all'] = true;
142
	$context['categories'] = array();
143
	while ($row = $smcFunc['db_fetch_assoc']($request))
144
	{
145
		// This category hasn't been set up yet..
146
		if (!isset($context['categories'][$row['id_cat']]))
147
			$context['categories'][$row['id_cat']] = array(
148
				'id' => $row['id_cat'],
149
				'name' => $row['cat_name'],
150
				'boards' => array()
151
			);
152
153
		// Set this board up, and let the template know when it's a child.  (indent them..)
154
		$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
155
			'id' => $row['id_board'],
156
			'name' => $row['name'],
157
			'child_level' => $row['child_level'],
158
			'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']))
159
		);
160
161
		// If a board wasn't checked that probably should have been ensure the board selection is selected, yo!
162
		if (!$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] && (empty($modSettings['recycle_enable']) || $row['id_board'] != $modSettings['recycle_board']))
163
			$context['boards_check_all'] = false;
164
	}
165
	$smcFunc['db_free_result']($request);
166
167
	require_once($sourcedir . '/Subs-Boards.php');
168
	sortCategories($context['categories']);
169
170
	// Now, let's sort the list of categories into the boards for templates that like that.
171
	$temp_boards = array();
172
	foreach ($context['categories'] as $category)
173
	{
174
		$temp_boards[] = array(
175
			'name' => $category['name'],
176
			'child_ids' => array_keys($category['boards'])
177
		);
178
		$temp_boards = array_merge($temp_boards, array_values($category['boards']));
179
180
		// Include a list of boards per category for easy toggling.
181
		$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
182
	}
183
184
	$max_boards = ceil(count($temp_boards) / 2);
185
	if ($max_boards == 1)
186
		$max_boards = 2;
187
188
	// Now, alternate them so they can be shown left and right ;).
189
	$context['board_columns'] = array();
190
	for ($i = 0; $i < $max_boards; $i++)
191
	{
192
		$context['board_columns'][] = $temp_boards[$i];
193
		if (isset($temp_boards[$i + $max_boards]))
194
			$context['board_columns'][] = $temp_boards[$i + $max_boards];
195
		else
196
			$context['board_columns'][] = array();
197
	}
198
199
	if (!empty($_REQUEST['topic']))
200
	{
201
		$context['search_params']['topic'] = (int) $_REQUEST['topic'];
202
		$context['search_params']['show_complete'] = true;
203
	}
204
	if (!empty($context['search_params']['topic']))
205
	{
206
		$context['search_params']['topic'] = (int) $context['search_params']['topic'];
207
208
		$context['search_topic'] = array(
209
			'id' => $context['search_params']['topic'],
210
			'href' => $scripturl . '?topic=' . $context['search_params']['topic'] . '.0',
211
		);
212
213
		$request = $smcFunc['db_query']('', '
214
			SELECT ms.subject
215
			FROM {db_prefix}topics AS t
216
				INNER JOIN {db_prefix}messages AS ms ON (ms.id_msg = t.id_first_msg)
217
			WHERE t.id_topic = {int:search_topic_id}
218
				AND {query_see_message_board} ' . ($modSettings['postmod_active'] ? '
219
				AND t.approved = {int:is_approved_true}' : '') . '
220
			LIMIT 1',
221
			array(
222
				'is_approved_true' => 1,
223
				'search_topic_id' => $context['search_params']['topic'],
224
			)
225
		);
226
227
		if ($smcFunc['db_num_rows']($request) == 0)
228
			fatal_lang_error('topic_gone', false);
229
230
		list ($context['search_topic']['subject']) = $smcFunc['db_fetch_row']($request);
231
		$smcFunc['db_free_result']($request);
232
233
		$context['search_topic']['link'] = '<a href="' . $context['search_topic']['href'] . '">' . $context['search_topic']['subject'] . '</a>';
234
	}
235
236
	$context['page_title'] = $txt['set_parameters'];
237
238
	call_integration_hook('integrate_search');
239
}
240
241
/**
242
 * Gather the results and show them.
243
 * What it does:
244
 * - checks user input and searches the messages table for messages matching the query.
245
 * - requires the search_posts permission.
246
 * - uses the results sub template of the Search template.
247
 * - uses the Search language file.
248
 * - stores the results into the search cache.
249
 * - show the results of the search query.
250
 */
251
function PlushSearch2()
252
{
253
	global $scripturl, $modSettings, $sourcedir, $txt;
254
	global $user_info, $context, $options, $messages_request, $boards_can;
255
	global $excludedWords, $participants, $smcFunc;
256
257
	// if comming from the quick search box, and we want to search on members, well we need to do that ;)
258
	if (isset($_REQUEST['search_selection']) && $_REQUEST['search_selection'] === 'members')
259
		redirectexit($scripturl . '?action=mlist;sa=search;fields=name,email;search=' . urlencode($_REQUEST['search']));
260
261
	if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
262
		fatal_lang_error('loadavg_search_disabled', false);
263
264
	// No, no, no... this is a bit hard on the server, so don't you go prefetching it!
265
	if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
266
	{
267
		ob_end_clean();
268
		send_http_status(403);
269
		die;
0 ignored issues
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

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