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

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

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