Completed
Push — branch-7.1 ( cc7dbf...9c7f76 )
by Jeremy
13:12 queued 06:35
created

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