-
Notifications
You must be signed in to change notification settings - Fork 313
/
Post.php
2979 lines (2599 loc) · 84.5 KB
/
Post.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
/**
* Post indexable
*
* @since 3.0
* @package elasticpress
*/
namespace ElasticPress\Indexable\Post;
use \WP_Query;
use \WP_User;
use ElasticPress\Elasticsearch;
use ElasticPress\Indexable;
if ( ! defined( 'ABSPATH' ) ) {
// @codeCoverageIgnoreStart
exit; // Exit if accessed directly.
// @codeCoverageIgnoreEnd
}
/**
* Post indexable class
*/
class Post extends Indexable {
/**
* Indexable slug used for identification
*
* @var string
* @since 3.0
*/
public $slug = 'post';
/**
* Flag to indicate if the indexable has support for
* `id_range` pagination method during a sync.
*
* @var boolean
* @since 4.1.0
*/
public $support_indexing_advanced_pagination = true;
/**
* Create indexable and initialize dependencies
*
* @since 3.0
*/
public function __construct() {
$this->labels = [
'plural' => esc_html__( 'Posts', 'elasticpress' ),
'singular' => esc_html__( 'Post', 'elasticpress' ),
];
$this->sync_manager = new SyncManager( $this->slug );
$this->query_integration = new QueryIntegration( $this->slug );
}
/**
* Query database for posts
*
* @param array $args Query DB args
* @since 3.0
* @return array
*/
public function query_db( $args ) {
$defaults = [
'posts_per_page' => $this->get_bulk_items_per_page(),
'post_type' => $this->get_indexable_post_types(),
'post_status' => $this->get_indexable_post_status(),
'offset' => 0,
'ignore_sticky_posts' => true,
'orderby' => 'ID',
'order' => 'desc',
'no_found_rows' => false,
'ep_indexing_advanced_pagination' => true,
'has_password' => false,
];
if ( isset( $args['per_page'] ) ) {
$args['posts_per_page'] = $args['per_page'];
}
if ( isset( $args['include'] ) ) {
$args['post__in'] = $args['include'];
}
if ( isset( $args['exclude'] ) ) {
$args['post__not_in'] = $args['exclude'];
}
/**
* Filter arguments used to query posts from database
*
* @hook ep_post_query_db_args
* @param {array} $args Database arguments
* @return {array} New arguments
*/
$args = apply_filters( 'ep_index_posts_args', apply_filters( 'ep_post_query_db_args', wp_parse_args( $args, $defaults ) ) );
if ( isset( $args['post__in'] ) || 0 < $args['offset'] ) {
// Disable advanced pagination. Not useful if only indexing specific IDs.
$args['ep_indexing_advanced_pagination'] = false;
}
// Enforce the following query args during advanced pagination to ensure things work correctly.
if ( $args['ep_indexing_advanced_pagination'] ) {
$args = array_merge(
$args,
[
'suppress_filters' => false,
'orderby' => 'ID',
'order' => 'DESC',
'paged' => 1,
'offset' => 0,
'no_found_rows' => true,
]
);
add_filter( 'posts_where', array( $this, 'bulk_indexing_filter_posts_where' ), 9999, 2 );
$query = new WP_Query( $args );
$total_objects = $this->get_total_objects_for_query( $args );
remove_filter( 'posts_where', array( $this, 'bulk_indexing_filter_posts_where' ), 9999, 2 );
} else {
$query = new WP_Query( $args );
$total_objects = $query->found_posts;
}
return [
'objects' => $query->posts,
'total_objects' => $total_objects,
];
}
/**
* Manipulate the WHERE clause of the bulk indexing query to paginate by ID in order to avoid performance issues with SQL offset.
*
* @param string $where The current $where clause.
* @param WP_Query $query WP_Query object.
* @return string WHERE clause with our pagination added if needed.
*/
public function bulk_indexing_filter_posts_where( $where, $query ) {
$using_advanced_pagination = $query->get( 'ep_indexing_advanced_pagination', false );
if ( $using_advanced_pagination ) {
$requested_upper_limit_id = $query->get( 'ep_indexing_upper_limit_object_id', PHP_INT_MAX );
$requested_lower_limit_post_id = $query->get( 'ep_indexing_lower_limit_object_id', 0 );
$last_processed_id = $query->get( 'ep_indexing_last_processed_object_id', null );
// On the first loopthrough we begin with the requested upper limit ID. Afterwards, use the last processed ID to paginate.
$upper_limit_range_post_id = $requested_upper_limit_id;
if ( is_numeric( $last_processed_id ) ) {
$upper_limit_range_post_id = $last_processed_id - 1;
}
// Sanitize. Abort if unexpected data at this point.
if ( ! is_numeric( $upper_limit_range_post_id ) || ! is_numeric( $requested_lower_limit_post_id ) ) {
return $where;
}
$range = [
'upper_limit' => "{$GLOBALS['wpdb']->posts}.ID <= {$upper_limit_range_post_id}",
'lower_limit' => "{$GLOBALS['wpdb']->posts}.ID >= {$requested_lower_limit_post_id}",
];
// Skip the end range if it's unnecessary.
$skip_ending_range = 0 === $requested_lower_limit_post_id;
$where = $skip_ending_range ? "AND {$range['upper_limit']} {$where}" : "AND {$range['upper_limit']} AND {$range['lower_limit']} {$where}";
}
return $where;
}
/**
* Get SQL_CALC_FOUND_ROWS for a specific query based on it's args.
*
* @param array $query_args The query args.
* @return int The query result's found_posts.
*/
protected function get_total_objects_for_query( $query_args ) {
static $object_counts = [];
// Reset the pagination-related args for optimal caching.
$normalized_query_args = array_merge(
$query_args,
[
'offset' => 0,
'paged' => 1,
'posts_per_page' => 1,
'no_found_rows' => false,
'ep_indexing_last_processed_object_id' => null,
]
);
$cache_key = md5( get_current_blog_id() . wp_json_encode( $normalized_query_args ) );
if ( ! isset( $object_counts[ $cache_key ] ) ) {
$object_counts[ $cache_key ] = ( new WP_Query( $normalized_query_args ) )->found_posts;
}
if ( 0 === $object_counts[ $cache_key ] ) {
// Do a DB count to make sure the query didn't just die and return 0.
$db_post_count = $this->get_total_objects_for_query_from_db( $normalized_query_args );
if ( $db_post_count !== $object_counts[ $cache_key ] ) {
$object_counts[ $cache_key ] = $db_post_count;
}
}
return $object_counts[ $cache_key ];
}
/**
* Get total posts from DB for a specific query based on it's args.
*
* @param array $query_args The query args.
* @since 4.0.0
* @return int The total posts.
*/
protected function get_total_objects_for_query_from_db( $query_args ) {
global $wpdb;
$post_count = 0;
if ( ! isset( $query_args['post_type'] ) || isset( $query_args['ep_indexing_upper_limit_object_id'] )
|| isset( $query_args['ep_indexing_lower_limit_object_id'] ) ) {
return $post_count;
}
foreach ( $query_args['post_type'] as $post_type ) {
$post_counts_by_post_status = wp_count_posts( $post_type );
foreach ( $post_counts_by_post_status as $post_status => $post_status_count ) {
if ( ! in_array( $post_status, $query_args['post_status'], true ) ) {
continue;
}
$post_count += $post_status_count;
}
}
/**
* As `wp_count_posts` will also count posts with password, we need to remove
* them from the final count if they will not be used.
*
* The if below will pass if `has_password` is false but not null.
*/
if ( isset( $query_args['has_password'] ) && ! $query_args['has_password'] ) {
$posts_with_password = (int) $wpdb->get_var( "SELECT COUNT(1) AS posts_with_password FROM {$wpdb->posts} WHERE post_password != ''" ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery
$post_count -= $posts_with_password;
}
return $post_count;
}
/**
* Returns indexable post types for the current site
*
* @since 0.9
* @return mixed|void
*/
public function get_indexable_post_types() {
$post_types = get_post_types( array( 'public' => true ) );
/**
* Remove attachments by default
*
* @since 3.0
*/
unset( $post_types['attachment'] );
/**
* Filter indexable post types
*
* @hook ep_indexable_post_types
* @param {array} $post_types Indexable post types
* @return {array} New post types
*/
return apply_filters( 'ep_indexable_post_types', $post_types );
}
/**
* Return indexable post_status for the current site
*
* @since 1.3
* @return array
*/
public function get_indexable_post_status() {
/**
* Filter indexable post statuses
*
* @hook ep_indexable_post_status
* @param {array} $post_statuses Indexable post statuses
* @return {array} New post statuses
*/
return apply_filters( 'ep_indexable_post_status', array( 'publish' ) );
}
/**
* Determine required mapping file
*
* @since 3.6.2
* @return string
*/
public function get_mapping_name() {
$es_version = Elasticsearch::factory()->get_elasticsearch_version();
if ( empty( $es_version ) ) {
/**
* Filter fallback Elasticsearch version
*
* @hook ep_fallback_elasticsearch_version
* @param {string} $version Fall back Elasticsearch version
* @return {string} New version
*/
$es_version = apply_filters( 'ep_fallback_elasticsearch_version', '2.0' );
}
$es_version = (string) $es_version;
$mapping_file = '7-0.php';
if ( version_compare( $es_version, '7.0', '<' ) ) {
$mapping_file = '5-2.php';
}
return apply_filters( 'ep_post_mapping_version', $mapping_file );
}
/**
* Generate the mapping array
*
* @since 4.1.0
* @return array
*/
public function generate_mapping() {
$mapping_file = $this->get_mapping_name();
/**
* Filter post indexable mapping file
*
* @hook ep_post_mapping_file
* @param {string} $file Path to file
* @return {string} New file path
*/
$mapping = require apply_filters( 'ep_post_mapping_file', __DIR__ . '/../../../mappings/post/' . $mapping_file );
/**
* Filter post indexable mapping
*
* @hook ep_post_mapping
* @param {array} $mapping Mapping
* @return {array} New mapping
*/
$mapping = apply_filters( 'ep_post_mapping', $mapping );
delete_transient( 'ep_post_mapping_version' );
return $mapping;
}
/**
* Determine version of mapping currently on the post index.
*
* @since 3.6.2
* @return string|WP_Error|false $version
*/
public function determine_mapping_version() {
$version = get_transient( 'ep_post_mapping_version' );
if ( empty( $version ) ) {
$index = $this->get_index_name();
$mapping = Elasticsearch::factory()->get_mapping( $index );
if ( empty( $mapping ) ) {
return new \WP_Error( 'ep_failed_mapping_version', esc_html__( 'Error while fetching the mapping version.', 'elasticpress' ) );
}
if ( ! isset( $mapping[ $index ] ) ) {
return false;
}
$version = $this->determine_mapping_version_based_on_existing( $mapping, $index );
set_transient(
'ep_post_mapping_version',
$version,
/**
* Filter the post mapping version cache expiration.
*
* @hook ep_post_mapping_version_cache_expiration
* @since 3.6.5
* @param {int} $version Time in seconds for the transient expiration
* @return {int} New time
*/
apply_filters( 'ep_post_mapping_version_cache_expiration', DAY_IN_SECONDS )
);
}
/**
* Filter the mapping version for posts.
*
* @hook ep_post_mapping_version_determined
* @since 3.6.2
* @param {string} $version Determined version string
* @return {string} New version string
*/
return apply_filters( 'ep_post_mapping_version_determined', $version );
}
/**
* Prepare a post for syncing
*
* @param int $post_id Post ID.
* @since 0.9.1
* @return bool|array
*/
public function prepare_document( $post_id ) {
global $post;
$post = get_post( $post_id );
setup_postdata( $post );
if ( empty( $post ) ) {
return false;
}
$user = get_userdata( $post->post_author );
if ( $user instanceof WP_User ) {
$user_data = array(
'raw' => $user->user_login,
'login' => $user->user_login,
'display_name' => $user->display_name,
'id' => $user->ID,
);
} else {
$user_data = array(
'raw' => '',
'login' => '',
'display_name' => '',
'id' => '',
);
}
$post_date = $post->post_date;
$post_date_gmt = $post->post_date_gmt;
$post_modified = $post->post_modified;
$post_modified_gmt = $post->post_modified_gmt;
$comment_count = absint( $post->comment_count );
$comment_status = $post->comment_status;
$ping_status = $post->ping_status;
$menu_order = (int) $post->menu_order;
/**
* Filter to ignore invalid dates
*
* @hook ep_ignore_invalid_dates
* @param {bool} $ignore True to ignore
* @param {int} $post_id Post ID
* @param {WP_Post} $post Post object
* @return {bool} New ignore value
*/
if ( apply_filters( 'ep_ignore_invalid_dates', true, $post_id, $post ) ) {
if ( ! strtotime( $post_date ) || '0000-00-00 00:00:00' === $post_date ) {
$post_date = null;
}
if ( ! strtotime( $post_date_gmt ) || '0000-00-00 00:00:00' === $post_date_gmt ) {
$post_date_gmt = null;
}
if ( ! strtotime( $post_modified ) || '0000-00-00 00:00:00' === $post_modified ) {
$post_modified = null;
}
if ( ! strtotime( $post_modified_gmt ) || '0000-00-00 00:00:00' === $post_modified_gmt ) {
$post_modified_gmt = null;
}
}
// To prevent infinite loop, we don't queue when updated_postmeta.
remove_action( 'updated_postmeta', [ $this->sync_manager, 'action_queue_meta_sync' ], 10 );
/**
* Filter to allow indexing of filtered post content
*
* @hook ep_allow_post_content_filtered_index
* @param {bool} $ignore True to allow
* @return {bool} New value
*/
$post_content_filtered_allowed = apply_filters( 'ep_allow_post_content_filtered_index', true );
$post_args = array(
'post_id' => $post_id,
'ID' => $post_id,
'post_author' => $user_data,
'post_date' => $post_date,
'post_date_gmt' => $post_date_gmt,
'post_title' => $post->post_title,
'post_excerpt' => $post->post_excerpt,
'post_content_filtered' => $post_content_filtered_allowed ? apply_filters( 'the_content', $post->post_content ) : '',
'post_content' => $post->post_content,
'post_status' => $post->post_status,
'post_name' => $post->post_name,
'post_modified' => $post_modified,
'post_modified_gmt' => $post_modified_gmt,
'post_parent' => $post->post_parent,
'post_type' => $post->post_type,
'post_mime_type' => $post->post_mime_type,
'permalink' => get_permalink( $post_id ),
'terms' => $this->prepare_terms( $post ),
'meta' => $this->prepare_meta_types( $this->prepare_meta( $post ) ), // post_meta removed in 2.4.
'date_terms' => $this->prepare_date_terms( $post_date ),
'comment_count' => $comment_count,
'comment_status' => $comment_status,
'ping_status' => $ping_status,
'menu_order' => $menu_order,
'guid' => $post->guid,
'thumbnail' => $this->prepare_thumbnail( $post ),
);
/**
* Filter sync arguments for a post. For backwards compatibility.
*
* @hook ep_post_sync_args
* @param {array} $post_args Post arguments
* @param {int} $post_id Post ID
* @return {array} New arguments
*/
$post_args = apply_filters( 'ep_post_sync_args', $post_args, $post_id );
/**
* Filter sync arguments for a post after meta preparation.
*
* @hook ep_post_sync_args_post_prepare_meta
* @param {array} $post_args Post arguments
* @param {int} $post_id Post ID
* @return {array} New arguments
*/
$post_args = apply_filters( 'ep_post_sync_args_post_prepare_meta', $post_args, $post_id );
// Turn back on updated_postmeta hook
add_action( 'updated_postmeta', [ $this->sync_manager, 'action_queue_meta_sync' ], 10, 4 );
return $post_args;
}
/**
* Prepare thumbnail to send to ES.
*
* @param WP_Post $post Post object.
* @return array|null Thumbnail data.
*/
public function prepare_thumbnail( $post ) {
$attachment_id = get_post_thumbnail_id( $post );
if ( ! $attachment_id ) {
return null;
}
/**
* Filters the image size to use when indexing the post thumbnail.
*
* Defaults to the `woocommerce_thumbnail` size if WooCommerce is in
* use. Otherwise the `thumbnail` size is used.
*
* @hook ep_thumbnail_image_size
* @since 4.0.0
* @param {string|int[]} $image_size Image size. Can be any registered
* image size name, or an array of
* width and height values in pixels
* (in that order).
* @param {WP_Post} $post Post being indexed.
* @return {array} Image size to pass to wp_get_attachment_image_src().
*/
$image_size = apply_filters(
'ep_post_thumbnail_image_size',
function_exists( 'WC' ) ? 'woocommerce_thumbnail' : 'thumbnail',
$post
);
$image_src = wp_get_attachment_image_src( $attachment_id, $image_size );
$image_alt = trim( wp_strip_all_tags( get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ) ) );
if ( ! $image_src ) {
return null;
}
return [
'ID' => $attachment_id,
'src' => $image_src[0],
'width' => $image_src[1],
'height' => $image_src[2],
'alt' => $image_alt,
];
}
/**
* Prepare date terms to send to ES.
*
* @param string $date_to_prepare Post date
* @since 0.1.4
* @return array
*/
public function prepare_date_terms( $date_to_prepare ) {
$terms_to_prepare = [
'year' => 'Y',
'month' => 'm',
'week' => 'W',
'dayofyear' => 'z',
'day' => 'd',
'dayofweek' => 'w',
'dayofweek_iso' => 'N',
'hour' => 'H',
'minute' => 'i',
'second' => 's',
'm' => 'Ym', // yearmonth
];
// Combine all the date term formats and perform one single call to date_i18n() for performance.
$date_format = implode( '||', array_values( $terms_to_prepare ) );
$combined_dates = explode( '||', date_i18n( $date_format, strtotime( $date_to_prepare ) ) );
// Then split up the results for individual indexing.
$date_terms = [];
foreach ( $terms_to_prepare as $term_name => $date_format ) {
$index_in_combined_format = array_search( $term_name, array_keys( $terms_to_prepare ), true );
$date_terms[ $term_name ] = (int) $combined_dates[ $index_in_combined_format ];
}
return $date_terms;
}
/**
* Get an array of taxonomies that are indexable for the given post
*
* @since 4.0.0
* @param WP_Post $post Post object
* @return array Array of WP_Taxonomy objects that should be indexed
*/
public function get_indexable_post_taxonomies( $post ) {
$taxonomies = get_object_taxonomies( $post->post_type, 'objects' );
$selected_taxonomies = [];
foreach ( $taxonomies as $taxonomy ) {
if ( $taxonomy->public || $taxonomy->publicly_queryable ) {
$selected_taxonomies[] = $taxonomy;
}
}
/**
* Filter taxonomies to be synced with post
*
* @hook ep_sync_taxonomies
* @param {array} $selected_taxonomies Selected taxonomies
* @param {WP_Post} Post object
* @return {array} New taxonomies
*/
$selected_taxonomies = (array) apply_filters( 'ep_sync_taxonomies', $selected_taxonomies, $post );
// Important we validate here to ensure there are no invalid taxonomy values returned from the filter, as just one would cause wp_get_object_terms() to fail.
$validated_taxonomies = [];
foreach ( $selected_taxonomies as $selected_taxonomy ) {
// If we get a taxonomy name, we need to convert it to taxonomy object
if ( ! is_object( $selected_taxonomy ) && taxonomy_exists( (string) $selected_taxonomy ) ) {
$selected_taxonomy = get_taxonomy( $selected_taxonomy );
}
// We check if the $taxonomy object has a valid name property. Backward compatibility since WP_Taxonomy introduced in WP 4.7
if ( ! is_a( $selected_taxonomy, '\WP_Taxonomy' ) || ! property_exists( $selected_taxonomy, 'name' ) || ! taxonomy_exists( $selected_taxonomy->name ) ) {
continue;
}
$validated_taxonomies[] = $selected_taxonomy;
}
return $validated_taxonomies;
}
/**
* Prepare terms to send to ES.
*
* @param WP_Post $post Post object
* @since 0.1.0
* @return array
*/
private function prepare_terms( $post ) {
$selected_taxonomies = $this->get_indexable_post_taxonomies( $post );
if ( empty( $selected_taxonomies ) ) {
return [];
}
$terms = [];
/**
* Filter to allow child terms to be indexed
*
* @hook ep_sync_terms_allow_hierarchy
* @param {bool} $allow True means allow
* @return {bool} New value
*/
$allow_hierarchy = apply_filters( 'ep_sync_terms_allow_hierarchy', true );
foreach ( $selected_taxonomies as $taxonomy ) {
$object_terms = get_the_terms( $post->ID, $taxonomy->name );
if ( ! $object_terms || is_wp_error( $object_terms ) ) {
continue;
}
$terms_dic = [];
foreach ( $object_terms as $term ) {
if ( ! isset( $terms_dic[ $term->term_id ] ) ) {
$terms_dic[ $term->term_id ] = $this->get_formatted_term( $term, $post->ID );
if ( $allow_hierarchy ) {
$terms_dic = $this->get_parent_terms( $terms_dic, $term, $taxonomy->name, $post->ID );
}
}
}
$terms[ $taxonomy->name ] = array_values( $terms_dic );
}
return $terms;
}
/**
* Recursively get all the ancestor terms of the given term
*
* @param array $terms Terms array
* @param WP_Term $term Current term
* @param string $tax_name Taxonomy
* @param int $object_id Post ID
*
* @return array
*/
private function get_parent_terms( $terms, $term, $tax_name, $object_id ) {
$parent_term = get_term( $term->parent, $tax_name );
if ( ! $parent_term || is_wp_error( $parent_term ) ) {
return $terms;
}
if ( ! isset( $terms[ $parent_term->term_id ] ) ) {
$terms[ $parent_term->term_id ] = $this->get_formatted_term( $parent_term, $object_id );
}
return $this->get_parent_terms( $terms, $parent_term, $tax_name, $object_id );
}
/**
* Given a term, format it to be appended to the post ES document.
*
* @since 4.5.0
* @param \WP_Term $term Term to be formatted
* @param int $post_id The post ID
* @return array
*/
private function get_formatted_term( \WP_Term $term, int $post_id ) : array {
$formatted_term = [
'term_id' => $term->term_id,
'slug' => $term->slug,
'name' => $term->name,
'parent' => $term->parent,
'term_taxonomy_id' => $term->term_taxonomy_id,
'term_order' => (int) $this->get_term_order( $term->term_taxonomy_id, $post_id ),
];
/**
* As the name implies, the facet attribute is used to list all terms in facets.
* As in facets, the term_order associated with a post does not matter, we set it as 0 here.
* Note that this is set as 0 instead of simply removed to keep backward compatibility.
*/
$term_facet = $formatted_term;
$term_facet['term_order'] = 0;
$formatted_term['facet'] = wp_json_encode( $term_facet );
return $formatted_term;
}
/**
* Retrieves term order for the object/term_taxonomy_id combination
*
* @param int $term_taxonomy_id Term Taxonomy ID
* @param int $object_id Post ID
*
* @return int Term Order
*/
protected function get_term_order( $term_taxonomy_id, $object_id ) {
global $wpdb;
$cache_key = "{$object_id}_term_order";
$term_orders = wp_cache_get( $cache_key );
if ( false === $term_orders ) {
$results = $wpdb->get_results( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
$wpdb->prepare(
"SELECT term_taxonomy_id, term_order from $wpdb->term_relationships where object_id=%d;",
$object_id
),
ARRAY_A
);
$term_orders = [];
foreach ( $results as $result ) {
$term_orders[ $result['term_taxonomy_id'] ] = $result['term_order'];
}
wp_cache_set( $cache_key, $term_orders );
}
return isset( $term_orders[ $term_taxonomy_id ] ) ? (int) $term_orders[ $term_taxonomy_id ] : 0;
}
/**
* Checks if meta key is allowed
*
* @param string $meta_key meta key to check
* @param WP_Post $post Post object
* @since 4.3.0
* @return boolean
*/
public function is_meta_allowed( $meta_key, $post ) {
$test_metas = [
$meta_key => true,
];
$filtered_test_metas = $this->filter_allowed_metas( $test_metas, $post );
return array_key_exists( $meta_key, $filtered_test_metas );
}
/**
* Filter post meta to only the allowed ones to be send to ES
*
* @param array $metas Key => value pairs of post meta
* @param WP_Post $post Post object
* @since 4.3.0
* @return array
*/
public function filter_allowed_metas( $metas, $post ) {
$filtered_metas = [];
$search = \ElasticPress\Features::factory()->get_registered_feature( 'search' );
if ( $search && ! empty( $search->weighting ) && 'manual' === $search->weighting->get_meta_mode() ) {
$filtered_metas = $this->filter_allowed_metas_manual( $metas, $post );
} else {
$filtered_metas = $this->filter_allowed_metas_auto( $metas, $post );
}
return $filtered_metas;
}
/**
* Prepare post meta to send to ES
*
* @param WP_Post $post Post object
* @since 0.1.0
* @return array
*/
public function prepare_meta( $post ) {
/**
* Filter pre-prepare meta for a post
*
* @hook ep_prepare_meta_data
* @param {array} $meta Meta data
* @param {WP_Post} $post Post object
* @return {array} New meta
*/
$meta = apply_filters( 'ep_prepare_meta_data', (array) get_post_meta( $post->ID ), $post );
if ( empty( $meta ) ) {
/**
* Filter final list of prepared meta.
*
* @hook ep_prepared_post_meta
* @param {array} $prepared_meta Prepared meta
* @param {WP_Post} $post Post object
* @since 3.4
* @return {array} Prepared meta
*/
return apply_filters( 'ep_prepared_post_meta', [], $post );
}
$filtered_metas = $this->filter_allowed_metas( $meta, $post );
$prepared_meta = [];
foreach ( $filtered_metas as $key => $value ) {
if ( ! empty( $key ) ) {
$prepared_meta[ $key ] = maybe_unserialize( $value );
}
}
/**
* Filter final list of prepared meta.
*
* @hook ep_prepared_post_meta
* @param {array} $prepared_meta Prepared meta
* @param {WP_Post} $post Post object
* @since 3.4
* @return {array} Prepared meta
*/
return apply_filters( 'ep_prepared_post_meta', $prepared_meta, $post );
}
/**
* Format WP query args for ES
*
* @param array $args WP_Query arguments.
* @param WP_Query $wp_query WP_Query object
* @since 0.9.0
* @return array
*/
public function format_args( $args, $wp_query ) {
$args = $this->sanitize_wp_query_args( $args );
$formatted_args = [
'from' => $this->parse_from( $args ),
'size' => $this->parse_size( $args ),
];
$filters = $this->parse_filters( $args, $wp_query );
if ( ! empty( $filters ) ) {
$formatted_args['post_filter'] = $filters;
}
$formatted_args = $this->maybe_set_search_fields( $formatted_args, $args );
$formatted_args = $this->maybe_set_fields( $formatted_args, $args );
$formatted_args = $this->maybe_orderby( $formatted_args, $args );
$formatted_args = $this->maybe_add_sticky_posts( $formatted_args, $args );
$formatted_args = $this->maybe_set_aggs( $formatted_args, $args, $filters );
/**
* Filter formatted Elasticsearch [ost ]query (entire query)
*
* @hook ep_formatted_args
* @param {array} $formatted_args Formatted Elasticsearch query
* @param {array} $query_vars Query variables
* @param {array} $query Query part
* @return {array} New query
*/
$formatted_args = apply_filters( 'ep_formatted_args', $formatted_args, $args, $wp_query );
/**
* Filter formatted Elasticsearch [ost ]query (entire query)
*
* @hook ep_post_formatted_args
* @param {array} $formatted_args Formatted Elasticsearch query
* @param {array} $query_vars Query variables
* @param {array} $query Query part
* @return {array} New query
*/
$formatted_args = apply_filters( 'ep_post_formatted_args', $formatted_args, $args, $wp_query );
return $formatted_args;
}
/**
* Adjust the fuzziness parameter if needed.
*
* If using fields with type `long`, queries should not have a fuzziness parameter.
*
* @param array $query Current query
* @param array $query_vars Query variables
* @param string $search_text Search text
* @param array $search_fields Search fields
* @return array New query
*/
public function adjust_query_fuzziness( $query, $query_vars, $search_text, $search_fields ) {
if ( empty( array_intersect( $search_fields, [ 'ID', 'post_id', 'post_parent' ] ) ) ) {
return $query;
}
if ( ! isset( $query['bool'] ) || ! isset( $query['bool']['should'] ) ) {
return $query;
}
foreach ( $query['bool']['should'] as &$clause ) {
if ( ! isset( $clause['multi_match'] ) ) {
continue;
}
if ( isset( $clause['multi_match']['fuzziness'] ) ) {
unset( $clause['multi_match']['fuzziness'] );
}
}
return $query;
}
/**
* Parse and build out our tax query.
*
* @access protected
*
* @param array $query Tax query
* @return array