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