-
Notifications
You must be signed in to change notification settings - Fork 255
/
Copy pathSearch.php
2387 lines (2057 loc) · 89.6 KB
/
Search.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Handle all of the searching from here.
*
* Simple Machines Forum (SMF)
*
* @package SMF
* @author Simple Machines https://www.simplemachines.org
* @copyright 2023 Simple Machines and individual contributors
* @license https://www.simplemachines.org/about/smf/license.php BSD
*
* @version 2.1.4
*/
if (!defined('SMF'))
die('No direct access...');
/**
* Ask the user what they want to search for.
* What it does:
* - shows the screen to search forum posts (action=search)
* - uses the main sub template of the Search template.
* - uses the Search language file.
* - requires the search_posts permission.
* - decodes and loads search parameters given in the URL (if any).
* - the form redirects to index.php?action=search2.
*/
function PlushSearch1()
{
global $txt, $scripturl, $modSettings, $user_info, $context, $smcFunc, $sourcedir;
// Is the load average too high to allow searching just now?
if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
fatal_lang_error('loadavg_search_disabled', false);
loadLanguage('Search');
// Don't load this in XML mode.
if (!isset($_REQUEST['xml']))
{
loadTemplate('Search');
loadJavaScriptFile('suggest.js', array('defer' => false, 'minimize' => true), 'smf_suggest');
}
// Check the user's permissions.
isAllowedTo('search_posts');
// Link tree....
$context['linktree'][] = array(
'url' => $scripturl . '?action=search',
'name' => $txt['search']
);
// This is hard coded maximum string length.
$context['search_string_limit'] = 100;
$context['require_verification'] = $user_info['is_guest'] && !empty($modSettings['search_enable_captcha']) && empty($_SESSION['ss_vv_passed']);
if ($context['require_verification'])
{
require_once($sourcedir . '/Subs-Editor.php');
$verificationOptions = array(
'id' => 'search',
);
$context['require_verification'] = create_control_verification($verificationOptions);
$context['visual_verification_id'] = $verificationOptions['id'];
}
// If you got back from search2 by using the linktree, you get your original search parameters back.
if (isset($_REQUEST['params']))
{
// Due to IE's 2083 character limit, we have to compress long search strings
$temp_params = base64_decode(str_replace(array('-', '_', '.'), array('+', '/', '='), $_REQUEST['params']));
// Test for gzuncompress failing
$temp_params2 = @gzuncompress($temp_params);
$temp_params = explode('|"|', !empty($temp_params2) ? $temp_params2 : $temp_params);
$context['search_params'] = array();
foreach ($temp_params as $i => $data)
{
@list ($k, $v) = explode('|\'|', $data);
$context['search_params'][$k] = $v;
}
if (isset($context['search_params']['brd']))
$context['search_params']['brd'] = $context['search_params']['brd'] == '' ? array() : explode(',', $context['search_params']['brd']);
}
if (isset($_REQUEST['search']))
$context['search_params']['search'] = un_htmlspecialchars($_REQUEST['search']);
if (isset($context['search_params']['search']))
$context['search_params']['search'] = $smcFunc['htmlspecialchars']($context['search_params']['search']);
if (isset($context['search_params']['userspec']))
$context['search_params']['userspec'] = $smcFunc['htmlspecialchars']($context['search_params']['userspec']);
if (!empty($context['search_params']['searchtype']))
$context['search_params']['searchtype'] = 2;
if (!empty($context['search_params']['minage']))
$context['search_params']['minage'] = (int) $context['search_params']['minage'];
if (!empty($context['search_params']['maxage']))
$context['search_params']['maxage'] = (int) $context['search_params']['maxage'];
$context['search_params']['show_complete'] = !empty($context['search_params']['show_complete']);
$context['search_params']['subject_only'] = !empty($context['search_params']['subject_only']);
// Load the error text strings if there were errors in the search.
if (!empty($context['search_errors']))
{
loadLanguage('Errors');
$context['search_errors']['messages'] = array();
foreach ($context['search_errors'] as $search_error => $dummy)
{
if ($search_error === 'messages')
continue;
if ($search_error == 'string_too_long')
$txt['error_string_too_long'] = sprintf($txt['error_string_too_long'], $context['search_string_limit']);
$context['search_errors']['messages'][] = $txt['error_' . $search_error];
}
}
// Find all the boards this user is allowed to see.
$request = $smcFunc['db_query']('order_by_board_order', '
SELECT b.id_cat, c.name AS cat_name, b.id_board, b.name, b.child_level
FROM {db_prefix}boards AS b
LEFT JOIN {db_prefix}categories AS c ON (c.id_cat = b.id_cat)
WHERE {query_see_board}
AND redirect = {string:empty_string}',
array(
'empty_string' => '',
)
);
$context['num_boards'] = $smcFunc['db_num_rows']($request);
$context['boards_check_all'] = true;
$context['categories'] = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
{
// This category hasn't been set up yet..
if (!isset($context['categories'][$row['id_cat']]))
$context['categories'][$row['id_cat']] = array(
'id' => $row['id_cat'],
'name' => $row['cat_name'],
'boards' => array()
);
// Set this board up, and let the template know when it's a child. (indent them..)
$context['categories'][$row['id_cat']]['boards'][$row['id_board']] = array(
'id' => $row['id_board'],
'name' => $row['name'],
'child_level' => $row['child_level'],
'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']))
);
// If a board wasn't checked that probably should have been ensure the board selection is selected, yo!
if (!$context['categories'][$row['id_cat']]['boards'][$row['id_board']]['selected'] && (empty($modSettings['recycle_enable']) || $row['id_board'] != $modSettings['recycle_board']))
$context['boards_check_all'] = false;
}
$smcFunc['db_free_result']($request);
require_once($sourcedir . '/Subs-Boards.php');
sortCategories($context['categories']);
// Now, let's sort the list of categories into the boards for templates that like that.
$temp_boards = array();
foreach ($context['categories'] as $category)
{
$temp_boards[] = array(
'name' => $category['name'],
'child_ids' => array_keys($category['boards'])
);
$temp_boards = array_merge($temp_boards, array_values($category['boards']));
// Include a list of boards per category for easy toggling.
$context['categories'][$category['id']]['child_ids'] = array_keys($category['boards']);
}
$max_boards = ceil(count($temp_boards) / 2);
if ($max_boards == 1)
$max_boards = 2;
// Now, alternate them so they can be shown left and right ;).
$context['board_columns'] = array();
for ($i = 0; $i < $max_boards; $i++)
{
$context['board_columns'][] = $temp_boards[$i];
if (isset($temp_boards[$i + $max_boards]))
$context['board_columns'][] = $temp_boards[$i + $max_boards];
else
$context['board_columns'][] = array();
}
if (!empty($_REQUEST['topic']))
{
$context['search_params']['topic'] = (int) $_REQUEST['topic'];
$context['search_params']['show_complete'] = true;
}
if (!empty($context['search_params']['topic']))
{
$context['search_params']['topic'] = (int) $context['search_params']['topic'];
$context['search_topic'] = array(
'id' => $context['search_params']['topic'],
'href' => $scripturl . '?topic=' . $context['search_params']['topic'] . '.0',
);
$request = $smcFunc['db_query']('', '
SELECT subject
FROM {db_prefix}topics AS t
INNER JOIN {db_prefix}messages AS m ON (m.id_msg = t.id_first_msg)
WHERE t.id_topic = {int:search_topic_id}
AND {query_see_message_board} ' . ($modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved_true}' : '') . '
LIMIT 1',
array(
'is_approved_true' => 1,
'search_topic_id' => $context['search_params']['topic'],
)
);
if ($smcFunc['db_num_rows']($request) == 0)
fatal_lang_error('topic_gone', false);
list ($context['search_topic']['subject']) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
$context['search_topic']['link'] = '<a href="' . $context['search_topic']['href'] . '">' . $context['search_topic']['subject'] . '</a>';
}
$context['page_title'] = $txt['set_parameters'];
call_integration_hook('integrate_search');
}
/**
* Gather the results and show them.
* What it does:
* - checks user input and searches the messages table for messages matching the query.
* - requires the search_posts permission.
* - uses the results sub template of the Search template.
* - uses the Search language file.
* - stores the results into the search cache.
* - show the results of the search query.
*/
function PlushSearch2()
{
global $scripturl, $modSettings, $sourcedir, $txt;
global $user_info, $context, $options, $messages_request, $boards_can;
global $excludedWords, $participants, $smcFunc, $cache_enable;
// if comming from the quick search box, and we want to search on members, well we need to do that ;)
if (isset($_REQUEST['search_selection']) && $_REQUEST['search_selection'] === 'members')
redirectexit($scripturl . '?action=mlist;sa=search;fields=name,email;search=' . urlencode($_REQUEST['search']));
if (!empty($context['load_average']) && !empty($modSettings['loadavg_search']) && $context['load_average'] >= $modSettings['loadavg_search'])
fatal_lang_error('loadavg_search_disabled', false);
// No, no, no... this is a bit hard on the server, so don't you go prefetching it!
if (isset($_SERVER['HTTP_X_MOZ']) && $_SERVER['HTTP_X_MOZ'] == 'prefetch')
{
ob_end_clean();
send_http_status(403);
die;
}
if (isset($_REQUEST['start']))
$_REQUEST['start'] = (int) $_REQUEST['start'];
$weight_factors = array(
'frequency' => array(
'search' => 'COUNT(*) / (MAX(t.num_replies) + 1)',
'results' => '(t.num_replies + 1)',
),
'age' => array(
'search' => 'CASE WHEN MAX(m.id_msg) < {int:min_msg} THEN 0 ELSE (MAX(m.id_msg) - {int:min_msg}) / {int:recent_message} END',
'results' => 'CASE WHEN t.id_first_msg < {int:min_msg} THEN 0 ELSE (t.id_first_msg - {int:min_msg}) / {int:recent_message} END',
),
'length' => array(
'search' => 'CASE WHEN MAX(t.num_replies) < {int:huge_topic_posts} THEN MAX(t.num_replies) / {int:huge_topic_posts} ELSE 1 END',
'results' => 'CASE WHEN t.num_replies < {int:huge_topic_posts} THEN t.num_replies / {int:huge_topic_posts} ELSE 1 END',
),
'subject' => array(
'search' => 0,
'results' => 0,
),
'first_message' => array(
'search' => 'CASE WHEN MIN(m.id_msg) = MAX(t.id_first_msg) THEN 1 ELSE 0 END',
),
'sticky' => array(
'search' => 'MAX(t.is_sticky)',
'results' => 't.is_sticky',
),
);
call_integration_hook('integrate_search_weights', array(&$weight_factors));
$weight = array();
$weight_total = 0;
foreach ($weight_factors as $weight_factor => $value)
{
$weight[$weight_factor] = empty($modSettings['search_weight_' . $weight_factor]) ? 0 : (int) $modSettings['search_weight_' . $weight_factor];
$weight_total += $weight[$weight_factor];
}
// Zero weight. Weightless :P.
if (empty($weight_total))
fatal_lang_error('search_invalid_weights');
// These vars don't require an interface, they're just here for tweaking.
$recentPercentage = 0.30;
$humungousTopicPosts = 200;
$maxMembersToSearch = 500;
$maxMessageResults = empty($modSettings['search_max_results']) ? 0 : $modSettings['search_max_results'] * 5;
// Start with no errors.
$context['search_errors'] = array();
// Number of pages hard maximum - normally not set at all.
$modSettings['search_max_results'] = empty($modSettings['search_max_results']) ? 200 * $modSettings['search_results_per_page'] : (int) $modSettings['search_max_results'];
// Maximum length of the string.
$context['search_string_limit'] = 100;
loadLanguage('Search');
if (!isset($_REQUEST['xml']))
loadTemplate('Search');
//If we're doing XML we need to use the results template regardless really.
else
$context['sub_template'] = 'results';
// Are you allowed?
isAllowedTo('search_posts');
require_once($sourcedir . '/Display.php');
require_once($sourcedir . '/Subs-Package.php');
// Search has a special database set.
db_extend('search');
// Load up the search API we are going to use.
$searchAPI = findSearchAPI();
// $search_params will carry all settings that differ from the default search parameters.
// That way, the URLs involved in a search page will be kept as short as possible.
$search_params = array();
if (isset($_REQUEST['params']))
{
// Due to IE's 2083 character limit, we have to compress long search strings
$temp_params = base64_decode(str_replace(array('-', '_', '.'), array('+', '/', '='), $_REQUEST['params']));
// Test for gzuncompress failing
$temp_params2 = @gzuncompress($temp_params);
$temp_params = explode('|"|', (!empty($temp_params2) ? $temp_params2 : $temp_params));
foreach ($temp_params as $i => $data)
{
@list($k, $v) = explode('|\'|', $data);
$search_params[$k] = $v;
}
if (isset($search_params['brd']))
$search_params['brd'] = empty($search_params['brd']) ? array() : explode(',', $search_params['brd']);
}
// Store whether simple search was used (needed if the user wants to do another query).
if (!isset($search_params['advanced']))
$search_params['advanced'] = empty($_REQUEST['advanced']) ? 0 : 1;
// 1 => 'allwords' (default, don't set as param) / 2 => 'anywords'.
if (!empty($search_params['searchtype']) || (!empty($_REQUEST['searchtype']) && $_REQUEST['searchtype'] == 2))
$search_params['searchtype'] = 2;
// Minimum age of messages. Default to zero (don't set param in that case).
if (!empty($search_params['minage']) || (!empty($_REQUEST['minage']) && $_REQUEST['minage'] > 0))
$search_params['minage'] = !empty($search_params['minage']) ? (int) $search_params['minage'] : (int) $_REQUEST['minage'];
// Maximum age of messages. Default to infinite (9999 days: param not set).
if (!empty($search_params['maxage']) || (!empty($_REQUEST['maxage']) && $_REQUEST['maxage'] < 9999))
$search_params['maxage'] = !empty($search_params['maxage']) ? (int) $search_params['maxage'] : (int) $_REQUEST['maxage'];
// Searching a specific topic?
if (!empty($_REQUEST['topic']) || (!empty($_REQUEST['search_selection']) && $_REQUEST['search_selection'] == 'topic'))
{
$search_params['topic'] = empty($_REQUEST['search_selection']) ? (int) $_REQUEST['topic'] : (isset($_REQUEST['sd_topic']) ? (int) $_REQUEST['sd_topic'] : '');
$search_params['show_complete'] = true;
}
elseif (!empty($search_params['topic']))
$search_params['topic'] = (int) $search_params['topic'];
if (!empty($search_params['minage']) || !empty($search_params['maxage']))
{
$request = $smcFunc['db_query']('', '
SELECT ' . (empty($search_params['maxage']) ? '0, ' : 'COALESCE(MIN(id_msg), -1), ') . (empty($search_params['minage']) ? '0' : 'COALESCE(MAX(id_msg), -1)') . '
FROM {db_prefix}messages
WHERE 1=1' . ($modSettings['postmod_active'] ? '
AND approved = {int:is_approved_true}' : '') . (empty($search_params['minage']) ? '' : '
AND poster_time <= {int:timestamp_minimum_age}') . (empty($search_params['maxage']) ? '' : '
AND poster_time >= {int:timestamp_maximum_age}'),
array(
'timestamp_minimum_age' => empty($search_params['minage']) ? 0 : time() - 86400 * $search_params['minage'],
'timestamp_maximum_age' => empty($search_params['maxage']) ? 0 : time() - 86400 * $search_params['maxage'],
'is_approved_true' => 1,
)
);
list ($minMsgID, $maxMsgID) = $smcFunc['db_fetch_row']($request);
if ($minMsgID < 0 || $maxMsgID < 0)
$context['search_errors']['no_messages_in_time_frame'] = true;
$smcFunc['db_free_result']($request);
}
// Default the user name to a wildcard matching every user (*).
if (!empty($search_params['userspec']) || (!empty($_REQUEST['userspec']) && $_REQUEST['userspec'] != '*'))
$search_params['userspec'] = isset($search_params['userspec']) ? $search_params['userspec'] : $_REQUEST['userspec'];
// If there's no specific user, then don't mention it in the main query.
if (empty($search_params['userspec']))
$userQuery = '';
else
{
$userString = strtr($smcFunc['htmlspecialchars']($search_params['userspec'], ENT_QUOTES), array('"' => '"', '%' => '\%', '_' => '\_', '*' => '%', '?' => '_'));
preg_match_all('~"([^"]+)"~', $userString, $matches);
$possible_users = array_merge($matches[1], explode(',', preg_replace('~"[^"]+"~', '', $userString)));
for ($k = 0, $n = count($possible_users); $k < $n; $k++)
{
$possible_users[$k] = trim($possible_users[$k]);
if (strlen($possible_users[$k]) == 0)
unset($possible_users[$k]);
}
if (empty($possible_users))
{
$userQuery = '';
}
else
{
// Create a list of database-escaped search names.
$realNameMatches = array();
foreach ($possible_users as $possible_user)
$realNameMatches[] = $smcFunc['db_quote'](
'{string:possible_user}',
array(
'possible_user' => $possible_user
)
);
// Retrieve a list of possible members.
$request = $smcFunc['db_query']('', '
SELECT id_member
FROM {db_prefix}members
WHERE {raw:match_possible_users}',
array(
'match_possible_users' => 'real_name LIKE ' . implode(' OR real_name LIKE ', $realNameMatches),
)
);
// Simply do nothing if there're too many members matching the criteria.
if ($smcFunc['db_num_rows']($request) > $maxMembersToSearch)
{
$userQuery = '';
}
elseif ($smcFunc['db_num_rows']($request) == 0)
{
$userQuery = $smcFunc['db_quote'](
'm.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})',
array(
'id_member_guest' => 0,
'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches),
)
);
}
else
{
$memberlist = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
$memberlist[] = $row['id_member'];
$userQuery = $smcFunc['db_quote'](
'(m.id_member IN ({array_int:matched_members}) OR (m.id_member = {int:id_member_guest} AND ({raw:match_possible_guest_names})))',
array(
'matched_members' => $memberlist,
'id_member_guest' => 0,
'match_possible_guest_names' => 'm.poster_name LIKE ' . implode(' OR m.poster_name LIKE ', $realNameMatches),
)
);
}
$smcFunc['db_free_result']($request);
}
}
// If the boards were passed by URL (params=), temporarily put them back in $_REQUEST.
if (!empty($search_params['brd']) && is_array($search_params['brd']))
$_REQUEST['brd'] = $search_params['brd'];
// Ensure that brd is an array.
if ((!empty($_REQUEST['brd']) && !is_array($_REQUEST['brd'])) || (!empty($_REQUEST['search_selection']) && $_REQUEST['search_selection'] == 'board'))
{
if (!empty($_REQUEST['brd']))
{
$_REQUEST['brd'] = strpos($_REQUEST['brd'], ',') !== false ? explode(',', $_REQUEST['brd']) : array($_REQUEST['brd']);
}
else
$_REQUEST['brd'] = isset($_REQUEST['sd_brd']) ? array($_REQUEST['sd_brd']) : array();
}
// Make sure all boards are integers.
if (!empty($_REQUEST['brd']))
{
foreach ($_REQUEST['brd'] as $id => $brd)
$_REQUEST['brd'][$id] = (int) $brd;
}
// Special case for boards: searching just one topic?
if (!empty($search_params['topic']))
{
$request = $smcFunc['db_query']('', '
SELECT t.id_board
FROM {db_prefix}topics AS t
WHERE t.id_topic = {int:search_topic_id}
AND {query_see_topic_board}' . ($modSettings['postmod_active'] ? '
AND t.approved = {int:is_approved_true}' : '') . '
LIMIT 1',
array(
'search_topic_id' => $search_params['topic'],
'is_approved_true' => 1,
)
);
if ($smcFunc['db_num_rows']($request) == 0)
fatal_lang_error('topic_gone', false);
$search_params['brd'] = array();
list ($search_params['brd'][0]) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
}
// Select all boards you've selected AND are allowed to see.
elseif ($user_info['is_admin'] && (!empty($search_params['advanced']) || !empty($_REQUEST['brd'])))
{
$search_params['brd'] = empty($_REQUEST['brd']) ? array() : $_REQUEST['brd'];
}
else
{
$see_board = empty($search_params['advanced']) ? 'query_wanna_see_board' : 'query_see_board';
$request = $smcFunc['db_query']('', '
SELECT b.id_board
FROM {db_prefix}boards AS b
WHERE {raw:boards_allowed_to_see}
AND redirect = {string:empty_string}' . (empty($_REQUEST['brd']) ? (!empty($modSettings['recycle_enable']) && $modSettings['recycle_board'] > 0 ? '
AND b.id_board != {int:recycle_board_id}' : '') : '
AND b.id_board IN ({array_int:selected_search_boards})'),
array(
'boards_allowed_to_see' => $user_info[$see_board],
'empty_string' => '',
'selected_search_boards' => empty($_REQUEST['brd']) ? array() : $_REQUEST['brd'],
'recycle_board_id' => $modSettings['recycle_board'],
)
);
$search_params['brd'] = array();
while ($row = $smcFunc['db_fetch_assoc']($request))
$search_params['brd'][] = $row['id_board'];
$smcFunc['db_free_result']($request);
// This error should pro'bly only happen for hackers.
if (empty($search_params['brd']))
$context['search_errors']['no_boards_selected'] = true;
}
if (count($search_params['brd']) != 0)
{
foreach ($search_params['brd'] as $k => $v)
$search_params['brd'][$k] = (int) $v;
// If we've selected all boards, this parameter can be left empty.
$request = $smcFunc['db_query']('', '
SELECT COUNT(*)
FROM {db_prefix}boards
WHERE redirect = {string:empty_string}',
array(
'empty_string' => '',
)
);
list ($num_boards) = $smcFunc['db_fetch_row']($request);
$smcFunc['db_free_result']($request);
if (count($search_params['brd']) == $num_boards)
{
$boardQuery = '';
}
elseif (count($search_params['brd']) == $num_boards - 1 && !empty($modSettings['recycle_board']) && !in_array($modSettings['recycle_board'], $search_params['brd']))
{
$boardQuery = '!= ' . $modSettings['recycle_board'];
}
else
$boardQuery = 'IN (' . implode(', ', $search_params['brd']) . ')';
}
else
$boardQuery = '';
$search_params['show_complete'] = !empty($search_params['show_complete']) || !empty($_REQUEST['show_complete']);
$search_params['subject_only'] = !empty($search_params['subject_only']) || !empty($_REQUEST['subject_only']);
$context['compact'] = !$search_params['show_complete'];
// Get the sorting parameters right. Default to sort by relevance descending.
$sort_columns = array(
'relevance',
'num_replies',
'id_msg',
);
call_integration_hook('integrate_search_sort_columns', array(&$sort_columns));
if (empty($search_params['sort']) && !empty($_REQUEST['sort']))
{
list ($search_params['sort'], $search_params['sort_dir']) = array_pad(explode('|', $_REQUEST['sort']), 2, '');
}
$search_params['sort'] = !empty($search_params['sort']) && in_array($search_params['sort'], $sort_columns) ? $search_params['sort'] : 'relevance';
if (!empty($search_params['topic']) && $search_params['sort'] === 'num_replies')
$search_params['sort'] = 'id_msg';
// Sorting direction: descending unless stated otherwise.
$search_params['sort_dir'] = !empty($search_params['sort_dir']) && $search_params['sort_dir'] == 'asc' ? 'asc' : 'desc';
// Remember current sort type and sort direction
$context['current_sorting'] = $search_params['sort'] . '|' . $search_params['sort_dir'];
// Determine some values needed to calculate the relevance.
$minMsg = (int) ((1 - $recentPercentage) * $modSettings['maxMsgID']);
$recentMsg = $modSettings['maxMsgID'] - $minMsg;
// *** Parse the search query
call_integration_hook('integrate_search_params', array(&$search_params));
/*
* Unfortunately, searching for words like this is going to be slow, so we're blacklisting them.
*
* @todo Setting to add more here?
* @todo Maybe only blacklist if they are the only word, or "any" is used?
*/
$blacklisted_words = array('img', 'url', 'quote', 'www', 'http', 'the', 'is', 'it', 'are', 'if');
call_integration_hook('integrate_search_blacklisted_words', array(&$blacklisted_words));
// What are we searching for?
if (empty($search_params['search']))
{
if (isset($_GET['search']))
$search_params['search'] = un_htmlspecialchars($_GET['search']);
elseif (isset($_POST['search']))
$search_params['search'] = $_POST['search'];
else
$search_params['search'] = '';
}
// Nothing??
if (!isset($search_params['search']) || $search_params['search'] == '')
{
$context['search_errors']['invalid_search_string'] = true;
}
// Too long?
elseif ($smcFunc['strlen']($search_params['search']) > $context['search_string_limit'])
{
$context['search_errors']['string_too_long'] = true;
}
// Change non-word characters into spaces.
$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']);
// Make the query lower case. It's gonna be case insensitive anyway.
$stripped_query = un_htmlspecialchars($smcFunc['strtolower']($stripped_query));
// This (hidden) setting will do fulltext searching in the most basic way.
if (!empty($modSettings['search_simple_fulltext']))
$stripped_query = strtr($stripped_query, array('"' => ''));
$no_regexp = preg_match('~&#(?:\d{1,7}|x[0-9a-fA-F]{1,6});~', $stripped_query) === 1;
$is_search_regex = !empty($modSettings['search_match_words']) && !$no_regexp;
// Specify the function to search with. Regex is for word boundaries.
$query_match_type = $is_search_regex ? 'RLIKE' : 'LIKE';
$word_boundary_wrapper = function(string $str) use ($smcFunc): string
{
return sprintf($smcFunc['db_supports_pcre'] ? '\\b%s\\b' : '[[:<:]]%s[[:>:]]', $str);
};
$escape_sql_regex = function(string $str): string
{
return addcslashes(preg_replace('/[\[\]$.+*?&^|{}()]/', '[$0]', $str), '\\\'');
};
// Extract phrase parts first (e.g. some words "this is a phrase" some more words.)
preg_match_all('/(?:^|\s)([-]?)"([^"]+)"(?:$|\s)/', $stripped_query, $matches, PREG_PATTERN_ORDER);
$phraseArray = $matches[2];
// Remove the phrase parts and extract the words.
$wordArray = preg_replace('~(?:^|\s)[-]?"[^"]+"(?:$|\s)~' . ($context['utf8'] ? 'u' : ''), ' ', $search_params['search']);
$wordArray = explode(' ', $smcFunc['htmlspecialchars'](un_htmlspecialchars($wordArray), ENT_QUOTES));
// A minus sign in front of a word excludes the word.... so...
$excludedWords = array();
$excludedIndexWords = array();
$excludedSubjectWords = array();
$excludedPhrases = array();
// .. first, we check for things like -"some words", but not "-some words".
foreach ($matches[1] as $index => $word)
{
if ($word === '-')
{
if (($word = trim($phraseArray[$index], '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
$excludedWords[] = $word;
unset($phraseArray[$index]);
}
}
// Now we look for -test, etc.... normaller.
foreach ($wordArray as $index => $word)
{
if (strpos(trim($word), '-') === 0)
{
if (($word = trim($word, '-_\' ')) !== '' && !in_array($word, $blacklisted_words))
$excludedWords[] = $word;
unset($wordArray[$index]);
}
}
// The remaining words and phrases are all included.
$searchArray = array_merge($phraseArray, $wordArray);
$context['search_ignored'] = array();
// Trim everything and make sure there are no words that are the same.
foreach ($searchArray as $index => $value)
{
// Skip anything practically empty.
if (($searchArray[$index] = trim($value, '-_\' ')) === '')
{
unset($searchArray[$index]);
}
// Skip blacklisted words. Make sure to note we skipped them in case we end up with nothing.
elseif (in_array($searchArray[$index], $blacklisted_words))
{
$foundBlackListedWords = true;
unset($searchArray[$index]);
}
// Don't allow very, very short words.
elseif ($smcFunc['strlen']($value) < 2)
{
$context['search_ignored'][] = $value;
unset($searchArray[$index]);
}
}
$searchArray = array_slice(array_unique($searchArray), 0, 10);
// Create an array of replacements for highlighting.
$context['mark'] = array();
foreach ($searchArray as $word)
$context['mark'][$word] = '<strong class="highlight">' . $word . '</strong>';
// Initialize two arrays storing the words that have to be searched for.
$orParts = array();
$searchWords = array();
// Make sure at least one word is being searched for.
if (empty($searchArray))
{
$context['search_errors']['invalid_search_string' . (!empty($foundBlackListedWords) ? '_blacklist' : '')] = true;
}
// All words/sentences must match.
elseif (empty($search_params['searchtype']))
{
$orParts[0] = $searchArray;
}
// Any word/sentence must match.
else
{
foreach ($searchArray as $index => $value)
$orParts[$index] = array($value);
}
// Don't allow duplicate error messages if one string is too short.
if (isset($context['search_errors']['search_string_small_words'], $context['search_errors']['invalid_search_string']))
unset($context['search_errors']['invalid_search_string']);
// Make sure the excluded words are in all or-branches.
foreach ($orParts as $orIndex => $andParts)
foreach ($excludedWords as $word)
$orParts[$orIndex][] = $word;
// Determine the or-branches and the fulltext search words.
foreach ($orParts as $orIndex => $andParts)
{
$searchWords[$orIndex] = array(
'indexed_words' => array(),
'words' => array(),
'subject_words' => array(),
'all_words' => array(),
'complex_words' => array(),
);
// Sort the indexed words (large words -> small words -> excluded words).
if ($searchAPI->supportsMethod('searchSort'))
usort($orParts[$orIndex], 'searchSort');
foreach ($orParts[$orIndex] as $word)
{
$is_excluded = in_array($word, $excludedWords);
$searchWords[$orIndex]['all_words'][] = $word;
$subjectWords = text2words($word);
if (!$is_excluded || count($subjectWords) === 1)
{
$searchWords[$orIndex]['subject_words'] = array_merge($searchWords[$orIndex]['subject_words'], $subjectWords);
if ($is_excluded)
$excludedSubjectWords = array_merge($excludedSubjectWords, $subjectWords);
}
else
$excludedPhrases[] = $word;
// Have we got indexes to prepare?
if ($searchAPI->supportsMethod('prepareIndexes'))
$searchAPI->prepareIndexes($word, $searchWords[$orIndex], $excludedIndexWords, $is_excluded);
}
// Search_force_index requires all AND parts to have at least one fulltext word.
if (!empty($modSettings['search_force_index']) && empty($searchWords[$orIndex]['indexed_words']))
{
$context['search_errors']['query_not_specific_enough'] = true;
break;
}
elseif ($search_params['subject_only'] && empty($searchWords[$orIndex]['subject_words']) && empty($excludedSubjectWords))
{
$context['search_errors']['query_not_specific_enough'] = true;
break;
}
// Make sure we aren't searching for too many indexed words.
else
{
$searchWords[$orIndex]['indexed_words'] = array_slice($searchWords[$orIndex]['indexed_words'], 0, 7);
$searchWords[$orIndex]['subject_words'] = array_slice($searchWords[$orIndex]['subject_words'], 0, 7);
$searchWords[$orIndex]['words'] = array_slice($searchWords[$orIndex]['words'], 0, 4);
}
}
// *** Spell checking
if ($context['show_spellchecking'])
{
require_once($sourcedir . '/Subs-Post.php');
// Don't hardcode spellchecking functions!
$link = spell_init();
$did_you_mean = array('search' => array(), 'display' => array());
$found_misspelling = false;
foreach ($searchArray as $word)
{
if (empty($link))
continue;
// Don't check phrases.
if (preg_match('~^\w+$~', $word) === 0)
{
$did_you_mean['search'][] = '"' . $word . '"';
$did_you_mean['display'][] = '"' . $smcFunc['htmlspecialchars']($word) . '"';
continue;
}
// For some strange reason spell check can crash PHP on decimals.
elseif (preg_match('~\d~', $word) === 1)
{
$did_you_mean['search'][] = $word;
$did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
continue;
}
elseif (spell_check($link, $word))
{
$did_you_mean['search'][] = $word;
$did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
continue;
}
$suggestions = spell_suggest($link, $word);
foreach ($suggestions as $i => $s)
{
// Search is case insensitive.
if ($smcFunc['strtolower']($s) == $smcFunc['strtolower']($word))
unset($suggestions[$i]);
// Plus, don't suggest something the user thinks is rude!
elseif ($suggestions[$i] != censorText($s))
unset($suggestions[$i]);
}
// Anything found? If so, correct it!
if (!empty($suggestions))
{
$suggestions = array_values($suggestions);
$did_you_mean['search'][] = $suggestions[0];
$did_you_mean['display'][] = '<em><strong>' . $smcFunc['htmlspecialchars']($suggestions[0]) . '</strong></em>';
$found_misspelling = true;
}
else
{
$did_you_mean['search'][] = $word;
$did_you_mean['display'][] = $smcFunc['htmlspecialchars']($word);
}
}
if ($found_misspelling)
{
// Don't spell check excluded words, but add them still...
$temp_excluded = array('search' => array(), 'display' => array());
foreach ($excludedWords as $word)
{
if (preg_match('~^\w+$~', $word) == 0)
{
$temp_excluded['search'][] = '-"' . $word . '"';
$temp_excluded['display'][] = '-"' . $smcFunc['htmlspecialchars']($word) . '"';
}
else
{
$temp_excluded['search'][] = '-' . $word;
$temp_excluded['display'][] = '-' . $smcFunc['htmlspecialchars']($word);
}
}
$did_you_mean['search'] = array_merge($did_you_mean['search'], $temp_excluded['search']);
$did_you_mean['display'] = array_merge($did_you_mean['display'], $temp_excluded['display']);
$temp_params = $search_params;
$temp_params['search'] = implode(' ', $did_you_mean['search']);
if (isset($temp_params['brd']))
$temp_params['brd'] = implode(',', $temp_params['brd']);
$context['params'] = array();
foreach ($temp_params as $k => $v)
$context['did_you_mean_params'][] = $k . '|\'|' . $v;
$context['did_you_mean_params'] = base64_encode(implode('|"|', $context['did_you_mean_params']));
$context['did_you_mean'] = implode(' ', $did_you_mean['display']);
}
}
// Let the user adjust the search query, should they wish?
$context['search_params'] = $search_params;
if (isset($context['search_params']['search']))
$context['search_params']['search'] = $smcFunc['htmlspecialchars']($context['search_params']['search']);
if (isset($context['search_params']['userspec']))
$context['search_params']['userspec'] = $smcFunc['htmlspecialchars']($context['search_params']['userspec']);
// Do we have captcha enabled?
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']))
{
require_once($sourcedir . '/Subs-Editor.php');
$verificationOptions = array(
'id' => 'search',
);
$context['require_verification'] = create_control_verification($verificationOptions, true);
if (is_array($context['require_verification']))
{
foreach ($context['require_verification'] as $error)
$context['search_errors'][$error] = true;
}
// Don't keep asking for it - they've proven themselves worthy.
else
$_SESSION['ss_vv_passed'] = true;
}
// *** Encode all search params
// All search params have been checked, let's compile them to a single string... made less simple by PHP 4.3.9 and below.
$temp_params = $search_params;
if (isset($temp_params['brd']))
$temp_params['brd'] = implode(',', $temp_params['brd']);