Completed
Push — fix/security-scan-update ( fe68cd...01e67d )
by
unknown
10:34 queued 03:43
created

Jetpack_Instant_Search::get_asset_version()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 5

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
nc 4
nop 1
dl 0
loc 5
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Jetpack Search: Instant Front-End Search and Filtering
4
 *
5
 * @since 8.3.0
6
 * @package jetpack
7
 */
8
9
use Automattic\Jetpack\Connection\Client;
10
use Automattic\Jetpack\Constants;
11
12
/**
13
 * Class to load Instant Search experience on the site.
14
 *
15
 * @since 8.3.0
16
 */
17
class Jetpack_Instant_Search extends Jetpack_Search {
18
19
	/**
20
	 * Loads the php for this version of search
21
	 *
22
	 * @since 8.3.0
23
	 */
24
	public function load_php() {
25
		require_once dirname( __FILE__ ) . '/class.jetpack-search-template-tags.php';
26
		require_once JETPACK__PLUGIN_DIR . 'modules/widgets/search.php';
27
28
		if ( class_exists( 'WP_Customize_Manager' ) ) {
29
			require_once dirname( __FILE__ ) . '/class-jetpack-search-customize.php';
30
			new Jetpack_Search_Customize();
31
		}
32
	}
33
34
	/**
35
	 * Setup the various hooks needed for the plugin to take over search duties.
36
	 *
37
	 * @since 5.0.0
38
	 */
39 View Code Duplication
	public function init_hooks() {
40
		if ( ! is_admin() ) {
41
			add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
42
			add_action( 'parse_query', array( $this, 'action__parse_query' ), 10, 1 );
43
44
			add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
45
46
			add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) );
47
			add_action( 'wp_footer', array( $this, 'print_instant_search_sidebar' ) );
48
		} else {
49
			add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
50
		}
51
52
		add_action( 'widgets_init', array( $this, 'register_jetpack_instant_sidebar' ) );
53
		add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
54
	}
55
56
	/**
57
	 * Loads assets for Jetpack Instant Search Prototype featuring Search As You Type experience.
58
	 */
59
	public function load_assets() {
60
		$script_relative_path = '_inc/build/instant-search/jp-search.bundle.js';
61
		$style_relative_path  = '_inc/build/instant-search/instant-search.min.css';
62
		if ( ! file_exists( JETPACK__PLUGIN_DIR . $script_relative_path ) || ! file_exists( JETPACK__PLUGIN_DIR . $style_relative_path ) ) {
63
			return;
64
		}
65
66
		$script_version = self::get_asset_version( $script_relative_path );
67
		$script_path    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
68
		wp_enqueue_script( 'jetpack-instant-search', $script_path, array(), $script_version, true );
69
		$this->load_and_initialize_tracks();
70
		$this->inject_javascript_options();
71
72
		$style_version = self::get_asset_version( $style_relative_path );
73
		$style_path    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
74
		wp_enqueue_style( 'jetpack-instant-search', $style_path, array(), $style_version );
75
	}
76
77
	/**
78
	 * Passes all options to the JS app.
79
	 */
80
	protected function inject_javascript_options() {
81
		$widget_options = Jetpack_Search_Helpers::get_widgets_from_option();
82
		if ( is_array( $widget_options ) ) {
83
			$widget_options = end( $widget_options );
0 ignored issues
show
Unused Code introduced by
$widget_options 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...
84
		}
85
86
		$overlay_widget_ids      = array_key_exists( 'jetpack-instant-search-sidebar', get_option( 'sidebars_widgets', array() ) ) ?
87
			get_option( 'sidebars_widgets', array() )['jetpack-instant-search-sidebar'] : array();
88
		$filters                 = Jetpack_Search_Helpers::get_filters_from_widgets();
89
		$widgets                 = array();
90
		$widgets_outside_overlay = array();
91
		foreach ( $filters as $key => &$filter ) {
92
			$filter['filter_id'] = $key;
93
94
			if ( in_array( $filter['widget_id'], $overlay_widget_ids, true ) ) {
95 View Code Duplication
				if ( ! isset( $widgets[ $filter['widget_id'] ] ) ) {
96
					$widgets[ $filter['widget_id'] ]['filters']   = array();
97
					$widgets[ $filter['widget_id'] ]['widget_id'] = $filter['widget_id'];
98
				}
99
				$widgets[ $filter['widget_id'] ]['filters'][] = $filter;
100
			} else {
101 View Code Duplication
				if ( ! isset( $widgets_outside_overlay[ $filter['widget_id'] ] ) ) {
102
					$widgets_outside_overlay[ $filter['widget_id'] ]['filters']   = array();
103
					$widgets_outside_overlay[ $filter['widget_id'] ]['widget_id'] = $filter['widget_id'];
104
				}
105
				$widgets_outside_overlay[ $filter['widget_id'] ]['filters'][] = $filter;
106
			}
107
		}
108
		unset( $filter );
109
110
		$post_type_objs   = get_post_types( array(), 'objects' );
111
		$post_type_labels = array();
112
		foreach ( $post_type_objs as $key => $obj ) {
113
			$post_type_labels[ $key ] = array(
114
				'singular_name' => $obj->labels->singular_name,
115
				'name'          => $obj->labels->name,
116
			);
117
		}
118
119
		$prefix  = Jetpack_Search_Options::OPTION_PREFIX;
120
		$options = array(
121
			'overlayOptions'        => array(
122
				'colorTheme'      => get_option( $prefix . 'color_theme', 'light' ),
123
				'enableInfScroll' => (bool) get_option( $prefix . 'inf_scroll', false ),
124
				'highlightColor'  => get_option( $prefix . 'highlight_color', '#FFC' ),
125
				'opacity'         => (int) get_option( $prefix . 'opacity', 97 ),
126
				'overlayTrigger'  => get_option( $prefix . 'overlay_trigger', 'immediate' ),
127
				'showPoweredBy'   => (bool) get_option( $prefix . 'show_powered_by', true ),
128
			),
129
130
			// core config.
131
			'homeUrl'               => home_url(),
132
			'locale'                => str_replace( '_', '-', Jetpack_Search_Helpers::is_valid_locale( get_locale() ) ? get_locale() : 'en_US' ),
133
			'postsPerPage'          => get_option( 'posts_per_page' ),
134
			'siteId'                => Jetpack::get_option( 'id' ),
135
136
			'postTypes'             => $post_type_labels,
137
			'widgets'               => array_values( $widgets ),
138
			'widgetsOutsideOverlay' => array_values( $widgets_outside_overlay ),
139
		);
140
141
		/**
142
		 * Customize Instant Search Options.
143
		 *
144
		 * @module search
145
		 *
146
		 * @since 7.7.0
147
		 *
148
		 * @param array $options Array of parameters used in Instant Search queries.
149
		 */
150
		$options = apply_filters( 'jetpack_instant_search_options', $options );
151
152
		// Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
153
		wp_add_inline_script( 'jetpack-instant-search', 'var JetpackInstantSearchOptions=JSON.parse(decodeURIComponent("' . rawurlencode( wp_json_encode( $options ) ) . '"));' );
154
	}
155
156
	/**
157
	 * Registers a widget sidebar for Instant Search.
158
	 */
159
	public function register_jetpack_instant_sidebar() {
160
		$args = array(
161
			'name'          => __( 'Jetpack Search Sidebar', 'jetpack' ),
162
			'id'            => 'jetpack-instant-search-sidebar',
163
			'description'   => __( 'Customize the sidebar inside the Jetpack Search overlay', 'jetpack' ),
164
			'class'         => '',
165
			'before_widget' => '<div id="%1$s" class="widget %2$s">',
166
			'after_widget'  => '</div>',
167
			'before_title'  => '<h2 class="widgettitle">',
168
			'after_title'   => '</h2>',
169
		);
170
		register_sidebar( $args );
171
	}
172
173
	/**
174
	 * Prints Instant Search sidebar.
175
	 */
176
	public function print_instant_search_sidebar() {
177
		?>
178
		<div class="jetpack-instant-search__widget-area" style="display: none">
179
			<?php if ( is_active_sidebar( 'jetpack-instant-search-sidebar' ) ) { ?>
180
				<?php dynamic_sidebar( 'jetpack-instant-search-sidebar' ); ?>
181
			<?php } ?>
182
		</div>
183
		<?php
184
	}
185
186
	/**
187
	 * Loads scripts for Tracks analytics library
188
	 */
189
	public function load_and_initialize_tracks() {
190
		wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
191
	}
192
193
	/**
194
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
195
	 *
196
	 * @param string $file Path of the file we are looking for.
197
	 * @return string $script_version Version number.
198
	 */
199
	public static function get_asset_version( $file ) {
200
		return Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $file )
201
			? filemtime( JETPACK__PLUGIN_DIR . $file )
202
			: JETPACK__VERSION;
203
	}
204
205
	/**
206
	 * Bypass the normal Search query since we will run it with instant search.
207
	 *
208
	 * @since 8.3.0
209
	 *
210
	 * @param array    $posts Current array of posts (still pre-query).
211
	 * @param WP_Query $query The WP_Query being filtered.
212
	 *
213
	 * @return array Array of matching posts.
214
	 */
215
	public function filter__posts_pre_query( $posts, $query ) {
216
		if ( ! $this->should_handle_query( $query ) ) {
217
			// Intentionally not adding the 'jetpack_search_abort' action since this should fire for every request except for search.
218
			return $posts;
219
		}
220
221
		/**
222
		 * Bypass the main query and return dummy data
223
		 *  WP Core doesn't call the set_found_posts and its filters when filtering
224
		 *  posts_pre_query like we do, so need to do these manually.
225
		 */
226
		$query->found_posts   = 1;
227
		$query->max_num_pages = 1;
228
229
		return array();
230
	}
231
232
	/**
233
	 * Run the aggregations API query for any filtering
234
	 *
235
	 * @since 8.3.0
236
	 *
237
	 * @param WP_Query $query The WP_Query being filtered.
238
	 */
239
	public function action__parse_query( $query ) {
240
		if ( ! empty( $this->search_result ) ) {
241
			return;
242
		}
243
244
		if ( is_admin() ) {
245
			return;
246
		}
247
248
		if ( empty( $this->aggregations ) ) {
249
			return;
250
		}
251
252
		jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-builder' );
253
254
		$builder = new Jetpack_WPES_Query_Builder();
255
		$this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
256
		$this->search_result = $this->instant_api(
0 ignored issues
show
Documentation Bug introduced by
It seems like $this->instant_api(array...ze' => 0, 'from' => 0)) 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...
257
			array(
258
				'aggregations' => $builder->build_aggregation(),
259
				'size'         => 0,
260
				'from'         => 0,
261
			)
262
		);
263
	}
264
265
	/**
266
	 * Run an instant search on the WordPress.com public API.
267
	 *
268
	 * @since 8.3.0
269
	 *
270
	 * @param array $args Args conforming to the WP.com v1.3/sites/<blog_id>/search endpoint.
271
	 *
272
	 * @return object|WP_Error The response from the public API, or a WP_Error.
273
	 */
274
	public function instant_api( array $args ) {
275
		global $wp_version;
276
		$start_time = microtime( true );
277
278
		// Cache locally to avoid remote request slowing the page.
279
		$transient_name = 'jetpack_instant_search_cache_' . md5( wp_json_encode( $args ) );
280
		$cache          = get_transient( $transient_name );
281
		if ( false !== $cache ) {
282
			return $cache;
283
		}
284
285
		$service_url = add_query_arg(
286
			$args,
287
			sprintf(
288
				'https://public-api.wordpress.com/rest/v1.3/sites/%d/search',
289
				$this->jetpack_blog_id
290
			)
291
		);
292
293
		$request_args = array(
294
			'timeout'    => 10,
295
			'user-agent' => "WordPress/{$wp_version} | Jetpack/" . constant( 'JETPACK__VERSION' ),
296
		);
297
298
		$request  = wp_remote_get( esc_url_raw( $service_url ), $request_args );
299
		$end_time = microtime( true );
300
301
		if ( is_wp_error( $request ) ) {
302
			return $request;
303
		}
304
305
		$response_code = wp_remote_retrieve_response_code( $request );
306
		$response      = json_decode( wp_remote_retrieve_body( $request ), true );
307
308 View Code Duplication
		if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
309
			/**
310
			 * Fires after a search query request has failed
311
			 *
312
			 * @module search
313
			 *
314
			 * @since  5.6.0
315
			 *
316
			 * @param array Array containing the response code and response from the failed search query
317
			 */
318
			do_action(
319
				'failed_jetpack_search_query',
320
				array(
321
					'response_code' => $response_code,
322
					'json'          => $response,
323
				)
324
			);
325
326
			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...
327
		}
328
329
		$took = is_array( $response ) && ! empty( $response['took'] )
330
			? $response['took']
331
			: null;
332
333
		$query = array(
334
			'args'          => $args,
335
			'response'      => $response,
336
			'response_code' => $response_code,
337
			'elapsed_time'  => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
338
			'es_time'       => $took,
339
			'url'           => $service_url,
340
		);
341
342
		/**
343
		 * Fires after a search request has been performed.
344
		 *
345
		 * Includes the following info in the $query parameter:
346
		 *
347
		 * array args Array of Elasticsearch arguments for the search
348
		 * array response Raw API response, JSON decoded
349
		 * int response_code HTTP response code of the request
350
		 * float elapsed_time Roundtrip time of the search request, in milliseconds
351
		 * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
352
		 * string url API url that was queried
353
		 *
354
		 * @module search
355
		 *
356
		 * @since  5.0.0
357
		 * @since  5.8.0 This action now fires on all queries instead of just successful queries.
358
		 *
359
		 * @param array $query Array of information about the query performed
360
		 */
361
		do_action( 'did_jetpack_search_query', $query );
362
363
		// Update local cache.
364
		set_transient( $transient_name, $response, 1 * HOUR_IN_SECONDS );
365
366
		return $response;
367
	}
368
369
	/**
370
	 * Get the raw Aggregation results from the Elasticsearch response.
371
	 *
372
	 * @since  8.4.0
373
	 *
374
	 * @return array Array of Aggregations performed on the search.
375
	 */
376
	public function get_search_aggregations_results() {
377
		if ( empty( $this->search_result ) || is_wp_error( $this->search_result ) || ! isset( $this->search_result['aggregations'] ) ) {
378
			return array();
379
		}
380
381
		return $this->search_result['aggregations'];
382
	}
383
384
	/**
385
	 * Autoconfig search by adding filter widgets
386
	 *
387
	 * @since  8.3.0
388
	 */
389
	public function auto_config_search() {
390
		if ( ! current_user_can( 'edit_theme_options' ) ) {
391
			return;
392
		}
393
394
		global $wp_registered_sidebars;
395
		$sidebars = get_option( 'sidebars_widgets', array() );
396
		$slug     = Jetpack_Search_Helpers::FILTER_WIDGET_BASE;
397
398
		if ( isset( $sidebars['jetpack-instant-search-sidebar'] ) ) {
399
			foreach ( (array) $sidebars['jetpack-instant-search-sidebar'] as $widget_id ) {
400
				if ( 0 === strpos( $widget_id, $slug ) ) {
401
					// Already configured.
402
					return;
403
				}
404
			}
405
		}
406
407
		$has_sidebar           = isset( $wp_registered_sidebars['sidebar-1'] );
408
		$sidebar_id            = false;
409
		$sidebar_searchbox_idx = false;
410
		if ( $has_sidebar ) {
411
			if ( empty( $sidebars['sidebar-1'] ) ) {
412
				// Adding to an empty sidebar is generally a bad idea.
413
				$has_sidebar = false;
414
			}
415
			foreach ( (array) $sidebars['sidebar-1'] as $idx => $widget_id ) {
416
				if ( 0 === strpos( $widget_id, 'search-' ) ) {
417
					$sidebar_searchbox_idx = $idx;
418
				}
419
				if ( 0 === strpos( $widget_id, $slug ) ) {
420
					$sidebar_id = (int) str_replace( Jetpack_Search_Helpers::FILTER_WIDGET_BASE . '-', '', $widget_id );
421
					break;
422
				}
423
			}
424
		}
425
426
		$next_id         = 1;
427
		$widget_opt_name = Jetpack_Search_Helpers::get_widget_option_name();
428
		$widget_options  = get_option( $widget_opt_name, array() );
429
		foreach ( $widget_options as $id => $w ) {
430
			if ( $id >= $next_id ) {
431
				$next_id = $id + 1;
432
			}
433
		}
434
435
		// Copy sidebar settings to overlay.
436
		if ( ( false !== $sidebar_id ) && isset( $widget_options[ $sidebar_id ] ) ) {
437
			$widget_options[ $next_id ] = $widget_options[ $sidebar_id ];
438
			update_option( $widget_opt_name, $widget_options );
439
440
			if ( ! isset( $sidebars['jetpack-instant-search-sidebar'] ) ) {
441
				$sidebars['jetpack-instant-search-sidebar'] = array();
442
			}
443
			array_unshift( $sidebars['jetpack-instant-search-sidebar'], Jetpack_Search_Helpers::build_widget_id( $next_id ) );
444
			update_option( 'sidebars_widgets', $sidebars );
445
446
			return;
447
		}
448
449
		// Configure overlay and sidebar (if it exists).
450
		$preconfig_opts = $this->get_preconfig_widget_options();
451
		if ( ! isset( $sidebars['jetpack-instant-search-sidebar'] ) ) {
452
			$sidebars['jetpack-instant-search-sidebar'] = array();
453
		}
454
		if ( $has_sidebar ) {
455
			$widget_options[ $next_id ] = $preconfig_opts;
456
			if ( false !== $sidebar_searchbox_idx ) {
457
				// Replace Core search box.
458
				$sidebars['sidebar-1'][ $sidebar_searchbox_idx ] = Jetpack_Search_Helpers::build_widget_id( $next_id );
459
			} else {
460
				// Add to top.
461
				array_unshift( $sidebars['sidebar-1'], Jetpack_Search_Helpers::build_widget_id( $next_id ) );
462
			}
463
			$next_id++;
464
		}
465
		$widget_options[ $next_id ] = $preconfig_opts;
466
		array_unshift( $sidebars['jetpack-instant-search-sidebar'], Jetpack_Search_Helpers::build_widget_id( $next_id ) );
467
468
		update_option( $widget_opt_name, $widget_options );
469
		update_option( 'sidebars_widgets', $sidebars );
470
	}
471
472
	/**
473
	 * Autoconfig search by adding filter widgets
474
	 *
475
	 * @since  8.4.0
476
	 *
477
	 * @return array Array of config settings for search widget.
478
	 */
479
	protected function get_preconfig_widget_options() {
480
		$settings = array(
481
			'title'              => '',
482
			'search_box_enabled' => 1,
483
			'user_sort_enabled'  => 0,
484
			'filters'            => array(),
485
		);
486
487
		$post_types = get_post_types(
488
			array(
489
				'public'   => true,
490
				'_builtin' => false,
491
			)
492
		);
493
494
		if ( ! empty( $post_types ) ) {
495
			$settings['filters'][] = array(
496
				array(
497
					'name'  => '',
498
					'type'  => 'post_type',
499
					'count' => 5,
500
				),
501
			);
502
		}
503
504
		$taxonomies = get_taxonomies(
505
			array(
506
				'public'   => true,
507
				'_builtin' => false,
508
			)
509
		);
510
511
		foreach ( $taxonomies as $t ) {
512
			$settings['filters'][] = array(
513
				'name'     => '',
514
				'type'     => 'taxonomy',
515
				'taxonomy' => $t,
516
				'count'    => 5,
517
			);
518
		}
519
520
		$settings['filters'][] = array(
521
			'name'     => '',
522
			'type'     => 'taxonomy',
523
			'taxonomy' => 'category',
524
			'count'    => 5,
525
		);
526
		$settings['filters'][] = array(
527
			'name'     => '',
528
			'type'     => 'taxonomy',
529
			'taxonomy' => 'post_tag',
530
			'count'    => 5,
531
		);
532
		$settings['filters'][] = array(
533
			'name'     => '',
534
			'type'     => 'date_histogram',
535
			'count'    => 5,
536
			'field'    => 'post_date',
537
			'interval' => 'year',
538
		);
539
540
		return $settings;
541
	}
542
543
}
544