Completed
Push — update/search/check-checkbox-o... ( 420f8f...ec7e6f )
by Alex
09:02
created

Jetpack_Search::get_search_facet_data()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

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