Completed
Push — add/double-encode-message ( 8b6530...2d4e84 )
by
unknown
14:26 queued 05:57
created

Jetpack_Search::convert_wp_es_to_es_args()   F

Complexity

Conditions 36
Paths > 20000

Size

Total Lines 347

Duplication

Lines 32
Ratio 9.22 %

Importance

Changes 0
Metric Value
cc 36
nc 559872
nop 1
dl 32
loc 347
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Jetpack Search: Main Jetpack_Search class
4
 *
5
 * @package    Jetpack
6
 * @subpackage Jetpack Search
7
 * @since      5.0.0
8
 */
9
10
/**
11
 * The main class for the Jetpack Search module.
12
 *
13
 * @since 5.0.0
14
 */
15
class Jetpack_Search {
16
17
	/**
18
	 * The number of found posts.
19
	 *
20
	 * @since 5.0.0
21
	 *
22
	 * @var int
23
	 */
24
	protected $found_posts = 0;
25
26
	/**
27
	 * The search result, as returned by the WordPress.com REST API.
28
	 *
29
	 * @since 5.0.0
30
	 *
31
	 * @var array
32
	 */
33
	protected $search_result;
34
35
	/**
36
	 * This site's blog ID on WordPress.com.
37
	 *
38
	 * @since 5.0.0
39
	 *
40
	 * @var int
41
	 */
42
	protected $jetpack_blog_id;
43
44
	/**
45
	 * The Elasticsearch aggregations (filters).
46
	 *
47
	 * @since 5.0.0
48
	 *
49
	 * @var array
50
	 */
51
	protected $aggregations = array();
52
53
	/**
54
	 * The maximum number of aggregations allowed.
55
	 *
56
	 * @since 5.0.0
57
	 *
58
	 * @var int
59
	 */
60
	protected $max_aggregations_count = 100;
61
62
	/**
63
	 * Statistics about the last Elasticsearch query.
64
	 *
65
	 * @since 5.6.0
66
	 *
67
	 * @var array
68
	 */
69
	protected $last_query_info = array();
70
71
	/**
72
	 * Statistics about the last Elasticsearch query failure.
73
	 *
74
	 * @since 5.6.0
75
	 *
76
	 * @var array
77
	 */
78
	protected $last_query_failure_info = array();
79
80
	/**
81
	 * The singleton instance of this class.
82
	 *
83
	 * @since 5.0.0
84
	 *
85
	 * @var Jetpack_Search
86
	 */
87
	protected static $instance;
88
89
	/**
90
	 * Languages with custom analyzers. Other languages are supported, but are analyzed with the default analyzer.
91
	 *
92
	 * @since 5.0.0
93
	 *
94
	 * @var array
95
	 */
96
	public static $analyzed_langs = array( 'ar', 'bg', 'ca', 'cs', 'da', 'de', 'el', 'en', 'es', 'eu', 'fa', 'fi', 'fr', 'he', 'hi', 'hu', 'hy', 'id', 'it', 'ja', 'ko', 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh' );
97
98
	/**
99
	 * Jetpack_Search constructor.
100
	 *
101
	 * @since 5.0.0
102
	 *
103
	 * Doesn't do anything. This class needs to be initialized via the instance() method instead.
104
	 */
105
	protected function __construct() {
106
	}
107
108
	/**
109
	 * Prevent __clone()'ing of this class.
110
	 *
111
	 * @since 5.0.0
112
	 */
113
	public function __clone() {
114
		wp_die( "Please don't __clone Jetpack_Search" );
115
	}
116
117
	/**
118
	 * Prevent __wakeup()'ing of this class.
119
	 *
120
	 * @since 5.0.0
121
	 */
122
	public function __wakeup() {
123
		wp_die( "Please don't __wakeup Jetpack_Search" );
124
	}
125
126
	/**
127
	 * Get singleton instance of Jetpack_Search.
128
	 *
129
	 * Instantiates and sets up a new instance if needed, or returns the singleton.
130
	 *
131
	 * @since 5.0.0
132
	 *
133
	 * @return Jetpack_Search The Jetpack_Search singleton.
134
	 */
135
	public static function instance() {
136
		if ( ! isset( self::$instance ) ) {
137
			self::$instance = new Jetpack_Search();
138
139
			self::$instance->setup();
140
		}
141
142
		return self::$instance;
143
	}
144
145
	/**
146
	 * Perform various setup tasks for the class.
147
	 *
148
	 * Checks various pre-requisites and adds hooks.
149
	 *
150
	 * @since 5.0.0
151
	 */
152
	public function setup() {
153
		if ( ! Jetpack::is_active() || ! Jetpack::active_plan_supports( 'search' ) ) {
154
			return;
155
		}
156
157
		$this->jetpack_blog_id = Jetpack::get_option( 'id' );
158
159
		if ( ! $this->jetpack_blog_id ) {
160
			return;
161
		}
162
163
		require_once dirname( __FILE__ ) . '/class.jetpack-search-helpers.php';
164
		require_once dirname( __FILE__ ) . '/class.jetpack-search-template-tags.php';
165
		require_once JETPACK__PLUGIN_DIR . 'modules/widgets/search.php';
166
167
		$this->init_hooks();
168
	}
169
170
	/**
171
	 * Setup the various hooks needed for the plugin to take over search duties.
172
	 *
173
	 * @since 5.0.0
174
	 */
175
	public function init_hooks() {
176
		if ( ! is_admin() ) {
177
			add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
178
179
			add_filter( 'jetpack_search_es_wp_query_args', array( $this, 'filter__add_date_filter_to_query' ), 10, 2 );
180
181
			add_action( 'did_jetpack_search_query', array( $this, 'store_last_query_info' ) );
182
			add_action( 'failed_jetpack_search_query', array( $this, 'store_query_failure' ) );
183
184
			add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
185
186
			add_action( 'pre_get_posts', array( $this, 'maybe_add_post_type_as_var' ) );
187
		} else {
188
			add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
189
		}
190
191
		add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
192
	}
193
194
	/**
195
	 * When an Elasticsearch query fails, this stores it and enqueues some debug information in the footer.
196
	 *
197
	 * @since 5.6.0
198
	 *
199
	 * @param array $meta Information about the failure.
200
	 */
201
	public function store_query_failure( $meta ) {
202
		$this->last_query_failure_info = $meta;
203
		add_action( 'wp_footer', array( $this, 'print_query_failure' ) );
204
	}
205
206
	/**
207
	 * Outputs information about the last Elasticsearch failure.
208
	 *
209
	 * @since 5.6.0
210
	 */
211
	public function print_query_failure() {
212
		if ( $this->last_query_failure_info ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->last_query_failure_info of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
213
			printf(
214
				'<!-- Jetpack Search failed with code %s: %s - %s -->',
215
				esc_html( $this->last_query_failure_info['response_code'] ),
216
				esc_html( $this->last_query_failure_info['json']['error'] ),
217
				esc_html( $this->last_query_failure_info['json']['message'] )
218
			);
219
		}
220
	}
221
222
	/**
223
	 * Stores information about the last Elasticsearch query and enqueues some debug information in the footer.
224
	 *
225
	 * @since 5.6.0
226
	 *
227
	 * @param array $meta Information about the query.
228
	 */
229
	public function store_last_query_info( $meta ) {
230
		$this->last_query_info = $meta;
231
		add_action( 'wp_footer', array( $this, 'print_query_success' ) );
232
	}
233
234
	/**
235
	 * Outputs information about the last Elasticsearch search.
236
	 *
237
	 * @since 5.6.0
238
	 */
239
	public function print_query_success() {
240
		if ( $this->last_query_info ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $this->last_query_info of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
241
			printf(
242
				'<!-- Jetpack Search took %s ms, ES time %s ms -->',
243
				intval( $this->last_query_info['elapsed_time'] ),
244
				esc_html( $this->last_query_info['es_time'] )
245
			);
246
		}
247
	}
248
249
	/**
250
	 * Returns the last query information, or false if no information was stored.
251
	 *
252
	 * @since 5.8.0
253
	 *
254
	 * @return bool|array
255
	 */
256
	public function get_last_query_info() {
257
		return empty( $this->last_query_info ) ? false : $this->last_query_info;
258
	}
259
260
	/**
261
	 * Returns the last query failure information, or false if no failure information was stored.
262
	 *
263
	 * @since 5.8.0
264
	 *
265
	 * @return bool|array
266
	 */
267
	public function get_last_query_failure_info() {
268
		return empty( $this->last_query_failure_info ) ? false : $this->last_query_failure_info;
269
	}
270
271
	/**
272
	 * Wraps a WordPress filter called "jetpack_search_disable_widget_filters" that allows
273
	 * developers to disable filters supplied by the search widget. Useful if filters are
274
	 * being defined at the code level.
275
	 *
276
	 * @since      5.7.0
277
	 * @deprecated 5.8.0 Use Jetpack_Search_Helpers::are_filters_by_widget_disabled() directly.
278
	 *
279
	 * @return bool
280
	 */
281
	public function are_filters_by_widget_disabled() {
282
		return Jetpack_Search_Helpers::are_filters_by_widget_disabled();
283
	}
284
285
	/**
286
	 * Retrieves a list of known Jetpack search filters widget IDs, gets the filters for each widget,
287
	 * and applies those filters to this Jetpack_Search object.
288
	 *
289
	 * @since 5.7.0
290
	 */
291
	public function set_filters_from_widgets() {
292
		if ( Jetpack_Search_Helpers::are_filters_by_widget_disabled() ) {
293
			return;
294
		}
295
296
		$filters = Jetpack_Search_Helpers::get_filters_from_widgets();
297
298
		if ( ! empty( $filters ) ) {
299
			$this->set_filters( $filters );
300
		}
301
	}
302
303
	/**
304
	 * Restricts search results to certain post types via a GET argument.
305
	 *
306
	 * @since 5.8.0
307
	 *
308
	 * @param WP_Query $query A WP_Query instance.
309
	 */
310
	public function maybe_add_post_type_as_var( WP_Query $query ) {
311
		if ( $this->should_handle_query( $query ) && ! empty( $_GET['post_type'] ) ) {
312
			$post_types = ( is_string( $_GET['post_type'] ) && false !== strpos( $_GET['post_type'], ',' ) )
313
				? $post_type = explode( ',', $_GET['post_type'] )
314
				: (array) $_GET['post_type'];
315
			$post_types = array_map( 'sanitize_key', $post_types );
316
			$query->set( 'post_type', $post_types );
317
		}
318
	}
319
320
	/*
321
	 * Run a search on the WordPress.com public API.
322
	 *
323
	 * @since 5.0.0
324
	 *
325
	 * @param array $es_args Args conforming to the WP.com /sites/<blog_id>/search endpoint.
326
	 *
327
	 * @return object|WP_Error The response from the public API, or a WP_Error.
328
	 */
329
	public function search( array $es_args ) {
330
		$endpoint    = sprintf( '/sites/%s/search', $this->jetpack_blog_id );
331
		$service_url = 'https://public-api.wordpress.com/rest/v1' . $endpoint;
332
333
		$do_authenticated_request = false;
334
335
		if ( class_exists( 'Jetpack_Client' ) &&
336
			isset( $es_args['authenticated_request'] ) &&
337
			true === $es_args['authenticated_request'] ) {
338
			$do_authenticated_request = true;
339
		}
340
341
		unset( $es_args['authenticated_request'] );
342
343
		$request_args = array(
344
			'headers' => array(
345
				'Content-Type' => 'application/json',
346
			),
347
			'timeout'    => 10,
348
			'user-agent' => 'jetpack_search',
349
		);
350
351
		$request_body = wp_json_encode( $es_args );
352
353
		$start_time = microtime( true );
354
355
		if ( $do_authenticated_request ) {
356
			$request_args['method'] = 'POST';
357
358
			$request = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, Jetpack_Client::WPCOM_JSON_API_VERSION, $request_args, $request_body );
359
		} else {
360
			$request_args = array_merge( $request_args, array(
361
				'body' => $request_body,
362
			) );
363
364
			$request = wp_remote_post( $service_url, $request_args );
365
		}
366
367
		$end_time = microtime( true );
368
369
		if ( is_wp_error( $request ) ) {
370
			return $request;
371
		}
372
373
		$response_code = wp_remote_retrieve_response_code( $request );
374
375
		$response = json_decode( wp_remote_retrieve_body( $request ), true );
376
377
		$took = is_array( $response ) && ! empty( $response['took'] )
378
			? $response['took']
379
			: null;
380
381
		$query = array(
382
			'args'          => $es_args,
383
			'response'      => $response,
384
			'response_code' => $response_code,
385
			'elapsed_time'  => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
386
			'es_time'       => $took,
387
			'url'           => $service_url,
388
		);
389
390
		/**
391
		 * Fires after a search request has been performed.
392
		 *
393
		 * Includes the following info in the $query parameter:
394
		 *
395
		 * array args Array of Elasticsearch arguments for the search
396
		 * array response Raw API response, JSON decoded
397
		 * int response_code HTTP response code of the request
398
		 * float elapsed_time Roundtrip time of the search request, in milliseconds
399
		 * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
400
		 * string url API url that was queried
401
		 *
402
		 * @module search
403
		 *
404
		 * @since  5.0.0
405
		 * @since  5.8.0 This action now fires on all queries instead of just successful queries.
406
		 *
407
		 * @param array $query Array of information about the query performed
408
		 */
409
		do_action( 'did_jetpack_search_query', $query );
410
411
		if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
412
			/**
413
			 * Fires after a search query request has failed
414
			 *
415
			 * @module search
416
			 *
417
			 * @since  5.6.0
418
			 *
419
			 * @param array Array containing the response code and response from the failed search query
420
			 */
421
			do_action( 'failed_jetpack_search_query', array(
422
				'response_code' => $response_code,
423
				'json'          => $response,
424
			) );
425
426
			return new WP_Error( 'invalid_search_api_response', 'Invalid response from API - ' . $response_code );
427
		}
428
429
		return $response;
430
	}
431
432
	/**
433
	 * Bypass the normal Search query and offload it to Jetpack servers.
434
	 *
435
	 * This is the main hook of the plugin and is responsible for returning the posts that match the search query.
436
	 *
437
	 * @since 5.0.0
438
	 *
439
	 * @param array    $posts Current array of posts (still pre-query).
440
	 * @param WP_Query $query The WP_Query being filtered.
441
	 *
442
	 * @return array Array of matching posts.
443
	 */
444
	public function filter__posts_pre_query( $posts, $query ) {
445
		if ( ! $this->should_handle_query( $query ) ) {
446
			return $posts;
447
		}
448
449
		$this->do_search( $query );
450
451
		if ( ! is_array( $this->search_result ) ) {
452
			return $posts;
453
		}
454
455
		// If no results, nothing to do
456
		if ( ! count( $this->search_result['results']['hits'] ) ) {
457
			return array();
458
		}
459
460
		$post_ids = array();
461
462
		foreach ( $this->search_result['results']['hits'] as $result ) {
463
			$post_ids[] = (int) $result['fields']['post_id'];
464
		}
465
466
		// Query all posts now
467
		$args = array(
468
			'post__in'            => $post_ids,
469
			'orderby'             => 'post__in',
470
			'perm'                => 'readable',
471
			'post_type'           => 'any',
472
			'ignore_sticky_posts' => true,
473
			'suppress_filters'    => true,
474
		);
475
476
		$posts_query = new WP_Query( $args );
477
478
		// WP Core doesn't call the set_found_posts and its filters when filtering posts_pre_query like we do, so need to do these manually.
479
		$query->found_posts   = $this->found_posts;
480
		$query->max_num_pages = ceil( $this->found_posts / $query->get( 'posts_per_page' ) );
481
482
		return $posts_query->posts;
483
	}
484
485
	/**
486
	 * Build up the search, then run it against the Jetpack servers.
487
	 *
488
	 * @since 5.0.0
489
	 *
490
	 * @param WP_Query $query The original WP_Query to use for the parameters of our search.
491
	 */
492
	public function do_search( WP_Query $query ) {
493
		if ( ! $this->should_handle_query( $query ) ) {
494
			return;
495
		}
496
497
		$page = ( $query->get( 'paged' ) ) ? absint( $query->get( 'paged' ) ) : 1;
498
499
		// Get maximum allowed offset and posts per page values for the API.
500
		$max_offset         = Jetpack_Search_Helpers::get_max_offset();
501
		$max_posts_per_page = Jetpack_Search_Helpers::get_max_posts_per_page();
502
503
		$posts_per_page = $query->get( 'posts_per_page' );
504
		if ( $posts_per_page > $max_posts_per_page ) {
505
			$posts_per_page = $max_posts_per_page;
506
		}
507
508
		// Start building the WP-style search query args.
509
		// They'll be translated to ES format args later.
510
		$es_wp_query_args = array(
511
			'query'          => $query->get( 's' ),
512
			'posts_per_page' => $posts_per_page,
513
			'paged'          => $page,
514
			'orderby'        => $query->get( 'orderby' ),
515
			'order'          => $query->get( 'order' ),
516
		);
517
518
		if ( ! empty( $this->aggregations ) ) {
519
			$es_wp_query_args['aggregations'] = $this->aggregations;
520
		}
521
522
		// Did we query for authors?
523
		if ( $query->get( 'author_name' ) ) {
524
			$es_wp_query_args['author_name'] = $query->get( 'author_name' );
525
		}
526
527
		$es_wp_query_args['post_type'] = $this->get_es_wp_query_post_type_for_query( $query );
528
		$es_wp_query_args['terms']     = $this->get_es_wp_query_terms_for_query( $query );
529
530
		/**
531
		 * Modify the search query parameters, such as controlling the post_type.
532
		 *
533
		 * These arguments are in the format of WP_Query arguments
534
		 *
535
		 * @module search
536
		 *
537
		 * @since  5.0.0
538
		 *
539
		 * @param array    $es_wp_query_args The current query args, in WP_Query format.
540
		 * @param WP_Query $query            The original WP_Query object.
541
		 */
542
		$es_wp_query_args = apply_filters( 'jetpack_search_es_wp_query_args', $es_wp_query_args, $query );
543
544
		// If page * posts_per_page is greater than our max offset, send a 404. This is necessary because the offset is
545
		// capped at Jetpack_Search_Helpers::get_max_offset(), so a high page would always return the last page of results otherwise.
546
		if ( ( $es_wp_query_args['paged'] * $es_wp_query_args['posts_per_page'] ) > $max_offset ) {
547
			$query->set_404();
548
549
			return;
550
		}
551
552
		// If there were no post types returned, then 404 to avoid querying against non-public post types, which could
553
		// happen if we don't add the post type restriction to the ES query.
554
		if ( empty( $es_wp_query_args['post_type'] ) ) {
555
			$query->set_404();
556
557
			return;
558
		}
559
560
		// Convert the WP-style args into ES args.
561
		$es_query_args = $this->convert_wp_es_to_es_args( $es_wp_query_args );
562
563
		//Only trust ES to give us IDs, not the content since it is a mirror
564
		$es_query_args['fields'] = array(
565
			'post_id',
566
		);
567
568
		/**
569
		 * Modify the underlying ES query that is passed to the search endpoint. The returned args must represent a valid ES query
570
		 *
571
		 * This filter is harder to use if you're unfamiliar with ES, but allows complete control over the query
572
		 *
573
		 * @module search
574
		 *
575
		 * @since  5.0.0
576
		 *
577
		 * @param array    $es_query_args The raw Elasticsearch query args.
578
		 * @param WP_Query $query         The original WP_Query object.
579
		 */
580
		$es_query_args = apply_filters( 'jetpack_search_es_query_args', $es_query_args, $query );
581
582
		// Do the actual search query!
583
		$this->search_result = $this->search( $es_query_args );
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->search($es_query_args) of type object is incompatible with the declared type array of property $search_result.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
584
585
		if ( is_wp_error( $this->search_result ) || ! is_array( $this->search_result ) || empty( $this->search_result['results'] ) || empty( $this->search_result['results']['hits'] ) ) {
586
			$this->found_posts = 0;
587
588
			return;
589
		}
590
591
		// If we have aggregations, fix the ordering to match the input order (ES doesn't guarantee the return order).
592
		if ( isset( $this->search_result['results']['aggregations'] ) && ! empty( $this->search_result['results']['aggregations'] ) ) {
593
			$this->search_result['results']['aggregations'] = $this->fix_aggregation_ordering( $this->search_result['results']['aggregations'], $this->aggregations );
594
		}
595
596
		// Total number of results for paging purposes. Capped at $max_offset + $posts_per_page, as deep paging gets quite expensive.
597
		$this->found_posts = min( $this->search_result['results']['total'], $max_offset + $posts_per_page );
598
	}
599
600
	/**
601
	 * If the query has already been run before filters have been updated, then we need to re-run the query
602
	 * to get the latest aggregations.
603
	 *
604
	 * This is especially useful for supporting widget management in the customizer.
605
	 *
606
	 * @since 5.8.0
607
	 *
608
	 * @return bool Whether the query was successful or not.
609
	 */
610
	public function update_search_results_aggregations() {
611
		if ( empty( $this->last_query_info ) || empty( $this->last_query_info['args'] ) ) {
612
			return false;
613
		}
614
615
		$es_args = $this->last_query_info['args'];
616
		$builder = new Jetpack_WPES_Query_Builder();
617
		$this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
618
		$es_args['aggregations'] = $builder->build_aggregation();
619
620
		$this->search_result = $this->search( $es_args );
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->search($es_args) of type object is incompatible with the declared type array of property $search_result.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
621
622
		return ! is_wp_error( $this->search_result );
623
	}
624
625
	/**
626
	 * Given a WP_Query, convert its WP_Tax_Query (if present) into the WP-style Elasticsearch term arguments for the search.
627
	 *
628
	 * @since 5.0.0
629
	 *
630
	 * @param WP_Query $query The original WP_Query object for which to parse the taxonomy query.
631
	 *
632
	 * @return array The new WP-style Elasticsearch arguments (that will be converted into 'real' Elasticsearch arguments).
633
	 */
634
	public function get_es_wp_query_terms_for_query( WP_Query $query ) {
635
		$args = array();
636
637
		$the_tax_query = $query->tax_query;
638
639
		if ( ! $the_tax_query ) {
640
			return $args;
641
		}
642
643
644
		if ( ! $the_tax_query instanceof WP_Tax_Query || empty( $the_tax_query->queried_terms ) || ! is_array( $the_tax_query->queried_terms ) ) {
0 ignored issues
show
Bug introduced by
The class WP_Tax_Query does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
645
			return $args;
646
		}
647
648
		$args = array();
649
650
		foreach ( $the_tax_query->queries as $tax_query ) {
651
			// Right now we only support slugs...see note above
652
			if ( ! is_array( $tax_query ) || 'slug' !== $tax_query['field'] ) {
653
				continue;
654
			}
655
656
			$taxonomy = $tax_query['taxonomy'];
657
658 View Code Duplication
			if ( ! isset( $args[ $taxonomy ] ) || ! is_array( $args[ $taxonomy ] ) ) {
659
				$args[ $taxonomy ] = array();
660
			}
661
662
			$args[ $taxonomy ] = array_merge( $args[ $taxonomy ], $tax_query['terms'] );
663
		}
664
665
		return $args;
666
	}
667
668
	/**
669
	 * Parse out the post type from a WP_Query.
670
	 *
671
	 * Only allows post types that are not marked as 'exclude_from_search'.
672
	 *
673
	 * @since 5.0.0
674
	 *
675
	 * @param WP_Query $query Original WP_Query object.
676
	 *
677
	 * @return array Array of searchable post types corresponding to the original query.
678
	 */
679
	public function get_es_wp_query_post_type_for_query( WP_Query $query ) {
680
		$post_types = $query->get( 'post_type' );
681
682
		// If we're searching 'any', we want to only pass searchable post types to Elasticsearch.
683
		if ( 'any' === $post_types ) {
684
			$post_types = array_values( get_post_types( array(
685
				'exclude_from_search' => false,
686
			) ) );
687
		}
688
689
		if ( ! is_array( $post_types ) ) {
690
			$post_types = array( $post_types );
691
		}
692
693
		$post_types = array_unique( $post_types );
694
695
		$sanitized_post_types = array();
696
697
		// Make sure the post types are queryable.
698
		foreach ( $post_types as $post_type ) {
699
			if ( ! $post_type ) {
700
				continue;
701
			}
702
703
			$post_type_object = get_post_type_object( $post_type );
704
			if ( ! $post_type_object || $post_type_object->exclude_from_search ) {
705
				continue;
706
			}
707
708
			$sanitized_post_types[] = $post_type;
709
		}
710
711
		return $sanitized_post_types;
712
	}
713
714
	/**
715
	 * Get the Elasticsearch result.
716
	 *
717
	 * @since 5.0.0
718
	 *
719
	 * @param bool $raw If true, does not check for WP_Error or return the 'results' array - the JSON decoded HTTP response.
720
	 *
721
	 * @return array|bool The search results, or false if there was a failure.
722
	 */
723
	public function get_search_result( $raw = false ) {
724
		if ( $raw ) {
725
			return $this->search_result;
726
		}
727
728
		return ( ! empty( $this->search_result ) && ! is_wp_error( $this->search_result ) && is_array( $this->search_result ) && ! empty( $this->search_result['results'] ) ) ? $this->search_result['results'] : false;
729
	}
730
731
	/**
732
	 * Add the date portion of a WP_Query onto the query args.
733
	 *
734
	 * @since 5.0.0
735
	 *
736
	 * @param array    $es_wp_query_args The Elasticsearch query arguments in WordPress form.
737
	 * @param WP_Query $query            The original WP_Query.
738
	 *
739
	 * @return array The es wp query args, with date filters added (as needed).
740
	 */
741
	public function filter__add_date_filter_to_query( array $es_wp_query_args, WP_Query $query ) {
742
		if ( $query->get( 'year' ) ) {
743
			if ( $query->get( 'monthnum' ) ) {
744
				// Padding
745
				$date_monthnum = sprintf( '%02d', $query->get( 'monthnum' ) );
746
747
				if ( $query->get( 'day' ) ) {
748
					// Padding
749
					$date_day = sprintf( '%02d', $query->get( 'day' ) );
750
751
					$date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 00:00:00';
752
					$date_end   = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 23:59:59';
753
				} else {
754
					$days_in_month = date( 't', mktime( 0, 0, 0, $query->get( 'monthnum' ), 14, $query->get( 'year' ) ) ); // 14 = middle of the month so no chance of DST issues
755
756
					$date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-01 00:00:00';
757
					$date_end   = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $days_in_month . ' 23:59:59';
758
				}
759
			} else {
760
				$date_start = $query->get( 'year' ) . '-01-01 00:00:00';
761
				$date_end   = $query->get( 'year' ) . '-12-31 23:59:59';
762
			}
763
764
			$es_wp_query_args['date_range'] = array(
765
				'field' => 'date',
766
				'gte'   => $date_start,
767
				'lte'   => $date_end,
768
			);
769
		}
770
771
		return $es_wp_query_args;
772
	}
773
774
	/**
775
	 * Converts WP_Query style args to Elasticsearch args.
776
	 *
777
	 * @since 5.0.0
778
	 *
779
	 * @param array $args Array of WP_Query style arguments.
780
	 *
781
	 * @return array Array of ES style query arguments.
782
	 */
783
	public function convert_wp_es_to_es_args( array $args ) {
784
		jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-parser' );
785
786
		$defaults = array(
787
			'blog_id'        => get_current_blog_id(),
788
			'query'          => null,    // Search phrase
789
			'query_fields'   => array(), // list of fields to search
790
			'excess_boost'   => array(), // map of field to excess boost values (multiply)
791
			'post_type'      => null,    // string or an array
792
			'terms'          => array(), // ex: array( 'taxonomy-1' => array( 'slug' ), 'taxonomy-2' => array( 'slug-a', 'slug-b' ) )
793
			'author'         => null,    // id or an array of ids
794
			'author_name'    => array(), // string or an array
795
			'date_range'     => null,    // array( 'field' => 'date', 'gt' => 'YYYY-MM-dd', 'lte' => 'YYYY-MM-dd' ); date formats: 'YYYY-MM-dd' or 'YYYY-MM-dd HH:MM:SS'
796
			'orderby'        => null,    // Defaults to 'relevance' if query is set, otherwise 'date'. Pass an array for multiple orders.
797
			'order'          => 'DESC',
798
			'posts_per_page' => 10,
799
			'offset'         => null,
800
			'paged'          => null,
801
			/**
802
			 * Aggregations. Examples:
803
			 * array(
804
			 *     'Tag'       => array( 'type' => 'taxonomy', 'taxonomy' => 'post_tag', 'count' => 10 ) ),
805
			 *     'Post Type' => array( 'type' => 'post_type', 'count' => 10 ) ),
806
			 * );
807
			 */
808
			'aggregations'   => null,
809
		);
810
811
		$args = wp_parse_args( $args, $defaults );
812
813
		$parser = new Jetpack_WPES_Search_Query_Parser( $args['query'], array( get_locale() ) );
814
815
		if ( empty( $args['query_fields'] ) ) {
816
			if ( defined( 'JETPACK_SEARCH_VIP_INDEX' ) && JETPACK_SEARCH_VIP_INDEX ) {
817
				// VIP indices do not have per language fields
818
				$match_fields = $this->_get_caret_boosted_fields(
819
					array(
820
						'title'         => 0.1,
821
						'content'       => 0.1,
822
						'excerpt'       => 0.1,
823
						'tag.name'      => 0.1,
824
						'category.name' => 0.1,
825
						'author_login'  => 0.1,
826
						'author'        => 0.1,
827
					)
828
				);
829
830
				$boost_fields = $this->_get_caret_boosted_fields(
831
					$this->_apply_boosts_multiplier( array(
832
						'title'         => 2,
833
						'tag.name'      => 1,
834
						'category.name' => 1,
835
						'author_login'  => 1,
836
						'author'        => 1,
837
					), $args['excess_boost'] )
838
				);
839
840
				$boost_phrase_fields = $this->_get_caret_boosted_fields(
841
					array(
842
						'title'         => 1,
843
						'content'       => 1,
844
						'excerpt'       => 1,
845
						'tag.name'      => 1,
846
						'category.name' => 1,
847
						'author'        => 1,
848
					)
849
				);
850
			} else {
851
				$match_fields = $parser->merge_ml_fields(
852
					array(
853
						'title'         => 0.1,
854
						'content'       => 0.1,
855
						'excerpt'       => 0.1,
856
						'tag.name'      => 0.1,
857
						'category.name' => 0.1,
858
					),
859
					$this->_get_caret_boosted_fields( array(
860
						'author_login'  => 0.1,
861
						'author'        => 0.1,
862
					) )
863
				);
864
865
				$boost_fields = $parser->merge_ml_fields(
866
					$this->_apply_boosts_multiplier( array(
867
						'title'         => 2,
868
						'tag.name'      => 1,
869
						'category.name' => 1,
870
					), $args['excess_boost'] ),
871
					$this->_get_caret_boosted_fields( $this->_apply_boosts_multiplier( array(
872
						'author_login'  => 1,
873
						'author'        => 1,
874
					), $args['excess_boost'] ) )
875
				);
876
877
				$boost_phrase_fields = $parser->merge_ml_fields(
878
					array(
879
						'title'         => 1,
880
						'content'       => 1,
881
						'excerpt'       => 1,
882
						'tag.name'      => 1,
883
						'category.name' => 1,
884
					),
885
					$this->_get_caret_boosted_fields( array(
886
						'author'        => 1,
887
					) )
888
				);
889
			}
890
		} else {
891
			// If code is overriding the fields, then use that. Important for backwards compatibility.
892
			$match_fields        = $args['query_fields'];
893
			$boost_phrase_fields = $match_fields;
894
			$boost_fields        = null;
895
		}
896
897
		$parser->phrase_filter( array(
898
			'must_query_fields'  => $match_fields,
899
			'boost_query_fields' => null,
900
		) );
901
		$parser->remaining_query( array(
902
			'must_query_fields'  => $match_fields,
903
			'boost_query_fields' => $boost_fields,
904
		) );
905
906
		// Boost on phrase matches
907
		$parser->remaining_query( array(
908
			'boost_query_fields' => $boost_phrase_fields,
909
			'boost_query_type'   => 'phrase',
910
		) );
911
912
		/**
913
		 * Modify the recency decay parameters for the search query.
914
		 *
915
		 * The recency decay lowers the search scores based on the age of a post relative to an origin date. Basic adjustments:
916
		 *  - origin: A date. Posts with this date will have the highest score and no decay applied. Default is today.
917
		 *  - offset: Number of days/months/years (eg 30d). All posts within this time range of the origin (before and after) will have no decay applied. Default is no offset.
918
		 *  - scale: The number of days/months/years from the origin+offset at which the decay will equal the decay param. Default 360d
919
		 *  - decay: The amount of decay applied at offset+scale. Default 0.9.
920
		 *
921
		 * The curve applied is a Gaussian. More details available at {@see https://www.elastic.co/guide/en/elasticsearch/reference/current/query-dsl-function-score-query.html#function-decay}
922
		 *
923
		 * @module search
924
		 *
925
		 * @since  5.8.0
926
		 *
927
		 * @param array $decay_params The decay parameters.
928
		 * @param array $args         The WP query parameters.
929
		 */
930
		$decay_params = apply_filters(
931
			'jetpack_search_recency_score_decay',
932
			array(
933
				'origin' => date( 'Y-m-d' ),
934
				'scale'  => '360d',
935
				'decay'  => 0.9,
936
			),
937
			$args
938
		);
939
940
		if ( ! empty( $decay_params ) ) {
941
			// Newer content gets weighted slightly higher
942
			$parser->add_decay( 'gauss', array(
943
				'date_gmt' => $decay_params
944
			) );
945
		}
946
947
		$es_query_args = array(
948
			'blog_id' => absint( $args['blog_id'] ),
949
			'size'    => absint( $args['posts_per_page'] ),
950
		);
951
952
		// ES "from" arg (offset)
953
		if ( $args['offset'] ) {
954
			$es_query_args['from'] = absint( $args['offset'] );
955
		} elseif ( $args['paged'] ) {
956
			$es_query_args['from'] = max( 0, ( absint( $args['paged'] ) - 1 ) * $es_query_args['size'] );
957
		}
958
959
		$es_query_args['from'] = min( $es_query_args['from'], Jetpack_Search_Helpers::get_max_offset() );
960
961
		if ( ! is_array( $args['author_name'] ) ) {
962
			$args['author_name'] = array( $args['author_name'] );
963
		}
964
965
		// ES stores usernames, not IDs, so transform
966
		if ( ! empty( $args['author'] ) ) {
967
			if ( ! is_array( $args['author'] ) ) {
968
				$args['author'] = array( $args['author'] );
969
			}
970
971
			foreach ( $args['author'] as $author ) {
972
				$user = get_user_by( 'id', $author );
973
974
				if ( $user && ! empty( $user->user_login ) ) {
975
					$args['author_name'][] = $user->user_login;
976
				}
977
			}
978
		}
979
980
		//////////////////////////////////////////////////
981
		// Build the filters from the query elements.
982
		// Filters rock because they are cached from one query to the next
983
		// but they are cached as individual filters, rather than all combined together.
984
		// May get performance boost by also caching the top level boolean filter too.
985
986
		if ( $args['post_type'] ) {
987
			if ( ! is_array( $args['post_type'] ) ) {
988
				$args['post_type'] = array( $args['post_type'] );
989
			}
990
991
			$parser->add_filter( array(
992
				'terms' => array(
993
					'post_type' => $args['post_type'],
994
				),
995
			) );
996
		}
997
998
		if ( $args['author_name'] ) {
999
			$parser->add_filter( array(
1000
				'terms' => array(
1001
					'author_login' => $args['author_name'],
1002
				),
1003
			) );
1004
		}
1005
1006
		if ( ! empty( $args['date_range'] ) && isset( $args['date_range']['field'] ) ) {
1007
			$field = $args['date_range']['field'];
1008
1009
			unset( $args['date_range']['field'] );
1010
1011
			$parser->add_filter( array(
1012
				'range' => array(
1013
					$field => $args['date_range'],
1014
				),
1015
			) );
1016
		}
1017
1018
		if ( is_array( $args['terms'] ) ) {
1019
			foreach ( $args['terms'] as $tax => $terms ) {
1020
				$terms = (array) $terms;
1021
1022
				if ( count( $terms ) && mb_strlen( $tax ) ) {
1023 View Code Duplication
					switch ( $tax ) {
1024
						case 'post_tag':
1025
							$tax_fld = 'tag.slug';
1026
1027
							break;
1028
1029
						case 'category':
1030
							$tax_fld = 'category.slug';
1031
1032
							break;
1033
1034
						default:
1035
							$tax_fld = 'taxonomy.' . $tax . '.slug';
1036
1037
							break;
1038
					}
1039
1040
					foreach ( $terms as $term ) {
1041
						$parser->add_filter( array(
1042
							'term' => array(
1043
								$tax_fld => $term,
1044
							),
1045
						) );
1046
					}
1047
				}
1048
			}
1049
		}
1050
1051
		if ( ! $args['orderby'] ) {
1052
			if ( $args['query'] ) {
1053
				$args['orderby'] = array( 'relevance' );
1054
			} else {
1055
				$args['orderby'] = array( 'date' );
1056
			}
1057
		}
1058
1059
		// Validate the "order" field
1060
		switch ( strtolower( $args['order'] ) ) {
1061
			case 'asc':
1062
				$args['order'] = 'asc';
1063
				break;
1064
1065
			case 'desc':
1066
			default:
1067
				$args['order'] = 'desc';
1068
				break;
1069
		}
1070
1071
		$es_query_args['sort'] = array();
1072
1073
		foreach ( (array) $args['orderby'] as $orderby ) {
1074
			// Translate orderby from WP field to ES field
1075
			switch ( $orderby ) {
1076
				case 'relevance' :
1077
					//never order by score ascending
1078
					$es_query_args['sort'][] = array(
1079
						'_score' => array(
1080
							'order' => 'desc',
1081
						),
1082
					);
1083
1084
					break;
1085
1086 View Code Duplication
				case 'date' :
1087
					$es_query_args['sort'][] = array(
1088
						'date' => array(
1089
							'order' => $args['order'],
1090
						),
1091
					);
1092
1093
					break;
1094
1095 View Code Duplication
				case 'ID' :
1096
					$es_query_args['sort'][] = array(
1097
						'id' => array(
1098
							'order' => $args['order'],
1099
						),
1100
					);
1101
1102
					break;
1103
1104
				case 'author' :
1105
					$es_query_args['sort'][] = array(
1106
						'author.raw' => array(
1107
							'order' => $args['order'],
1108
						),
1109
					);
1110
1111
					break;
1112
			} // End switch().
1113
		} // End foreach().
1114
1115
		if ( empty( $es_query_args['sort'] ) ) {
1116
			unset( $es_query_args['sort'] );
1117
		}
1118
1119
		// Aggregations
1120
		if ( ! empty( $args['aggregations'] ) ) {
1121
			$this->add_aggregations_to_es_query_builder( $args['aggregations'], $parser );
0 ignored issues
show
Documentation introduced by
$args['aggregations'] is of type string, but the function expects a array.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
1122
		}
1123
1124
		$es_query_args['filter']       = $parser->build_filter();
1125
		$es_query_args['query']        = $parser->build_query();
1126
		$es_query_args['aggregations'] = $parser->build_aggregation();
1127
1128
		return $es_query_args;
1129
	}
1130
1131
	/**
1132
	 * Given an array of aggregations, parse and add them onto the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1133
	 *
1134
	 * @since 5.0.0
1135
	 *
1136
	 * @param array                      $aggregations Array of aggregations (filters) to add to the Jetpack_WPES_Query_Builder.
1137
	 * @param Jetpack_WPES_Query_Builder $builder      The builder instance that is creating the Elasticsearch query.
1138
	 */
1139
	public function add_aggregations_to_es_query_builder( array $aggregations, Jetpack_WPES_Query_Builder $builder ) {
1140
		foreach ( $aggregations as $label => $aggregation ) {
1141
			switch ( $aggregation['type'] ) {
1142
				case 'taxonomy':
1143
					$this->add_taxonomy_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1144
1145
					break;
1146
1147
				case 'post_type':
1148
					$this->add_post_type_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1149
1150
					break;
1151
1152
				case 'date_histogram':
1153
					$this->add_date_histogram_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1154
1155
					break;
1156
			}
1157
		}
1158
	}
1159
1160
	/**
1161
	 * Given an individual taxonomy aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1162
	 *
1163
	 * @since 5.0.0
1164
	 *
1165
	 * @param array                      $aggregation The aggregation to add to the query builder.
1166
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1167
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1168
	 */
1169
	public function add_taxonomy_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1170
		$field = null;
0 ignored issues
show
Unused Code introduced by
$field is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
1171
1172
		switch ( $aggregation['taxonomy'] ) {
1173
			case 'post_tag':
1174
				$field = 'tag';
1175
				break;
1176
1177
			case 'category':
1178
				$field = 'category';
1179
				break;
1180
1181
			default:
1182
				$field = 'taxonomy.' . $aggregation['taxonomy'];
1183
				break;
1184
		}
1185
1186
		$builder->add_aggs( $label, array(
1187
			'terms' => array(
1188
				'field' => $field . '.slug',
1189
				'size'  => min( (int) $aggregation['count'], $this->max_aggregations_count ),
1190
			),
1191
		) );
1192
	}
1193
1194
	/**
1195
	 * Given an individual post_type aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1196
	 *
1197
	 * @since 5.0.0
1198
	 *
1199
	 * @param array                      $aggregation The aggregation to add to the query builder.
1200
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1201
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1202
	 */
1203
	public function add_post_type_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1204
		$builder->add_aggs( $label, array(
1205
			'terms' => array(
1206
				'field' => 'post_type',
1207
				'size'  => min( (int) $aggregation['count'], $this->max_aggregations_count ),
1208
			),
1209
		) );
1210
	}
1211
1212
	/**
1213
	 * Given an individual date_histogram aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1214
	 *
1215
	 * @since 5.0.0
1216
	 *
1217
	 * @param array                      $aggregation The aggregation to add to the query builder.
1218
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1219
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1220
	 */
1221
	public function add_date_histogram_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1222
		$args = array(
1223
			'interval' => $aggregation['interval'],
1224
			'field'    => ( ! empty( $aggregation['field'] ) && 'post_date_gmt' == $aggregation['field'] ) ? 'date_gmt' : 'date',
1225
		);
1226
1227
		if ( isset( $aggregation['min_doc_count'] ) ) {
1228
			$args['min_doc_count'] = intval( $aggregation['min_doc_count'] );
1229
		} else {
1230
			$args['min_doc_count'] = 1;
1231
		}
1232
1233
		$builder->add_aggs( $label, array(
1234
			'date_histogram' => $args,
1235
		) );
1236
	}
1237
1238
	/**
1239
	 * And an existing filter object with a list of additional filters.
1240
	 *
1241
	 * Attempts to optimize the filters somewhat.
1242
	 *
1243
	 * @since 5.0.0
1244
	 *
1245
	 * @param array $curr_filter The existing filters to build upon.
1246
	 * @param array $filters     The new filters to add.
1247
	 *
1248
	 * @return array The resulting merged filters.
1249
	 */
1250
	public static function and_es_filters( array $curr_filter, array $filters ) {
1251
		if ( ! is_array( $curr_filter ) || isset( $curr_filter['match_all'] ) ) {
1252
			if ( 1 === count( $filters ) ) {
1253
				return $filters[0];
1254
			}
1255
1256
			return array(
1257
				'and' => $filters,
1258
			);
1259
		}
1260
1261
		return array(
1262
			'and' => array_merge( array( $curr_filter ), $filters ),
1263
		);
1264
	}
1265
1266
	/**
1267
	 * Set the available filters for the search.
1268
	 *
1269
	 * These get rendered via the Jetpack_Search_Widget() widget.
1270
	 *
1271
	 * Behind the scenes, these are implemented using Elasticsearch Aggregations.
1272
	 *
1273
	 * If you do not require counts of how many documents match each filter, please consider using regular WP Query
1274
	 * arguments instead, such as via the jetpack_search_es_wp_query_args filter
1275
	 *
1276
	 * @see    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
1277
	 *
1278
	 * @since  5.0.0
1279
	 *
1280
	 * @param array $aggregations Array of filters (aggregations) to apply to the search
1281
	 */
1282
	public function set_filters( array $aggregations ) {
1283
		foreach ( (array) $aggregations as $key => $agg ) {
1284
			if ( empty( $agg['name'] ) ) {
1285
				$aggregations[ $key ]['name'] = $key;
1286
			}
1287
		}
1288
		$this->aggregations = $aggregations;
1289
	}
1290
1291
	/**
1292
	 * Set the search's facets (deprecated).
1293
	 *
1294
	 * @deprecated 5.0 Please use Jetpack_Search::set_filters() instead.
1295
	 *
1296
	 * @see        Jetpack_Search::set_filters()
1297
	 *
1298
	 * @param array $facets Array of facets to apply to the search.
1299
	 */
1300
	public function set_facets( array $facets ) {
1301
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::set_filters()' );
1302
1303
		$this->set_filters( $facets );
1304
	}
1305
1306
	/**
1307
	 * Get the raw Aggregation results from the Elasticsearch response.
1308
	 *
1309
	 * @since  5.0.0
1310
	 *
1311
	 * @see    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
1312
	 *
1313
	 * @return array Array of Aggregations performed on the search.
1314
	 */
1315
	public function get_search_aggregations_results() {
1316
		$aggregations = array();
1317
1318
		$search_result = $this->get_search_result();
1319
1320
		if ( ! empty( $search_result ) && ! empty( $search_result['aggregations'] ) ) {
1321
			$aggregations = $search_result['aggregations'];
1322
		}
1323
1324
		return $aggregations;
1325
	}
1326
1327
	/**
1328
	 * Get the raw Facet results from the Elasticsearch response.
1329
	 *
1330
	 * @deprecated 5.0 Please use Jetpack_Search::get_search_aggregations_results() instead.
1331
	 *
1332
	 * @see        Jetpack_Search::get_search_aggregations_results()
1333
	 *
1334
	 * @return array Array of Facets performed on the search.
1335
	 */
1336
	public function get_search_facets() {
1337
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_search_aggregations_results()' );
1338
1339
		return $this->get_search_aggregations_results();
1340
	}
1341
1342
	/**
1343
	 * Get the results of the Filters performed, including the number of matching documents.
1344
	 *
1345
	 * Returns an array of Filters (keyed by $label, as passed to Jetpack_Search::set_filters()), containing the Filter and all resulting
1346
	 * matching buckets, the url for applying/removing each bucket, etc.
1347
	 *
1348
	 * NOTE - if this is called before the search is performed, an empty array will be returned. Use the $aggregations class
1349
	 * member if you need to access the raw filters set in Jetpack_Search::set_filters().
1350
	 *
1351
	 * @since 5.0.0
1352
	 *
1353
	 * @param WP_Query $query The optional original WP_Query to use for determining which filters are active. Defaults to the main query.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $query not be null|WP_Query?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
1354
	 *
1355
	 * @return array Array of filters applied and info about them.
1356
	 */
1357
	public function get_filters( WP_Query $query = null ) {
1358
		if ( ! $query instanceof WP_Query ) {
0 ignored issues
show
Bug introduced by
The class WP_Query does not exist. Did you forget a USE statement, or did you not list all dependencies?

This error could be the result of:

1. Missing dependencies

PHP Analyzer uses your composer.json file (if available) to determine the dependencies of your project and to determine all the available classes and functions. It expects the composer.json to be in the root folder of your repository.

Are you sure this class is defined by one of your dependencies, or did you maybe not list a dependency in either the require or require-dev section?

2. Missing use statement

PHP does not complain about undefined classes in ìnstanceof checks. For example, the following PHP code will work perfectly fine:

if ($x instanceof DoesNotExist) {
    // Do something.
}

If you have not tested against this specific condition, such errors might go unnoticed.

Loading history...
1359
			global $wp_query;
1360
1361
			$query = $wp_query;
1362
		}
1363
1364
		$aggregation_data = $this->aggregations;
1365
1366
		if ( empty( $aggregation_data ) ) {
1367
			return $aggregation_data;
1368
		}
1369
1370
		$aggregation_results = $this->get_search_aggregations_results();
1371
1372
		if ( ! $aggregation_results ) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $aggregation_results of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1373
			return $aggregation_data;
1374
		}
1375
1376
		// NOTE - Looping over the _results_, not the original configured aggregations, so we get the 'real' data from ES
1377
		foreach ( $aggregation_results as $label => $aggregation ) {
1378
			if ( empty( $aggregation ) ) {
1379
				continue;
1380
			}
1381
1382
			$type = $this->aggregations[ $label ]['type'];
1383
1384
			$aggregation_data[ $label ]['buckets'] = array();
1385
1386
			$existing_term_slugs = array();
1387
1388
			$tax_query_var = null;
1389
1390
			// Figure out which terms are active in the query, for this taxonomy
1391
			if ( 'taxonomy' === $this->aggregations[ $label ]['type'] ) {
1392
				$tax_query_var = $this->get_taxonomy_query_var( $this->aggregations[ $label ]['taxonomy'] );
1393
1394
				if ( ! empty( $query->tax_query ) && ! empty( $query->tax_query->queries ) && is_array( $query->tax_query->queries ) ) {
1395
					foreach ( $query->tax_query->queries as $tax_query ) {
1396
						if ( is_array( $tax_query ) && $this->aggregations[ $label ]['taxonomy'] === $tax_query['taxonomy'] &&
1397
						     'slug' === $tax_query['field'] &&
1398
						     is_array( $tax_query['terms'] ) ) {
1399
							$existing_term_slugs = array_merge( $existing_term_slugs, $tax_query['terms'] );
1400
						}
1401
					}
1402
				}
1403
			}
1404
1405
			// Now take the resulting found aggregation items and generate the additional info about them, such as activation/deactivation url, name, count, etc.
1406
			$buckets = array();
1407
1408
			if ( ! empty( $aggregation['buckets'] ) ) {
1409
				$buckets = (array) $aggregation['buckets'];
1410
			}
1411
1412
			if ( 'date_histogram' == $type ) {
1413
				//re-order newest to oldest
1414
				$buckets = array_reverse( $buckets );
1415
			}
1416
1417
			// Some aggregation types like date_histogram don't support the max results parameter
1418
			if ( is_int( $this->aggregations[ $label ]['count'] ) && count( $buckets ) > $this->aggregations[ $label ]['count'] ) {
1419
				$buckets = array_slice( $buckets, 0, $this->aggregations[ $label ]['count'] );
1420
			}
1421
1422
			foreach ( $buckets as $item ) {
1423
				$query_vars = array();
1424
				$active     = false;
1425
				$remove_url = null;
1426
				$name       = '';
1427
1428
				// What type was the original aggregation?
1429
				switch ( $type ) {
1430
					case 'taxonomy':
1431
						$taxonomy = $this->aggregations[ $label ]['taxonomy'];
1432
1433
						$term = get_term_by( 'slug', $item['key'], $taxonomy );
1434
1435
						if ( ! $term || ! $tax_query_var ) {
1436
							continue 2; // switch() is considered a looping structure
1437
						}
1438
1439
						$query_vars = array(
1440
							$tax_query_var => implode( '+', array_merge( $existing_term_slugs, array( $term->slug ) ) ),
1441
						);
1442
1443
						$name = $term->name;
1444
1445
						// Let's determine if this term is active or not
1446
1447
						if ( in_array( $item['key'], $existing_term_slugs, true ) ) {
1448
							$active = true;
1449
1450
							$slug_count = count( $existing_term_slugs );
1451
1452 View Code Duplication
							if ( $slug_count > 1 ) {
1453
								$remove_url = Jetpack_Search_Helpers::add_query_arg(
1454
									$tax_query_var,
0 ignored issues
show
Bug introduced by
It seems like $tax_query_var can also be of type boolean; however, Jetpack_Search_Helpers::add_query_arg() does only seem to accept string|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1455
									rawurlencode( implode( '+', array_diff( $existing_term_slugs, array( $item['key'] ) ) ) )
1456
								);
1457
							} else {
1458
								$remove_url = Jetpack_Search_Helpers::remove_query_arg( $tax_query_var );
0 ignored issues
show
Bug introduced by
It seems like $tax_query_var can also be of type boolean; however, Jetpack_Search_Helpers::remove_query_arg() does only seem to accept string|array, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
1459
							}
1460
						}
1461
1462
						break;
1463
1464
					case 'post_type':
1465
						$post_type = get_post_type_object( $item['key'] );
1466
1467
						if ( ! $post_type || $post_type->exclude_from_search ) {
1468
							continue 2;  // switch() is considered a looping structure
1469
						}
1470
1471
						$query_vars = array(
1472
							'post_type' => $item['key'],
1473
						);
1474
1475
						$name = $post_type->labels->singular_name;
1476
1477
						// Is this post type active on this search?
1478
						$post_types = $query->get( 'post_type' );
1479
1480
						if ( ! is_array( $post_types ) ) {
1481
							$post_types = array( $post_types );
1482
						}
1483
1484
						if ( in_array( $item['key'], $post_types ) ) {
1485
							$active = true;
1486
1487
							$post_type_count = count( $post_types );
1488
1489
							// For the right 'remove filter' url, we need to remove the post type from the array, or remove the param entirely if it's the only one
1490 View Code Duplication
							if ( $post_type_count > 1 ) {
1491
								$remove_url = Jetpack_Search_Helpers::add_query_arg(
1492
									'post_type',
1493
									rawurlencode( implode( ',', array_diff( $post_types, array( $item['key'] ) ) ) )
1494
								);
1495
							} else {
1496
								$remove_url = Jetpack_Search_Helpers::remove_query_arg( 'post_type' );
1497
							}
1498
						}
1499
1500
						break;
1501
1502
					case 'date_histogram':
1503
						$timestamp = $item['key'] / 1000;
1504
1505
						$current_year  = $query->get( 'year' );
1506
						$current_month = $query->get( 'monthnum' );
1507
						$current_day   = $query->get( 'day' );
1508
1509
						switch ( $this->aggregations[ $label ]['interval'] ) {
1510
							case 'year':
1511
								$year = (int) date( 'Y', $timestamp );
1512
1513
								$query_vars = array(
1514
									'year'     => $year,
1515
									'monthnum' => false,
1516
									'day'      => false,
1517
								);
1518
1519
								$name = $year;
1520
1521
								// Is this year currently selected?
1522
								if ( ! empty( $current_year ) && (int) $current_year === $year ) {
1523
									$active = true;
1524
1525
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum', 'day' ) );
1526
								}
1527
1528
								break;
1529
1530
							case 'month':
1531
								$year  = (int) date( 'Y', $timestamp );
1532
								$month = (int) date( 'n', $timestamp );
1533
1534
								$query_vars = array(
1535
									'year'     => $year,
1536
									'monthnum' => $month,
1537
									'day'      => false,
1538
								);
1539
1540
								$name = date( 'F Y', $timestamp );
1541
1542
								// Is this month currently selected?
1543
								if ( ! empty( $current_year ) && (int) $current_year === $year &&
1544
								     ! empty( $current_month ) && (int) $current_month === $month ) {
1545
									$active = true;
1546
1547
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum' ) );
1548
								}
1549
1550
								break;
1551
1552
							case 'day':
1553
								$year  = (int) date( 'Y', $timestamp );
1554
								$month = (int) date( 'n', $timestamp );
1555
								$day   = (int) date( 'j', $timestamp );
1556
1557
								$query_vars = array(
1558
									'year'     => $year,
1559
									'monthnum' => $month,
1560
									'day'      => $day,
1561
								);
1562
1563
								$name = date( 'F jS, Y', $timestamp );
1564
1565
								// Is this day currently selected?
1566
								if ( ! empty( $current_year ) && (int) $current_year === $year &&
1567
								     ! empty( $current_month ) && (int) $current_month === $month &&
1568
								     ! empty( $current_day ) && (int) $current_day === $day ) {
1569
									$active = true;
1570
1571
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'day' ) );
1572
								}
1573
1574
								break;
1575
1576
							default:
1577
								continue 3; // switch() is considered a looping structure
1578
						} // End switch().
1579
1580
						break;
1581
1582
					default:
1583
						//continue 2; // switch() is considered a looping structure
1584
				} // End switch().
1585
1586
				// Need to urlencode param values since add_query_arg doesn't
1587
				$url_params = urlencode_deep( $query_vars );
1588
1589
				$aggregation_data[ $label ]['buckets'][] = array(
1590
					'url'        => Jetpack_Search_Helpers::add_query_arg( $url_params ),
1591
					'query_vars' => $query_vars,
1592
					'name'       => $name,
1593
					'count'      => $item['doc_count'],
1594
					'active'     => $active,
1595
					'remove_url' => $remove_url,
1596
					'type'       => $type,
1597
					'type_label' => $aggregation_data[ $label ]['name'],
1598
					'widget_id'  => ! empty( $aggregation_data[ $label ]['widget_id'] ) ? $aggregation_data[ $label ]['widget_id'] : 0
1599
				);
1600
			} // End foreach().
1601
		} // End foreach().
1602
1603
		/**
1604
		 * Modify the aggregation filters returned by get_filters().
1605
		 *
1606
		 * Useful if you are setting custom filters outside of the supported filters (taxonomy, post_type etc.) and
1607
		 * want to hook them up so they're returned when you call `get_filters()`.
1608
		 *
1609
		 * @module search
1610
		 *
1611
		 * @since  6.9.0
1612
		 *
1613
		 * @param array    $aggregation_data The array of filters keyed on label.
1614
		 * @param WP_Query $query            The WP_Query object.
1615
		 */
1616
		return apply_filters( 'jetpack_search_get_filters', $aggregation_data, $query );
1617
	}
1618
1619
	/**
1620
	 * Get the results of the facets performed.
1621
	 *
1622
	 * @deprecated 5.0 Please use Jetpack_Search::get_filters() instead.
1623
	 *
1624
	 * @see        Jetpack_Search::get_filters()
1625
	 *
1626
	 * @return array $facets Array of facets applied and info about them.
1627
	 */
1628
	public function get_search_facet_data() {
1629
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_filters()' );
1630
1631
		return $this->get_filters();
1632
	}
1633
1634
	/**
1635
	 * Get the filters that are currently applied to this search.
1636
	 *
1637
	 * @since 5.0.0
1638
	 *
1639
	 * @return array Array of filters that were applied.
1640
	 */
1641
	public function get_active_filter_buckets() {
1642
		$active_buckets = array();
1643
1644
		$filters = $this->get_filters();
1645
1646
		if ( ! is_array( $filters ) ) {
1647
			return $active_buckets;
1648
		}
1649
1650
		foreach ( $filters as $filter ) {
1651
			if ( isset( $filter['buckets'] ) && is_array( $filter['buckets'] ) ) {
1652
				foreach ( $filter['buckets'] as $item ) {
1653
					if ( isset( $item['active'] ) && $item['active'] ) {
1654
						$active_buckets[] = $item;
1655
					}
1656
				}
1657
			}
1658
		}
1659
1660
		return $active_buckets;
1661
	}
1662
1663
	/**
1664
	 * Get the filters that are currently applied to this search.
1665
	 *
1666
	 * @deprecated 5.0 Please use Jetpack_Search::get_active_filter_buckets() instead.
1667
	 *
1668
	 * @see        Jetpack_Search::get_active_filter_buckets()
1669
	 *
1670
	 * @return array Array of filters that were applied.
1671
	 */
1672
	public function get_current_filters() {
1673
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_active_filter_buckets()' );
1674
1675
		return $this->get_active_filter_buckets();
1676
	}
1677
1678
	/**
1679
	 * Calculate the right query var to use for a given taxonomy.
1680
	 *
1681
	 * Allows custom code to modify the GET var that is used to represent a given taxonomy, via the jetpack_search_taxonomy_query_var filter.
1682
	 *
1683
	 * @since 5.0.0
1684
	 *
1685
	 * @param string $taxonomy_name The name of the taxonomy for which to get the query var.
1686
	 *
1687
	 * @return bool|string The query var to use for this taxonomy, or false if none found.
1688
	 */
1689
	public function get_taxonomy_query_var( $taxonomy_name ) {
1690
		$taxonomy = get_taxonomy( $taxonomy_name );
1691
1692
		if ( ! $taxonomy || is_wp_error( $taxonomy ) ) {
1693
			return false;
1694
		}
1695
1696
		/**
1697
		 * Modify the query var to use for a given taxonomy
1698
		 *
1699
		 * @module search
1700
		 *
1701
		 * @since  5.0.0
1702
		 *
1703
		 * @param string $query_var     The current query_var for the taxonomy
1704
		 * @param string $taxonomy_name The taxonomy name
1705
		 */
1706
		return apply_filters( 'jetpack_search_taxonomy_query_var', $taxonomy->query_var, $taxonomy_name );
1707
	}
1708
1709
	/**
1710
	 * Takes an array of aggregation results, and ensures the array key ordering matches the key order in $desired
1711
	 * which is the input order.
1712
	 *
1713
	 * Necessary because ES does not always return aggregations in the same order that you pass them in,
1714
	 * and it should be possible to control the display order easily.
1715
	 *
1716
	 * @since 5.0.0
1717
	 *
1718
	 * @param array $aggregations Aggregation results to be reordered.
1719
	 * @param array $desired      Array with keys representing the desired ordering.
1720
	 *
1721
	 * @return array A new array with reordered keys, matching those in $desired.
1722
	 */
1723
	public function fix_aggregation_ordering( array $aggregations, array $desired ) {
1724
		if ( empty( $aggregations ) || empty( $desired ) ) {
1725
			return $aggregations;
1726
		}
1727
1728
		$reordered = array();
1729
1730
		foreach ( array_keys( $desired ) as $agg_name ) {
1731
			if ( isset( $aggregations[ $agg_name ] ) ) {
1732
				$reordered[ $agg_name ] = $aggregations[ $agg_name ];
1733
			}
1734
		}
1735
1736
		return $reordered;
1737
	}
1738
1739
	/**
1740
	 * Sends events to Tracks when a search filters widget is updated.
1741
	 *
1742
	 * @since 5.8.0
1743
	 *
1744
	 * @param string $option    The option name. Only "widget_jetpack-search-filters" is cared about.
1745
	 * @param array  $old_value The old option value.
1746
	 * @param array  $new_value The new option value.
1747
	 */
1748
	public function track_widget_updates( $option, $old_value, $new_value ) {
1749
		if ( 'widget_jetpack-search-filters' !== $option ) {
1750
			return;
1751
		}
1752
1753
		$event = Jetpack_Search_Helpers::get_widget_tracks_value( $old_value, $new_value );
1754
		if ( ! $event ) {
1755
			return;
1756
		}
1757
1758
		jetpack_tracks_record_event(
1759
			wp_get_current_user(),
1760
			sprintf( 'jetpack_search_widget_%s', $event['action'] ),
1761
			$event['widget']
1762
		);
1763
	}
1764
1765
	/**
1766
	 * Moves any active search widgets to the inactive category.
1767
	 *
1768
	 * @since 5.9.0
1769
	 *
1770
	 * @param string $module Unused. The Jetpack module being disabled.
1771
	 */
1772
	public function move_search_widgets_to_inactive( $module ) {
1773
		if ( ! is_active_widget( false, false, Jetpack_Search_Helpers::FILTER_WIDGET_BASE, true ) ) {
1774
			return;
1775
		}
1776
1777
		$sidebars_widgets = wp_get_sidebars_widgets();
1778
1779
		if ( ! is_array( $sidebars_widgets ) ) {
1780
			return;
1781
		}
1782
1783
		$changed = false;
1784
1785
		foreach ( $sidebars_widgets as $sidebar => $widgets ) {
1786
			if ( 'wp_inactive_widgets' === $sidebar || 'orphaned_widgets' === substr( $sidebar, 0, 16 ) ) {
1787
				continue;
1788
			}
1789
1790
			if ( is_array( $widgets ) ) {
1791
				foreach ( $widgets as $key => $widget ) {
1792
					if ( _get_widget_id_base( $widget ) == Jetpack_Search_Helpers::FILTER_WIDGET_BASE ) {
1793
						$changed = true;
1794
1795
						array_unshift( $sidebars_widgets['wp_inactive_widgets'], $widget );
1796
						unset( $sidebars_widgets[ $sidebar ][ $key ] );
1797
					}
1798
				}
1799
			}
1800
		}
1801
1802
		if ( $changed ) {
1803
			wp_set_sidebars_widgets( $sidebars_widgets );
1804
		}
1805
	}
1806
1807
	/**
1808
	 * Determine whether a given WP_Query should be handled by ElasticSearch.
1809
	 *
1810
	 * @param WP_Query $query The WP_Query object.
1811
	 *
1812
	 * @return bool
1813
	 */
1814
	public function should_handle_query( $query ) {
1815
		/**
1816
		 * Determine whether a given WP_Query should be handled by ElasticSearch.
1817
		 *
1818
		 * @module search
1819
		 *
1820
		 * @since  5.6.0
1821
		 *
1822
		 * @param bool     $should_handle Should be handled by Jetpack Search.
1823
		 * @param WP_Query $query         The WP_Query object.
1824
		 */
1825
		return apply_filters( 'jetpack_search_should_handle_query', $query->is_main_query() && $query->is_search(), $query );
1826
	}
1827
1828
	/**
1829
	 * Transforms an array with fields name as keys and boosts as value into
1830
	 * shorthand "caret" format.
1831
	 *
1832
	 * @param array $fields_boost [ "title" => "2", "content" => "1" ]
1833
	 *
1834
	 * @return array [ "title^2", "content^1" ]
1835
	 */
1836
	private function _get_caret_boosted_fields( array $fields_boost ) {
1837
		$caret_boosted_fields = array();
1838
		foreach ( $fields_boost as $field => $boost ) {
1839
			$caret_boosted_fields[] = "$field^$boost";
1840
		}
1841
		return $caret_boosted_fields;
1842
	}
1843
1844
	/**
1845
	 * Apply a multiplier to boost values.
1846
	 *
1847
	 * @param array $fields_boost [ "title" => 2, "content" => 1 ]
1848
	 * @param array $fields_boost_multiplier [ "title" => 0.1234 ]
1849
	 *
1850
	 * @return array [ "title" => "0.247", "content" => "1.000" ]
1851
	 */
1852
	private function _apply_boosts_multiplier( array $fields_boost, array $fields_boost_multiplier ) {
1853
		foreach( $fields_boost as $field_name => $field_boost ) {
1854
			if ( isset( $fields_boost_multiplier[ $field_name ] ) ) {
1855
				$fields_boost[ $field_name ] *= $fields_boost_multiplier[ $field_name ];
1856
			}
1857
1858
			// Set a floor and format the number as string
1859
			$fields_boost[ $field_name ] = number_format(
1860
				max( 0.001, $fields_boost[ $field_name ] ),
1861
				3, '.', ''
1862
			);
1863
		}
1864
1865
		return $fields_boost;
1866
	}
1867
}
1868