Jetpack_Search::get_taxonomy_query_var()   A
last analyzed

Complexity

Conditions 3
Paths 2

Size

Total Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 2
nop 1
dl 0
loc 19
rs 9.6333
c 0
b 0
f 0
1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
3
/**
4
 * Jetpack Search: Main Jetpack_Search class
5
 *
6
 * @package    Jetpack
7
 * @subpackage Jetpack Search
8
 * @since      5.0.0
9
 */
10
11
use Automattic\Jetpack\Connection\Client;
12
13
require_once __DIR__ . '/class-jetpack-search-options.php';
14
15
/**
16
 * The main class for the Jetpack Search module.
17
 *
18
 * @since 5.0.0
19
 */
20
class Jetpack_Search {
21
22
	/**
23
	 * The number of found posts.
24
	 *
25
	 * @since 5.0.0
26
	 *
27
	 * @var int
28
	 */
29
	protected $found_posts = 0;
30
31
	/**
32
	 * The search result, as returned by the WordPress.com REST API.
33
	 *
34
	 * @since 5.0.0
35
	 *
36
	 * @var array
37
	 */
38
	protected $search_result;
39
40
	/**
41
	 * This site's blog ID on WordPress.com.
42
	 *
43
	 * @since 5.0.0
44
	 *
45
	 * @var int
46
	 */
47
	protected $jetpack_blog_id;
48
49
	/**
50
	 * The Elasticsearch aggregations (filters).
51
	 *
52
	 * @since 5.0.0
53
	 *
54
	 * @var array
55
	 */
56
	protected $aggregations = array();
57
58
	/**
59
	 * The maximum number of aggregations allowed.
60
	 *
61
	 * @since 5.0.0
62
	 *
63
	 * @var int
64
	 */
65
	protected $max_aggregations_count = 100;
66
67
	/**
68
	 * Statistics about the last Elasticsearch query.
69
	 *
70
	 * @since 5.6.0
71
	 *
72
	 * @var array
73
	 */
74
	protected $last_query_info = array();
75
76
	/**
77
	 * Statistics about the last Elasticsearch query failure.
78
	 *
79
	 * @since 5.6.0
80
	 *
81
	 * @var array
82
	 */
83
	protected $last_query_failure_info = array();
84
85
	/**
86
	 * The singleton instance of this class.
87
	 *
88
	 * @since 5.0.0
89
	 *
90
	 * @var Jetpack_Search
91
	 */
92
	protected static $instance;
93
94
	/**
95
	 * Languages with custom analyzers. Other languages are supported, but are analyzed with the default analyzer.
96
	 *
97
	 * @since 5.0.0
98
	 *
99
	 * @var array
100
	 */
101
	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' );
102
103
	/**
104
	 * Jetpack_Search constructor.
105
	 *
106
	 * @since 5.0.0
107
	 *
108
	 * Doesn't do anything. This class needs to be initialized via the instance() method instead.
109
	 */
110
	protected function __construct() {
111
	}
112
113
	/**
114
	 * Prevent __clone()'ing of this class.
115
	 *
116
	 * @since 5.0.0
117
	 */
118
	public function __clone() {
119
		wp_die( "Please don't __clone Jetpack_Search" );
120
	}
121
122
	/**
123
	 * Prevent __wakeup()'ing of this class.
124
	 *
125
	 * @since 5.0.0
126
	 */
127
	public function __wakeup() {
128
		wp_die( "Please don't __wakeup Jetpack_Search" );
129
	}
130
131
	/**
132
	 * Get singleton instance of Jetpack_Search.
133
	 *
134
	 * Instantiates and sets up a new instance if needed, or returns the singleton.
135
	 *
136
	 * @since 5.0.0
137
	 *
138
	 * @return Jetpack_Search The Jetpack_Search singleton.
139
	 */
140
	public static function instance() {
141
		if ( ! isset( self::$instance ) ) {
142
			if ( Jetpack_Search_Options::is_instant_enabled() ) {
143
				require_once __DIR__ . '/class-jetpack-instant-search.php';
144
				self::$instance = new Jetpack_Instant_Search();
145
			} else {
146
				self::$instance = new Jetpack_Search();
147
			}
148
149
			self::$instance->setup();
150
		}
151
152
		return self::$instance;
153
	}
154
155
	/**
156
	 * Perform various setup tasks for the class.
157
	 *
158
	 * Checks various pre-requisites and adds hooks.
159
	 *
160
	 * @since 5.0.0
161
	 */
162
	public function setup() {
163
		if ( ! Jetpack::is_connection_ready() || ! $this->is_search_supported() ) {
164
			/**
165
			 * Fires when the Jetpack Search fails and would fallback to MySQL.
166
			 *
167
			 * @module search
168
			 * @since 7.9.0
169
			 *
170
			 * @param string $reason Reason for Search fallback.
171
			 * @param mixed  $data   Data associated with the request, such as attempted search parameters.
172
			 */
173
			do_action( 'jetpack_search_abort', 'inactive', null );
174
			return;
175
		}
176
177
		$this->jetpack_blog_id = Jetpack::get_option( 'id' );
178
179
		if ( ! $this->jetpack_blog_id ) {
180
			/** This action is documented in modules/search/class.jetpack-search.php */
181
			do_action( 'jetpack_search_abort', 'no_blog_id', null );
182
			return;
183
		}
184
185
		$this->load_php();
186
		$this->init_hooks();
187
	}
188
189
	/**
190
	 * Loads the php for this version of search
191
	 *
192
	 * @since 8.3.0
193
	 */
194
	public function load_php() {
195
		$this->base_load_php();
196
	}
197
198
	/**
199
	 * Loads the PHP common to all search. Should be called from extending classes.
200
	 */
201
	protected function base_load_php() {
202
		require_once __DIR__ . '/class.jetpack-search-helpers.php';
203
		require_once __DIR__ . '/class.jetpack-search-template-tags.php';
204
		require_once JETPACK__PLUGIN_DIR . 'modules/widgets/search.php';
205
	}
206
207
	/**
208
	 * Setup the various hooks needed for the plugin to take over search duties.
209
	 *
210
	 * @since 5.0.0
211
	 */
212
	public function init_hooks() {
213 View Code Duplication
		if ( ! is_admin() ) {
214
			add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
215
216
			add_filter( 'jetpack_search_es_wp_query_args', array( $this, 'filter__add_date_filter_to_query' ), 10, 2 );
217
218
			add_action( 'did_jetpack_search_query', array( $this, 'store_last_query_info' ) );
219
			add_action( 'failed_jetpack_search_query', array( $this, 'store_query_failure' ) );
220
221
			add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
222
223
			add_action( 'pre_get_posts', array( $this, 'maybe_add_post_type_as_var' ) );
224
		} else {
225
			add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
226
		}
227
228
		add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
229
	}
230
231
	/**
232
	 * Is search supported on the current plan
233
	 *
234
	 * @since 6.0
235
	 * Loads scripts for Tracks analytics library
236
	 */
237
	public function is_search_supported() {
238
		if ( method_exists( 'Jetpack_Plan', 'supports' ) ) {
239
			return Jetpack_Plan::supports( 'search' );
240
		}
241
		return false;
242
	}
243
244
	/**
245
	 * Does this site have a VIP index
246
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
247
	 *
248
	 * @since 6.0
249
	 * @return string $script_version Version number.
250
	 */
251
	public function has_vip_index() {
252
		return defined( 'JETPACK_SEARCH_VIP_INDEX' ) && JETPACK_SEARCH_VIP_INDEX;
253
	}
254
255
	/**
256
	 * When an Elasticsearch query fails, this stores it and enqueues some debug information in the footer.
257
	 *
258
	 * @since 5.6.0
259
	 *
260
	 * @param array $meta Information about the failure.
261
	 */
262
	public function store_query_failure( $meta ) {
263
		$this->last_query_failure_info = $meta;
264
		add_action( 'wp_footer', array( $this, 'print_query_failure' ) );
265
	}
266
267
	/**
268
	 * Outputs information about the last Elasticsearch failure.
269
	 *
270
	 * @since 5.6.0
271
	 */
272
	public function print_query_failure() {
273
		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...
274
			printf(
275
				'<!-- Jetpack Search failed with code %s: %s - %s -->',
276
				esc_html( $this->last_query_failure_info['response_code'] ),
277
				esc_html( $this->last_query_failure_info['json']['error'] ),
278
				esc_html( $this->last_query_failure_info['json']['message'] )
279
			);
280
		}
281
	}
282
283
	/**
284
	 * Stores information about the last Elasticsearch query and enqueues some debug information in the footer.
285
	 *
286
	 * @since 5.6.0
287
	 *
288
	 * @param array $meta Information about the query.
289
	 */
290
	public function store_last_query_info( $meta ) {
291
		$this->last_query_info = $meta;
292
		add_action( 'wp_footer', array( $this, 'print_query_success' ) );
293
	}
294
295
	/**
296
	 * Outputs information about the last Elasticsearch search.
297
	 *
298
	 * @since 5.6.0
299
	 */
300
	public function print_query_success() {
301
		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...
302
			printf(
303
				'<!-- Jetpack Search took %s ms, ES time %s ms -->',
304
				(int) $this->last_query_info['elapsed_time'],
305
				esc_html( $this->last_query_info['es_time'] )
306
			);
307
308
			if ( isset( $_GET['searchdebug'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
309
				printf(
310
					'<!-- Query response data: %s -->',
311
					esc_html( print_r( $this->last_query_info, 1 ) ) // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_print_r
312
				);
313
			}
314
		}
315
	}
316
317
	/**
318
	 * Returns the last query information, or false if no information was stored.
319
	 *
320
	 * @since 5.8.0
321
	 *
322
	 * @return bool|array
323
	 */
324
	public function get_last_query_info() {
325
		return empty( $this->last_query_info ) ? false : $this->last_query_info;
326
	}
327
328
	/**
329
	 * Returns the last query failure information, or false if no failure information was stored.
330
	 *
331
	 * @since 5.8.0
332
	 *
333
	 * @return bool|array
334
	 */
335
	public function get_last_query_failure_info() {
336
		return empty( $this->last_query_failure_info ) ? false : $this->last_query_failure_info;
337
	}
338
339
	/**
340
	 * Wraps a WordPress filter called "jetpack_search_disable_widget_filters" that allows
341
	 * developers to disable filters supplied by the search widget. Useful if filters are
342
	 * being defined at the code level.
343
	 *
344
	 * @since      5.7.0
345
	 * @deprecated 5.8.0 Use Jetpack_Search_Helpers::are_filters_by_widget_disabled() directly.
346
	 *
347
	 * @return bool
348
	 */
349
	public function are_filters_by_widget_disabled() {
350
		return Jetpack_Search_Helpers::are_filters_by_widget_disabled();
351
	}
352
353
	/**
354
	 * Retrieves a list of known Jetpack search filters widget IDs, gets the filters for each widget,
355
	 * and applies those filters to this Jetpack_Search object.
356
	 *
357
	 * @since 5.7.0
358
	 */
359
	public function set_filters_from_widgets() {
360
		if ( Jetpack_Search_Helpers::are_filters_by_widget_disabled() ) {
361
			return;
362
		}
363
364
		$filters = Jetpack_Search_Helpers::get_filters_from_widgets();
365
366
		if ( ! empty( $filters ) ) {
367
			$this->set_filters( $filters );
368
		}
369
	}
370
371
	/**
372
	 * Restricts search results to certain post types via a GET argument.
373
	 *
374
	 * @since 5.8.0
375
	 *
376
	 * @param WP_Query $query A WP_Query instance.
377
	 */
378
	public function maybe_add_post_type_as_var( WP_Query $query ) {
379
		$post_type = ( ! empty( $_GET['post_type'] ) ) ? $_GET['post_type'] : false; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
380
		if ( $this->should_handle_query( $query ) && $post_type ) {
381
			$post_types = ( is_string( $post_type ) && false !== strpos( $post_type, ',' ) )
382
				? explode( ',', $post_type )
383
				: (array) $post_type;
384
			$post_types = array_map( 'sanitize_key', $post_types );
385
			$query->set( 'post_type', $post_types );
386
		}
387
	}
388
389
	/**
390
	 * Run a search on the WordPress.com public API.
391
	 *
392
	 * @since 5.0.0
393
	 *
394
	 * @param array $es_args Args conforming to the WP.com /sites/<blog_id>/search endpoint.
395
	 *
396
	 * @return object|WP_Error The response from the public API, or a WP_Error.
397
	 */
398
	public function search( array $es_args ) {
399
		$endpoint    = sprintf( '/sites/%s/search', $this->jetpack_blog_id );
400
		$service_url = 'https://public-api.wordpress.com/rest/v1' . $endpoint;
401
402
		$do_authenticated_request = false;
403
404
		if ( class_exists( 'Automattic\\Jetpack\\Connection\\Client' ) &&
405
			isset( $es_args['authenticated_request'] ) &&
406
			true === $es_args['authenticated_request'] ) {
407
			$do_authenticated_request = true;
408
		}
409
410
		unset( $es_args['authenticated_request'] );
411
412
		$request_args = array(
413
			'headers'    => array(
414
				'Content-Type' => 'application/json',
415
			),
416
			'timeout'    => 10,
417
			'user-agent' => 'jetpack_search',
418
		);
419
420
		$request_body = wp_json_encode( $es_args );
421
422
		$start_time = microtime( true );
423
424
		if ( $do_authenticated_request ) {
425
			$request_args['method'] = 'POST';
426
427
			$request = Client::wpcom_json_api_request_as_blog( $endpoint, Client::WPCOM_JSON_API_VERSION, $request_args, $request_body );
0 ignored issues
show
Security Bug introduced by
It seems like $request_body defined by wp_json_encode($es_args) on line 420 can also be of type false; however, Automattic\Jetpack\Conne...n_api_request_as_blog() does only seem to accept string|null, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
428
		} else {
429
			$request_args = array_merge(
430
				$request_args,
431
				array(
432
					'body' => $request_body,
433
				)
434
			);
435
436
			$request = wp_remote_post( $service_url, $request_args );
437
		}
438
439
		$end_time = microtime( true );
440
441
		if ( is_wp_error( $request ) ) {
442
			return $request;
443
		}
444
		$response_code = wp_remote_retrieve_response_code( $request );
445
446
		if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
447
			return new WP_Error( 'invalid_search_api_response', 'Invalid response from API - ' . $response_code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_search_api_response'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
448
		}
449
450
		$response = json_decode( wp_remote_retrieve_body( $request ), true );
451
452
		$took = is_array( $response ) && ! empty( $response['took'] )
453
			? $response['took']
454
			: null;
455
456
		$query = array(
457
			'args'          => $es_args,
458
			'response'      => $response,
459
			'response_code' => $response_code,
460
			'elapsed_time'  => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
461
			'es_time'       => $took,
462
			'url'           => $service_url,
463
		);
464
465
		/**
466
		 * Fires after a search request has been performed.
467
		 *
468
		 * Includes the following info in the $query parameter:
469
		 *
470
		 * array args Array of Elasticsearch arguments for the search
471
		 * array response Raw API response, JSON decoded
472
		 * int response_code HTTP response code of the request
473
		 * float elapsed_time Roundtrip time of the search request, in milliseconds
474
		 * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
475
		 * string url API url that was queried
476
		 *
477
		 * @module search
478
		 *
479
		 * @since  5.0.0
480
		 * @since  5.8.0 This action now fires on all queries instead of just successful queries.
481
		 *
482
		 * @param array $query Array of information about the query performed
483
		 */
484
		do_action( 'did_jetpack_search_query', $query );
485
486 View Code Duplication
		if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
487
			/**
488
			 * Fires after a search query request has failed
489
			 *
490
			 * @module search
491
			 *
492
			 * @since  5.6.0
493
			 *
494
			 * @param array Array containing the response code and response from the failed search query
495
			 */
496
			do_action(
497
				'failed_jetpack_search_query',
498
				array(
499
					'response_code' => $response_code,
500
					'json'          => $response,
501
				)
502
			);
503
504
			return new WP_Error( 'invalid_search_api_response', 'Invalid response from API - ' . $response_code );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'invalid_search_api_response'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
505
		}
506
507
		return $response;
508
	}
509
510
	/**
511
	 * Bypass the normal Search query and offload it to Jetpack servers.
512
	 *
513
	 * This is the main hook of the plugin and is responsible for returning the posts that match the search query.
514
	 *
515
	 * @since 5.0.0
516
	 *
517
	 * @param array    $posts Current array of posts (still pre-query).
518
	 * @param WP_Query $query The WP_Query being filtered.
519
	 *
520
	 * @return array Array of matching posts.
521
	 */
522
	public function filter__posts_pre_query( $posts, $query ) {
523
		if ( ! $this->should_handle_query( $query ) ) {
524
			// Intentionally not adding the 'jetpack_search_abort' action since this should fire for every request except for search.
525
			return $posts;
526
		}
527
528
		$this->do_search( $query );
529
530
		if ( ! is_array( $this->search_result ) ) {
531
			/** This action is documented in modules/search/class.jetpack-search.php */
532
			do_action( 'jetpack_search_abort', 'no_search_results_array', $this->search_result );
533
			return $posts;
534
		}
535
536
		// If no results, nothing to do.
537
		if ( ! count( $this->search_result['results']['hits'] ) ) {
538
			return array();
539
		}
540
541
		$post_ids = array();
542
543
		foreach ( $this->search_result['results']['hits'] as $result ) {
544
			$post_ids[] = (int) $result['fields']['post_id'];
545
		}
546
547
		// Query all posts now.
548
		$args = array(
549
			'post__in'            => $post_ids,
550
			'orderby'             => 'post__in',
551
			'perm'                => 'readable',
552
			'post_type'           => 'any',
553
			'ignore_sticky_posts' => true,
554
			'suppress_filters'    => true,
555
			'posts_per_page'      => $query->get( 'posts_per_page' ),
556
		);
557
558
		$posts_query = new WP_Query( $args );
559
560
		// 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.
561
		$query->found_posts   = $this->found_posts;
562
		$query->max_num_pages = ceil( $this->found_posts / $query->get( 'posts_per_page' ) );
563
564
		return $posts_query->posts;
565
	}
566
567
	/**
568
	 * Build up the search, then run it against the Jetpack servers.
569
	 *
570
	 * @since 5.0.0
571
	 *
572
	 * @param WP_Query $query The original WP_Query to use for the parameters of our search.
573
	 */
574
	public function do_search( WP_Query $query ) {
575
		if ( ! $this->should_handle_query( $query ) ) {
576
			// If we make it here, either 'filter__posts_pre_query' somehow allowed it or a different entry to do_search.
577
			/** This action is documented in modules/search/class.jetpack-search.php */
578
			do_action( 'jetpack_search_abort', 'search_attempted_non_search_query', $query );
579
			return;
580
		}
581
582
		$page = ( $query->get( 'paged' ) ) ? absint( $query->get( 'paged' ) ) : 1;
583
584
		// Get maximum allowed offset and posts per page values for the API.
585
		$max_offset         = Jetpack_Search_Helpers::get_max_offset();
586
		$max_posts_per_page = Jetpack_Search_Helpers::get_max_posts_per_page();
587
588
		$posts_per_page = $query->get( 'posts_per_page' );
589
		if ( $posts_per_page > $max_posts_per_page ) {
590
			$posts_per_page = $max_posts_per_page;
591
		}
592
593
		// Start building the WP-style search query args.
594
		// They'll be translated to ES format args later.
595
		$es_wp_query_args = array(
596
			'query'          => $query->get( 's' ),
597
			'posts_per_page' => $posts_per_page,
598
			'paged'          => $page,
599
			'orderby'        => $query->get( 'orderby' ),
600
			'order'          => $query->get( 'order' ),
601
		);
602
603
		if ( ! empty( $this->aggregations ) ) {
604
			$es_wp_query_args['aggregations'] = $this->aggregations;
605
		}
606
607
		// Did we query for authors?
608
		if ( $query->get( 'author_name' ) ) {
609
			$es_wp_query_args['author_name'] = $query->get( 'author_name' );
610
		}
611
612
		$es_wp_query_args['post_type'] = $this->get_es_wp_query_post_type_for_query( $query );
613
		$es_wp_query_args['terms']     = $this->get_es_wp_query_terms_for_query( $query );
614
615
		/**
616
		 * Modify the search query parameters, such as controlling the post_type.
617
		 *
618
		 * These arguments are in the format of WP_Query arguments
619
		 *
620
		 * @module search
621
		 *
622
		 * @since  5.0.0
623
		 *
624
		 * @param array    $es_wp_query_args The current query args, in WP_Query format.
625
		 * @param WP_Query $query            The original WP_Query object.
626
		 */
627
		$es_wp_query_args = apply_filters( 'jetpack_search_es_wp_query_args', $es_wp_query_args, $query );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $query.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
628
629
		// If page * posts_per_page is greater than our max offset, send a 404. This is necessary because the offset is
630
		// capped at Jetpack_Search_Helpers::get_max_offset(), so a high page would always return the last page of results otherwise.
631
		if ( ( $es_wp_query_args['paged'] * $es_wp_query_args['posts_per_page'] ) > $max_offset ) {
632
			$query->set_404();
633
634
			return;
635
		}
636
637
		// If there were no post types returned, then 404 to avoid querying against non-public post types, which could
638
		// happen if we don't add the post type restriction to the ES query.
639
		if ( empty( $es_wp_query_args['post_type'] ) ) {
640
			$query->set_404();
641
642
			return;
643
		}
644
645
		// Convert the WP-style args into ES args.
646
		$es_query_args = $this->convert_wp_es_to_es_args( $es_wp_query_args );
647
648
		// Only trust ES to give us IDs, not the content since it is a mirror.
649
		$es_query_args['fields'] = array(
650
			'post_id',
651
		);
652
653
		/**
654
		 * Modify the underlying ES query that is passed to the search endpoint. The returned args must represent a valid ES query
655
		 *
656
		 * This filter is harder to use if you're unfamiliar with ES, but allows complete control over the query
657
		 *
658
		 * @module search
659
		 *
660
		 * @since  5.0.0
661
		 *
662
		 * @param array    $es_query_args The raw Elasticsearch query args.
663
		 * @param WP_Query $query         The original WP_Query object.
664
		 */
665
		$es_query_args = apply_filters( 'jetpack_search_es_query_args', $es_query_args, $query );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $query.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
666
667
		// Do the actual search query!
668
		$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...
669
670
		if ( is_wp_error( $this->search_result ) || ! is_array( $this->search_result ) || empty( $this->search_result['results'] ) || empty( $this->search_result['results']['hits'] ) ) {
671
			$this->found_posts = 0;
672
673
			return;
674
		}
675
676
		// If we have aggregations, fix the ordering to match the input order (ES doesn't guarantee the return order).
677
		if ( isset( $this->search_result['results']['aggregations'] ) && ! empty( $this->search_result['results']['aggregations'] ) ) {
678
			$this->search_result['results']['aggregations'] = $this->fix_aggregation_ordering( $this->search_result['results']['aggregations'], $this->aggregations );
679
		}
680
681
		// Total number of results for paging purposes. Capped at $max_offset + $posts_per_page, as deep paging gets quite expensive.
682
		$this->found_posts = min( $this->search_result['results']['total'], $max_offset + $posts_per_page );
683
	}
684
685
	/**
686
	 * If the query has already been run before filters have been updated, then we need to re-run the query
687
	 * to get the latest aggregations.
688
	 *
689
	 * This is especially useful for supporting widget management in the customizer.
690
	 *
691
	 * @since 5.8.0
692
	 *
693
	 * @return bool Whether the query was successful or not.
694
	 */
695
	public function update_search_results_aggregations() {
696
		if ( empty( $this->last_query_info ) || empty( $this->last_query_info['args'] ) ) {
697
			return false;
698
		}
699
700
		$es_args = $this->last_query_info['args'];
701
		$builder = new Jetpack_WPES_Query_Builder();
702
		$this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
703
		$es_args['aggregations'] = $builder->build_aggregation();
704
705
		$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...
706
707
		return ! is_wp_error( $this->search_result );
708
	}
709
710
	/**
711
	 * Given a WP_Query, convert its WP_Tax_Query (if present) into the WP-style Elasticsearch term arguments for the search.
712
	 *
713
	 * @since 5.0.0
714
	 *
715
	 * @param WP_Query $query The original WP_Query object for which to parse the taxonomy query.
716
	 *
717
	 * @return array The new WP-style Elasticsearch arguments (that will be converted into 'real' Elasticsearch arguments).
718
	 */
719
	public function get_es_wp_query_terms_for_query( WP_Query $query ) {
720
		$args = array();
721
722
		$the_tax_query = $query->tax_query;
723
724
		if ( ! $the_tax_query ) {
725
			return $args;
726
		}
727
728
		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...
729
			return $args;
730
		}
731
732
		$args = array();
733
734
		foreach ( $the_tax_query->queries as $tax_query ) {
735
			// Right now we only support slugs...see note above.
736
			if ( ! is_array( $tax_query ) || 'slug' !== $tax_query['field'] ) {
737
				continue;
738
			}
739
740
			$taxonomy = $tax_query['taxonomy'];
741
742 View Code Duplication
			if ( ! isset( $args[ $taxonomy ] ) || ! is_array( $args[ $taxonomy ] ) ) {
743
				$args[ $taxonomy ] = array();
744
			}
745
746
			$args[ $taxonomy ] = array_merge( $args[ $taxonomy ], $tax_query['terms'] );
747
		}
748
749
		return $args;
750
	}
751
752
	/**
753
	 * Parse out the post type from a WP_Query.
754
	 *
755
	 * Only allows post types that are not marked as 'exclude_from_search'.
756
	 *
757
	 * @since 5.0.0
758
	 *
759
	 * @param WP_Query $query Original WP_Query object.
760
	 *
761
	 * @return array Array of searchable post types corresponding to the original query.
762
	 */
763
	public function get_es_wp_query_post_type_for_query( WP_Query $query ) {
764
		$post_types = $query->get( 'post_type' );
765
766
		// If we're searching 'any', we want to only pass searchable post types to Elasticsearch.
767
		if ( 'any' === $post_types ) {
768
			$post_types = array_values(
769
				get_post_types(
770
					array(
771
						'exclude_from_search' => false,
772
					)
773
				)
774
			);
775
		}
776
777
		if ( ! is_array( $post_types ) ) {
778
			$post_types = array( $post_types );
779
		}
780
781
		$post_types = array_unique( $post_types );
782
783
		$sanitized_post_types = array();
784
785
		// Make sure the post types are queryable.
786
		foreach ( $post_types as $post_type ) {
787
			if ( ! $post_type ) {
788
				continue;
789
			}
790
791
			$post_type_object = get_post_type_object( $post_type );
792
			if ( ! $post_type_object || $post_type_object->exclude_from_search ) {
793
				continue;
794
			}
795
796
			$sanitized_post_types[] = $post_type;
797
		}
798
799
		return $sanitized_post_types;
800
	}
801
802
	/**
803
	 * Initialize widgets for the Search module (on wp.com only).
804
	 *
805
	 * @module search
806
	 */
807
	public function action__widgets_init() {
808
		require_once __DIR__ . '/class.jetpack-search-widget-filters.php';
809
810
		register_widget( 'Jetpack_Search_Widget_Filters' );
811
	}
812
813
	/**
814
	 * Get the Elasticsearch result.
815
	 *
816
	 * @since 5.0.0
817
	 *
818
	 * @param bool $raw If true, does not check for WP_Error or return the 'results' array - the JSON decoded HTTP response.
819
	 *
820
	 * @return array|bool The search results, or false if there was a failure.
821
	 */
822
	public function get_search_result( $raw = false ) {
823
		if ( $raw ) {
824
			return $this->search_result;
825
		}
826
827
		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;
828
	}
829
830
	/**
831
	 * Add the date portion of a WP_Query onto the query args.
832
	 *
833
	 * @since 5.0.0
834
	 *
835
	 * @param array    $es_wp_query_args The Elasticsearch query arguments in WordPress form.
836
	 * @param WP_Query $query            The original WP_Query.
837
	 *
838
	 * @return array The es wp query args, with date filters added (as needed).
839
	 */
840
	public function filter__add_date_filter_to_query( array $es_wp_query_args, WP_Query $query ) {
841
		if ( $query->get( 'year' ) ) {
842
			if ( $query->get( 'monthnum' ) ) {
843
				// Padding.
844
				$date_monthnum = sprintf( '%02d', $query->get( 'monthnum' ) );
845
846
				if ( $query->get( 'day' ) ) {
847
					// Padding.
848
					$date_day = sprintf( '%02d', $query->get( 'day' ) );
849
850
					$date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 00:00:00';
851
					$date_end   = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $date_day . ' 23:59:59';
852
				} else {
853
					$days_in_month = gmdate( 't', mktime( 0, 0, 0, $query->get( 'monthnum' ), 14, $query->get( 'year' ) ) ); // 14 = middle of the month so no chance of DST issues
854
855
					$date_start = $query->get( 'year' ) . '-' . $date_monthnum . '-01 00:00:00';
856
					$date_end   = $query->get( 'year' ) . '-' . $date_monthnum . '-' . $days_in_month . ' 23:59:59';
857
				}
858
			} else {
859
				$date_start = $query->get( 'year' ) . '-01-01 00:00:00';
860
				$date_end   = $query->get( 'year' ) . '-12-31 23:59:59';
861
			}
862
863
			$es_wp_query_args['date_range'] = array(
864
				'field' => 'date',
865
				'gte'   => $date_start,
866
				'lte'   => $date_end,
867
			);
868
		}
869
870
		return $es_wp_query_args;
871
	}
872
873
	/**
874
	 * Converts WP_Query style args to Elasticsearch args.
875
	 *
876
	 * @since 5.0.0
877
	 *
878
	 * @param array $args Array of WP_Query style arguments.
879
	 *
880
	 * @return array Array of ES style query arguments.
881
	 */
882
	public function convert_wp_es_to_es_args( array $args ) {
883
		jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-parser' );
884
885
		$defaults = array(
886
			'blog_id'        => get_current_blog_id(),
887
			'query'          => null,    // Search phrase.
888
			'query_fields'   => array(), // list of fields to search.
889
			'excess_boost'   => array(), // map of field to excess boost values (multiply).
890
			'post_type'      => null,    // string or an array.
891
			'terms'          => array(), // ex: array( 'taxonomy-1' => array( 'slug' ), 'taxonomy-2' => array( 'slug-a', 'slug-b' ) ). phpcs:ignore Squiz.PHP.CommentedOutCode.Found.
892
			'author'         => null,    // id or an array of ids.
893
			'author_name'    => array(), // string or an array.
894
			'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'. phpcs:ignore Squiz.PHP.CommentedOutCode.Found.
895
			'orderby'        => null,    // Defaults to 'relevance' if query is set, otherwise 'date'. Pass an array for multiple orders.
896
			'order'          => 'DESC',
897
			'posts_per_page' => 10,
898
			'offset'         => null,
899
			'paged'          => null,
900
			/**
901
			 * Aggregations. Examples:
902
			 * array(
903
			 *     'Tag'       => array( 'type' => 'taxonomy', 'taxonomy' => 'post_tag', 'count' => 10 ) ),
904
			 *     'Post Type' => array( 'type' => 'post_type', 'count' => 10 ) ),
905
			 * );
906
			 */
907
			'aggregations'   => null,
908
		);
909
910
		$args = wp_parse_args( $args, $defaults );
0 ignored issues
show
Documentation introduced by
$defaults is of type array<string,?,{"blog_id..."aggregations":"null"}>, but the function expects a string.

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...
911
912
		$parser = new Jetpack_WPES_Search_Query_Parser(
913
			$args['query'],
914
			/**
915
			 * Filter the languages used by Jetpack Search's Query Parser.
916
			 *
917
			 * @module search
918
			 *
919
			 * @since  7.9.0
920
			 *
921
			 * @param array $languages The array of languages. Default is value of get_locale().
922
			 */
923
			apply_filters( 'jetpack_search_query_languages', array( get_locale() ) )
924
		);
925
926
		if ( empty( $args['query_fields'] ) ) {
927
			if ( $this->has_vip_index() ) {
928
				// VIP indices do not have per language fields.
929
				$match_fields = $this->_get_caret_boosted_fields(
930
					array(
931
						'title'         => 0.1,
932
						'content'       => 0.1,
933
						'excerpt'       => 0.1,
934
						'tag.name'      => 0.1,
935
						'category.name' => 0.1,
936
						'author_login'  => 0.1,
937
						'author'        => 0.1,
938
					)
939
				);
940
941
				$boost_fields = $this->_get_caret_boosted_fields(
942
					$this->_apply_boosts_multiplier(
943
						array(
944
							'title'         => 2,
945
							'tag.name'      => 1,
946
							'category.name' => 1,
947
							'author_login'  => 1,
948
							'author'        => 1,
949
						),
950
						$args['excess_boost']
951
					)
952
				);
953
954
				$boost_phrase_fields = $this->_get_caret_boosted_fields(
955
					array(
956
						'title'         => 1,
957
						'content'       => 1,
958
						'excerpt'       => 1,
959
						'tag.name'      => 1,
960
						'category.name' => 1,
961
						'author'        => 1,
962
					)
963
				);
964
			} else {
965
				$match_fields = $parser->merge_ml_fields(
966
					array(
967
						'title'         => 0.1,
968
						'content'       => 0.1,
969
						'excerpt'       => 0.1,
970
						'tag.name'      => 0.1,
971
						'category.name' => 0.1,
972
					),
973
					$this->_get_caret_boosted_fields(
974
						array(
975
							'author_login' => 0.1,
976
							'author'       => 0.1,
977
						)
978
					)
979
				);
980
981
				$boost_fields = $parser->merge_ml_fields(
982
					$this->_apply_boosts_multiplier(
983
						array(
984
							'title'         => 2,
985
							'tag.name'      => 1,
986
							'category.name' => 1,
987
						),
988
						$args['excess_boost']
989
					),
990
					$this->_get_caret_boosted_fields(
991
						$this->_apply_boosts_multiplier(
992
							array(
993
								'author_login' => 1,
994
								'author'       => 1,
995
							),
996
							$args['excess_boost']
997
						)
998
					)
999
				);
1000
1001
				$boost_phrase_fields = $parser->merge_ml_fields(
1002
					array(
1003
						'title'         => 1,
1004
						'content'       => 1,
1005
						'excerpt'       => 1,
1006
						'tag.name'      => 1,
1007
						'category.name' => 1,
1008
					),
1009
					$this->_get_caret_boosted_fields(
1010
						array(
1011
							'author' => 1,
1012
						)
1013
					)
1014
				);
1015
			}
1016
		} else {
1017
			// If code is overriding the fields, then use that. Important for backwards compatibility.
1018
			$match_fields        = $args['query_fields'];
1019
			$boost_phrase_fields = $match_fields;
1020
			$boost_fields        = null;
1021
		}
1022
1023
		$parser->phrase_filter(
1024
			array(
1025
				'must_query_fields'  => $match_fields,
1026
				'boost_query_fields' => null,
1027
			)
1028
		);
1029
		$parser->remaining_query(
1030
			array(
1031
				'must_query_fields'  => $match_fields,
1032
				'boost_query_fields' => $boost_fields,
1033
			)
1034
		);
1035
1036
		// Boost on phrase matches.
1037
		$parser->remaining_query(
1038
			array(
1039
				'boost_query_fields' => $boost_phrase_fields,
1040
				'boost_query_type'   => 'phrase',
1041
			)
1042
		);
1043
1044
		/**
1045
		 * Modify the recency decay parameters for the search query.
1046
		 *
1047
		 * The recency decay lowers the search scores based on the age of a post relative to an origin date. Basic adjustments:
1048
		 *  - origin: A date. Posts with this date will have the highest score and no decay applied. Default is today.
1049
		 *  - 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.
1050
		 *  - scale: The number of days/months/years from the origin+offset at which the decay will equal the decay param. Default 360d
1051
		 *  - decay: The amount of decay applied at offset+scale. Default 0.9.
1052
		 *
1053
		 * 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}
1054
		 *
1055
		 * @module search
1056
		 *
1057
		 * @since  5.8.0
1058
		 *
1059
		 * @param array $decay_params The decay parameters.
1060
		 * @param array $args         The WP query parameters.
1061
		 */
1062
		$decay_params = apply_filters(
1063
			'jetpack_search_recency_score_decay',
1064
			array(
1065
				'origin' => gmdate( 'Y-m-d' ),
1066
				'scale'  => '360d',
1067
				'decay'  => 0.9,
1068
			),
1069
			$args
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $args.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1070
		);
1071
1072
		if ( ! empty( $decay_params ) ) {
1073
			// Newer content gets weighted slightly higher.
1074
			$parser->add_decay(
1075
				'gauss',
1076
				array(
1077
					'date_gmt' => $decay_params,
1078
				)
1079
			);
1080
		}
1081
1082
		$es_query_args = array(
1083
			'blog_id' => absint( $args['blog_id'] ),
1084
			'size'    => absint( $args['posts_per_page'] ),
1085
		);
1086
1087
		// ES "from" arg (offset).
1088
		if ( $args['offset'] ) {
1089
			$es_query_args['from'] = absint( $args['offset'] );
1090
		} elseif ( $args['paged'] ) {
1091
			$es_query_args['from'] = max( 0, ( absint( $args['paged'] ) - 1 ) * $es_query_args['size'] );
1092
		}
1093
1094
		$es_query_args['from'] = min( $es_query_args['from'], Jetpack_Search_Helpers::get_max_offset() );
1095
1096
		if ( ! is_array( $args['author_name'] ) ) {
1097
			$args['author_name'] = array( $args['author_name'] );
1098
		}
1099
1100
		// ES stores usernames, not IDs, so transform.
1101
		if ( ! empty( $args['author'] ) ) {
1102
			if ( ! is_array( $args['author'] ) ) {
1103
				$args['author'] = array( $args['author'] );
1104
			}
1105
1106
			foreach ( $args['author'] as $author ) {
1107
				$user = get_user_by( 'id', $author );
1108
1109
				if ( $user && ! empty( $user->user_login ) ) {
1110
					$args['author_name'][] = $user->user_login;
1111
				}
1112
			}
1113
		}
1114
1115
		/*
1116
		 * Build the filters from the query elements.
1117
		 * Filters rock because they are cached from one query to the next
1118
		 * but they are cached as individual filters, rather than all combined together.
1119
		 * May get performance boost by also caching the top level boolean filter too.
1120
		 */
1121
1122
		if ( $args['post_type'] ) {
1123
			if ( ! is_array( $args['post_type'] ) ) {
1124
				$args['post_type'] = array( $args['post_type'] );
1125
			}
1126
1127
			$parser->add_filter(
1128
				array(
1129
					'terms' => array(
1130
						'post_type' => $args['post_type'],
1131
					),
1132
				)
1133
			);
1134
		}
1135
1136
		if ( $args['author_name'] ) {
1137
			$parser->add_filter(
1138
				array(
1139
					'terms' => array(
1140
						'author_login' => $args['author_name'],
1141
					),
1142
				)
1143
			);
1144
		}
1145
1146
		if ( ! empty( $args['date_range'] ) && isset( $args['date_range']['field'] ) ) {
1147
			$field = $args['date_range']['field'];
1148
1149
			unset( $args['date_range']['field'] );
1150
1151
			$parser->add_filter(
1152
				array(
1153
					'range' => array(
1154
						$field => $args['date_range'],
1155
					),
1156
				)
1157
			);
1158
		}
1159
1160
		if ( is_array( $args['terms'] ) ) {
1161
			foreach ( $args['terms'] as $tax => $terms ) {
1162
				$terms = (array) $terms;
1163
1164
				if ( count( $terms ) && mb_strlen( $tax ) ) {
1165 View Code Duplication
					switch ( $tax ) {
1166
						case 'post_tag':
1167
							$tax_fld = 'tag.slug';
1168
1169
							break;
1170
1171
						case 'category':
1172
							$tax_fld = 'category.slug';
1173
1174
							break;
1175
1176
						default:
1177
							$tax_fld = 'taxonomy.' . $tax . '.slug';
1178
1179
							break;
1180
					}
1181
1182
					foreach ( $terms as $term ) {
1183
						$parser->add_filter(
1184
							array(
1185
								'term' => array(
1186
									$tax_fld => $term,
1187
								),
1188
							)
1189
						);
1190
					}
1191
				}
1192
			}
1193
		}
1194
1195
		if ( ! $args['orderby'] ) {
1196
			if ( $args['query'] ) {
1197
				$args['orderby'] = array( 'relevance' );
1198
			} else {
1199
				$args['orderby'] = array( 'date' );
1200
			}
1201
		}
1202
1203
		// Validate the "order" field.
1204
		switch ( strtolower( $args['order'] ) ) {
1205
			case 'asc':
1206
				$args['order'] = 'asc';
1207
				break;
1208
1209
			case 'desc':
1210
			default:
1211
				$args['order'] = 'desc';
1212
				break;
1213
		}
1214
1215
		$es_query_args['sort'] = array();
1216
1217
		foreach ( (array) $args['orderby'] as $orderby ) {
1218
			// Translate orderby from WP field to ES field.
1219
			switch ( $orderby ) {
1220
				case 'relevance':
1221
					// never order by score ascending.
1222
					$es_query_args['sort'][] = array(
1223
						'_score' => array(
1224
							'order' => 'desc',
1225
						),
1226
					);
1227
1228
					break;
1229
1230 View Code Duplication
				case 'date':
1231
					$es_query_args['sort'][] = array(
1232
						'date' => array(
1233
							'order' => $args['order'],
1234
						),
1235
					);
1236
1237
					break;
1238
1239 View Code Duplication
				case 'ID':
1240
					$es_query_args['sort'][] = array(
1241
						'id' => array(
1242
							'order' => $args['order'],
1243
						),
1244
					);
1245
1246
					break;
1247
1248
				case 'author':
1249
					$es_query_args['sort'][] = array(
1250
						'author.raw' => array(
1251
							'order' => $args['order'],
1252
						),
1253
					);
1254
1255
					break;
1256
			} // End switch.
1257
		} // End foreach.
1258
1259
		if ( empty( $es_query_args['sort'] ) ) {
1260
			unset( $es_query_args['sort'] );
1261
		}
1262
1263
		// Aggregations.
1264
		if ( ! empty( $args['aggregations'] ) ) {
1265
			$this->add_aggregations_to_es_query_builder( $args['aggregations'], $parser );
1266
		}
1267
1268
		$es_query_args['filter']       = $parser->build_filter();
1269
		$es_query_args['query']        = $parser->build_query();
1270
		$es_query_args['aggregations'] = $parser->build_aggregation();
1271
1272
		return $es_query_args;
1273
	}
1274
1275
	/**
1276
	 * Given an array of aggregations, parse and add them onto the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1277
	 *
1278
	 * @since 5.0.0
1279
	 *
1280
	 * @param array                      $aggregations Array of aggregations (filters) to add to the Jetpack_WPES_Query_Builder.
1281
	 * @param Jetpack_WPES_Query_Builder $builder      The builder instance that is creating the Elasticsearch query.
1282
	 */
1283
	public function add_aggregations_to_es_query_builder( array $aggregations, Jetpack_WPES_Query_Builder $builder ) {
1284
		foreach ( $aggregations as $label => $aggregation ) {
1285
			if ( ! isset( $aggregation['type'] ) ) {
1286
				continue;
1287
			}
1288
			switch ( $aggregation['type'] ) {
1289
				case 'taxonomy':
1290
					$this->add_taxonomy_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1291
1292
					break;
1293
1294
				case 'post_type':
1295
					$this->add_post_type_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1296
1297
					break;
1298
1299
				case 'date_histogram':
1300
					$this->add_date_histogram_aggregation_to_es_query_builder( $aggregation, $label, $builder );
1301
1302
					break;
1303
			}
1304
		}
1305
	}
1306
1307
	/**
1308
	 * Given an individual taxonomy aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1309
	 *
1310
	 * @since 5.0.0
1311
	 *
1312
	 * @param array                      $aggregation The aggregation to add to the query builder.
1313
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1314
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1315
	 */
1316
	public function add_taxonomy_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1317
		$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...
1318
1319
		switch ( $aggregation['taxonomy'] ) {
1320
			case 'post_tag':
1321
				$field = 'tag';
1322
				break;
1323
1324
			case 'category':
1325
				$field = 'category';
1326
				break;
1327
1328
			default:
1329
				$field = 'taxonomy.' . $aggregation['taxonomy'];
1330
				break;
1331
		}
1332
1333
		$builder->add_aggs(
1334
			$label,
1335
			array(
1336
				'terms' => array(
1337
					'field' => $field . '.slug',
1338
					'size'  => min( (int) $aggregation['count'], $this->max_aggregations_count ),
1339
				),
1340
			)
1341
		);
1342
	}
1343
1344
	/**
1345
	 * Given an individual post_type aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1346
	 *
1347
	 * @since 5.0.0
1348
	 *
1349
	 * @param array                      $aggregation The aggregation to add to the query builder.
1350
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1351
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1352
	 */
1353
	public function add_post_type_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1354
		$builder->add_aggs(
1355
			$label,
1356
			array(
1357
				'terms' => array(
1358
					'field' => 'post_type',
1359
					'size'  => min( (int) $aggregation['count'], $this->max_aggregations_count ),
1360
				),
1361
			)
1362
		);
1363
	}
1364
1365
	/**
1366
	 * Given an individual date_histogram aggregation, add it to the Jetpack_WPES_Query_Builder object for use in Elasticsearch.
1367
	 *
1368
	 * @since 5.0.0
1369
	 *
1370
	 * @param array                      $aggregation The aggregation to add to the query builder.
1371
	 * @param string                     $label       The 'label' (unique id) for this aggregation.
1372
	 * @param Jetpack_WPES_Query_Builder $builder     The builder instance that is creating the Elasticsearch query.
1373
	 */
1374
	public function add_date_histogram_aggregation_to_es_query_builder( array $aggregation, $label, Jetpack_WPES_Query_Builder $builder ) {
1375
		$args = array(
1376
			'interval' => $aggregation['interval'],
1377
			'field'    => ( ! empty( $aggregation['field'] ) && 'post_date_gmt' === $aggregation['field'] ) ? 'date_gmt' : 'date',
1378
		);
1379
1380
		if ( isset( $aggregation['min_doc_count'] ) ) {
1381
			$args['min_doc_count'] = (int) $aggregation['min_doc_count'];
1382
		} else {
1383
			$args['min_doc_count'] = 1;
1384
		}
1385
1386
		$builder->add_aggs(
1387
			$label,
1388
			array(
1389
				'date_histogram' => $args,
1390
			)
1391
		);
1392
	}
1393
1394
	/**
1395
	 * And an existing filter object with a list of additional filters.
1396
	 *
1397
	 * Attempts to optimize the filters somewhat.
1398
	 *
1399
	 * @since 5.0.0
1400
	 *
1401
	 * @param array $curr_filter The existing filters to build upon.
1402
	 * @param array $filters     The new filters to add.
1403
	 *
1404
	 * @return array The resulting merged filters.
1405
	 */
1406
	public static function and_es_filters( array $curr_filter, array $filters ) {
1407
		if ( ! is_array( $curr_filter ) || isset( $curr_filter['match_all'] ) ) {
1408
			if ( 1 === count( $filters ) ) {
1409
				return $filters[0];
1410
			}
1411
1412
			return array(
1413
				'and' => $filters,
1414
			);
1415
		}
1416
1417
		return array(
1418
			'and' => array_merge( array( $curr_filter ), $filters ),
1419
		);
1420
	}
1421
1422
	/**
1423
	 * Set the available filters for the search.
1424
	 *
1425
	 * These get rendered via the Jetpack_Search_Widget() widget.
1426
	 *
1427
	 * Behind the scenes, these are implemented using Elasticsearch Aggregations.
1428
	 *
1429
	 * If you do not require counts of how many documents match each filter, please consider using regular WP Query
1430
	 * arguments instead, such as via the jetpack_search_es_wp_query_args filter
1431
	 *
1432
	 * @see    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
1433
	 *
1434
	 * @since  5.0.0
1435
	 *
1436
	 * @param array $aggregations Array of filters (aggregations) to apply to the search.
1437
	 */
1438
	public function set_filters( array $aggregations ) {
1439
		foreach ( (array) $aggregations as $key => $agg ) {
1440
			if ( empty( $agg['name'] ) ) {
1441
				$aggregations[ $key ]['name'] = $key;
1442
			}
1443
		}
1444
		$this->aggregations = $aggregations;
1445
	}
1446
1447
	/**
1448
	 * Set the search's facets (deprecated).
1449
	 *
1450
	 * @deprecated 5.0 Please use Jetpack_Search::set_filters() instead.
1451
	 *
1452
	 * @see        Jetpack_Search::set_filters()
1453
	 *
1454
	 * @param array $facets Array of facets to apply to the search.
1455
	 */
1456
	public function set_facets( array $facets ) {
1457
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::set_filters()' );
1458
1459
		$this->set_filters( $facets );
1460
	}
1461
1462
	/**
1463
	 * Get the raw Aggregation results from the Elasticsearch response.
1464
	 *
1465
	 * @since  5.0.0
1466
	 *
1467
	 * @see    https://www.elastic.co/guide/en/elasticsearch/reference/current/search-aggregations.html
1468
	 *
1469
	 * @return array Array of Aggregations performed on the search.
1470
	 */
1471
	public function get_search_aggregations_results() {
1472
		$aggregations = array();
1473
1474
		$search_result = $this->get_search_result();
1475
1476
		if ( ! empty( $search_result ) && ! empty( $search_result['aggregations'] ) ) {
1477
			$aggregations = $search_result['aggregations'];
1478
		}
1479
1480
		return $aggregations;
1481
	}
1482
1483
	/**
1484
	 * Get the raw Facet results from the Elasticsearch response.
1485
	 *
1486
	 * @deprecated 5.0 Please use Jetpack_Search::get_search_aggregations_results() instead.
1487
	 *
1488
	 * @see        Jetpack_Search::get_search_aggregations_results()
1489
	 *
1490
	 * @return array Array of Facets performed on the search.
1491
	 */
1492
	public function get_search_facets() {
1493
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_search_aggregations_results()' );
1494
1495
		return $this->get_search_aggregations_results();
1496
	}
1497
1498
	/**
1499
	 * Get the results of the Filters performed, including the number of matching documents.
1500
	 *
1501
	 * Returns an array of Filters (keyed by $label, as passed to Jetpack_Search::set_filters()), containing the Filter and all resulting
1502
	 * matching buckets, the url for applying/removing each bucket, etc.
1503
	 *
1504
	 * NOTE - if this is called before the search is performed, an empty array will be returned. Use the $aggregations class
1505
	 * member if you need to access the raw filters set in Jetpack_Search::set_filters().
1506
	 *
1507
	 * @since 5.0.0
1508
	 *
1509
	 * @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...
1510
	 *
1511
	 * @return array Array of filters applied and info about them.
1512
	 */
1513
	public function get_filters( WP_Query $query = null ) {
1514
		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...
1515
			global $wp_query;
1516
1517
			$query = $wp_query;
1518
		}
1519
1520
		$aggregation_data = $this->aggregations;
1521
1522
		if ( empty( $aggregation_data ) ) {
1523
			return $aggregation_data;
1524
		}
1525
1526
		$aggregation_results = $this->get_search_aggregations_results();
1527
1528
		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...
1529
			return $aggregation_data;
1530
		}
1531
1532
		// NOTE - Looping over the _results_, not the original configured aggregations, so we get the 'real' data from ES.
1533
		foreach ( $aggregation_results as $label => $aggregation ) {
1534
			if ( empty( $aggregation ) ) {
1535
				continue;
1536
			}
1537
1538
			$type = $this->aggregations[ $label ]['type'];
1539
1540
			$aggregation_data[ $label ]['buckets'] = array();
1541
1542
			$existing_term_slugs = array();
1543
1544
			$tax_query_var = null;
1545
1546
			// Figure out which terms are active in the query, for this taxonomy.
1547
			if ( 'taxonomy' === $this->aggregations[ $label ]['type'] ) {
1548
				$tax_query_var = $this->get_taxonomy_query_var( $this->aggregations[ $label ]['taxonomy'] );
1549
1550
				if ( ! empty( $query->tax_query ) && ! empty( $query->tax_query->queries ) && is_array( $query->tax_query->queries ) ) {
1551
					foreach ( $query->tax_query->queries as $tax_query ) {
1552
						if ( is_array( $tax_query ) && $this->aggregations[ $label ]['taxonomy'] === $tax_query['taxonomy'] &&
1553
							'slug' === $tax_query['field'] &&
1554
							is_array( $tax_query['terms'] ) ) {
1555
							$existing_term_slugs = array_merge( $existing_term_slugs, $tax_query['terms'] );
1556
						}
1557
					}
1558
				}
1559
			}
1560
1561
			// Now take the resulting found aggregation items and generate the additional info about them, such as activation/deactivation url, name, count, etc.
1562
			$buckets = array();
1563
1564
			if ( ! empty( $aggregation['buckets'] ) ) {
1565
				$buckets = (array) $aggregation['buckets'];
1566
			}
1567
1568
			if ( 'date_histogram' === $type ) {
1569
				// re-order newest to oldest.
1570
				$buckets = array_reverse( $buckets );
1571
			}
1572
1573
			// Some aggregation types like date_histogram don't support the max results parameter.
1574
			if ( is_int( $this->aggregations[ $label ]['count'] ) && count( $buckets ) > $this->aggregations[ $label ]['count'] ) {
1575
				$buckets = array_slice( $buckets, 0, $this->aggregations[ $label ]['count'] );
1576
			}
1577
1578
			foreach ( $buckets as $item ) {
1579
				$query_vars = array();
1580
				$active     = false;
1581
				$remove_url = null;
1582
				$name       = '';
1583
1584
				// What type was the original aggregation?
1585
				switch ( $type ) {
1586
					case 'taxonomy':
1587
						$taxonomy = $this->aggregations[ $label ]['taxonomy'];
1588
1589
						$term = get_term_by( 'slug', $item['key'], $taxonomy );
1590
1591
						if ( ! $term || ! $tax_query_var ) {
1592
							continue 2; // switch() is considered a looping structure.
1593
						}
1594
1595
						$query_vars = array(
1596
							$tax_query_var => implode( '+', array_merge( $existing_term_slugs, array( $term->slug ) ) ),
1597
						);
1598
1599
						$name = $term->name;
1600
1601
						// Let's determine if this term is active or not.
1602
1603 View Code Duplication
						if ( in_array( $item['key'], $existing_term_slugs, true ) ) {
1604
							$active = true;
1605
1606
							$slug_count = count( $existing_term_slugs );
1607
1608
							if ( $slug_count > 1 ) {
1609
								$remove_url = Jetpack_Search_Helpers::add_query_arg(
1610
									$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...
1611
									rawurlencode( implode( '+', array_diff( $existing_term_slugs, array( $item['key'] ) ) ) )
1612
								);
1613
							} else {
1614
								$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...
1615
							}
1616
						}
1617
1618
						break;
1619
1620
					case 'post_type':
1621
						$post_type = get_post_type_object( $item['key'] );
1622
1623
						if ( ! $post_type || $post_type->exclude_from_search ) {
1624
							continue 2;  // switch() is considered a looping structure.
1625
						}
1626
1627
						$query_vars = array(
1628
							'post_type' => $item['key'],
1629
						);
1630
1631
						$name = $post_type->labels->singular_name;
1632
1633
						// Is this post type active on this search?
1634
						$post_types = $query->get( 'post_type' );
1635
1636
						if ( ! is_array( $post_types ) ) {
1637
							$post_types = array( $post_types );
1638
						}
1639
1640 View Code Duplication
						if ( in_array( $item['key'], $post_types, true ) ) {
1641
							$active = true;
1642
1643
							$post_type_count = count( $post_types );
1644
1645
							// 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.
1646
							if ( $post_type_count > 1 ) {
1647
								$remove_url = Jetpack_Search_Helpers::add_query_arg(
1648
									'post_type',
1649
									rawurlencode( implode( ',', array_diff( $post_types, array( $item['key'] ) ) ) )
1650
								);
1651
							} else {
1652
								$remove_url = Jetpack_Search_Helpers::remove_query_arg( 'post_type' );
1653
							}
1654
						}
1655
1656
						break;
1657
1658
					case 'date_histogram':
1659
						$timestamp = $item['key'] / 1000;
1660
1661
						$current_year  = $query->get( 'year' );
1662
						$current_month = $query->get( 'monthnum' );
1663
						$current_day   = $query->get( 'day' );
1664
1665
						switch ( $this->aggregations[ $label ]['interval'] ) {
1666
							case 'year':
1667
								$year = (int) gmdate( 'Y', $timestamp );
1668
1669
								$query_vars = array(
1670
									'year'     => $year,
1671
									'monthnum' => false,
1672
									'day'      => false,
1673
								);
1674
1675
								$name = $year;
1676
1677
								// Is this year currently selected?
1678
								if ( ! empty( $current_year ) && (int) $current_year === $year ) {
1679
									$active = true;
1680
1681
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum', 'day' ) );
1682
								}
1683
1684
								break;
1685
1686
							case 'month':
1687
								$year  = (int) gmdate( 'Y', $timestamp );
1688
								$month = (int) gmdate( 'n', $timestamp );
1689
1690
								$query_vars = array(
1691
									'year'     => $year,
1692
									'monthnum' => $month,
1693
									'day'      => false,
1694
								);
1695
1696
								$name = gmdate( 'F Y', $timestamp );
1697
1698
								// Is this month currently selected?
1699
								if ( ! empty( $current_year ) && (int) $current_year === $year &&
1700
									! empty( $current_month ) && (int) $current_month === $month ) {
1701
									$active = true;
1702
1703
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'year', 'monthnum' ) );
1704
								}
1705
1706
								break;
1707
1708
							case 'day':
1709
								$year  = (int) gmdate( 'Y', $timestamp );
1710
								$month = (int) gmdate( 'n', $timestamp );
1711
								$day   = (int) gmdate( 'j', $timestamp );
1712
1713
								$query_vars = array(
1714
									'year'     => $year,
1715
									'monthnum' => $month,
1716
									'day'      => $day,
1717
								);
1718
1719
								$name = gmdate( 'F jS, Y', $timestamp );
1720
1721
								// Is this day currently selected?
1722
								if ( ! empty( $current_year ) && (int) $current_year === $year &&
1723
									! empty( $current_month ) && (int) $current_month === $month &&
1724
									! empty( $current_day ) && (int) $current_day === $day ) {
1725
									$active = true;
1726
1727
									$remove_url = Jetpack_Search_Helpers::remove_query_arg( array( 'day' ) );
1728
								}
1729
1730
								break;
1731
1732
							default:
1733
								continue 3; // switch() is considered a looping structure.
1734
						} // End switch.
1735
1736
						break;
1737
1738
					default:
1739
						// continue 2; // switch() is considered a looping structure.
1740
				} // End switch.
1741
1742
				// Need to urlencode param values since add_query_arg doesn't.
1743
				$url_params = urlencode_deep( $query_vars );
1744
1745
				$aggregation_data[ $label ]['buckets'][] = array(
1746
					'url'        => Jetpack_Search_Helpers::add_query_arg( $url_params ),
1747
					'query_vars' => $query_vars,
1748
					'name'       => $name,
1749
					'count'      => $item['doc_count'],
1750
					'active'     => $active,
1751
					'remove_url' => $remove_url,
1752
					'type'       => $type,
1753
					'type_label' => $aggregation_data[ $label ]['name'],
1754
					'widget_id'  => ! empty( $aggregation_data[ $label ]['widget_id'] ) ? $aggregation_data[ $label ]['widget_id'] : 0,
1755
				);
1756
			} // End foreach.
1757
		} // End foreach.
1758
1759
		/**
1760
		 * Modify the aggregation filters returned by get_filters().
1761
		 *
1762
		 * Useful if you are setting custom filters outside of the supported filters (taxonomy, post_type etc.) and
1763
		 * want to hook them up so they're returned when you call `get_filters()`.
1764
		 *
1765
		 * @module search
1766
		 *
1767
		 * @since  6.9.0
1768
		 *
1769
		 * @param array    $aggregation_data The array of filters keyed on label.
1770
		 * @param WP_Query $query            The WP_Query object.
1771
		 */
1772
		return apply_filters( 'jetpack_search_get_filters', $aggregation_data, $query );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $query.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1773
	}
1774
1775
	/**
1776
	 * Get the results of the facets performed.
1777
	 *
1778
	 * @deprecated 5.0 Please use Jetpack_Search::get_filters() instead.
1779
	 *
1780
	 * @see        Jetpack_Search::get_filters()
1781
	 *
1782
	 * @return array $facets Array of facets applied and info about them.
1783
	 */
1784
	public function get_search_facet_data() {
1785
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_filters()' );
1786
1787
		return $this->get_filters();
1788
	}
1789
1790
	/**
1791
	 * Get the filters that are currently applied to this search.
1792
	 *
1793
	 * @since 5.0.0
1794
	 *
1795
	 * @return array Array of filters that were applied.
1796
	 */
1797
	public function get_active_filter_buckets() {
1798
		$active_buckets = array();
1799
1800
		$filters = $this->get_filters();
1801
1802
		if ( ! is_array( $filters ) ) {
1803
			return $active_buckets;
1804
		}
1805
1806
		foreach ( $filters as $filter ) {
1807
			if ( isset( $filter['buckets'] ) && is_array( $filter['buckets'] ) ) {
1808
				foreach ( $filter['buckets'] as $item ) {
1809
					if ( isset( $item['active'] ) && $item['active'] ) {
1810
						$active_buckets[] = $item;
1811
					}
1812
				}
1813
			}
1814
		}
1815
1816
		return $active_buckets;
1817
	}
1818
1819
	/**
1820
	 * Get the filters that are currently applied to this search.
1821
	 *
1822
	 * @deprecated 5.0 Please use Jetpack_Search::get_active_filter_buckets() instead.
1823
	 *
1824
	 * @see        Jetpack_Search::get_active_filter_buckets()
1825
	 *
1826
	 * @return array Array of filters that were applied.
1827
	 */
1828
	public function get_current_filters() {
1829
		_deprecated_function( __METHOD__, 'jetpack-5.0', 'Jetpack_Search::get_active_filter_buckets()' );
1830
1831
		return $this->get_active_filter_buckets();
1832
	}
1833
1834
	/**
1835
	 * Calculate the right query var to use for a given taxonomy.
1836
	 *
1837
	 * Allows custom code to modify the GET var that is used to represent a given taxonomy, via the jetpack_search_taxonomy_query_var filter.
1838
	 *
1839
	 * @since 5.0.0
1840
	 *
1841
	 * @param string $taxonomy_name The name of the taxonomy for which to get the query var.
1842
	 *
1843
	 * @return bool|string The query var to use for this taxonomy, or false if none found.
1844
	 */
1845
	public function get_taxonomy_query_var( $taxonomy_name ) {
1846
		$taxonomy = get_taxonomy( $taxonomy_name );
1847
1848
		if ( ! $taxonomy || is_wp_error( $taxonomy ) ) {
1849
			return false;
1850
		}
1851
1852
		/**
1853
		 * Modify the query var to use for a given taxonomy
1854
		 *
1855
		 * @module search
1856
		 *
1857
		 * @since  5.0.0
1858
		 *
1859
		 * @param string $query_var     The current query_var for the taxonomy
1860
		 * @param string $taxonomy_name The taxonomy name
1861
		 */
1862
		return apply_filters( 'jetpack_search_taxonomy_query_var', $taxonomy->query_var, $taxonomy_name );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $taxonomy_name.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1863
	}
1864
1865
	/**
1866
	 * Takes an array of aggregation results, and ensures the array key ordering matches the key order in $desired
1867
	 * which is the input order.
1868
	 *
1869
	 * Necessary because ES does not always return aggregations in the same order that you pass them in,
1870
	 * and it should be possible to control the display order easily.
1871
	 *
1872
	 * @since 5.0.0
1873
	 *
1874
	 * @param array $aggregations Aggregation results to be reordered.
1875
	 * @param array $desired      Array with keys representing the desired ordering.
1876
	 *
1877
	 * @return array A new array with reordered keys, matching those in $desired.
1878
	 */
1879
	public function fix_aggregation_ordering( array $aggregations, array $desired ) {
1880
		if ( empty( $aggregations ) || empty( $desired ) ) {
1881
			return $aggregations;
1882
		}
1883
1884
		$reordered = array();
1885
1886
		foreach ( array_keys( $desired ) as $agg_name ) {
1887
			if ( isset( $aggregations[ $agg_name ] ) ) {
1888
				$reordered[ $agg_name ] = $aggregations[ $agg_name ];
1889
			}
1890
		}
1891
1892
		return $reordered;
1893
	}
1894
1895
	/**
1896
	 * Sends events to Tracks when a search filters widget is updated.
1897
	 *
1898
	 * @since 5.8.0
1899
	 *
1900
	 * @param string $option    The option name. Only "widget_jetpack-search-filters" is cared about.
1901
	 * @param array  $old_value The old option value.
1902
	 * @param array  $new_value The new option value.
1903
	 */
1904
	public function track_widget_updates( $option, $old_value, $new_value ) {
1905
		if ( 'widget_jetpack-search-filters' !== $option ) {
1906
			return;
1907
		}
1908
1909
		$event = Jetpack_Search_Helpers::get_widget_tracks_value( $old_value, $new_value );
1910
		if ( ! $event ) {
1911
			return;
1912
		}
1913
1914
		$tracking = new Automattic\Jetpack\Tracking();
1915
		$tracking->tracks_record_event(
1916
			wp_get_current_user(),
1917
			sprintf( 'jetpack_search_widget_%s', $event['action'] ),
1918
			$event['widget']
1919
		);
1920
	}
1921
1922
	/**
1923
	 * Moves any active search widgets to the inactive category.
1924
	 *
1925
	 * @since 5.9.0
1926
	 */
1927
	public function move_search_widgets_to_inactive() {
1928
		if ( ! is_active_widget( false, false, Jetpack_Search_Helpers::FILTER_WIDGET_BASE, true ) ) {
1929
			return;
1930
		}
1931
1932
		$sidebars_widgets = wp_get_sidebars_widgets();
1933
1934
		if ( ! is_array( $sidebars_widgets ) ) {
1935
			return;
1936
		}
1937
1938
		$changed = false;
1939
1940
		foreach ( $sidebars_widgets as $sidebar => $widgets ) {
1941
			if ( 'wp_inactive_widgets' === $sidebar || 'orphaned_widgets' === substr( $sidebar, 0, 16 ) ) {
1942
				continue;
1943
			}
1944
1945
			if ( is_array( $widgets ) ) {
1946
				foreach ( $widgets as $key => $widget ) {
1947
					if ( _get_widget_id_base( $widget ) === Jetpack_Search_Helpers::FILTER_WIDGET_BASE ) {
1948
						$changed = true;
1949
1950
						array_unshift( $sidebars_widgets['wp_inactive_widgets'], $widget );
1951
						unset( $sidebars_widgets[ $sidebar ][ $key ] );
1952
					}
1953
				}
1954
			}
1955
		}
1956
1957
		if ( $changed ) {
1958
			wp_set_sidebars_widgets( $sidebars_widgets );
1959
		}
1960
	}
1961
1962
	/**
1963
	 * Determine whether a given WP_Query should be handled by ElasticSearch.
1964
	 *
1965
	 * @param WP_Query $query The WP_Query object.
1966
	 *
1967
	 * @return bool
1968
	 */
1969
	public function should_handle_query( $query ) {
1970
		/**
1971
		 * Determine whether a given WP_Query should be handled by ElasticSearch.
1972
		 *
1973
		 * @module search
1974
		 *
1975
		 * @since  5.6.0
1976
		 *
1977
		 * @param bool     $should_handle Should be handled by Jetpack Search.
1978
		 * @param WP_Query $query         The WP_Query object.
1979
		 */
1980
		return apply_filters( 'jetpack_search_should_handle_query', $query->is_main_query() && $query->is_search(), $query );
0 ignored issues
show
Unused Code introduced by
The call to apply_filters() has too many arguments starting with $query.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1981
	}
1982
1983
	/**
1984
	 * Transforms an array with fields name as keys and boosts as value into
1985
	 * shorthand "caret" format.
1986
	 *
1987
	 * @param array $fields_boost [ "title" => "2", "content" => "1" ].
1988
	 *
1989
	 * @return array [ "title^2", "content^1" ]
1990
	 */
1991
	private function _get_caret_boosted_fields( array $fields_boost ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
1992
		$caret_boosted_fields = array();
1993
		foreach ( $fields_boost as $field => $boost ) {
1994
			$caret_boosted_fields[] = "$field^$boost";
1995
		}
1996
		return $caret_boosted_fields;
1997
	}
1998
1999
	/**
2000
	 * Apply a multiplier to boost values.
2001
	 *
2002
	 * @param array $fields_boost [ "title" => 2, "content" => 1 ].
2003
	 * @param array $fields_boost_multiplier [ "title" => 0.1234 ].
2004
	 *
2005
	 * @return array [ "title" => "0.247", "content" => "1.000" ]
2006
	 */
2007
	private function _apply_boosts_multiplier( array $fields_boost, array $fields_boost_multiplier ) { // phpcs:ignore PSR2.Methods.MethodDeclaration.Underscore
2008
		foreach ( $fields_boost as $field_name => $field_boost ) {
2009
			if ( isset( $fields_boost_multiplier[ $field_name ] ) ) {
2010
				$fields_boost[ $field_name ] *= $fields_boost_multiplier[ $field_name ];
2011
			}
2012
2013
			// Set a floor and format the number as string.
2014
			$fields_boost[ $field_name ] = number_format(
2015
				max( 0.001, $fields_boost[ $field_name ] ),
2016
				3,
2017
				'.',
2018
				''
2019
			);
2020
		}
2021
2022
		return $fields_boost;
2023
	}
2024
}
2025