-
Notifications
You must be signed in to change notification settings - Fork 1
/
search.php
executable file
·3793 lines (3373 loc) · 122 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
/*======================================================================*\
|| #################################################################### ||
|| # vBulletin 3.8.11 - Licence Number VBF83FEF44
|| # ---------------------------------------------------------------- # ||
|| # Copyright ©2000-2017 vBulletin Solutions Inc. All Rights Reserved. ||
|| # This file may not be redistributed in whole or significant part. # ||
|| # ---------------- VBULLETIN IS NOT FREE SOFTWARE ---------------- # ||
|| # www.vbulletin.com | www.vbulletin.com/license.html # ||
|| #################################################################### ||
\*======================================================================*/
// ####################### SET PHP ENVIRONMENT ###########################
error_reporting(E_ALL & ~E_NOTICE);
// #################### DEFINE IMPORTANT CONSTANTS #######################
define('THIS_SCRIPT', 'search');
define('CSRF_PROTECTION', true);
define('ALTSEARCH', true);
// ################### PRE-CACHE TEMPLATES AND DATA ######################
// get special phrase groups
$phrasegroups = array('search', 'inlinemod', 'prefix');
// get special data templates from the datastore
$specialtemplates = array(
'iconcache',
'searchcloud'
);
// pre-cache templates used by all actions
$globaltemplates = array(
'humanverify',
'optgroup',
'search_forums',
'search_results',
'search_results_postbit', // result from search posts
'search_results_postbit_lastvisit',
'threadbit', // result from search threads
'threadbit_deleted', // result from deleted search threads
'threadbit_lastvisit',
'threadbit_announcement',
'newreply_reviewbit_ignore',
'threadadmin_imod_menu_thread',
'threadadmin_imod_menu_post',
'tag_cloud_link',
'tag_cloud_box_search',
'tag_cloud_headinclude'
);
// ######################### REQUIRE BACK-END ############################
require_once('./global.php');
require_once(DIR . '/includes/functions_search.php');
require_once(DIR . '/includes/functions_forumlist.php');
require_once(DIR . '/includes/functions_misc.php');
// #######################################################################
// ######################## START MAIN SCRIPT ############################
// #######################################################################
if (!($permissions['forumpermissions'] & $vbulletin->bf_ugp_forumpermissions['cansearch']))
{
print_no_permission();
}
if (!$vbulletin->options['enablesearches'])
{
eval(standard_error(fetch_error('searchdisabled')));
}
// #############################################################################
$globals = array(
'query' => TYPE_STR,
'searchuser' => TYPE_STR,
'exactname' => TYPE_BOOL,
'starteronly' => TYPE_BOOL,
'tag' => TYPE_STR, // TYPE_STR, because that's what the error cond for intro expects
'forumchoice' => TYPE_ARRAY,
'prefixchoice' => TYPE_ARRAY_NOHTML,
'childforums' => TYPE_BOOL,
'titleonly' => TYPE_BOOL,
'showposts' => TYPE_BOOL,
'searchdate' => TYPE_NOHTML,
'beforeafter' => TYPE_NOHTML,
'sortby' => TYPE_NOHTML,
'sortorder' => TYPE_NOHTML,
'replyless' => TYPE_UINT,
'replylimit' => TYPE_UINT,
'searchthreadid' => TYPE_UINT,
'saveprefs' => TYPE_BOOL,
'quicksearch' => TYPE_BOOL,
'searchtype' => TYPE_BOOL,
'exclude' => TYPE_NOHTML,
'nocache' => TYPE_BOOL,
'ajax' => TYPE_BOOL,
'humanverify' => TYPE_ARRAY,
'userid' => TYPE_UINT,
);
$vbulletin->input->clean_array_gpc('r', array(
'doprefs' => TYPE_NOHTML,
'searchtype' => TYPE_BOOL,
'searchid' => TYPE_UINT,
));
// #############################################################################
if (empty($_REQUEST['do']))
{
if ($vbulletin->GPC['searchid'])
{
$_REQUEST['do'] = 'showresults';
}
else
{
$_REQUEST['do'] = 'intro';
}
}
if (empty($_POST['do']))
{
$_POST['do'] = '';
}
if ($vbulletin->options['fulltextsearch'])
{
if ($permissions['genericpermissions'] & $vbulletin->bf_ugp_genericpermissions['cansearchft_bool'])
{
// use boolean when user has boolean, ignore NL
$vbulletin->GPC['searchtype'] = 1;
}
else
{
// user only has permission to use nl search
$vbulletin->GPC['searchtype'] = 0;
}
}
// check for extra variables from the advanced search form
if ($_POST['do'] == 'process')
{
// don't go to do=process, go to do=doprefs
if ($vbulletin->GPC['doprefs'] != '')
{
$_POST['do'] = 'doprefs';
$_REQUEST['do'] = 'doprefs';
}
}
// workaround for 3.6 bug 1229 - 'find all threads started by x' + captcha
if ($_REQUEST['do'] == 'process' AND fetch_require_hvcheck('search') AND !isset($_POST['humanverify']))
{
// guest user has come from a do=process link that does not include human verification
$_REQUEST['do'] = 'intro';
}
// make first part of navbar
$navbits = array('search.php' . $vbulletin->session->vars['sessionurl_q'] => $vbphrase['search_forums']);
$errors = array();
// #############################################################################
if ((in_array($_REQUEST['do'], array('intro', 'showresults', 'doprefs')) == false) AND $vbulletin->options['searchfloodtime'] AND !($permissions['adminpermissions'] & $vbulletin->bf_ugp_adminpermissions['cancontrolpanel']) AND !can_moderate())
{
// get last search for this user and check floodcheck
if ($prevsearch = $db->query_first("
SELECT searchid, dateline
FROM " . TABLE_PREFIX . "search AS search
WHERE " . iif(!$vbulletin->userinfo['userid'], "ipaddress ='" . $db->escape_string(IPADDRESS) . "'", "userid = " . $vbulletin->userinfo['userid']) . "
ORDER BY dateline DESC LIMIT 1
"))
{
if (($timepassed = TIMENOW - $prevsearch['dateline']) < $vbulletin->options['searchfloodtime'])
{
if ($_REQUEST['do'] == 'process')
{
$errors[] = array('searchfloodcheck', $vbulletin->options['searchfloodtime'], ($vbulletin->options['searchfloodtime'] - $timepassed));
}
else
{
eval(standard_error(fetch_error('searchfloodcheck', $vbulletin->options['searchfloodtime'], ($vbulletin->options['searchfloodtime'] - $timepassed))));
}
}
}
}
// #############################################################################
// allows an alternative processing branch to be executed
($hook = vBulletinHook::fetch_hook('search_before_process')) ? eval($hook) : false;
// #############################################################################
if ($_REQUEST['do'] == 'process')
{
$vbulletin->input->clean_array_gpc('r', $globals);
($hook = vBulletinHook::fetch_hook('search_process_start')) ? eval($hook) : false;
if (!$vbulletin->options['threadtagging'])
{
// tagging disabled, don't let them search on it
$vbulletin->GPC['tag'] = '';
}
// #############################################################################
// start search timer
$searchstart = microtime();
if ($vbulletin->GPC['userid'] AND $userinfo = fetch_userinfo($vbulletin->GPC['userid']))
{
$vbulletin->GPC_exists['searchuser'] = true;
$vbulletin->GPC['searchuser'] = unhtmlspecialchars($userinfo['username']);
}
// #############################################################################
// error if no search terms
$vbulletin->GPC['prefixchoice'] = array_unique($vbulletin->GPC['prefixchoice']);
$have_prefix_limit = false;
foreach ($vbulletin->GPC['prefixchoice'] AS $prefixid)
{
if (!$prefixid OR $prefixid == '-1')
{
// searching on any or no prefix - this is not restrictive enough
// so this overrides any other setting
$have_prefix_limit = false;
break;
}
else
{
// matched a prefix - we have a limit, but we might still have
// a non-restrictive value so continue looping
$have_prefix_limit = true;
}
}
$have_search_limit = (
$vbulletin->GPC['query']
OR $vbulletin->GPC['searchuser']
OR $vbulletin->GPC['replyless']
OR $vbulletin->GPC['tag']
OR $have_prefix_limit
);
if (!$have_search_limit)
{
$errors[] = 'searchspecifyterms';
}
if (fetch_require_hvcheck('search'))
{
require_once(DIR . '/includes/class_humanverify.php');
$verify = vB_HumanVerify::fetch_library($vbulletin);
if (!$verify->verify_token($vbulletin->GPC['humanverify']))
{
$errors[] = $verify->fetch_error();
}
}
if (empty($errors))
{
// #############################################################################
// if searching within a thread, $showposts must be true and sorting should be "dateline ASC"
if ($vbulletin->GPC['searchthreadid'])
{
$vbulletin->GPC['sortby'] = 'dateline';
$vbulletin->GPC['sortorder'] = 'ASC';
$vbulletin->GPC['showposts'] = true;
$vbulletin->GPC['forumchoice'] = array();
$vbulletin->GPC['starteronly'] = false;
$vbulletin->GPC['titleonly'] = false;
$vbulletin->GPC['replyless'] = false;
$vbulletin->GPC['replylimit'] = false;
}
// if searching for only a tag, we must show results as threads
if ($vbulletin->GPC['tag'] AND empty($vbulletin->GPC['query']) AND empty($vbulletin->GPC['searchuser']))
{
$vbulletin->GPC['showposts'] = false;
}
// #############################################################################
// make array of search terms for back referencing
$searchterms = array();
foreach ($globals AS $varname => $value)
{
if ($varname == 'forumchoice' AND is_array($vbulletin->GPC['forumchoice']))
{
$searchterms["$varname"] = $vbulletin->GPC['forumchoice'];
}
else
{
$searchterms["$varname"] = $vbulletin->GPC["$varname"];
}
}
// #############################################################################
// if query string is specified, check syntax and replace common syntax errors
if ($vbulletin->GPC['query'])
{
// are we using FT and boolean search?
if ($vbulletin->options['fulltextsearch'] AND $vbulletin->GPC['searchtype'])
{
// look for entire words that consist of "Ӓ". MySQL boolean
// search will tokenize them seperately. Wrap them in quotes if they're
// not already to emulate search for exactly that word.
$query = explode('"', $vbulletin->GPC['query']);
$query_part_count = count($query);
$vbulletin->GPC['query'] = '';
for ($i = 0; $i < $query_part_count; $i++)
{
// exploding by " means the 0th, 2nd, 4th... entries in the array
// are outside of quotes
if ($i % 2 == 1)
{
// 1st, 3rd.. entry = in quotes
$vbulletin->GPC['query'] .= '"' . $query["$i"] . '"';
}
else
{
// look for words that are contain Ӓ, ., or - and quote them (more logical behavior, 24676)
$query_parts = '';
$space_skipped = false;
foreach (preg_split('#[ \r\n\t]#s', $query["$i"]) AS $query_part)
{
if ($space_skipped)
{
$query_parts .= ' ';
}
$space_skipped = true;
if (preg_match('/(&#[0-9]+;|\.|-)/s', $query_part))
{
$query_parts .= '"' . $query_part . '"';
}
else
{
$query_parts .= $query_part;
}
}
$vbulletin->GPC['query'] .= $query_parts;
}
}
$vbulletin->GPC['query'] = preg_replace_callback(
'#"([^"]+)"#si',
function($matches)
{
return stripslashes(str_replace(' ', '*', $matches[0]));
},
$vbulletin->GPC['query']
);
}
$vbulletin->GPC['query'] = sanitize_search_query($vbulletin->GPC['query'], $errors);
}
if (empty($errors))
{
// #############################################################################
// get forums in which to search
$forumchoice = implode(',', fetch_search_forumids($vbulletin->GPC['forumchoice'], $vbulletin->GPC['childforums']));
// get prefixes
if (in_array('', $vbulletin->GPC['prefixchoice']) OR empty($vbulletin->GPC['prefixchoice']))
{
// any prefix
$vbulletin->GPC['prefixchoice'] = array();
$prefixchoice = '';
$display_prefixes = array();
}
else
{
$vbulletin->GPC['prefixchoice'] = array_unique($vbulletin->GPC['prefixchoice']);
$prefixchoice = implode(',', $vbulletin->GPC['prefixchoice']);
$display_prefixes = $vbulletin->GPC['prefixchoice'];
}
// #############################################################################
// get correct sortby value
$vbulletin->GPC['sortby'] = strtolower($vbulletin->GPC['sortby']);
switch($vbulletin->GPC['sortby'])
{
// sort variables that don't need changing
case 'title':
case 'views':
case 'lastpost':
case 'replycount':
case 'postusername':
case 'rank':
break;
// sort variables that need changing
case 'forum':
$vbulletin->GPC['sortby'] = 'forum.title';
break;
case 'threadstart':
$vbulletin->GPC['sortby'] = 'thread.dateline';
break;
// set default sortby if not specified or unrecognized
default:
$vbulletin->GPC['sortby'] = 'lastpost';
}
// #############################################################################
// if showing results as posts, translate the $sortby variable
if ($vbulletin->GPC['showposts'])
{
switch($vbulletin->GPC['sortby'])
{
case 'title':
$vbulletin->GPC['sortby'] = 'thread.title';
break;
case 'lastpost':
$vbulletin->GPC['sortby'] = 'post.dateline';
break;
case 'postusername':
$vbulletin->GPC['sortby'] = 'username';
break;
}
}
// #############################################################################
// get correct sortorder value
$vbulletin->GPC['sortorder'] = strtolower($vbulletin->GPC['sortorder']);
switch($vbulletin->GPC['sortorder'])
{
case 'ascending':
$vbulletin->GPC['sortorder'] = 'ASC';
break;
default:
$vbulletin->GPC['sortorder'] = 'DESC';
break;
}
// #############################################################################
// build search hash
$searchhash = md5(strtolower($vbulletin->GPC['query']) . "||" . strtolower($vbulletin->GPC['searchuser']) . '||' . strtolower($vbulletin->GPC['tag']) . '||' . $vbulletin->GPC['exactname'] . '||' . $vbulletin->GPC['starteronly'] . "||$forumchoice||$prefixchoice||" . $vbulletin->GPC['childforums'] . '||' . $vbulletin->GPC['titleonly'] . '||' . $vbulletin->GPC['showposts'] . '||' . $vbulletin->GPC['searchdate'] . '||' . $vbulletin->GPC['beforeafter'] . '||' . $vbulletin->GPC['replyless'] . '||' . $vbulletin->GPC['replylimit'] . '||' . $vbulletin->GPC['searchthreadid'] . '||' . $vbulletin->GPC['exclude'] . iif($vbulletin->options['fulltextsearch'], '||' . $vbulletin->GPC['searchtype']));
// #############################################################################
// search for already existing searches...
if (!$vbulletin->GPC['nocache'])
{
$getsearches = $db->query_read("
SELECT * FROM " . TABLE_PREFIX . "search AS search
WHERE searchhash = '" . $db->escape_string($searchhash) . "'
AND userid = " . $vbulletin->userinfo['userid'] . "
AND completed = 1
");
if ($numsearches = $db->num_rows($getsearches))
{
$highScore = 0;
while ($getsearch = $db->fetch_array($getsearches))
{
// is $sortby the same?
if ($getsearch['sortby'] == $vbulletin->GPC['sortby'])
{
if ($getsearch['sortorder'] == $vbulletin->GPC['sortorder'])
{
// search matches exactly
$search = $getsearch;
$highScore = 3;
}
else if ($highScore < 2)
{
// search matches but needs order reversed
$search = $getsearch;
$highScore = 2;
}
}
// $sortby is different
else if ($highScore < 1)
{
// search matches but needs total re-ordering
$search = $getsearch;
$highScore = 1;
}
}
unset($getsearch);
$db->free_result($getsearches);
// check our results and decide what to do
switch ($highScore)
{
// #############################################################################
// found a saved search that matches perfectly
case 3:
$searchtime = fetch_microtime_difference($searchstart);
// redirect to saved search
$vbulletin->url = 'search.php?' . $vbulletin->session->vars['sessionurl'] . "searchid=$search[searchid]";
eval(print_standard_redirect('search'));
break;
// #############################################################################
// found a saved search and just need to reverse sort order
case 2:
// reverse sort order
$search['orderedids'] = array_reverse(explode(',', $search['orderedids']));
// stop search timer
$searchtime = number_format(fetch_microtime_difference($searchstart), 5, '.', '');
// insert new search into database
/*insert query*/
$db->query_write("
REPLACE INTO " . TABLE_PREFIX . "search
(userid, titleonly, ipaddress, personal, query, searchuser, forumchoice, prefixchoice,
sortby, sortorder, searchtime, showposts, orderedids, dateline, searchterms,
displayterms, searchhash, completed)
VALUES
(" . $vbulletin->userinfo['userid'] . ",
" . intval($vbulletin->GPC['titleonly']) . ",
'" . $db->escape_string(IPADDRESS) . "',
" . ($vbulletin->options['searchsharing'] ? 0 : 1) . ",
'" . $db->escape_string($search['query']) . "',
'" . $db->escape_string($search['searchuser']) . "',
'" . $db->escape_string($search['forumchoice']) . "',
'" . $db->escape_string($search['prefixchoice']) . "',
'" . $db->escape_string($search['sortby']) . "',
'" . $db->escape_string($vbulletin->GPC['sortorder']) . "',
$searchtime,
" . intval($vbulletin->GPC['showposts']) . ",
'" . implode(',', $search['orderedids']) . "',
" . TIMENOW . ",
'" . $db->escape_string($search['searchterms']) . "',
'" . $db->escape_string($search['displayterms']) . "',
'" . $db->escape_string($searchhash) . "',
1)
");
// redirect to new search result
$vbulletin->url = 'search.php?' . $vbulletin->session->vars['sessionurl'] . 'searchid=' . $db->insert_id();
eval(print_standard_redirect('search'));
break;
// #############################################################################
// Found a search with correct query conditions, but ORDER BY clause needs to be totally redone
case 1:
if ($vbulletin->GPC['sortby'] == 'rank' OR $search['sortby'] == 'rank')
{
// if we are changing to or from a relevancy search, we need to re-do the search
break;
}
else
{
// re order search items
$search['orderedids'] = iif($search['showposts'], 'postid', 'threadid') . " IN($search[orderedids])";
$search['orderedids'] = sort_search_items($search['orderedids'], $search['showposts'], $vbulletin->GPC['sortby'], $vbulletin->GPC['sortorder']);
// stop search timer
$searchtime = number_format(fetch_microtime_difference($searchstart), 5, '.', '');
// insert new search into database
/*insert query*/
$db->query_write("
REPLACE INTO " . TABLE_PREFIX . "search (userid, titleonly, ipaddress, personal, query, searchuser, forumchoice, sortby, sortorder, searchtime, showposts, orderedids, dateline, searchterms, displayterms, searchhash, completed)
VALUES (
" . $vbulletin->userinfo['userid'] . ",
" . intval($vbulletin->GPC['titleonly']) . ",
'" . $db->escape_string(IPADDRESS) . "',
" . ($vbulletin->options['searchsharing'] ? 0 : 1) . ",
'" . $db->escape_string($search['query']) . "',
'" . $db->escape_string($search['searchuser']) . "',
'" . $db->escape_string($search['forumchoice']) . "',
'" . $db->escape_string($vbulletin->GPC['sortby']) . "',
'" . $db->escape_string($vbulletin->GPC['sortorder']) .
"', $searchtime,
$search[showposts],
'" . implode(',', $search['orderedids']) . "',
" . TIMENOW . ",
'" . $db->escape_string(serialize($searchterms)) . "',
'" . $db->escape_string($search['displayterms']) . "',
'" . $db->escape_string($searchhash) . "',
1
)
");
// redirect to new search result
$vbulletin->url = 'search.php?' . $vbulletin->session->vars['sessionurl'] . 'searchid=' . $db->insert_id();
eval(print_standard_redirect('search'));
break;
}
}
}
}
// now we know this will be a unique search, put a placeholder in
// for the floodcheck
/*insert query*/
$db->query_write("
REPLACE INTO " . TABLE_PREFIX . "search
(userid, titleonly, ipaddress, personal, query, searchuser, forumchoice, prefixchoice, sortby, sortorder, searchtime, showposts, orderedids, dateline, searchterms, displayterms, searchhash, completed)
VALUES (
" . $vbulletin->userinfo['userid'] . ",
" . intval($vbulletin->GPC['titleonly']) . " ,
'" . $db->escape_string(IPADDRESS) . "',
" . ($vbulletin->options['searchsharing'] ? 0 : 1) . ",
'" . $db->escape_string($vbulletin->GPC['query']) . "',
'" . $db->escape_string($vbulletin->GPC['searchuser']) . "',
'" . $db->escape_string($forumchoice) . "',
'" . $db->escape_string($prefixchoice) . "',
'" . $db->escape_string($vbulletin->GPC['sortby']) . "',
'" . $db->escape_string($vbulletin->GPC['sortorder']) . "',
0,
" . intval($vbulletin->GPC['showposts']) . ",
'',
" . TIMENOW . ",
'" . $db->escape_string(serialize($searchterms)) . "',
'',
'" . $db->escape_string($searchhash) . "',
0
)
");
// #############################################################################
// #############################################################################
// if we got this far we need to do a full search
// #############################################################################
// #############################################################################
// $post_query_logic stores all the SQL conditions for our search in posts
$post_query_logic = array();
// $thread_query_logic stores all SQL conditions for the search in threads
$thread_query_logic = array();
// $words stores all the search words with their word IDs
$words = array(
'AND' => array(),
'OR' => array(),
'NOT' => array(),
'COMMON' => array()
);
// $queryWords provides a way to talk to words within the $words array
$queryWords = array();
// $display - stores a list of things searched for
$display = array(
'words' => array(),
'highlight' => array(),
'common' => array(),
'users' => array(),
'forums' => $display['forums'],
'prefixes' => $display_prefixes,
'tag' => htmlspecialchars_uni($vbulletin->GPC['tag']),
'options' => array(
'starteronly' => $vbulletin->GPC['starteronly'],
'childforums' => $vbulletin->GPC['childforums'],
'action' => $_REQUEST['do']
)
);
$postscores = array();
($hook = vBulletinHook::fetch_hook('search_process_fullsearch')) ? eval($hook) : false;
// #############################################################################
// ####################### START USER QUERY LOGIC ##############################
// #############################################################################
$postsum = 0;
if ($vbulletin->GPC['searchuser'])
{
// username too short
if (!$vbulletin->GPC['exactname'] AND strlen($vbulletin->GPC['searchuser']) < 3)
{
$errors[] = 'searchnametooshort';
}
else
{
$username = htmlspecialchars_uni($vbulletin->GPC['searchuser']);
$q = "
SELECT posts, userid, username
FROM " . TABLE_PREFIX . "user AS user
WHERE username " .
($vbulletin->GPC['exactname'] ?
"= '" . $db->escape_string($username) . "'" :
"LIKE('%" . sanitize_word_for_sql($username) . "%')"
)
;
require_once(DIR . '/includes/functions_bigthree.php');
$coventry = fetch_coventry();
$users = $db->query_read_slave($q);
if ($db->num_rows($users))
{
$userids = array();
while ($user = $db->fetch_array($users))
{
$postsum += $user['posts'];
$display['users']["$user[userid]"] = $user['username'];
$userids[] = (in_array($user['userid'], $coventry) AND !can_moderate()) ? -1 : $user['userid'];
}
$userids = implode(', ', $userids);
if ($vbulletin->GPC['starteronly'])
{
if ($vbulletin->GPC['showposts'])
{
$post_query_logic[50] = "post.userid IN($userids)";
}
$thread_query_logic[] = "thread.postuserid IN($userids)";
}
// add the userids to the $post_query_logic search conditions
else
{
if ($vbulletin->GPC['showposts'])
{
$post_query_logic[50] = "post.userid IN($userids)";
}
else
{ // use the (threadid, userid) index of post to limit the join
$post_join_query_logic = " AND post.userid IN($userids)";
}
}
}
else
{
$errors[] = array('invalidid', $vbphrase['user'], $vbulletin->options['contactuslink']);
}
}
}
}
$tag_join = '';
if ($vbulletin->GPC['tag'])
{
$verified_tag = $db->query_first_slave("
SELECT tagid, tagtext
FROM " . TABLE_PREFIX . "tag
WHERE tagtext = '" . $db->escape_string(htmlspecialchars_uni($vbulletin->GPC['tag'])) . "'
");
if (!$verified_tag)
{
$errors[] = 'invalid_tag_specified';
}
else
{
$db->query_write("INSERT INTO " . TABLE_PREFIX . "tagsearch (tagid, dateline) VALUES (" . $verified_tag['tagid'] . ", " . TIMENOW . ")");
$tag_join = "INNER JOIN " . TABLE_PREFIX . "tagthread AS tagthread ON (tagthread.tagid = $verified_tag[tagid] AND tagthread.threadid = thread.threadid)";
}
}
if (empty($errors))
{
// #############################################################################
// ########################## START WORD QUERY LOGIC ###########################
// #############################################################################
if ($vbulletin->GPC['query'] AND (!$vbulletin->options['fulltextsearch'] OR ($vbulletin->options['fulltextsearch'] AND $vbulletin->GPC['searchtype'])))
{
$querysplit = $vbulletin->GPC['query'];
// split string into seperate words and back again, this will deal with MB languages without space delimiters
$querysplit = implode(' ', split_string($querysplit));
// #############################################################################
// if we are doing a relevancy sort, use all AND and OR words as OR
if ($vbulletin->GPC['sortby'] == 'rank')
{
$not = '';
while (preg_match_all('# -(.*) #siU', " $querysplit ", $regs))
{
foreach ($regs[0] AS $word)
{
$not .= ' ' . trim($word);
$querysplit = trim(str_replace($word, ' ', " $querysplit "));
}
}
$querysplit = preg_replace('# (OR )*#si', ' OR ', $querysplit) . $not;
}
// #############################################################################
// strip out common words from OR clauses pt1
if (preg_match_all('#OR ([^\s]+) #sU', "$querysplit ", $regs))
{
foreach ($regs[1] AS $key => $word)
{
if (!verify_word_allowed($word))
{
$display['common'][] = $word;
$querysplit = trim(str_replace($regs[0]["$key"], '', "$querysplit "));
}
}
}
// strip out common words from OR clauses pt2
if (preg_match_all('# ([^\s]+) OR#sU', " $querysplit", $regs))
{
foreach ($regs[1] AS $key => $word)
{
if (!verify_word_allowed($word))
{
$display['common'][] = $word;
$querysplit = trim(str_replace($regs[0]["$key"], ' ', " $querysplit "));
}
}
}
// regular expressions to match query syntax
$syntax = array(
'NOT' => '/( -[^\s]+)/si',
'OR' => '#( ([^\s]+)(( OR [^\s]+)+))#si',
'AND' => '/(\s|\+)+/siU'
);
// #############################################################################
// find NOT clauses
if (preg_match_all($syntax['NOT'], " $querysplit", $regs))
{
foreach ($regs[0] AS $word)
{
$word = substr(trim($word), 1);
if (verify_word_allowed($word))
{
// word is okay - add it to the list of NOT words to be queried
$words['NOT']["$word"] = 'NOT';
$queryWords["$word"] =& $words['NOT']["$word"];
}
else
{
// word is bad or unindexed - add to list of common words
$display['common'][] = $word;
}
}
$querysplit = preg_replace($syntax['NOT'], ' ', " $querysplit");
}
// #############################################################################
// find OR clauses
if (preg_match_all($syntax['OR'], " $querysplit", $regs))
{
foreach ($regs[0] AS $word)
{
$word = trim($word);
$orBits = explode(' OR ', $word);
$checkwords = array();
foreach ($orBits AS $orBit)
{
if (verify_word_allowed($orBit))
{
// word is okay - add it to the list of OR words for this clause
$checkwords[] = $orBit;
}
else
{
// word is bad or unindexed - add to list of common words
$display['common'][] = $orBit;
}
}
// check to see how many words we have in the current OR clause
switch(sizeof($checkwords))
{
case 0:
// all words were bad or not indexed
if (sizeof($display['common']) > 0)
{
$displayCommon = "<p>$vbphrase[words_very_common] : <b>" . implode('</b>, <b>', htmlspecialchars_uni($display['common'])) . '</b></p>';
}
else
{
$displayCommon = '';
}
$errors[] = array('searchnoresults', $displayCommon);
break;
case 1:
// just one word is okay - use it as an AND word instead of an OR
$word = implode('', $checkwords);
$words['AND']["$word"] = 'AND';
$queryWords["$word"] =& $words['AND']["$word"];
break;
default:
// two or more words were okay - use them as an OR clause
foreach ($checkwords AS $checkword)
{
$words['OR']["$word"]["$checkword"] = 'OR';
$queryWords["$checkword"] =& $words['OR']["$word"]["$checkword"];
}
break;
}
}
$querysplit = preg_replace($syntax['OR'], '', " $querysplit");
}
// #############################################################################
// other words must be required (AND)
foreach (preg_split($syntax['AND'], $querysplit, -1, PREG_SPLIT_NO_EMPTY) AS $word)
{
if (verify_word_allowed($word))
{
// word is okay - add it to the list of AND words to be queried
$words['AND']["$word"] = 'AND';
$queryWords["$word"] =& $words['AND']["$word"];
}
else
{
// word is bad or unindexed - add to list of common words
$display['common'][] = $word;
}
}
if (sizeof($display['common']) > 0)
{
$displayCommon = "<p>$vbphrase[words_very_common] : <b>" . implode('</b>, <b>', htmlspecialchars_uni($display['common'])) . '</b></p>';
}
else
{
$displayCommon = '';
}
// now that we've checked all the words, are there still some terms to search with?
if (empty($queryWords) AND empty($display['users']))
{
// all search words bad or unindexed
$errors[] = array('searchnoresults', $displayCommon);
}
if (empty($errors))
{
if (!$vbulletin->options['fulltextsearch'])
{
// #############################################################################
// get highlight words (part 1)
foreach ($queryWords AS $word => $wordtype)
{
if ($wordtype != 'NOT')
{
$display['highlight'][] = $word;
}
}
// #############################################################################
// query words from word and postindex tables to get post ids
// #############################################################################
foreach ($queryWords AS $word => $wordtype)
{
// should remove characters just like we do when we insert into post index
$queryword = preg_replace('#[()"\'!\#{};]|\\\\|:(?!//)#s', '', $word);
// make sure word is safe to insert into the query
$queryword = sanitize_word_for_sql($queryword);
if ($vbulletin->options['allowwildcards'])
{
$queryword = str_replace('*', '%', $queryword);
}
$getwords = $db->query_read_slave("
SELECT wordid, title FROM " . TABLE_PREFIX . "word
WHERE title LIKE('$queryword')
");
if ($db->num_rows($getwords))
{
// found some results for current word
$wordids = array();
while ($getword = $db->fetch_array($getwords))
{
$wordids[] = $getword['wordid'];
}
// query post ids for current word...
// if $titleonly is specified, also get the value of postindex.intitle
$postmatches = $db->query_read_slave("
SELECT postid" . iif($vbulletin->GPC['titleonly'], ', intitle') . iif($vbulletin->GPC['sortby'] == 'rank', ", score AS origscore,
CASE intitle
WHEN 1 THEN score + " . $vbulletin->options['posttitlescore'] . "
WHEN 2 THEN score + " . ($vbulletin->options['posttitlescore'] + $vbulletin->options['threadtitlescore']) . "
ELSE score
END AS score") . "
FROM " . TABLE_PREFIX . "postindex
WHERE wordid IN(" . implode(',', $wordids) . ") " . ($vbulletin->GPC['titleonly'] ? " AND intitle = 2" : "") . "
");
if ($db->num_rows($postmatches) == 0)
{
if ($wordtype == 'AND')
{
// could not find any posts containing required word
$errors[] = array('searchnoresults', $displayCommon);
break;
}
else
{
// Could not find any posts containing word
// remove this word from the $queryWords array so we don't use it in the posts query
unset($queryWords["$word"]);
}
}
else
{
// reset the $queryWords entry for current word
$queryWords["$word"] = array();
// check that word exists in the title
if ($vbulletin->GPC['titleonly'])