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

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

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