-
Notifications
You must be signed in to change notification settings - Fork 36
/
solr-for-wordpress.php
1499 lines (1286 loc) · 55.4 KB
/
solr-for-wordpress.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: Solr for WordPress
Plugin URI: http://wordpress.org/extend/plugins/solr-for-wordpress/
Donate link: http://www.mattweber.org
Description: Indexes, removes, and updates documents in the Solr search engine.
Version: 0.5.1
Author: Matt Weber
Author URI: http://www.mattweber.org
*/
/*
Copyright (c) 2011 Matt Weber
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
global $wp_version, $version;
$version = '0.5.1';
$errmsg = __('Solr for WordPress requires WordPress 3.0 or greater. ', 'solr4wp');
if (version_compare($wp_version, '3.0', '<')) {
exit ($errmsg);
}
require_once(dirname(__FILE__) . '/SolrPhpClient/Apache/Solr/Service.php');
function s4w_get_option() {
$indexall = FALSE;
$option = 'plugin_s4w_settings';
if (is_multisite()) {
$plugin_s4w_settings = get_site_option($option);
$indexall = $plugin_s4w_settings['s4w_index_all_sites'];
}
if ($indexall) {
return get_site_option($option);
} else {
return get_option($option);
}
}
function s4w_update_option($optval) {
$indexall = FALSE;
$option = 'plugin_s4w_settings';
if (is_multisite()) {
$plugin_s4w_settings = get_site_option($option);
$indexall = $plugin_s4w_settings['s4w_index_all_sites'];
}
if ($indexall) {
update_site_option($option, $optval);
} else {
update_option($option, $optval);
}
}
/**
* Connect to the solr service
* @param $server_id string/int its either master or array index
* @return solr service object
*/
function s4w_get_solr($server_id = NULL) {
# get the connection options
$plugin_s4w_settings = s4w_get_option();
//if the provided server_id does not exist use the default id 'master'
if(!$plugin_s4w_settings['s4w_server']['info'][$server_id]['host']) {
$server_id = $plugin_s4w_settings['s4w_server']['type']['update'];
}
$host = $plugin_s4w_settings['s4w_server']['info'][$server_id]['host'];
$port = $plugin_s4w_settings['s4w_server']['info'][$server_id]['port'];
$path = $plugin_s4w_settings['s4w_server']['info'][$server_id]['path'];
# double check everything has been set
if ( ! ($host and $port and $path) ) {
syslog(LOG_ERR,"host, port or path are empty, host:$host, port:$port, path:$path");
return NULL;
}
# create the solr service object
$solr = new Apache_Solr_Service($host, $port, $path);
return $solr;
}
/**
* check if the server by pinging it
* @param server if wanting to ping a different
* server than default provide name
* @return boolean
*/
function s4w_ping_server($server_id = NULL) {
$solr = s4w_get_solr($server);
$ping = FALSE;
# if we want to check if the server is alive, ping it
if ($solr->ping()) {
$ping = TRUE;
}
return $ping;
}
function s4w_build_document( $post_info, $domain = NULL, $path = NULL) {
global $blog_id;
global $current_blog;
$doc = NULL;
$plugin_s4w_settings = s4w_get_option();
$exclude_ids = $plugin_s4w_settings['s4w_exclude_pages'];
$categoy_as_taxonomy = $plugin_s4w_settings['s4w_cat_as_taxo'];
$index_comments = $plugin_s4w_settings['s4w_index_comments'];
$index_custom_fields = $plugin_s4w_settings['s4w_index_custom_fields'];
if ($post_info) {
# check if we need to exclude this document
if (is_multisite() && in_array($current_blog->domain . $post_info->ID, (array)$exclude_ids)) {
return NULL;
} else if ( !is_multisite() && in_array($post_info->ID, (array)$exclude_ids) ) {
return NULL;
}
$doc = new Apache_Solr_Document();
$auth_info = get_userdata( $post_info->post_author );
# wpmu specific info
if (is_multisite()) {
// if we get here we expect that we've "switched" what blog we're running
// as
if ($domain == NULL)
$domain = $current_blog->domain;
if ($path == NULL)
$path = $current_blog->path;
$blogid = get_blog_id_from_url($domain, $path);
$doc->setField( 'id', $domain . $path . $post_info->ID );
$doc->setField( 'permalink', get_blog_permalink($blogid, $post_info->ID));
$doc->setField( 'blogid', $blogid );
$doc->setField( 'blogdomain', $domain );
$doc->setField( 'blogpath', $path );
$doc->setField( 'wp', 'multisite');
} else {
$doc->setField( 'id', $post_info->ID );
$doc->setField( 'permalink', get_permalink( $post_info->ID ) );
$doc->setField( 'wp', 'wp');
}
$numcomments = 0;
if ($index_comments) {
$comments = get_comments("status=approve&post_id={$post_info->ID}");
foreach ($comments as $comment) {
$doc->addField( 'comments', $comment->comment_content );
$numcomments += 1;
}
}
$doc->setField( 'title', $post_info->post_title );
$doc->setField( 'content', strip_tags($post_info->post_content) );
// rawcontent strips out characters lower than 0x20
$doc->setField( 'rawcontent', strip_tags(preg_replace('/[^(\x20-\x7F)\x0A]*/','', $post_info->post_content)));
// contentnoshortcodes also strips characters below 0x20 but also strips shortcodes
// used in WP to add images or other content, useful if you're pulling this data
// into another system
//
// For example
// [caption id="attachment_92495" align="alignright" width="160" caption="Duane Sand"][/caption] FARGO - Republican U.S. Senate...
//
// Will become
// FARGO - Republican U.S. Senate...
$doc->setField( 'contentnoshortcodes', strip_tags(preg_replace('/[^(\x20-\x7F)\x0A]*/','', strip_tags(strip_shortcodes($post_info->post_content)))));
$doc->setField( 'numcomments', $numcomments );
$doc->setField( 'author', $auth_info->display_name );
$doc->setField( 'author_s', get_author_posts_url($auth_info->ID, $auth_info->user_nicename));
$doc->setField( 'type', $post_info->post_type );
$doc->setField( 'date', s4w_format_date($post_info->post_date_gmt) );
$doc->setField( 'modified', s4w_format_date($post_info->post_modified_gmt) );
$doc->setField( 'displaydate', $post_info->post_date );
$doc->setField( 'displaymodified', $post_info->post_modified );
$categories = get_the_category($post_info->ID);
if ( ! $categories == NULL ) {
foreach( $categories as $category ) {
if ($categoy_as_taxonomy) {
$doc->addField('categories', get_category_parents($category->cat_ID, FALSE, '^^'));
} else {
$doc->addField('categories', $category->cat_name);
}
}
}
//get all the taxonomy names used by wp
$taxonomies = (array)get_taxonomies(array('_builtin'=>FALSE),'names');
foreach($taxonomies as $parent) {
$terms = get_the_terms( $post_info->ID, $parent );
if ((array) $terms === $terms) {
//we are creating *_taxonomy as dynamic fields using our schema
//so lets set up all our taxonomies in that format
$parent = $parent."_taxonomy";
foreach ($terms as $term) {
$doc->addField($parent, $term->name);
}
}
}
$tags = get_the_tags($post_info->ID);
if ( ! $tags == NULL ) {
foreach( $tags as $tag ) {
$doc->addField('tags', $tag->name);
}
}
if (count($index_custom_fields)>0 && count($custom_fields = get_post_custom($post_info->ID))) {
foreach ((array)$index_custom_fields as $field_name ) {
$field = (array)$custom_fields[$field_name];
foreach ( $field as $key => $value ) {
$doc->addField($field_name . '_str', $value);
$doc->addField($field_name . '_srch', $value);
}
}
}
} else {
// this will fire during blog sign up on multisite, not sure why
_e('Post Information is NULL', 'solr4wp');
}
syslog(LOG_ERR, "built document for $blog_id - $domain$path with title " . $post_info->post_title .
" and status of " . $post_info->post_status);
return $doc;
}
function s4w_format_date( $thedate ) {
$datere = '/(\d{4}-\d{2}-\d{2})\s(\d{2}:\d{2}:\d{2})/';
$replstr = '${1}T${2}Z';
return preg_replace($datere, $replstr, $thedate);
}
function s4w_post( $documents, $commit = TRUE, $optimize = FALSE) {
try {
$solr = s4w_get_solr();
if ( ! $solr == NULL ) {
if ($documents) {
syslog(LOG_ERR,"posting " . count($documents) . " documents for blog:" . get_bloginfo('wpurl'));
$solr->addDocuments( $documents );
}
if ($commit) {
syslog(LOG_ERR,"telling Solr to commit");
$solr->commit();
}
if ($optimize) {
$solr->optimize();
}
}
else {
syslog(LOG_ERR, "failed to get a solr instance created");
}
} catch ( Exception $e ) {
syslog(LOG_ERR,"ERROR: " . $e->getMessage());
//echo $e->getMessage();
}
}
function s4w_optimize() {
try {
$solr = s4w_get_solr();
if ( ! $solr == NULL ) {
$solr->optimize();
}
} catch ( Exception $e ) {
syslog(LOG_ERR,$e->getMessage());
}
}
function s4w_delete( $doc_id ) {
try {
$solr = s4w_get_solr();
if ( ! $solr == NULL ) {
$solr->deleteById( $doc_id );
$solr->commit();
}
} catch ( Exception $e ) {
syslog(LOG_ERR,$e->getMessage());
}
}
function s4w_delete_all() {
try {
$solr = s4w_get_solr();
if ( ! $solr == NULL ) {
$solr->deleteByQuery( '*:*' );
$solr->commit();
}
} catch ( Exception $e ) {
echo $e->getMessage();
}
}
function s4w_delete_blog($blogid) {
try {
$solr = s4w_get_solr();
if ( ! $solr == NULL ) {
$solr->deleteByQuery( "blogid:{$blogid}" );
$solr->commit();
}
} catch ( Exception $e ) {
echo $e->getMessage();
}
}
function s4w_load_blog_all($blogid) {
global $wpdb;
$documents = array();
$cnt = 0;
$batchsize = 10;
$bloginfo = get_blog_details($blogid, FALSE);
if ($bloginfo->public && !$bloginfo->archived && !$bloginfo->spam && !$bloginfo->deleted) {
$postids = $wpdb->get_results("SELECT ID FROM {$wpdb->base_prefix}{$blogid}_posts WHERE post_status = 'publish';");
for ($idx = 0; $idx < count($postids); $idx++) {
$postid = $ids[$idx];
$documents[] = s4w_build_document( get_blog_post($blogid, $postid->ID), $bloginfo->domain, $bloginfo->path );
$cnt++;
if ($cnt == $batchsize) {
s4w_post($documents);
$cnt = 0;
$documents = array();
}
}
if ($documents) {
s4w_post($documents);
}
}
}
function s4w_handle_modified( $post_id ) {
global $current_blog;
$post_info = get_post( $post_id );
$plugin_s4w_settings = s4w_get_option();
$index_pages = $plugin_s4w_settings['s4w_content']['index']['page'];
$index_posts = $plugin_s4w_settings['s4w_content']['index']['post'];
s4w_handle_status_change( $post_id, $post_info );
if (($index_pages && $post_info->post_type == 'page' && $post_info->post_status == 'publish') ||
($index_posts && $post_info->post_type == 'post' && $post_info->post_status == 'publish')) {
# make sure this blog is not private or a spam if indexing on a multisite install
if (is_multisite() && ($current_blog->public != 1 || $current_blog->spam == 1 || $current_blog->archived == 1)) {
return;
}
$docs = array();
$doc = s4w_build_document( $post_info , $current_blog->domain , $current_blog->path );
if ( $doc ) {
$docs[] = $doc;
s4w_post( $docs );
}
}
}
function s4w_handle_status_change( $post_id, $post_info = null ) {
global $current_blog;
if ( ! $post_info ){
$post_info = get_post( $post_id );
}
$plugin_s4w_settings = s4w_get_option();
$private_page = $plugin_s4w_settings['s4w_private_page'];
$private_post = $plugin_s4w_settings['s4w_private_post'];
if ( ($private_page && $post_info->post_type == 'page') || ($private_post && $post_info->post_type == 'post') ) {
/**
* We need to check if the status of the post has changed.
* Inline edits won't have the prev_status of original_post_status,
* instead we check of the _inline_edit variable is present in the $_POST variable
*/
if ( ($_POST['prev_status'] == 'publish' || $_POST['original_post_status'] == 'publish' ||
( isset( $_POST['_inline_edit'] ) && !empty( $_POST['_inline_edit']) ) ) &&
($post_info->post_status == 'draft' || $post_info->post_status == 'private') ) {
if (is_multisite()) {
s4w_delete( $current_blog->domain . $current_blog->path . $post_info->ID );
} else {
s4w_delete( $post_info->ID );
}
}
}
}
function s4w_handle_delete( $post_id ) {
global $current_blog;
$post_info = get_post( $post_id );
syslog(LOG_ERR,"deleting post titled '" . $post_info->post_title . "' for " . $current_blog->domain . $current_blog->path);
$plugin_s4w_settings = s4w_get_option();
$delete_page = $plugin_s4w_settings['s4w_delete_page'];
$delete_post = $plugin_s4w_settings['s4w_delete_post'];
if ( ($delete_page && $post_info->post_type == 'page') || ($delete_post && $post_info->post_type == 'post') ) {
if (is_multisite()) {
s4w_delete( $current_blog->domain . $current_blog->path . $post_info->ID );
} else {
s4w_delete( $post_info->ID );
}
}
}
function s4w_handle_deactivate_blog($blogid) {
s4w_delete_blog($blogid);
}
function s4w_handle_activate_blog($blogid) {
s4w_apply_config_to_blog($blogid);
s4w_load_blog_all($blogid);
}
function s4w_handle_archive_blog($blogid) {
s4w_delete_blog($blogid);
}
function s4w_handle_unarchive_blog($blogid) {
s4w_apply_config_to_blog($blogid);
s4w_load_blog_all($blogid);
}
function s4w_handle_spam_blog($blogid) {
s4w_delete_blog($blogid);
}
function s4w_handle_unspam_blog($blogid) {
s4w_apply_config_to_blog($blogid);
s4w_load_blog_all($blogid);
}
function s4w_handle_delete_blog($blogid) {
s4w_delete_blog($blogid);
}
function s4w_handle_new_blog($blogid) {
s4w_apply_config_to_blog($blogid);
s4w_load_blog_all($blogid);
}
/**
* This function indexes all the different content types.
* This does not include attachments and revisions
*
* @param $prev
* @param $type what content to index: post type machine name or all content.
* @return string (json reply)
*/
function s4w_load_all_posts($prev, $type = 'all') {
global $wpdb, $current_blog, $current_site;
$documents = array();
$cnt = 0;
$batchsize = 250;
$last = "";
$found = FALSE;
$end = FALSE;
$percent = 0;
//multisite logic is decided s4w_get_option
$plugin_s4w_settings = s4w_get_option();
$blog_id = $blog->blog_id;
//retrieve the post types that can be indexed
$indexable_content = $plugin_s4w_settings['s4w_content']['index'];
$indexable_type = array_keys($indexable_content);
//if the provided $type is not allowed to be index, lets stop
if (!in_array($type,$indexable_type) && $type != 'all') {
return false;
}
//lets setup our where clause to find the appropriate posts
$where_and = ($type == 'all') ?"AND post_type IN ('".implode("', '", $indexable_type). "')" : " AND post_type = '$type'";
if ($plugin_s4w_settings['s4w_index_all_sites']) {
// there is potential for this to run for an extended period of time, depending on the # of blgos
syslog(LOG_ERR,"starting batch import, setting max execution time to unlimited");
ini_set('memory_limit', '1024M');
set_time_limit(0);
// get a list of blog ids
$bloglist = $wpdb->get_col("SELECT * FROM {$wpdb->base_prefix}blogs WHERE spam = 0 AND deleted = 0", 0);
syslog(LOG_ERR,"pushing posts from " . count($bloglist) . " blogs into Solr");
foreach ($bloglist as $bloginfo) {
// for each blog we need to import we get their id
// and tell wordpress to switch to that blog
$blog_id = trim($bloginfo);
syslog(LOG_ERR,"switching to blogid $blog_id");
// attempt to save some memory by flushing wordpress's cache
wp_cache_flush();
// everything just works better if we tell wordpress
// to switch to the blog we're using, this is a multi-site
// specific function
switch_to_blog($blog_id);
// now we actually gather the blog posts
$postids = $wpdb->get_results("SELECT ID FROM {$wpdb->base_prefix}{$bloginfo}_posts WHERE post_status = 'publish' $where_and ORDER BY ID;");
$postcount = count($postids);
syslog(LOG_ERR,"building $postcount documents for " . substr(get_bloginfo('wpurl'),7));
for ($idx = 0; $idx < $postcount; $idx++) {
$postid = $postids[$idx]->ID;
$last = $postid;
$percent = (floatval($idx) / floatval($postcount)) * 100;
if ($prev && !$found) {
if ($postid === $prev) {
$found = TRUE;
}
continue;
}
if ($idx === $postcount - 1) {
$end = TRUE;
}
// using wpurl is better because it will return the proper
// URL for the blog whether it is a subdomain install or otherwise
$documents[] = s4w_build_document( get_blog_post($blog_id, $postid), substr(get_bloginfo('wpurl'),7), $current_site->path );
$cnt++;
if ($cnt == $batchsize) {
s4w_post( $documents, false, false);
s4w_post(false, true, false);
wp_cache_flush();
$cnt = 0;
$documents = array();
}
}
// post the documents to Solr
// and reset the batch counters
s4w_post( $documents, false, false);
s4w_post(false, true, false);
$cnt = 0;
$documents = array();
syslog(LOG_ERR,"finished building $postcount documents for " . substr(get_bloginfo('wpurl'),7));
wp_cache_flush();
}
// done importing so lets switch back to the proper blog id
restore_current_blog();
} else {
$posts = $wpdb->get_results("SELECT ID FROM $wpdb->posts WHERE post_status = 'publish' $where_and ORDER BY ID;" );
$postcount = count($posts);
for ($idx = 0; $idx < $postcount; $idx++) {
$postid = $posts[$idx]->ID;
$last = $postid;
$percent = (floatval($idx) / floatval($postcount)) * 100;
if ($prev && !$found) {
if ($postid === $prev) {
$found = TRUE;
}
continue;
}
if ($idx === $postcount - 1) {
$end = TRUE;
}
$documents[] = s4w_build_document( get_post($postid) );
$cnt++;
if ($cnt == $batchsize) {
s4w_post( $documents, FALSE, FALSE);
$cnt = 0;
$documents = array();
wp_cache_flush();
break;
}
}
}
if ( $documents ) {
s4w_post( $documents , FALSE, FALSE);
}
if ($end) {
s4w_post(FALSE, TRUE, FALSE);
printf("{\"type\": \"%s\", \"last\": \"%s\", \"end\": true, \"percent\": \"%.2f\"}", $type, $last, $percent);
} else {
printf("{\"type\": \"%s\", \"last\": \"%s\", \"end\": false, \"percent\": \"%.2f\"}", $type, $last, $percent);
}
}
function s4w_search_form() {
$sort = $_GET['sort'];
$order = $_GET['order'];
$server = $_GET['server'];
if ($sort == 'date') {
$sortval = __('<option value="score">Score</option><option value="date" selected="selected">Date</option><option value="modified">Last Modified</option>');
} else if ($sort == 'modified') {
$sortval = __('<option value="score">Score</option><option value="date">Date</option><option value="modified" selected="selected">Last Modified</option>');
} else {
$sortval = __('<option value="score" selected="selected">Score</option><option value="date">Date</option><option value="modified">Last Modified</option>');
}
if ($order == 'asc') {
$orderval = __('<option value="desc">Descending</option><option value="asc" selected="selected">Ascending</option>');
} else {
$orderval = __('<option value="desc" selected="selected">Descending</option><option value="asc">Ascending</option>');
}
//if server id has been defined keep hold of it
if($server) {
$serverval = '<input name="server" type="hidden" value="'.$server.'" />';
}
$form = __('<form name="searchbox" method="get" id="searchbox" action=""><input type="text" id="qrybox" name="s" value="%s"/><input type="submit" id="searchbtn" /><label for="sortselect" id="sortlabel">Sort By:</label><select name="sort" id="sortselect">%s</select><label for="orderselect" id="orderlabel">Order By:</label><select name="order" id="orderselect">%s</select>%s</form>');
printf($form, htmlspecialchars(stripslashes($_GET['s'])), $sortval, $orderval,$serverval);
}
function s4w_search_results() {
$qry = stripslashes($_GET['s']);
$offset = $_GET['offset'];
$count = $_GET['count'];
$fq = $_GET['fq'];
$sort = $_GET['sort'];
$order = $_GET['order'];
$isdym = $_GET['isdym'];
$server = $_GET['server'];
$plugin_s4w_settings = s4w_get_option();
$output_info = $plugin_s4w_settings['s4w_output_info'];
$output_pager = $plugin_s4w_settings['s4w_output_pager'];
$output_facets = $plugin_s4w_settings['s4w_output_facets'];
$results_per_page = $plugin_s4w_settings['s4w_num_results'];
$categoy_as_taxonomy = $plugin_s4w_settings['s4w_cat_as_taxo'];
$dym_enabled = $plugin_s4w_settings['s4w_enable_dym'];
$out = array();
if ( ! $qry ) {
$qry = '';
}
//if server value has been set lets set it up here
// and add it to all the search urls henceforth
if ($server) {
$serverval = '&server='.$server;
}
# set some default values
if ( ! $offset ) {
$offset = 0;
}
# only use default if not specified in post information
if ( ! $count ) {
$count = $results_per_page;
}
if ( ! $fq ) {
$fq = '';
}
if ( $sort && $order ) {
$sortby = $sort . ' ' . $order;
} else {
$sortby = '';
$order = '';
}
if ( ! $isdym ) {
$isdym = 0;
}
$fqstr = '';
$fqitms = split('\|\|', stripslashes($fq));
$selectedfacets = array();
foreach ($fqitms as $fqitem) {
if ($fqitem) {
$splititm = split(':', $fqitem, 2);
$selectedfacet = array();
$selectedfacet['name'] = sprintf(__("%s:%s"), ucwords(preg_replace('/_str$/i', '', $splititm[0])), str_replace("^^", "/", $splititm[1]));
$removelink = '';
foreach($fqitms as $fqitem2) {
if ($fqitem2 && !($fqitem2 === $fqitem)) {
$splititm2 = split(':', $fqitem2, 2);
$removelink = $removelink . urlencode('||') . $splititm2[0] . ':' . urlencode($splititm2[1]);
}
}
if ($removelink) {
$selectedfacet['removelink'] = htmlspecialchars(sprintf(__("?s=%s&fq=%s"), urlencode($qry), $removelink));
} else {
$selectedfacet['removelink'] = htmlspecialchars(sprintf(__("?s=%s"), urlencode($qry)));
}
//if server is set add it on the end of the url
$selectedfacet['removelink'] .=$serverval;
$fqstr = $fqstr . urlencode('||') . $splititm[0] . ':' . urlencode($splititm[1]);
$selectedfacets[] = $selectedfacet;
}
}
if ($qry) {
$results = s4w_query( $qry, $offset, $count, $fqitms, $sortby, $server);
if ($results) {
$response = $results->response;
$header = $results->responseHeader;
$teasers = get_object_vars($results->highlighting);
$didyoumean = $results->spellcheck->suggestions->collation;
if ($output_info) {
$out['hits'] = sprintf(__("%d"), $response->numFound);
$out['qtime'] = sprintf(__("%.3f"), $header->QTime/1000);
if ($didyoumean && !$isdym && $dym_enabled) {
$dymout = array();
$dymout['term'] = htmlspecialchars($didyoumean);
$dymout['link'] = htmlspecialchars(sprintf(__("?s=%s&isdym=1"), urlencode($didyoumean)));
//if server is set add it on the end of the url
$selectedfacet['removelink'] .=$serverval;
$out['dym'] = $dymout.$serverval;
}
}
if ($output_pager) {
# calculate the number of pages
$numpages = ceil($response->numFound / $count);
$currentpage = ceil($offset / $count) + 1;
$pagerout = array();
if ($numpages == 0) {
$numpages = 1;
}
foreach (range(1, $numpages) as $pagenum) {
if ( $pagenum != $currentpage ) {
$offsetnum = ($pagenum - 1) * $count;
$pageritm = array();
$pageritm['page'] = sprintf(__("%d"), $pagenum);
$pagerlink = sprintf(__("?s=%s&offset=%d&count=%d"), urlencode($qry), $offsetnum, $count);
if ($order != "")
$pagerlink .= sprintf("&order=%s",$order);
if ($sort != "")
$pagerlink .= sprintf("&sort=%s", $sort);
if($fqstr) $pagerlink .= '&fq=' . $fqstr;
$pageritm['link'] = htmlspecialchars($pagerlink);
//if server is set add it on the end of the url
$selectedfacet['removelink'] .=$serverval;
$pagerout[] = $pageritm;
} else {
$pageritm = array();
$pageritm['page'] = sprintf(__("%d"), $pagenum);
$pageritm['link'] = "";
$pagerout[] = $pageritm;
}
}
$out['pager'] = $pagerout;
}
if ($output_facets) {
# handle facets
$facetout = array();
if($results->facet_counts) {
foreach ($results->facet_counts->facet_fields as $facetfield => $facet) {
if ( ! get_object_vars($facet) ) {
continue;
}
$facetinfo = array();
$facetitms = array();
$facetinfo['name'] = ucwords(preg_replace('/_str$/i', '', $facetfield));
# categories is a taxonomy
if ($categoy_as_taxonomy && $facetfield == 'categories') {
# generate taxonomy and counts
$taxo = array();
foreach ($facet as $facetval => $facetcnt) {
$taxovals = explode('^^', rtrim($facetval, '^^'));
$taxo = s4w_gen_taxo_array($taxo, $taxovals);
}
$facetitms = s4w_get_output_taxo($facet, $taxo, '', $fqstr.$serverval, $facetfield);
} else {
foreach ($facet as $facetval => $facetcnt) {
$facetitm = array();
$facetitm['count'] = sprintf(__("%d"), $facetcnt);
$facetitm['link'] = htmlspecialchars(sprintf(__('?s=%s&fq=%s:%s%s', 'solr4wp'), urlencode($qry), $facetfield, urlencode('"' . $facetval . '"'), $fqstr));
//if server is set add it on the end of the url
$facetitm['link'] .=$serverval;
$facetitm['name'] = $facetval;
$facetitms[] = $facetitm;
}
}
$facetinfo['items'] = $facetitms;
$facetout[$facetfield] = $facetinfo;
}
}
$facetout['selected'] = $selectedfacets;
$out['facets'] = $facetout;
}
$resultout = array();
if ($response->numFound != 0) {
foreach ( $response->docs as $doc ) {
$resultinfo = array();
$docid = strval($doc->id);
$resultinfo['permalink'] = $doc->permalink;
$resultinfo['title'] = $doc->title;
$resultinfo['author'] = $doc->author;
$resultinfo['authorlink'] = htmlspecialchars($doc->author_s);
$resultinfo['numcomments'] = $doc->numcomments;
$resultinfo['date'] = $doc->displaydate;
if ($doc->numcomments === 0) {
$resultinfo['comment_link'] = $doc->permalink . "#respond";
} else {
$resultinfo['comment_link'] = $doc->permalink . "#comments";
}
$resultinfo['score'] = $doc->score;
$resultinfo['id'] = $docid;
$docteaser = $teasers[$docid];
if ($docteaser->content) {
$resultinfo['teaser'] = sprintf(__("...%s..."), implode("...", $docteaser->content));
} else {
$words = split(' ', $doc->content);
$teaser = implode(' ', array_slice($words, 0, 30));
$resultinfo['teaser'] = sprintf(__("%s..."), $teaser);
}
$resultout[] = $resultinfo;
}
}
$out['results'] = $resultout;
}
} else {
$out['hits'] = "0";
}
# pager and results count helpers
$out['query'] = htmlspecialchars($qry);
$out['offset'] = strval($offset);
$out['count'] = strval($count);
$out['firstresult'] = strval($offset + 1);
$out['lastresult'] = strval(min($offset + $count, $out['hits']));
$out['sortby'] = $sortby;
$out['order'] = $order;
$out['sorting'] = array(
'scoreasc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=score&order=asc%s', urlencode($qry), stripslashes($fq), $serverval)),
'scoredesc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=score&order=desc%s', urlencode($qry), stripslashes($fq), $serverval)),
'dateasc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=date&order=asc%s', urlencode($qry), stripslashes($fq), $serverval)),
'datedesc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=date&order=desc%s', urlencode($qry), stripslashes($fq), $serverval)),
'modifiedasc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=modified&order=asc%s', urlencode($qry), stripslashes($fq), $serverval)),
'modifieddesc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=modified&order=desc%s', urlencode($qry), stripslashes($fq), $serverval)),
'commentsasc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=numcomments&order=asc%s', urlencode($qry), stripslashes($fq), $serverval)),
'commentsdesc' => htmlspecialchars(sprintf('?s=%s&fq=%s&sort=numcomments&order=desc%s', urlencode($qry), stripslashes($fq), $serverval))
);
return $out;
}
function s4w_print_facet_items($items, $pre = "<ul>", $post = "</ul>", $before = "<li>", $after = "</li>",
$nestedpre = "<ul>", $nestedpost = "</ul>", $nestedbefore = "<li>", $nestedafter = "</li>") {
if (!$items) {
return;
}
printf(__("%s\n"), $pre);
foreach ($items as $item) {
printf(__("%s<a href=\"%s\">%s (%s)</a>%s\n"), $before, $item["link"], $item["name"], $item["count"], $after);
$item_items = isset($item["items"]) ? true : false;
if ($item_items) {
s4w_print_facet_items($item["items"], $nestedpre, $nestedpost, $nestedbefore, $nestedafter,
$nestedpre, $nestedpost, $nestedbefore, $nestedafter);
}
}
printf(__("%s\n"), $post);
}
function s4w_get_output_taxo($facet, $taxo, $prefix, $fqstr, $field) {
$qry = stripslashes($_GET['s']);
if (count($taxo) == 0) {
return;
} else {
$facetitms = array();
foreach ($taxo as $taxoname => $taxoval) {
$newprefix = $prefix . $taxoname . '^^';
$facetvars = get_object_vars($facet);
$facetitm = array();
$facetitm['count'] = sprintf(__("%d"), $facetvars[$newprefix]);
$facetitm['link'] = htmlspecialchars(sprintf(__('?s=%s&fq=%s:%s%s', 'solr4wp'), $qry, $field, urlencode('"' . $newprefix . '"'), $fqstr));
$facetitm['name'] = $taxoname;
$outitms = s4w_get_output_taxo($facet, $taxoval, $newprefix, $fqstr, $field);
if ($outitms) {
$facetitm['items'] = $outitms;
}
$facetitms[] = $facetitm;
}
return $facetitms;
}
}
function s4w_gen_taxo_array($in, $vals) {
if (count($vals) == 1) {
if ( ! $in[$vals[0]]) {
$in[$vals[0]] = array();
}
return $in;
} else {
$in[$vals[0]] = s4w_gen_taxo_array($in[$vals[0]], array_slice($vals, 1));
return $in;
}
}
/**
* Query the required server
* passes all parameters to the appropriate function based on the server name
* This allows for extensible server/core based query functions.
* TODO allow for similar theme/output function
*/
function s4w_query( $qry, $offset, $count, $fq, $sortby, $server = NULL) {
//NOTICE: does this needs to be cached to stop the db being hit to grab the options everytime search is being done.
$plugin_s4w_settings = s4w_get_option();
//if no server has been provided use the default server
if(!$server) {
$server = $plugin_s4w_settings['s4w_server']['type']['search'];
}
$solr = s4w_get_solr($server);
if (!function_exists($function = 's4w_'.$server.'_query')) {
$function = 's4w_master_query';
}
return $function($solr, $qry, $offset, $count, $fq, $sortby, $plugin_s4w_settings);
}
function s4w_master_query($solr, $qry, $offset, $count, $fq, $sortby, &$plugin_s4w_settings) {
$response = NULL;
$facet_fields = array();
$number_of_tags = $plugin_s4w_settings['s4w_max_display_tags'];
if ($plugin_s4w_settings['s4w_facet_on_categories']) {
$facet_fields[] = 'categories';
}
$facet_on_tags = $plugin_s4w_settings['s4w_facet_on_tags'];
if ($facet_on_tags) {
$facet_fields[] = 'tags';
}
if ($plugin_s4w_settings['s4w_facet_on_author']) {
$facet_fields[] = 'author';
}
if ($plugin_s4w_settings['s4w_facet_on_type']) {
$facet_fields[] = 'type';
}
$facet_on_custom_taxonomy = $plugin_s4w_settings['s4w_facet_on_taxonomy'];
if (count($facet_on_custom_taxonomy)) {
$taxonomies = (array)get_taxonomies(array('_builtin'=>FALSE),'names');
foreach($taxonomies as $parent) {
$facet_fields[] = $parent."_taxonomy";
}
}
$facet_on_custom_fields = $plugin_s4w_settings['s4w_facet_on_custom_fields'];
if (count($facet_on_custom_fields)) {
foreach ( $facet_on_custom_fields as $field_name ) {
$facet_fields[] = $field_name . '_str';
}
}