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

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

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