Completed
Push — branch-7.2 ( 9de9d8...2ff64e )
by
unknown
49:03 queued 42:11
created

Jetpack_Plugin_Search::__construct()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
nc 1
nop 0
1
<?php
2
/**
3
 * Disable direct access and execution.
4
 */
5
if ( ! defined( 'ABSPATH' ) ) {
6
	exit;
7
}
8
9
10
if (
11
	is_admin() &&
12
	Jetpack::is_active() &&
13
	/** This filter is documented in _inc/lib/admin-pages/class.jetpack-react-page.php */
14
	apply_filters( 'jetpack_show_promotions', true ) &&
15
	jetpack_is_psh_active()
16
) {
17
	Jetpack_Plugin_Search::init();
18
}
19
20
// Register endpoints when WP REST API is initialized.
21
add_action( 'rest_api_init', array( 'Jetpack_Plugin_Search', 'register_endpoints' ) );
22
23
/**
24
 * Class that includes cards in the plugin search results when users enter terms that match some Jetpack feature.
25
 * Card can be dismissed and includes a title, description, button to enable the feature and a link for more information.
26
 *
27
 * @since 7.1.0
28
 */
29
class Jetpack_Plugin_Search {
30
31
	static $slug = 'jetpack-plugin-search';
32
33
	public static function init() {
34
		static $instance = null;
35
36
		if ( ! $instance ) {
37
			jetpack_require_lib( 'tracks/client' );
38
			$instance = new Jetpack_Plugin_Search();
39
		}
40
41
		return $instance;
42
	}
43
44
	public function __construct() {
45
		add_action( 'current_screen', array( $this, 'start' ) );
46
	}
47
48
	/**
49
	 * Add actions and filters only if this is the plugin installation screen and it's the first page.
50
	 *
51
	 * @param object $screen
52
	 *
53
	 * @since 7.1.0
54
	 */
55
	public function start( $screen ) {
56
		if ( 'plugin-install' === $screen->base && ( ! isset( $_GET['paged'] ) || 1 == $_GET['paged'] ) ) {
57
			add_action( 'admin_enqueue_scripts', array( $this, 'load_plugins_search_script' ) );
58
			add_filter( 'plugins_api_result', array( $this, 'inject_jetpack_module_suggestion' ), 10, 3 );
59
			add_filter( 'self_admin_url', array( $this, 'plugin_details' ) );
60
			add_filter( 'plugin_install_action_links', array( $this, 'insert_module_related_links' ), 10, 2 );
61
		}
62
	}
63
64
	/**
65
	 * Modify URL used to fetch to plugin information so it pulls Jetpack plugin page.
66
	 *
67
	 * @param string $url URL to load in dialog pulling the plugin page from wporg.
68
	 *
69
	 * @since 7.1.0
70
	 *
71
	 * @return string The URL with 'jetpack' instead of 'jetpack-plugin-search'.
72
	 */
73
	public function plugin_details( $url ) {
74
		return false !== stripos( $url, 'tab=plugin-information&amp;plugin=' . self::$slug )
75
			? 'plugin-install.php?tab=plugin-information&amp;plugin=jetpack&amp;TB_iframe=true&amp;width=600&amp;height=550'
76
			: $url;
77
	}
78
79
	/**
80
	 * Register REST API endpoints.
81
	 *
82
	 * @since 7.1.0
83
	 */
84
	public static function register_endpoints() {
85
		register_rest_route( 'jetpack/v4', '/hints', array(
86
			'methods' => WP_REST_Server::EDITABLE,
87
			'callback' => __CLASS__ . '::dismiss',
88
			'permission_callback' => __CLASS__ . '::can_request',
89
			'args' => array(
90
				'hint' => array(
91
					'default'           => '',
92
					'type'              => 'string',
93
					'required'          => true,
94
					'validate_callback' => __CLASS__ . '::is_hint_id',
95
				),
96
			)
97
		) );
98
	}
99
100
	/**
101
	 * A WordPress REST API permission callback method that accepts a request object and
102
	 * decides if the current user has enough privileges to act.
103
	 *
104
	 * @since 7.1.0
105
	 *
106
	 * @return bool does a current user have enough privileges.
107
	 */
108
	public static function can_request() {
109
		return current_user_can( 'jetpack_admin_page' );
110
	}
111
112
	/**
113
	 * Validates that the ID of the hint to dismiss is a string.
114
	 *
115
	 * @since 7.1.0
116
	 *
117
	 * @param string|bool $value Value to check.
118
	 * @param WP_REST_Request $request The request sent to the WP REST API.
119
	 * @param string $param Name of the parameter passed to endpoint holding $value.
120
	 *
121
	 * @return bool|WP_Error
122
	 */
123
	public static function is_hint_id( $value, $request, $param ) {
124
		return in_array( $value, Jetpack::get_available_modules(), true )
125
			? true
126
			: new WP_Error( 'invalid_param', sprintf( esc_html__( '%s must be an alphanumeric string.', 'jetpack' ), $param ) );
127
	}
128
129
	/**
130
	 * A WordPress REST API callback method that accepts a request object and decides what to do with it.
131
	 *
132
	 * @param WP_REST_Request $request {
133
	 *     Array of parameters received by request.
134
	 *
135
	 *     @type string $hint Slug of card to dismiss.
136
	 * }
137
	 *
138
	 * @since 7.1.0
139
	 *
140
	 * @return bool|array|WP_Error a resulting value or object, or an error.
141
	 */
142
	public static function dismiss( WP_REST_Request $request ) {
143
		return self::add_to_dismissed_hints( $request['hint'] )
144
			? rest_ensure_response( array( 'code' => 'success' ) )
145
			: new WP_Error( 'not_dismissed', esc_html__( 'The card could not be dismissed', 'jetpack' ), array( 'status' => 400 ) );
146
	}
147
148
	/**
149
	 * Returns a list of previously dismissed hints.
150
	 *
151
	 * @since 7.1.0
152
	 *
153
	 * @return array List of dismissed hints.
154
	 */
155
	protected static function get_dismissed_hints() {
156
		$dismissed_hints = Jetpack_Options::get_option( 'dismissed_hints' );
157
		return isset( $dismissed_hints ) && is_array( $dismissed_hints )
158
			? $dismissed_hints
159
			: array();
160
	}
161
162
	/**
163
	 * Save the hint in the list of dismissed hints.
164
	 *
165
	 * @since 7.1.0
166
	 *
167
	 * @param string $hint The hint id, which is a Jetpack module slug.
168
	 *
169
	 * @return bool Whether the card was added to the list and hence dismissed.
170
	 */
171
	protected static function add_to_dismissed_hints( $hint ) {
172
		return Jetpack_Options::update_option( 'dismissed_hints', array_merge( self::get_dismissed_hints(), array( $hint ) ) );
173
	}
174
175
	/**
176
	 * Checks that the module slug passed should be displayed.
177
	 *
178
	 * A feature hint will be displayed if it has not been dismissed before or if 2 or fewer other hints have been dismissed.
179
	 *
180
	 * @since 7.2.1
181
	 *
182
	 * @param string $hint The hint id, which is a Jetpack module slug.
183
	 *
184
	 * @return bool True if $hint should be displayed.
185
	 */
186
	protected function should_display_hint( $hint ) {
187
		$dismissed_hints = $this->get_dismissed_hints();
188
		// If more than 2 hints have been dismissed, then show no more.
189
		if ( 2 < count( $dismissed_hints ) ) {
190
			return false;
191
		}
192
		return ! in_array( $hint, $dismissed_hints, true );
193
	}
194
195
	public function load_plugins_search_script() {
196
		wp_enqueue_script( self::$slug, plugins_url( 'modules/plugin-search/plugin-search.js', JETPACK__PLUGIN_FILE ), array( 'jquery' ), JETPACK__VERSION, true );
197
		wp_localize_script(
198
			self::$slug,
199
			'jetpackPluginSearch',
200
			array(
201
				'nonce'          => wp_create_nonce( 'wp_rest' ),
202
				'base_rest_url'  => rest_url( '/jetpack/v4' ),
203
				'manageSettings' => esc_html__( 'Configure', 'jetpack' ),
204
				'activateModule' => esc_html__( 'Activate Module', 'jetpack' ),
205
				'getStarted'     => esc_html__( 'Get started', 'jetpack' ),
206
				'activated'      => esc_html__( 'Activated', 'jetpack' ),
207
				'activating'     => esc_html__( 'Activating', 'jetpack' ),
208
				'logo'           => 'https://ps.w.org/jetpack/assets/icon.svg?rev=1791404',
209
				'legend'         => esc_html__(
210
					'Jetpack is trusted by millions to help secure and speed up their WordPress site. Make the most of it today.',
211
					'jetpack'
212
				),
213
				'hideText'       => esc_html__( 'Hide this suggestion', 'jetpack' ),
214
			)
215
		);
216
217
		wp_enqueue_style( self::$slug, plugins_url( 'modules/plugin-search/plugin-search.css', JETPACK__PLUGIN_FILE ) );
218
	}
219
220
	/**
221
	 * Get the plugin repo's data for Jetpack to populate the fields with.
222
	 *
223
	 * @return array|mixed|object|WP_Error
224
	 */
225
	public static function get_jetpack_plugin_data() {
226
		$data = get_transient( 'jetpack_plugin_data' );
227
228
		if ( false === $data || is_wp_error( $data ) ) {
229
			include_once( ABSPATH . 'wp-admin/includes/plugin-install.php' );
230
			$data = plugins_api( 'plugin_information', array(
231
				'slug' => 'jetpack',
232
				'is_ssl' => is_ssl(),
233
				'fields' => array(
234
					'banners' => true,
235
					'reviews' => true,
236
					'active_installs' => true,
237
					'versions' => false,
238
					'sections' => false,
239
				),
240
			) );
241
			set_transient( 'jetpack_plugin_data', $data, DAY_IN_SECONDS );
242
		}
243
244
		return $data;
245
	}
246
247
	/**
248
	 * Create a list with additional features for those we don't have a module, like Akismet.
249
	 *
250
	 * @since 7.1.0
251
	 *
252
	 * @return array List of features.
253
	 */
254
	public function get_extra_features() {
255
		return array(
256
			'akismet' => array(
257
				'name' => 'Akismet',
258
				'search_terms' => 'akismet, anti-spam, antispam, comments, spam, spam protection, form spam, captcha, no captcha, nocaptcha, recaptcha, phising, google',
259
				'short_description' => esc_html__( 'Keep your visitors and search engines happy by stopping comment and contact form spam with Akismet.', 'jetpack' ),
260
				'requires_connection' => true,
261
				'module' => 'akismet',
262
				'sort' => '16',
263
				'learn_more_button' => 'https://jetpack.com/features/security/spam-filtering/',
264
				'configure_url' => admin_url( 'admin.php?page=akismet-key-config' ),
265
			),
266
		);
267
	}
268
269
	/**
270
	 * Intercept the plugins API response and add in an appropriate card for Jetpack
271
	 */
272
	public function inject_jetpack_module_suggestion( $result, $action, $args ) {
273
		// Looks like a search query; it's matching time
274
		if ( ! empty( $args->search ) ) {
275
			require_once JETPACK__PLUGIN_DIR . 'class.jetpack-admin.php';
276
			$jetpack_modules_list = array_intersect_key(
277
				array_merge( $this->get_extra_features(), Jetpack_Admin::init()->get_modules() ),
278
				array_flip( array(
279
					'contact-form',
280
					'lazy-images',
281
					'monitor',
282
					'photon',
283
					'photon-cdn',
284
					'protect',
285
					'publicize',
286
					'related-posts',
287
					'sharedaddy',
288
					'akismet',
289
					'vaultpress',
290
					'videopress',
291
					'search',
292
				) )
293
			);
294
			uasort( $jetpack_modules_list, array( $this, 'by_sorting_option' ) );
295
296
			// Record event when user searches for a term over 3 chars (less than 3 is not very useful.)
297
			if ( strlen( $args->search ) >= 3 ) {
298
				JetpackTracking::record_user_event( 'wpa_plugin_search_term', array( 'search_term' => $args->search ) );
299
			}
300
301
			// Lowercase, trim, remove punctuation/special chars, decode url, remove 'jetpack'
302
			$normalized_term = $this->sanitize_search_term( $args->search );
303
304
			$matching_module = null;
305
306
			// Try to match a passed search term with module's search terms
307
			foreach ( $jetpack_modules_list as $module_slug => $module_opts ) {
308
				/*
309
				* Does the site's current plan support the feature?
310
				* We don't use Jetpack_Plan::supports() here because
311
				* that check always returns Akismet as supported,
312
				* since Akismet has a free version.
313
				*/
314
				$current_plan         = Jetpack_Plan::get();
315
				$is_supported_by_plan = in_array( $module_slug, $current_plan['supports'], true );
316
317
				if (
318
					false !== stripos( $module_opts['search_terms'] . ', ' . $module_opts['name'], $normalized_term )
319
					&& $is_supported_by_plan
320
				) {
321
					$matching_module = $module_slug;
322
					break;
323
				}
324
			}
325
326
			if ( isset( $matching_module ) && $this->should_display_hint( $matching_module ) ) {
327
				// Record event when a matching feature is found
328
				JetpackTracking::record_user_event( 'wpa_plugin_search_match_found', array( 'feature' => $matching_module ) );
329
330
				$inject = (array) self::get_jetpack_plugin_data();
331
				$image_url = plugins_url( 'modules/plugin-search/psh', JETPACK__PLUGIN_FILE );
332
				$overrides = array(
333
					'plugin-search' => true, // Helps to determine if that an injected card.
334
					'name' => sprintf(       // Supplement name/description so that they clearly indicate this was added.
335
						esc_html_x( 'Jetpack: %s', 'Jetpack: Module Name', 'jetpack' ),
336
						$jetpack_modules_list[ $matching_module ]['name']
337
					),
338
					'short_description' => $jetpack_modules_list[ $matching_module ]['short_description'],
339
					'requires_connection' => (bool) $jetpack_modules_list[ $matching_module ]['requires_connection'],
340
					'slug'    => self::$slug,
341
					'version' => JETPACK__VERSION,
342
					'icons' => array(
343
						'1x'  => "$image_url-128.png",
344
						'2x'  => "$image_url-256.png",
345
						'svg' => "$image_url.svg",
346
					),
347
				);
348
349
				// Splice in the base module data
350
				$inject = array_merge( $inject, $jetpack_modules_list[ $matching_module ], $overrides );
351
352
				// Add it to the top of the list
353
				$result->plugins = array_filter( $result->plugins, array( $this, 'filter_cards' ) );
354
				array_unshift( $result->plugins, $inject );
355
			}
356
		}
357
		return $result;
358
	}
359
360
	/**
361
	 * Remove cards for Jetpack plugins since we don't want duplicates.
362
	 *
363
	 * @since 7.1.0
364
	 * @since 7.2.0 Only remove Jetpack.
365
	 *
366
	 * @param array|object $plugin
367
	 *
368
	 * @return bool
369
	 */
370
	function filter_cards( $plugin ) {
371
		// Take in account that before WordPress 5.1, the list of plugins is an array of objects.
372
		// With WordPress 5.1 the list of plugins is an array of arrays.
373
		$slug = is_array( $plugin ) ? $plugin['slug'] : $plugin->slug;
374
		return ! in_array( $slug, array( 'jetpack' ), true );
375
	}
376
377
	/**
378
	 * Take a raw search query and return something a bit more standardized and
379
	 * easy to work with.
380
	 *
381
	 * @param  String $term The raw search term
382
	 * @return String A simplified/sanitized version.
383
	 */
384
	private function sanitize_search_term( $term ) {
385
		$term = strtolower( urldecode( $term ) );
386
387
		// remove non-alpha/space chars.
388
		$term = preg_replace( '/[^a-z ]/', '', $term );
389
390
		// remove strings that don't help matches.
391
		$term = trim( str_replace( array( 'jetpack', 'jp', 'free', 'wordpress' ), '', $term ) );
392
393
		return $term;
394
	}
395
396
	/**
397
	 * Callback function to sort the array of modules by the sort option.
398
	 */
399
	private function by_sorting_option( $m1, $m2 ) {
400
		return $m1['sort'] - $m2['sort'];
401
	}
402
403
	/**
404
	 * Builds a URL to purchase and upgrade inserting the site fragment and the affiliate code if it exists.
405
	 *
406
	 * @param string $feature Module slug (or forged one for extra features).
407
	 *
408
	 * @since 7.1.0
409
	 *
410
	 * @return string URL to upgrade.
411
	 */
412
	private function get_upgrade_url( $feature ) {
413
		$site_raw_url = Jetpack::build_raw_urls( get_home_url() );
414
		$affiliateCode = Jetpack_Affiliate::init()->get_affiliate_code();
415
		$user = wp_get_current_user()->ID;
416
		return "https://jetpack.com/redirect/?source=plugin-hint-upgrade-$feature&site=$site_raw_url&u=$user" .
417
		       ( $affiliateCode ? "&aff=$affiliateCode" : '' );
418
	}
419
420
	/**
421
	 * Modify the URL to the feature settings, for example Publicize.
422
	 * Sharing is included here because while we still have a page in WP Admin,
423
	 * we prefer to send users to Calypso.
424
	 *
425
	 * @param string $feature
426
	 * @param string $configure_url
427
	 *
428
	 * @return string
429
	 * @since 7.1.0
430
	 *
431
	 */
432
	private function get_configure_url( $feature, $configure_url ) {
433
		$siteFragment = Jetpack::build_raw_urls( get_home_url() );
434
		switch ( $feature ) {
435
			case 'sharing':
436
			case 'publicize':
437
				$configure_url = "https://wordpress.com/sharing/$siteFragment";
438
				break;
439
			case 'seo-tools':
440
				$configure_url = "https://wordpress.com/settings/traffic/$siteFragment#seo";
441
				break;
442
			case 'google-analytics':
443
				$configure_url = "https://wordpress.com/settings/traffic/$siteFragment#analytics";
444
				break;
445
			case 'wordads':
446
				$configure_url = "https://wordpress.com/ads/settings/$siteFragment";
447
				break;
448
		}
449
		return $configure_url;
450
	}
451
452
	/**
453
	 * Put some more appropriate links on our custom result cards.
454
	 */
455
	public function insert_module_related_links( $links, $plugin ) {
456
		if ( self::$slug !== $plugin['slug'] ) {
457
			return $links;
458
		}
459
460
		// By the time this filter is applied, self_admin_url was already applied and we don't need it anymore.
461
		remove_filter( 'self_admin_url', array( $this, 'plugin_details' ) );
462
463
		$links = array();
464
465
		if ( 'akismet' === $plugin['module'] || 'vaultpress' === $plugin['module'] ) {
466
			$links['jp_get_started'] = '<a
467
				id="plugin-select-settings"
468
				class="jetpack-plugin-search__primary jetpack-plugin-search__get-started button"
469
				href="https://jetpack.com/redirect/?source=plugin-hint-learn-' . $plugin['module'] . '"
470
				data-module="' . esc_attr( $plugin['module'] ) . '"
471
				data-track="get_started"
472
				>' . esc_html__( 'Get started', 'jetpack' ) . '</a>';
473
			// Jetpack installed, active, feature not enabled; prompt to enable.
474
		} elseif (
475
			current_user_can( 'jetpack_activate_modules' ) &&
476
			! Jetpack::is_module_active( $plugin['module'] ) &&
477
			Jetpack_Plan::supports( $plugin['module'] )
478
		) {
479
			$links[] = '<button
480
					id="plugin-select-activate"
481
					class="jetpack-plugin-search__primary button"
482
					data-module="' . esc_attr( $plugin['module'] ) . '"
483
					data-configure-url="' . esc_url( $this->get_configure_url( $plugin['module'], $plugin['configure_url'] ) ) . '"
484
					> ' . esc_html__( 'Enable', 'jetpack' ) . '</button>';
485
486
			// Jetpack installed, active, feature enabled; link to settings.
487
		} elseif (
488
			! empty( $plugin['configure_url'] ) &&
489
			current_user_can( 'jetpack_configure_modules' ) &&
490
			Jetpack::is_module_active( $plugin['module'] ) &&
491
			/** This filter is documented in class.jetpack-admin.php */
492
			apply_filters( 'jetpack_module_configurable_' . $plugin['module'], false )
493
		) {
494
			$links[] = '<a
495
				id="plugin-select-settings"
496
				class="jetpack-plugin-search__primary button jetpack-plugin-search__configure"
497
				href="' . esc_url( $this->get_configure_url( $plugin['module'], $plugin['configure_url'] ) ) . '"
498
				data-module="' . esc_attr( $plugin['module'] ) . '"
499
				data-track="configure"
500
				>' . esc_html__( 'Configure', 'jetpack' ) . '</a>';
501
			// Module is active, doesn't have options to configure
502
		} elseif ( Jetpack::is_module_active( $plugin['module'] ) ) {
503
			$links['jp_get_started'] = '<a
504
				id="plugin-select-settings"
505
				class="jetpack-plugin-search__primary jetpack-plugin-search__get-started button"
506
				href="https://jetpack.com/redirect/?source=plugin-hint-learn-' . $plugin['module'] . '"
507
				data-module="' . esc_attr( $plugin['module'] ) . '"
508
				data-track="get_started"
509
				>' . esc_html__( 'Get started', 'jetpack' ) . '</a>';
510
		}
511
512
		// Add link pointing to a relevant doc page in jetpack.com only if the Get started button isn't displayed.
513
		if ( ! empty( $plugin['learn_more_button'] ) && ! isset( $links['jp_get_started'] ) ) {
514
			$links[] = '<a
515
				class="jetpack-plugin-search__learn-more"
516
				href="' . esc_url( $plugin['learn_more_button'] ) . '"
517
				target="_blank"
518
				data-module="' . esc_attr( $plugin['module'] ) . '"
519
				data-track="learn_more"
520
				>' . esc_html__( 'Learn more', 'jetpack' ) . '</a>';
521
		}
522
523
		// Dismiss link
524
		$links[] = '<a
525
			class="jetpack-plugin-search__dismiss"
526
			data-module="' . esc_attr( $plugin['module'] ) . '"
527
			>' . esc_html__( 'Hide this suggestion', 'jetpack' ) . '</a>';
528
529
		return $links;
530
	}
531
532
}
533
534
/**
535
 * Master control that checks if Plugin search hints is active.
536
 *
537
 * @since 7.1.1
538
 *
539
 * @return bool True if PSH is active.
540
 */
541
function jetpack_is_psh_active() {
542
	// false means unset, 1 means active, 0 means inactive.
543
	$status = get_transient( 'jetpack_psh_status' );
544
545
	if ( false === $status ) {
546
		$error = false;
547
		$status = jetpack_get_remote_is_psh_active( $error );
548
		set_transient(
549
			'jetpack_psh_status',
550
			// Cache as int
551
			(int) $status,
552
			// If there was an error, still cache but for a shorter time
553
			( $error ? 5 : 15 ) * MINUTE_IN_SECONDS
554
		);
555
	}
556
557
	return (bool) $status;
558
}
559
560
/**
561
 * Makes remote request to determine if Plugin search hints is active.
562
 *
563
 * @since 7.1.1
564
 * @internal
565
 *
566
 * @param bool &$error Did the remote request result in an error?
567
 * @return bool True if PSH is active.
568
 */
569
function jetpack_get_remote_is_psh_active( &$error ) {
570
	$response = wp_remote_get( 'https://jetpack.com/psh-status/' );
571
	if ( is_wp_error( $response ) ) {
572
		$error = true;
573
		return true;
574
	}
575
576
	$body = wp_remote_retrieve_body( $response );
577
	if ( empty( $body ) ) {
578
		$error = true;
579
		return true;
580
	}
581
582
	$json = json_decode( $body );
583
	if ( ! isset( $json->active ) ) {
584
		$error = true;
585
		return true;
586
	}
587
588
	$error = false;
589
	return (bool) $json->active;
590
}
591