Completed
Push — update/refactor-search-php ( dbec44...f46b79 )
by
unknown
07:49
created

load_and_initialize_tracks()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 3
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
class Jetpack_Instant_Search extends Jetpack_Search {
13
14
	/**
15
	 * Loads the php for this version of search
16
	 *
17
	 * @since 8.3.0
18
	 */
19
	public function load_php() {
20
		require_once dirname( __FILE__ ) . '/class.jetpack-search-template-tags.php';
21
		require_once JETPACK__PLUGIN_DIR . 'modules/widgets/search.php';
22
23
		if ( class_exists( 'WP_Customize_Manager' ) ) {
24
			require_once dirname( __FILE__ ) . '/class-jetpack-search-customize.php';
25
			new Jetpack_Search_Customize();
26
		}
27
	}
28
29
	/**
30
	 * Setup the various hooks needed for the plugin to take over search duties.
31
	 *
32
	 * @since 5.0.0
33
	 */
34
	public function init_hooks() {
35
		if ( ! is_admin() ) {
36
			add_filter( 'posts_pre_query', array( $this, 'filter__posts_pre_query' ), 10, 2 );
37
			add_action( 'parse_query', array( $this, 'action__parse_query' ), 10, 1 );
38
39
			add_action( 'init', array( $this, 'set_filters_from_widgets' ) );
40
41
			add_action( 'wp_enqueue_scripts', array( $this, 'load_assets' ) );
42
		} else {
43
			add_action( 'update_option', array( $this, 'track_widget_updates' ), 10, 3 );
44
		}
45
46
		add_action( 'jetpack_deactivate_module_search', array( $this, 'move_search_widgets_to_inactive' ) );
47
	}
48
49
	/**
50
	 * Loads assets for Jetpack Instant Search Prototype featuring Search As You Type experience.
51
	 */
52
	public function load_assets() {
53
		$script_relative_path = '_inc/build/instant-search/jp-search.bundle.js';
54
		$style_relative_path  = '_inc/build/instant-search/instant-search.min.css';
55
		if ( ! file_exists( JETPACK__PLUGIN_DIR . $script_relative_path ) || ! file_exists( JETPACK__PLUGIN_DIR . $style_relative_path ) ) {
56
			return;
57
		}
58
59
		$script_version = self::get_asset_version( $script_relative_path );
60
		$script_path    = plugins_url( $script_relative_path, JETPACK__PLUGIN_FILE );
61
		wp_enqueue_script( 'jetpack-instant-search', $script_path, array(), $script_version, true );
62
		$this->load_and_initialize_tracks();
63
		$this->inject_javascript_options();
64
65
		$style_version = self::get_asset_version( $style_relative_path );
66
		$style_path    = plugins_url( $style_relative_path, JETPACK__PLUGIN_FILE );
67
		wp_enqueue_style( 'jetpack-instant-search', $style_path, array(), $style_version );
68
	}
69
70
	/**
71
	 * Passes all options to the JS app.
72
	 */
73
	protected function inject_javascript_options() {
74
		$widget_options = Jetpack_Search_Helpers::get_widgets_from_option();
75
		if ( is_array( $widget_options ) ) {
76
			$widget_options = end( $widget_options );
77
		}
78
79
		$filters = Jetpack_Search_Helpers::get_filters_from_widgets();
80
		$widgets = array();
81
		foreach ( $filters as $key => $filter ) {
82
			if ( ! isset( $widgets[ $filter['widget_id'] ] ) ) {
83
				$widgets[ $filter['widget_id'] ]['filters']   = array();
84
				$widgets[ $filter['widget_id'] ]['widget_id'] = $filter['widget_id'];
85
			}
86
			$new_filter                                   = $filter;
87
			$new_filter['filter_id']                      = $key;
88
			$widgets[ $filter['widget_id'] ]['filters'][] = $new_filter;
89
		}
90
91
		$post_type_objs   = get_post_types( array(), 'objects' );
92
		$post_type_labels = array();
93
		foreach ( $post_type_objs as $key => $obj ) {
94
			$post_type_labels[ $key ] = array(
95
				'singular_name' => $obj->labels->singular_name,
96
				'name'          => $obj->labels->name,
97
			);
98
		}
99
100
		$prefix  = Jetpack_Search_Options::OPTION_PREFIX;
101
		$options = array(
102
			// overlay options.
103
			'closeColor'      => (bool) get_option( $prefix . 'close_color', '#BD3854' ),
104
			'colorTheme'      => (bool) get_option( $prefix . 'color_theme', 'light' ),
105
			'enableInfScroll' => (bool) get_option( $prefix . 'inf_scroll', true ),
106
			'highlightColor'  => (bool) get_option( $prefix . 'highlight_color', '#FFC' ),
107
			'opacity'         => (bool) get_option( $prefix . 'opacity', 97 ),
108
			'showLogo'        => (bool) get_option( $prefix . 'show_logo', true ),
109
			'showPoweredBy'   => (bool) get_option( $prefix . 'show_powered_by', true ),
110
111
			// core config.
112
			'homeUrl'         => home_url(),
113
			'locale'          => str_replace( '_', '-', get_locale() ),
114
			'postsPerPage'    => get_option( 'posts_per_page' ),
115
			'siteId'          => Jetpack::get_option( 'id' ),
116
117
			// filtering.
118
			'postTypeFilters' => $widget_options['post_types'],
119
			'postTypes'       => $post_type_labels,
120
			'sort'            => $widget_options['sort'],
121
			'widgets'         => array_values( $widgets ),
122
		);
123
124
		/**
125
		 * Customize Instant Search Options.
126
		 *
127
		 * @module search
128
		 *
129
		 * @since 7.7.0
130
		 *
131
		 * @param array $options Array of parameters used in Instant Search queries.
132
		 */
133
		$options = apply_filters( 'jetpack_instant_search_options', $options );
134
135
		wp_localize_script(
136
			'jetpack-instant-search',
137
			'JetpackInstantSearchOptions',
138
			$options
139
		);
140
	}
141
142
	/**
143
	 * Loads scripts for Tracks analytics library
144
	 */
145
	public function load_and_initialize_tracks() {
146
		wp_enqueue_script( 'jp-tracks', '//stats.wp.com/w.js', array(), gmdate( 'YW' ), true );
147
	}
148
149
	/**
150
	 * Get the version number to use when loading the file. Allows us to bypass cache when developing.
151
	 *
152
	 * @param string $file Path of the file we are looking for.
153
	 * @return string $script_version Version number.
154
	 */
155
	public static function get_asset_version( $file ) {
156
		return Jetpack::is_development_version() && file_exists( JETPACK__PLUGIN_DIR . $file )
157
			? filemtime( JETPACK__PLUGIN_DIR . $file )
158
			: JETPACK__VERSION;
159
	}
160
161
	/**
162
	 * Bypass the normal Search query since we will run it with instant search.
163
	 *
164
	 * @since 8.3.0
165
	 *
166
	 * @param array    $posts Current array of posts (still pre-query).
167
	 * @param WP_Query $query The WP_Query being filtered.
168
	 *
169
	 * @return array Array of matching posts.
170
	 */
171
	public function filter__posts_pre_query( $posts, $query ) {
172
		if ( ! $this->should_handle_query( $query ) ) {
173
			// Intentionally not adding the 'jetpack_search_abort' action since this should fire for every request except for search.
174
			return $posts;
175
		}
176
177
		/**
178
		 * Bypass the main query and return dummy data
179
		 *  WP Core doesn't call the set_found_posts and its filters when filtering
180
		 *  posts_pre_query like we do, so need to do these manually.
181
		 */
182
		$query->found_posts   = 1;
183
		$query->max_num_pages = 1;
184
185
		return array(
186
			new WP_Post(
187
				array(
188
					'ID'             => 1,
189
					'post_author'    => 1,
190
					'post_date'      => current_time( 'mysql' ),
191
					'post_date_gmt'  => current_time( 'mysql', 1 ),
192
					'post_title'     => 'Some title or other',
193
					'post_content'   => 'Whatever you want here. Maybe some cat pictures....',
194
					'post_status'    => 'publish',
195
					'comment_status' => 'closed',
196
					'ping_status'    => 'closed',
197
					'post_name'      => 'fake-page',
198
					'post_type'      => 'page',
199
					'filter'         => 'raw',
200
				)
201
			),
202
		);
203
	}
204
205
	/**
206
	 * Run the aggregations API query for any filtering
207
	 *
208
	 * @since 8.3.0
209
	 *
210
	 * @param WP_Query $query The WP_Query being filtered.
211
	 */
212
	public function action__parse_query( $query ) {
213
		if ( ! empty( $this->search_result ) ) {
214
			return;
215
		}
216
217
		if ( is_admin() ) {
218
			return;
219
		}
220
221
		if ( empty( $this->aggregations ) ) {
222
			return;
223
		}
224
225
		jetpack_require_lib( 'jetpack-wpes-query-builder/jetpack-wpes-query-builder' );
226
227
		$builder = new Jetpack_WPES_Query_Builder();
228
		$this->add_aggregations_to_es_query_builder( $this->aggregations, $builder );
229
		$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...
230
			array(
231
				'aggregations' => $builder->build_aggregation(),
232
				'size'         => 0,
233
				'from'         => 0,
234
			)
235
		);
236
	}
237
238
	/**
239
	 * Run an instant search on the WordPress.com public API.
240
	 *
241
	 * @since 8.3.0
242
	 *
243
	 * @param array $args Args conforming to the WP.com v1.3/sites/<blog_id>/search endpoint.
244
	 *
245
	 * @return object|WP_Error The response from the public API, or a WP_Error.
246
	 */
247
	public function instant_api( array $args ) {
248
		$start_time = microtime( true );
249
250
		// Cache locally to avoid remote request slowing the page.
251
		$transient_name = '_jetpack_instant_search_cache_' . md5( wp_json_encode( $args ) );
252
		$cache          = get_transient( $transient_name );
253
		if ( false !== $cache ) {
254
			$end_time = microtime( true );
0 ignored issues
show
Unused Code introduced by
$end_time 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...
255
			return $cache;
256
		}
257
258
		$endpoint     = sprintf( '/sites/%s/search', $this->jetpack_blog_id );
259
		$query_params = urldecode( http_build_query( $args ) );
260
		$service_url  = 'https://public-api.wordpress.com/rest/v1.3' . $endpoint . '?' . $query_params;
261
262
		$request_args = array(
263
			'timeout'    => 10,
264
			'user-agent' => 'jetpack_search',
265
		);
266
267
		$request  = wp_remote_get( $service_url, $request_args );
268
		$end_time = microtime( true );
269
270
		if ( is_wp_error( $request ) ) {
271
			return $request;
272
		}
273
274
		$response_code = wp_remote_retrieve_response_code( $request );
275
		$response      = json_decode( wp_remote_retrieve_body( $request ), true );
276
277 View Code Duplication
		if ( ! $response_code || $response_code < 200 || $response_code >= 300 ) {
278
			/**
279
			 * Fires after a search query request has failed
280
			 *
281
			 * @module search
282
			 *
283
			 * @since  5.6.0
284
			 *
285
			 * @param array Array containing the response code and response from the failed search query
286
			 */
287
			do_action(
288
				'failed_jetpack_search_query',
289
				array(
290
					'response_code' => $response_code,
291
					'json'          => $response,
292
				)
293
			);
294
295
			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...
296
		}
297
298
		$took = is_array( $response ) && ! empty( $response['took'] )
299
			? $response['took']
300
			: null;
301
302
		$query = array(
303
			'args'          => $args,
304
			'response'      => $response,
305
			'response_code' => $response_code,
306
			'elapsed_time'  => ( $end_time - $start_time ) * 1000, // Convert from float seconds to ms.
307
			'es_time'       => $took,
308
			'url'           => $service_url,
309
		);
310
311
		/**
312
		 * Fires after a search request has been performed.
313
		 *
314
		 * Includes the following info in the $query parameter:
315
		 *
316
		 * array args Array of Elasticsearch arguments for the search
317
		 * array response Raw API response, JSON decoded
318
		 * int response_code HTTP response code of the request
319
		 * float elapsed_time Roundtrip time of the search request, in milliseconds
320
		 * float es_time Amount of time Elasticsearch spent running the request, in milliseconds
321
		 * string url API url that was queried
322
		 *
323
		 * @module search
324
		 *
325
		 * @since  5.0.0
326
		 * @since  5.8.0 This action now fires on all queries instead of just successful queries.
327
		 *
328
		 * @param array $query Array of information about the query performed
329
		 */
330
		do_action( 'did_jetpack_search_query', $query );
331
332
		// Update local cache.
333
		set_transient( $transient_name, $response, 1 * HOUR_IN_SECONDS );
334
335
		return $response;
336
	}
337
338
	/**
339
	 * Get the raw Aggregation results from the Elasticsearch response.
340
	 *
341
	 * @since  8.3.0
342
	 *
343
	 * @return array Array of Aggregations performed on the search.
344
	 */
345
	public function get_search_aggregations_results() {
346
		if ( empty( $this->search_result ) || ! isset( $this->search_result['aggregations'] ) ) {
347
			return array();
348
		}
349
350
		return $this->search_result['aggregations'];
351
	}
352
353
354
}
355