PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 16.3-a.5
Jetpack – WP Security, Backup, Speed, & Growth v16.3-a.5
16.3-a.5 16.3-a.7 16.3-a.3 16.3-a.1 16.2 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 All 506 releases
jetpack / class.jetpack.php

class.jetpack.php in Jetpack – WP Security, Backup, Speed, & Growth 16.3-a.5, at class.jetpack.php

6,674 lines 226.8 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 * The mega-class.
4 *
5 * This contains too much, so please think twice before adding more.
6 *
7 * @package automattic/jetpack
8 */
9
10 use Automattic\Jetpack\Assets;
11 use Automattic\Jetpack\Boost_Speed_Score\Speed_Score;
12 use Automattic\Jetpack\Config;
13 use Automattic\Jetpack\Connection\Authorize_Json_Api;
14 use Automattic\Jetpack\Connection\Client;
15 use Automattic\Jetpack\Connection\Manager as Connection_Manager;
16 use Automattic\Jetpack\Connection\Rest_Authentication as Connection_Rest_Authentication;
17 use Automattic\Jetpack\Connection\Secrets;
18 use Automattic\Jetpack\Connection\Tokens;
19 use Automattic\Jetpack\Connection\Webhooks\Authorize_Redirect;
20 use Automattic\Jetpack\Constants;
21 use Automattic\Jetpack\CookieState;
22 use Automattic\Jetpack\Current_Plan as Jetpack_Plan;
23 use Automattic\Jetpack\Device_Detection\User_Agent_Info;
24 use Automattic\Jetpack\Errors;
25 use Automattic\Jetpack\Feature_Policy;
26 use Automattic\Jetpack\Files;
27 use Automattic\Jetpack\Heartbeat;
28 use Automattic\Jetpack\Identity_Crisis;
29 use Automattic\Jetpack\Import\Main as Import_Main;
30 use Automattic\Jetpack\Licensing;
31 use Automattic\Jetpack\Modules;
32 use Automattic\Jetpack\My_Jetpack\Initializer as My_Jetpack_Initializer;
33 use Automattic\Jetpack\Newsletter\Reader_Link;
34 use Automattic\Jetpack\Paths;
35 use Automattic\Jetpack\Plugin\Deprecate;
36 use Automattic\Jetpack\Plugin\Tracking as Plugin_Tracking;
37 use Automattic\Jetpack\Podcast\Podcast;
38 use Automattic\Jetpack\Redirect;
39 use Automattic\Jetpack\Scan_Page\Jetpack_Scan as Scan_Page_Init;
40 use Automattic\Jetpack\SEO\Initializer as Jetpack_SEO_Initializer;
41 use Automattic\Jetpack\Status;
42 use Automattic\Jetpack\Status\Host;
43 use Automattic\Jetpack\Status\Visitor;
44 use Automattic\Jetpack\Sync\Actions as Sync_Actions;
45 use Automattic\Jetpack\Sync\Health;
46 use Automattic\Jetpack\Sync\Sender;
47 use Automattic\Jetpack\Terms_Of_Service;
48 use Automattic\Jetpack\Tracking;
49 use Automattic\Woocommerce_Analytics;
50
51 if ( ! defined( 'ABSPATH' ) ) {
52 exit( 0 );
53 }
54
55 /*
56 Options:
57 jetpack_options (array)
58 An array of options.
59 @see Jetpack_Options::get_option_names()
60
61 jetpack_register (string)
62 Temporary verification secrets.
63
64 jetpack_activated (int)
65 1: the plugin was activated normally
66 2: the plugin was activated on this site because of a network-wide activation
67 3: the plugin was auto-installed
68 4: the plugin was manually disconnected (but is still installed)
69
70 jetpack_active_modules (array)
71 Array of active module slugs.
72
73 jetpack_do_activate (bool)
74 Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
75 */
76
77 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.media.php';
78
79 /**
80 * The Jetpack class.
81 */
82 class Jetpack {
83 /**
84 * XMLRPC server instance.
85 *
86 * @var null|Jetpack_XMLRPC_Server XMLRPC server used by Jetpack.
87 */
88 public $xmlrpc_server = null;
89
90 /**
91 * Contains all assets that have had their URL rewritten to minified versions.
92 *
93 * @var array
94 */
95 public static $min_assets = array();
96
97 /**
98 * Plugins to deactivate.
99 *
100 * @var array Plugins to deactivate by module.
101 */
102 public $plugins_to_deactivate = array(
103 'contact-form' => array(
104 array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
105 array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
106 ),
107 'gravatar-hovercards' => array(
108 array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
109 ),
110 'latex' => array(
111 array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
112 ),
113 'random-redirect' => array(
114 array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
115 ),
116 'sharedaddy' => array(
117 array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
118 array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
119 ),
120 'shortlinks' => array(
121 array( 'stats/stats.php', 'WordPress.com Stats' ),
122 ),
123 'stats' => array(
124 array( 'stats/stats.php', 'WordPress.com Stats' ),
125 ),
126 'twitter-widget' => array(
127 array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
128 ),
129 'videopress' => array(
130 array( 'video/video.php', 'VideoPress' ),
131 ),
132 'widget-visibility' => array(
133 array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
134 array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
135 ),
136 );
137
138 /**
139 * Map of roles we care about, and their corresponding minimum capabilities.
140 *
141 * @deprecated 7.6 Use Automattic\Jetpack\Roles::$capability_translations instead.
142 *
143 * @access public
144 * @static
145 *
146 * @var array
147 */
148 public static $capability_translations = array(
149 'administrator' => 'manage_options',
150 'editor' => 'edit_others_posts',
151 'author' => 'publish_posts',
152 'contributor' => 'edit_posts',
153 'subscriber' => 'read',
154 );
155
156 /**
157 * Map of modules that have conflicts with plugins and should not be auto-activated
158 * if the plugins are active. Used by filter_default_modules
159 *
160 * Plugin Authors: If you'd like to prevent a single module from auto-activating,
161 * change `module-slug` and add this to your plugin:
162 *
163 * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
164 * function my_jetpack_get_default_modules( $modules ) {
165 * return array_diff( $modules, array( 'module-slug' ) );
166 * }
167 *
168 * @var array
169 */
170 private $conflicting_plugins = array(
171 'comments' => array(
172 'Intense Debate' => 'intensedebate/intensedebate.php',
173 'Disqus' => 'disqus-comment-system/disqus.php',
174 'Livefyre' => 'livefyre-comments/livefyre.php',
175 'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
176 'Google+ Comments' => 'google-plus-comments/google-plus-comments.php',
177 'WP-SpamShield Anti-Spam' => 'wp-spamshield/wp-spamshield.php',
178 ),
179 'comment-likes' => array(
180 'Epoch' => 'epoch/plugincore.php',
181 ),
182 'latex' => array(
183 'LaTeX for WordPress' => 'latex/latex.php',
184 'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
185 'Easy WP LaTeX' => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
186 'MathJax-LaTeX' => 'mathjax-latex/mathjax-latex.php',
187 'Enable Latex' => 'enable-latex/enable-latex.php',
188 'WP QuickLaTeX' => 'wp-quicklatex/wp-quicklatex.php',
189 ),
190 'protect' => array(
191 'Limit Login Attempts' => 'limit-login-attempts/limit-login-attempts.php',
192 'Captcha' => 'captcha/captcha.php',
193 'Brute Force Login Protection' => 'brute-force-login-protection/brute-force-login-protection.php',
194 'Login Security Solution' => 'login-security-solution/login-security-solution.php',
195 'WPSecureOps Brute Force Protect' => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
196 'BulletProof Security' => 'bulletproof-security/bulletproof-security.php',
197 'SiteGuard WP Plugin' => 'siteguard/siteguard.php',
198 'Security-protection' => 'security-protection/security-protection.php',
199 'Login Security' => 'login-security/login-security.php',
200 'Botnet Attack Blocker' => 'botnet-attack-blocker/botnet-attack-blocker.php',
201 'Wordfence Security' => 'wordfence/wordfence.php',
202 'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
203 'iThemes Security' => 'better-wp-security/better-wp-security.php',
204 ),
205 'random-redirect' => array(
206 'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
207 ),
208 'related-posts' => array(
209 'YARPP' => 'yet-another-related-posts-plugin/yarpp.php',
210 'WordPress Related Posts' => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
211 'nrelate Related Content' => 'nrelate-related-content/nrelate-related.php',
212 'Contextual Related Posts' => 'contextual-related-posts/contextual-related-posts.php',
213 'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
214 'outbrain' => 'outbrain/outbrain.php',
215 'Shareaholic' => 'shareaholic/shareaholic.php',
216 'Sexybookmarks' => 'sexybookmarks/shareaholic.php',
217 ),
218 'sharedaddy' => array(
219 'AddThis' => 'addthis/addthis_social_widget.php',
220 'Add To Any' => 'add-to-any/add-to-any.php',
221 'ShareThis' => 'share-this/sharethis.php',
222 'Shareaholic' => 'shareaholic/shareaholic.php',
223 ),
224 'seo-tools' => array(
225 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
226 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
227 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
228 'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
229 'The SEO Framework' => 'autodescription/autodescription.php',
230 'Rank Math' => 'seo-by-rank-math/rank-math.php',
231 'Slim SEO' => 'slim-seo/slim-seo.php',
232 'SEOKEY' => 'seo-key/seo-key.php',
233 'SEOKEY Pro' => 'seo-key-pro/seo-key.php',
234 'SEOPress' => 'wp-seopress/seopress.php',
235 'SEOPress Pro' => 'wp-seopress-pro/seopress-pro.php',
236 ),
237 'verification-tools' => array(
238 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
239 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
240 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
241 'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
242 'The SEO Framework' => 'autodescription/autodescription.php',
243 'Rank Math' => 'seo-by-rank-math/rank-math.php',
244 'Slim SEO' => 'slim-seo/slim-seo.php',
245 ),
246 'widget-visibility' => array(
247 'Widget Logic' => 'widget-logic/widget_logic.php',
248 'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
249 ),
250 'sitemaps' => array(
251 'Google XML Sitemaps' => 'google-sitemap-generator/sitemap.php',
252 'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
253 'Google XML Sitemaps for qTranslate' => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
254 'XML Sitemap & Google News feeds' => 'xml-sitemap-feed/xml-sitemap.php',
255 'Google Sitemap by BestWebSoft' => 'google-sitemap-plugin/google-sitemap-plugin.php',
256 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
257 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
258 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
259 'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
260 'The SEO Framework' => 'autodescription/autodescription.php',
261 'Sitemap' => 'sitemap/sitemap.php',
262 'Simple Wp Sitemap' => 'simple-wp-sitemap/simple-wp-sitemap.php',
263 'Simple Sitemap' => 'simple-sitemap/simple-sitemap.php',
264 'XML Sitemaps' => 'xml-sitemaps/xml-sitemaps.php',
265 'MSM Sitemaps' => 'msm-sitemap/msm-sitemap.php',
266 'Rank Math' => 'seo-by-rank-math/rank-math.php',
267 'Slim SEO' => 'slim-seo/slim-seo.php',
268 ),
269 );
270
271 /**
272 * Plugins for which we turn off our Facebook OG Tags implementation.
273 *
274 * Note: the following plugins automatically deactivate Jetpack's Open
275 * Graph tags via filter when their Social Meta modules are active:
276 *
277 * - All in One SEO Pack, All in one SEO Pack Pro
278 * - WordPress SEO by Yoast, WordPress SEO Premium by Yoast
279 *
280 * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
281 * add_filter( 'jetpack_enable_open_graph', '__return_false' );
282 *
283 * @var array Array of plugin slugs.
284 */
285 private $open_graph_conflicting_plugins = array(
286 '2-click-socialmedia-buttons/2-click-socialmedia-buttons.php', // 2 Click Social Media Buttons.
287 'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook.
288 'add-meta-tags/add-meta-tags.php', // Add Meta Tags.
289 'complete-open-graph/complete-open-graph.php', // Complete Open Graph.
290 'easy-facebook-share-thumbnails/esft.php', // Easy Facebook Share Thumbnail.
291 'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php', // Open Graph Meta Tags by Heateor.
292 'facebook/facebook.php', // Facebook (official plugin).
293 'facebook-awd/AWD_facebook.php', // Facebook AWD All in one.
294 'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php', // Facebook Featured Image & OG Meta Tags.
295 'facebook-meta-tags/facebook-metatags.php', // Facebook Meta Tags.
296 'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php', // Facebook Open Graph Meta Tags for WordPress.
297 'facebook-revised-open-graph-meta-tag/index.php', // Facebook Revised Open Graph Meta Tag.
298 'facebook-thumb-fixer/_facebook-thumb-fixer.php', // Facebook Thumb Fixer.
299 'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php', // Fedmich's Facebook Open Graph Meta.
300 'network-publisher/networkpub.php', // Network Publisher.
301 'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG.
302 'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php', // NextScripts SNAP.
303 'og-tags/og-tags.php', // OG Tags.
304 'opengraph/opengraph.php', // Open Graph.
305 'open-graph-protocol-framework/open-graph-protocol-framework.php', // Open Graph Protocol Framework.
306 'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments.
307 'seo-ultimate/seo-ultimate.php', // SEO Ultimate.
308 'sexybookmarks/sexy-bookmarks.php', // Shareaholic.
309 'shareaholic/sexy-bookmarks.php', // Shareaholic.
310 'sharepress/sharepress.php', // SharePress.
311 'simple-facebook-connect/sfc.php', // Simple Facebook Connect.
312 'social-discussions/social-discussions.php', // Social Discussions.
313 'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit.
314 'socialize/socialize.php', // Socialize.
315 'squirrly-seo/squirrly.php', // SEO by SQUIRRLY™.
316 'only-tweet-like-share-and-google-1/tweet-like-plusone.php', // Tweet, Like, Google +1 and Share.
317 'wordbooker/wordbooker.php', // Wordbooker.
318 'wpsso/wpsso.php', // WordPress Social Sharing Optimization.
319 'wp-caregiver/wp-caregiver.php', // WP Caregiver.
320 'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php', // WP Facebook Like Send & Open Graph Meta.
321 'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol.
322 'wp-ogp/wp-ogp.php', // WP-OGP.
323 'wp-seopress/seopress.php', // SEOPress.
324 'wp-seopress-pro/seopress-pro.php', // SEOPress Pro.
325 'zoltonorg-social-plugin/zosp.php', // Zolton.org Social Plugin.
326 'wp-fb-share-like-button/wp_fb_share-like_widget.php', // WP Facebook Like Button.
327 'open-graph-metabox/open-graph-metabox.php', // Open Graph Metabox.
328 'seo-by-rank-math/rank-math.php', // Rank Math.
329 'slim-seo/slim-seo.php', // Slim SEO.
330 );
331
332 /**
333 * Plugins for which we turn off our Twitter Cards Tags implementation.
334 *
335 * @var array Plugins that conflict with Twitter cards.
336 */
337 private $twitter_cards_conflicting_plugins = array(
338 // phpcs:ignore Squiz.PHP.CommentedOutCode.Found
339 // 'twitter/twitter.php', // The official one handles this on its own.
340 // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
341 'eewee-twitter-card/index.php', // Eewee Twitter Card.
342 'ig-twitter-cards/ig-twitter-cards.php', // IG:Twitter Cards.
343 'jm-twitter-cards/jm-twitter-cards.php', // JM Twitter Cards.
344 'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php', // Pure Web Brilliant's Social Graph Twitter Cards Extension.
345 'twitter-cards/twitter-cards.php', // Twitter Cards.
346 'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta.
347 'wp-to-twitter/wp-to-twitter.php', // WP to Twitter.
348 'wp-twitter-cards/twitter_cards.php', // WP Twitter Cards.
349 'seo-by-rank-math/rank-math.php', // Rank Math.
350 'slim-seo/slim-seo.php', // Slim SEO.
351 );
352
353 /**
354 * Message to display in admin_notice
355 *
356 * @var string
357 */
358 public $message = '';
359
360 /**
361 * Error to display in admin_notice
362 *
363 * @var string
364 */
365 public $error = '';
366
367 /**
368 * Modules that need more privacy description.
369 *
370 * @var string
371 */
372 public $privacy_checks = '';
373
374 /**
375 * Stats to record once the page loads
376 *
377 * @var array
378 */
379 public $stats = array();
380
381 /**
382 * Jetpack_Sync object
383 *
384 * @todo This is also seemingly unused.
385 *
386 * @var object
387 */
388 public $sync;
389
390 /**
391 * Verified data for JSON authorization request
392 *
393 * @deprecated 13.4
394 *
395 * @var array
396 */
397 public $json_api_authorization_request = array();
398
399 /**
400 * Connection manager.
401 *
402 * @var Automattic\Jetpack\Connection\Manager
403 */
404 protected $connection_manager;
405
406 /**
407 * Plugin lock key.
408 *
409 * @var string Transient key used to prevent multiple simultaneous plugin upgrades
410 */
411 public static $plugin_upgrade_lock_key = 'jetpack_upgrade_lock';
412
413 /**
414 * Holds an instance of Automattic\Jetpack\A8c_Mc_Stats
415 *
416 * @var Automattic\Jetpack\A8c_Mc_Stats
417 */
418 public $a8c_mc_stats_instance;
419
420 /**
421 * Constant for login redirect key.
422 *
423 * @var string
424 * @since 8.4.0
425 */
426 public static $jetpack_redirect_login = 'jetpack_connect_login_redirect';
427
428 /**
429 * Holds the singleton instance of this class
430 *
431 * @since 2.3.3
432 * @var Jetpack
433 */
434 public static $instance = false;
435
436 /**
437 * Resolved answer for `is_premium_analytics_enabled()`, or null before the first call.
438 *
439 * @since 16.1
440 * @var bool|null
441 */
442 private static $premium_analytics_enabled = null;
443
444 /**
445 * Singleton
446 *
447 * @static
448 */
449 public static function init() {
450 if ( ! self::$instance ) {
451 self::$instance = new Jetpack();
452 add_action( 'plugins_loaded', array( self::$instance, 'plugin_upgrade' ) );
453 add_action( 'jetpack_idc_disconnect', array( __CLASS__, 'on_idc_disconnect' ) );
454 }
455
456 return self::$instance;
457 }
458
459 /**
460 * Must never be called statically
461 */
462 public function plugin_upgrade() {
463 if ( self::is_connection_ready() ) {
464 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
465 if ( JETPACK__VERSION !== $version ) {
466 // Prevent multiple upgrades at once - only a single process should trigger an upgrade to avoid stampedes.
467 if ( wp_using_ext_object_cache() ) {
468 if ( true !== wp_cache_add( self::$plugin_upgrade_lock_key, 1, 'transient', 10 ) ) {
469 return;
470 }
471 } else {
472 if ( false !== get_transient( self::$plugin_upgrade_lock_key ) ) {
473 return;
474 }
475
476 set_transient( self::$plugin_upgrade_lock_key, 1, 10 );
477 }
478
479 // check which active modules actually exist and remove others from active_modules list.
480 $unfiltered_modules = self::get_active_modules();
481 $modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
482 if ( array_diff( $unfiltered_modules, $modules ) ) {
483 self::update_active_modules( $modules );
484 }
485
486 self::register_upgrade_init_hooks();
487
488 // Upgrade to 4.3.0.
489 if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
490 Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
491 }
492
493 // Make sure Markdown for posts gets turned back on.
494 if ( ! get_option( 'wpcom_publish_posts_with_markdown' ) ) {
495 update_option( 'wpcom_publish_posts_with_markdown', true );
496 }
497
498 /*
499 * Minileven deprecation. 8.3.0.
500 * Only delete options if not using
501 * the replacement standalone Minileven plugin.
502 */
503 if (
504 ! self::is_plugin_active( 'minileven-master/minileven.php' )
505 && ! self::is_plugin_active( 'minileven/minileven.php' )
506 ) {
507 if ( get_option( 'wp_mobile_custom_css' ) ) {
508 delete_option( 'wp_mobile_custom_css' );
509 }
510 if ( get_option( 'wp_mobile_excerpt' ) ) {
511 delete_option( 'wp_mobile_excerpt' );
512 }
513 if ( get_option( 'wp_mobile_featured_images' ) ) {
514 delete_option( 'wp_mobile_featured_images' );
515 }
516 if ( get_option( 'wp_mobile_app_promos' ) ) {
517 delete_option( 'wp_mobile_app_promos' );
518 }
519 }
520
521 // Upgrade to 8.4.0.
522 if ( Jetpack_Options::get_option( 'ab_connect_banner_green_bar' ) ) {
523 Jetpack_Options::delete_option( 'ab_connect_banner_green_bar' );
524 }
525
526 // Update to 8.8.x (WordPress 5.5 Compatibility).
527 if ( Jetpack_Options::get_option( 'autoupdate_plugins' ) ) {
528 $updated = update_site_option(
529 'auto_update_plugins',
530 array_unique(
531 array_merge(
532 (array) Jetpack_Options::get_option( 'autoupdate_plugins', array() ),
533 (array) get_site_option( 'auto_update_plugins', array() )
534 )
535 )
536 );
537
538 if ( $updated ) {
539 Jetpack_Options::delete_option( 'autoupdate_plugins' );
540 } // Should we have some type of fallback if something fails here?
541 }
542
543 // Set the newsletter send default option for existing sites.
544 if ( false === get_option( 'wpcom_newsletter_send_default' ) ) {
545 add_option( 'wpcom_newsletter_send_default', 1 );
546 }
547
548 // Its handler went with the Recommendations assistant.
549 wp_clear_scheduled_hook( 'jetpack_recommend_videopress' );
550
551 if ( did_action( 'wp_loaded' ) ) {
552 self::upgrade_on_load();
553 } else {
554 add_action(
555 'wp_loaded',
556 array( __CLASS__, 'upgrade_on_load' )
557 );
558 }
559 }
560 }
561 }
562
563 /**
564 * Runs upgrade routines that need to have modules loaded.
565 */
566 public static function upgrade_on_load() {
567
568 // Not attempting any upgrades if jetpack_modules_loaded did not fire.
569 // This can happen in case Jetpack has been just upgraded and is
570 // being initialized late during the page load. In this case we wait
571 // until the next proper admin page load with Jetpack active.
572 if ( ! did_action( 'jetpack_modules_loaded' ) ) {
573 delete_transient( self::$plugin_upgrade_lock_key );
574
575 return;
576 }
577
578 self::maybe_set_version_option();
579
580 if ( method_exists( 'Jetpack_Widget_Conditions', 'migrate_post_type_rules' ) ) {
581 Jetpack_Widget_Conditions::migrate_post_type_rules();
582 }
583
584 if (
585 class_exists( 'Jetpack_Sitemap_Manager' )
586 ) {
587 do_action( 'jetpack_sitemaps_purge_data' );
588 }
589
590 // Delete old stats cache.
591 delete_option( 'jetpack_restapi_stats_cache' );
592
593 delete_transient( self::$plugin_upgrade_lock_key );
594 }
595
596 /**
597 * Saves all the currently active modules to options.
598 * Also fires Action hooks for each newly activated and deactivated module.
599 *
600 * @param array $modules Array of active modules to be saved in options.
601 *
602 * @return bool $success true for success, false for failure.
603 */
604 public static function update_active_modules( $modules ) {
605 return ( new Modules() )->update_active( $modules );
606 }
607
608 /**
609 * Remove all active modules.
610 *
611 * @return void
612 */
613 public static function delete_active_modules() {
614 self::update_active_modules( array() );
615 }
616
617 /**
618 * Adds a hook to plugins_loaded at a priority that's currently the earliest
619 * available.
620 */
621 public function add_configure_hook() {
622 global $wp_filter;
623
624 $current_priority = has_filter( 'plugins_loaded', array( $this, 'configure' ) );
625 if ( false !== $current_priority ) {
626 remove_action( 'plugins_loaded', array( $this, 'configure' ), $current_priority );
627 }
628
629 $taken_priorities = array_map( 'intval', array_keys( $wp_filter['plugins_loaded']->callbacks ) );
630 sort( $taken_priorities );
631
632 $first_priority = array_shift( $taken_priorities );
633
634 if ( $first_priority <= PHP_INT_MIN ) {
635 $new_priority = PHP_INT_MIN;
636 } else {
637 $new_priority = $first_priority - 1;
638 }
639
640 add_action( 'plugins_loaded', array( $this, 'configure' ), $new_priority );
641 }
642
643 /**
644 * Constructor. Initializes WordPress hooks
645 */
646 private function __construct() {
647 /*
648 * Check for and alert any deprecated hooks
649 */
650 add_action( 'init', array( $this, 'deprecated_hooks' ) );
651
652 // Note how this runs at an earlier plugin_loaded hook intentionally to accomodate for other plugins.
653 add_action( 'plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
654 add_action( 'network_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
655 add_action( 'mu_plugin_loaded', array( $this, 'add_configure_hook' ), 90 );
656 add_action( 'plugins_loaded', array( $this, 'late_initialization' ), 90 );
657
658 /**
659 * Prepare Gutenberg Editor functionality
660 *
661 * The hooks previously here have been moved to modules/blocks.php but leaving this here pending
662 * a longer investigation to see if code is expecting the Gutenberg class to always be available.
663 */
664 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-gutenberg.php';
665 add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
666
667 add_action( 'jetpack_event_log', array( 'Jetpack', 'log' ), 10, 2 );
668
669 add_filter( 'login_url', array( $this, 'login_url' ), 10, 2 );
670 add_action( 'login_init', array( $this, 'login_init' ) );
671
672 // Set up the REST authentication hooks.
673 Connection_Rest_Authentication::init();
674
675 // Register Jetpack-specific connection tests (sync health, etc.) with the connection
676 // package's health test suite. This runs on all requests (not just admin), because
677 // the connection/test REST endpoint can be called outside admin context.
678 add_action( 'jetpack_connection_tests_loaded', array( $this, 'register_jetpack_connection_tests' ) );
679
680 add_action( 'admin_init', array( $this, 'admin_init' ) );
681 add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
682
683 add_filter( 'admin_body_class', array( $this, 'admin_body_class' ), 20 );
684
685 // Filter the dashboard meta box order to swap the new one in in place of the old one.
686 add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
687
688 // WordPress dashboard widget.
689 require_once JETPACK__PLUGIN_DIR . 'class-jetpack-stats-dashboard-widget.php';
690 add_action( 'wp_dashboard_setup', array( new Jetpack_Stats_Dashboard_Widget(), 'init' ) );
691
692 // Returns HTTPS support status.
693 add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
694
695 add_action( 'wp_loaded', array( $this, 'register_assets' ) );
696
697 /**
698 * These actions run checks to load additional files.
699 * They check for external files or plugins, so they need to run as late as possible.
700 */
701 add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
702 add_action( 'web_stories_story_head', array( $this, 'check_open_graph' ), 1 );
703 add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
704 add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
705
706 add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
707 add_action( 'style_loader_src', array( 'Jetpack', 'set_suffix_on_min' ), 10, 2 );
708
709 add_filter( 'profile_update', array( 'Jetpack', 'user_meta_cleanup' ) );
710
711 add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
712 add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
713
714 add_action(
715 'plugins_loaded',
716 function () {
717 if ( User_Agent_Info::is_mobile_app() ) {
718 add_filter( 'get_edit_post_link', '__return_empty_string' );
719 }
720 }
721 );
722
723 // Update the site's Jetpack plan and products from API on heartbeats.
724 add_action( 'jetpack_heartbeat', array( Jetpack_Plan::class, 'refresh_from_wpcom' ) );
725
726 // The Connection package fetches the site record for `jetpack/v4/site`; reuse it to refresh the plan.
727 add_action( 'jetpack_site_data_fetched', array( Jetpack_Plan::class, 'update_from_site_record' ) );
728
729 // Actually push the stats on shutdown.
730 if ( ! has_action( 'shutdown', array( $this, 'push_stats' ) ) ) {
731 add_action( 'shutdown', array( $this, 'push_stats' ) );
732 }
733
734 // After a successful connection.
735 add_action( 'jetpack_site_registered', array( $this, 'activate_default_modules_on_site_register' ) );
736 add_action( 'jetpack_site_registered', array( $this, 'handle_unique_registrations_stats' ) );
737 add_action( 'jetpack_site_registered', array( Reader_Link::class, 'activate_on_connection' ), 9 );
738 add_action( 'jetpack_site_registered', array( \Automattic\Jetpack\Reprint_Export\Reprint_Exporter::class, 'discard_credentials' ) );
739
740 // Actions for Manager::authorize().
741 add_action( 'jetpack_authorize_starting', array( $this, 'authorize_starting' ) );
742 add_action( 'jetpack_authorize_ending_linked', array( $this, 'authorize_ending_linked' ) );
743 add_action( 'jetpack_authorize_ending_authorized', array( $this, 'authorize_ending_authorized' ) );
744
745 Jetpack_Client_Server::init();
746 add_action( 'jetpack_client_authorize_error', array( Jetpack_Client_Server::class, 'client_authorize_error' ) );
747 add_filter( 'jetpack_client_authorize_already_authorized_url', array( Jetpack_Client_Server::class, 'client_authorize_already_authorized_url' ) );
748 add_action( 'jetpack_client_authorize_processing', array( Jetpack_Client_Server::class, 'client_authorize_processing' ) );
749 add_filter( 'jetpack_client_authorize_fallback_url', array( Jetpack_Client_Server::class, 'client_authorize_fallback_url' ) );
750
751 // Filters for the Manager::get_token() urls and request body.
752 add_filter( 'jetpack_token_redirect_url', array( Authorize_Redirect::class, 'filter_connect_redirect_url' ) );
753 add_filter( 'jetpack_token_request_body', array( __CLASS__, 'filter_token_request_body' ) );
754
755 // Filter for the `jetpack/v4/connection/data` API response.
756 add_filter( 'jetpack_current_user_connection_data', array( __CLASS__, 'filter_jetpack_current_user_connection_data' ) );
757
758 // Actions for successful reconnect.
759 add_action( 'jetpack_reconnection_completed', array( $this, 'reconnection_completed' ) );
760
761 // Actions for successful disconnect.
762 add_action( 'jetpack_site_disconnected', array( $this, 'jetpack_site_disconnected' ) );
763
764 // Actions for licensing.
765 Licensing::instance()->initialize();
766
767 // Filters for Sync Callables.
768 add_filter( 'jetpack_sync_callable_whitelist', array( $this, 'filter_sync_callable_whitelist' ), 10, 1 );
769 add_filter( 'jetpack_sync_multisite_callable_whitelist', array( $this, 'filter_sync_multisite_callable_whitelist' ), 10, 1 );
770
771 // Make resources use static domain when possible.
772 add_filter( 'jetpack_static_url', array( 'Automattic\\Jetpack\\Assets', 'staticize_subdomain' ) );
773
774 // Validate the domain names in Jetpack development versions.
775 add_action( 'jetpack_pre_register', array( static::class, 'registration_check_domains' ) );
776
777 // Register product descriptions for partner coupon usage.
778 add_filter( 'jetpack_partner_coupon_products', array( $this, 'get_partner_coupon_product_descriptions' ) );
779
780 // Add 5-star
781 add_filter( 'plugin_row_meta', array( $this, 'add_5_star_review_link' ), 10, 2 );
782 add_action( 'init', array( Deprecate::class, 'instance' ) );
783
784 // Register Jetpack module management abilities (WordPress Abilities API, WP 6.9+).
785 \Automattic\Jetpack\Plugin\Abilities\Modules_Abilities::init();
786
787 // Register Connection abilities (WordPress Abilities API, WP 6.9+). Scoped to the
788 // Jetpack plugin for now: the Connection package no longer auto-wires these, so
789 // connection-only consumers (Boost, Protect, Search, etc.) do not register them yet.
790 \Automattic\Jetpack\Connection\Abilities\Connection_Abilities::init();
791 }
792
793 /**
794 * Whether the current request should eagerly initialize the admin/REST-only
795 * packages (the Import package and My Jetpack) now, at `plugins_loaded` time.
796 *
797 * Returns true for admin, cron, POST, and WP-CLI requests — the contexts,
798 * knowable this early, where those packages have work to do. Returns false
799 * for a plain front-end GET *and* for a REST request: the two can't be told
800 * apart yet (this runs before `rest_api_init`), so callers defer the REST
801 * case by initializing the package on `rest_api_init` instead, while a plain
802 * page view never fires that hook and so loads nothing. This keeps
803 * admin/REST-only PHP out of opcache on the front-end GET hot path.
804 *
805 * No in-repo code depends on the deferral. The one externally observable
806 * change is timing: the packages' documented init hooks
807 * (`jetpack_import_initialized`, `jetpack_feature_import_enabled`, and
808 * `my_jetpack_init`) no longer fire on a plain front-end GET — they fire on
809 * the admin, cron, POST, WP-CLI, and REST requests where the packages load.
810 *
811 * @return bool
812 */
813 private static function should_eager_load_packages() {
814 $is_post_request = isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) );
815 $is_wp_cli = Constants::is_true( 'WP_CLI' );
816
817 return is_admin() || wp_doing_cron() || $is_post_request || $is_wp_cli;
818 }
819
820 /**
821 * Configure the Import package from a deferred hook.
822 *
823 * The eager path uses Config::ensure( 'import' ), but the deferred REST path
824 * runs after Config::on_plugins_loaded() has already processed its feature
825 * flags, so it needs a hookable bootstrap callback. Preserve Config's
826 * feature-enabled action for hook consumers.
827 *
828 * @since 16.0
829 *
830 * @return void
831 */
832 public static function configure_import_package() {
833 if ( class_exists( Import_Main::class ) ) {
834 Import_Main::configure();
835
836 if ( ! did_action( 'jetpack_feature_import_enabled' ) ) {
837 do_action( 'jetpack_feature_import_enabled' );
838 }
839 }
840 }
841
842 /**
843 * Whether the bundled Stats v2 dashboard is enabled.
844 *
845 * Stats v2 (formerly "Premium Analytics") ships with the plugin behind this
846 * flag while it rolls out (WOOA7S-1595). When enabled it adds its own admin
847 * menu alongside the existing Stats UI; it never replaces or hides the
848 * legacy Stats menu, admin-bar entries, post-list column, or WP dashboard
849 * widget. The Stats module's tracking is unaffected either way, and Stats v2
850 * reads what that module collects, so while the module is off the plugin
851 * answers false here before even reading the flag.
852 *
853 * The package has to be loadable for this to be true, so a site with the
854 * flag on but a missing package answers false here and never adds the
855 * Stats v2 menu (a warning is logged instead).
856 *
857 * @since 16.1
858 *
859 * @return bool
860 */
861 public static function is_premium_analytics_enabled() {
862 if ( null !== self::$premium_analytics_enabled ) {
863 return self::$premium_analytics_enabled;
864 }
865
866 if ( ! self::is_module_active( 'stats' ) ) {
867 self::$premium_analytics_enabled = false;
868 return false;
869 }
870
871 /**
872 * Filters whether the bundled Premium Analytics dashboard is enabled.
873 *
874 * Resolved once, from `Jetpack::configure()` on `plugins_loaded`, and only
875 * while the Stats module is active. Register this from a mu-plugin or a
876 * plugin's main file — a callback added on `plugins_loaded` or later runs
877 * too late to be seen.
878 *
879 * @since 16.1
880 *
881 * @param bool $enabled Defaults to the `jetpack_premium_analytics_enabled` option (false).
882 */
883 $flag = (bool) apply_filters( 'jetpack_premium_analytics_enabled', (bool) get_option( 'jetpack_premium_analytics_enabled' ) );
884
885 self::$premium_analytics_enabled = $flag && class_exists( 'Automattic\Jetpack\PremiumAnalytics\Analytics' );
886
887 if ( $flag && ! self::$premium_analytics_enabled ) {
888 wp_trigger_error(
889 __METHOD__,
890 'The jetpack_premium_analytics_enabled flag is on but the Premium Analytics package is not loadable; keeping the Stats UI in place.'
891 );
892 }
893
894 return self::$premium_analytics_enabled;
895 }
896
897 /**
898 * Expose the setting that turns the Premium Analytics dashboard on and off.
899 *
900 * Deliberately not behind is_premium_analytics_enabled(): this is the setting that flips that
901 * check, so it has to answer while the dashboard is still off.
902 *
903 * @since 16.2
904 *
905 * @return void
906 */
907 public static function register_premium_analytics_enablement_setting() {
908 if ( class_exists( 'Automattic\Jetpack\PremiumAnalytics\Enablement_Setting' ) ) {
909 \Automattic\Jetpack\PremiumAnalytics\Enablement_Setting::register();
910 }
911 }
912
913 /**
914 * Before everything else starts getting initalized, we need to initialize Jetpack using the
915 * Config object.
916 */
917 public function configure() {
918 $config = new Config();
919
920 foreach (
921 array(
922 'jitm',
923 'sync',
924 'account_protection',
925 'waf',
926 )
927 as $feature
928 ) {
929 $config->ensure( $feature );
930 }
931
932 // Enable the VideoPress admin UI (the "Jetpack > VideoPress" dashboard) inside the
933 // Jetpack plugin, mirroring the standalone Jetpack VideoPress plugin. The dashboard
934 // only renders when the VideoPress module is active (Status::is_active()); when it
935 // is not, the menu item links to the My Jetpack interstitial to activate it.
936 $config->ensure( 'videopress', array( 'admin_ui' => true ) );
937
938 /*
939 * The Import package only registers `jetpack/v4/import` REST routes — it
940 * does nothing when rendering a front-end page — so gate its `ensure()`
941 * to keep its PHP out of opcache on the front-end GET hot path. It still
942 * loads on admin, cron, POST, and WP-CLI requests, and on `rest_api_init`
943 * for REST: a REST request can't be identified yet at `plugins_loaded`
944 * (this runs before `Config::on_plugins_loaded`, and `rest_api_init`
945 * fires later), so it is initialized directly when that hook fires, while
946 * a plain page view never fires it and so loads nothing.
947 *
948 * JITM stays eager (above): unlike Import, its `register()` adds a
949 * `jetpack_sync_before_send_updated_option` filter that records the
950 * `jetpack_last_plugin_sync` transient, and a Jetpack Sync send can fire
951 * on a plain front-end GET — including the dedicated-sync `spawn-sync`
952 * GET, which runs on `init` and exits before `rest_api_init`. Deferring
953 * JITM would skip that bookkeeping and leave its message cache stale after
954 * a plugin change, so it loads on every request as before.
955 */
956 if ( self::should_eager_load_packages() ) {
957 $config->ensure( 'import' );
958 } else {
959 add_action(
960 'rest_api_init',
961 array( __CLASS__, 'configure_import_package' ),
962 0
963 );
964 }
965
966 /*
967 * The Stats and Stats Admin packages only do work when the Stats module
968 * is active (the front-end tracking pixel) or on wp-admin, REST, cron,
969 * POST, and WP-CLI requests: the Stats dashboard page, the stats /
970 * stats-app REST endpoints (which the block editor also calls for
971 * email-open rates), the transient-cleanup cron, the connection
972 * package's package-version tracker (which runs on POSTs and reads the
973 * `jetpack_package_versions` filter that Stats registers), and CLI
974 * introspection such as the heartbeat inspector. On a plain front-end
975 * GET page view with the module off they are inert: the pixel
976 * short-circuits on `Stats\Main::should_track()` and every other entry
977 * point only hooks rest_api_init, admin, cron, the POST-only tracker, or
978 * is reached through WP-CLI.
979 * Skip loading them — and eagerly constructing the Stats Admin REST
980 * controller — on that hot path to keep their PHP out of opcache, but
981 * keep loading them everywhere else exactly as before so the stats REST
982 * permission mapping (view_stats, registered by Stats\Main), the
983 * editor's stats-app calls, the cleanup cron, and the package-version
984 * tracker are all unchanged.
985 *
986 * REST requests are not yet identifiable here (REST_REQUEST is defined
987 * after plugins_loaded), so defer those to rest_api_init. Call the
988 * package initializers directly rather than `$config->ensure()`: ensure()
989 * only flags a feature for `Config::on_plugins_loaded()` (plugins_loaded
990 * priority 2), which has already run by the time rest_api_init fires.
991 * Priority 0 runs before each package's own priority-10 route
992 * registration, so their routes still register within the same dispatch.
993 * A plain page view never fires rest_api_init, so the packages stay
994 * unloaded there. See JETPACK-1747.
995 */
996 $is_post_request = isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' === $_SERVER['REQUEST_METHOD'];
997 $is_wp_cli = defined( 'WP_CLI' ) && WP_CLI;
998
999 if ( self::is_module_active( 'stats' ) || is_admin() || wp_doing_cron() || $is_post_request || $is_wp_cli ) {
1000 $config->ensure( 'stats' );
1001 $config->ensure( 'stats_admin' );
1002 } else {
1003 add_action(
1004 'rest_api_init',
1005 static function () {
1006 if ( class_exists( 'Automattic\Jetpack\Stats\Main' ) ) {
1007 \Automattic\Jetpack\Stats\Main::init();
1008 }
1009 if ( class_exists( 'Automattic\Jetpack\Stats_Admin\Main' ) ) {
1010 \Automattic\Jetpack\Stats_Admin\Main::init();
1011 }
1012 },
1013 0
1014 );
1015 }
1016
1017 // Stats v2 (WOOA7S-1595). Unlike Stats above it cannot be deferred when enabled — see
1018 // Analytics::init() for why, and for why it takes no menu_title here.
1019 if ( self::is_premium_analytics_enabled() ) {
1020 \Automattic\Jetpack\PremiumAnalytics\Analytics::init();
1021 }
1022
1023 // Outside the check above on purpose — see Enablement_Setting. Deferred like Stats, to keep
1024 // the autoload off the front-end hot path.
1025 add_action( 'rest_api_init', array( __CLASS__, 'register_premium_analytics_enablement_setting' ), 0 );
1026
1027 $config->ensure(
1028 'connection',
1029 array(
1030 'slug' => 'jetpack',
1031 'name' => 'Jetpack',
1032 )
1033 );
1034
1035 // Identity crisis package.
1036 $config->ensure(
1037 'identity_crisis',
1038 array(
1039 'slug' => 'jetpack',
1040 'admin_page' => '/wp-admin/admin.php?page=jetpack',
1041 )
1042 );
1043
1044 $config->ensure( 'search' );
1045
1046 if ( ! $this->connection_manager ) {
1047 $this->connection_manager = new Connection_Manager( 'jetpack' );
1048 }
1049
1050 $modules = new Automattic\Jetpack\Modules();
1051 if ( $modules->is_active( 'publicize' ) && $this->connection_manager->has_connected_user() ) {
1052 $config->ensure( 'publicize' );
1053 }
1054
1055 add_action( 'jetpack_initialize_tracking', array( $this, 'initialize_tracking' ) );
1056
1057 /*
1058 * Load things that should only be in Network Admin.
1059 *
1060 * For now blow away everything else until a more full
1061 * understanding of what is needed at the network level is
1062 * available
1063 */
1064 if ( is_multisite() ) {
1065 $network = Jetpack_Network::init();
1066 $network->set_connection( $this->connection_manager );
1067 }
1068
1069 $is_connection_ready = self::is_connection_ready();
1070
1071 if ( $is_connection_ready ) {
1072 add_action( 'login_form_jetpack_json_api_authorization', array( $this, 'login_form_json_api_authorization' ) );
1073 $this->run_initialize_tracking_action();
1074
1075 Jetpack_Heartbeat::init();
1076 if ( self::is_module_active( 'stats' ) && self::is_module_active( 'search' ) ) {
1077 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-search-performance-logger.php';
1078 Jetpack_Search_Performance_Logger::init();
1079 }
1080 } else {
1081 add_action( 'jetpack_agreed_to_terms_of_service', array( $this, 'run_initialize_tracking_action' ) );
1082 add_action( 'rest_api_init', array( $this, 'run_initialize_tracking_action' ) );
1083 add_filter(
1084 'xmlrpc_methods',
1085 function ( $methods ) {
1086 $this->run_initialize_tracking_action();
1087 return $methods;
1088 },
1089 1
1090 );
1091 }
1092
1093 // Initialize remote file upload request handlers.
1094 $this->add_remote_request_handlers();
1095
1096 /*
1097 * Enable enhanced handling of previewing sites in Calypso
1098 */
1099 if ( $is_connection_ready ) {
1100 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.jetpack-iframe-embed.php';
1101 add_action( 'init', array( 'Jetpack_Iframe_Embed', 'init' ), 9, 0 );
1102 add_action( 'rest_api_init', array( $this, 'maybe_initialize_rest_jsonapi' ) );
1103 }
1104 }
1105
1106 /**
1107 * Runs on plugins_loaded. Use this to add code that needs to be executed later than other
1108 * initialization code.
1109 *
1110 * @action plugins_loaded
1111 */
1112 public function late_initialization() {
1113 add_action( 'after_setup_theme', array( 'Jetpack', 'load_modules' ), -2 );
1114
1115 /*
1116 * My Jetpack is a wp-admin dashboard. Its Initializer::init() only wires
1117 * up admin-menu, admin_init, and rest_api_init surfaces — and eagerly
1118 * loads every product class (backup, boost, protect, …) just to register
1119 * admin plugin-action links — so none of it is needed on a plain
1120 * front-end GET page view. (The pieces that do immediate work, e.g.
1121 * Connection REST authentication and Licensing, are already initialized
1122 * unconditionally in Jetpack's constructor, so they are unaffected here.)
1123 *
1124 * Gate the call to the request types where My Jetpack actually does work.
1125 * REST can't be detected yet at plugins_loaded, so initialize on
1126 * rest_api_init for that branch; a plain page view never fires it, so My
1127 * Jetpack stays unloaded there.
1128 */
1129 if ( self::should_eager_load_packages() ) {
1130 My_Jetpack_Initializer::init();
1131 } else {
1132 add_action( 'rest_api_init', array( My_Jetpack_Initializer::class, 'init' ), 0 );
1133 }
1134
1135 Scan_Page_Init::initialize();
1136 Jetpack_SEO_Initializer::init();
1137
1138 if ( ( new Modules() )->is_active( 'podcast' ) ) {
1139 Podcast::init();
1140 }
1141
1142 /*
1143 * Initialize Boost Speed Score. It only does work on REST requests (the
1144 * dashboard speed-score endpoints) and on a few Jetpack Boost lifecycle
1145 * actions, so defer constructing it — and loading the boost-speed-score
1146 * package classes — until one of those hooks actually fires instead of on
1147 * every request. Priority 0 ensures the object's own callbacks (added in
1148 * its constructor at the default priority) still run for the firing hook.
1149 */
1150 $initialize_speed_score = static function () {
1151 static $initialized = false;
1152 if ( $initialized ) {
1153 return;
1154 }
1155 $initialized = true;
1156 new Speed_Score( array(), 'jetpack-dashboard' );
1157 };
1158 add_action( 'rest_api_init', $initialize_speed_score, 0 );
1159 add_action( 'jetpack_boost_deactivate', $initialize_speed_score, 0 );
1160 add_action( 'jetpack_boost_environment_changed', $initialize_speed_score, 0 );
1161 add_action( 'handle_environment_change', $initialize_speed_score, 0 );
1162
1163 /**
1164 * Fires when Jetpack is fully loaded and ready. This is the point where it's safe
1165 * to instantiate classes from packages and namespaces that are managed by the Jetpack Autoloader.
1166 *
1167 * @since 8.1.0
1168 *
1169 * @param Jetpack $jetpack the main plugin class object.
1170 */
1171 do_action( 'jetpack_loaded', $this );
1172
1173 add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 2 );
1174 }
1175
1176 /**
1177 * This is ported over from the manage module, which has been deprecated and baked in here.
1178 */
1179 public function add_wpcom_to_allowed_redirect_hosts() {
1180 add_filter( 'allowed_redirect_hosts', array( $this, 'allow_wpcom_domain' ) );
1181 }
1182
1183 /**
1184 * Return $domains, with 'wordpress.com' appended.
1185 * This is ported over from the manage module, which has been deprecated and baked in here.
1186 *
1187 * @param array $domains Array of domains allowed for redirect.
1188 *
1189 * @return array
1190 */
1191 public function allow_wpcom_domain( $domains ) {
1192 if ( empty( $domains ) ) {
1193 $domains = array();
1194 }
1195 $domains[] = 'wordpress.com';
1196 return array_unique( $domains );
1197 }
1198
1199 /**
1200 * Redirect edit post links to Calypso.
1201 *
1202 * @deprecated since 13.9
1203 *
1204 * @param string $default_url Post edit URL.
1205 * @param int $post_id Post ID.
1206 *
1207 * @return string
1208 */
1209 public function point_edit_post_links_to_calypso( $default_url, $post_id ) {
1210 _deprecated_function( __METHOD__, '13.9' );
1211
1212 $post = get_post( $post_id );
1213
1214 if ( empty( $post ) ) {
1215 return $default_url;
1216 }
1217
1218 $post_type = $post->post_type;
1219
1220 // Mapping the allowed CPTs on WordPress.com to corresponding paths in Calypso.
1221 // https://en.support.wordpress.com/custom-post-types/.
1222 $allowed_post_types = array(
1223 'post',
1224 'page',
1225 'jetpack-portfolio',
1226 'jetpack-testimonial',
1227 );
1228
1229 if ( ! in_array( $post_type, $allowed_post_types, true ) ) {
1230 return $default_url;
1231 }
1232
1233 return Redirect::get_url(
1234 'calypso-edit-' . $post_type,
1235 array(
1236 'path' => $post_id,
1237 )
1238 );
1239 }
1240
1241 /**
1242 * Redirect edit comment links to Calypso.
1243 *
1244 * @deprecated since 13.9
1245 *
1246 * @param string $url Comment edit URL.
1247 *
1248 * @return string
1249 */
1250 public function point_edit_comment_links_to_calypso( $url ) {
1251 _deprecated_function( __METHOD__, '13.9' );
1252
1253 // Take the `query` key value from the URL, and parse its parts to the $query_args. `amp;c` matches the comment ID.
1254 $query_args = null;
1255 wp_parse_str( wp_parse_url( $url, PHP_URL_QUERY ), $query_args );
1256
1257 return Redirect::get_url(
1258 'calypso-edit-comment',
1259 array(
1260 'path' => $query_args['amp;c'],
1261 )
1262 );
1263 }
1264
1265 /**
1266 * Extend Sync callables with Jetpack Plugin functions.
1267 *
1268 * @param array $callables list of callables.
1269 *
1270 * @return array list of callables.
1271 */
1272 public function filter_sync_callable_whitelist( $callables ) {
1273 // Jetpack Functions.
1274 $jetpack_callables = array(
1275 'single_user_site' => array( 'Jetpack', 'is_single_user_site' ),
1276 'updates' => array( 'Jetpack', 'get_updates' ),
1277 'available_jetpack_blocks' => array( 'Jetpack_Gutenberg', 'get_availability' ), // Includes both Gutenberg blocks *and* plugins.
1278 'theme_styles' => array( 'Automattic\\Jetpack\\Plugin\\Theme_Styles_Sync', 'get_theme_styles' ),
1279 );
1280 return array_merge( $callables, $jetpack_callables );
1281 }
1282
1283 /**
1284 * Extend Sync multisite callables with Jetpack Plugin functions.
1285 *
1286 * @param array $callables list of callables.
1287 *
1288 * @return array list of callables.
1289 */
1290 public function filter_sync_multisite_callable_whitelist( $callables ) {
1291
1292 // Jetpack Funtions.
1293 $jetpack_multisite_callables = array(
1294 'network_name' => array( 'Jetpack', 'network_name' ),
1295 'network_allow_new_registrations' => array( 'Jetpack', 'network_allow_new_registrations' ),
1296 'network_add_new_users' => array( 'Jetpack', 'network_add_new_users' ),
1297 'network_site_upload_space' => array( 'Jetpack', 'network_site_upload_space' ),
1298 'network_upload_file_types' => array( 'Jetpack', 'network_upload_file_types' ),
1299 'network_enable_administration_menus' => array( 'Jetpack', 'network_enable_administration_menus' ),
1300 );
1301 $callables = array_merge( $callables, $jetpack_multisite_callables );
1302
1303 return $callables;
1304 }
1305
1306 /**
1307 * If there are any stats that need to be pushed, but haven't been, push them now.
1308 */
1309 public function push_stats() {
1310 if ( ! empty( $this->stats ) ) {
1311 $this->do_stats( 'server_side' );
1312 }
1313 }
1314
1315 /**
1316 * Sets the Jetpack custom capabilities.
1317 *
1318 * @param string[] $caps Array of the user's capabilities.
1319 * @param string $cap Capability name.
1320 */
1321 public function jetpack_custom_caps( $caps, $cap ) {
1322 switch ( $cap ) {
1323 case 'jetpack_manage_autoupdates':
1324 $caps = array(
1325 'manage_options',
1326 'update_plugins',
1327 );
1328 break;
1329 case 'jetpack_network_admin_page':
1330 case 'jetpack_network_settings_page':
1331 $caps = array( 'manage_network_plugins' );
1332 break;
1333 case 'jetpack_network_sites_page':
1334 $caps = array( 'manage_sites' );
1335 break;
1336 case 'jetpack_admin_page':
1337 $is_offline_mode = ( new Status() )->is_offline_mode();
1338 if ( $is_offline_mode ) {
1339 $caps = array( 'manage_options' );
1340 break;
1341 } else {
1342 $caps = array( 'edit_posts' );
1343 }
1344 break;
1345 }
1346 return $caps;
1347 }
1348
1349 /**
1350 * Register assets for use in various modules and the Jetpack admin page.
1351 *
1352 * @uses wp_script_is, wp_register_script, plugins_url
1353 * @action wp_loaded
1354 * @return void
1355 */
1356 public function register_assets() {
1357 if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
1358 wp_register_script(
1359 'jetpack-gallery-settings',
1360 Assets::get_file_url_for_environment( '_inc/build/gallery-settings.min.js', '_inc/gallery-settings.js' ),
1361 array( 'media-views' ),
1362 '20121225',
1363 true
1364 );
1365 }
1366
1367 if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
1368 wp_register_script(
1369 'jetpack-twitter-timeline',
1370 Assets::get_file_url_for_environment( '_inc/build/twitter-timeline.min.js', '_inc/twitter-timeline.js' ),
1371 array(),
1372 '4.0.0',
1373 true
1374 );
1375 }
1376
1377 if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
1378 wp_register_script(
1379 'jetpack-facebook-embed',
1380 Assets::get_file_url_for_environment( '_inc/build/facebook-embed.min.js', '_inc/facebook-embed.js' ),
1381 array(),
1382 JETPACK__VERSION,
1383 true
1384 );
1385
1386 /** This filter is documented in modules/sharedaddy/sharing-sources.php */
1387 $fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
1388 if ( ! is_numeric( $fb_app_id ) ) {
1389 $fb_app_id = '';
1390 }
1391 wp_localize_script(
1392 'jetpack-facebook-embed',
1393 'jpfbembed',
1394 array(
1395 'appid' => $fb_app_id,
1396 'locale' => $this->get_locale(),
1397 )
1398 );
1399 }
1400
1401 /**
1402 * As jetpack_register_genericons is by default fired off a hook,
1403 * the hook may have already fired by this point.
1404 * So, let's just trigger it manually.
1405 */
1406 require_once JETPACK__PLUGIN_DIR . '_inc/genericons.php';
1407 jetpack_register_genericons();
1408
1409 /**
1410 * Register the social logos
1411 */
1412 require_once JETPACK__PLUGIN_DIR . '_inc/social-logos.php';
1413 jetpack_register_social_logos();
1414 }
1415
1416 /**
1417 * Guess locale from language code.
1418 *
1419 * @param string $lang Language code.
1420 * @return string|bool
1421 */
1422 public function guess_locale_from_lang( $lang ) {
1423 if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
1424 return 'en_US';
1425 }
1426
1427 if ( ! class_exists( 'GP_Locales' ) ) {
1428 if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
1429 return false;
1430 }
1431
1432 require JETPACK__GLOTPRESS_LOCALES_PATH;
1433 }
1434
1435 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
1436 // WP.com: get_locale() returns 'it'.
1437 $locale = GP_Locales::by_slug( $lang );
1438 } else {
1439 // Jetpack: get_locale() returns 'it_IT';.
1440 $locale = GP_Locales::by_field( 'facebook_locale', $lang );
1441 }
1442
1443 if ( ! $locale ) {
1444 return false;
1445 }
1446
1447 if ( empty( $locale->facebook_locale ) ) {
1448 if ( empty( $locale->wp_locale ) ) {
1449 return false;
1450 } else {
1451 // Facebook SDK is smart enough to fall back to en_US if a
1452 // locale isn't supported. Since supported Facebook locales
1453 // can fall out of sync, we'll attempt to use the known
1454 // wp_locale value and rely on said fallback.
1455 return $locale->wp_locale;
1456 }
1457 }
1458
1459 return $locale->facebook_locale;
1460 }
1461
1462 /**
1463 * Get the locale.
1464 *
1465 * @return string|bool
1466 */
1467 public function get_locale() {
1468 $locale = $this->guess_locale_from_lang( get_locale() );
1469
1470 if ( ! $locale ) {
1471 $locale = 'en_US';
1472 }
1473
1474 return $locale;
1475 }
1476
1477 /**
1478 * Return the network_site_url so that .com knows what network this site is a part of.
1479 *
1480 * @return string
1481 */
1482 public function jetpack_main_network_site_option() {
1483 return network_site_url();
1484 }
1485 /**
1486 * Network Name.
1487 */
1488 public static function network_name() {
1489 global $current_site;
1490 return $current_site->site_name;
1491 }
1492 /**
1493 * Does the network allow new user and site registrations.
1494 *
1495 * @return string
1496 */
1497 public static function network_allow_new_registrations() {
1498 return ( in_array( get_site_option( 'registration' ), array( 'none', 'user', 'blog', 'all' ), true ) ? get_site_option( 'registration' ) : 'none' );
1499 }
1500 /**
1501 * Does the network allow admins to add new users.
1502 *
1503 * @return bool
1504 */
1505 public static function network_add_new_users() {
1506 return (bool) get_site_option( 'add_new_users' );
1507 }
1508 /**
1509 * File upload psace left per site in MB.
1510 * -1 means NO LIMIT.
1511 *
1512 * @return int
1513 */
1514 public static function network_site_upload_space() {
1515 // value in MB.
1516 return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
1517 }
1518
1519 /**
1520 * Network allowed file types.
1521 *
1522 * @return string
1523 */
1524 public static function network_upload_file_types() {
1525 return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
1526 }
1527
1528 /**
1529 * Maximum file upload size set by the network.
1530 *
1531 * @return int
1532 */
1533 public static function network_max_upload_file_size() {
1534 // value in KB.
1535 return get_site_option( 'fileupload_maxk', 300 );
1536 }
1537
1538 /**
1539 * Lets us know if a site allows admins to manage the network.
1540 *
1541 * @return array
1542 */
1543 public static function network_enable_administration_menus() {
1544 return get_site_option( 'menu_items' );
1545 }
1546
1547 /**
1548 * If a user has been promoted to or demoted from admin, we need to clear the
1549 * jetpack_other_linked_admins transient.
1550 *
1551 * @since 4.3.2
1552 * @since 4.4.0 $old_roles is null by default and if it's not passed, the transient is cleared.
1553 *
1554 * @param int $user_id The user ID whose role changed.
1555 * @param string $role The new role.
1556 * @param array $old_roles An array of the user's previous roles.
1557 */
1558 public function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
1559 if ( 'administrator' === $role
1560 || ( is_array( $old_roles ) && in_array( 'administrator', $old_roles, true ) )
1561 || $old_roles === null
1562 ) {
1563 delete_transient( 'jetpack_other_linked_admins' );
1564 }
1565 }
1566
1567 /**
1568 * Checks to see if there are any other users available to become primary
1569 * Users must both:
1570 * - Be linked to wpcom
1571 * - Be an admin
1572 *
1573 * @return mixed False if no other users are linked, Int if there are.
1574 */
1575 public static function get_other_linked_admins() {
1576 $other_linked_users = get_transient( 'jetpack_other_linked_admins' );
1577
1578 if ( false === $other_linked_users ) {
1579 $admins = get_users( array( 'role' => 'administrator' ) );
1580 if ( count( $admins ) > 1 ) {
1581 $available = array();
1582 foreach ( $admins as $admin ) {
1583 if ( self::connection()->is_user_connected( $admin->ID ) ) {
1584 $available[] = $admin->ID;
1585 }
1586 }
1587
1588 $count_connected_admins = count( $available );
1589 if ( count( $available ) > 1 ) {
1590 $other_linked_users = $count_connected_admins;
1591 } else {
1592 $other_linked_users = 0;
1593 }
1594 } else {
1595 $other_linked_users = 0;
1596 }
1597
1598 set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
1599 }
1600
1601 return ( 0 === $other_linked_users ) ? false : $other_linked_users;
1602 }
1603
1604 /**
1605 * Return whether we are dealing with a multi network setup or not.
1606 * The reason we are type casting this is because we want to avoid the situation where
1607 * the result is false since when is_main_network_option return false it cases
1608 * the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
1609 * database which could be set to anything as opposed to what this function returns.
1610 *
1611 * @return boolean
1612 */
1613 public function is_main_network_option() {
1614 // returns either an '1' or an empty string.
1615 return (string) (bool) self::is_multi_network();
1616 }
1617
1618 /**
1619 * Return true if we are with multi-site or multi-network false if we are dealing with single site.
1620 *
1621 * @return string
1622 */
1623 public function is_multisite() {
1624 return (string) (bool) is_multisite();
1625 }
1626
1627 /**
1628 * Implemented since there is no core is multi network function
1629 * Right now there is no way to tell if we which network is the dominant network on the system
1630 *
1631 * @since 3.3
1632 * @return boolean
1633 */
1634 public static function is_multi_network() {
1635 global $wpdb;
1636
1637 // if we don't have a multi site setup no need to do any more.
1638 if ( ! is_multisite() ) {
1639 return false;
1640 }
1641
1642 $num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
1643 if ( $num_sites > 1 ) {
1644 return true;
1645 } else {
1646 return false;
1647 }
1648 }
1649
1650 /**
1651 * Get back if the current site is single user site.
1652 *
1653 * @return bool
1654 */
1655 public static function is_single_user_site() {
1656 global $wpdb;
1657
1658 $some_users = get_transient( 'jetpack_is_single_user' );
1659 if ( false === $some_users ) {
1660 $some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
1661 set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
1662 }
1663 return 1 === (int) $some_users;
1664 }
1665
1666 /**
1667 * Returns true if the site has file write access false otherwise.
1668 *
1669 * @return string ( '1' | '0' )
1670 **/
1671 public static function file_system_write_access() {
1672 if ( ! function_exists( 'get_filesystem_method' ) ) {
1673 require_once ABSPATH . 'wp-admin/includes/file.php';
1674 }
1675
1676 require_once ABSPATH . 'wp-admin/includes/template.php';
1677
1678 $filesystem_method = get_filesystem_method();
1679 if ( 'direct' === $filesystem_method ) {
1680 return 1;
1681 }
1682
1683 ob_start();
1684 $filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
1685 ob_end_clean();
1686 if ( $filesystem_credentials_are_stored ) {
1687 return 1;
1688 }
1689 return 0;
1690 }
1691
1692 // phpcs:disable WordPress.WP.CapitalPDangit.MisspelledInComment
1693 /**
1694 * Gets updates and stores in jetpack_updates.
1695 *
1696 * The jetpack_updates option is saved in the following schema:
1697 *
1698 * array (
1699 * 'plugins' => (int) Number of plugin updates available.
1700 * 'themes' => (int) Number of theme updates available.
1701 * 'wordpress' => (int) Number of WordPress core updates available.
1702 * 'translations' => (int) Number of translation updates available.
1703 * 'total' => (int) Total of all available updates.
1704 * 'wp_update_version' => (string) The latest available version of WordPress, only present if a WordPress update is needed.
1705 * )
1706 *
1707 * @return array
1708 */
1709 public static function get_updates() {
1710 $updates = array();
1711 $update_data = wp_get_update_data();
1712
1713 // Stores the individual update counts as well as the total count.
1714 if ( isset( $update_data['counts'] ) ) {
1715 $updates = $update_data['counts'];
1716 }
1717
1718 // If we need to update WordPress core, let's find the latest version number.
1719 if ( ! empty( $updates['wordpress'] ) ) {
1720 $cur = get_preferred_from_update_core();
1721 if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
1722 $updates['wp_update_version'] = $cur->current;
1723 }
1724 }
1725 return $updates;
1726 }
1727 // phpcs:enable WordPress.WP.CapitalPDangit.MisspelledInComment
1728
1729 /**
1730 * Get update details for core, plugins, and themes.
1731 *
1732 * @return array
1733 */
1734 public static function get_update_details() {
1735 $update_details = array(
1736 'update_core' => get_site_transient( 'update_core' ),
1737 'update_plugins' => get_site_transient( 'update_plugins' ),
1738 'update_themes' => get_site_transient( 'update_themes' ),
1739 );
1740 return $update_details;
1741 }
1742
1743 /**
1744 * Is Jetpack active?
1745 * The method only checks if there's an existing token for the master user. It doesn't validate the token.
1746 *
1747 * This method is deprecated since 9.6.0. Please use one of the methods provided by the Manager class in the Connection package,
1748 * or Jetpack::is_connection_ready if you want to know when the Jetpack plugin starts considering the connection ready to be used.
1749 *
1750 * Since this method has a wide spread use, we decided not to throw any deprecation warnings for now.
1751 *
1752 * @deprecated 9.6.0
1753 *
1754 * @return bool
1755 */
1756 public static function is_active() {
1757 return self::connection()->has_connected_owner();
1758 }
1759
1760 /**
1761 * Returns true if the current site is connected to WordPress.com and has the minimum requirements to enable Jetpack UI
1762 *
1763 * This method was introduced just before the release of the possibility to use Jetpack without a user connection, while
1764 * it was available only when no_user_testing_mode was enabled. In the near future, this will return is_connected for all
1765 * users and this option will be available by default for everybody.
1766 *
1767 * @since 9.6.0
1768 * @since 9.7.0 returns is_connected in all cases and adds filter to the returned value
1769 *
1770 * @return bool is the site connection ready to be used?
1771 */
1772 public static function is_connection_ready() {
1773 /**
1774 * Allows filtering whether the connection is ready to be used. If true, this will enable the Jetpack UI and modules
1775 *
1776 * Modules will be enabled depending on the connection status and if the module requires a connection or user connection.
1777 *
1778 * @since 9.7.0
1779 *
1780 * @param bool $is_connection_ready Is the connection ready?
1781 * @param Automattic\Jetpack\Connection\Manager $connection_manager Instance of the Manager class, can be used to check the connection status.
1782 */
1783 return apply_filters( 'jetpack_is_connection_ready', self::connection()->is_connected(), self::connection() );
1784 }
1785
1786 /**
1787 * Determines reason for Jetpack offline mode.
1788 */
1789 public static function development_mode_trigger_text() {
1790 $status = new Status();
1791
1792 if ( ! $status->is_offline_mode() ) {
1793 return __( 'Jetpack is not in Offline Mode.', 'jetpack' );
1794 }
1795
1796 if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
1797 $notice = __( 'The JETPACK_DEV_DEBUG constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1798 } elseif ( defined( 'WP_LOCAL_DEV' ) && WP_LOCAL_DEV ) {
1799 $notice = __( 'The WP_LOCAL_DEV constant is defined in wp-config.php or elsewhere.', 'jetpack' );
1800 } elseif ( $status->is_local_site() ) {
1801 $notice = __( 'The site URL is a known local development environment URL (e.g. http://localhost).', 'jetpack' );
1802 } elseif ( get_option( 'jetpack_offline_mode' ) ) {
1803 $notice = __( 'The jetpack_offline_mode option is set to true.', 'jetpack' );
1804 } else {
1805 $notice = __( 'The jetpack_offline_mode filter is set to true.', 'jetpack' );
1806 }
1807
1808 return $notice;
1809 }
1810 /**
1811 * Get Jetpack offline mode notice text and notice class.
1812 *
1813 * Mirrors the checks made in Automattic\Jetpack\Status->is_offline_mode
1814 */
1815 public static function show_development_mode_notice() {
1816 if ( ( new Status() )->is_offline_mode() ) {
1817 $notice = sprintf(
1818 /* translators: %s is a URL */
1819 __( 'In <a href="%s" target="_blank">Offline Mode</a>:', 'jetpack' ),
1820 esc_url( Redirect::get_url( 'jetpack-support-development-mode' ) )
1821 );
1822
1823 $notice .= ' ' . self::development_mode_trigger_text();
1824
1825 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All provided text.
1826 }
1827
1828 // Throw up a notice if using a development version and as for feedback.
1829 if ( self::is_development_version() ) {
1830 /* translators: %s is a URL */
1831 $notice = sprintf( __( 'You are currently running a development version of Jetpack. <a href="%s" target="_blank">Submit your feedback</a>', 'jetpack' ), esc_url( Redirect::get_url( 'jetpack-contact-support-beta-group' ) ) );
1832
1833 echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>'; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- All provided text.
1834 }
1835 }
1836
1837 /**
1838 * Whether Jetpack's version maps to a public release, or a development version.
1839 */
1840 public static function is_development_version() {
1841 /**
1842 * Allows filtering whether this is a development version of Jetpack.
1843 *
1844 * This filter is especially useful for tests.
1845 *
1846 * @since 4.3.0
1847 *
1848 * @param bool $development_version Is this a develoment version of Jetpack?
1849 */
1850 return (bool) apply_filters(
1851 'jetpack_development_version',
1852 ! preg_match( '/^\d+(\.\d+)+$/', Constants::get_constant( 'JETPACK__VERSION' ) )
1853 );
1854 }
1855
1856 /**
1857 * Get the wpcom email of the current|specified connected user.
1858 *
1859 * @param null|int $user_id User ID or will use get_current_user_id if null.
1860 */
1861 public static function get_connected_user_email( $user_id = null ) {
1862 if ( ! $user_id ) {
1863 $user_id = get_current_user_id();
1864 }
1865
1866 $xml = new Jetpack_IXR_Client(
1867 array(
1868 'user_id' => $user_id,
1869 )
1870 );
1871 $xml->query( 'wpcom.getUserEmail' );
1872 if ( ! $xml->isError() ) {
1873 return $xml->getResponse();
1874 }
1875 return false;
1876 }
1877
1878 /**
1879 * Get the wpcom email of the master user.
1880 */
1881 public static function get_master_user_email() {
1882 $master_user_id = Jetpack_Options::get_option( 'master_user' );
1883 if ( $master_user_id ) {
1884 return self::get_connected_user_email( $master_user_id );
1885 }
1886 return '';
1887 }
1888
1889 /**
1890 * Gets current user IP address.
1891 *
1892 * @param bool $check_all_headers Check all headers? Default is `false`.
1893 *
1894 * @deprecated Jetpack 10.6
1895 *
1896 * @return string Current user IP address.
1897 */
1898 public static function current_user_ip( $check_all_headers = false ) {
1899 _deprecated_function( __METHOD__, 'jetpack-10.6', 'Automattic\\Jetpack\\Status\\Visitor::get_ip' );
1900
1901 return ( new Visitor() )->get_ip( $check_all_headers );
1902 }
1903
1904 /**
1905 * Loads the currently active modules.
1906 */
1907 public static function load_modules() {
1908 $status = new Status();
1909
1910 if (
1911 ! self::is_connection_ready()
1912 && ! $status->is_offline_mode()
1913 && (
1914 ! is_multisite()
1915 || ! get_site_option( 'jetpack_protect_active' )
1916 )
1917 ) {
1918 return;
1919 }
1920
1921 $version = Jetpack_Options::get_option( 'version' );
1922 if ( ! $version ) {
1923 $version = JETPACK__VERSION . ':' . time();
1924 $old_version = $version;
1925 /** This action is documented in class.jetpack.php */
1926 do_action( 'updating_jetpack_version', $version, false );
1927 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
1928 }
1929 list( $version ) = explode( ':', $version );
1930
1931 $modules = array_filter( self::get_active_modules(), array( 'Jetpack', 'is_module' ) );
1932
1933 $modules_data = array();
1934
1935 // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
1936 if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
1937 $updated_modules = array();
1938 foreach ( $modules as $module ) {
1939 $modules_data[ $module ] = self::get_module( $module );
1940 if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
1941 continue;
1942 }
1943
1944 if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
1945 continue;
1946 }
1947
1948 $updated_modules[] = $module;
1949 }
1950
1951 $modules = array_diff( $modules, $updated_modules );
1952 }
1953
1954 $is_site_connection = false;
1955
1956 if ( method_exists( self::connection(), 'is_site_connection' ) ) {
1957 $is_site_connection = self::connection()->is_site_connection();
1958 }
1959
1960 foreach ( $modules as $index => $module ) {
1961 // If we're in offline/site-connection mode, disable modules requiring a connection/user connection.
1962 if ( $status->is_offline_mode() || $is_site_connection ) {
1963 // Prime the pump if we need to.
1964 if ( empty( $modules_data[ $module ] ) ) {
1965 $modules_data[ $module ] = self::get_module( $module );
1966 }
1967 // If the module requires a connection, but we're in local mode, don't include it.
1968 if ( $status->is_offline_mode() && $modules_data[ $module ]['requires_connection'] ) {
1969 continue;
1970 }
1971
1972 if ( $is_site_connection && $modules_data[ $module ]['requires_user_connection'] ) {
1973 continue;
1974 }
1975 }
1976
1977 if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
1978 continue;
1979 }
1980
1981 if ( ! include_once self::get_module_path( $module ) ) { // phpcs:ignore WordPressVIPMinimum.Files.IncludingFile.NotAbsolutePath
1982 unset( $modules[ $index ] );
1983 self::update_active_modules( array_values( $modules ) );
1984 continue;
1985 }
1986
1987 /**
1988 * Fires when a specific module is loaded.
1989 * The dynamic part of the hook, $module, is the module slug.
1990 *
1991 * @since 1.1.0
1992 */
1993 do_action( 'jetpack_module_loaded_' . $module );
1994 }
1995
1996 /**
1997 * Fires when all the modules are loaded.
1998 *
1999 * @since 1.1.0
2000 */
2001 do_action( 'jetpack_modules_loaded' );
2002
2003 // Load module-specific code that is needed even when a module isn't active. Loaded here because code contained therein may need actions such as setup_theme.
2004 require_once JETPACK__PLUGIN_DIR . 'modules/module-extras.php';
2005 }
2006
2007 /**
2008 * Check if Jetpack's REST API compat file should be included
2009 *
2010 * @action plugins_loaded
2011 * @return void
2012 */
2013 public function check_rest_api_compat() {
2014 /**
2015 * Filters the list of REST API compat files to be included.
2016 *
2017 * @since 2.2.5
2018 *
2019 * @param array $args Array of REST API compat files to include.
2020 */
2021 $_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
2022
2023 foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include ) {
2024 require_once $_jetpack_rest_api_compat_include;
2025 }
2026 }
2027
2028 /**
2029 * Gets all plugins currently active in values, regardless of whether they're
2030 * traditionally activated or network activated.
2031 *
2032 * @todo Store the result in core's object cache maybe?
2033 */
2034 public static function get_active_plugins() {
2035 // Older Connection copies can load first and lack this method.
2036 if ( ! method_exists( Heartbeat::class, 'get_active_plugins' ) ) {
2037 return array();
2038 }
2039
2040 return Heartbeat::get_active_plugins();
2041 }
2042
2043 /**
2044 * Gets and parses additional plugin data to send with the heartbeat data
2045 *
2046 * @since 3.8.1
2047 *
2048 * @return array Array of plugin data
2049 */
2050 public static function get_parsed_plugin_data() {
2051 if ( ! function_exists( 'get_plugins' ) ) {
2052 require_once ABSPATH . 'wp-admin/includes/plugin.php';
2053 }
2054 /** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
2055 $all_plugins = apply_filters( 'all_plugins', get_plugins() );
2056 $active_plugins = self::get_active_plugins();
2057
2058 $plugins = array();
2059 foreach ( $all_plugins as $path => $plugin_data ) {
2060 $plugins[ $path ] = array(
2061 'is_active' => in_array( $path, $active_plugins, true ),
2062 'file' => $path,
2063 'name' => $plugin_data['Name'],
2064 'version' => $plugin_data['Version'],
2065 'author' => $plugin_data['Author'],
2066 );
2067 }
2068
2069 return $plugins;
2070 }
2071
2072 /**
2073 * Gets and parses theme data to send with the heartbeat data
2074 *
2075 * @since 3.8.1
2076 *
2077 * @return array Array of theme data
2078 */
2079 public static function get_parsed_theme_data() {
2080 $all_themes = wp_get_themes( array( 'allowed' => true ) );
2081 $header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
2082
2083 $themes = array();
2084 foreach ( $all_themes as $slug => $theme_data ) {
2085 $theme_headers = array();
2086 foreach ( $header_keys as $header_key ) {
2087 $theme_headers[ $header_key ] = $theme_data->get( $header_key );
2088 }
2089
2090 $themes[ $slug ] = array(
2091 'is_active_theme' => wp_get_theme()->get_template() === $slug,
2092 'slug' => $slug,
2093 'theme_root' => $theme_data->get_theme_root_uri(),
2094 'parent' => $theme_data->parent(),
2095 'headers' => $theme_headers,
2096 );
2097 }
2098
2099 return $themes;
2100 }
2101
2102 /**
2103 * Checks whether a specific plugin is active.
2104 *
2105 * We don't want to store these in a static variable, in case
2106 * there are switch_to_blog() calls involved.
2107 *
2108 * @param string $plugin Plugin to check in 'folder/file.php` format.
2109 */
2110 public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
2111 return in_array( $plugin, self::get_active_plugins(), true );
2112 }
2113
2114 /**
2115 * Check if Jetpack's Open Graph tags should be used.
2116 * If certain plugins are active, Jetpack's og tags are suppressed.
2117 *
2118 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2119 * @action plugins_loaded
2120 * @return void
2121 */
2122 public function check_open_graph() {
2123 if ( in_array( 'publicize', self::get_active_modules(), true ) || in_array( 'sharedaddy', self::get_active_modules(), true ) ) {
2124 include_once JETPACK__PLUGIN_DIR . 'enhanced-open-graph.php';
2125 add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
2126 }
2127
2128 $active_plugins = self::get_active_plugins();
2129
2130 if ( ! empty( $active_plugins ) ) {
2131 foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
2132 if ( in_array( $plugin, $active_plugins, true ) ) {
2133 add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
2134 break;
2135 }
2136 }
2137 }
2138
2139 /**
2140 * Allow the addition of Open Graph Meta Tags to all pages.
2141 *
2142 * @since 2.0.3
2143 *
2144 * @param bool false Should Open Graph Meta tags be added. Default to false.
2145 */
2146 if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
2147 require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
2148 }
2149 }
2150
2151 /**
2152 * Check if Jetpack's Twitter tags should be used.
2153 * If certain plugins are active, Jetpack's twitter tags are suppressed.
2154 *
2155 * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
2156 * @action plugins_loaded
2157 * @return void
2158 */
2159 public function check_twitter_tags() {
2160
2161 $active_plugins = self::get_active_plugins();
2162
2163 if ( ! empty( $active_plugins ) ) {
2164 foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
2165 if ( in_array( $plugin, $active_plugins, true ) ) {
2166 add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
2167 break;
2168 }
2169 }
2170 }
2171
2172 /**
2173 * Allow Twitter Card Meta tags to be disabled.
2174 *
2175 * @since 2.6.0
2176 *
2177 * @param bool true Should Twitter Card Meta tags be disabled. Default to true.
2178 */
2179 if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
2180 // @todo Remove this require once the deprecated Jetpack_Twitter_Cards wrapper has been removed.
2181 // Twitter Cards functionality now lives in the jetpack-post-media package (Automattic\Jetpack\Post_Media\Twitter_Cards).
2182 require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
2183 }
2184 }
2185
2186 /* Jetpack Options API */
2187
2188 /**
2189 * Gets the option names from Jetpack_Options.
2190 *
2191 * @param string $type Jetpack option type.
2192 *
2193 * @return array
2194 */
2195 public static function get_option_names( $type = 'compact' ) {
2196 return Jetpack_Options::get_option_names( $type );
2197 }
2198
2199 /**
2200 * Returns the requested option.
2201 *
2202 * Looks in jetpack_options or jetpack_$name as appropriate.
2203 *
2204 * @param string $name Option name.
2205 * @param mixed $default Default value.
2206 */
2207 public static function get_option( $name, $default = false ) {
2208 return Jetpack_Options::get_option( $name, $default );
2209 }
2210
2211 /**
2212 * Returns an array of all PHP files in the specified absolute path.
2213 * Equivalent to glob( "$absolute_path/*.php" ).
2214 *
2215 * @param string $absolute_path The absolute path of the directory to search.
2216 * @return array Array of absolute paths to the PHP files.
2217 */
2218 public static function glob_php( $absolute_path ) {
2219 return ( new Files() )->glob_php( $absolute_path );
2220 }
2221
2222 /**
2223 * Activate new modules.
2224 *
2225 * @param bool $redirect Should this function redirect after activation.
2226 *
2227 * @return void
2228 */
2229 public static function activate_new_modules( $redirect = false ) {
2230 if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
2231 return;
2232 }
2233
2234 $jetpack_old_version = Jetpack_Options::get_option( 'version' );
2235 if ( ! $jetpack_old_version ) {
2236 $old_version = '1.1:' . time();
2237 $version = $old_version;
2238 $jetpack_old_version = $version;
2239 /** This action is documented in class.jetpack.php */
2240 do_action( 'updating_jetpack_version', $version, false );
2241 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
2242 }
2243
2244 list( $jetpack_version ) = explode( ':', $jetpack_old_version );
2245
2246 if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
2247 return;
2248 }
2249
2250 $active_modules = self::get_active_modules();
2251 $reactivate_modules = array();
2252 foreach ( $active_modules as $active_module ) {
2253 $module = self::get_module( $active_module );
2254 if ( ! isset( $module['changed'] ) ) {
2255 continue;
2256 }
2257
2258 if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
2259 continue;
2260 }
2261
2262 $reactivate_modules[] = $active_module;
2263 self::deactivate_module( $active_module );
2264 }
2265
2266 $new_version = JETPACK__VERSION . ':' . time();
2267 /** This action is documented in class.jetpack.php */
2268 do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
2269 Jetpack_Options::update_options(
2270 array(
2271 'version' => $new_version,
2272 'old_version' => $jetpack_old_version,
2273 )
2274 );
2275
2276 self::state( 'message', 'modules_activated' );
2277
2278 self::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules, $redirect );
2279
2280 if ( $redirect ) {
2281 $page = 'jetpack'; // make sure we redirect to either settings or the jetpack page.
2282 if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ), true ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're not changing the site.
2283 $page = sanitize_text_field( wp_unslash( $_GET['page'] ) ); // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- we're not changing the site.
2284 }
2285 wp_safe_redirect( self::admin_url( 'page=' . rawurlencode( $page ) ) );
2286 exit( 0 );
2287 }
2288 }
2289
2290 /**
2291 * List available Jetpack modules. Simply lists .php files in /modules/.
2292 * Make sure to tuck away module "library" files in a sub-directory.
2293 *
2294 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2295 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2296 * @param bool|null $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2297 * @param bool|null $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2298 *
2299 * @return array $modules Array of module slugs
2300 */
2301 public static function get_available_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2302 return ( new Modules() )->get_available( $min_version, $max_version, $requires_connection, $requires_user_connection );
2303 }
2304
2305 /**
2306 * Get default modules loaded on activation.
2307 *
2308 * @param bool|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2309 * @param bool|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2310 * @param bool|null $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2311 * @param bool|null $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2312 *
2313 * @return array $modules Array of module slugs
2314 */
2315 public static function get_default_modules( $min_version = false, $max_version = false, $requires_connection = null, $requires_user_connection = null ) {
2316 $return = array();
2317
2318 foreach ( self::get_available_modules( $min_version, $max_version, $requires_connection, $requires_user_connection ) as $module ) {
2319 $module_data = self::get_module( $module );
2320
2321 switch ( strtolower( $module_data['auto_activate'] ) ) {
2322 case 'yes':
2323 $return[] = $module;
2324 break;
2325 case 'public':
2326 if ( Jetpack_Options::get_option( 'public' ) ) {
2327 $return[] = $module;
2328 }
2329 break;
2330 case 'no':
2331 default:
2332 break;
2333 }
2334 }
2335 if ( method_exists( Feature_Policy::class, 'ensure_hooks' ) ) {
2336 Feature_Policy::ensure_hooks();
2337 }
2338
2339 /**
2340 * Filters the array of default modules.
2341 *
2342 * @since 2.5.0
2343 *
2344 * @param array $return Array of default modules.
2345 * @param string $min_version Minimum version number required to use modules.
2346 * @param string $max_version Maximum version number required to use modules.
2347 * @param bool|null $requires_connection Value of the Requires Connection filter.
2348 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2349 */
2350 return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version, $requires_connection, $requires_user_connection );
2351 }
2352
2353 /**
2354 * Checks activated modules during auto-activation to determine
2355 * if any of those modules are being deprecated. If so, close
2356 * them out, and add any replacement modules.
2357 *
2358 * Runs at priority 99 by default.
2359 *
2360 * This is run late, so that it can still activate a module if
2361 * the new module is a replacement for another that the user
2362 * currently has active, even if something at the normal priority
2363 * would kibosh everything.
2364 *
2365 * @since 2.6
2366 * @uses jetpack_get_default_modules filter
2367 * @param array $modules Array of Jetpack modules.
2368 * @return array
2369 */
2370 public function handle_deprecated_modules( $modules ) {
2371 $deprecated_modules = array(
2372 'debug' => null, // Closed out and moved to the debugger library.
2373 'wpcc' => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
2374 'gplus-authorship' => null, // Closed out in 3.2 -- Google dropped support.
2375 'minileven' => null, // Closed out in 8.3 -- Responsive themes are common now, and so is AMP.
2376 'lazy-images' => null, // Closed out in 12.8 -- WordPress core now has native lazy loading.
2377 'enhanced-distribution' => null, // Closed out in 13.3 -- WP.com is winding down the firehose.
2378 );
2379
2380 // Don't activate SSO if they never completed activating WPCC.
2381 if ( self::is_module_active( 'wpcc' ) ) {
2382 $wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
2383 if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
2384 $deprecated_modules['wpcc'] = null;
2385 }
2386 }
2387
2388 foreach ( $deprecated_modules as $module => $replacement ) {
2389 if ( self::is_module_active( $module ) ) {
2390 self::deactivate_module( $module );
2391 if ( $replacement ) {
2392 $modules[] = $replacement;
2393 }
2394 }
2395 }
2396
2397 return array_unique( $modules );
2398 }
2399
2400 /**
2401 * Checks activated plugins during auto-activation to determine
2402 * if any of those plugins are in the list with a corresponding module
2403 * that is not compatible with the plugin. The module will not be allowed
2404 * to auto-activate.
2405 *
2406 * @since 2.6
2407 * @uses jetpack_get_default_modules filter
2408 * @param array $modules Array of Jetpack modules.
2409 * @return array
2410 */
2411 public function filter_default_modules( $modules ) {
2412
2413 $active_plugins = self::get_active_plugins();
2414
2415 if ( ! empty( $active_plugins ) ) {
2416
2417 // For each module we'd like to auto-activate...
2418 foreach ( $modules as $key => $module ) {
2419 // If there are potential conflicts for it...
2420 if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
2421 // For each potential conflict...
2422 foreach ( $this->conflicting_plugins[ $module ] as $plugin ) {
2423 // If that conflicting plugin is active...
2424 if ( in_array( $plugin, $active_plugins, true ) ) {
2425 // Remove that item from being auto-activated.
2426 unset( $modules[ $key ] );
2427 }
2428 }
2429 }
2430 }
2431 }
2432
2433 // Special case to convert block setting to a block module.
2434 $block_key = array_search( 'blocks', $modules, true );
2435 if ( $block_key !== false ) { // Only care if 'blocks' made it through the previous filters.
2436 $block_option = get_option( 'jetpack_blocks_disabled', null );
2437 if ( $block_option ) {
2438 unset( $modules[ $block_key ] );
2439 }
2440 }
2441
2442 return $modules;
2443 }
2444
2445 /**
2446 * Extract a module's slug from its full path.
2447 *
2448 * @param string $file Full path to a file.
2449 *
2450 * @return string Module slug.
2451 */
2452 public static function get_module_slug( $file ) {
2453 return ( new Modules() )->get_slug( $file );
2454 }
2455
2456 /**
2457 * Generate a module's path from its slug.
2458 *
2459 * @param string $slug Module slug.
2460 */
2461 public static function get_module_path( $slug ) {
2462 return ( new Modules() )->get_path( $slug );
2463 }
2464
2465 /**
2466 * Load module data from module file. Headers differ from WordPress
2467 * plugin headers to avoid them being identified as standalone
2468 * plugins on the WordPress plugins page.
2469 *
2470 * @param string $module The module slug.
2471 */
2472 public static function get_module( $module ) {
2473 return ( new Modules() )->get( $module );
2474 }
2475
2476 /**
2477 * Like core's get_file_data implementation, but caches the result.
2478 *
2479 * @param string $file Absolute path to the file.
2480 * @param array $headers List of headers, in the format array( 'HeaderKey' => 'Header Name' ).
2481 */
2482 public static function get_file_data( $file, $headers ) {
2483 return ( new Modules() )->get_file_data( $file, $headers );
2484 }
2485
2486 /**
2487 * Return translated module tag.
2488 *
2489 * @param string $tag Tag as it appears in each module heading.
2490 *
2491 * @return mixed
2492 */
2493 public static function translate_module_tag( $tag ) {
2494 return jetpack_get_module_i18n_tag( $tag );
2495 }
2496
2497 /**
2498 * Return module name translation. Uses matching string created in modules/module-headings.php.
2499 *
2500 * The module list is globbed from `modules/` at runtime, so a module can be listed with no
2501 * entry in that generated file. Fall back to the untranslated header rather than overwriting
2502 * it with the null `jetpack_get_module_i18n()` returns for an unknown slug.
2503 *
2504 * @since 3.9.2
2505 *
2506 * @param array $modules Array of Jetpack modules.
2507 *
2508 * @return array
2509 */
2510 public static function get_translated_modules( $modules ) {
2511 foreach ( $modules as $index => $module ) {
2512 $i18n_module = jetpack_get_module_i18n( $module['module'] );
2513 $name = $i18n_module['name'] ?? null;
2514 $description = $i18n_module['description'] ?? null;
2515
2516 if ( null !== $name && isset( $module['name'] ) ) {
2517 $modules[ $index ]['name'] = $name;
2518 }
2519 if ( null !== $description && isset( $module['description'] ) ) {
2520 $modules[ $index ]['description'] = $description;
2521 $modules[ $index ]['short_description'] = $description;
2522 }
2523 if ( isset( $module['module_tags'] ) ) {
2524 $modules[ $index ]['module_tags'] = array_map( 'jetpack_get_module_i18n_tag', $module['module_tags'] );
2525 }
2526 }
2527 return $modules;
2528 }
2529
2530 /**
2531 * Get a list of activated modules as an array of module slugs.
2532 */
2533 public static function get_active_modules() {
2534 return ( new Modules() )->get_active();
2535 }
2536
2537 /**
2538 * Check whether or not a Jetpack module is active.
2539 *
2540 * @param string $module The slug of a Jetpack module.
2541 * @return bool
2542 *
2543 * @static
2544 */
2545 public static function is_module_active( $module ) {
2546 return ( new Modules() )->is_active( $module );
2547 }
2548
2549 /**
2550 * Is slug a valid module.
2551 *
2552 * @param string $module Module slug.
2553 *
2554 * @return bool
2555 */
2556 public static function is_module( $module ) {
2557 return ( new Modules() )->is_module( $module );
2558 }
2559
2560 /**
2561 * Catches PHP errors. Must be used in conjunction with output buffering.
2562 *
2563 * @deprecated since 13.5
2564 * @param bool $catch True to start catching, False to stop.
2565 *
2566 * @static
2567 * @deprecated 13.5
2568 * @see \Automattic\Jetpack\Errors
2569 */
2570 public static function catch_errors( $catch ) {
2571 _deprecated_function( __METHOD__, '13.5' );
2572 // @phan-suppress-next-line PhanDeprecatedClass
2573 return ( new Errors() )->catch_errors( $catch );
2574 }
2575
2576 /**
2577 * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
2578 *
2579 * @deprecated since 13.5
2580 */
2581 public static function catch_errors_on_shutdown() {
2582 _deprecated_function( __METHOD__, '13.5' );
2583 self::state( 'php_errors', self::alias_directories( ob_get_clean() ) );
2584 }
2585
2586 /**
2587 * Rewrite any string to make paths easier to read.
2588 *
2589 * Rewrites ABSPATH (eg `/home/jetpack/wordpress/`) to ABSPATH, and if WP_CONTENT_DIR
2590 * is located outside of ABSPATH, rewrites that to WP_CONTENT_DIR.
2591 *
2592 * @param string $string String to attempt rewrite.
2593 * @return mixed
2594 */
2595 public static function alias_directories( $string ) {
2596 // ABSPATH has a trailing slash.
2597 $string = str_replace( ABSPATH, 'ABSPATH/', $string );
2598 // WP_CONTENT_DIR does not have a trailing slash.
2599 $string = str_replace( WP_CONTENT_DIR, 'WP_CONTENT_DIR', $string );
2600
2601 return $string;
2602 }
2603
2604 /**
2605 * Activates default Jetpack modules.
2606 *
2607 * @param null|string $min_version Only return modules introduced in this version or later. Default is false, do not filter.
2608 * @param null|string $max_version Only return modules introduced before this version. Default is false, do not filter.
2609 * @param array $other_modules Other modules to activate.
2610 * @param null|bool $redirect Should there be a redirection after activation.
2611 * @param bool $send_state_messages If a state message should be sent.
2612 * @param bool|null $requires_connection Pass a boolean value to only return modules that require (or do not require) a connection.
2613 * @param bool|null $requires_user_connection Pass a boolean value to only return modules that require (or do not require) a user connection.
2614 *
2615 * @return void
2616 */
2617 public static function activate_default_modules(
2618 $min_version = false,
2619 $max_version = false,
2620 $other_modules = array(),
2621 $redirect = null,
2622 $send_state_messages = null,
2623 $requires_connection = null,
2624 $requires_user_connection = null
2625 ) {
2626 $jetpack = self::init();
2627
2628 if ( $redirect === null ) {
2629 if (
2630 ( defined( 'REST_REQUEST' ) && REST_REQUEST )
2631 ||
2632 ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST )
2633 ||
2634 ( defined( 'WP_CLI' ) && WP_CLI )
2635 ||
2636 ( defined( 'DOING_CRON' ) && DOING_CRON )
2637 ||
2638 ( defined( 'DOING_AJAX' ) && DOING_AJAX )
2639 ) {
2640 $redirect = false;
2641 } elseif ( is_admin() ) {
2642 $redirect = true;
2643 } else {
2644 $redirect = false;
2645 }
2646 }
2647
2648 if ( $send_state_messages === null ) {
2649 $send_state_messages = current_user_can( 'jetpack_activate_modules' );
2650 }
2651
2652 $modules = self::get_default_modules( $min_version, $max_version, $requires_connection, $requires_user_connection );
2653 $modules = array_merge( $other_modules, $modules );
2654
2655 // Look for standalone plugins and disable if active.
2656
2657 $to_deactivate = array();
2658 foreach ( $modules as $module ) {
2659 if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
2660 $to_deactivate[ $module ] = $jetpack->plugins_to_deactivate[ $module ];
2661 }
2662 }
2663
2664 $deactivated = array();
2665 foreach ( $to_deactivate as $module => $deactivate_us ) {
2666 foreach ( $deactivate_us as $i => $deactivate_me ) {
2667 list( $probable_file, $probable_title ) = $deactivate_me;
2668 if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
2669 $deactivated[] = "$module:$i";
2670 }
2671 }
2672 }
2673
2674 if ( $deactivated ) {
2675 if ( $send_state_messages ) {
2676 self::state( 'deactivated_plugins', implode( ',', $deactivated ) );
2677 }
2678
2679 if ( $redirect ) {
2680 $url = add_query_arg(
2681 array(
2682 'action' => 'activate_default_modules',
2683 '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
2684 ),
2685 add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), self::admin_url( 'page=jetpack' ) )
2686 );
2687 wp_safe_redirect( $url );
2688 exit( 0 );
2689 }
2690 }
2691
2692 /**
2693 * Fires before default modules are activated.
2694 *
2695 * @since 1.9.0
2696 *
2697 * @param string $min_version Minimum version number required to use modules.
2698 * @param string $max_version Maximum version number required to use modules.
2699 * @param array $other_modules Array of other modules to activate alongside the default modules.
2700 * @param bool|null $requires_connection Value of the Requires Connection filter.
2701 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2702 */
2703 do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
2704
2705 // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating.
2706 if ( $send_state_messages ) {
2707 self::restate();
2708 }
2709
2710 $active = self::get_active_modules();
2711
2712 foreach ( $modules as $module ) {
2713 if ( did_action( "jetpack_module_loaded_$module" ) ) {
2714 $active[] = $module;
2715 self::update_active_modules( $active );
2716 continue;
2717 }
2718
2719 if ( $send_state_messages && in_array( $module, $active, true ) ) {
2720 $module_info = self::get_module( $module );
2721 if ( ! $module_info['deactivate'] ) {
2722 $state = in_array( $module, $other_modules, true ) ? 'reactivated_modules' : 'activated_modules';
2723 $active_state = self::state( $state );
2724 if ( $active_state ) {
2725 $active_state = explode( ',', $active_state );
2726 } else {
2727 $active_state = array();
2728 }
2729 $active_state[] = $module;
2730 self::state( $state, implode( ',', $active_state ) );
2731 }
2732 continue;
2733 }
2734
2735 $file = self::get_module_path( $module );
2736 if ( ! file_exists( $file ) ) {
2737 continue;
2738 }
2739
2740 // we'll override this later if the plugin can be included without fatal error.
2741 if ( $redirect ) {
2742 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
2743 }
2744
2745 if ( $send_state_messages ) {
2746 self::state( 'error', 'module_activation_failed' );
2747 self::state( 'module', $module );
2748 }
2749
2750 ob_start();
2751 require_once $file;
2752
2753 $active[] = $module;
2754
2755 if ( $send_state_messages ) {
2756
2757 $state = in_array( $module, $other_modules, true ) ? 'reactivated_modules' : 'activated_modules';
2758 $active_state = self::state( $state );
2759 if ( $active_state ) {
2760 $active_state = explode( ',', $active_state );
2761 } else {
2762 $active_state = array();
2763 }
2764 $active_state[] = $module;
2765 self::state( $state, implode( ',', $active_state ) );
2766 }
2767
2768 self::update_active_modules( $active );
2769
2770 ob_end_clean();
2771 }
2772
2773 if ( $send_state_messages ) {
2774 self::state( 'error', false );
2775 self::state( 'module', false );
2776 }
2777 /**
2778 * Fires when default modules are activated.
2779 *
2780 * @since 1.9.0
2781 *
2782 * @param string $min_version Minimum version number required to use modules.
2783 * @param string $max_version Maximum version number required to use modules.
2784 * @param array $other_modules Array of other modules to activate alongside the default modules.
2785 * @param bool|null $requires_connection Value of the Requires Connection filter.
2786 * @param bool|null $requires_user_connection Value of the Requires User Connection filter.
2787 */
2788 do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules, $requires_connection, $requires_user_connection );
2789 }
2790
2791 /**
2792 * Activate a module.
2793 *
2794 * @param string $module Module slug.
2795 * @param bool $exit Should exit be called after deactivation.
2796 * @param bool $redirect Should there be a redirection after activation.
2797 *
2798 * @return bool|void
2799 */
2800 public static function activate_module( $module, $exit = true, $redirect = true ) {
2801 return ( new Modules() )->activate( $module, $exit, $redirect );
2802 }
2803
2804 /**
2805 * Deactivate module.
2806 *
2807 * @param string $module Module slug.
2808 *
2809 * @return bool
2810 */
2811 public static function deactivate_module( $module ) {
2812 return ( new Modules() )->deactivate( $module );
2813 }
2814
2815 /**
2816 * Enable a configuable module.
2817 *
2818 * @param string $module Module slug.
2819 *
2820 * @return void
2821 */
2822 public static function enable_module_configurable( $module ) {
2823 $module = self::get_module_slug( $module );
2824 add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
2825 }
2826
2827 /**
2828 * Composes a module configure URL. It uses Jetpack settings search as default value
2829 * It is possible to redefine resulting URL by using "jetpack_module_configuration_url_$module" filter
2830 *
2831 * @param string $module Module slug.
2832 * @return string $url module configuration URL.
2833 */
2834 public static function module_configuration_url( $module ) {
2835 $module = self::get_module_slug( $module );
2836 $default_url = self::admin_url( array( 'page' => 'jetpack-settings' ) ) . "#/settings?term=$module";
2837 /**
2838 * Allows to modify configure_url of specific module to be able to redirect to some custom location.
2839 *
2840 * @since 6.9.0
2841 *
2842 * @param string $default_url Default url, which redirects to jetpack settings page.
2843 */
2844 $url = apply_filters( 'jetpack_module_configuration_url_' . $module, $default_url );
2845
2846 return $url;
2847 }
2848
2849 /* Installation */
2850 /**
2851 * Bail on activation if there is an issue.
2852 *
2853 * @param string $message Error message.
2854 * @param bool $deactivate Deactivate Jetpack or not.
2855 *
2856 * @return never
2857 */
2858 public static function bail_on_activation( $message, $deactivate = true ) {
2859 ?>
2860 <!doctype html>
2861 <html>
2862 <head>
2863 <meta charset="<?php bloginfo( 'charset' ); ?>">
2864 <style>
2865 * {
2866 text-align: center;
2867 margin: 0;
2868 padding: 0;
2869 font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
2870 }
2871 p {
2872 margin-top: 1em;
2873 font-size: 18px;
2874 }
2875 </style>
2876 <body>
2877 <p><?php echo esc_html( $message ); ?></p>
2878 </body>
2879 </html>
2880 <?php
2881 if ( $deactivate ) {
2882 $plugins = get_option( 'active_plugins' );
2883 $jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
2884 $update = false;
2885 foreach ( $plugins as $i => $plugin ) {
2886 if ( $plugin === $jetpack ) {
2887 $plugins[ $i ] = false;
2888 $update = true;
2889 }
2890 }
2891
2892 if ( $update ) {
2893 update_option( 'active_plugins', array_filter( $plugins ) );
2894 }
2895 }
2896 exit( 0 );
2897 }
2898
2899 /**
2900 * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
2901 *
2902 * @param bool $network_wide Network-wide activation.
2903 */
2904 public static function plugin_activation( $network_wide ) {
2905 Jetpack_Options::update_option( 'activated', 1 );
2906
2907 if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
2908 /* translators: Jetpack version number. */
2909 self::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
2910 }
2911
2912 if ( $network_wide ) {
2913 self::state( 'network_nag', true );
2914 }
2915
2916 // For firing one-off events (notices) immediately after activation.
2917 set_transient( 'activated_jetpack', true, 0.1 * MINUTE_IN_SECONDS );
2918
2919 update_option( 'jetpack_activation_source', self::get_activation_source( wp_get_referer() ) );
2920
2921 Health::on_jetpack_activated();
2922
2923 \Automattic\Jetpack\Reprint_Export\Reprint_Exporter::discard_credentials();
2924
2925 if ( self::is_connection_ready() && method_exists( 'Automattic\Jetpack\Sync\Actions', 'do_only_first_initial_sync' ) ) {
2926 Sync_Actions::do_only_first_initial_sync();
2927 }
2928
2929 if ( ! defined( 'WC_ANALYTICS' ) && class_exists( 'Automattic\Woocommerce_Analytics' ) ) {
2930 Woocommerce_Analytics::maybe_add_proxy_speed_module();
2931 }
2932
2933 self::plugin_initialize();
2934 }
2935
2936 /**
2937 * Returns the activation source.
2938 *
2939 * @param string $referer_url URL.
2940 *
2941 * @return array source_type, source_query.
2942 */
2943 public static function get_activation_source( $referer_url ) {
2944 if ( defined( 'WP_CLI' ) && WP_CLI ) {
2945 return array( 'wp-cli', null );
2946 }
2947
2948 $referer = wp_parse_url( $referer_url );
2949
2950 $source_type = 'unknown';
2951 $source_query = null;
2952
2953 if ( ! is_array( $referer ) || ! isset( $referer['path'] ) ) {
2954 return array( $source_type, $source_query );
2955 }
2956
2957 $plugins_path = wp_parse_url( admin_url( 'plugins.php' ), PHP_URL_PATH );
2958 $plugins_install_path = wp_parse_url( admin_url( 'plugin-install.php' ), PHP_URL_PATH );// /wp-admin/plugin-install.php
2959
2960 if ( isset( $referer['query'] ) ) {
2961 parse_str( $referer['query'], $query_parts );
2962 } else {
2963 $query_parts = array();
2964 }
2965
2966 if ( $plugins_path === $referer['path'] ) {
2967 $source_type = 'list';
2968 } elseif ( $plugins_install_path === $referer['path'] ) {
2969 $tab = $query_parts['tab'] ?? 'featured';
2970 switch ( $tab ) {
2971 case 'popular':
2972 $source_type = 'popular';
2973 break;
2974 case 'recommended':
2975 $source_type = 'recommended';
2976 break;
2977 case 'favorites':
2978 $source_type = 'favorites';
2979 break;
2980 case 'search':
2981 $source_type = 'search-' . ( $query_parts['type'] ?? 'term' );
2982 $source_query = $query_parts['s'] ?? null;
2983 break;
2984 default:
2985 $source_type = 'featured';
2986 }
2987 }
2988
2989 return array( $source_type, $source_query );
2990 }
2991
2992 /**
2993 * Runs before bumping version numbers up to a new version.
2994 *
2995 * Only ever registered the hooks for the release post update modal, which has been removed.
2996 * No longer hooked to `updating_jetpack_version`.
2997 *
2998 * @deprecated 16.2
2999 *
3000 * @param string $version Version:timestamp.
3001 * @param string $old_version Old Version:timestamp or false if not set yet.
3002 */
3003 public static function do_version_bump( $version, $old_version ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- Signature preserved for the deprecation shim.
3004 _deprecated_function( __METHOD__, 'jetpack-16.2' );
3005 }
3006
3007 /**
3008 * Enables the Newsletter (subscriptions) module for existing sites now that it is a default-on module.
3009 *
3010 * Fresh installs receive the module via its "Auto Activate: Yes" header, so this only handles sites
3011 * upgrading from a version where the module defaulted off. It runs once per site (guarded by the
3012 * subscriptions_default_on_migrated option). Fresh installs are marked as migrated immediately so the
3013 * migration never runs for them. After it has run, the user's choice to deactivate the module again
3014 * (for example from the My Jetpack Products page) is respected and never reverted.
3015 *
3016 * The module requires a connection, so on a disconnected site the migration is deferred without setting
3017 * the guard, allowing a later version bump to retry once the site is connected.
3018 *
3019 * @param string $version New Jetpack version:timestamp.
3020 * @param string|false $old_version Previous Jetpack version:timestamp, or false on a fresh install.
3021 */
3022 public static function activate_subscriptions_module_for_existing_sites( $version, $old_version ) {
3023 if ( get_option( 'jetpack_subscriptions_default_on_migrated' ) ) {
3024 return;
3025 }
3026
3027 // Fresh installs get the module via its "Auto Activate: Yes" header. Mark them as migrated so a
3028 // later opt-out is never reverted by the existing-site path on a subsequent version bump.
3029 if ( ! $old_version ) {
3030 update_option( 'jetpack_subscriptions_default_on_migrated', true );
3031 return;
3032 }
3033
3034 if ( ! self::is_connection_ready() ) {
3035 return;
3036 }
3037
3038 // Mark as migrated only once the module is active, so a transient activation failure is retried on
3039 // a later version bump rather than being silently skipped.
3040 if ( self::is_module_active( 'subscriptions' ) || self::activate_module( 'subscriptions', false, false ) ) {
3041 update_option( 'jetpack_subscriptions_default_on_migrated', true );
3042 }
3043 }
3044
3045 /**
3046 * Option flag that records the AI master-switch opt-out reconciliation has run,
3047 * so it never runs twice.
3048 *
3049 * @var string
3050 */
3051 const AI_MASTER_OPTOUT_MIGRATED_OPTION = 'jetpack_ai_master_optout_migrated';
3052
3053 /**
3054 * Register the on-upgrade init hooks whose relative ORDER matters, extracted so
3055 * the ordering can be asserted in tests without invoking plugin_upgrade() (whose
3056 * guards make it unreliable to trigger under test). activate_new_modules()
3057 * (init, default priority 10) auto-activates "Auto Activate: Yes" modules
3058 * including the `ai` master; reconcile_ai_master_optout() must run at a LATER
3059 * priority to honor an explicit AI opt-out.
3060 *
3061 * @return void
3062 */
3063 public static function register_upgrade_init_hooks() {
3064 add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
3065 add_action( 'init', array( __CLASS__, 'reconcile_ai_master_optout' ), 20 );
3066 }
3067
3068 /**
3069 * Preserves an explicit Jetpack AI opt-out when the `ai` module becomes the site-wide
3070 * master switch off WordPress.com Simple (self-hosted and Atomic).
3071 *
3072 * The `ai` module is "Auto Activate: Yes", so on upgrade {@see self::activate_new_modules()}
3073 * turns it on for connected sites — the desired default-on / auto-enable-on-connection
3074 * behavior, which this method deliberately leaves alone. The one case it corrects is a site
3075 * that had explicitly disabled Jetpack AI (the `jetpack_ai_enabled` option present and falsey)
3076 * before the module shipped: that opt-out must survive the module becoming the master, so the
3077 * module is deactivated for exactly those sites. An absent or truthy option is left untouched.
3078 *
3079 * Ordering is the whole point. `activate_new_modules()` is hooked on `init` at priority 10 and
3080 * auto-activates the module there; this method is hooked on `init` at priority 20 (see
3081 * {@see self::plugin_upgrade()}), so it runs AFTER the auto-activation and its deactivation is
3082 * the final state. A version-guarded block that ran inline during `plugins_loaded` would be
3083 * undone by the later auto-activation, which is why this is a late-init hook rather than an
3084 * inline upgrade step.
3085 *
3086 * WordPress.com Simple never runs modules — the option stays the master there — so this is a
3087 * no-op on Simple. The {@see self::AI_MASTER_OPTOUT_MIGRATED_OPTION} flag makes it run exactly
3088 * once, which matters because off-Simple the option is no longer the master after this runs:
3089 * a stale falsey option must not keep re-deactivating a module the user later turns back on.
3090 *
3091 * @return void
3092 */
3093 public static function reconcile_ai_master_optout() {
3094 if ( get_option( self::AI_MASTER_OPTOUT_MIGRATED_OPTION ) ) {
3095 return;
3096 }
3097
3098 // Simple keeps the `jetpack_ai_enabled` option as the master; modules don't run there.
3099 if ( ( new Host() )->is_wpcom_simple() ) {
3100 return;
3101 }
3102
3103 // A sentinel default distinguishes an absent option (leave auto-activation alone) from one
3104 // explicitly stored falsey (an opt-out to preserve).
3105 $stored = get_option( 'jetpack_ai_enabled', 'not-set' );
3106 if ( 'not-set' !== $stored && ! (bool) $stored ) {
3107 ( new Modules() )->deactivate( 'ai' );
3108 }
3109
3110 update_option( self::AI_MASTER_OPTOUT_MIGRATED_OPTION, true );
3111 }
3112
3113 /**
3114 * Deletes obsolete SEO module-state options without changing module activation.
3115 *
3116 * @since 16.3
3117 */
3118 public static function cleanup_seo_module_state_options() {
3119 delete_option( 'jetpack_seo_sitemap_enabled' );
3120 delete_option( 'jetpack_seo_canonical_urls_enabled' );
3121 delete_option( 'jetpack_seo_module_state_reconciled' );
3122 }
3123
3124 /**
3125 * Seeds the Jetpack SEO discoverability cohort once, so the new SEO surface is
3126 * auto-discoverable on fresh installs but opt-in on existing ones (JETPACK-1700).
3127 *
3128 * Hooked on `updating_jetpack_version`, which fires on every install including the
3129 * first — with `$old_version === false` on a brand-new site (the same signal
3130 * {@see self::activate_subscriptions_module_for_existing_sites()} keys off). Fresh
3131 * installs are seeded visible; existing installs are seeded hidden and opt in later
3132 * via the legacy Traffic page or My Jetpack. `add_option()` makes this seed-once: it
3133 * never overrides a value a later opt-in (or opt-out) has set. WordPress.com sites
3134 * ignore this option entirely (always visible) — see
3135 * {@see \Automattic\Jetpack\SEO\Initializer::is_seo_surface_visible()}.
3136 *
3137 * @param string $version The new Jetpack version (unused).
3138 * @param string|false $old_version The previous version, or false on a fresh install.
3139 */
3140 public static function seed_seo_visibility_cohort( $version, $old_version ) {
3141 add_option( Jetpack_SEO_Initializer::VISIBILITY_OPTION, ! $old_version );
3142 }
3143
3144 /**
3145 * Sets the display_update_modal state.
3146 *
3147 * The release post update modal that read this state has been removed. The write is kept so the
3148 * method still behaves as documented for the deprecation window. When this is deleted, also drop
3149 * the matching `display_update_modal` guard in Automattic\Jetpack\CookieState::should_set_cookie(),
3150 * which exists only to keep this key out of the cookie on the Jetpack admin screen.
3151 *
3152 * @deprecated 16.2
3153 */
3154 public static function set_update_modal_display() {
3155 _deprecated_function( __METHOD__, 'jetpack-16.2' );
3156 self::state( 'display_update_modal', true );
3157 }
3158
3159 /**
3160 * Enqueues the block library styles.
3161 *
3162 * Only ever used by the release post update modal, which has been removed.
3163 *
3164 * @deprecated 16.2
3165 *
3166 * @param string $hook The current admin page.
3167 */
3168 public static function enqueue_block_style( $hook ) {
3169 _deprecated_function( __METHOD__, 'jetpack-16.2' );
3170 if ( 'toplevel_page_jetpack' === $hook ) {
3171 wp_enqueue_style( 'wp-block-library' );
3172 }
3173 }
3174
3175 /**
3176 * Sets the internal version number and activation state.
3177 *
3178 * @static
3179 */
3180 public static function plugin_initialize() {
3181 if ( ! Jetpack_Options::get_option( 'activated' ) ) {
3182 Jetpack_Options::update_option( 'activated', 2 );
3183 }
3184
3185 if ( ! Jetpack_Options::get_option( 'version' ) ) {
3186 $old_version = JETPACK__VERSION . ':' . time();
3187 $version = $old_version;
3188 /** This action is documented in class.jetpack.php */
3189 do_action( 'updating_jetpack_version', $version, false );
3190 Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
3191 }
3192
3193 if ( self::is_connection_ready() ) {
3194 self::handle_default_module_activation( true );
3195 }
3196
3197 self::load_modules();
3198
3199 Jetpack_Options::delete_option( 'do_activate' );
3200 }
3201
3202 /**
3203 * Handles the activation of the default modules depending on the current state of the site:
3204 * - If the site already has the jetpack_active_modules option, activate those.
3205 * - If the site has a site-only connection, only activate the default modules that require only a site connection.
3206 * - If the site has a user connection, activate the default modules that require a user connection.
3207 *
3208 * @param bool $should_activate_user_modules Whether the status of the user connection should be checked and the default modules that
3209 * require a user connection activated.
3210 */
3211 private static function handle_default_module_activation( $should_activate_user_modules ) {
3212 $active_modules = Jetpack_Options::get_option( 'active_modules' );
3213 if ( $active_modules ) {
3214 self::delete_active_modules();
3215
3216 /**
3217 * Previously active modules could mean two things. First, it could mean
3218 * that Jetpack was previously active on the site. In this case we would like
3219 * to only activate the modules that were set to active.
3220 * Another case could be that the module option was set by a standalone
3221 * plugin. In that case the `active_modules_initalized` option will not
3222 * be set, so we need to enable default Jetpack modules as well.
3223 */
3224 if ( ! Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
3225 $default_modules = self::get_default_modules();
3226 $active_modules = array_merge( $active_modules, $default_modules );
3227 Jetpack_Options::update_option( 'active_modules_initialized', true );
3228 }
3229
3230 self::activate_default_modules(
3231 999, // This version trick basically excludes every default module.
3232 1,
3233 $active_modules,
3234 false
3235 );
3236 } elseif ( $should_activate_user_modules && ( new Connection_Manager() )->get_connection_owner_id() ) { // Check for a user connection.
3237 self::activate_default_modules( false, false, array(), false, null, null, null );
3238 Jetpack_Options::update_option( 'active_modules_initialized', true );
3239 } else {
3240 self::activate_default_modules( false, false, array(), false, null, null, false );
3241 }
3242 }
3243
3244 /**
3245 * Removes all connection options
3246 *
3247 * @static
3248 */
3249 public static function plugin_deactivation() {
3250 require_once ABSPATH . '/wp-admin/includes/plugin.php';
3251 $tracking = new Tracking();
3252 $tracking->record_user_event( 'deactivate_plugin', array() );
3253 if ( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
3254 Jetpack_Network::init()->deactivate();
3255 } else {
3256 add_filter( 'jetpack_update_activated_state_on_disconnect', '__return_false' );
3257 self::disconnect();
3258 Jetpack_Options::delete_option( 'version' );
3259 }
3260
3261 if ( ! defined( 'WC_ANALYTICS' ) && class_exists( 'Automattic\Woocommerce_Analytics' ) ) {
3262 Woocommerce_Analytics::maybe_remove_proxy_speed_module();
3263 }
3264 }
3265
3266 /**
3267 * Set activated option to 4 on jetpack_idc_disconnect action.
3268 */
3269 public static function on_idc_disconnect() {
3270 \Jetpack_Options::update_option( 'activated', 4 );
3271 }
3272
3273 /**
3274 * Disconnects from the Jetpack servers.
3275 * Forgets all connection details and tells the Jetpack servers to do the same.
3276 *
3277 * Will not disconnect if there are other plugins using the connection.
3278 *
3279 * @since 11.0 Do not disconnect if other plugins are using the connection.
3280 *
3281 * @static
3282 */
3283 public static function disconnect() {
3284
3285 $connection = self::connection();
3286
3287 // If the site is in an IDC because sync is not allowed,
3288 // let's make sure to not disconnect the production site.
3289 $connection->remove_connection( ! Identity_Crisis::validate_sync_error_idc_option() );
3290 }
3291
3292 /**
3293 * Happens after a successful disconnection.
3294 *
3295 * @static
3296 */
3297 public static function jetpack_site_disconnected() {
3298 Identity_Crisis::clear_all_idc_options();
3299
3300 \Automattic\Jetpack\Reprint_Export\Reprint_Exporter::discard_credentials();
3301
3302 // Delete all the sync related data. Since it could be taking up space.
3303 Sender::get_instance()->uninstall();
3304
3305 /**
3306 * Filters whether the Jetpack activated state should be updated after disconnecting.
3307 *
3308 * @since 10.0.0
3309 *
3310 * @param bool $update_activated_state Whether activated state should be updated after disconnecting, defaults to true.
3311 */
3312 $update_activated_state = apply_filters( 'jetpack_update_activated_state_on_disconnect', true );
3313
3314 if ( $update_activated_state ) {
3315 Jetpack_Options::update_option( 'activated', 4 );
3316 }
3317 }
3318
3319 /**
3320 * Disconnects the user.
3321 *
3322 * @deprecated 13.4
3323 * @see \Automattic\Jetpack\Connection\Manager::disconnect_user()
3324 *
3325 * @param int $user_id The user ID to disconnect.
3326 */
3327 public function disconnect_user( $user_id ) {
3328 $this->connection_manager->disconnect_user( $user_id );
3329 }
3330
3331 /**
3332 * Checking the domain names in beta versions.
3333 * If this is a development version, before attempting to connect, let's make sure that the domains are viable.
3334 *
3335 * @param null|\WP_Error $error The domain validation error, or `null` if everything's fine.
3336 *
3337 * @return null|\WP_Error The domain validation error, or `null` if everything's fine.
3338 */
3339 public static function registration_check_domains( $error ) {
3340 if ( static::is_development_version() ) {
3341 $domains_to_check = array_unique(
3342 array(
3343 'siteurl' => wp_parse_url( get_site_url(), PHP_URL_HOST ),
3344 'homeurl' => wp_parse_url( get_home_url(), PHP_URL_HOST ),
3345 )
3346 );
3347 foreach ( $domains_to_check as $domain ) {
3348 $result = static::connection()->is_usable_domain( $domain );
3349 if ( is_wp_error( $result ) ) {
3350 return $result;
3351 }
3352 }
3353 }
3354
3355 return $error;
3356 }
3357
3358 /**
3359 * Tracking an internal event log. Try not to put too much chaff in here.
3360 *
3361 * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
3362 *
3363 * @param mixed $code Error code to log.
3364 * @param mixed $data Data to log.
3365 */
3366 public static function log( $code, $data = null ) {
3367
3368 $raw_log = Jetpack_Options::get_option( 'log', array() );
3369 // This can be modified by the `jetpack_options` filter, so abort if we don't have an array.
3370 if ( ! is_array( $raw_log ) ) {
3371 return;
3372 }
3373
3374 // only grab the latest 200 entries.
3375 $log = array_slice( $raw_log, -199, 199 );
3376
3377 // Append our event to the log.
3378 $log_entry = array(
3379 'time' => time(),
3380 'user_id' => get_current_user_id(),
3381 'blog_id' => Jetpack_Options::get_option( 'id' ),
3382 'code' => $code,
3383 );
3384 // Don't bother storing it unless we've got some.
3385 if ( $data !== null ) {
3386 $log_entry['data'] = $data;
3387 }
3388 $log[] = $log_entry;
3389
3390 // Try add_option first, to make sure it's not autoloaded.
3391 // @todo: Add an add_option method to Jetpack_Options.
3392 if ( ! add_option( 'jetpack_log', $log, '', 'no' ) ) {
3393 Jetpack_Options::update_option( 'log', $log );
3394 }
3395
3396 /**
3397 * Fires when Jetpack logs an internal event.
3398 *
3399 * @since 3.0.0
3400 *
3401 * @param array $log_entry {
3402 * Array of details about the log entry.
3403 *
3404 * @param string time Time of the event.
3405 * @param int user_id ID of the user who trigerred the event.
3406 * @param int blog_id Jetpack Blog ID.
3407 * @param string code Unique name for the event.
3408 * @param string data Data about the event.
3409 * }
3410 */
3411 do_action( 'jetpack_log_entry', $log_entry );
3412 }
3413
3414 /**
3415 * Get the internal event log.
3416 *
3417 * @param string $event only return the specific log events.
3418 * @param int $num - get specific number of latest results, limited to 200.
3419 *
3420 * @return array of log events || WP_Error for invalid params
3421 */
3422 public static function get_log( $event = false, $num = false ) {
3423 if ( $event && ! is_string( $event ) ) {
3424 return new WP_Error( __( 'First param must be string or empty', 'jetpack' ) );
3425 }
3426
3427 if ( $num && ! is_numeric( $num ) ) {
3428 return new WP_Error( __( 'Second param must be numeric or empty', 'jetpack' ) );
3429 }
3430
3431 $entire_log = Jetpack_Options::get_option( 'log', array() );
3432
3433 // If nothing set - act as it did before, otherwise let's start customizing the output.
3434 if ( ! $num && ! $event ) {
3435 return $entire_log;
3436 } else {
3437 $entire_log = array_reverse( $entire_log );
3438 }
3439
3440 $custom_log_output = array();
3441
3442 if ( $event ) {
3443 foreach ( $entire_log as $log_event ) {
3444 if ( $event === $log_event['code'] ) {
3445 $custom_log_output[] = $log_event;
3446 }
3447 }
3448 } else {
3449 $custom_log_output = $entire_log;
3450 }
3451
3452 if ( $num ) {
3453 $custom_log_output = array_slice( $custom_log_output, 0, $num );
3454 }
3455
3456 return $custom_log_output;
3457 }
3458
3459 /**
3460 * Log modification of important settings.
3461 *
3462 * @param string $option Option name.
3463 * @param string $old_value Old value of option.
3464 * @param string $value New value of option.
3465 */
3466 public static function log_settings_change( $option, $old_value, $value ) {
3467 switch ( $option ) {
3468 case 'jetpack_sync_non_public_post_stati':
3469 self::log( $option, $value );
3470 break;
3471 }
3472 }
3473
3474 /**
3475 * Return stat data for WPCOM sync.
3476 *
3477 * The Sync stats module was this method's last caller and moved to the Connection package's
3478 * `Heartbeat::generate_stats_array()`, which assembles the heartbeat data through the
3479 * `jetpack_heartbeat_stats_array` filter. Note the package method does not include the extended
3480 * data from `get_additional_stat_data()`, so callers relying on `$extended` need to add it themselves.
3481 *
3482 * @deprecated 16.2
3483 *
3484 * @param bool $encode JSON encode the result.
3485 * @param bool $extended Adds additional stats data.
3486 *
3487 * @return array|string Stats data. Array if $encode is false. JSON-encoded string is $encode is true.
3488 */
3489 public static function get_stat_data( $encode = true, $extended = true ) {
3490 _deprecated_function( __METHOD__, 'jetpack-16.2', 'Automattic\\Jetpack\\Heartbeat::generate_stats_array' );
3491
3492 $env_stats = method_exists( Heartbeat::class, 'get_environment_stats' )
3493 ? Heartbeat::get_environment_stats()
3494 : array();
3495 $data = array_merge( Jetpack_Heartbeat::generate_stats_array(), $env_stats );
3496
3497 if ( $extended ) {
3498 $additional_data = self::get_additional_stat_data();
3499 $data = array_merge( $data, $additional_data );
3500 }
3501
3502 if ( $encode ) {
3503 return wp_json_encode( $data, JSON_UNESCAPED_SLASHES );
3504 }
3505
3506 return $data;
3507 }
3508
3509 /**
3510 * Get additional stat data to sync to WPCOM
3511 *
3512 * @param string $prefix Stats prefix.
3513 *
3514 * @return array stats values.
3515 */
3516 public static function get_additional_stat_data( $prefix = '' ) {
3517 $return = array();
3518 $return[ "{$prefix}themes" ] = self::get_parsed_theme_data();
3519 $return[ "{$prefix}plugins-extra" ] = self::get_parsed_plugin_data();
3520 $return[ "{$prefix}users" ] = (int) self::get_site_user_count();
3521 $return[ "{$prefix}site-count" ] = 0;
3522
3523 if ( function_exists( 'get_blog_count' ) ) {
3524 $return[ "{$prefix}site-count" ] = get_blog_count();
3525 }
3526 return $return;
3527 }
3528
3529 /**
3530 * Get current site's user count.
3531 *
3532 * @return int|string|null Number of users on the site. -1 for a large network.
3533 */
3534 private static function get_site_user_count() {
3535 global $wpdb;
3536
3537 if ( function_exists( 'wp_is_large_network' ) ) {
3538 if ( wp_is_large_network( 'users' ) ) {
3539 return -1; // Not a real value but should tell us that we are dealing with a large network.
3540 }
3541 }
3542 $user_count = get_transient( 'jetpack_site_user_count' );
3543 if ( false === ( $user_count ) ) {
3544 // It wasn't there, so regenerate the data and save the transient.
3545 $user_count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities'" );
3546 set_transient( 'jetpack_site_user_count', $user_count, DAY_IN_SECONDS );
3547 }
3548 return $user_count;
3549 }
3550
3551 /* Admin Pages */
3552
3553 /**
3554 * Admin init function.
3555 *
3556 * Runs on admin_init hook.
3557 *
3558 * @return void
3559 */
3560 public function admin_init() {
3561 // If the plugin is not connected, display a connect message.
3562 if (
3563 // the plugin was auto-activated and needs its candy.
3564 Jetpack_Options::get_option_and_ensure_autoload( 'do_activate', '0' )
3565 ||
3566 // the plugin is active, but was never activated. Probably came from a site-wide network activation.
3567 ! Jetpack_Options::get_option( 'activated' )
3568 ) {
3569 self::plugin_initialize();
3570 }
3571
3572 $is_offline_mode = ( new Status() )->is_offline_mode();
3573 $fallback_no_verify_ssl_certs = Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' );
3574 /** Already documented in automattic/jetpack-connection::src/class-client.php */
3575 $client_verify_ssl_certs = apply_filters( 'jetpack_client_verify_ssl_certs', false );
3576
3577 // Run post-activation actions if needed.
3578 $this->plugin_post_activation();
3579
3580 if ( ( self::is_connection_ready() || $is_offline_mode ) && false === $fallback_no_verify_ssl_certs && ! $client_verify_ssl_certs ) {
3581 // Upgrade: 1.1 -> 1.1.1
3582 // Check and see if host can verify the Jetpack servers' SSL certificate.
3583 $args = array();
3584 // @phan-suppress-next-line PhanAccessMethodInternal -- Phan is correct, but the usage is intentional.
3585 Client::_wp_remote_request( self::connection()->api_url( 'test' ), $args, true );
3586 }
3587
3588 if (
3589 current_user_can( 'manage_options' )
3590 && ! self::permit_ssl()
3591 && ! $is_offline_mode
3592 ) {
3593 add_action( 'jetpack_notices', array( $this, 'alert_auto_ssl_fail' ) );
3594 }
3595
3596 add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
3597 add_action( 'load-plugins.php', array( $this, 'plugins_page_init_jetpack_state' ) );
3598
3599 if ( ! ( is_multisite() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) && ! is_network_admin() ) ) {
3600 add_action( 'admin_enqueue_scripts', array( $this, 'deactivate_dialog' ) );
3601 }
3602
3603 add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
3604
3605 if ( self::is_connection_ready() || $is_offline_mode ) {
3606 // Artificially throw errors in certain specific cases during plugin activation.
3607 add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
3608 }
3609 }
3610
3611 /**
3612 * Adds body classes.
3613 *
3614 * @param string $admin_body_class Body classes.
3615 *
3616 * @return string
3617 */
3618 public function admin_body_class( $admin_body_class = '' ) {
3619 $classes = explode( ' ', trim( $admin_body_class ) );
3620
3621 $classes[] = self::is_connection_ready() ? 'jetpack-connected' : 'jetpack-disconnected';
3622
3623 $admin_body_class = implode( ' ', array_unique( $classes ) );
3624 return " $admin_body_class ";
3625 }
3626
3627 /**
3628 * Adds Jetpack Page styles by appending class to the admin body class.
3629 *
3630 * @param string $admin_body_class Existing admin body class string.
3631 *
3632 * @return string
3633 */
3634 public static function add_jetpack_pagestyles( $admin_body_class = '' ) {
3635 return $admin_body_class . ' jetpack-pagestyles ';
3636 }
3637
3638 /**
3639 * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
3640 * This function artificially throws errors for such cases (per a specific list).
3641 *
3642 * @param string $plugin The activated plugin.
3643 * @throws RuntimeException If a conflicting plugin is detected.
3644 */
3645 public function throw_error_on_activate_plugin( $plugin ) {
3646 $active_modules = self::get_active_modules();
3647
3648 // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
3649 if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules, true ) ) {
3650 $throw = false;
3651
3652 // Try and make sure it really was the stats plugin.
3653 if ( ! class_exists( 'ReflectionFunction' ) ) {
3654 if ( 'stats.php' === basename( $plugin ) ) {
3655 $throw = true;
3656 }
3657 } else {
3658 // @phan-suppress-next-line PhanUndeclaredFunctionInCallable -- Checked above. See also https://github.com/phan/phan/issues/1204.
3659 $reflection = new ReflectionFunction( 'stats_get_api_key' );
3660 if ( basename( $plugin ) === basename( $reflection->getFileName() ) ) {
3661 $throw = true;
3662 }
3663 }
3664
3665 if ( $throw ) {
3666 /* translators: Plugin name to deactivate. */
3667 throw new RuntimeException( sprintf( __( 'Jetpack contains the most recent version of the old "%1$s" plugin.', 'jetpack' ), 'WordPress.com Stats' ) );
3668 }
3669 }
3670 }
3671
3672 /**
3673 * Call to Jetpack::state on the load-plugins.php hook.
3674 * In case the jetpackState cookie is populated, this call will read and re-set the cookie before HTTP headers are sent.
3675 */
3676 public function plugins_page_init_jetpack_state() {
3677 self::state( 'message' );
3678 }
3679
3680 /**
3681 * Adds the intercept action to the check_admin_referer hook.
3682 *
3683 * @return void
3684 */
3685 public function intercept_plugin_error_scrape_init() {
3686 add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
3687 }
3688
3689 /**
3690 * Detect if conflicting plugin is being deactivated.
3691 *
3692 * @param string $action The nonce action.
3693 * @param bool|int $result False if the nonce is invalid, 1 if the nonce is valid and generated between 0-12 hours ago, 2 if the nonce is valid and generated between 12-24 hours ago.
3694 *
3695 * @return void
3696 */
3697 public function intercept_plugin_error_scrape( $action, $result ) {
3698 if ( ! $result ) {
3699 return;
3700 }
3701
3702 foreach ( $this->plugins_to_deactivate as $deactivate_us ) {
3703 foreach ( $deactivate_us as $deactivate_me ) {
3704 if ( "plugin-activation-error_{$deactivate_me[0]}" === $action ) {
3705 /* translators: Plugin name to deactivate. */
3706 self::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
3707 }
3708 }
3709 }
3710 }
3711
3712 /**
3713 * Register the remote file upload request handlers, if needed.
3714 *
3715 * @access public
3716 */
3717 public function add_remote_request_handlers() {
3718 // Remote file uploads are allowed only via AJAX requests.
3719 if ( ! is_admin() || ! Constants::get_constant( 'DOING_AJAX' ) ) {
3720 return;
3721 }
3722
3723 // Remote file uploads are allowed only for a set of specific AJAX actions.
3724 $remote_request_actions = array(
3725 'jetpack_upload_file',
3726 'jetpack_update_file',
3727 );
3728
3729 // phpcs:ignore WordPress.Security.NonceVerification
3730 if ( ! isset( $_POST['action'] ) || ! in_array( $_POST['action'], $remote_request_actions, true ) ) {
3731 return;
3732 }
3733
3734 // Require Jetpack authentication for the remote file upload AJAX requests.
3735 if ( ! $this->connection_manager ) {
3736 $this->connection_manager = new Connection_Manager();
3737 }
3738
3739 $this->connection_manager->require_jetpack_authentication();
3740
3741 // Register the remote file upload AJAX handlers.
3742 foreach ( $remote_request_actions as $action ) {
3743 add_action( "wp_ajax_nopriv_{$action}", array( $this, 'remote_request_handlers' ) );
3744 }
3745 }
3746
3747 /**
3748 * Handler for Jetpack remote file uploads.
3749 *
3750 * @access public
3751 * @return never
3752 */
3753 public function remote_request_handlers() {
3754 switch ( current_filter() ) {
3755 case 'wp_ajax_nopriv_jetpack_upload_file':
3756 $response = $this->upload_handler();
3757 break;
3758
3759 case 'wp_ajax_nopriv_jetpack_update_file':
3760 $response = $this->upload_handler( true );
3761 break;
3762 default:
3763 $response = new WP_Error( 'unknown_handler', 'Unknown Handler', 400 );
3764 break;
3765 }
3766
3767 if ( ! $response ) {
3768 $response = new WP_Error( 'unknown_error', 'Unknown Error', 400 );
3769 }
3770
3771 if ( is_wp_error( $response ) ) {
3772 $status_code = $response->get_error_data();
3773 $error = $response->get_error_code();
3774 $error_description = $response->get_error_message();
3775
3776 if ( ! is_int( $status_code ) ) {
3777 $status_code = 400;
3778 }
3779
3780 wp_send_json( (object) compact( 'error', 'error_description' ), $status_code, JSON_UNESCAPED_SLASHES );
3781 }
3782
3783 if ( true === $response ) {
3784 status_header( 200 );
3785 exit( 0 );
3786 }
3787
3788 wp_send_json( (object) $response, 200, JSON_UNESCAPED_SLASHES );
3789 }
3790
3791 /**
3792 * Uploads a file gotten from the global $_FILES.
3793 * If `$update_media_item` is true and `post_id` is defined
3794 * the attachment file of the media item (gotten through of the post_id)
3795 * will be updated instead of add a new one.
3796 *
3797 * @param boolean $update_media_item - update media attachment.
3798 * @return array|WP_Error - An array describing the uploading files process.
3799 */
3800 public function upload_handler( $update_media_item = false ) {
3801 if ( isset( $_SERVER['REQUEST_METHOD'] ) && 'POST' !== strtoupper( sanitize_text_field( wp_unslash( $_SERVER['REQUEST_METHOD'] ) ) ) ) {
3802 return new WP_Error( 405, get_status_header_desc( 405 ), 405 );
3803 }
3804
3805 $user = wp_authenticate( '', '' );
3806 if ( ! $user || is_wp_error( $user ) ) {
3807 return new WP_Error( 403, get_status_header_desc( 403 ), 403 );
3808 }
3809
3810 wp_set_current_user( $user->ID );
3811
3812 if ( ! current_user_can( 'upload_files' ) ) {
3813 return new WP_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
3814 }
3815
3816 if ( empty( $_FILES ) ) {
3817 return new WP_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
3818 }
3819
3820 foreach ( array_keys( $_FILES ) as $files_key ) {
3821 if ( ! isset( $_POST[ "_jetpack_file_hmac_{$files_key}" ] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Missing -- no site changes here.
3822 return new WP_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
3823 }
3824 }
3825
3826 $media_keys = isset( $_FILES['media'] ) ? array_keys( $_FILES['media'] ) : array(); // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- Unslash is not needed for `$_FILES`, the sniff is wrong. Sanitization should happen below.
3827
3828 $token = ( new Tokens() )->get_access_token( get_current_user_id() );
3829 if ( ! $token || is_wp_error( $token ) ) {
3830 return new WP_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
3831 }
3832
3833 /**
3834 * Optionally block uploads processed through Jetpack's upload_handler().
3835 * The filter may return false or WP_Error to block this particular upload.
3836 *
3837 * @since 10.8
3838 *
3839 * @param bool|WP_Error $allowed If false or WP_Error, block the upload. If true, allow the upload.
3840 * @param mixed $_FILES The $_FILES attempting to be uploaded.
3841 */
3842 $can_upload = apply_filters( 'jetpack_upload_handler_can_upload', true, $_FILES );
3843 if ( ! $can_upload || is_wp_error( $can_upload ) ) {
3844 if ( is_wp_error( $can_upload ) ) {
3845 return $can_upload;
3846 }
3847 return new WP_Error( 'handler_cannot_upload', __( 'The upload handler cannot upload files', 'jetpack' ), 400 );
3848 }
3849
3850 $uploaded_files = array();
3851 $global_post = $GLOBALS['post'] ?? null;
3852 unset( $GLOBALS['post'] );
3853 if ( empty( $_FILES['media']['name'] ) ) {
3854 // Nothing to process, just return.
3855 return $uploaded_files;
3856 }
3857 foreach ( $_FILES['media']['name'] as $index => $name ) { // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- As above, unslash sniff is wrong. Validation should happen below.
3858 $file = array();
3859 foreach ( $media_keys as $media_key ) {
3860 $file[ $media_key ] = $_FILES['media'][ $media_key ][ $index ] ?? null; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash,,WordPress.Security.NonceVerification.Missing,WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- As above, the unslash sniff is wrong.
3861 }
3862
3863 list( $hmac_provided, $salt ) = isset( $_POST['_jetpack_file_hmac_media'][ $index ] ) ? explode( ':', filter_var( wp_unslash( $_POST['_jetpack_file_hmac_media'][ $index ] ) ) ) : array( 'no', '' ); // phpcs:ignore WordPress.Security.NonceVerification.Missing -- Nonce should have been checked by the caller.
3864
3865 $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
3866 if ( $hmac_provided !== $hmac_file ) {
3867 $uploaded_files[ $index ] = (object) array(
3868 'error' => 'invalid_hmac',
3869 'error_description' => 'The corresponding HMAC for this file does not match',
3870 );
3871 continue;
3872 }
3873
3874 $_FILES['.jetpack.upload.'] = $file;
3875 $post_id = isset( $_POST['post_id'][ $index ] ) ? absint( $_POST['post_id'][ $index ] ) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Missing -- caller should have checked a nonce.
3876 if ( ! current_user_can( 'edit_post', $post_id ) ) {
3877 $post_id = 0;
3878 }
3879
3880 if ( $update_media_item ) {
3881 if ( ! isset( $post_id ) || 0 === $post_id ) {
3882 return new WP_Error( 'invalid_input', 'Media ID must be defined.', 400 );
3883 }
3884
3885 $media_array = $_FILES['media']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.MissingUnslash, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
3886
3887 $file_array = array();
3888 $file_array['name'] = $media_array['name'][0];
3889 $file_array['type'] = $media_array['type'][0];
3890 $file_array['tmp_name'] = $media_array['tmp_name'][0];
3891 $file_array['error'] = $media_array['error'][0];
3892 $file_array['size'] = $media_array['size'][0];
3893
3894 $edited_media_item = Jetpack_Media::edit_media_file( $post_id, $file_array );
3895
3896 if ( is_wp_error( $edited_media_item ) ) {
3897 return $edited_media_item;
3898 }
3899
3900 $response = (object) array(
3901 'id' => (string) $post_id,
3902 'file' => (string) $edited_media_item->post_title,
3903 'url' => (string) wp_get_attachment_url( $post_id ),
3904 'type' => (string) $edited_media_item->post_mime_type,
3905 'meta' => (array) wp_get_attachment_metadata( $post_id ),
3906 );
3907
3908 return array( $response );
3909 }
3910
3911 $attachment_id = media_handle_upload(
3912 '.jetpack.upload.',
3913 $post_id,
3914 array(),
3915 array(
3916 'action' => 'jetpack_upload_file',
3917 )
3918 );
3919
3920 if ( ! $attachment_id ) {
3921 $uploaded_files[ $index ] = (object) array(
3922 'error' => 'unknown',
3923 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site',
3924 );
3925 } elseif ( is_wp_error( $attachment_id ) ) {
3926 $uploaded_files[ $index ] = (object) array(
3927 'error' => 'attachment_' . $attachment_id->get_error_code(),
3928 'error_description' => $attachment_id->get_error_message(),
3929 );
3930 } else {
3931 $attachment = get_post( $attachment_id );
3932 $uploaded_files[ $index ] = (object) array(
3933 'id' => (string) $attachment_id,
3934 'file' => $attachment->post_title,
3935 'url' => wp_get_attachment_url( $attachment_id ),
3936 'type' => $attachment->post_mime_type,
3937 'meta' => wp_get_attachment_metadata( $attachment_id ),
3938 );
3939 }
3940 }
3941 if ( $global_post !== null ) {
3942 $GLOBALS['post'] = $global_post; // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited
3943 }
3944
3945 return $uploaded_files;
3946 }
3947
3948 /**
3949 * Add action links for the Jetpack plugin.
3950 *
3951 * @param array $actions Plugin actions.
3952 *
3953 * @return array
3954 */
3955 public function plugin_action_links( $actions ) {
3956 if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
3957 return array_merge(
3958 array( 'settings' => sprintf( '<a href="%s">%s</a>', esc_url( self::admin_url( 'page=jetpack-settings#/settings' ) ), __( 'Settings', 'jetpack' ) ) ),
3959 $actions
3960 );
3961 }
3962
3963 return $actions;
3964 }
3965
3966 /**
3967 * Adds the deactivation warning modal for Jetpack.
3968 *
3969 * @param string $hook The current admin page.
3970 *
3971 * @return void
3972 */
3973 public function deactivate_dialog( $hook ) {
3974 if (
3975 'plugins.php' === $hook
3976 && self::is_connection_ready()
3977 ) {
3978
3979 // Register jp-tracks-functions dependency.
3980 Tracking::register_tracks_functions_scripts( true );
3981
3982 // add a deactivation script that will pick up deactivation actions for the Jetpack plugin.
3983 Assets::register_script(
3984 'jetpack-plugins-page-js',
3985 '_inc/build/plugins-page.js',
3986 JETPACK__PLUGIN_FILE,
3987 array(
3988 'in_footer' => true,
3989 'textdomain' => 'jetpack',
3990 )
3991 );
3992 Assets::enqueue_script( 'jetpack-plugins-page-js' );
3993
3994 // Add objects to be passed to the initial state of the app.
3995 // Use wp_add_inline_script instead of wp_localize_script, see https://core.trac.wordpress.org/ticket/25280.
3996 wp_add_inline_script( 'jetpack-plugins-page-js', 'var Initial_State=' . wp_json_encode( Jetpack_Redux_State_Helper::get_plugins_page_state(), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ) . ';', 'before' );
3997
3998 add_action( 'admin_footer', array( $this, 'jetpack_plugin_portal_containers' ) );
3999 }
4000 }
4001
4002 /**
4003 * Outputs the wrapper for the plugin modal
4004 * Contents are loaded by React script
4005 *
4006 * @return void
4007 */
4008 public function jetpack_plugin_portal_containers() {
4009 $this->load_view( 'admin/jetpack-plugin-portal-containers.php' );
4010 }
4011
4012 /**
4013 * Filters the login URL to include the registration flow in case the user isn't logged in.
4014 *
4015 * @param string $login_url The wp-login URL.
4016 * @param string $redirect URL to redirect users after logging in.
4017 * @since Jetpack 8.4
4018 * @return string
4019 */
4020 public function login_url( $login_url, $redirect ) {
4021 parse_str( (string) wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4022 if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4023 $login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4024 }
4025 return $login_url;
4026 }
4027
4028 /**
4029 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4030 *
4031 * @since Jetpack 8.4
4032 */
4033 public function login_init() {
4034 // phpcs:ignore WordPress.Security.NonceVerification
4035 if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4036 add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_environments' ) );
4037 wp_safe_redirect(
4038 add_query_arg(
4039 array(
4040 'forceInstall' => 1,
4041 'url' => rawurlencode( get_site_url() ),
4042 ),
4043 // @todo provide way to go to specific calypso env.
4044 self::get_calypso_host() . 'jetpack/connect'
4045 )
4046 );
4047 exit( 0 );
4048 }
4049 }
4050
4051 /*
4052 * Registration flow:
4053 * 1 - ::admin_page_load() action=register
4054 * 2 - ::try_registration()
4055 * 3 - ::register()
4056 * - Creates jetpack_register option containing two secrets and a timestamp
4057 * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4058 * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4059 * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
4060 * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4061 * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4062 * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4063 * jetpack_id, jetpack_secret, jetpack_public
4064 * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4065 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4066 * 5 - user logs in with WP.com account
4067 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4068 * - Manager::authorize()
4069 * - Manager::get_token()
4070 * - GET https://jetpack.wordpress.com/jetpack.token/1/ with
4071 * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4072 * - which responds with access_token, token_type, scope
4073 * - Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4074 * - Jetpack::activate_default_modules()
4075 * - Deactivates deprecated plugins
4076 * - Activates all default modules
4077 * - Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4078 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4079 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4080 * Done!
4081 */
4082
4083 /**
4084 * Build the user-facing description stored alongside a registration error code.
4085 *
4086 * @since 16.2
4087 *
4088 * @param string $error_code The WP_Error code.
4089 * @param string $message The WP_Error message.
4090 * @return string The description, empty when the message is not user-facing copy.
4091 */
4092 public static function get_registration_error_description( $error_code, $message ) {
4093 // Manager::validate_remote_register_response() does not always put user-facing copy in the
4094 // message slot: wpcom_5??, wpcom_408 and wpcom_bad_response store the HTTP status there,
4095 // and jetpack_id stores the raw response body, which can also overflow the state cookie.
4096 if ( 'jetpack_id' === $error_code || is_numeric( $message ) ) {
4097 return '';
4098 }
4099
4100 return mb_substr( (string) $message, 0, 250 );
4101 }
4102
4103 /**
4104 * Handles the page load events for the Jetpack admin page
4105 */
4106 public function admin_page_load() {
4107 $error = false;
4108
4109 // Make sure we have the right body class to hook stylings for subpages off of.
4110 add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4111
4112 if ( ! empty( $_GET['jetpack_restate'] ) ) {
4113 // Should only be used in intermediate redirects to preserve state across redirects.
4114 self::restate();
4115 }
4116
4117 if ( isset( $_GET['action'] ) ) {
4118 switch ( $_GET['action'] ) {
4119 /**
4120 * Cases authorize and authorize_redirect are now handled by Connection package Webhooks
4121 */
4122 case 'authorize_redirect':
4123 case 'authorize':
4124 break;
4125 case 'register':
4126 if ( ! current_user_can( 'jetpack_connect' ) ) {
4127 $error = 'cheatin';
4128 break;
4129 }
4130 check_admin_referer( 'jetpack-register' );
4131 self::log( 'register' );
4132 self::maybe_set_version_option();
4133 $from = isset( $_GET['from'] ) ? sanitize_text_field( wp_unslash( $_GET['from'] ) ) : false;
4134 if ( $from ) {
4135 static::connection()->add_register_request_param( 'from', (string) $from );
4136 }
4137 $registered = static::connection()->try_registration();
4138 if ( is_wp_error( $registered ) ) {
4139 $error = $registered->get_error_code();
4140 self::state( 'error', $error );
4141
4142 self::state( 'error_description', self::get_registration_error_description( $error, $registered->get_error_message() ) );
4143
4144 /**
4145 * Jetpack registration Error.
4146 *
4147 * @since 7.5.0
4148 *
4149 * @param string|int $error The error code.
4150 * @param \WP_Error $registered The error object.
4151 */
4152 do_action( 'jetpack_connection_register_fail', $error, $registered );
4153 break;
4154 }
4155
4156 $redirect = isset( $_GET['redirect'] ) ? wp_unslash( $_GET['redirect'] ) : false; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
4157
4158 /**
4159 * Jetpack registration Success.
4160 *
4161 * @since 7.5.0
4162 *
4163 * @param string $from 'from' GET parameter;
4164 */
4165 do_action( 'jetpack_connection_register_success', $from );
4166
4167 $url = $this->build_connect_url( true, $redirect, $from );
4168
4169 if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4170 $url = add_query_arg( 'auth_approved', 'true', $url );
4171 }
4172
4173 add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_environments' ) );
4174 wp_safe_redirect( $url );
4175 exit( 0 );
4176 case 'activate':
4177 if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4178 $error = 'cheatin';
4179 break;
4180 }
4181
4182 $module = isset( $_GET['module'] ) ? sanitize_text_field( wp_unslash( $_GET['module'] ) ) : '';
4183 check_admin_referer( "jetpack_activate-$module" );
4184 self::log( 'activate', $module );
4185 if ( ! self::activate_module( $module ) ) {
4186 /* translators: module/feature name */
4187 self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4188 }
4189 // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4190 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4191 exit( 0 );
4192 case 'activate_default_modules':
4193 check_admin_referer( 'activate_default_modules' );
4194 self::log( 'activate_default_modules' );
4195 self::restate();
4196 $min_version = isset( $_GET['min_version'] ) ? sanitize_text_field( wp_unslash( $_GET['min_version'] ) ) : false;
4197 $max_version = isset( $_GET['max_version'] ) ? sanitize_text_field( wp_unslash( $_GET['max_version'] ) ) : false;
4198 $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? array_map( 'sanitize_text_field', wp_unslash( $_GET['other_modules'] ) ) : array();
4199 self::activate_default_modules( $min_version, $max_version, $other_modules );
4200 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4201 exit( 0 );
4202 case 'disconnect':
4203 if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4204 $error = 'cheatin';
4205 break;
4206 }
4207
4208 check_admin_referer( 'jetpack-disconnect' );
4209 self::log( 'disconnect' );
4210 self::disconnect();
4211 wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4212 exit( 0 );
4213 case 'reconnect':
4214 if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4215 $error = 'cheatin';
4216 break;
4217 }
4218
4219 check_admin_referer( 'jetpack-reconnect' );
4220 self::log( 'reconnect' );
4221 self::disconnect();
4222
4223 add_filter( 'allowed_redirect_hosts', array( Host::class, 'allow_wpcom_environments' ) );
4224 wp_safe_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4225 exit( 0 );
4226 case 'deactivate':
4227 if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4228 $error = 'cheatin';
4229 break;
4230 }
4231
4232 $modules = sanitize_text_field( wp_unslash( $_GET['module'] ) );
4233 check_admin_referer( "jetpack_deactivate-$modules" );
4234 foreach ( explode( ',', $modules ) as $module ) {
4235 self::log( 'deactivate', $module );
4236 self::deactivate_module( $module );
4237 self::state( 'message', 'module_deactivated' );
4238 }
4239 self::state( 'module', $modules );
4240 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4241 exit( 0 );
4242 case 'unlink':
4243 $redirect = isset( $_GET['redirect'] ) ? sanitize_text_field( wp_unslash( $_GET['redirect'] ) ) : '';
4244 check_admin_referer( 'jetpack-unlink' );
4245 self::log( 'unlink' );
4246 $this->connection_manager->disconnect_user();
4247 self::state( 'message', 'unlinked' );
4248 if ( 'sub-unlink' === $redirect ) {
4249 wp_safe_redirect( admin_url() );
4250 } else {
4251 wp_safe_redirect( self::admin_url( array( 'page' => rawurlencode( $redirect ) ) ) );
4252 }
4253 exit( 0 );
4254 default:
4255 /**
4256 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4257 *
4258 * @since 2.6.0
4259 *
4260 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4261 */
4262 do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4263 }
4264 }
4265
4266 $error = $error ? $error : self::state( 'error' );
4267 if ( ! $error ) {
4268 self::activate_new_modules( true );
4269 }
4270
4271 $activated_manage = false;
4272 $message_code = self::state( 'message' );
4273 if ( self::state( 'optin-manage' ) ) {
4274 $activated_manage = $message_code;
4275 $message_code = 'jetpack-manage';
4276 }
4277
4278 switch ( $message_code ) {
4279 case 'jetpack-manage':
4280 $sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4281 // translators: %s is the URL to the "Sites" panel on wordpress.com.
4282 $this->message = '<strong>' . sprintf( __( 'You are all set! Your site can now be managed from <a href="%s" target="_blank">wordpress.com/sites</a>.', 'jetpack' ), $sites_url ) . '</strong>';
4283 if ( $activated_manage ) {
4284 $this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4285 }
4286 break;
4287
4288 }
4289
4290 $deactivated_plugins = self::state( 'deactivated_plugins' );
4291
4292 if ( ! empty( $deactivated_plugins ) ) {
4293 $deactivated_plugins = explode( ',', $deactivated_plugins );
4294 $deactivated_titles = array();
4295 foreach ( $deactivated_plugins as $deactivated_plugin ) {
4296 list( $module, $idx ) = explode( ':', $deactivated_plugin );
4297 if ( ! isset( $this->plugins_to_deactivate[ $module ][ $idx ] ) ) {
4298 continue;
4299 }
4300
4301 $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $module ][ $idx ][1] ) . '</strong>';
4302 }
4303
4304 if ( $deactivated_titles ) {
4305 if ( $this->message ) {
4306 $this->message .= "<br /><br />\n";
4307 }
4308
4309 $this->message .= wp_sprintf(
4310 _n(
4311 'Jetpack contains the most recent version of the old %l plugin.',
4312 'Jetpack contains the most recent versions of the old %l plugins.',
4313 count( $deactivated_titles ),
4314 'jetpack'
4315 ),
4316 $deactivated_titles
4317 );
4318
4319 $this->message .= "<br />\n";
4320
4321 $this->message .= _n(
4322 'The old version has been deactivated and can be removed from your site.',
4323 'The old versions have been deactivated and can be removed from your site.',
4324 count( $deactivated_titles ),
4325 'jetpack'
4326 );
4327 }
4328 }
4329
4330 $this->privacy_checks = self::state( 'privacy_checks' );
4331
4332 if ( $this->message || $this->error || $this->privacy_checks ) {
4333 add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4334 }
4335
4336 add_filter( 'jetpack_short_module_description', 'wptexturize' );
4337 }
4338
4339 /**
4340 * Display admin notice upon error.
4341 *
4342 * @return void
4343 */
4344 public function admin_notices() {
4345
4346 if ( $this->error ) {
4347 ?>
4348 <div id="message" class="jetpack-message jetpack-err">
4349 <div class="squeezer">
4350 <h2>
4351 <?php
4352 echo wp_kses(
4353 $this->error,
4354 array(
4355 'a' => array( 'href' => array() ),
4356 'small' => true,
4357 'code' => true,
4358 'strong' => true,
4359 'br' => true,
4360 'b' => true,
4361 )
4362 );
4363 ?>
4364 </h2>
4365 <?php
4366 $desc = self::state( 'error_description' );
4367 if ( $desc ) :
4368 ?>
4369 <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4370 <?php endif; ?>
4371 </div>
4372 </div>
4373 <?php
4374 }
4375
4376 if ( $this->message ) {
4377 ?>
4378 <div id="message" class="jetpack-message">
4379 <div class="squeezer">
4380 <h2>
4381 <?php
4382 echo wp_kses(
4383 $this->message,
4384 array(
4385 'strong' => array(),
4386 'a' => array( 'href' => true ),
4387 'br' => true,
4388 )
4389 );
4390 ?>
4391 </h2>
4392 </div>
4393 </div>
4394 <?php
4395 }
4396
4397 if ( $this->privacy_checks ) :
4398 $module_names = array();
4399 $module_slugs = array();
4400
4401 $privacy_checks = explode( ',', $this->privacy_checks );
4402 $privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4403 foreach ( $privacy_checks as $module_slug ) {
4404 $module = self::get_module( $module_slug );
4405 if ( ! $module ) {
4406 continue;
4407 }
4408
4409 $module_slugs[] = $module_slug;
4410 $module_names[] = "<strong>{$module['name']}</strong>";
4411 }
4412
4413 $module_slugs = implode( ',', $module_slugs );
4414 ?>
4415 <div id="message" class="jetpack-message jetpack-err">
4416 <div class="squeezer">
4417 <h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4418 <p>
4419 <?php
4420 echo wp_kses(
4421 wptexturize(
4422 wp_sprintf(
4423 _nx(
4424 "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4425 "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4426 count( $privacy_checks ),
4427 '%l = list of Jetpack module/feature names',
4428 'jetpack'
4429 ),
4430 $module_names
4431 )
4432 ),
4433 array( 'strong' => true )
4434 );
4435
4436 echo "\n<br />\n";
4437
4438 echo wp_kses(
4439 sprintf(
4440 /* translators: URL to deactivate Jetpack features. */
4441 _nx(
4442 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4443 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4444 count( $privacy_checks ),
4445 '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4446 'jetpack'
4447 ),
4448 esc_url(
4449 wp_nonce_url(
4450 self::admin_url(
4451 array(
4452 'page' => 'jetpack',
4453 'action' => 'deactivate',
4454 'module' => rawurlencode( $module_slugs ),
4455 )
4456 ),
4457 "jetpack_deactivate-$module_slugs"
4458 )
4459 ),
4460 esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4461 ),
4462 array(
4463 'a' => array(
4464 'href' => true,
4465 'title' => true,
4466 ),
4467 )
4468 );
4469 ?>
4470 </p>
4471 </div>
4472 </div>
4473 <?php
4474 endif;
4475 }
4476
4477 /**
4478 * Initialize the jetpack stats instance only when needed
4479 *
4480 * @return void
4481 */
4482 private function initialize_stats() {
4483 if ( $this->a8c_mc_stats_instance === null ) {
4484 $this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4485 }
4486 }
4487
4488 /**
4489 * Record a stat for later output. This will only currently output in the admin_footer.
4490 *
4491 * @param string $group Stats group.
4492 * @param string $detail Stats detail.
4493 */
4494 public function stat( $group, $detail ) {
4495 $this->initialize_stats();
4496 $this->a8c_mc_stats_instance->add( $group, $detail );
4497
4498 // Keep a local copy for backward compatibility (there are some direct checks on this).
4499 $this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4500 }
4501
4502 /**
4503 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4504 *
4505 * @param string $method Used to check if method is "server-side".
4506 */
4507 public function do_stats( $method = '' ) {
4508 $this->initialize_stats();
4509 if ( 'server_side' === $method ) {
4510 $this->a8c_mc_stats_instance->do_server_side_stats();
4511 } else {
4512 $this->a8c_mc_stats_instance->do_stats();
4513 }
4514
4515 // Keep a local copy for backward compatibility (there are some direct checks on this).
4516 $this->stats = array();
4517 }
4518
4519 /**
4520 * Runs stats code for a one-off, server-side.
4521 *
4522 * @param array|string $args The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4523 *
4524 * @return bool If it worked.
4525 */
4526 public static function do_server_side_stat( $args ) {
4527 $url = self::build_stats_url( $args );
4528 $a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4529 return $a8c_mc_stats_instance->do_server_side_stat( $url );
4530 }
4531
4532 /**
4533 * Builds the stats url.
4534 *
4535 * @param array|string $args The arguments to append to the URL.
4536 *
4537 * @return string The URL to be pinged.
4538 */
4539 public static function build_stats_url( $args ) {
4540
4541 $a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4542 return $a8c_mc_stats_instance->build_stats_url( $args );
4543 }
4544
4545 /**
4546 * Builds a URL to the Jetpack connection auth page
4547 *
4548 * @since 3.9.5
4549 *
4550 * @param bool $raw If true, URL will not be escaped.
4551 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4552 * If string, will be a custom redirect.
4553 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4554 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0.
4555 *
4556 * @return string Connect URL
4557 */
4558 public function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4559 $site_id = Jetpack_Options::get_option( 'id' );
4560 $blog_token = ( new Tokens() )->get_access_token();
4561
4562 if ( $register || ! $blog_token || ! $site_id ) {
4563 $url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4564
4565 if ( ! empty( $redirect ) ) {
4566 $url = add_query_arg(
4567 'redirect',
4568 rawurlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4569 $url
4570 );
4571 }
4572
4573 if ( is_network_admin() ) {
4574 $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4575 }
4576
4577 $calypso_env = ( new Host() )->get_calypso_env();
4578
4579 if ( ! empty( $calypso_env ) ) {
4580 $url = add_query_arg( 'calypso_env', $calypso_env, $url );
4581 }
4582 } else {
4583
4584 // Let's check the existing blog token to see if we need to re-register. We only check once per minute
4585 // because otherwise this logic can get us in to a loop.
4586 $last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4587 if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4588 Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4589
4590 $response = Client::wpcom_json_api_request_as_blog(
4591 sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4592 '1.1'
4593 );
4594
4595 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4596
4597 // Generating a register URL instead to refresh the existing token.
4598 return $this->build_connect_url( $raw, $redirect, $from, true );
4599 }
4600 }
4601
4602 $url = ( new Authorize_Redirect( static::connection() ) )->build_authorize_url( $redirect );
4603 }
4604
4605 if ( $from ) {
4606 $url = add_query_arg( 'from', $from, $url );
4607 }
4608
4609 $url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4610 /**
4611 * Filter the URL used when connecting a user to a WordPress.com account.
4612 *
4613 * @since 8.1.0
4614 *
4615 * @param string $url Connection URL.
4616 * @param bool $raw If true, URL will not be escaped.
4617 */
4618 return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4619 }
4620
4621 /**
4622 * Create the Jetpack authorization URL.
4623 *
4624 * @param bool|string $redirect URL to redirect to.
4625 * @param null $deprecated Deprecated since Jetpack 10.9.
4626 *
4627 * @todo Update default value for redirect since the called function expects a string.
4628 *
4629 * @deprecated 13.4
4630 *
4631 * @return mixed|void
4632 */
4633 public static function build_authorize_url( $redirect = false, $deprecated = null ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
4634 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Authorize_Redirect::build_authorize_url' );
4635
4636 return ( new Authorize_Redirect( static::connection() ) )->build_authorize_url( $redirect );
4637 }
4638
4639 /**
4640 * Filters the connection URL parameter array.
4641 *
4642 * @deprecated 13.4
4643 *
4644 * @param array $args default URL parameters used by the package.
4645 * @return array the modified URL arguments array.
4646 */
4647 public static function filter_connect_request_body( $args ) {
4648 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Authorize_Redirect::filter_connect_request_body' );
4649
4650 return Authorize_Redirect::filter_connect_request_body( $args );
4651 }
4652
4653 /**
4654 * Filters the `jetpack/v4/connection/data` API response of the Connection package in order to
4655 * add Jetpack-the-plugin related permissions.
4656 *
4657 * @since 10.0
4658 *
4659 * @param array $current_user_connection_data An array containing the current user connection data.
4660 * @return array
4661 */
4662 public static function filter_jetpack_current_user_connection_data( $current_user_connection_data ) {
4663 $jetpack_permissions = array(
4664 'admin_page' => current_user_can( 'jetpack_admin_page' ),
4665 'manage_modules' => current_user_can( 'jetpack_manage_modules' ),
4666 'network_admin' => current_user_can( 'jetpack_network_admin_page' ),
4667 'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
4668 'edit_posts' => current_user_can( 'edit_posts' ),
4669 'publish_posts' => current_user_can( 'publish_posts' ),
4670 'manage_options' => current_user_can( 'manage_options' ),
4671 'view_stats' => current_user_can( 'view_stats' ),
4672 'manage_plugins' => current_user_can( 'install_plugins' )
4673 && current_user_can( 'activate_plugins' )
4674 && current_user_can( 'update_plugins' )
4675 && current_user_can( 'delete_plugins' ),
4676 );
4677
4678 if ( isset( $current_user_connection_data['permissions'] ) &&
4679 is_array( $current_user_connection_data['permissions'] ) ) {
4680 $current_user_connection_data['permissions'] = array_merge( $current_user_connection_data['permissions'], $jetpack_permissions );
4681 } else {
4682 $current_user_connection_data['permissions'] = $jetpack_permissions;
4683 }
4684
4685 return $current_user_connection_data;
4686 }
4687
4688 /**
4689 * Filters the redirection URL that is used for connect requests. The redirect
4690 * URL should return the user back to the Jetpack console.
4691 *
4692 * @deprecated 13.4
4693 *
4694 * @param String $redirect the default redirect URL used by the package.
4695 * @return String the modified URL.
4696 */
4697 public static function filter_connect_redirect_url( $redirect ) {
4698 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Authorize_Redirect::filter_connect_redirect_url' );
4699 return Authorize_Redirect::filter_connect_redirect_url( $redirect );
4700 }
4701
4702 /**
4703 * This action fires at the beginning of the Manager::authorize method.
4704 */
4705 public static function authorize_starting() {
4706 $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
4707 // Checking if site has been active/connected previously before recording unique connection.
4708 if ( ! $jetpack_unique_connection ) {
4709 // jetpack_unique_connection option has never been set.
4710 $jetpack_unique_connection = array(
4711 'connected' => 0,
4712 'disconnected' => 0,
4713 'version' => '3.6.1',
4714 );
4715
4716 update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
4717
4718 // Track unique connection.
4719 $jetpack = self::init();
4720
4721 $jetpack->stat( 'connections', 'unique-connection' );
4722 $jetpack->do_stats( 'server_side' );
4723 }
4724
4725 // Increment number of times connected.
4726 $jetpack_unique_connection['connected'] += 1;
4727 Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
4728 }
4729
4730 /**
4731 * This action fires when the site is registered (connected at a site level).
4732 */
4733 public function handle_unique_registrations_stats() {
4734 $jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
4735 // Checking if site has been registered previously before recording unique connection.
4736 if ( ! $jetpack_unique_registrations ) {
4737
4738 $jetpack_unique_registrations = 0;
4739
4740 $this->stat( 'connections', 'unique-registrations' );
4741 $this->do_stats( 'server_side' );
4742 }
4743
4744 // Increment number of times connected.
4745 ++$jetpack_unique_registrations;
4746 Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
4747 }
4748
4749 /**
4750 * This action fires at the end of the Manager::authorize method when a secondary user is
4751 * linked.
4752 */
4753 public static function authorize_ending_linked() {
4754 // Don't activate anything since we are just connecting a user.
4755 self::state( 'message', 'linked' );
4756 }
4757
4758 /**
4759 * This action fires at the end of the Manager::authorize method when the master user is
4760 * authorized.
4761 *
4762 * @param array $data The request data.
4763 */
4764 public static function authorize_ending_authorized( $data ) {
4765 // If redirect_uri is SSO, ensure SSO module is enabled.
4766 parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
4767
4768 /** This filter is documented in class.jetpack-cli.php */
4769 $jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
4770
4771 $activate_sso = (
4772 isset( $redirect_options['action'] ) &&
4773 'jetpack-sso' === $redirect_options['action'] &&
4774 $jetpack_start_enable_sso
4775 );
4776
4777 $do_redirect_on_error = ( 'client' === $data['auth_type'] );
4778
4779 self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
4780 }
4781
4782 /**
4783 * Fires on the jetpack_site_registered hook and acitvates default modules
4784 */
4785 public static function activate_default_modules_on_site_register() {
4786 self::handle_default_module_activation( false );
4787
4788 // Since this is a fresh connection, be sure to clear out IDC options.
4789 Identity_Crisis::clear_all_idc_options();
4790 }
4791
4792 /**
4793 * This action fires at the end of the REST_Connector connection_reconnect method when the
4794 * reconnect process is completed.
4795 * Note that this currently only happens when we don't need the user to re-authorize
4796 * their WP.com account, eg in cases where we are restoring a connection with
4797 * unhealthy blog token.
4798 */
4799 public static function reconnection_completed() {
4800 self::state( 'message', 'reconnection_completed' );
4801 }
4802
4803 /**
4804 * Apply activation source to a query string array.
4805 *
4806 * @param array $args Args used for a query string.
4807 *
4808 * @return void
4809 */
4810 public static function apply_activation_source_to_args( &$args ) {
4811 list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
4812
4813 if ( $activation_source_name ) {
4814 $args['_as'] = rawurlencode( $activation_source_name );
4815 }
4816
4817 if ( $activation_source_keyword ) {
4818 $args['_ak'] = rawurlencode( $activation_source_keyword );
4819 }
4820 }
4821
4822 /**
4823 * Returns the reconnection URL.
4824 *
4825 * @param bool $raw True to return an unescaped URL. False returns value after `esc_url`.
4826 *
4827 * @return string|null
4828 */
4829 public function build_reconnect_url( $raw = false ) {
4830 $url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
4831 return $raw ? $url : esc_url( $url );
4832 }
4833
4834 /**
4835 * Jetpack Admin URL.
4836 *
4837 * @param array $args Query string args.
4838 *
4839 * @return string Jetpack admin URL.
4840 */
4841 public static function admin_url( $args = null ) {
4842 return ( new Paths() )->admin_url( $args );
4843 }
4844
4845 /**
4846 * Creates a nonce from an URL.
4847 *
4848 * @param string $actionurl URL for action.
4849 * @param string $action Nonce action.
4850 * @param string $name Query arg name.
4851 *
4852 * @return string
4853 */
4854 public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
4855 $actionurl = str_replace( '&amp;', '&', $actionurl );
4856 return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
4857 }
4858
4859 /**
4860 * Dismiss Jetpack notices.
4861 *
4862 * @return void
4863 */
4864 public function dismiss_jetpack_notice() {
4865 if ( ! isset( $_GET['jetpack-notice'] ) ) {
4866 return;
4867 }
4868
4869 switch ( $_GET['jetpack-notice'] ) {
4870 case 'dismiss':
4871 if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
4872
4873 require_once ABSPATH . 'wp-admin/includes/plugin.php';
4874 deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
4875 wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
4876 }
4877 break;
4878 }
4879 }
4880
4881 /**
4882 * Determines which module has a higher sort order.
4883 *
4884 * @param array $a Modules array.
4885 * @param array $b Modules array.
4886 *
4887 * @return int 0 if the same sort or (+/-) to indicate which is greater.
4888 */
4889 public static function sort_modules( $a, $b ) {
4890 return $a['sort'] <=> $b['sort'];
4891 }
4892
4893 /**
4894 * Recheck SSL status for use via an AJAX call.
4895 *
4896 * Sends data back via `wp_send_json`.
4897 *
4898 * @return void
4899 */
4900 public function ajax_recheck_ssl() {
4901 check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
4902 $result = self::permit_ssl( true );
4903 wp_send_json(
4904 array(
4905 'enabled' => $result,
4906 'message' => self::get_ssl_test_message(),
4907 ),
4908 null, // @phan-suppress-current-line PhanTypeMismatchArgumentProbablyReal -- It takes null, but its phpdoc only says int.
4909 JSON_UNESCAPED_SLASHES
4910 );
4911 }
4912
4913 /* Client API */
4914
4915 /**
4916 * Verify the onboarding token.
4917 *
4918 * @deprecated since 13.9
4919 *
4920 * @param array $token_data Token data.
4921 * @param string $token Token value.
4922 * @param string $request_data JSON-encoded request data.
4923 *
4924 * @return mixed
4925 */
4926 public static function verify_onboarding_token( $token_data, $token, $request_data ) {
4927 _deprecated_function( __METHOD__, '13.9' );
4928 // Default to a blog token.
4929 $token_type = 'blog';
4930
4931 // Let's see if this is onboarding. In such case, use user token type and the provided user id.
4932 if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes, if caller is changing the site the nonce should be verified there.
4933 if ( ! empty( $_GET['onboarding'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
4934 $jpo = $_GET; // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
4935 } else {
4936 $jpo = json_decode( $request_data, true );
4937 }
4938
4939 $jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
4940 $jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
4941
4942 if (
4943 isset( $jpo_user )
4944 && isset( $jpo_token )
4945 && is_email( $jpo_user )
4946 && ctype_alnum( $jpo_token )
4947 && isset( $_GET['rest_route'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- no site changes.
4948 && self::validate_onboarding_token_action(
4949 $jpo_token,
4950 wp_unslash( $_GET['rest_route'] ) // phpcs:ignore WordPress.Security.NonceVerification.Recommended, WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- no site changes.
4951 )
4952 ) {
4953 $jp_user = get_user_by( 'email', $jpo_user );
4954 if ( is_a( $jp_user, 'WP_User' ) ) {
4955 wp_set_current_user( $jp_user->ID );
4956 $user_can = is_multisite()
4957 ? current_user_can_for_site( get_current_blog_id(), 'manage_options' )
4958 : current_user_can( 'manage_options' );
4959 if ( $user_can ) {
4960 $token_type = 'user';
4961 $token->external_user_id = $jp_user->ID;
4962 }
4963 }
4964 }
4965
4966 $token_data['type'] = $token_type;
4967 $token_data['user_id'] = $token->external_user_id;
4968 }
4969
4970 return $token_data;
4971 }
4972
4973 /**
4974 * Create a random secret for validating onboarding payload
4975 *
4976 * @deprecated since 13.9
4977 * @return string Secret token
4978 */
4979 public static function create_onboarding_token() {
4980 _deprecated_function( __METHOD__, '13.9' );
4981 $token = Jetpack_Options::get_option( 'onboarding' );
4982 if ( false === ( $token ) ) {
4983 $token = wp_generate_password( 32, false );
4984 Jetpack_Options::update_option( 'onboarding', $token );
4985 }
4986
4987 return $token;
4988 }
4989
4990 /**
4991 * Remove the onboarding token
4992 *
4993 * @deprecated since 13.9
4994 * @return bool True on success, false on failure
4995 */
4996 public static function invalidate_onboarding_token() {
4997 _deprecated_function( __METHOD__, '13.9' );
4998 return Jetpack_Options::delete_option( 'onboarding' );
4999 }
5000
5001 /**
5002 * Validate an onboarding token for a specific action
5003 *
5004 * @deprecated since 13.9
5005 *
5006 * @param string $token Onboarding token.
5007 * @param string $action Action name.
5008 *
5009 * @return boolean True if token/action pair is accepted, false if not
5010 */
5011 public static function validate_onboarding_token_action( $token, $action ) {
5012 _deprecated_function( __METHOD__, '13.9' );
5013 // Compare tokens, bail if tokens do not match.
5014 if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5015 return false;
5016 }
5017
5018 // List of valid actions we can take.
5019 $valid_actions = array(
5020 '/jetpack/v4/settings',
5021 );
5022
5023 // Only allow valid actions.
5024 if ( ! in_array( $action, $valid_actions, true ) ) {
5025 return false;
5026 }
5027
5028 return true;
5029 }
5030
5031 /**
5032 * Checks to see if the URL is using SSL to connect with Jetpack
5033 *
5034 * @param bool $force_recheck Force SSL recheck.
5035 *
5036 * @return boolean
5037 * @since 2.3.3
5038 */
5039 public static function permit_ssl( $force_recheck = false ) {
5040 if ( ! method_exists( Heartbeat::class, 'permit_ssl' ) ) {
5041 // Skip the SSL-fail notice when the check cannot run.
5042 return true;
5043 }
5044
5045 return Heartbeat::permit_ssl( $force_recheck );
5046 }
5047
5048 /**
5049 * Returns a localized message describing the last SSL connectivity failure, if any.
5050 *
5051 * The Connection package's canonical SSL check stores a neutral reason code; this maps it to
5052 * a translated, `jetpack`-domain message for display in the admin notice and AJAX recheck.
5053 *
5054 * @since 16.1
5055 *
5056 * @return string The localized message, or an empty string when there is no failure.
5057 */
5058 public static function get_ssl_test_message() {
5059 if ( ! method_exists( Heartbeat::class, 'get_ssl_test_error' ) ) {
5060 return '';
5061 }
5062
5063 $error = Heartbeat::get_ssl_test_error();
5064
5065 switch ( $error['code'] ) {
5066 case 'no_ssl_support':
5067 return __( 'WordPress reports no SSL support', 'jetpack' );
5068 case 'bad_response':
5069 return __( 'Response was not OK: ', 'jetpack' ) . $error['detail'];
5070 default:
5071 return '';
5072 }
5073 }
5074
5075 /**
5076 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5077 */
5078 public function alert_auto_ssl_fail() {
5079 if ( ! current_user_can( 'manage_options' ) ) {
5080 return;
5081 }
5082
5083 $ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5084 ?>
5085
5086 <div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5087 <div class="jp-banner__content">
5088 <h2><?php esc_html_e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5089 <p><?php esc_html_e( 'Your site could not connect to WordPress.com via HTTPS. This could be due to any number of reasons, including faulty SSL certificates, misconfigured or missing SSL libraries, or network issues.', 'jetpack' ); ?></p>
5090 <p>
5091 <?php esc_html_e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5092 <a href="#" id="jetpack-recheck-ssl-button"><?php esc_html_e( 'Try again', 'jetpack' ); ?></a>
5093 <span id="jetpack-recheck-ssl-output"><?php echo esc_html( self::get_ssl_test_message() ); ?></span>
5094 </p>
5095 <p>
5096 <?php
5097 printf(
5098 /* translators: Both are URLs. First for the connection debug tool and the second for a support page. */
5099 __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ), // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- we're building known HTML.
5100 esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5101 esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5102 );
5103 ?>
5104 </p>
5105 </div>
5106 </div>
5107 <style>
5108 #jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5109 </style>
5110 <script type="text/javascript">
5111 jQuery( document ).ready( function( $ ) {
5112 $( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5113 var $this = $( this );
5114 $this.html( <?php echo wp_json_encode( esc_html__( 'Checking', 'jetpack' ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
5115 $( '#jetpack-recheck-ssl-output' ).html( '' );
5116 e.preventDefault();
5117 var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': <?php echo wp_json_encode( $ajax_nonce, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> };
5118 $.post( ajaxurl, data )
5119 .done( function( response ) {
5120 if ( response.enabled ) {
5121 $( '#jetpack-ssl-warning' ).hide();
5122 } else {
5123 this.html( <?php echo wp_json_encode( esc_html__( 'Try again', 'jetpack' ), JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP ); ?> );
5124 $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5125 }
5126 }.bind( $this ) );
5127 } );
5128 } );
5129 </script>
5130
5131 <?php
5132 }
5133
5134 /**
5135 * Returns the connection manager object.
5136 *
5137 * @return Automattic\Jetpack\Connection\Manager
5138 */
5139 public static function connection() {
5140 $jetpack = static::init();
5141
5142 // If the connection manager hasn't been instantiated, do that now.
5143 if ( ! $jetpack->connection_manager ) {
5144 $jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5145 }
5146
5147 return $jetpack->connection_manager;
5148 }
5149
5150 /**
5151 * Get verification secrets.
5152 *
5153 * @param string $action Action name.
5154 * @param int $user_id User ID.
5155 *
5156 * @return array|string|WP_Error
5157 */
5158 public static function get_secrets( $action, $user_id ) {
5159 $secrets = ( new Secrets() )->get( $action, $user_id );
5160
5161 if ( Secrets::SECRETS_MISSING === $secrets ) {
5162 return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5163 }
5164
5165 if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5166 return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5167 }
5168
5169 return $secrets;
5170 }
5171
5172 /**
5173 * Filters the token request body to include tracking properties.
5174 *
5175 * @param array $properties Token request properties.
5176 *
5177 * @return array amended properties.
5178 */
5179 public static function filter_token_request_body( $properties ) {
5180 $tracking = new Tracking();
5181 $tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5182
5183 return array_merge(
5184 $properties,
5185 array(
5186 '_ui' => $tracks_identity['_ui'],
5187 '_ut' => $tracks_identity['_ut'],
5188 )
5189 );
5190 }
5191
5192 /**
5193 * If the db version is showing something other that what we've got now, bump it to current.
5194 *
5195 * @return bool True if the option was incorrect and updated, false if nothing happened.
5196 */
5197 public static function maybe_set_version_option() {
5198 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5199 if ( JETPACK__VERSION !== $version ) {
5200 Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5201
5202 if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5203 /** This action is documented in class.jetpack.php */
5204 do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5205 }
5206
5207 return true;
5208 }
5209 return false;
5210 }
5211
5212 /* Client Server API */
5213
5214 /**
5215 * State is passed via cookies from one request to the next, but never to subsequent requests.
5216 * SET: state( $key, $value );
5217 * GET: $value = state( $key );
5218 *
5219 * @param string $key State key.
5220 * @param string $value Value.
5221 * @param bool $restate Reset the cookie (private).
5222 */
5223 public static function state( $key = null, $value = null, $restate = false ) {
5224 return ( new CookieState() )->state( $key, $value, $restate );
5225 }
5226
5227 /**
5228 * Set an empty state.
5229 *
5230 * @return void
5231 */
5232 public static function restate() {
5233 self::state( null, null, true );
5234 }
5235
5236 /**
5237 * Determines whether the jetpackState[$key] value should be added to the
5238 * cookie.
5239 *
5240 * @param string $key The state key.
5241 *
5242 * @return boolean Whether the value should be added to the cookie.
5243 */
5244 public static function should_set_cookie( $key ) {
5245 return ( new CookieState() )->should_set_cookie( $key );
5246 }
5247
5248 /**
5249 * Check if site is publicly accessible.
5250 *
5251 * @param string $file Module file.
5252 *
5253 * @return void
5254 */
5255 public static function check_privacy( $file ) {
5256 static $is_site_publicly_accessible = null;
5257
5258 if ( $is_site_publicly_accessible === null ) {
5259 $is_site_publicly_accessible = false;
5260
5261 $rpc = new Jetpack_IXR_Client();
5262
5263 $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5264 if ( $success ) {
5265 $response = $rpc->getResponse();
5266 if ( $response ) {
5267 $is_site_publicly_accessible = true;
5268 }
5269 }
5270
5271 Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5272 }
5273
5274 if ( $is_site_publicly_accessible ) {
5275 return;
5276 }
5277
5278 $module_slug = self::get_module_slug( $file );
5279
5280 $privacy_checks = self::state( 'privacy_checks' );
5281 if ( ! $privacy_checks ) {
5282 $privacy_checks = $module_slug;
5283 } else {
5284 $privacy_checks .= ",$module_slug";
5285 }
5286
5287 self::state( 'privacy_checks', $privacy_checks );
5288 }
5289
5290 /* JSON API Authorization */
5291
5292 /**
5293 * Handles the login action for Authorizing the JSON API
5294 */
5295 public function login_form_json_api_authorization() {
5296 $authorize_json_api = new Authorize_Json_Api();
5297 $authorize_json_api->verify_json_api_authorization_request();
5298
5299 add_action( 'wp_login', array( $authorize_json_api, 'store_json_api_authorization_token' ), 10, 2 );
5300
5301 add_action( 'login_message', array( $authorize_json_api, 'login_message_json_api_authorization' ) );
5302 add_action( 'login_form', array( $this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5303 add_filter( 'site_url', array( $this, 'post_login_form_to_signed_url' ), 10, 3 );
5304 }
5305
5306 /**
5307 * Make sure the login form is POSTed to the signed URL so we can reverify the request.
5308 *
5309 * @param string $url Redirect URL.
5310 * @param string $path Path.
5311 * @param string $scheme URL Scheme.
5312 */
5313 public function post_login_form_to_signed_url( $url, $path, $scheme ) {
5314 if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
5315 return $url;
5316 }
5317 $query_string = isset( $_SERVER['QUERY_STRING'] ) ? wp_unslash( $_SERVER['QUERY_STRING'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized
5318 $parsed_url = wp_parse_url( $url );
5319 $url = strtok( $url, '?' );
5320 $url = "$url?{$query_string}";
5321 if ( ! empty( $parsed_url['query'] ) ) {
5322 $url .= "&{$parsed_url['query']}";
5323 }
5324
5325 return $url;
5326 }
5327
5328 /**
5329 * Make sure the POSTed request is handled by the same action.
5330 */
5331 public function preserve_action_in_login_form_for_json_api_authorization() {
5332 $http_host = isset( $_SERVER['HTTP_HOST'] ) ? wp_unslash( $_SERVER['HTTP_HOST'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- escaped with esc_url below.
5333 $request_uri = isset( $_SERVER['REQUEST_URI'] ) ? wp_unslash( $_SERVER['REQUEST_URI'] ) : ''; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized -- escaped with esc_url below.
5334 echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
5335 echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $http_host . $request_uri ) ) . "' />\n";
5336 }
5337
5338 /**
5339 * If someone logs in to approve API access, store the Access Code in usermeta.
5340 *
5341 * @deprecated 13.4
5342 *
5343 * @param string $user_login Unused.
5344 * @param WP_User $user User logged in.
5345 */
5346 public function store_json_api_authorization_token( $user_login, $user ) {
5347 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::store_json_api_authorization_token' );
5348
5349 return ( new Authorize_Json_Api() )->store_json_api_authorization_token( $user_login, $user );
5350 }
5351
5352 /**
5353 * Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
5354 *
5355 * To be used with a filter of allowed domains for a redirect.
5356 *
5357 * @deprecated 13.4
5358 *
5359 * @param array $domains Allowed WP.com Environments.
5360 */
5361 public function allow_wpcom_public_api_domain( $domains ) {
5362 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Status\\Host::allow_wpcom_public_api_domain' );
5363
5364 return Host::allow_wpcom_public_api_domain( $domains );
5365 }
5366
5367 /**
5368 * Check if the redirect is encoded.
5369 *
5370 * @deprecated 13.4
5371 *
5372 * @param string $redirect_url Redirect URL.
5373 *
5374 * @return bool If redirect has been encoded.
5375 */
5376 public static function is_redirect_encoded( $redirect_url ) {
5377 _deprecated_function( __METHOD__, 'jetpack-13.4' );
5378 return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
5379 }
5380
5381 /**
5382 * Add all wordpress.com environments to the safe redirect allowed list.
5383 *
5384 * To be used with a filter of allowed domains for a redirect.
5385 *
5386 * @param array $domains Allowed WP.com Environments.
5387 *
5388 * @deprecated since 11.1
5389 */
5390 public function allow_wpcom_environments( $domains ) {
5391 return Host::allow_wpcom_environments( $domains );
5392 }
5393
5394 /**
5395 * Add the Access Code details to the public-api.wordpress.com redirect.
5396 *
5397 * @deprecated 13.4
5398 *
5399 * @param string $redirect_to URL.
5400 * @param string $original_redirect_to URL.
5401 * @param WP_User $user WP_User for the redirect.
5402 *
5403 * @return string
5404 */
5405 public function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
5406 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::add_token_to_login_redirect_json_api_authorization' );
5407
5408 return ( new Authorize_Json_Api() )->add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user );
5409 }
5410
5411 /**
5412 * Verifies the request by checking the signature
5413 *
5414 * @deprecated 13.4
5415 *
5416 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
5417 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
5418 *
5419 * @param null|array $environment Value to override $_REQUEST.
5420 */
5421 public function verify_json_api_authorization_request( $environment = null ) {
5422 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::verify_json_api_authorization_request' );
5423
5424 return ( new Authorize_Json_Api() )->verify_json_api_authorization_request( $environment );
5425 }
5426
5427 /**
5428 * HTML for the JSON API authorization notice.
5429 *
5430 * @deprecated 13.4
5431 *
5432 * @return string
5433 */
5434 public function login_message_json_api_authorization() {
5435 _deprecated_function( __METHOD__, 'jetpack-13.4', 'Automattic\\Jetpack\\Connection\\Authorize_Json_Api::login_message_json_api_authorization' );
5436
5437 return ( new Authorize_Json_Api() )->login_message_json_api_authorization();
5438 }
5439
5440 /**
5441 * Get $content_width, but with a <s>twist</s> filter.
5442 */
5443 public static function get_content_width() {
5444 $content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
5445 ? $GLOBALS['content_width']
5446 : false;
5447 /**
5448 * Filter the Content Width value.
5449 *
5450 * @since 2.2.3
5451 *
5452 * @param string $content_width Content Width value.
5453 */
5454 return apply_filters( 'jetpack_content_width', $content_width );
5455 }
5456
5457 /**
5458 * Pings the WordPress.com Mirror Site for the specified options.
5459 *
5460 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site.
5461 *
5462 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
5463 */
5464 public function get_cloud_site_options( $option_names ) {
5465 $option_names = array_filter( (array) $option_names, 'is_string' );
5466
5467 $xml = new Jetpack_IXR_Client();
5468 $xml->query( 'jetpack.fetchSiteOptions', $option_names );
5469 if ( $xml->isError() ) {
5470 return array(
5471 'error_code' => $xml->getErrorCode(),
5472 'error_msg' => $xml->getErrorMessage(),
5473 );
5474 }
5475 $cloud_site_options = $xml->getResponse();
5476
5477 return $cloud_site_options;
5478 }
5479
5480 /**
5481 * Checks if the site is currently in an identity crisis.
5482 *
5483 * Now delegates to the Connection package so this matches what the heartbeat itself reports.
5484 * Note the package guards on `Connection\Manager::is_connected()` where this used to guard on
5485 * `Jetpack::is_connection_ready()`, so the `jetpack_is_connection_ready` filter no longer applies.
5486 *
5487 * @deprecated 16.2
5488 *
5489 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
5490 */
5491 public static function check_identity_crisis() {
5492 _deprecated_function( __METHOD__, 'jetpack-16.2', 'Automattic\\Jetpack\\Identity_Crisis::check_identity_crisis' );
5493
5494 return Identity_Crisis::check_identity_crisis();
5495 }
5496
5497 /**
5498 * Normalizes a url by doing three things:
5499 * - Strips protocol
5500 * - Strips www
5501 * - Adds a trailing slash
5502 *
5503 * @since 4.4.0
5504 * @param string $url URL.
5505 * @return WP_Error|string
5506 */
5507 public static function normalize_url_protocol_agnostic( $url ) {
5508 $parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
5509 if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
5510 /* translators: URL string */
5511 return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
5512 }
5513
5514 // Strip www and protocols.
5515 $url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
5516 return $url;
5517 }
5518
5519 /**
5520 * Maybe Use a .min.css stylesheet, maybe not.
5521 *
5522 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
5523 *
5524 * @param string $url URL.
5525 * @param string $path File path.
5526 * @param string $plugin Plugin.
5527 *
5528 * @return mixed
5529 */
5530 public static function maybe_min_asset( $url, $path, $plugin ) {
5531 // Short out on things trying to find actual paths.
5532 if ( ! $path || empty( $plugin ) ) {
5533 return $url;
5534 }
5535
5536 $path = ltrim( $path, '/' );
5537
5538 // Strip out the abspath.
5539 $base = dirname( plugin_basename( $plugin ) );
5540
5541 // Short out on non-Jetpack assets.
5542 if ( ! str_starts_with( $base, 'jetpack/' ) ) {
5543 return $url;
5544 }
5545
5546 // File name parsing.
5547 $file = "{$base}/{$path}";
5548 $full_path = JETPACK__PLUGIN_DIR . substr( $file, 8 );
5549 $file_name = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
5550 $file_name_parts_r = array_reverse( explode( '.', $file_name ) );
5551 $extension = array_shift( $file_name_parts_r );
5552
5553 if ( in_array( strtolower( $extension ), array( 'css', 'js' ), true ) ) {
5554 // Already pointing at the minified version.
5555 if ( 'min' === $file_name_parts_r[0] ) {
5556 return $url;
5557 }
5558
5559 $min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
5560 if ( file_exists( $min_full_path ) ) {
5561 $url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
5562 // If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
5563 if ( 'css' === $extension ) {
5564 $key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
5565 self::$min_assets[ $key ] = $path;
5566 }
5567 }
5568 }
5569
5570 return $url;
5571 }
5572
5573 /**
5574 * If the asset is minified, let's flag .min as the suffix.
5575 *
5576 * Attached to `style_loader_src` filter.
5577 *
5578 * @param string $src source file.
5579 * @param string $handle The registered handle of the script in question.
5580 *
5581 * @return mixed
5582 */
5583 public static function set_suffix_on_min( $src, $handle ) {
5584 if ( ! is_string( $src ) || ! str_contains( $src, '.min.css' ) ) {
5585 return $src;
5586 }
5587
5588 if ( ! empty( self::$min_assets ) ) {
5589 foreach ( self::$min_assets as $file => $path ) {
5590 if ( str_contains( $src, $file ) ) {
5591 wp_style_add_data( $handle, 'suffix', '.min' );
5592 return $src;
5593 }
5594 }
5595 }
5596
5597 return $src;
5598 }
5599
5600 /**
5601 * Maybe inlines a stylesheet.
5602 *
5603 * @deprecated since 11.7.
5604 *
5605 * @param string $tag The tag that would link to the external asset.
5606 * @param string $handle The registered handle of the script in question.
5607 *
5608 * @return string
5609 */
5610 public static function maybe_inline_style( $tag, $handle ) { //phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable
5611 _deprecated_function( __METHOD__, '11.7', 'wp_maybe_inline_styles' );
5612
5613 return $tag;
5614 }
5615
5616 /**
5617 * Loads a view file from the views
5618 *
5619 * Data passed in with the $data parameter will be available in the
5620 * template file as $data['value']
5621 *
5622 * @html-template-var array $data
5623 *
5624 * @param string $template - Template file to load.
5625 * @param array $data - Any data to pass along to the template.
5626 * @return boolean - If template file was found.
5627 **/
5628 public function load_view( $template, $data = array() ) { // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.UnusedVariable -- This is used via the required files.
5629 $views_dir = JETPACK__PLUGIN_DIR . 'views/';
5630
5631 if ( file_exists( $views_dir . $template ) ) {
5632 require_once $views_dir . $template;
5633 return true;
5634 }
5635
5636 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
5637 trigger_error( sprintf( 'Jetpack: Unable to find view file: %s', esc_html( $views_dir . $template ) ), E_USER_WARNING ); // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_trigger_error
5638 }
5639 return false;
5640 }
5641
5642 /**
5643 * Register Jetpack-specific tests on the connection package's health test suite.
5644 *
5645 * @param \Automattic\Jetpack\Connection\Connection_Health_Tests $connection_tests The test suite instance.
5646 */
5647 public function register_jetpack_connection_tests( $connection_tests ) {
5648 require_once JETPACK__PLUGIN_DIR . '_inc/lib/debugger/class-jetpack-cxn-tests.php';
5649 $jetpack_tests = new Jetpack_Cxn_Tests();
5650 $jetpack_tests->register_tests_on( $connection_tests );
5651 }
5652
5653 /**
5654 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
5655 */
5656 public function deprecated_hooks() {
5657 $filter_deprecated_list = array(
5658 'jetpack_bail_on_shortcode' => array(
5659 'replacement' => 'jetpack_shortcodes_to_include',
5660 'version' => 'jetpack-3.1.0',
5661 ),
5662 'wpl_sharing_2014_1' => array(
5663 'replacement' => null,
5664 'version' => 'jetpack-3.6.0',
5665 ),
5666 'jetpack-tools-to-include' => array(
5667 'replacement' => 'jetpack_tools_to_include',
5668 'version' => 'jetpack-3.9.0',
5669 ),
5670 'jetpack_identity_crisis_options_to_check' => array(
5671 'replacement' => null,
5672 'version' => 'jetpack-4.0.0',
5673 ),
5674 'update_option_jetpack_single_user_site' => array(
5675 'replacement' => null,
5676 'version' => 'jetpack-4.3.0',
5677 ),
5678 'audio_player_default_colors' => array(
5679 'replacement' => null,
5680 'version' => 'jetpack-4.3.0',
5681 ),
5682 'add_option_jetpack_featured_images_enabled' => array(
5683 'replacement' => null,
5684 'version' => 'jetpack-4.3.0',
5685 ),
5686 'add_option_jetpack_update_details' => array(
5687 'replacement' => null,
5688 'version' => 'jetpack-4.3.0',
5689 ),
5690 'add_option_jetpack_updates' => array(
5691 'replacement' => null,
5692 'version' => 'jetpack-4.3.0',
5693 ),
5694 'add_option_jetpack_network_name' => array(
5695 'replacement' => null,
5696 'version' => 'jetpack-4.3.0',
5697 ),
5698 'add_option_jetpack_network_allow_new_registrations' => array(
5699 'replacement' => null,
5700 'version' => 'jetpack-4.3.0',
5701 ),
5702 'add_option_jetpack_network_add_new_users' => array(
5703 'replacement' => null,
5704 'version' => 'jetpack-4.3.0',
5705 ),
5706 'add_option_jetpack_network_site_upload_space' => array(
5707 'replacement' => null,
5708 'version' => 'jetpack-4.3.0',
5709 ),
5710 'add_option_jetpack_network_upload_file_types' => array(
5711 'replacement' => null,
5712 'version' => 'jetpack-4.3.0',
5713 ),
5714 'add_option_jetpack_network_enable_administration_menus' => array(
5715 'replacement' => null,
5716 'version' => 'jetpack-4.3.0',
5717 ),
5718 'add_option_jetpack_is_multi_site' => array(
5719 'replacement' => null,
5720 'version' => 'jetpack-4.3.0',
5721 ),
5722 'add_option_jetpack_is_main_network' => array(
5723 'replacement' => null,
5724 'version' => 'jetpack-4.3.0',
5725 ),
5726 'add_option_jetpack_main_network_site' => array(
5727 'replacement' => null,
5728 'version' => 'jetpack-4.3.0',
5729 ),
5730 'jetpack_sync_all_registered_options' => array(
5731 'replacement' => null,
5732 'version' => 'jetpack-4.3.0',
5733 ),
5734 'jetpack_has_identity_crisis' => array(
5735 'replacement' => 'jetpack_sync_error_idc_validation',
5736 'version' => 'jetpack-4.4.0',
5737 ),
5738 'jetpack_is_post_mailable' => array(
5739 'replacement' => null,
5740 'version' => 'jetpack-4.4.0',
5741 ),
5742 'jetpack_seo_site_host' => array(
5743 'replacement' => null,
5744 'version' => 'jetpack-5.1.0',
5745 ),
5746 'jetpack_installed_plugin' => array(
5747 'replacement' => 'jetpack_plugin_installed',
5748 'version' => 'jetpack-6.0.0',
5749 ),
5750 'jetpack_holiday_snow_option_name' => array(
5751 'replacement' => null,
5752 'version' => 'jetpack-6.0.0',
5753 ),
5754 'jetpack_holiday_chance_of_snow' => array(
5755 'replacement' => null,
5756 'version' => 'jetpack-6.0.0',
5757 ),
5758 'jetpack_holiday_snow_js_url' => array(
5759 'replacement' => null,
5760 'version' => 'jetpack-6.0.0',
5761 ),
5762 'jetpack_is_holiday_snow_season' => array(
5763 'replacement' => null,
5764 'version' => 'jetpack-6.0.0',
5765 ),
5766 'jetpack_holiday_snow_option_updated' => array(
5767 'replacement' => null,
5768 'version' => 'jetpack-6.0.0',
5769 ),
5770 'jetpack_holiday_snowing' => array(
5771 'replacement' => null,
5772 'version' => 'jetpack-6.0.0',
5773 ),
5774 'jetpack_sso_auth_cookie_expirtation' => array(
5775 'replacement' => 'jetpack_sso_auth_cookie_expiration',
5776 'version' => 'jetpack-6.1.0',
5777 ),
5778 'jetpack_cache_plans' => array(
5779 'replacement' => null,
5780 'version' => 'jetpack-6.1.0',
5781 ),
5782 'jetpack_enable_site_verification' => array(
5783 'replacement' => null,
5784 'version' => 'jetpack-6.5.0',
5785 ),
5786 'can_display_jetpack_manage_notice' => array(
5787 'replacement' => null,
5788 'version' => 'jetpack-7.3.0',
5789 ),
5790 'atd_http_post_timeout' => array(
5791 'replacement' => null,
5792 'version' => 'jetpack-7.3.0',
5793 ),
5794 'atd_service_domain' => array(
5795 'replacement' => null,
5796 'version' => 'jetpack-7.3.0',
5797 ),
5798 'atd_load_scripts' => array(
5799 'replacement' => null,
5800 'version' => 'jetpack-7.3.0',
5801 ),
5802 'jetpack_widget_authors_exclude' => array(
5803 'replacement' => 'jetpack_widget_authors_params',
5804 'version' => 'jetpack-7.7.0',
5805 ),
5806 // Removed in Jetpack 7.9.0.
5807 'jetpack_pwa_manifest' => array(
5808 'replacement' => null,
5809 'version' => 'jetpack-7.9.0',
5810 ),
5811 'jetpack_pwa_background_color' => array(
5812 'replacement' => null,
5813 'version' => 'jetpack-7.9.0',
5814 ),
5815 'jetpack_check_mobile' => array(
5816 'replacement' => null,
5817 'version' => 'jetpack-8.3.0',
5818 ),
5819 'jetpack_mobile_stylesheet' => array(
5820 'replacement' => null,
5821 'version' => 'jetpack-8.3.0',
5822 ),
5823 'jetpack_mobile_template' => array(
5824 'replacement' => null,
5825 'version' => 'jetpack-8.3.0',
5826 ),
5827 'jetpack_mobile_theme_menu' => array(
5828 'replacement' => null,
5829 'version' => 'jetpack-8.3.0',
5830 ),
5831 'minileven_show_featured_images' => array(
5832 'replacement' => null,
5833 'version' => 'jetpack-8.3.0',
5834 ),
5835 'minileven_attachment_size' => array(
5836 'replacement' => null,
5837 'version' => 'jetpack-8.3.0',
5838 ),
5839 'instagram_cache_oembed_api_response_body' => array(
5840 'replacement' => null,
5841 'version' => 'jetpack-9.1.0',
5842 ),
5843 'jetpack_can_make_outbound_https' => array(
5844 'replacement' => null,
5845 'version' => 'jetpack-9.1.0',
5846 ),
5847 'sharing_email_can_send' => array(
5848 'replacement' => null,
5849 'version' => 'jetpack-11.0.0',
5850 ),
5851 'sharing_email_check' => array(
5852 'replacement' => null,
5853 'version' => 'jetpack-11.0.0',
5854 ),
5855 'sharing_services_email' => array(
5856 'replacement' => null,
5857 'version' => 'jetpack-11.0.0',
5858 ),
5859 'jetpack_dsp_promote_posts_enabled' => array(
5860 'replacement' => null,
5861 'version' => 'jetpack-11.8.0',
5862 ),
5863 'jetpack_are_blogging_prompts_enabled' => array(
5864 'replacement' => null,
5865 'version' => 'jetpack-11.8.0',
5866 ),
5867 'jetpack_subscriptions_modal_enabled' => array(
5868 'replacement' => null,
5869 'version' => 'jetpack-12.7.0',
5870 ),
5871 'jetpack_pre_connection_prompt_helpers' => array(
5872 'replacement' => null,
5873 'version' => 'jetpack-13.2.0',
5874 ),
5875 'jetpack_contact_form_use_package' => array(
5876 'replacement' => null,
5877 'version' => 'jetpack-13.4.0',
5878 ),
5879 // jetpack_implode_frontend_css has been removed, but is not listed here. The updated behavior is exactly the only use of the filter.
5880 // We can reassess formally deprecating it here later; for now, it would be noise with no functional difference.
5881 );
5882
5883 foreach ( $filter_deprecated_list as $tag => $args ) {
5884 if ( has_filter( $tag ) ) {
5885 apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
5886 }
5887 }
5888
5889 $action_deprecated_list = array(
5890 'jetpack_updated_theme' => array(
5891 'replacement' => 'jetpack_updated_themes',
5892 'version' => 'jetpack-6.2.0',
5893 ),
5894 'atd_http_post_error' => array(
5895 'replacement' => null,
5896 'version' => 'jetpack-7.3.0',
5897 ),
5898 'mobile_reject_mobile' => array(
5899 'replacement' => null,
5900 'version' => 'jetpack-8.3.0',
5901 ),
5902 'mobile_force_mobile' => array(
5903 'replacement' => null,
5904 'version' => 'jetpack-8.3.0',
5905 ),
5906 'mobile_app_promo_download' => array(
5907 'replacement' => null,
5908 'version' => 'jetpack-8.3.0',
5909 ),
5910 'mobile_setup' => array(
5911 'replacement' => null,
5912 'version' => 'jetpack-8.3.0',
5913 ),
5914 'jetpack_mobile_footer_before' => array(
5915 'replacement' => null,
5916 'version' => 'jetpack-8.3.0',
5917 ),
5918 'wp_mobile_theme_footer' => array(
5919 'replacement' => null,
5920 'version' => 'jetpack-8.3.0',
5921 ),
5922 'minileven_credits' => array(
5923 'replacement' => null,
5924 'version' => 'jetpack-8.3.0',
5925 ),
5926 'jetpack_mobile_header_before' => array(
5927 'replacement' => null,
5928 'version' => 'jetpack-8.3.0',
5929 ),
5930 'jetpack_mobile_header_after' => array(
5931 'replacement' => null,
5932 'version' => 'jetpack-8.3.0',
5933 ),
5934 'sharing_email_dialog' => array(
5935 'replacement' => null,
5936 'version' => 'jetpack-11.0.0',
5937 ),
5938 'sharing_email_send_post' => array(
5939 'replacement' => null,
5940 'version' => 'jetpack-11.0.0',
5941 ),
5942 );
5943
5944 foreach ( $action_deprecated_list as $tag => $args ) {
5945 if ( has_action( $tag ) ) {
5946 do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
5947 }
5948 }
5949 }
5950
5951 /**
5952 * Converts any url in a stylesheet, to the correct absolute url.
5953 *
5954 * Considerations:
5955 * - Normal, relative URLs `feh.png`
5956 * - Data URLs `data:image/gif;base64,eh129ehiuehjdhsa==`
5957 * - Schema-agnostic URLs `//domain.com/feh.png`
5958 * - Absolute URLs `http://domain.com/feh.png`
5959 * - Domain root relative URLs `/feh.png`
5960 *
5961 * @param string $css The raw CSS -- should be read in directly from the file.
5962 * @param string $css_file_url The URL that the file can be accessed at, for calculating paths from.
5963 *
5964 * @return mixed|string
5965 */
5966 public static function absolutize_css_urls( $css, $css_file_url ) {
5967 $pattern = '#url\((?P<path>[^)]*)\)#i';
5968 $css_dir = dirname( $css_file_url );
5969 $p = wp_parse_url( $css_dir );
5970 $domain = sprintf(
5971 '%1$s//%2$s%3$s%4$s',
5972 isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
5973 isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
5974 $p['host'],
5975 isset( $p['port'] ) ? ":{$p['port']}" : ''
5976 );
5977
5978 if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
5979 $replace = array();
5980 $find = array();
5981 foreach ( $matches as $match ) {
5982 $url = trim( $match['path'], "'\" \t" );
5983
5984 // If this is a data url, we don't want to mess with it.
5985 if ( str_starts_with( $url, 'data:' ) ) {
5986 continue;
5987 }
5988
5989 // If this is an absolute or protocol-agnostic url,
5990 // we don't want to mess with it.
5991 if ( preg_match( '#^(https?:)?//#i', $url ) ) {
5992 continue;
5993 }
5994
5995 switch ( substr( $url, 0, 1 ) ) {
5996 case '/':
5997 $absolute = $domain . $url;
5998 break;
5999 default:
6000 $absolute = $css_dir . '/' . $url;
6001 }
6002
6003 $find[] = $match[0];
6004 $replace[] = sprintf( 'url("%s")', $absolute );
6005 }
6006 $css = str_replace( $find, $replace, $css );
6007 }
6008
6009 return $css;
6010 }
6011
6012 /**
6013 * Check the heartbeat data
6014 *
6015 * Organizes the heartbeat data by severity. For example, if the site
6016 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6017 *
6018 * Data will be added to "caution" array, if it either:
6019 * - Out of date Jetpack version
6020 * - Out of date WP version
6021 * - Out of date PHP version
6022 *
6023 * $return array $filtered_data
6024 */
6025 public static function jetpack_check_heartbeat_data() {
6026 /*
6027 * Site environment stats (incl. wp-version/php-version checked below) now live in the Connection package,
6028 * and the IDC stat is contributed by the Connection package's `jetpack_heartbeat_stats_array` filter
6029 * callback. We rebuild the stat here rather than running that filter: the filter's callbacks have side
6030 * effects (Connection\Manager::add_stats_to_heartbeat() consumes and deletes the `xmlrpc_errors` option)
6031 * and return non-scalar values, neither of which is appropriate for this read-only diagnostic.
6032 */
6033 $env_stats = method_exists( Heartbeat::class, 'get_environment_stats' )
6034 ? Heartbeat::get_environment_stats()
6035 : array();
6036 $raw_data = array_merge(
6037 Jetpack_Heartbeat::generate_stats_array(),
6038 $env_stats,
6039 array( 'identitycrisis' => Identity_Crisis::check_identity_crisis() ? 'yes' : 'no' )
6040 );
6041
6042 $good = array();
6043 $caution = array();
6044 $bad = array();
6045
6046 foreach ( $raw_data as $stat => $value ) {
6047
6048 // Check jetpack version.
6049 if ( 'version' === $stat ) {
6050 if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6051 $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6052 continue;
6053 }
6054 }
6055
6056 // Check WP version.
6057 if ( 'wp-version' === $stat ) {
6058 if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6059 $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6060 continue;
6061 }
6062 }
6063
6064 // Check PHP version.
6065 if ( 'php-version' === $stat ) {
6066 if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6067 $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6068 continue;
6069 }
6070 }
6071
6072 // Check ID crisis.
6073 if ( 'identitycrisis' === $stat ) {
6074 if ( 'yes' === $value ) {
6075 $bad[ $stat ] = $value;
6076 continue;
6077 }
6078 }
6079
6080 // The rest are good :).
6081 $good[ $stat ] = $value;
6082 }
6083
6084 $filtered_data = array(
6085 'good' => $good,
6086 'caution' => $caution,
6087 'bad' => $bad,
6088 );
6089
6090 return $filtered_data;
6091 }
6092
6093 /**
6094 * This method is used to organize all options that can be reset
6095 * without disconnecting Jetpack.
6096 *
6097 * It is used in class.jetpack-cli.php to reset options
6098 *
6099 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6100 *
6101 * @return array of options to delete.
6102 */
6103 public static function get_jetpack_options_for_reset() {
6104 return Jetpack_Options::get_options_for_reset();
6105 }
6106
6107 /**
6108 * Get the user's meta box order.
6109 *
6110 * @param array $sorted Value for the user's option.
6111 * @return mixed
6112 */
6113 public function get_user_option_meta_box_order_dashboard( $sorted ) {
6114 if ( ! is_array( $sorted ) ) {
6115 return $sorted;
6116 }
6117
6118 foreach ( $sorted as $box_context => $ids ) {
6119 if ( ! str_contains( $ids, 'dashboard_stats' ) ) {
6120 // If the old id isn't anywhere in the ids, don't bother exploding and fail out.
6121 continue;
6122 }
6123
6124 $ids_array = explode( ',', $ids );
6125 $key = array_search( 'dashboard_stats', $ids_array, true );
6126
6127 if ( false !== $key ) {
6128 // If we've found that exact value in the option (and not `google_dashboard_stats` for example).
6129 $ids_array[ $key ] = 'jetpack_summary_widget';
6130 $sorted[ $box_context ] = implode( ',', $ids_array );
6131 // We've found it, stop searching, and just return.
6132 break;
6133 }
6134 }
6135
6136 return $sorted;
6137 }
6138 /**
6139 * Checks if Akismet is active and working.
6140 *
6141 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
6142 * that implied usage of methods present since more recent version.
6143 * See https://github.com/Automattic/jetpack/pull/9585
6144 *
6145 * @since 5.1.0
6146 *
6147 * @return bool True = Akismet available. False = Aksimet not available.
6148 */
6149 public static function is_akismet_active() {
6150 static $status = null;
6151
6152 if ( $status !== null ) {
6153 return $status;
6154 }
6155
6156 // Check if a modern version of Akismet is active.
6157 if ( ! method_exists( 'Akismet', 'http_post' ) ) {
6158 $status = false;
6159 return $status;
6160 }
6161
6162 // Make sure there is a key known to Akismet at all before verifying key.
6163 $akismet_key = Akismet::get_api_key();
6164 if ( ! $akismet_key ) {
6165 $status = false;
6166 return $status;
6167 }
6168
6169 // Possible values: valid, invalid, failure via Akismet. false if no status is cached.
6170 $akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
6171
6172 // Do not used the cache result in wp-admin or REST API requests if the key isn't valid, in case someone is actively renewing, etc.
6173 $recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
6174 // We cache the result of the Akismet key verification for ten minutes.
6175 if ( ! $akismet_key_state || $recheck ) {
6176 $akismet_key_state = Akismet::verify_key( $akismet_key );
6177 set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
6178 }
6179
6180 $status = 'valid' === $akismet_key_state;
6181
6182 return $status;
6183 }
6184
6185 /**
6186 * Given a minified path, and a non-minified path, will return
6187 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
6188 *
6189 * Both `$min_base` and `$non_min_base` are expected to be relative to the
6190 * root Jetpack directory.
6191 *
6192 * @since 5.6.0
6193 *
6194 * @param string $min_path Minimized path.
6195 * @param string $non_min_path Non-minimized path.
6196 * @return string The URL to the file
6197 */
6198 public static function get_file_url_for_environment( $min_path, $non_min_path ) {
6199 return Assets::get_file_url_for_environment( $min_path, $non_min_path );
6200 }
6201
6202 /**
6203 * Checks for whether Jetpack Backup is enabled.
6204 * Will return true if the state of Backup is anything except "unavailable".
6205 *
6206 * @return bool|int|mixed
6207 */
6208 public static function is_rewind_enabled() {
6209 // Rewind is a paid feature, therefore requires a user-level connection.
6210 if ( ! static::connection()->has_connected_owner() ) {
6211 return false;
6212 }
6213 $rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
6214 $recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && '0' === $rewind_enabled;
6215 if ( false === $rewind_enabled || $recheck ) {
6216 require_once JETPACK__PLUGIN_DIR . '_inc/lib/class.core-rest-api-endpoints.php';
6217 $rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
6218 $rewind_enabled = ( ! is_wp_error( $rewind_data )
6219 && ! empty( $rewind_data['state'] )
6220 && 'active' === $rewind_data['state'] )
6221 ? 1
6222 : 0;
6223 set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
6224 }
6225 return $rewind_enabled;
6226 }
6227
6228 /**
6229 * Return Calypso environment value; used for developing Jetpack and pairing
6230 * it with different Calypso enrionments, such as localhost.
6231 *
6232 * @deprecated 12.4 Moved to the Status package.
6233 *
6234 * @return string Calypso environment
6235 */
6236 public static function get_calypso_env() {
6237 _deprecated_function( __METHOD__, 'jetpack-12.4', '\Automattic\Jetpack\Status\Host->get_calypso_env' );
6238 return ( new Host() )->get_calypso_env();
6239 }
6240
6241 /**
6242 * Returns the hostname with protocol for Calypso.
6243 * Used for developing Jetpack with Calypso.
6244 *
6245 * @since 8.4.0
6246 *
6247 * @return string Calypso host.
6248 */
6249 public static function get_calypso_host() {
6250 $calypso_env = ( new Host() )->get_calypso_env();
6251 switch ( $calypso_env ) {
6252 case 'development':
6253 return 'http://calypso.localhost:3000/';
6254 case 'wpcalypso':
6255 return 'https://wpcalypso.wordpress.com/';
6256 case 'horizon':
6257 return 'https://horizon.wordpress.com/';
6258 default:
6259 return 'https://wordpress.com/';
6260 }
6261 }
6262
6263 /**
6264 * Handles activating default modules as well general cleanup for the new connection.
6265 *
6266 * @param boolean $activate_sso Whether to activate the SSO module when activating default modules.
6267 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
6268 * @param boolean $send_state_messages Whether to send state messages.
6269 * @return void
6270 */
6271 public static function handle_post_authorization_actions(
6272 $activate_sso = false,
6273 $redirect_on_activation_error = false,
6274 $send_state_messages = true
6275 ) {
6276 $other_modules = $activate_sso
6277 ? array( 'sso' )
6278 : array();
6279
6280 if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
6281 $active_modules = self::get_active_modules();
6282 self::delete_active_modules();
6283
6284 self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
6285 } else {
6286 // Default modules that don't require a user were already activated on site_register.
6287 // This time let's activate only those that require a user, this assures we don't reactivate manually deactivated modules while the site was connected only at a site level.
6288 self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
6289 Jetpack_Options::update_option( 'active_modules_initialized', true );
6290 }
6291
6292 // Since this is a fresh connection, be sure to clear out IDC options.
6293 Identity_Crisis::clear_all_idc_options();
6294
6295 if ( $send_state_messages ) {
6296 self::state( 'message', 'authorized' );
6297 }
6298 }
6299
6300 /**
6301 * Whether UI for backups should be displayed.
6302 *
6303 * On WPCom platforms this is gated on the backups-self-serve site feature.
6304 * On self-hosted Jetpack sites it falls back to the jetpack_show_backups filter.
6305 *
6306 * @return bool Should backups UI be displayed?
6307 */
6308 public static function show_backups_ui() {
6309 if ( ( new \Automattic\Jetpack\Status\Host() )->is_wpcom_platform() ) {
6310 return function_exists( 'wpcom_site_has_feature' ) && wpcom_site_has_feature( 'backups-self-serve' );
6311 }
6312
6313 /**
6314 * Whether UI for backups should be displayed.
6315 *
6316 * @since 6.5.0
6317 *
6318 * @param bool $show_backups Should UI for backups be displayed? True by default.
6319 */
6320 return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
6321 }
6322
6323 /**
6324 * Whether UI for security scanning should be displayed.
6325 *
6326 * On WPCom platforms this is gated on the scan-self-serve site feature.
6327 * On self-hosted Jetpack sites it always returns true.
6328 *
6329 * @return bool Should scan UI be displayed?
6330 */
6331 public static function show_scan_ui() {
6332 if ( ( new \Automattic\Jetpack\Status\Host() )->is_wpcom_platform() ) {
6333 return function_exists( 'wpcom_site_has_feature' ) && wpcom_site_has_feature( 'scan-self-serve' );
6334 }
6335
6336 return true;
6337 }
6338
6339 /**
6340 * Clean leftoveruser meta.
6341 *
6342 * Delete Jetpack-related user meta when it is no longer needed.
6343 *
6344 * @since 7.3.0
6345 *
6346 * @param int $user_id User ID being updated.
6347 */
6348 public static function user_meta_cleanup( $user_id ) {
6349 $meta_keys = array(
6350 // AtD removed from Jetpack 7.3.
6351 'AtD_options',
6352 'AtD_check_when',
6353 'AtD_guess_lang',
6354 'AtD_ignored_phrases',
6355 );
6356
6357 foreach ( $meta_keys as $meta_key ) {
6358 if ( get_user_meta( $user_id, $meta_key ) ) {
6359 delete_user_meta( $user_id, $meta_key );
6360 }
6361 }
6362 }
6363
6364 /**
6365 * Checks if a Jetpack site is both active and not in offline mode.
6366 *
6367 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
6368 *
6369 * @since 8.8.0
6370 *
6371 * @return bool True if Jetpack is active and not in offline mode.
6372 */
6373 public static function is_active_and_not_offline_mode() {
6374 if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
6375 return false;
6376 }
6377 return true;
6378 }
6379
6380 /**
6381 * Returns the list of products that we have available for purchase.
6382 *
6383 * This method will not take current purchases or upgrades into account
6384 * but is instead a static list of products Jetpack offers with some
6385 * corresponding sales text/materials.
6386 *
6387 * @param bool $show_legacy Determine if we should include legacy product/plan details.
6388 * @return array
6389 */
6390 public static function get_products_for_purchase( $show_legacy = false ) {
6391 $products = array();
6392
6393 $products['backup'] = array(
6394 'title' => __( 'Jetpack Backup', 'jetpack' ),
6395 'slug' => 'jetpack_backup_t1_yearly',
6396 'description' => __( 'Never lose a word, image, page, or time worrying about your site with automated backups & one-click restores.', 'jetpack' ),
6397 'show_promotion' => true,
6398 'discount_percent' => 50,
6399 'included_in_plans' => array( 'security' ),
6400 'features' => array(
6401 _x( 'Real-time cloud backups', 'Backup Product Feature', 'jetpack' ),
6402 _x( '10GB of backup storage', 'Backup Product Feature', 'jetpack' ),
6403 _x( '30-day archive & activity log*', 'Backup Product Feature', 'jetpack' ),
6404 _x( 'One-click restores', 'Backup Product Feature', 'jetpack' ),
6405 ),
6406 'disclaimer' => array(
6407 'text' => __( '* Subject to your usage and storage limit.', 'jetpack' ),
6408 'link_text' => __( 'Learn more', 'jetpack' ),
6409 'url' => Redirect::get_url( 'jetpack-faq-backup-disclaimer' ),
6410 ),
6411 );
6412
6413 $products['creator'] = array(
6414 'title' => __( 'Jetpack Creator', 'jetpack' ),
6415 'slug' => 'jetpack_creator_yearly',
6416 'description' => __( 'Craft stunning content, boost your subscriber base, and monetize your online presence.', 'jetpack' ),
6417 'show_promotion' => true,
6418 'discount_percent' => 50,
6419 'included_in_plans' => array( 'complete' ),
6420 'features' => array(
6421 _x( 'Unlimited subscriber imports', 'Creator Product Feature', 'jetpack' ),
6422 _x( 'Earn more from your content', 'Creator Product Feature', 'jetpack' ),
6423 _x( 'Accept payments with PayPal', 'Creator Product Feature', 'jetpack' ),
6424 _x( 'Increase earnings with WordAds', 'Creator Product Feature', 'jetpack' ),
6425 ),
6426 );
6427
6428 $products['growth'] = array(
6429 'title' => __( 'Jetpack Growth', 'jetpack' ),
6430 'slug' => 'jetpack_growth_yearly',
6431 'description' => __( 'Essential tools to help you grow your audience, track visitor engagement, and turn leads into loyal customers and advocates.', 'jetpack' ),
6432 'show_promotion' => true,
6433 'discount_percent' => 50,
6434 'included_in_plans' => array( 'complete' ),
6435 'features' => array(
6436 _x( 'Jetpack Social', 'Growth Product Feature', 'jetpack' ),
6437 _x( 'Jetpack Stats (10K site views, upgradeable)', 'Growth Product Feature', 'jetpack' ),
6438 _x( 'Unlimited subscriber imports', 'Growth Product Feature', 'jetpack' ),
6439 _x( 'Earn more from your content', 'Growth Product Feature', 'jetpack' ),
6440 _x( 'Accept payments with PayPal', 'Growth Product Feature', 'jetpack' ),
6441 _x( 'Increase earnings with WordAds', 'Growth Product Feature', 'jetpack' ),
6442 ),
6443 );
6444
6445 $products['scan'] = array(
6446 'title' => __( 'Jetpack Scan', 'jetpack' ),
6447 'slug' => 'jetpack_scan',
6448 'description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats and malware.', 'jetpack' ),
6449 'show_promotion' => true,
6450 'discount_percent' => 50,
6451 'included_in_plans' => array( 'security' ),
6452 'features' => array(
6453 _x( 'Automated daily scanning', 'Scan Product Feature', 'jetpack' ),
6454 _x( 'One-click fixes for most issues', 'Scan Product Feature', 'jetpack' ),
6455 _x( 'Instant email notifications', 'Scan Product Feature', 'jetpack' ),
6456 _x( 'Access to latest Firewall rules', 'Scan Product Feature', 'jetpack' ),
6457 ),
6458 );
6459
6460 $products['search'] = array(
6461 'title' => __( 'Jetpack Site Search', 'jetpack' ),
6462 'slug' => 'jetpack_search',
6463 'description' => __( 'Help your site visitors find answers instantly so they keep reading and buying. Great for sites with a lot of content.', 'jetpack' ),
6464 'show_promotion' => true,
6465 'discount_percent' => 50,
6466 'included_in_plans' => array(),
6467 'features' => array(
6468 _x( 'Instant search and indexing', 'Search Product Feature', 'jetpack' ),
6469 _x( 'Powerful filtering', 'Search Product Feature', 'jetpack' ),
6470 _x( 'Supports 38 languages', 'Search Product Feature', 'jetpack' ),
6471 _x( 'Spelling correction', 'Search Product Feature', 'jetpack' ),
6472 ),
6473 );
6474
6475 $products['akismet'] = array(
6476 'title' => __( 'Akismet Anti-spam', 'jetpack' ),
6477 'slug' => 'jetpack_anti_spam',
6478 'description' => __( 'Save time and get better responses by automatically blocking spam from your comments and forms.', 'jetpack' ),
6479 'show_promotion' => true,
6480 'discount_percent' => 50,
6481 'included_in_plans' => array( 'security' ),
6482 'features' => array(
6483 _x( 'Comment and form spam protection', 'Anti-Spam Product Feature', 'jetpack' ),
6484 _x( 'Block spam without CAPTCHAs', 'Anti-Spam Product Feature', 'jetpack' ),
6485 _x( 'Advanced stats', 'Anti-Spam Product Feature', 'jetpack' ),
6486 ),
6487 );
6488
6489 $products['security'] = array(
6490 'title' => _x( 'Security', 'Jetpack product name', 'jetpack' ),
6491 'slug' => 'jetpack_security_t1_yearly',
6492 'description' => __( 'Comprehensive site security, including Backup, Scan, and Anti-spam.', 'jetpack' ),
6493 'show_promotion' => true,
6494 'discount_percent' => 50,
6495 'included_in_plans' => array(),
6496 'features' => array(
6497 _x( 'Real-time cloud backups with 10GB storage', 'Security Tier 1 Feature', 'jetpack' ),
6498 _x( 'Automated real-time malware scan', 'Security Daily Plan Feature', 'jetpack' ),
6499 _x( 'One-click fixes for most threats', 'Security Daily Plan Feature', 'jetpack' ),
6500 _x( 'Comment & form spam protection', 'Security Daily Plan Feature', 'jetpack' ),
6501 ),
6502 );
6503
6504 $products['videopress'] = array(
6505 'title' => __( 'Jetpack VideoPress', 'jetpack' ),
6506 'slug' => 'jetpack_videopress',
6507 'description' => __( 'High-quality, ad-free video built specifically for WordPress.', 'jetpack' ),
6508 'show_promotion' => true,
6509 'discount_percent' => 50,
6510 'included_in_plans' => array(),
6511 'features' => array(
6512 _x( '1TB of storage', 'VideoPress Product Feature', 'jetpack' ),
6513 _x( 'Built into WordPress editor', 'VideoPress Product Feature', 'jetpack' ),
6514 _x( 'Ad-free and customizable player', 'VideoPress Product Feature', 'jetpack' ),
6515 _x( 'Unlimited users', 'VideoPress Product Feature', 'jetpack' ),
6516 ),
6517 );
6518
6519 if ( $show_legacy ) {
6520 $products['jetpack_backup_daily'] = array(
6521 'title' => __( 'Jetpack Backup', 'jetpack' ),
6522 'slug' => 'jetpack_backup_daily',
6523 'description' => __( 'Never lose a word, image, page, or time worrying about your site with automated backups & one-click restores.', 'jetpack' ),
6524 'show_promotion' => false,
6525 'discount_percent' => 0,
6526 'included_in_plans' => array(),
6527 'features' => array(
6528 _x( 'Automated daily backups (off-site)', 'Backup Product Feature', 'jetpack' ),
6529 _x( 'One-click restores', 'Backup Product Feature', 'jetpack' ),
6530 _x( 'Unlimited backup storage', 'Backup Product Feature', 'jetpack' ),
6531 ),
6532 );
6533 }
6534
6535 return $products;
6536 }
6537
6538 /**
6539 * Register product descriptions for partner coupon usage.
6540 *
6541 * @since 10.4.0
6542 *
6543 * @param array $products An array of registered products.
6544 *
6545 * @return array
6546 */
6547 public function get_partner_coupon_product_descriptions( $products ) {
6548 return array_merge( $products, self::get_products_for_purchase( true ) );
6549 }
6550
6551 /**
6552 * Determine if the current user is allowed to make Jetpack purchases without
6553 * a WordPress.com account
6554 *
6555 * @return boolean True if the user can make purchases, false if not
6556 */
6557 public static function current_user_can_purchase() {
6558
6559 // The site must be site-connected to Jetpack (no users connected).
6560 if ( ! self::connection()->is_site_connection() ) {
6561 return false;
6562 }
6563
6564 // Make sure only administrators can make purchases.
6565 if ( ! current_user_can( 'manage_options' ) ) {
6566 return false;
6567 }
6568
6569 return true;
6570 }
6571
6572 /**
6573 * Add 5-star review link on the Jetpack Plugin meta, in the plugins list table (on the plugins page).
6574 *
6575 * @param array $plugin_meta An array of the plugin's metadata.
6576 * @param string $plugin_file Path to the plugin file.
6577 *
6578 * @return array $plugin_meta An array of the plugin's metadata.
6579 */
6580 public function add_5_star_review_link( $plugin_meta, $plugin_file ) {
6581 if ( $plugin_file !== 'jetpack/jetpack.php' ) {
6582 return $plugin_meta;
6583 }
6584
6585 $u = get_current_user_id();
6586 $site = get_site_url();
6587
6588 $plugin_meta[] = '<a href="https://jetpack.com/redirect?source=jetpack-plugin-review&site=' . esc_attr( $site ) . '&u=' . esc_attr( $u ) . '" target="_blank" rel="noopener noreferrer" title="' . esc_attr__( 'Rate Jetpack on WordPress.org', 'jetpack' ) . '" style="color: #ffb900">'
6589 . str_repeat( '<span class="dashicons dashicons-star-filled" style="font-size: 16px; width:16px; height: 16px"></span>', 5 )
6590 . '</a>';
6591
6592 return $plugin_meta;
6593 }
6594
6595 /**
6596 * Lazy instantiation of the Plugin_Tracking object.
6597 *
6598 * @since 13.9
6599 *
6600 * @return void
6601 */
6602 public function initialize_tracking() {
6603 if ( did_action( 'jetpack_initialize_tracking' ) > 1 ) {
6604 // Only need to run once.
6605 return;
6606 }
6607
6608 if ( ( new Tracking( 'jetpack', $this->connection_manager ) )->should_enable_tracking( new Terms_Of_Service(), new Status() ) || static::is_connection_ready() ) {
6609 ( new Plugin_Tracking() )->init();
6610 }
6611 }
6612
6613 /**
6614 * Run the "initialize tracking" hook.
6615 *
6616 * @since 13.9
6617 */
6618 public function run_initialize_tracking_action() {
6619 /**
6620 * Fires when the tracking needs to be initialized.
6621 * Doesn't necessarily mean that will actually happen, depends if the 'jetpack_tos_agreed' option is set.
6622 *
6623 * @since 13.9
6624 */
6625 do_action( 'jetpack_initialize_tracking' );
6626 }
6627
6628 /**
6629 * Initialize REST jsonAPI if needed.
6630 *
6631 * @return void
6632 */
6633 public function maybe_initialize_rest_jsonapi() {
6634 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
6635 if ( ! empty( $_GET['jsonapi'] ) && ( ! defined( 'IS_WPCOM' ) || ! IS_WPCOM ) ) {
6636 require_once ABSPATH . 'wp-admin/includes/admin.php'; // JSON API relies on WP functionality not autoloaded in REST.
6637
6638 define( 'WPCOM_JSON_API__BASE', 'public-api.wordpress.com/rest/v1' );
6639 require_once JETPACK__PLUGIN_DIR . 'class.json-api-endpoints.php';
6640 }
6641 }
6642
6643 /**
6644 * Run plugin post-activation actions if we need to.
6645 *
6646 * @return void
6647 */
6648 private function plugin_post_activation() {
6649 if ( ( new Status() )->is_offline_mode() ) {
6650 return;
6651 }
6652
6653 if ( get_transient( 'activated_jetpack' ) ) {
6654 delete_transient( 'activated_jetpack' );
6655
6656 if ( ( new Host() )->is_woa_site() ) {
6657 $redirect_url = static::admin_url( 'page=jetpack' );
6658 } elseif ( is_network_admin() ) {
6659 $redirect_url = admin_url( 'network/admin.php?page=jetpack' );
6660 } elseif ( get_transient( 'my_jetpack_product_activated' ) ) {
6661 // don't redirect if this is an activation that just came from My Jetpack
6662 // My Jetpack has its own set of post-activation redirects
6663 return;
6664 } elseif ( My_Jetpack_Initializer::should_initialize() ) {
6665 $redirect_url = static::admin_url( 'page=my-jetpack' );
6666 } else {
6667 $redirect_url = static::admin_url( 'page=jetpack' );
6668 }
6669
6670 wp_safe_redirect( $redirect_url );
6671 }
6672 }
6673 }
6674