PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 10.4
Jetpack – WP Security, Backup, Speed, & Growth v10.4
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 10.4, at class.jetpack.php

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