-
Notifications
You must be signed in to change notification settings - Fork 0
/
relevanssi.php
2306 lines (1972 loc) · 79.6 KB
/
relevanssi.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
/*
Plugin Name: Relevanssi Premium
Plugin URI: http://www.relevanssi.com/
Description: This premium plugin replaces WordPress search with a relevance-sorting search.
Version: 1.15.0.1
Author: Mikko Saari
Author URI: http://www.mikkosaari.fi/
Text-domain: relevanssi
*/
/* Copyright 2017 Mikko Saari (email: [email protected])
This file is part of Relevanssi Premium, a search plugin for WordPress.
Relevanssi Premium is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
Relevanssi Premium is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with Relevanssi Premium. If not, see <http://www.gnu.org/licenses/>.
*/
// For debugging purposes
// error_reporting(E_ALL);
// ini_set("display_errors", 1);
// define('WP-DEBUG', true);
add_action('init', 'relevanssi_premium_init');
add_action('init', 'relevanssi_wptuts_activate_au');
add_action('profile_update', 'relevanssi_profile_update');
add_action('edit_user_profile_update', 'relevanssi_profile_update');
add_action('user_register', 'relevanssi_profile_update');
add_action('delete_user', 'relevanssi_delete_user');
add_action('edit_term', 'relevanssi_edit_term');
add_action('delete_term', 'relevanssi_delete_taxonomy_term');
add_action('wpmu_new_blog', 'relevanssi_new_blog', 10, 6);
add_action('save_post', 'relevanssi_save_postdata');
add_action('edit_attachment', 'relevanssi_save_postdata');
add_filter('the_permalink', 'relevanssi_permalink');
add_filter('relevanssi_permalink', 'relevanssi_permalink');
add_filter('wpmu_drop_tables', 'relevanssi_wpmu_drop');
add_action('network_admin_menu', 'relevanssi_network_menu');
global $wpdb;
global $relevanssi_variables;
$relevanssi_variables['relevanssi_table'] = $wpdb->prefix . "relevanssi";
$relevanssi_variables['stopword_table'] = $wpdb->prefix . "relevanssi_stopwords";
$relevanssi_variables['log_table'] = $wpdb->prefix . "relevanssi_log";
$relevanssi_variables['relevanssi_cache'] = $wpdb->prefix . "relevanssi_cache";
$relevanssi_variables['relevanssi_excerpt_cache'] = $wpdb->prefix . "relevanssi_excerpt_cache";
$relevanssi_variables['post_type_weight_defaults']['post_tag'] = 0.5;
$relevanssi_variables['post_type_weight_defaults']['category'] = 0.5;
$relevanssi_variables['title_boost_default'] = 5;
$relevanssi_variables['link_boost_default'] = 0.75;
$relevanssi_variables['comment_boost_default'] = 0.75;
$relevanssi_variables['database_version'] = 17;
$relevanssi_variables['plugin_version'] = "1.15.0.1";
$relevanssi_variables['plugin_dir'] = plugin_dir_path(__FILE__);
$relevanssi_variables['plugin_basename'] = plugin_basename(__FILE__);
$relevanssi_variables['file'] = __FILE__;
define('RELEVANSSI_PREMIUM', true);
require_once('lib/init.php');
require_once('lib/interface.php');
require_once('lib/indexing.php');
require_once('lib/stopwords.php');
require_once('lib/search.php');
require_once('lib/excerpts-highlights.php');
require_once('lib/shortcodes.php');
require_once('lib/common.php');
require_once('lib/autoupdate.php');
require_once('lib/SpellCorrector.php');
function relevanssi_premium_init() {
if (get_option('relevanssi_hide_post_controls') == 'off') {
add_action('add_meta_boxes', 'relevanssi_add_metaboxes');
}
if (get_option('relevanssi_index_synonyms') == 'on') {
add_filter('relevanssi_post_to_index', 'relevanssi_index_synonyms', 10);
}
add_action('future_to_publish',
function($post) {
remove_action('save_post', 'relevanssi_save_postdata');
}
);
return;
}
function relevanssi_check_old_data() {
$screen = get_current_screen();
if ($screen->base != 'settings_page_relevanssi-premium/relevanssi') return;
global $wpdb, $relevanssi_variables;
// Clean out empty _relevanssi_hide_post meta fields
$wpdb->query("DELETE FROM $wpdb->postmeta WHERE meta_key = '_relevanssi_hide_post' AND meta_value = ''");
// Version 1.13 changed taxonomy term indexing
$taxonomies = $wpdb->get_var("SELECT doc FROM " . $relevanssi_variables['relevanssi_table'] . " WHERE type = 'taxonomy'");
if ($taxonomies != NULL) {
function relevanssi_taxonomies_warning() {
echo "<div id='relevanssi-warning' class='error'><p><strong>"
. sprintf(__('Thanks for updating the plugin. After the update, Relevanssi requires re-indexing in order to handle taxonomy terms better. You can reindex at <a href="%1$s">the
settings page</a>. If you just completed indexing, disregard this message - all is good and this message should not appear again. Thanks!'), "options-general.php?page=relevanssi-premium/relevanssi.php")
. "</strong></p></div>";
}
add_action('admin_notices', 'relevanssi_taxonomies_warning');
}
// Version 1.12 removes the cache feature
$cache = get_option('relevanssi_enable_cache', 'nothing');
if ($cache != 'nothing') {
$relevanssi_cache = $wpdb->prefix . "relevanssi_cache";
$relevanssi_excerpt_cache = $wpdb->prefix . "relevanssi_excerpt_cache";
$wpdb->query("DROP TABLE $relevanssi_cache");
$wpdb->query("DROP TABLE $relevanssi_excerpt_cache");
delete_option('relevanssi_enable_cache');
delete_option('relevanssi_cache_seconds');
wp_clear_scheduled_hook('relevanssi_truncate_cache');
}
// Version 1.10.5 combined taxonomy indexing options
$inctags = get_option('relevanssi_include_tags', 'nothing');
if ($inctags == 'on') {
$taxonomies = get_option('relevanssi_index_taxonomies_list');
if (!is_array($taxonomies)) $taxonomies = array();
$taxonomies[] = 'post_tag';
update_option('relevanssi_index_taxonomies_list', $taxonomies);
delete_option('relevanssi_include_tags');
}
$inccats = get_option('relevanssi_include_cats', 'nothing');
if ($inccats == 'on') {
$taxonomies = get_option('relevanssi_index_taxonomies_list');
if (!is_array($taxonomies)) $taxonomies = array();
$taxonomies[] = 'category';
update_option('relevanssi_index_taxonomies_list', $taxonomies);
delete_option('relevanssi_include_cats');
}
$custom = get_option('relevanssi_custom_taxonomies', 'nothing');
if ($custom != 'nothing') {
$cts = explode(",", $custom);
$taxonomies = get_option('relevanssi_index_taxonomies_list');
if (!is_array($taxonomies)) $taxonomies = array();
foreach ($cts as $taxonomy) {
$taxonomy = trim($taxonomy);
$taxonomies[] = $taxonomy;
}
update_option('relevanssi_index_taxonomies_list', $taxonomies);
delete_option('relevanssi_custom_taxonomies');
}
$taxos = get_option('relevanssi_taxonomies_to_index', 'nothing');
if ($taxos != 'nothing') {
if ($taxos == 'all') {
$taxonomies = get_option('relevanssi_index_terms');
if (!is_array($taxonomies)) $taxonomies = array();
$all_taxonomies = get_taxonomies('', 'names');
foreach ($all_taxonomies as $taxonomy) {
$taxonomies[] = $taxonomy;
}
update_option('relevanssi_index_terms', $taxonomies);
delete_option('relevanssi_taxonomies_to_index');
}
else {
$cts = explode(",", $taxos);
$taxonomies = get_option('relevanssi_index_terms');
if (!is_array($taxonomies)) $taxonomies = array();
foreach ($cts as $taxonomy) {
$taxonomy = trim($taxonomy);
$taxonomies[] = $taxonomy;
}
update_option('relevanssi_index_terms', $taxonomies);
delete_option('relevanssi_taxonomies_to_index');
}
}
$limit = get_option('relevanssi_throttle_limit');
if (empty($limit)) update_option('relevanssi_throttle_limit', 500);
if ($relevanssi_variables['database_version'] == 15) {
$res = $wpdb->query("SHOW INDEX FROM " . $relevanssi_variables['relevanssi_table'] . " WHERE Key_name = 'typeitem'");
if ($res == 0) $wpdb->query("ALTER TABLE " . $relevanssi_variables['relevanssi_table'] . " ADD INDEX `typeitem` (`type`, `item`)");
}
// Version 1.7.3 renamed relevanssi_hide_post
/*
$query = "UPDATE $wpdb->postmeta SET meta_key = '_relevanssi_hide_post' WHERE meta_key = 'relevanssi_hide_post'";
$wpdb->query($query);
*/
// Version 1.6.3 removed relevanssi_tag_boost
$tag_boost = get_option('relevanssi_tag_boost', 'nothing');
if ($tag_boost != 'nothing') {
$post_type_weights = get_option('relevanssi_post_type_weights');
if (!is_array($post_type_weights)) {
$post_type_weights = array();
}
$post_type_weights['post_tag'] = $tag_boost;
delete_option('relevanssi_tag_boost');
update_option('relevanssi_post_type_weights', $post_type_weights);
}
$index_type = get_option('relevanssi_index_type', 'nothing');
if ($index_type != 'nothing') {
// Delete unused options from 1.5 versions
$post_types = get_option('relevanssi_index_post_types');
if (!is_array($post_types)) $post_types = array();
switch ($index_type) {
case "posts":
array_push($post_types, 'post');
break;
case "pages":
array_push($post_types, 'page');
break;
case 'public':
if (function_exists('get_post_types')) {
$pt_1 = get_post_types(array('exclude_from_search' => '0'));
$pt_2 = get_post_types(array('exclude_from_search' => false));
foreach (array_merge($pt_1, $pt_2) as $type) {
array_push($post_types, $type);
}
}
break;
case "both": // really should be "everything"
$pt = get_post_types();
foreach ($pt as $type) {
array_push($post_types, $type);
}
break;
}
$attachments = get_option('relevanssi_index_attachments');
if ('on' == $attachments) array_push($post_types, 'attachment');
$custom_types = get_option('relevanssi_custom_types');
$custom_types = explode(',', $custom_types);
if (is_array($custom_types)) {
foreach ($custom_types as $type) {
$type = trim($type);
if (substr($type, 0, 1) != '-') {
array_push($post_types, $type);
}
}
}
update_option('relevanssi_index_post_types', $post_types);
delete_option('relevanssi_index_type');
delete_option('relevanssi_index_attachments');
delete_option('relevanssi_custom_types');
}
}
function relevanssi_didyoumean($query, $pre, $post, $n = 5, $echo = true) {
global $wpdb, $relevanssi_variables, $wp_query;
$total_results = $wp_query->found_posts;
$result = "";
if ($total_results > $n) return $result;
$suggestion = "";
$suggestion_enc = "";
$exact_match = false;
if (class_exists('SpellCorrector')) {
$query = htmlspecialchars_decode($query);
$tokens = relevanssi_tokenize($query);
$sc = new SpellCorrector();
$correct = array();
foreach ($tokens as $token => $count) {
$token = trim($token);
$c = $sc->correct($token);
if ($c !== strval($token)) {
array_push($correct, $c);
$query = str_ireplace($token, $c, $query); // Replace misspelled word in query with suggestion
}
else {
$exact_match = true;
}
}
if (count($correct) > 0) {
$suggestion = $query;
$suggestion_enc = urlencode($suggestion);
}
}
if ("" == $suggestion && !$exact_match) {
$q = "SELECT query, count(query) as c, AVG(hits) as a FROM " . $relevanssi_variables['log_table'] . " WHERE hits > 1 GROUP BY query ORDER BY count(query) DESC";
$q = apply_filters('relevanssi_didyoumean_query', $q);
$data = $wpdb->get_results($q);
$distance = -1;
$closest = "";
foreach ($data as $row) {
if ($row->c < 2) break;
$lev = levenshtein($query, $row->query);
if ($lev < $distance || $distance < 0) {
if ($row->a > 0) {
$distance = $lev;
$closest = $row->query;
if ($lev == 1) break; // get the first with distance of 1 and go
}
}
}
if ($distance > 0) {
$suggestion = $closest;
$suggestion_enc = urlencode($closest);
}
}
$result = null;
if ($suggestion) {
$url = get_bloginfo('url');
$url = esc_attr(add_query_arg(array(
's' => $suggestion_enc
), $url));
$url = apply_filters('relevanssi_didyoumean_url', $url, $query, $suggestion);
// Escape the suggestion to avoid XSS attacks
$suggestion = htmlspecialchars($suggestion);
$result = apply_filters('relevanssi_didyoumean_suggestion', "$pre<a href='$url'>$suggestion</a>$post");
if ($echo) echo $result;
}
return $result;
}
function relevanssi_profile_update($user) {
if (get_option('relevanssi_index_users') == 'on') {
$update = true;
relevanssi_index_user($user, $update);
}
}
function relevanssi_edit_term($term) {
if (get_option('relevanssi_index_taxonomies') == 'on') {
$update = true;
global $wpdb;
$taxonomies = get_option('relevanssi_index_terms');
$taxonomy = $wpdb->get_var("SELECT taxonomy FROM $wpdb->term_taxonomy WHERE term_id=$term");
if (in_array($taxonomy, $taxonomies)) {
relevanssi_index_taxonomy_term($term, $taxonomy, $update);
}
}
}
function relevanssi_delete_user($user) {
global $wpdb, $relevanssi_variables;
$wpdb->query("DELETE FROM " . $relevanssi_variables['relevanssi_table'] . " WHERE item = $user AND type = 'user'");
}
function relevanssi_delete_taxonomy_term($term) {
global $wpdb, $relevanssi_variables;
$wpdb->query("DELETE FROM " . $relevanssi_variables['relevanssi_table'] . " WHERE item = $term AND type = 'taxonomy'");
}
function relevanssi_new_blog($blog_id, $user_id, $domain, $path, $site_id, $meta ) {
global $wpdb;
if (is_plugin_active_for_network('relevanssi-premium/relevanssi.php')) {
switch_to_blog($blog_id);
_relevanssi_install();
restore_current_blog();
}
}
function relevanssi_install($network_wide = false) {
global $wpdb;
if ($network_wide) {
$blogids = $wpdb->get_col($wpdb->prepare("
SELECT blog_id
FROM $wpdb->blogs
WHERE site_id = %d
AND deleted = 0
AND spam = 0
", $wpdb->siteid));
foreach ($blogids as $blog_id) {
switch_to_blog($blog_id);
_relevanssi_install();
}
restore_current_blog();
} else {
_relevanssi_install();
}
}
function _relevanssi_install() {
global $relevanssi_variables;
add_option('relevanssi_title_boost', $relevanssi_variables['title_boost_default']);
add_option('relevanssi_link_boost', $relevanssi_variables['link_boost_default']);
add_option('relevanssi_comment_boost', $relevanssi_variables['comment_boost_default']);
add_option('relevanssi_admin_search', 'off');
add_option('relevanssi_highlight', 'strong');
add_option('relevanssi_txt_col', '#ff0000');
add_option('relevanssi_bg_col', '#ffaf75');
add_option('relevanssi_css', 'text-decoration: underline; text-color: #ff0000');
add_option('relevanssi_class', 'relevanssi-query-term');
add_option('relevanssi_excerpts', 'on');
add_option('relevanssi_excerpt_length', '30');
add_option('relevanssi_excerpt_type', 'words');
add_option('relevanssi_excerpt_allowable_tags', '');
add_option('relevanssi_log_queries', 'off');
add_option('relevanssi_log_queries_with_ip', 'off');
add_option('relevanssi_cat', '0');
add_option('relevanssi_excat', '0');
add_option('relevanssi_extag', '0');
add_option('relevanssi_index_fields', '');
add_option('relevanssi_exclude_posts', ''); //added by OdditY
add_option('relevanssi_hilite_title', ''); //added by OdditY
add_option('relevanssi_highlight_docs', 'off');
add_option('relevanssi_highlight_docs_external', 'off');
add_option('relevanssi_highlight_comments', 'off');
add_option('relevanssi_index_comments', 'none'); //added by OdditY
add_option('relevanssi_show_matches', '');
add_option('relevanssi_show_matches_text', '(Search hits: %body% in body, %title% in title, %categories% in categories, %tags% in tags, %taxonomies% in other taxonomies, %comments% in comments. Score: %score%)');
add_option('relevanssi_fuzzy', 'sometimes');
add_option('relevanssi_indexed', '');
add_option('relevanssi_expand_shortcodes', 'on');
add_option('relevanssi_index_author', '');
add_option('relevanssi_implicit_operator', 'OR');
add_option('relevanssi_omit_from_logs', '');
add_option('relevanssi_synonyms', '');
add_option('relevanssi_index_excerpt', 'off');
add_option('relevanssi_index_limit', '500');
add_option('relevanssi_disable_or_fallback', 'off');
add_option('relevanssi_respect_exclude', 'on');
add_option('relevanssi_min_word_length', '3');
add_option('relevanssi_throttle', 'on');
add_option('relevanssi_throttle_limit', '500');
add_option('relevanssi_db_version', '1');
add_option('relevanssi_wpml_only_current', 'on');
add_option('relevanssi_post_type_weights', '');
add_option('relevanssi_index_users', 'off');
add_option('relevanssi_index_subscribers', 'off');
add_option('relevanssi_index_taxonomies', 'off');
add_option('relevanssi_internal_links', 'noindex');
add_option('relevanssi_word_boundaries', 'on');
add_option('relevanssi_default_orderby', 'relevance');
add_option('relevanssi_thousand_separator', '');
add_option('relevanssi_disable_shortcodes', '');
add_option('relevanssi_api_key', '');
add_option('relevanssi_index_post_types', array('post', 'page'));
add_option('relenvassi_recency_bonus', array('bonus' => '', 'days' => ''));
add_option('relevanssi_mysql_columns', '');
add_option('relevanssi_hide_post_controls', 'off');
add_option('relevanssi_index_taxonomies_list', array());
add_option('relevanssi_index_terms', array());
add_option('relevanssi_index_synonyms', 'off');
relevanssi_create_database_tables($relevanssi_variables['database_version']);
}
add_filter('query_vars', 'relevanssi_premium_query_vars');
function relevanssi_premium_query_vars($qv) {
$qv[] = 'searchblogs';
$qv[] = 'customfield_key';
$qv[] = 'customfield_value';
$qv[] = 'operator';
return $qv;
}
function relevanssi_set_operator($query) {
isset($query->query_vars['operator']) ?
$operator = $query->query_vars['operator'] :
$operator = get_option("relevanssi_implicit_operator");
return $operator;
}
function relevanssi_process_taxonomies($taxonomy, $taxonomy_term, $tax_query) {
$taxonomies = explode('|', $taxonomy);
$terms = explode('|', $taxonomy_term);
$i = 0;
foreach ($taxonomies as $taxonomy) {
$term_tax_id = null;
$taxonomy_terms = explode(',', $terms[$i]);
foreach ($taxonomy_terms as $taxonomy_term) {
if (!empty($taxonomy_term))
$tax_query[] = array('taxonomy' => $taxonomy, 'field' => 'slug', 'terms' => $taxonomy_term);
}
$i++;
}
return $tax_query;
}
/* Custom-made get_posts() replacement that creates post objects for
users and taxonomy terms. For regular posts, the function uses
a caching mechanism.
*/
function relevanssi_get_post($id) {
global $relevanssi_post_array;
$type = substr($id, 0, 2);
switch ($type) {
case 'u_':
list($throwaway, $id) = explode('_', $id);
$user = get_userdata($id);
$post = new stdClass;
$post->post_title = $user->display_name;
$post->post_content = $user->description;
$post->post_type = 'user';
$post->ID = $id;
$post->link = get_author_posts_url($id);
$post->post_status = 'publish';
$post->post_date = date("Y-m-d H:i:s");
$post->post_author = 0;
$post->post_name = '';
$post->post_excerpt = '';
$post->comment_status = '';
$post->ping_status = '';
$post->user_id = $id;
$post = apply_filters('relevanssi_user_profile_to_post', $post);
break;
case '**':
list($throwaway, $taxonomy, $id) = explode('**', $id);
$term = get_term($id, $taxonomy);
$post = new stdClass;
$post->post_title = $term->name;
$post->post_content = $term->description;
$post->post_type = $taxonomy;
$post->ID = -1;
$post->post_status = 'publish';
$post->post_date = date("Y-m-d H:i:s");
$post->link = get_term_link($term, $taxonomy);
$post->post_author = 0;
$post->post_name = '';
$post->post_excerpt = '';
$post->comment_status = '';
$post->ping_status = '';
$post->term_id = $id;
$post = apply_filters('relevanssi_taxonomy_term_to_post', $post);
break;
default:
if (isset($relevanssi_post_array[$id])) {
$post = $relevanssi_post_array[$id];
}
else {
$post = get_post($id);
}
}
return $post;
}
function relevanssi_get_multisite_post($blogid, $id) {
switch_to_blog($blogid);
$post = relevanssi_get_post($id);
restore_current_blog();
return $post;
}
function relevanssi_permalink($content, $link_post = NULL) {
if ($link_post == NULL) {
global $post;
if (isset($post->link))
$content = $post->link;
}
return $content;
}
function relevanssi_get_permalink() {
$permalink = apply_filters('relevanssi_permalink', get_permalink());
return $permalink;
}
function relevanssi_correct_query($q) {
if (class_exists('SpellCorrector')) {
$tokens = relevanssi_tokenize($q, false);
$sc = new SpellCorrector();
$correct = array();
foreach ($tokens as $token => $count) {
$c = $sc->correct($token);
if ($c !== $token) array_push($correct, $c);
}
if (count($correct) > 0) $q = implode(' ', $correct);
}
return $q;
}
function relevanssi_search_multi($multi_args) {
global $relevanssi_variables, $wpdb;
$filtered_values = apply_filters( 'relevanssi_search_filters', $multi_args );
$q = $filtered_values['q'];
isset( $filtered_values['post_type'] ) ? $post_type = $filtered_values['post_type'] : $post_type = "";
isset( $filtered_values['search_blogs'] ) ? $search_blogs = $filtered_values['search_blogs'] : $search_blogs = "";
isset( $filtered_values['operator'] ) ? $operator = $filtered_values['operator'] : $operator = "";
isset( $filtered_values['meta_query'] ) ? $meta_query = $filtered_values['meta_query'] : $meta_query = "";
$hits = array();
$remove_stopwords = false;
$terms = relevanssi_tokenize($q, $remove_stopwords);
if (count($terms) < 1) {
// Tokenizer killed all the search terms.
return $hits;
}
$terms = array_keys($terms); // don't care about tf in query
$total_hits = 0;
$title_matches = array();
$tag_matches = array();
$link_matches = array();
$comment_matches = array();
$body_matches = array();
$scores = array();
$term_hits = array();
$hitsbyweight = array();
$fuzzy = get_option('relevanssi_fuzzy');
$search_blogs = explode(",", $search_blogs);
$post_type_weights = get_option('relevanssi_post_type_weights');
$orig_blog = $wpdb->blogid;
foreach ($search_blogs as $blogid) {
switch_to_blog($blogid);
$relevanssi_table = $wpdb->prefix . "relevanssi";
$query_join = "";
$query_restrictions = "";
if ($post_type) {
if ($post_type == -1) $post_type = null; // Facetious sets post_type to -1 if not selected
if (!is_array($post_type)) {
$post_types = esc_sql(explode(',', $post_type));
}
else {
$post_types = esc_sql($post_type);
}
$__post_type = count($post_types) ? "'" . implode( "', '", $post_types) . "'" : 'NULL';
$query_restrictions .= " AND (doc IN (SELECT DISTINCT(ID) FROM $wpdb->posts
WHERE post_type IN ($__post_type)) OR (doc = -1))";
}
$query_restrictions = apply_filters('relevanssi_where', $query_restrictions); // Charles St-Pierre
// handle the meta query
if ( ! empty( $meta_query ) ) {
$mq = new WP_Meta_Query();
$mq->parse_query_vars( array( 'meta_query' => $meta_query ) );
$meta_sql = $mq->get_sql( 'post', 'relevanssi', 'doc' );
if ( $meta_sql ) {
$query_join .= $meta_sql['join'];
$query_restrictions .= $meta_sql['where'];
}
}
$D = $wpdb->get_var("SELECT COUNT(DISTINCT(doc)) FROM $relevanssi_table");
$no_matches = true;
if ("always" == $fuzzy) {
$o_term_cond = "(term LIKE '%#term#' OR term LIKE '#term#%') ";
}
else {
$o_term_cond = " term = '#term#' ";
}
$min_length = get_option('relevanssi_min_word_length');
$search_again = false;
do {
foreach ($terms as $term) {
$term = trim($term); // numeric search terms will start with a space
if (strlen($term) < $min_length) continue;
if (method_exists($wpdb, 'esc_like')) {
$term = esc_sql($wpdb->esc_like($term));
}
else {
// Compatibility for pre-4.0 WordPress
$term = esc_sql(like_escape($term));
}
$term_cond = str_replace('#term#', $term, $o_term_cond);
$query = "SELECT *, title + content + comment + tag + link + author + category + excerpt + taxonomy + customfield AS tf
FROM $relevanssi_table AS relevanssi $query_join WHERE $term_cond $query_restrictions";
$query = apply_filters('relevanssi_query_filter', $query);
// Clean: $term is escaped, as are $query_restrictions
$matches = $wpdb->get_results($query);
if (count($matches) < 1) {
continue;
}
else {
$no_matches = false;
}
$total_hits += count($matches);
$query = "SELECT COUNT(DISTINCT(doc)) FROM $relevanssi_table WHERE $term_cond $query_restrictions";
$query = apply_filters('relevanssi_df_query_filter', $query);
$df = $wpdb->get_var($query);
// Clean: $term is escaped, as are $query_restrictions
if ($df < 1 && "sometimes" == $fuzzy) {
$query = "SELECT COUNT(DISTINCT(doc)) FROM $relevanssi_table
WHERE (term LIKE '%$term' OR term LIKE '$term%') $query_restrictions";
$query = apply_filters('relevanssi_df_query_filter', $query);
$df = $wpdb->get_var($query);
// Clean: $term is escaped, as are $query_restrictions
}
$title_boost = floatval(get_option('relevanssi_title_boost'));
isset($post_type_weights['post_tag']) ? $tag_boost = $post_type_weights['post_tag'] : 1;
$link_boost = floatval(get_option('relevanssi_link_boost'));
$comment_boost = floatval(get_option('relevanssi_comment_boost'));
$doc_weight = array();
$scores = array();
$term_hits = array();
$idf = log($D / (1 + $df));
foreach ($matches as $match) {
if ('user' == $match->type) {
$match->doc = 'u_' . $match->item;
}
else if (!in_array($match->type, array('post', 'attachment'))) {
$match->doc = '**' . $match->type . '**' . $match->item;
}
$match->tf =
$match->title * $title_boost +
$match->content +
$match->comment * $comment_boost +
$match->tag * $tag_boost +
$match->link * $link_boost +
$match->author +
$match->category +
$match->excerpt +
$match->taxonomy +
$match->customfield;
$term_hits[$match->doc][$term] =
$match->title +
$match->content +
$match->comment +
$match->tag +
$match->link +
$match->author +
$match->category +
$match->excerpt +
$match->taxonomy +
$match->customfield;
if ($idf < 1) $idf = 1;
$match->weight = $match->tf * $idf;
$type = relevanssi_get_post_type($match->doc);
if (!empty($post_type_weights[$type])) {
$match->weight = $match->weight * $post_type_weights[$type];
}
$match = apply_filters('relevanssi_match', $match, $idf, $term);
if ($match->weight == 0) continue; // the filters killed the match
$post_ok = true;
$post_ok = apply_filters('relevanssi_post_ok', $post_ok, $match->doc);
$doc_terms[$match->doc][$term] = true; // count how many terms are matched to a doc
isset($doc_weight[$match->doc]) ?
$doc_weight[$match->doc] += $match->weight :
$doc_weight[$match->doc] = $match->weight;
isset($scores[$match->doc]) ?
$scores[$match->doc] += $match->weight :
$scores[$match->doc] = $match->weight;
$body_matches[$match->doc] = $match->content;
$title_matches[$match->doc] = $match->title;
$link_matches[$match->doc] = $match->link;
$tag_matches[$match->doc] = $match->tag;
$comment_matches[$match->doc] = $match->comment;
}
}
if ($no_matches) {
if ($search_again) {
// no hits even with fuzzy search!
$search_again = false;
}
else {
if ("sometimes" == $fuzzy) {
$search_again = true;
$o_term_cond = "(term LIKE '%#term#' OR term LIKE '#term#%') ";
}
}
}
else {
$search_again = false;
}
} while ($search_again);
$strip_stops = true;
$terms_without_stops = array_keys(relevanssi_tokenize(implode(' ', $terms), $strip_stops));
$total_terms = count($terms_without_stops);
if (isset($doc_weight) && count($doc_weight) > 0 && !$no_matches) {
arsort($doc_weight);
$i = 0;
foreach ($doc_weight as $doc => $weight) {
if (count($doc_terms[$doc]) < $total_terms && $operator == "AND") {
// AND operator in action:
// doc didn't match all terms, so it's discarded
continue;
}
$status = relevanssi_get_post_status($doc);
$post_ok = true;
if ('private' == $status) {
$post_ok = false;
if (function_exists('awp_user_can')) {
// Role-Scoper
$current_user = wp_get_current_user();
$post_ok = awp_user_can('read_post', $doc, $current_user->ID);
}
else {
// Basic WordPress version
$type = get_post_type($doc);
$cap = 'read_private_' . $type . 's';
if (current_user_can($cap)) {
$post_ok = true;
}
}
} else if ( 'publish' != $status ) {
$post_ok = false;
}
if ($post_ok) {
$post_object = relevanssi_get_multisite_post($blogid, $doc);
$post_object->blog_id = $blogid;
$object_id = $blogid . '|' . $doc;
$hitsbyweight[$object_id] = $weight;
$post_objects[$object_id] = $post_object;
}
}
}
restore_current_blog();
}
arsort($hitsbyweight);
$i = 0;
foreach ($hitsbyweight as $hit => $weight) {
$hit = $post_objects[$hit];
$hits[intval($i)] = $hit;
$hits[intval($i)]->relevance_score = round($weight, 2);
$i++;
}
if (count($hits) < 1) {
if ($operator == "AND" AND get_option('relevanssi_disable_or_fallback') != 'on') {
$or_args = $multi_args;
$or_args['operator'] = "OR";
$return = relevanssi_search_multi($or_args);
extract($return);
}
}
global $wp;
$default_order = get_option('relevanssi_default_orderby', 'relevance');
isset($wp->query_vars["orderby"]) ? $orderby = $wp->query_vars["orderby"] : $orderby = $default_order;
isset($wp->query_vars["order"]) ? $order = $wp->query_vars["order"] : $order = 'desc';
if ($orderby != 'relevance')
relevanssi_object_sort($hits, $orderby, $order);
$return = array('hits' => $hits, 'body_matches' => $body_matches, 'title_matches' => $title_matches,
'tag_matches' => $tag_matches, 'comment_matches' => $comment_matches, 'scores' => $scores,
'term_hits' => $term_hits, 'query' => $q, 'link_matches' => $link_matches);
return $return;
}
function relevanssi_recognize_negatives($q) {
$term = strtok($q, " ");
$negative_terms = array();
while ($term !== false) {
if (substr($term, 0, 1) == '-') array_push($negative_terms, substr($term, 1));
$term = strtok(" ");
}
return $negative_terms;
}
function relevanssi_recognize_positives($q) {
$term = strtok($q, " ");
$positive_terms = array();
while ($term !== false) {
if (substr($term, 0, 1) == '+') {
$term_part = substr($term, 1);
if (!empty($term_part)) array_push($positive_terms, $term_part);
// to avoid problems with just plus signs
}
$term = strtok(" ");
}
return $positive_terms;
}
function relevanssi_negatives_positives($negative_terms, $positive_terms, $relevanssi_table) {
$query_restrictions = "";
if ($negative_terms) {
for ($i = 0; $i < sizeof($negative_terms); $i++) {
$negative_terms[$i] = "'" . esc_sql($negative_terms[$i]) . "'";
}
$negatives = implode(',', $negative_terms);
$query_restrictions .= " AND doc NOT IN (SELECT DISTINCT(doc) FROM $relevanssi_table WHERE term IN ($negatives))";
// Clean: escaped
}
if ($positive_terms) {
for ($i = 0; $i < sizeof($positive_terms); $i++) {
$positive_term = esc_sql($positive_terms[$i]);
$query_restrictions .= " AND doc IN (SELECT DISTINCT(doc) FROM $relevanssi_table WHERE term = '$positive_term')";
// Clean: escaped
}
}
return $query_restrictions;
}
function relevanssi_get_recency_bonus() {
$recency_bonus = get_option('relevanssi_recency_bonus');
if (empty($recency_bonus['days']) OR empty($recency_bonus['bonus'])) {
$recency_bonus = false;
$recency_cutoff_date = false;
}
if ($recency_bonus) {
$recency_cutoff_date = time() - 60 * 60 * 24 * $recency_bonus['days'];
}
return array($recency_bonus, $recency_cutoff_date);
}
function relevanssi_get_internal_links($text) {
$links = array();
if ( preg_match_all( '@<a[^>]*?href="(' . home_url() . '[^"]*?)"[^>]*?>(.*?)</a>@siu', $text, $m ) ) {
foreach ( $m[1] as $i => $link ) {
if ( !isset( $links[$link] ) )
$links[$link] = '';
$links[$link] .= ' ' . $m[2][$i];
}
}
if ( preg_match_all( '@<a[^>]*?href="(/[^"]*?)"[^>]*?>(.*?)</a>@siu', $text, $m ) ) {
foreach ( $m[1] as $i => $link ) {
if ( !isset( $links[$link] ) )
$links[$link] = '';
$links[$link] .= ' ' . $m[2][$i];
}
}
if (count($links) > 0)
return $links;
return false;
}
function relevanssi_strip_internal_links($text) {
$text = preg_replace(
array(
'@<a[^>]*?href="' . home_url() . '[^>]*?>.*?</a>@siu',
),
' ',
$text );
$text = preg_replace(
array(
'@<a[^>]*?href="/[^>]*?>.*?</a>@siu',
),
' ',
$text );
return $text;
}
function relevanssi_nonlocal_highlighting($referrer, $content, $query) {
if (get_option('relevanssi_highlight_docs_external', 'off') != 'off') {
$query = relevanssi_add_synonyms($query);
if (strpos($referrer, 'google') !== false) {
$content = relevanssi_highlight_terms($content, $query);
} elseif (strpos($referrer, 'bing') !== false) {
$content = relevanssi_highlight_terms($content, $query);
} elseif (strpos($referrer, 'ask') !== false) {