PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 12.3
Jetpack – WP Security, Backup, Speed, & Growth v12.3
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 12.3, at class.jetpack.php

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