PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 13.0.1
Jetpack – WP Security, Backup, Speed, & Growth v13.0.1
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / modules / plugin-search.php

plugin-search.php in Jetpack – WP Security, Backup, Speed, & Growth 13.0.1, at modules/plugin-search.php

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