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

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