PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 11.2.2
Jetpack – WP Security, Backup, Speed, & Growth v11.2.2
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 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 11.2.2, at class.jetpack.php

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