PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 11.1.4
Jetpack – WP Security, Backup, Speed, & Growth v11.1.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.1.4, at class.jetpack.php

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