Completed
Push — gm18/grunionblock ( c0d4d9...98e9b9 )
by George
10:00 queued 01:55
created

Jetpack_Search::_apply_boosts_multiplier()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 15

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 3
nop 2
dl 0
loc 15
rs 9.7666
c 0
b 0
f 0
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 ( $query->is_main_query() && $query->is_search && ! 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
		/**
446
		 * Determine whether a given WP_Query should be handled by ElasticSearch.
447
		 *
448
		 * @module search
449
		 *
450
		 * @since  5.6.0
451
		 *
452
		 * @param bool     $should_handle Should be handled by Jetpack Search.
453
		 * @param WP_Query $query         The WP_Query object.
454
		 */
455
		if ( ! apply_filters( 'jetpack_search_should_handle_query', ( $query->is_main_query() && $query->is_search() ), $query ) ) {
456
			return $posts;
457
		}
458
459
		$this->do_search( $query );
460
461
		if ( ! is_array( $this->search_result ) ) {
462
			return $posts;
463
		}
464
465
		// If no results, nothing to do
466
		if ( ! count( $this->search_result['results']['hits'] ) ) {
467
			return array();
468
		}
469
470
		$post_ids = array();
471
472
		foreach ( $this->search_result['results']['hits'] as $result ) {
473
			$post_ids[] = (int) $result['fields']['post_id'];
474
		}
475
476
		// Query all posts now
477
		$args = array(
478
			'post__in'            => $post_ids,
479
			'orderby'             => 'post__in',
480
			'perm'                => 'readable',
481
			'post_type'           => 'any',
482
			'ignore_sticky_posts' => true,
483
			'suppress_filters'    => true,
484
		);
485
486
		$posts_query = new WP_Query( $args );
487
488
		// 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.
489
		$query->found_posts   = $this->found_posts;
490
		$query->max_num_pages = ceil( $this->found_posts / $query->get( 'posts_per_page' ) );
491
492
		return $posts_query->posts;
493
	}
494
495
	/**
496
	 * Build up the search, then run it against the Jetpack servers.
497
	 *
498
	 * @since 5.0.0
499
	 *
500
	 * @param WP_Query $query The original WP_Query to use for the parameters of our search.
501
	 */
502
	public function do_search( WP_Query $query ) {
503
		if ( ! $query->is_main_query() || ! $query->is_search() ) {
504
			return;
505
		}
506
507
		$page = ( $query->get( 'paged' ) ) ? absint( $query->get( 'paged' ) ) : 1;
508
509
		// Get maximum allowed offset and posts per page values for the API.
510
		$max_offset         = Jetpack_Search_Helpers::get_max_offset();
511
		$max_posts_per_page = Jetpack_Search_Helpers::get_max_posts_per_page();
512
513
		$posts_per_page = $query->get( 'posts_per_page' );
514
		if ( $posts_per_page > $max_posts_per_page ) {
515
			$posts_per_page = $max_posts_per_page;
516
		}
517
518
		// Start building the WP-style search query args.
519
		// They'll be translated to ES format args later.
520
		$es_wp_query_args = array(
521
			'query'          => $query->get( 's' ),
522
			'posts_per_page' => $posts_per_page,
523
			'paged'          => $page,
524
			'orderby'        => $query->get( 'orderby' ),
525
			'order'          => $query->get( 'order' ),
526
		);
527
528
		if ( ! empty( $this->aggregations ) ) {
529
			$es_wp_query_args['aggregations'] = $this->aggregations;
530
		}
531
532
		// Did we query for authors?
533
		if ( $query->get( 'author_name' ) ) {
534
			$es_wp_query_args['author_name'] = $query->get( 'author_name' );
535
		}
536
537
		$es_wp_query_args['post_type'] = $this->get_es_wp_query_post_type_for_query( $query );
538
		$es_wp_query_args['terms']     = $this->get_es_wp_query_terms_for_query( $query );
539
540
		/**
541
		 * Modify the search query parameters, such as controlling the post_type.
542
		 *
543
		 * These arguments are in the format of WP_Query arguments
544
		 *
545
		 * @module search
546
		 *
547
		 * @since  5.0.0
548
		 *
549
		 * @param array    $es_wp_query_args The current query args, in WP_Query format.
550
		 * @param WP_Query $query            The original WP_Query object.
551
		 */
552
		$es_wp_query_args = apply_filters( 'jetpack_search_es_wp_query_args', $es_wp_query_args, $query );
553
554
		// If page * posts_per_page is greater than our max offset, send a 404. This is necessary because the offset is
555
		// capped at Jetpack_Search_Helpers::get_max_offset(), so a high page would always return the last page of results otherwise.
556
		if ( ( $es_wp_query_args['paged'] * $es_wp_query_args['posts_per_page'] ) > $max_offset ) {
557
			$query->set_404();
558
559
			return;
560
		}
561
562
		// If there were no post types returned, then 404 to avoid querying against non-public post types, which could
563
		// happen if we don't add the post type restriction to the ES query.
564
		if ( empty( $es_wp_query_args['post_type'] ) ) {
565
			$query->set_404();
566
567
			return;
568
		}
569
570
		// Convert the WP-style args into ES args.
571
		$es_query_args = $this->convert_wp_es_to_es_args( $es_wp_query_args );
572
573
		//Only trust ES to give us IDs, not the content since it is a mirror
574
		$es_query_args['fields'] = array(
575
			'post_id',
576
		);
577
578
		/**
579
		 * Modify the underlying ES query that is passed to the search endpoint. The returned args must represent a valid ES query
580
		 *
581
		 * This filter is harder to use if you're unfamiliar with ES, but allows complete control over the query
582
		 *
583
		 * @module search
584
		 *
585
		 * @since  5.0.0
586
		 *
587
		 * @param array    $es_query_args The raw Elasticsearch query args.
588
		 * @param WP_Query $query         The original WP_Query object.
589
		 */
590
		$es_query_args = apply_filters( 'jetpack_search_es_query_args', $es_query_args, $query );
591
592
		// Do the actual search query!
593
		$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...
594
595
		if ( is_wp_error( $this->search_result ) || ! is_array( $this->search_result ) || empty( $this->search_result['results'] ) || empty( $this->search_result['results']['hits'] ) ) {
596
			$this->found_posts = 0;
597
598
			return;
599
		}
600
601
		// If we have aggregations, fix the ordering to match the input order (ES doesn't guarantee the return order).
602
		if ( isset( $this->search_result['results']['aggregations'] ) && ! empty( $this->search_result['results']['aggregations'] ) ) {
603
			$this->search_result['results']['aggregations'] = $this->fix_aggregation_ordering( $this->search_result['results']['aggregations'], $this->aggregations );
604
		}
605
606
		// Total number of results for paging purposes. Capped at $max_offset + $posts_per_page, as deep paging gets quite expensive.
607
		$this->found_posts = min( $this->search_result['results']['total'], $max_offset + $posts_per_page );
608
	}
609
610
	/**
611
	 * If the query has already been run before filters have been updated, then we need to re-run the query
612
	 * to get the latest aggregations.
613
	 *
614
	 * This is especially useful for supporting widget management in the customizer.
615
	 *
616
	 * @since 5.8.0
617
	 *
618
	 * @return bool Whether the query was successful or not.
619
	 */
620
	public function update_search_results_aggregations() {
621
		if ( empty( $this->last_query_info ) || empty( $this->last_query_info['args'] ) ) {
622
			return false;
623
		}
624
625
		$es_args = $this->last_query_info['args'];
626
		$builder = new Jetpack_WPES_Query_Builder();
627
		$this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
628
		$es_args['aggregations'] = $builder->build_aggregation();
629
630
		$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...
631
632
		return ! is_wp_error( $this->search_result );
633
	}
634
635
	/**
636
	 * Given a WP_Query, convert its WP_Tax_Query (if present) into the WP-style Elasticsearch term arguments for the search.
637
	 *
638
	 * @since 5.0.0
639
	 *
640
	 * @param WP_Query $query The original WP_Query object for which to parse the taxonomy query.
641
	 *
642
	 * @return array The new WP-style Elasticsearch arguments (that will be converted into 'real' Elasticsearch arguments).
643
	 */
644
	public function get_es_wp_query_terms_for_query( WP_Query $query ) {
645
		$args = array();
646
647
		$the_tax_query = $query->tax_query;
648
649
		if ( ! $the_tax_query ) {
650
			return $args;
651
		}
652
653
654
		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...
655
			return $args;
656
		}
657
658
		$args = array();
659
660
		foreach ( $the_tax_query->queries as $tax_query ) {
661
			// Right now we only support slugs...see note above
662
			if ( ! is_array( $tax_query ) || 'slug' !== $tax_query['field'] ) {
663
				continue;
664
			}
665
666
			$taxonomy = $tax_query['taxonomy'];
667
668 View Code Duplication
			if ( ! isset( $args[ $taxonomy ] ) || ! is_array( $args[ $taxonomy ] ) ) {
669
				$args[ $taxonomy ] = array();
670
			}
671
672
			$args[ $taxonomy ] = array_merge( $args[ $taxonomy ], $tax_query['terms'] );
673
		}
674
675
		return $args;
676
	}
677
678
	/**
679
	 * Parse out the post type from a WP_Query.
680
	 *
681
	 * Only allows post types that are not marked as 'exclude_from_search'.
682
	 *
683
	 * @since 5.0.0
684
	 *
685
	 * @param WP_Query $query Original WP_Query object.
686
	 *
687
	 * @return array Array of searchable post types corresponding to the original query.
688
	 */
689
	public function get_es_wp_query_post_type_for_query( WP_Query $query ) {
690
		$post_types = $query->get( 'post_type' );
691
692
		// If we're searching 'any', we want to only pass searchable post types to Elasticsearch.
693
		if ( 'any' === $post_types ) {
694
			$post_types = array_values( get_post_types( array(
695
				'exclude_from_search' => false,
696
			) ) );
697
		}
698
699
		if ( ! is_array( $post_types ) ) {
700
			$post_types = array( $post_types );
701
		}
702
703
		$post_types = array_unique( $post_types );
704
705
		$sanitized_post_types = array();
706
707
		// Make sure the post types are queryable.
708
		foreach ( $post_types as $post_type ) {
709
			if ( ! $post_type ) {
710
				continue;
711
			}
712
713
			$post_type_object = get_post_type_object( $post_type );
714
			if ( ! $post_type_object || $post_type_object->exclude_from_search ) {
715
				continue;
716
			}
717
718
			$sanitized_post_types[] = $post_type;
719
		}
720
721
		return $sanitized_post_types;
722
	}
723
724
	/**
725
	 * Get the Elasticsearch result.
726
	 *
727
	 * @since 5.0.0
728
	 *
729
	 * @param bool $raw If true, does not check for WP_Error or return the 'results' array - the JSON decoded HTTP response.
730
	 *
731
	 * @return array|bool The search results, or false if there was a failure.
732
	 */
733
	public function get_search_result( $raw = false ) {
734
		if ( $raw ) {
735
			return $this->search_result;
736
		}
737
738
		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;
739
	}
740
741
	/**
742
	 * Add the date portion of a WP_Query onto the query args.
743
	 *
744
	 * @since 5.0.0
745
	 *
746
	 * @param array    $es_wp_query_args The Elasticsearch query arguments in WordPress form.
747
	 * @param WP_Query $query            The original WP_Query.
748
	 *
749
	 * @return array The es wp query args, with date filters added (as needed).
750
	 */
751
	public function filter__add_date_filter_to_query( array $es_wp_query_args, WP_Query $query ) {
752
		if ( $query->get( 'year' ) ) {
753
			if ( $query->get( 'monthnum' ) ) {
754
				// Padding
755
				$date_monthnum = sprintf( '%02d', $query->get( 'monthnum' ) );
756
757
				if ( $query->get( 'day' ) ) {
758
					// Padding
759
					$date_day = sprintf( '%02d', $query->get( 'day' ) );
760
761
					$date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 00:00:00';
762
					$date_end   = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 23:59:59';
763
				} else {
764
					$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
765
766
					$date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-01 00:00:00';
767
					$date_end   = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $days_in_month . ' 23:59:59';
768
				}
769
			} else {
770
				$date_start = $query->get( 'year' ) . '-01-01 00:00:00';
771
				$date_end   = $query->get( 'year' ) . '-12-31 23:59:59';
772
			}
773
774
			$es_wp_query_args['date_range'] = array(
775
				'field' => 'date',
776
				'gte'   => $date_start,
777
				'lte'   => $date_end,
778
			);
779
		}
780
781
		return $es_wp_query_args;
782
	}
783
784
	/**
785
	 * Converts WP_Query style args to Elasticsearch args.
786
	 *
787
	 * @since 5.0.0
788
	 *
789
	 * @param array $args Array of WP_Query style arguments.
790
	 *
791
	 * @return array Array of ES style query arguments.
792
	 */
793
	public function convert_wp_es_to_es_args( array $args ) {
794
		jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-parser' );
795
796
		$defaults = array(
797
			'blog_id'        => get_current_blog_id(),
798
			'query'          => null,    // Search phrase
799
			'query_fields'   => array(), //list of fields to search
800
			'post_type'      => null,    // string or an array
801
			'terms'          => array(), // ex: array( 'taxonomy-1' => array( 'slug' ), 'taxonomy-2' => array( 'slug-a', 'slug-b' ) )
802
			'author'         => null,    // id or an array of ids
803
			'author_name'    => array(), // string or an array
804
			'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'
805
			'orderby'        => null,    // Defaults to 'relevance' if query is set, otherwise 'date'. Pass an array for multiple orders.
806
			'order'          => 'DESC',
807
			'posts_per_page' => 10,
808
			'offset'         => null,
809
			'paged'          => null,
810
			/**
811
			 * Aggregations. Examples:
812
			 * array(
813
			 *     'Tag'       => array( 'type' => 'taxonomy', 'taxonomy' => 'post_tag', 'count' => 10 ) ),
814
			 *     'Post Type' => array( 'type' => 'post_type', 'count' => 10 ) ),
815
			 * );
816
			 */
817
			'aggregations'   => null,
818
		);
819
820
		$args = wp_parse_args( $args, $defaults );
821
822
		$parser = new Jetpack_WPES_Search_Query_Parser( $args['query'], array( get_locale() ) );
823
824
		if ( empty( $args['query_fields'] ) ) {
825
			if ( defined( 'JETPACK_SEARCH_VIP_INDEX' ) && JETPACK_SEARCH_VIP_INDEX ) {
826
				// VIP indices do not have per language fields
827
				$match_fields        = array(
828
					'title^0.1',
829
					'content^0.1',
830
					'excerpt^0.1',
831
					'tag.name^0.1',
832
					'category.name^0.1',
833
					'author_login^0.1',
834
					'author^0.1',
835
				);
836
				$boost_fields        = array(
837
					'title^2',
838
					'tag.name',
839
					'category.name',
840
					'author_login',
841
					'author',
842
				);
843
				$boost_phrase_fields = array(
844
					'title',
845
					'content',
846
					'excerpt',
847
					'tag.name',
848
					'category.name',
849
					'author',
850
				);
851
			} else {
852
				$match_fields = $parser->merge_ml_fields(
853
					array(
854
						'title'         => 0.1,
855
						'content'       => 0.1,
856
						'excerpt'       => 0.1,
857
						'tag.name'      => 0.1,
858
						'category.name' => 0.1,
859
					),
860
					array(
861
						'author_login^0.1',
862
						'author^0.1',
863
					)
864
				);
865
866
				$boost_fields = $parser->merge_ml_fields(
867
					array(
868
						'title'         => 2,
869
						'tag.name'      => 1,
870
						'category.name' => 1,
871
					),
872
					array(
873
						'author_login',
874
						'author',
875
					)
876
				);
877
878
				$boost_phrase_fields = $parser->merge_ml_fields(
879
					array(
880
						'title'         => 1,
881
						'content'       => 1,
882
						'excerpt'       => 1,
883
						'tag.name'      => 1,
884
						'category.name' => 1,
885
					),
886
					array(
887
						'author',
888
					)
889
				);
890
			}
891
		} else {
892
			// If code is overriding the fields, then use that. Important for backwards compatibility.
893
			$match_fields        = $args['query_fields'];
894
			$boost_phrase_fields = $match_fields;
895
			$boost_fields        = null;
896
		}
897
898
		$parser->phrase_filter( array(
899
			'must_query_fields'  => $match_fields,
900
			'boost_query_fields' => null,
901
		) );
902
		$parser->remaining_query( array(
903
			'must_query_fields'  => $match_fields,
904
			'boost_query_fields' => $boost_fields,
905
		) );
906
907
		// Boost on phrase matches
908
		$parser->remaining_query( array(
909
			'boost_query_fields' => $boost_phrase_fields,
910
			'boost_query_type'   => 'phrase',
911
		) );
912
913
		/**
914
		 * Modify the recency decay parameters for the search query.
915
		 *
916
		 * The recency decay lowers the search scores based on the age of a post relative to an origin date. Basic adjustments:
917
		 *  - origin: A date. Posts with this date will have the highest score and no decay applied. Default is today.
918
		 *  - 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.
919
		 *  - scale: The number of days/months/years from the origin+offset at which the decay will equal the decay param. Default 360d
920
		 *  - decay: The amount of decay applied at offset+scale. Default 0.9.
921
		 *
922
		 * 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}
923
		 *
924
		 * @module search
925
		 *
926
		 * @since  5.8.0
927
		 *
928
		 * @param array $decay_params The decay parameters.
929
		 * @param array $args         The WP query parameters.
930
		 */
931
		$decay_params = apply_filters(
932
			'jetpack_search_recency_score_decay',
933
			array(
934
				'origin' => date( 'Y-m-d' ),
935
				'scale'  => '360d',
936
				'decay'  => 0.9,
937
			),
938
			$args
939
		);
940
941
		if ( ! empty( $decay_params ) ) {
942
			// Newer content gets weighted slightly higher
943
			$parser->add_decay( 'gauss', array(
944
				'date_gmt' => $decay_params
945
			) );
946
		}
947
948
		$es_query_args = array(
949
			'blog_id' => absint( $args['blog_id'] ),
950
			'size'    => absint( $args['posts_per_page'] ),
951
		);
952
953
		// ES "from" arg (offset)
954
		if ( $args['offset'] ) {
955
			$es_query_args['from'] = absint( $args['offset'] );
956
		} elseif ( $args['paged'] ) {
957
			$es_query_args['from'] = max( 0, ( absint( $args['paged'] ) - 1 ) * $es_query_args['size'] );
958
		}
959
960
		$es_query_args['from'] = min( $es_query_args['from'], Jetpack_Search_Helpers::get_max_offset() );
961
962
		if ( ! is_array( $args['author_name'] ) ) {
963
			$args['author_name'] = array( $args['author_name'] );
964
		}
965
966
		// ES stores usernames, not IDs, so transform
967
		if ( ! empty( $args['author'] ) ) {
968
			if ( ! is_array( $args['author'] ) ) {
969
				$args['author'] = array( $args['author'] );
970
			}
971
972
			foreach ( $args['author'] as $author ) {
973
				$user = get_user_by( 'id', $author );
974
975
				if ( $user && ! empty( $user->user_login ) ) {
976
					$args['author_name'][] = $user->user_login;
977
				}
978
			}
979
		}
980
981
		//////////////////////////////////////////////////
982
		// Build the filters from the query elements.
983
		// Filters rock because they are cached from one query to the next
984
		// but they are cached as individual filters, rather than all combined together.
985
		// May get performance boost by also caching the top level boolean filter too.
986
987
		if ( $args['post_type'] ) {
988
			if ( ! is_array( $args['post_type'] ) ) {
989
				$args['post_type'] = array( $args['post_type'] );
990
			}
991
992
			$parser->add_filter( array(
993
				'terms' => array(
994
					'post_type' => $args['post_type'],
995
				),
996
			) );
997
		}
998
999
		if ( $args['author_name'] ) {
1000
			$parser->add_filter( array(
1001
				'terms' => array(
1002
					'author_login' => $args['author_name'],
1003
				),
1004
			) );
1005
		}
1006
1007
		if ( ! empty( $args['date_range'] ) && isset( $args['date_range']['field'] ) ) {
1008
			$field = $args['date_range']['field'];
1009
1010
			unset( $args['date_range']['field'] );
1011
1012
			$parser->add_filter( array(
1013
				'range' => array(
1014
					$field => $args['date_range'],
1015
				),
1016
			) );
1017
		}
1018
1019
		if ( is_array( $args['terms'] ) ) {
1020
			foreach ( $args['terms'] as $tax => $terms ) {
1021
				$terms = (array) $terms;
1022
1023
				if ( count( $terms ) && mb_strlen( $tax ) ) {
1024 View Code Duplication
					switch ( $tax ) {
1025
						case 'post_tag':
1026
							$tax_fld = 'tag.slug';
1027
1028
							break;
1029
1030
						case 'category':
1031
							$tax_fld = 'category.slug';
1032
1033
							break;
1034
1035
						default:
1036
							$tax_fld = 'taxonomy.' . $tax . '.slug';
1037
1038
							break;
1039
					}
1040
1041
					foreach ( $terms as $term ) {
1042
						$parser->add_filter( array(
1043
							'term' => array(
1044
								$tax_fld => $term,
1045
							),
1046
						) );
1047
					}
1048
				}
1049
			}
1050
		}
1051
1052
		if ( ! $args['orderby'] ) {
1053
			if ( $args['query'] ) {
1054
				$args['orderby'] = array( 'relevance' );
1055
			} else {
1056
				$args['orderby'] = array( 'date' );
1057
			}
1058
		}
1059
1060
		// Validate the "order" field
1061
		switch ( strtolower( $args['order'] ) ) {
1062
			case 'asc':
1063
				$args['order'] = 'asc';
1064
				break;
1065
1066
			case 'desc':
1067
			default:
1068
				$args['order'] = 'desc';
1069
				break;
1070
		}
1071
1072
		$es_query_args['sort'] = array();
1073
1074
		foreach ( (array) $args['orderby'] as $orderby ) {
1075
			// Translate orderby from WP field to ES field
1076
			switch ( $orderby ) {
1077
				case 'relevance' :
1078
					//never order by score ascending
1079
					$es_query_args['sort'][] = array(
1080
						'_score' => array(
1081
							'order' => 'desc',
1082
						),
1083
					);
1084
1085
					break;
1086
1087 View Code Duplication
				case 'date' :
1088
					$es_query_args['sort'][] = array(
1089
						'date' => array(
1090
							'order' => $args['order'],
1091
						),
1092
					);
1093
1094
					break;
1095
1096 View Code Duplication
				case 'ID' :
1097
					$es_query_args['sort'][] = array(
1098
						'id' => array(
1099
							'order' => $args['order'],
1100
						),
1101
					);
1102
1103
					break;
1104
1105
				case 'author' :
1106
					$es_query_args['sort'][] = array(
1107
						'author.raw' => array(
1108
							'order' => $args['order'],
1109
						),
1110
					);
1111
1112
					break;
1113
			} // End switch().
1114
		} // End foreach().
1115
1116
		if ( empty( $es_query_args['sort'] ) ) {
1117
			unset( $es_query_args['sort'] );
1118
		}
1119
1120
		// Aggregations
1121
		if ( ! empty( $args['aggregations'] ) ) {
1122
			$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...
1123
		}
1124
1125
		$es_query_args['filter']       = $parser->build_filter();
1126
		$es_query_args['query']        = $parser->build_query();
1127
		$es_query_args['aggregations'] = $parser->build_aggregation();
1128
1129
		return $es_query_args;
1130
	}
1131
1132
	/**
1133
	 * Given an array of aggregations, parse and add them onto the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1134
	 *
1135
	 * @since 5.0.0
1136
	 *
1137
	 * @param array                      $aggregations Array of aggregations (filters) to add to the Jetpack_WPES_Query_Builder.
1138
	 * @param Jetpack_WPES_Query_Builder $builder      The builder instance that is creating the Elasticsearch query.
1139
	 */
1140
	public function add_aggregations_to_es_query_builder( array $aggregations, Jetpack_WPES_Query_Builder $builder ) {
1141
		foreach ( $aggregations as $label => $aggregation ) {
1142
			switch ( $aggregation['type'] ) {
1143
				case 'taxonomy':
1144
					$this->add_taxonomy_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1145
1146
					break;
1147
1148
				case 'post_type':
1149
					$this->add_post_type_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1150
1151
					break;
1152
1153
				case 'date_histogram':
1154
					$this->add_date_histogram_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1155
1156
					break;
1157
			}
1158
		}
1159
	}
1160
1161
	/**
1162
	 * Given an individual taxonomy aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1163
	 *
1164
	 * @since 5.0.0
1165
	 *
1166
	 * @param array                      $aggregation The aggregation to add to the query builder.
1167
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1168
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1169
	 */
1170
	public function add_taxonomy_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1171
		$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...
1172
1173
		switch ( $aggregation['taxonomy'] ) {
1174
			case 'post_tag':
1175
				$field = 'tag';
1176
				break;
1177
1178
			case 'category':
1179
				$field = 'category';
1180
				break;
1181
1182
			default:
1183
				$field = 'taxonomy.' . $aggregation['taxonomy'];
1184
				break;
1185
		}
1186
1187
		$builder->add_aggs( $label, array(
1188
			'terms' => array(
1189
				'field' => $field . '.slug',
1190
				'size'  => min( (int) $aggregation['count'], $this->max_aggregations_count ),
1191
			),
1192
		) );
1193
	}
1194
1195
	/**
1196
	 * Given an individual post_type aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1197
	 *
1198
	 * @since 5.0.0
1199
	 *
1200
	 * @param array                      $aggregation The aggregation to add to the query builder.
1201
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1202
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1203
	 */
1204
	public function add_post_type_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1205
		$builder->add_aggs( $label, array(
1206
			'terms' => array(
1207
				'field' => 'post_type',
1208
				'size'  => min( (int) $aggregation['count'], $this->max_aggregations_count ),
1209
			),
1210
		) );
1211
	}
1212
1213
	/**
1214
	 * Given an individual date_histogram aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1215
	 *
1216
	 * @since 5.0.0
1217
	 *
1218
	 * @param array                      $aggregation The aggregation to add to the query builder.
1219
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1220
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1221
	 */
1222
	public function add_date_histogram_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1223
		$args = array(
1224
			'interval' => $aggregation['interval'],
1225
			'field'    => ( ! empty( $aggregation['field'] ) && 'post_date_gmt' == $aggregation['field'] ) ? 'date_gmt' : 'date',
1226
		);
1227
1228
		if ( isset( $aggregation['min_doc_count'] ) ) {
1229
			$args['min_doc_count'] = intval( $aggregation['min_doc_count'] );
1230
		} else {
1231
			$args['min_doc_count'] = 1;
1232
		}
1233
1234
		$builder->add_aggs( $label, array(
1235
			'date_histogram' => $args,
1236
		) );
1237
	}
1238
1239
	/**
1240
	 * And an existing filter object with a list of additional filters.
1241
	 *
1242
	 * Attempts to optimize the filters somewhat.
1243
	 *
1244
	 * @since 5.0.0
1245
	 *
1246
	 * @param array $curr_filter The existing filters to build upon.
1247
	 * @param array $filters     The new filters to add.
1248
	 *
1249
	 * @return array The resulting merged filters.
1250
	 */
1251
	public static function and_es_filters( array $curr_filter, array $filters ) {
1252
		if ( ! is_array( $curr_filter ) || isset( $curr_filter['match_all'] ) ) {
1253
			if ( 1 === count( $filters ) ) {
1254
				return $filters[0];
1255
			}
1256
1257
			return array(
1258
				'and' => $filters,
1259
			);
1260
		}
1261
1262
		return array(
1263
			'and' => array_merge( array( $curr_filter ), $filters ),
1264
		);
1265
	}
1266
1267
	/**
1268
	 * Set the available filters for the search.
1269
	 *
1270
	 * These get rendered via the Jetpack_Search_Widget() widget.
1271
	 *
1272
	 * Behind the scenes, these are implemented using Elasticsearch Aggregations.
1273
	 *
1274
	 * If you do not require counts of how many documents match each filter, please consider using regular WP Query
1275
	 * arguments instead, such as via the jetpack_search_es_wp_query_args filter
1276
	 *
1277
	 * @see    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
1278
	 *
1279
	 * @since  5.0.0
1280
	 *
1281
	 * @param array $aggregations Array of filters (aggregations) to apply to the search
1282
	 */
1283
	public function set_filters( array $aggregations ) {
1284
		foreach ( (array) $aggregations as $key => $agg ) {
1285
			if ( empty( $agg['name'] ) ) {
1286
				$aggregations[ $key ]['name'] = $key;
1287
			}
1288
		}
1289
		$this->aggregations = $aggregations;
1290
	}
1291
1292
	/**
1293
	 * Set the search's facets (deprecated).
1294
	 *
1295
	 * @deprecated 5.0 Please use Jetpack_Search::set_filters() instead.
1296
	 *
1297
	 * @see        Jetpack_Search::set_filters()
1298
	 *
1299
	 * @param array $facets Array of facets to apply to the search.
1300
	 */
1301
	public function set_facets( array $facets ) {
1302
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::set_filters()' );
1303
1304
		$this->set_filters( $facets );
1305
	}
1306
1307
	/**
1308
	 * Get the raw Aggregation results from the Elasticsearch response.
1309
	 *
1310
	 * @since  5.0.0
1311
	 *
1312
	 * @see    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
1313
	 *
1314
	 * @return array Array of Aggregations performed on the search.
1315
	 */
1316
	public function get_search_aggregations_results() {
1317
		$aggregations = array();
1318
1319
		$search_result = $this->get_search_result();
1320
1321
		if ( ! empty( $search_result ) && ! empty( $search_result['aggregations'] ) ) {
1322
			$aggregations = $search_result['aggregations'];
1323
		}
1324
1325
		return $aggregations;
1326
	}
1327
1328
	/**
1329
	 * Get the raw Facet results from the Elasticsearch response.
1330
	 *
1331
	 * @deprecated 5.0 Please use Jetpack_Search::get_search_aggregations_results() instead.
1332
	 *
1333
	 * @see        Jetpack_Search::get_search_aggregations_results()
1334
	 *
1335
	 * @return array Array of Facets performed on the search.
1336
	 */
1337
	public function get_search_facets() {
1338
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_search_aggregations_results()' );
1339
1340
		return $this->get_search_aggregations_results();
1341
	}
1342
1343
	/**
1344
	 * Get the results of the Filters performed, including the number of matching documents.
1345
	 *
1346
	 * Returns an array of Filters (keyed by $label, as passed to Jetpack_Search::set_filters()), containing the Filter and all resulting
1347
	 * matching buckets, the url for applying/removing each bucket, etc.
1348
	 *
1349
	 * NOTE - if this is called before the search is performed, an empty array will be returned. Use the $aggregations class
1350
	 * member if you need to access the raw filters set in Jetpack_Search::set_filters().
1351
	 *
1352
	 * @since 5.0.0
1353
	 *
1354
	 * @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...
1355
	 *
1356
	 * @return array Array of filters applied and info about them.
1357
	 */
1358
	public function get_filters( WP_Query $query = null ) {
1359
		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...
1360
			global $wp_query;
1361
1362
			$query = $wp_query;
1363
		}
1364
1365
		$aggregation_data = $this->aggregations;
1366
1367
		if ( empty( $aggregation_data ) ) {
1368
			return $aggregation_data;
1369
		}
1370
1371
		$aggregation_results = $this->get_search_aggregations_results();
1372
1373
		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...
1374
			return $aggregation_data;
1375
		}
1376
1377
		// NOTE - Looping over the _results_, not the original configured aggregations, so we get the 'real' data from ES
1378
		foreach ( $aggregation_results as $label => $aggregation ) {
1379
			if ( empty( $aggregation ) ) {
1380
				continue;
1381
			}
1382
1383
			$type = $this->aggregations[ $label ]['type'];
1384
1385
			$aggregation_data[ $label ]['buckets'] = array();
1386
1387
			$existing_term_slugs = array();
1388
1389
			$tax_query_var = null;
1390
1391
			// Figure out which terms are active in the query, for this taxonomy
1392
			if ( 'taxonomy' === $this->aggregations[ $label ]['type'] ) {
1393
				$tax_query_var = $this->get_taxonomy_query_var( $this->aggregations[ $label ]['taxonomy'] );
1394
1395
				if ( ! empty( $query->tax_query ) && ! empty( $query->tax_query->queries ) && is_array( $query->tax_query->queries ) ) {
1396
					foreach ( $query->tax_query->queries as $tax_query ) {
1397
						if ( is_array( $tax_query ) && $this->aggregations[ $label ]['taxonomy'] === $tax_query['taxonomy'] &&
1398
						     'slug' === $tax_query['field'] &&
1399
						     is_array( $tax_query['terms'] ) ) {
1400
							$existing_term_slugs = array_merge( $existing_term_slugs, $tax_query['terms'] );
1401
						}
1402
					}
1403
				}
1404
			}
1405
1406
			// Now take the resulting found aggregation items and generate the additional info about them, such as activation/deactivation url, name, count, etc.
1407
			$buckets = array();
1408
1409
			if ( ! empty( $aggregation['buckets'] ) ) {
1410
				$buckets = (array) $aggregation['buckets'];
1411
			}
1412
1413
			if ( 'date_histogram' == $type ) {
1414
				//re-order newest to oldest
1415
				$buckets = array_reverse( $buckets );
1416
			}
1417
1418
			// Some aggregation types like date_histogram don't support the max results parameter
1419
			if ( is_int( $this->aggregations[ $label ]['count'] ) && count( $buckets ) > $this->aggregations[ $label ]['count'] ) {
1420
				$buckets = array_slice( $buckets, 0, $this->aggregations[ $label ]['count'] );
1421
			}
1422
1423
			foreach ( $buckets as $item ) {
1424
				$query_vars = array();
1425
				$active     = false;
1426
				$remove_url = null;
1427
				$name       = '';
1428
1429
				// What type was the original aggregation?
1430
				switch ( $type ) {
1431
					case 'taxonomy':
1432
						$taxonomy = $this->aggregations[ $label ]['taxonomy'];
1433
1434
						$term = get_term_by( 'slug', $item['key'], $taxonomy );
1435
1436
						if ( ! $term || ! $tax_query_var ) {
1437
							continue 2; // switch() is considered a looping structure
1438
						}
1439
1440
						$query_vars = array(
1441
							$tax_query_var => implode( '+', array_merge( $existing_term_slugs, array( $term->slug ) ) ),
1442
						);
1443
1444
						$name = $term->name;
1445
1446
						// Let's determine if this term is active or not
1447
1448
						if ( in_array( $item['key'], $existing_term_slugs, true ) ) {
1449
							$active = true;
1450
1451
							$slug_count = count( $existing_term_slugs );
1452
1453 View Code Duplication
							if ( $slug_count > 1 ) {
1454
								$remove_url = Jetpack_Search_Helpers::add_query_arg(
1455
									$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...
1456
									rawurlencode( implode( '+', array_diff( $existing_term_slugs, array( $item['key'] ) ) ) )
1457
								);
1458
							} else {
1459
								$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...
1460
							}
1461
						}
1462
1463
						break;
1464
1465
					case 'post_type':
1466
						$post_type = get_post_type_object( $item['key'] );
1467
1468
						if ( ! $post_type || $post_type->exclude_from_search ) {
1469
							continue 2;  // switch() is considered a looping structure
1470
						}
1471
1472
						$query_vars = array(
1473
							'post_type' => $item['key'],
1474
						);
1475
1476
						$name = $post_type->labels->singular_name;
1477
1478
						// Is this post type active on this search?
1479
						$post_types = $query->get( 'post_type' );
1480
1481
						if ( ! is_array( $post_types ) ) {
1482
							$post_types = array( $post_types );
1483
						}
1484
1485
						if ( in_array( $item['key'], $post_types ) ) {
1486
							$active = true;
1487
1488
							$post_type_count = count( $post_types );
1489
1490
							// 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
1491 View Code Duplication
							if ( $post_type_count > 1 ) {
1492
								$remove_url = Jetpack_Search_Helpers::add_query_arg(
1493
									'post_type',
1494
									rawurlencode( implode( ',', array_diff( $post_types, array( $item['key'] ) ) ) )
1495
								);
1496
							} else {
1497
								$remove_url = Jetpack_Search_Helpers::remove_query_arg( 'post_type' );
1498
							}
1499
						}
1500
1501
						break;
1502
1503
					case 'date_histogram':
1504
						$timestamp = $item['key'] / 1000;
1505
1506
						$current_year  = $query->get( 'year' );
1507
						$current_month = $query->get( 'monthnum' );
1508
						$current_day   = $query->get( 'day' );
1509
1510
						switch ( $this->aggregations[ $label ]['interval'] ) {
1511
							case 'year':
1512
								$year = (int) date( 'Y', $timestamp );
1513
1514
								$query_vars = array(
1515
									'year'     => $year,
1516
									'monthnum' => false,
1517
									'day'      => false,
1518
								);
1519
1520
								$name = $year;
1521
1522
								// Is this year currently selected?
1523
								if ( ! empty( $current_year ) && (int) $current_year === $year ) {
1524
									$active = true;
1525
1526
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum', 'day' ) );
1527
								}
1528
1529
								break;
1530
1531
							case 'month':
1532
								$year  = (int) date( 'Y', $timestamp );
1533
								$month = (int) date( 'n', $timestamp );
1534
1535
								$query_vars = array(
1536
									'year'     => $year,
1537
									'monthnum' => $month,
1538
									'day'      => false,
1539
								);
1540
1541
								$name = date( 'F Y', $timestamp );
1542
1543
								// Is this month currently selected?
1544
								if ( ! empty( $current_year ) && (int) $current_year === $year &&
1545
								     ! empty( $current_month ) && (int) $current_month === $month ) {
1546
									$active = true;
1547
1548
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum' ) );
1549
								}
1550
1551
								break;
1552
1553
							case 'day':
1554
								$year  = (int) date( 'Y', $timestamp );
1555
								$month = (int) date( 'n', $timestamp );
1556
								$day   = (int) date( 'j', $timestamp );
1557
1558
								$query_vars = array(
1559
									'year'     => $year,
1560
									'monthnum' => $month,
1561
									'day'      => $day,
1562
								);
1563
1564
								$name = date( 'F jS, Y', $timestamp );
1565
1566
								// Is this day currently selected?
1567
								if ( ! empty( $current_year ) && (int) $current_year === $year &&
1568
								     ! empty( $current_month ) && (int) $current_month === $month &&
1569
								     ! empty( $current_day ) && (int) $current_day === $day ) {
1570
									$active = true;
1571
1572
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'day' ) );
1573
								}
1574
1575
								break;
1576
1577
							default:
1578
								continue 3; // switch() is considered a looping structure
1579
						} // End switch().
1580
1581
						break;
1582
1583
					default:
1584
						//continue 2; // switch() is considered a looping structure
1585
				} // End switch().
1586
1587
				// Need to urlencode param values since add_query_arg doesn't
1588
				$url_params = urlencode_deep( $query_vars );
1589
1590
				$aggregation_data[ $label ]['buckets'][] = array(
1591
					'url'        => Jetpack_Search_Helpers::add_query_arg( $url_params ),
1592
					'query_vars' => $query_vars,
1593
					'name'       => $name,
1594
					'count'      => $item['doc_count'],
1595
					'active'     => $active,
1596
					'remove_url' => $remove_url,
1597
					'type'       => $type,
1598
					'type_label' => $aggregation_data[ $label ]['name'],
1599
					'widget_id'  => ! empty( $aggregation_data[ $label ]['widget_id'] ) ? $aggregation_data[ $label ]['widget_id'] : 0
1600
				);
1601
			} // End foreach().
1602
		} // End foreach().
1603
1604
		return $aggregation_data;
1605
	}
1606
1607
	/**
1608
	 * Get the results of the facets performed.
1609
	 *
1610
	 * @deprecated 5.0 Please use Jetpack_Search::get_filters() instead.
1611
	 *
1612
	 * @see        Jetpack_Search::get_filters()
1613
	 *
1614
	 * @return array $facets Array of facets applied and info about them.
1615
	 */
1616
	public function get_search_facet_data() {
1617
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_filters()' );
1618
1619
		return $this->get_filters();
1620
	}
1621
1622
	/**
1623
	 * Get the filters that are currently applied to this search.
1624
	 *
1625
	 * @since 5.0.0
1626
	 *
1627
	 * @return array Array of filters that were applied.
1628
	 */
1629
	public function get_active_filter_buckets() {
1630
		$active_buckets = array();
1631
1632
		$filters = $this->get_filters();
1633
1634
		if ( ! is_array( $filters ) ) {
1635
			return $active_buckets;
1636
		}
1637
1638
		foreach ( $filters as $filter ) {
1639
			if ( isset( $filter['buckets'] ) && is_array( $filter['buckets'] ) ) {
1640
				foreach ( $filter['buckets'] as $item ) {
1641
					if ( isset( $item['active'] ) && $item['active'] ) {
1642
						$active_buckets[] = $item;
1643
					}
1644
				}
1645
			}
1646
		}
1647
1648
		return $active_buckets;
1649
	}
1650
1651
	/**
1652
	 * Get the filters that are currently applied to this search.
1653
	 *
1654
	 * @deprecated 5.0 Please use Jetpack_Search::get_active_filter_buckets() instead.
1655
	 *
1656
	 * @see        Jetpack_Search::get_active_filter_buckets()
1657
	 *
1658
	 * @return array Array of filters that were applied.
1659
	 */
1660
	public function get_current_filters() {
1661
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_active_filter_buckets()' );
1662
1663
		return $this->get_active_filter_buckets();
1664
	}
1665
1666
	/**
1667
	 * Calculate the right query var to use for a given taxonomy.
1668
	 *
1669
	 * Allows custom code to modify the GET var that is used to represent a given taxonomy, via the jetpack_search_taxonomy_query_var filter.
1670
	 *
1671
	 * @since 5.0.0
1672
	 *
1673
	 * @param string $taxonomy_name The name of the taxonomy for which to get the query var.
1674
	 *
1675
	 * @return bool|string The query var to use for this taxonomy, or false if none found.
1676
	 */
1677
	public function get_taxonomy_query_var( $taxonomy_name ) {
1678
		$taxonomy = get_taxonomy( $taxonomy_name );
1679
1680
		if ( ! $taxonomy || is_wp_error( $taxonomy ) ) {
1681
			return false;
1682
		}
1683
1684
		/**
1685
		 * Modify the query var to use for a given taxonomy
1686
		 *
1687
		 * @module search
1688
		 *
1689
		 * @since  5.0.0
1690
		 *
1691
		 * @param string $query_var     The current query_var for the taxonomy
1692
		 * @param string $taxonomy_name The taxonomy name
1693
		 */
1694
		return apply_filters( 'jetpack_search_taxonomy_query_var', $taxonomy->query_var, $taxonomy_name );
1695
	}
1696
1697
	/**
1698
	 * Takes an array of aggregation results, and ensures the array key ordering matches the key order in $desired
1699
	 * which is the input order.
1700
	 *
1701
	 * Necessary because ES does not always return aggregations in the same order that you pass them in,
1702
	 * and it should be possible to control the display order easily.
1703
	 *
1704
	 * @since 5.0.0
1705
	 *
1706
	 * @param array $aggregations Aggregation results to be reordered.
1707
	 * @param array $desired      Array with keys representing the desired ordering.
1708
	 *
1709
	 * @return array A new array with reordered keys, matching those in $desired.
1710
	 */
1711
	public function fix_aggregation_ordering( array $aggregations, array $desired ) {
1712
		if ( empty( $aggregations ) || empty( $desired ) ) {
1713
			return $aggregations;
1714
		}
1715
1716
		$reordered = array();
1717
1718
		foreach ( array_keys( $desired ) as $agg_name ) {
1719
			if ( isset( $aggregations[ $agg_name ] ) ) {
1720
				$reordered[ $agg_name ] = $aggregations[ $agg_name ];
1721
			}
1722
		}
1723
1724
		return $reordered;
1725
	}
1726
1727
	/**
1728
	 * Sends events to Tracks when a search filters widget is updated.
1729
	 *
1730
	 * @since 5.8.0
1731
	 *
1732
	 * @param string $option    The option name. Only "widget_jetpack-search-filters" is cared about.
1733
	 * @param array  $old_value The old option value.
1734
	 * @param array  $new_value The new option value.
1735
	 */
1736
	public function track_widget_updates( $option, $old_value, $new_value ) {
1737
		if ( 'widget_jetpack-search-filters' !== $option ) {
1738
			return;
1739
		}
1740
1741
		$event = Jetpack_Search_Helpers::get_widget_tracks_value( $old_value, $new_value );
1742
		if ( ! $event ) {
1743
			return;
1744
		}
1745
1746
		jetpack_tracks_record_event(
1747
			wp_get_current_user(),
1748
			sprintf( 'jetpack_search_widget_%s', $event['action'] ),
1749
			$event['widget']
1750
		);
1751
	}
1752
1753
	/**
1754
	 * Moves any active search widgets to the inactive category.
1755
	 *
1756
	 * @since 5.9.0
1757
	 *
1758
	 * @param string $module Unused. The Jetpack module being disabled.
1759
	 */
1760
	public function move_search_widgets_to_inactive( $module ) {
1761
		if ( ! is_active_widget( false, false, Jetpack_Search_Helpers::FILTER_WIDGET_BASE, true ) ) {
1762
			return;
1763
		}
1764
1765
		$sidebars_widgets = wp_get_sidebars_widgets();
1766
1767
		if ( ! is_array( $sidebars_widgets ) ) {
1768
			return;
1769
		}
1770
1771
		$changed = false;
1772
1773
		foreach ( $sidebars_widgets as $sidebar => $widgets ) {
1774
			if ( 'wp_inactive_widgets' === $sidebar || 'orphaned_widgets' === substr( $sidebar, 0, 16 ) ) {
1775
				continue;
1776
			}
1777
1778
			if ( is_array( $widgets ) ) {
1779
				foreach ( $widgets as $key => $widget ) {
1780
					if ( _get_widget_id_base( $widget ) == Jetpack_Search_Helpers::FILTER_WIDGET_BASE ) {
1781
						$changed = true;
1782
1783
						array_unshift( $sidebars_widgets['wp_inactive_widgets'], $widget );
1784
						unset( $sidebars_widgets[ $sidebar ][ $key ] );
1785
					}
1786
				}
1787
			}
1788
		}
1789
1790
		if ( $changed ) {
1791
			wp_set_sidebars_widgets( $sidebars_widgets );
1792
		}
1793
	}
1794
}
1795