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

class.jetpack.php in Jetpack – WP Security, Backup, Speed, & Growth 16.0, at class.jetpack.php

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