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