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

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

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