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

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

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