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

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

7,618 lines 248.2 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-swiper-css',
64 'jetpack-carousel',
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 }
4028 }
4029 if ( ! is_null( $global_post ) ) {
4030 $GLOBALS['post'] = $global_post;
4031 }
4032
4033 return $uploaded_files;
4034 }
4035
4036 /**
4037 * Add help to the Jetpack page
4038 *
4039 * @since Jetpack (1.2.3)
4040 * @return false if not the Jetpack page
4041 */
4042 function admin_help() {
4043 $current_screen = get_current_screen();
4044
4045 // Overview
4046 $current_screen->add_help_tab(
4047 array(
4048 'id' => 'home',
4049 'title' => __( 'Home', 'jetpack' ),
4050 'content' =>
4051 '<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
4052 '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
4053 '<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>',
4054 )
4055 );
4056
4057 // Screen Content
4058 if ( current_user_can( 'manage_options' ) ) {
4059 $current_screen->add_help_tab(
4060 array(
4061 'id' => 'settings',
4062 'title' => __( 'Settings', 'jetpack' ),
4063 'content' =>
4064 '<p><strong>' . __( 'Jetpack', 'jetpack' ) . '</strong></p>' .
4065 '<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
4066 '<ol>' .
4067 '<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
4068 '<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>' .
4069 '</ol>' .
4070 '<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>',
4071 )
4072 );
4073 }
4074
4075 // Help Sidebar
4076 $support_url = Redirect::get_url( 'jetpack-support' );
4077 $faq_url = Redirect::get_url( 'jetpack-faq' );
4078 $current_screen->set_help_sidebar(
4079 '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
4080 '<p><a href="' . $faq_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
4081 '<p><a href="' . $support_url . '" rel="noopener noreferrer" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
4082 '<p><a href="' . self::admin_url( array( 'page' => 'jetpack-debugger' ) ) . '">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
4083 );
4084 }
4085
4086 function admin_menu_css() {
4087 wp_enqueue_style( 'jetpack-icons' );
4088 }
4089
4090 function admin_menu_order() {
4091 return true;
4092 }
4093
4094 function jetpack_menu_order( $menu_order ) {
4095 $jp_menu_order = array();
4096
4097 foreach ( $menu_order as $index => $item ) {
4098 if ( $item != 'jetpack' ) {
4099 $jp_menu_order[] = $item;
4100 }
4101
4102 if ( $index == 0 ) {
4103 $jp_menu_order[] = 'jetpack';
4104 }
4105 }
4106
4107 return $jp_menu_order;
4108 }
4109
4110 function admin_banner_styles() {
4111 $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
4112
4113 if ( ! wp_style_is( 'jetpack-dops-style' ) ) {
4114 wp_register_style(
4115 'jetpack-dops-style',
4116 plugins_url( '_inc/build/admin.css', JETPACK__PLUGIN_FILE ),
4117 array(),
4118 JETPACK__VERSION
4119 );
4120 }
4121
4122 wp_enqueue_style(
4123 'jetpack',
4124 plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ),
4125 array( 'jetpack-dops-style' ),
4126 JETPACK__VERSION . '-20121016'
4127 );
4128 wp_style_add_data( 'jetpack', 'rtl', 'replace' );
4129 wp_style_add_data( 'jetpack', 'suffix', $min );
4130 }
4131
4132 function plugin_action_links( $actions ) {
4133
4134 $jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack' ), __( 'My Jetpack', 'jetpack' ) ) );
4135
4136 if ( current_user_can( 'jetpack_manage_modules' ) && ( self::is_connection_ready() || ( new Status() )->is_offline_mode() ) ) {
4137 return array_merge(
4138 $jetpack_home,
4139 array( 'settings' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack#/settings' ), __( 'Settings', 'jetpack' ) ) ),
4140 array( 'support' => sprintf( '<a href="%s">%s</a>', self::admin_url( 'page=jetpack-debugger ' ), __( 'Support', 'jetpack' ) ) ),
4141 $actions
4142 );
4143 }
4144
4145 return array_merge( $jetpack_home, $actions );
4146 }
4147
4148 /**
4149 * Adds the deactivation warning modal if there are other active plugins using the connection
4150 *
4151 * @param string $hook The current admin page.
4152 *
4153 * @return void
4154 */
4155 public function deactivate_dialog( $hook ) {
4156 if (
4157 'plugins.php' === $hook
4158 && self::is_connection_ready()
4159 ) {
4160
4161 $active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4162
4163 if ( count( $active_plugins_using_connection ) > 1 ) {
4164
4165 add_thickbox();
4166
4167 // Register jp-tracks-functions dependency.
4168 Tracking::register_tracks_functions_scripts();
4169
4170 wp_enqueue_script(
4171 'jetpack-deactivate-dialog-js',
4172 Assets::get_file_url_for_environment(
4173 '_inc/build/jetpack-deactivate-dialog.min.js',
4174 '_inc/jetpack-deactivate-dialog.js'
4175 ),
4176 array( 'jquery', 'jp-tracks-functions' ),
4177 JETPACK__VERSION,
4178 true
4179 );
4180
4181 wp_localize_script(
4182 'jetpack-deactivate-dialog-js',
4183 'deactivate_dialog',
4184 array(
4185 'title' => __( 'Deactivate Jetpack', 'jetpack' ),
4186 'deactivate_label' => __( 'Disconnect and Deactivate', 'jetpack' ),
4187 'tracksUserData' => Jetpack_Tracks_Client::get_connected_user_tracks_identity(),
4188 )
4189 );
4190
4191 add_action( 'admin_footer', array( $this, 'deactivate_dialog_content' ) );
4192
4193 wp_enqueue_style( 'jetpack-deactivate-dialog', plugins_url( 'css/jetpack-deactivate-dialog.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
4194 }
4195 }
4196 }
4197
4198 /**
4199 * Outputs the content of the deactivation modal
4200 *
4201 * @return void
4202 */
4203 public function deactivate_dialog_content() {
4204 $active_plugins_using_connection = Connection_Plugin_Storage::get_all();
4205 unset( $active_plugins_using_connection['jetpack'] );
4206 $this->load_view( 'admin/deactivation-dialog.php', $active_plugins_using_connection );
4207 }
4208
4209 /**
4210 * Filters the login URL to include the registration flow in case the user isn't logged in.
4211 *
4212 * @param string $login_url The wp-login URL.
4213 * @param string $redirect URL to redirect users after logging in.
4214 * @since Jetpack 8.4
4215 * @return string
4216 */
4217 public function login_url( $login_url, $redirect ) {
4218 parse_str( wp_parse_url( $redirect, PHP_URL_QUERY ), $redirect_parts );
4219 if ( ! empty( $redirect_parts[ self::$jetpack_redirect_login ] ) ) {
4220 $login_url = add_query_arg( self::$jetpack_redirect_login, 'true', $login_url );
4221 }
4222 return $login_url;
4223 }
4224
4225 /**
4226 * Redirects non-authenticated users to authenticate with Calypso if redirect flag is set.
4227 *
4228 * @since Jetpack 8.4
4229 */
4230 public function login_init() {
4231 // phpcs:ignore WordPress.Security.NonceVerification
4232 if ( ! empty( $_GET[ self::$jetpack_redirect_login ] ) ) {
4233 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4234 wp_safe_redirect(
4235 add_query_arg(
4236 array(
4237 'forceInstall' => 1,
4238 'url' => rawurlencode( get_site_url() ),
4239 ),
4240 // @todo provide way to go to specific calypso env.
4241 self::get_calypso_host() . 'jetpack/connect'
4242 )
4243 );
4244 exit;
4245 }
4246 }
4247
4248 /*
4249 * Registration flow:
4250 * 1 - ::admin_page_load() action=register
4251 * 2 - ::try_registration()
4252 * 3 - ::register()
4253 * - Creates jetpack_register option containing two secrets and a timestamp
4254 * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
4255 * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
4256 * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
4257 * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
4258 * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
4259 * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
4260 * jetpack_id, jetpack_secret, jetpack_public
4261 * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
4262 * 4 - redirect to https://wordpress.com/start/jetpack-connect
4263 * 5 - user logs in with WP.com account
4264 * 6 - remote request to this site's xmlrpc.php with action remoteAuthorize, Jetpack_XMLRPC_Server->remote_authorize
4265 * - Manager::authorize()
4266 * - Manager::get_token()
4267 * - GET https://jetpack.wordpress.com/jetpack.token/1/ with
4268 * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
4269 * - which responds with access_token, token_type, scope
4270 * - Manager::authorize() stores jetpack_options: user_token => access_token.$user_id
4271 * - Jetpack::activate_default_modules()
4272 * - Deactivates deprecated plugins
4273 * - Activates all default modules
4274 * - Responds with either error, or 'connected' for new connection, or 'linked' for additional linked users
4275 * 7 - For a new connection, user selects a Jetpack plan on wordpress.com
4276 * 8 - User is redirected back to wp-admin/index.php?page=jetpack with state:message=authorized
4277 * Done!
4278 */
4279
4280 /**
4281 * Handles the page load events for the Jetpack admin page
4282 */
4283 function admin_page_load() {
4284 $error = false;
4285
4286 // Make sure we have the right body class to hook stylings for subpages off of.
4287 add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ), 20 );
4288
4289 if ( ! empty( $_GET['jetpack_restate'] ) ) {
4290 // Should only be used in intermediate redirects to preserve state across redirects
4291 self::restate();
4292 }
4293
4294 if ( isset( $_GET['connect_url_redirect'] ) ) {
4295 // @todo: Add validation against a known allowed list.
4296 $from = ! empty( $_GET['from'] ) ? $_GET['from'] : 'iframe';
4297 // User clicked in the iframe to link their accounts
4298 if ( ! self::connection()->is_user_connected() ) {
4299 $redirect = ! empty( $_GET['redirect_after_auth'] ) ? $_GET['redirect_after_auth'] : false;
4300
4301 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4302 $connect_url = $this->build_connect_url( true, $redirect, $from );
4303 remove_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_environments' ) );
4304
4305 if ( isset( $_GET['notes_iframe'] ) ) {
4306 $connect_url .= '&notes_iframe';
4307 }
4308 wp_redirect( $connect_url );
4309 exit;
4310 } else {
4311 if ( ! isset( $_GET['calypso_env'] ) ) {
4312 self::state( 'message', 'already_authorized' );
4313 wp_safe_redirect( self::admin_url() );
4314 exit;
4315 } else {
4316 $connect_url = $this->build_connect_url( true, false, $from );
4317 $connect_url .= '&already_authorized=true';
4318 wp_redirect( $connect_url );
4319 exit;
4320 }
4321 }
4322 }
4323
4324 if ( isset( $_GET['action'] ) ) {
4325 switch ( $_GET['action'] ) {
4326 case 'authorize_redirect':
4327 self::log( 'authorize_redirect' );
4328
4329 add_filter(
4330 'allowed_redirect_hosts',
4331 function ( $domains ) {
4332 $domains[] = 'jetpack.com';
4333 $domains[] = 'jetpack.wordpress.com';
4334 $domains[] = 'wordpress.com';
4335 $domains[] = wp_parse_url( static::get_calypso_host(), PHP_URL_HOST ); // May differ from `wordpress.com`.
4336 return array_unique( $domains );
4337 }
4338 );
4339
4340 // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4341 $dest_url = empty( $_GET['dest_url'] ) ? null : $_GET['dest_url'];
4342
4343 if ( ! $dest_url || ( 0 === stripos( $dest_url, 'https://jetpack.com/' ) && 0 === stripos( $dest_url, 'https://wordpress.com/' ) ) ) {
4344 // The destination URL is missing or invalid, nothing to do here.
4345 exit;
4346 }
4347
4348 if ( static::connection()->is_connected() && static::connection()->is_user_connected() ) {
4349 // The user is either already connected, or finished the connection process.
4350 wp_safe_redirect( $dest_url );
4351 exit;
4352 } elseif ( ! empty( $_GET['done'] ) ) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
4353 // The user decided not to proceed with setting up the connection.
4354 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4355 exit;
4356 }
4357
4358 $redirect_args = array(
4359 'page' => 'jetpack',
4360 'action' => 'authorize_redirect',
4361 'dest_url' => rawurlencode( $dest_url ),
4362 'done' => '1',
4363 );
4364
4365 if ( ! empty( $_GET['from'] ) && 'jetpack_site_only_checkout' === $_GET['from'] ) {
4366 $redirect_args['from'] = 'jetpack_site_only_checkout';
4367 }
4368
4369 wp_safe_redirect( static::build_authorize_url( self::admin_url( $redirect_args ) ) );
4370 exit;
4371 case 'authorize':
4372 _doing_it_wrong( __METHOD__, 'The `page=jetpack&action=authorize` webhook is deprecated. Use `handler=jetpack-connection-webhooks&action=authorize` instead', 'Jetpack 9.5.0' );
4373 ( new Connection_Webhooks( $this->connection_manager ) )->handle_authorize();
4374 exit;
4375 case 'register':
4376 if ( ! current_user_can( 'jetpack_connect' ) ) {
4377 $error = 'cheatin';
4378 break;
4379 }
4380 check_admin_referer( 'jetpack-register' );
4381 self::log( 'register' );
4382 self::maybe_set_version_option();
4383 $from = isset( $_GET['from'] ) ? $_GET['from'] : false;
4384 if ( $from ) {
4385 static::connection()->add_register_request_param( 'from', (string) $from );
4386 }
4387 $registered = static::connection()->try_registration();
4388 if ( is_wp_error( $registered ) ) {
4389 $error = $registered->get_error_code();
4390 self::state( 'error', $error );
4391 self::state( 'error', $registered->get_error_message() );
4392
4393 /**
4394 * Jetpack registration Error.
4395 *
4396 * @since 7.5.0
4397 *
4398 * @param string|int $error The error code.
4399 * @param \WP_Error $registered The error object.
4400 */
4401 do_action( 'jetpack_connection_register_fail', $error, $registered );
4402 break;
4403 }
4404
4405 $redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : false;
4406
4407 /**
4408 * Jetpack registration Success.
4409 *
4410 * @since 7.5.0
4411 *
4412 * @param string $from 'from' GET parameter;
4413 */
4414 do_action( 'jetpack_connection_register_success', $from );
4415
4416 $url = $this->build_connect_url( true, $redirect, $from );
4417
4418 if ( ! empty( $_GET['onboarding'] ) ) {
4419 $url = add_query_arg( 'onboarding', $_GET['onboarding'], $url );
4420 }
4421
4422 if ( ! empty( $_GET['auth_approved'] ) && 'true' === $_GET['auth_approved'] ) {
4423 $url = add_query_arg( 'auth_approved', 'true', $url );
4424 }
4425
4426 wp_redirect( $url );
4427 exit;
4428 case 'activate':
4429 if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
4430 $error = 'cheatin';
4431 break;
4432 }
4433
4434 $module = stripslashes( $_GET['module'] );
4435 check_admin_referer( "jetpack_activate-$module" );
4436 self::log( 'activate', $module );
4437 if ( ! self::activate_module( $module ) ) {
4438 self::state( 'error', sprintf( __( 'Could not activate %s', 'jetpack' ), $module ) );
4439 }
4440 // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
4441 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4442 exit;
4443 case 'activate_default_modules':
4444 check_admin_referer( 'activate_default_modules' );
4445 self::log( 'activate_default_modules' );
4446 self::restate();
4447 $min_version = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
4448 $max_version = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
4449 $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
4450 self::activate_default_modules( $min_version, $max_version, $other_modules );
4451 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4452 exit;
4453 case 'disconnect':
4454 if ( ! current_user_can( 'jetpack_disconnect' ) ) {
4455 $error = 'cheatin';
4456 break;
4457 }
4458
4459 check_admin_referer( 'jetpack-disconnect' );
4460 self::log( 'disconnect' );
4461 self::disconnect();
4462 wp_safe_redirect( self::admin_url( 'disconnected=true' ) );
4463 exit;
4464 case 'reconnect':
4465 if ( ! current_user_can( 'jetpack_reconnect' ) ) {
4466 $error = 'cheatin';
4467 break;
4468 }
4469
4470 check_admin_referer( 'jetpack-reconnect' );
4471 self::log( 'reconnect' );
4472 self::disconnect();
4473 wp_redirect( $this->build_connect_url( true, false, 'reconnect' ) );
4474 exit;
4475 case 'deactivate':
4476 if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
4477 $error = 'cheatin';
4478 break;
4479 }
4480
4481 $modules = stripslashes( $_GET['module'] );
4482 check_admin_referer( "jetpack_deactivate-$modules" );
4483 foreach ( explode( ',', $modules ) as $module ) {
4484 self::log( 'deactivate', $module );
4485 self::deactivate_module( $module );
4486 self::state( 'message', 'module_deactivated' );
4487 }
4488 self::state( 'module', $modules );
4489 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4490 exit;
4491 case 'unlink':
4492 $redirect = isset( $_GET['redirect'] ) ? $_GET['redirect'] : '';
4493 check_admin_referer( 'jetpack-unlink' );
4494 self::log( 'unlink' );
4495 $this->connection_manager->disconnect_user();
4496 self::state( 'message', 'unlinked' );
4497 if ( 'sub-unlink' == $redirect ) {
4498 wp_safe_redirect( admin_url() );
4499 } else {
4500 wp_safe_redirect( self::admin_url( array( 'page' => $redirect ) ) );
4501 }
4502 exit;
4503 case 'onboard':
4504 if ( ! current_user_can( 'manage_options' ) ) {
4505 wp_safe_redirect( self::admin_url( 'page=jetpack' ) );
4506 } else {
4507 self::create_onboarding_token();
4508 $url = $this->build_connect_url( true );
4509
4510 if ( false !== ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
4511 $url = add_query_arg( 'onboarding', $token, $url );
4512 }
4513
4514 $calypso_env = $this->get_calypso_env();
4515 if ( ! empty( $calypso_env ) ) {
4516 $url = add_query_arg( 'calypso_env', $calypso_env, $url );
4517 }
4518
4519 wp_redirect( $url );
4520 exit;
4521 }
4522 exit;
4523 default:
4524 /**
4525 * Fires when a Jetpack admin page is loaded with an unrecognized parameter.
4526 *
4527 * @since 2.6.0
4528 *
4529 * @param string sanitize_key( $_GET['action'] ) Unrecognized URL parameter.
4530 */
4531 do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
4532 }
4533 }
4534
4535 if ( ! $error = $error ? $error : self::state( 'error' ) ) {
4536 self::activate_new_modules( true );
4537 }
4538
4539 $message_code = self::state( 'message' );
4540 if ( self::state( 'optin-manage' ) ) {
4541 $activated_manage = $message_code;
4542 $message_code = 'jetpack-manage';
4543 }
4544
4545 switch ( $message_code ) {
4546 case 'jetpack-manage':
4547 $sites_url = esc_url( Redirect::get_url( 'calypso-sites' ) );
4548 // translators: %s is the URL to the "Sites" panel on wordpress.com.
4549 $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>';
4550 if ( $activated_manage ) {
4551 $this->message .= '<br /><strong>' . __( 'Manage has been activated for you!', 'jetpack' ) . '</strong>';
4552 }
4553 break;
4554
4555 }
4556
4557 $deactivated_plugins = self::state( 'deactivated_plugins' );
4558
4559 if ( ! empty( $deactivated_plugins ) ) {
4560 $deactivated_plugins = explode( ',', $deactivated_plugins );
4561 $deactivated_titles = array();
4562 foreach ( $deactivated_plugins as $deactivated_plugin ) {
4563 if ( ! isset( $this->plugins_to_deactivate[ $deactivated_plugin ] ) ) {
4564 continue;
4565 }
4566
4567 $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[ $deactivated_plugin ][1] ) . '</strong>';
4568 }
4569
4570 if ( $deactivated_titles ) {
4571 if ( $this->message ) {
4572 $this->message .= "<br /><br />\n";
4573 }
4574
4575 $this->message .= wp_sprintf(
4576 _n(
4577 'Jetpack contains the most recent version of the old %l plugin.',
4578 'Jetpack contains the most recent versions of the old %l plugins.',
4579 count( $deactivated_titles ),
4580 'jetpack'
4581 ),
4582 $deactivated_titles
4583 );
4584
4585 $this->message .= "<br />\n";
4586
4587 $this->message .= _n(
4588 'The old version has been deactivated and can be removed from your site.',
4589 'The old versions have been deactivated and can be removed from your site.',
4590 count( $deactivated_titles ),
4591 'jetpack'
4592 );
4593 }
4594 }
4595
4596 $this->privacy_checks = self::state( 'privacy_checks' );
4597
4598 if ( $this->message || $this->error || $this->privacy_checks ) {
4599 add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
4600 }
4601
4602 add_filter( 'jetpack_short_module_description', 'wptexturize' );
4603 }
4604
4605 function admin_notices() {
4606
4607 if ( $this->error ) {
4608 ?>
4609 <div id="message" class="jetpack-message jetpack-err">
4610 <div class="squeezer">
4611 <h2>
4612 <?php
4613 echo wp_kses(
4614 $this->error,
4615 array(
4616 'a' => array( 'href' => array() ),
4617 'small' => true,
4618 'code' => true,
4619 'strong' => true,
4620 'br' => true,
4621 'b' => true,
4622 )
4623 );
4624 ?>
4625 </h2>
4626 <?php if ( $desc = self::state( 'error_description' ) ) : ?>
4627 <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
4628 <?php endif; ?>
4629 </div>
4630 </div>
4631 <?php
4632 }
4633
4634 if ( $this->message ) {
4635 ?>
4636 <div id="message" class="jetpack-message">
4637 <div class="squeezer">
4638 <h2>
4639 <?php
4640 echo wp_kses(
4641 $this->message,
4642 array(
4643 'strong' => array(),
4644 'a' => array( 'href' => true ),
4645 'br' => true,
4646 )
4647 );
4648 ?>
4649 </h2>
4650 </div>
4651 </div>
4652 <?php
4653 }
4654
4655 if ( $this->privacy_checks ) :
4656 $module_names = $module_slugs = array();
4657
4658 $privacy_checks = explode( ',', $this->privacy_checks );
4659 $privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
4660 foreach ( $privacy_checks as $module_slug ) {
4661 $module = self::get_module( $module_slug );
4662 if ( ! $module ) {
4663 continue;
4664 }
4665
4666 $module_slugs[] = $module_slug;
4667 $module_names[] = "<strong>{$module['name']}</strong>";
4668 }
4669
4670 $module_slugs = join( ',', $module_slugs );
4671 ?>
4672 <div id="message" class="jetpack-message jetpack-err">
4673 <div class="squeezer">
4674 <h2><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h2><br />
4675 <p>
4676 <?php
4677 echo wp_kses(
4678 wptexturize(
4679 wp_sprintf(
4680 _nx(
4681 "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
4682 "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
4683 count( $privacy_checks ),
4684 '%l = list of Jetpack module/feature names',
4685 'jetpack'
4686 ),
4687 $module_names
4688 )
4689 ),
4690 array( 'strong' => true )
4691 );
4692
4693 echo "\n<br />\n";
4694
4695 echo wp_kses(
4696 sprintf(
4697 _nx(
4698 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
4699 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
4700 count( $privacy_checks ),
4701 '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
4702 'jetpack'
4703 ),
4704 wp_nonce_url(
4705 self::admin_url(
4706 array(
4707 'page' => 'jetpack',
4708 'action' => 'deactivate',
4709 'module' => urlencode( $module_slugs ),
4710 )
4711 ),
4712 "jetpack_deactivate-$module_slugs"
4713 ),
4714 esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
4715 ),
4716 array(
4717 'a' => array(
4718 'href' => true,
4719 'title' => true,
4720 ),
4721 )
4722 );
4723 ?>
4724 </p>
4725 </div>
4726 </div>
4727 <?php
4728 endif;
4729 }
4730
4731 /**
4732 * We can't always respond to a signed XML-RPC request with a
4733 * helpful error message. In some circumstances, doing so could
4734 * leak information.
4735 *
4736 * Instead, track that the error occurred via a Jetpack_Option,
4737 * and send that data back in the heartbeat.
4738 * All this does is increment a number, but it's enough to find
4739 * trends.
4740 *
4741 * @param WP_Error $xmlrpc_error The error produced during
4742 * signature validation.
4743 */
4744 function track_xmlrpc_error( $xmlrpc_error ) {
4745 $code = is_wp_error( $xmlrpc_error )
4746 ? $xmlrpc_error->get_error_code()
4747 : 'should-not-happen';
4748
4749 $xmlrpc_errors = Jetpack_Options::get_option( 'xmlrpc_errors', array() );
4750 if ( isset( $xmlrpc_errors[ $code ] ) && $xmlrpc_errors[ $code ] ) {
4751 // No need to update the option if we already have
4752 // this code stored.
4753 return;
4754 }
4755 $xmlrpc_errors[ $code ] = true;
4756
4757 Jetpack_Options::update_option( 'xmlrpc_errors', $xmlrpc_errors, false );
4758 }
4759
4760 /**
4761 * Initialize the jetpack stats instance only when needed
4762 *
4763 * @return void
4764 */
4765 private function initialize_stats() {
4766 if ( is_null( $this->a8c_mc_stats_instance ) ) {
4767 $this->a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4768 }
4769 }
4770
4771 /**
4772 * Record a stat for later output. This will only currently output in the admin_footer.
4773 */
4774 function stat( $group, $detail ) {
4775 $this->initialize_stats();
4776 $this->a8c_mc_stats_instance->add( $group, $detail );
4777
4778 // Keep a local copy for backward compatibility (there are some direct checks on this).
4779 $this->stats = $this->a8c_mc_stats_instance->get_current_stats();
4780 }
4781
4782 /**
4783 * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
4784 */
4785 function do_stats( $method = '' ) {
4786 $this->initialize_stats();
4787 if ( 'server_side' === $method ) {
4788 $this->a8c_mc_stats_instance->do_server_side_stats();
4789 } else {
4790 $this->a8c_mc_stats_instance->do_stats();
4791 }
4792
4793 // Keep a local copy for backward compatibility (there are some direct checks on this).
4794 $this->stats = array();
4795 }
4796
4797 /**
4798 * Runs stats code for a one-off, server-side.
4799 *
4800 * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
4801 *
4802 * @return bool If it worked.
4803 */
4804 static function do_server_side_stat( $args ) {
4805 $url = self::build_stats_url( $args );
4806 $a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4807 return $a8c_mc_stats_instance->do_server_side_stat( $url );
4808 }
4809
4810 /**
4811 * Builds the stats url.
4812 *
4813 * @param $args array|string The arguments to append to the URL.
4814 *
4815 * @return string The URL to be pinged.
4816 */
4817 static function build_stats_url( $args ) {
4818
4819 $a8c_mc_stats_instance = new Automattic\Jetpack\A8c_Mc_Stats();
4820 return $a8c_mc_stats_instance->build_stats_url( $args );
4821
4822 }
4823
4824 /**
4825 * Builds a URL to the Jetpack connection auth page
4826 *
4827 * @since 3.9.5
4828 *
4829 * @param bool $raw If true, URL will not be escaped.
4830 * @param bool|string $redirect If true, will redirect back to Jetpack wp-admin landing page after connection.
4831 * If string, will be a custom redirect.
4832 * @param bool|string $from If not false, adds 'from=$from' param to the connect URL.
4833 * @param bool $register If true, will generate a register URL regardless of the existing token, since 4.9.0
4834 *
4835 * @return string Connect URL
4836 */
4837 function build_connect_url( $raw = false, $redirect = false, $from = false, $register = false ) {
4838 $site_id = Jetpack_Options::get_option( 'id' );
4839 $blog_token = ( new Tokens() )->get_access_token();
4840
4841 if ( $register || ! $blog_token || ! $site_id ) {
4842 $url = self::nonce_url_no_esc( self::admin_url( 'action=register' ), 'jetpack-register' );
4843
4844 if ( ! empty( $redirect ) ) {
4845 $url = add_query_arg(
4846 'redirect',
4847 urlencode( wp_validate_redirect( esc_url_raw( $redirect ) ) ),
4848 $url
4849 );
4850 }
4851
4852 if ( is_network_admin() ) {
4853 $url = add_query_arg( 'is_multisite', network_admin_url( 'admin.php?page=jetpack-settings' ), $url );
4854 }
4855
4856 $calypso_env = self::get_calypso_env();
4857
4858 if ( ! empty( $calypso_env ) ) {
4859 $url = add_query_arg( 'calypso_env', $calypso_env, $url );
4860 }
4861 } else {
4862
4863 // Let's check the existing blog token to see if we need to re-register. We only check once per minute
4864 // because otherwise this logic can get us in to a loop.
4865 $last_connect_url_check = (int) Jetpack_Options::get_raw_option( 'jetpack_last_connect_url_check' );
4866 if ( ! $last_connect_url_check || ( time() - $last_connect_url_check ) > MINUTE_IN_SECONDS ) {
4867 Jetpack_Options::update_raw_option( 'jetpack_last_connect_url_check', time() );
4868
4869 $response = Client::wpcom_json_api_request_as_blog(
4870 sprintf( '/sites/%d', $site_id ) . '?force=wpcom',
4871 '1.1'
4872 );
4873
4874 if ( 200 !== wp_remote_retrieve_response_code( $response ) ) {
4875
4876 // Generating a register URL instead to refresh the existing token
4877 return $this->build_connect_url( $raw, $redirect, $from, true );
4878 }
4879 }
4880
4881 $url = $this->build_authorize_url( $redirect );
4882 }
4883
4884 if ( $from ) {
4885 $url = add_query_arg( 'from', $from, $url );
4886 }
4887
4888 $url = $raw ? esc_url_raw( $url ) : esc_url( $url );
4889 /**
4890 * Filter the URL used when connecting a user to a WordPress.com account.
4891 *
4892 * @since 8.1.0
4893 *
4894 * @param string $url Connection URL.
4895 * @param bool $raw If true, URL will not be escaped.
4896 */
4897 return apply_filters( 'jetpack_build_connection_url', $url, $raw );
4898 }
4899
4900 public static function build_authorize_url( $redirect = false, $iframe = false ) {
4901
4902 add_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4903 add_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4904
4905 if ( $iframe ) {
4906 add_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4907 }
4908
4909 $c8n = self::connection();
4910 $url = $c8n->get_authorization_url( wp_get_current_user(), $redirect );
4911
4912 remove_filter( 'jetpack_connect_request_body', array( __CLASS__, 'filter_connect_request_body' ) );
4913 remove_filter( 'jetpack_connect_redirect_url', array( __CLASS__, 'filter_connect_redirect_url' ) );
4914
4915 if ( $iframe ) {
4916 remove_filter( 'jetpack_use_iframe_authorization_flow', '__return_true' );
4917 }
4918
4919 /**
4920 * Filter the URL used when authorizing a user to a WordPress.com account.
4921 *
4922 * @since 8.9.0
4923 *
4924 * @param string $url Connection URL.
4925 */
4926 return apply_filters( 'jetpack_build_authorize_url', $url );
4927 }
4928
4929 /**
4930 * Filters the connection URL parameter array.
4931 *
4932 * @param array $args default URL parameters used by the package.
4933 * @return array the modified URL arguments array.
4934 */
4935 public static function filter_connect_request_body( $args ) {
4936 if (
4937 Constants::is_defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4938 && include_once Constants::get_constant( 'JETPACK__GLOTPRESS_LOCALES_PATH' )
4939 ) {
4940 $gp_locale = GP_Locales::by_field( 'wp_locale', get_locale() );
4941 $args['locale'] = isset( $gp_locale ) && isset( $gp_locale->slug )
4942 ? $gp_locale->slug
4943 : '';
4944 }
4945
4946 $tracking = new Tracking();
4947 $tracks_identity = $tracking->tracks_get_identity( $args['state'] );
4948
4949 $args = array_merge(
4950 $args,
4951 array(
4952 '_ui' => $tracks_identity['_ui'],
4953 '_ut' => $tracks_identity['_ut'],
4954 )
4955 );
4956
4957 $calypso_env = self::get_calypso_env();
4958
4959 if ( ! empty( $calypso_env ) ) {
4960 $args['calypso_env'] = $calypso_env;
4961 }
4962
4963 return $args;
4964 }
4965
4966 /**
4967 * Filters the `jetpack/v4/connection/data` API response of the Connection package in order to
4968 * add Jetpack-the-plugin related permissions.
4969 *
4970 * @since 10.0
4971 *
4972 * @param array $current_user_connection_data An array containing the current user connection data.
4973 * @return array
4974 */
4975 public static function filter_jetpack_current_user_connection_data( $current_user_connection_data ) {
4976 $jetpack_permissions = array(
4977 'admin_page' => current_user_can( 'jetpack_admin_page' ),
4978 'manage_modules' => current_user_can( 'jetpack_manage_modules' ),
4979 'network_admin' => current_user_can( 'jetpack_network_admin_page' ),
4980 'network_sites_page' => current_user_can( 'jetpack_network_sites_page' ),
4981 'edit_posts' => current_user_can( 'edit_posts' ),
4982 'publish_posts' => current_user_can( 'publish_posts' ),
4983 'manage_options' => current_user_can( 'manage_options' ),
4984 'view_stats' => current_user_can( 'view_stats' ),
4985 'manage_plugins' => current_user_can( 'install_plugins' )
4986 && current_user_can( 'activate_plugins' )
4987 && current_user_can( 'update_plugins' )
4988 && current_user_can( 'delete_plugins' ),
4989 );
4990
4991 if ( isset( $current_user_connection_data['permissions'] ) &&
4992 is_array( $current_user_connection_data['permissions'] ) ) {
4993 $current_user_connection_data['permissions'] = array_merge( $current_user_connection_data['permissions'], $jetpack_permissions );
4994 } else {
4995 $current_user_connection_data['permissions'] = $jetpack_permissions;
4996 }
4997
4998 return $current_user_connection_data;
4999 }
5000
5001 /**
5002 * Filters the URL that will process the connection data. It can be different from the URL
5003 * that we send the user to after everything is done.
5004 *
5005 * @param String $processing_url the default redirect URL used by the package.
5006 * @return String the modified URL.
5007 *
5008 * @deprecated since Jetpack 9.5.0
5009 */
5010 public static function filter_connect_processing_url( $processing_url ) {
5011 _deprecated_function( __METHOD__, 'jetpack-9.5' );
5012
5013 $processing_url = admin_url( 'admin.php?page=jetpack' ); // Making PHPCS happy.
5014 return $processing_url;
5015 }
5016
5017 /**
5018 * Filters the redirection URL that is used for connect requests. The redirect
5019 * URL should return the user back to the Jetpack console.
5020 *
5021 * @param String $redirect the default redirect URL used by the package.
5022 * @return String the modified URL.
5023 */
5024 public static function filter_connect_redirect_url( $redirect ) {
5025 $jetpack_admin_page = esc_url_raw( admin_url( 'admin.php?page=jetpack' ) );
5026 $redirect = $redirect
5027 ? wp_validate_redirect( esc_url_raw( $redirect ), $jetpack_admin_page )
5028 : $jetpack_admin_page;
5029
5030 if ( isset( $_REQUEST['is_multisite'] ) ) {
5031 $redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
5032 }
5033
5034 return $redirect;
5035 }
5036
5037 /**
5038 * This action fires at the beginning of the Manager::authorize method.
5039 */
5040 public static function authorize_starting() {
5041 $jetpack_unique_connection = Jetpack_Options::get_option( 'unique_connection' );
5042 // Checking if site has been active/connected previously before recording unique connection.
5043 if ( ! $jetpack_unique_connection ) {
5044 // jetpack_unique_connection option has never been set.
5045 $jetpack_unique_connection = array(
5046 'connected' => 0,
5047 'disconnected' => 0,
5048 'version' => '3.6.1',
5049 );
5050
5051 update_option( 'jetpack_unique_connection', $jetpack_unique_connection );
5052
5053 // Track unique connection.
5054 $jetpack = self::init();
5055
5056 $jetpack->stat( 'connections', 'unique-connection' );
5057 $jetpack->do_stats( 'server_side' );
5058 }
5059
5060 // Increment number of times connected.
5061 $jetpack_unique_connection['connected'] += 1;
5062 Jetpack_Options::update_option( 'unique_connection', $jetpack_unique_connection );
5063 }
5064
5065 /**
5066 * This action fires when the site is registered (connected at a site level).
5067 */
5068 public function handle_unique_registrations_stats() {
5069 $jetpack_unique_registrations = Jetpack_Options::get_option( 'unique_registrations' );
5070 // Checking if site has been registered previously before recording unique connection.
5071 if ( ! $jetpack_unique_registrations ) {
5072
5073 $jetpack_unique_registrations = 0;
5074
5075 $this->stat( 'connections', 'unique-registrations' );
5076 $this->do_stats( 'server_side' );
5077 }
5078
5079 // Increment number of times connected.
5080 $jetpack_unique_registrations ++;
5081 Jetpack_Options::update_option( 'unique_registrations', $jetpack_unique_registrations );
5082 }
5083
5084 /**
5085 * This action fires at the end of the Manager::authorize method when a secondary user is
5086 * linked.
5087 */
5088 public static function authorize_ending_linked() {
5089 // Don't activate anything since we are just connecting a user.
5090 self::state( 'message', 'linked' );
5091 }
5092
5093 /**
5094 * This action fires at the end of the Manager::authorize method when the master user is
5095 * authorized.
5096 *
5097 * @param array $data The request data.
5098 */
5099 public static function authorize_ending_authorized( $data ) {
5100 // If this site has been through the Jetpack Onboarding flow, delete the onboarding token.
5101 self::invalidate_onboarding_token();
5102
5103 // If redirect_uri is SSO, ensure SSO module is enabled.
5104 parse_str( wp_parse_url( $data['redirect_uri'], PHP_URL_QUERY ), $redirect_options );
5105
5106 /** This filter is documented in class.jetpack-cli.php */
5107 $jetpack_start_enable_sso = apply_filters( 'jetpack_start_enable_sso', true );
5108
5109 $activate_sso = (
5110 isset( $redirect_options['action'] ) &&
5111 'jetpack-sso' === $redirect_options['action'] &&
5112 $jetpack_start_enable_sso
5113 );
5114
5115 $do_redirect_on_error = ( 'client' === $data['auth_type'] );
5116
5117 self::handle_post_authorization_actions( $activate_sso, $do_redirect_on_error );
5118 }
5119
5120 /**
5121 * Fires on the jetpack_site_registered hook and acitvates default modules
5122 */
5123 public static function activate_default_modules_on_site_register() {
5124 $active_modules = Jetpack_Options::get_option( 'active_modules' );
5125 if ( $active_modules ) {
5126 self::delete_active_modules();
5127
5128 // 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.
5129 self::activate_default_modules( 999, 1, $active_modules, false );
5130 } else {
5131 // On a fresh new connection, at this point we activate only modules that do not require a user connection.
5132 self::activate_default_modules( false, false, array(), false, null, null, false );
5133 }
5134
5135 // Since this is a fresh connection, be sure to clear out IDC options.
5136 Identity_Crisis::clear_all_idc_options();
5137 }
5138
5139 /**
5140 * This action fires at the end of the REST_Connector connection_reconnect method when the
5141 * reconnect process is completed.
5142 * Note that this currently only happens when we don't need the user to re-authorize
5143 * their WP.com account, eg in cases where we are restoring a connection with
5144 * unhealthy blog token.
5145 */
5146 public static function reconnection_completed() {
5147 self::state( 'message', 'reconnection_completed' );
5148 }
5149
5150 /**
5151 * Get our assumed site creation date.
5152 * Calculated based on the earlier date of either:
5153 * - Earliest admin user registration date.
5154 * - Earliest date of post of any post type.
5155 *
5156 * @since 7.2.0
5157 * @deprecated since 7.8.0
5158 *
5159 * @return string Assumed site creation date and time.
5160 */
5161 public static function get_assumed_site_creation_date() {
5162 _deprecated_function( __METHOD__, 'jetpack-7.8', 'Automattic\\Jetpack\\Connection\\Manager' );
5163 return self::connection()->get_assumed_site_creation_date();
5164 }
5165
5166 public static function apply_activation_source_to_args( &$args ) {
5167 list( $activation_source_name, $activation_source_keyword ) = get_option( 'jetpack_activation_source' );
5168
5169 if ( $activation_source_name ) {
5170 $args['_as'] = urlencode( $activation_source_name );
5171 }
5172
5173 if ( $activation_source_keyword ) {
5174 $args['_ak'] = urlencode( $activation_source_keyword );
5175 }
5176 }
5177
5178 function build_reconnect_url( $raw = false ) {
5179 $url = wp_nonce_url( self::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
5180 return $raw ? $url : esc_url( $url );
5181 }
5182
5183 public static function admin_url( $args = null ) {
5184 $args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
5185 $url = add_query_arg( $args, admin_url( 'admin.php' ) );
5186 return $url;
5187 }
5188
5189 public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
5190 $actionurl = str_replace( '&amp;', '&', $actionurl );
5191 return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
5192 }
5193
5194 function dismiss_jetpack_notice() {
5195
5196 if ( ! isset( $_GET['jetpack-notice'] ) ) {
5197 return;
5198 }
5199
5200 switch ( $_GET['jetpack-notice'] ) {
5201 case 'dismiss':
5202 if ( check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
5203
5204 require_once ABSPATH . 'wp-admin/includes/plugin.php';
5205 deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
5206 wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
5207 }
5208 break;
5209 }
5210 }
5211
5212 public static function sort_modules( $a, $b ) {
5213 if ( $a['sort'] == $b['sort'] ) {
5214 return 0;
5215 }
5216
5217 return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
5218 }
5219
5220 function ajax_recheck_ssl() {
5221 check_ajax_referer( 'recheck-ssl', 'ajax-nonce' );
5222 $result = self::permit_ssl( true );
5223 wp_send_json(
5224 array(
5225 'enabled' => $result,
5226 'message' => get_transient( 'jetpack_https_test_message' ),
5227 )
5228 );
5229 }
5230
5231 /* Client API */
5232
5233 /**
5234 * Returns the requested Jetpack API URL
5235 *
5236 * @deprecated since 7.7
5237 * @return string
5238 */
5239 public static function api_url( $relative_url ) {
5240 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::api_url' );
5241 $connection = self::connection();
5242 return $connection->api_url( $relative_url );
5243 }
5244
5245 /**
5246 * @deprecated 8.0
5247 *
5248 * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requests.
5249 * But we no longer fix "bad hosts" anyway, outbound HTTPS is required for Jetpack to function.
5250 */
5251 public static function fix_url_for_bad_hosts( $url ) {
5252 _deprecated_function( __METHOD__, 'jetpack-8.0' );
5253 return $url;
5254 }
5255
5256 public static function verify_onboarding_token( $token_data, $token, $request_data ) {
5257 // Default to a blog token.
5258 $token_type = 'blog';
5259
5260 // Let's see if this is onboarding. In such case, use user token type and the provided user id.
5261 if ( isset( $request_data ) || ! empty( $_GET['onboarding'] ) ) {
5262 if ( ! empty( $_GET['onboarding'] ) ) {
5263 $jpo = $_GET;
5264 } else {
5265 $jpo = json_decode( $request_data, true );
5266 }
5267
5268 $jpo_token = ! empty( $jpo['onboarding']['token'] ) ? $jpo['onboarding']['token'] : null;
5269 $jpo_user = ! empty( $jpo['onboarding']['jpUser'] ) ? $jpo['onboarding']['jpUser'] : null;
5270
5271 if (
5272 isset( $jpo_user )
5273 && isset( $jpo_token )
5274 && is_email( $jpo_user )
5275 && ctype_alnum( $jpo_token )
5276 && isset( $_GET['rest_route'] )
5277 && self::validate_onboarding_token_action(
5278 $jpo_token,
5279 $_GET['rest_route']
5280 )
5281 ) {
5282 $jp_user = get_user_by( 'email', $jpo_user );
5283 if ( is_a( $jp_user, 'WP_User' ) ) {
5284 wp_set_current_user( $jp_user->ID );
5285 $user_can = is_multisite()
5286 ? current_user_can_for_blog( get_current_blog_id(), 'manage_options' )
5287 : current_user_can( 'manage_options' );
5288 if ( $user_can ) {
5289 $token_type = 'user';
5290 $token->external_user_id = $jp_user->ID;
5291 }
5292 }
5293 }
5294
5295 $token_data['type'] = $token_type;
5296 $token_data['user_id'] = $token->external_user_id;
5297 }
5298
5299 return $token_data;
5300 }
5301
5302 /**
5303 * Create a random secret for validating onboarding payload
5304 *
5305 * @return string Secret token
5306 */
5307 public static function create_onboarding_token() {
5308 if ( false === ( $token = Jetpack_Options::get_option( 'onboarding' ) ) ) {
5309 $token = wp_generate_password( 32, false );
5310 Jetpack_Options::update_option( 'onboarding', $token );
5311 }
5312
5313 return $token;
5314 }
5315
5316 /**
5317 * Remove the onboarding token
5318 *
5319 * @return bool True on success, false on failure
5320 */
5321 public static function invalidate_onboarding_token() {
5322 return Jetpack_Options::delete_option( 'onboarding' );
5323 }
5324
5325 /**
5326 * Validate an onboarding token for a specific action
5327 *
5328 * @return boolean True if token/action pair is accepted, false if not
5329 */
5330 public static function validate_onboarding_token_action( $token, $action ) {
5331 // Compare tokens, bail if tokens do not match
5332 if ( ! hash_equals( $token, Jetpack_Options::get_option( 'onboarding' ) ) ) {
5333 return false;
5334 }
5335
5336 // List of valid actions we can take
5337 $valid_actions = array(
5338 '/jetpack/v4/settings',
5339 );
5340
5341 // Only allow valid actions.
5342 if ( ! in_array( $action, $valid_actions ) ) {
5343 return false;
5344 }
5345
5346 return true;
5347 }
5348
5349 /**
5350 * Checks to see if the URL is using SSL to connect with Jetpack
5351 *
5352 * @since 2.3.3
5353 * @return boolean
5354 */
5355 public static function permit_ssl( $force_recheck = false ) {
5356 // Do some fancy tests to see if ssl is being supported
5357 if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
5358 $message = '';
5359 if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
5360 $ssl = 0;
5361 } else {
5362 $ssl = 1;
5363
5364 if ( ! wp_http_supports( array( 'ssl' => true ) ) ) {
5365 $ssl = 0;
5366 $message = __( 'WordPress reports no SSL support', 'jetpack' );
5367 } else {
5368 $response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
5369 if ( is_wp_error( $response ) ) {
5370 $ssl = 0;
5371 $message = __( 'WordPress reports no SSL support', 'jetpack' );
5372 } elseif ( 'OK' !== wp_remote_retrieve_body( $response ) ) {
5373 $ssl = 0;
5374 $message = __( 'Response was not OK: ', 'jetpack' ) . wp_remote_retrieve_body( $response );
5375 }
5376 }
5377 }
5378 set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
5379 set_transient( 'jetpack_https_test_message', $message, DAY_IN_SECONDS );
5380 }
5381
5382 return (bool) $ssl;
5383 }
5384
5385 /*
5386 * Displays an admin_notice, alerting the user that outbound SSL isn't working.
5387 */
5388 public function alert_auto_ssl_fail() {
5389 if ( ! current_user_can( 'manage_options' ) ) {
5390 return;
5391 }
5392
5393 $ajax_nonce = wp_create_nonce( 'recheck-ssl' );
5394 ?>
5395
5396 <div id="jetpack-ssl-warning" class="error jp-identity-crisis">
5397 <div class="jp-banner__content">
5398 <h2><?php _e( 'Outbound HTTPS not working', 'jetpack' ); ?></h2>
5399 <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>
5400 <p>
5401 <?php _e( 'Jetpack will re-test for HTTPS support once a day, but you can click here to try again immediately: ', 'jetpack' ); ?>
5402 <a href="#" id="jetpack-recheck-ssl-button"><?php _e( 'Try again', 'jetpack' ); ?></a>
5403 <span id="jetpack-recheck-ssl-output"><?php echo get_transient( 'jetpack_https_test_message' ); ?></span>
5404 </p>
5405 <p>
5406 <?php
5407 printf(
5408 __( 'For more help, try our <a href="%1$s">connection debugger</a> or <a href="%2$s" target="_blank">troubleshooting tips</a>.', 'jetpack' ),
5409 esc_url( self::admin_url( array( 'page' => 'jetpack-debugger' ) ) ),
5410 esc_url( Redirect::get_url( 'jetpack-support-getting-started-troubleshooting-tips' ) )
5411 );
5412 ?>
5413 </p>
5414 </div>
5415 </div>
5416 <style>
5417 #jetpack-recheck-ssl-output { margin-left: 5px; color: red; }
5418 </style>
5419 <script type="text/javascript">
5420 jQuery( document ).ready( function( $ ) {
5421 $( '#jetpack-recheck-ssl-button' ).click( function( e ) {
5422 var $this = $( this );
5423 $this.html( <?php echo json_encode( __( 'Checking', 'jetpack' ) ); ?> );
5424 $( '#jetpack-recheck-ssl-output' ).html( '' );
5425 e.preventDefault();
5426 var data = { action: 'jetpack-recheck-ssl', 'ajax-nonce': '<?php echo $ajax_nonce; ?>' };
5427 $.post( ajaxurl, data )
5428 .done( function( response ) {
5429 if ( response.enabled ) {
5430 $( '#jetpack-ssl-warning' ).hide();
5431 } else {
5432 this.html( <?php echo json_encode( __( 'Try again', 'jetpack' ) ); ?> );
5433 $( '#jetpack-recheck-ssl-output' ).html( 'SSL Failed: ' + response.message );
5434 }
5435 }.bind( $this ) );
5436 } );
5437 } );
5438 </script>
5439
5440 <?php
5441 }
5442
5443 /**
5444 * Returns the Jetpack XML-RPC API
5445 *
5446 * @deprecated 8.0 Use Connection_Manager instead.
5447 * @return string
5448 */
5449 public static function xmlrpc_api_url() {
5450 _deprecated_function( __METHOD__, 'jetpack-8.0', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_api_url()' );
5451 return self::connection()->xmlrpc_api_url();
5452 }
5453
5454 /**
5455 * Returns the connection manager object.
5456 *
5457 * @return Automattic\Jetpack\Connection\Manager
5458 */
5459 public static function connection() {
5460 $jetpack = static::init();
5461
5462 // If the connection manager hasn't been instantiated, do that now.
5463 if ( ! $jetpack->connection_manager ) {
5464 $jetpack->connection_manager = new Connection_Manager( 'jetpack' );
5465 }
5466
5467 return $jetpack->connection_manager;
5468 }
5469
5470 /**
5471 * Creates two secret tokens and the end of life timestamp for them.
5472 *
5473 * Note these tokens are unique per call, NOT static per site for connecting.
5474 *
5475 * @deprecated 9.5 Use Automattic\Jetpack\Connection\Secrets->generate() instead.
5476 *
5477 * @since 2.6
5478 * @param String $action The action name.
5479 * @param Integer $user_id The user identifier.
5480 * @param Integer $exp Expiration time in seconds.
5481 * @return array
5482 */
5483 public static function generate_secrets( $action, $user_id = false, $exp = 600 ) {
5484 _deprecated_function( __METHOD__, 'jetpack-9.5', 'Automattic\\Jetpack\\Connection\\Secrets->generate' );
5485 return self::connection()->generate_secrets( $action, $user_id, $exp );
5486 }
5487
5488 public static function get_secrets( $action, $user_id ) {
5489 $secrets = ( new Secrets() )->get( $action, $user_id );
5490
5491 if ( Secrets::SECRETS_MISSING === $secrets ) {
5492 return new WP_Error( 'verify_secrets_missing', 'Verification secrets not found' );
5493 }
5494
5495 if ( Secrets::SECRETS_EXPIRED === $secrets ) {
5496 return new WP_Error( 'verify_secrets_expired', 'Verification took too long' );
5497 }
5498
5499 return $secrets;
5500 }
5501
5502 /**
5503 * Builds the timeout limit for queries talking with the wpcom servers.
5504 *
5505 * Based on local php max_execution_time in php.ini
5506 *
5507 * @since 2.6
5508 * @return int
5509 * @deprecated
5510 **/
5511 public function get_remote_query_timeout_limit() {
5512 _deprecated_function( __METHOD__, 'jetpack-5.4' );
5513 return self::get_max_execution_time();
5514 }
5515
5516 /**
5517 * Builds the timeout limit for queries talking with the wpcom servers.
5518 *
5519 * Based on local php max_execution_time in php.ini
5520 *
5521 * @since 5.4
5522 * @return int
5523 **/
5524 public static function get_max_execution_time() {
5525 $timeout = (int) ini_get( 'max_execution_time' );
5526
5527 // Ensure exec time set in php.ini
5528 if ( ! $timeout ) {
5529 $timeout = 30;
5530 }
5531 return $timeout;
5532 }
5533
5534 /**
5535 * Sets a minimum request timeout, and returns the current timeout
5536 *
5537 * @since 5.4
5538 **/
5539 public static function set_min_time_limit( $min_timeout ) {
5540 $timeout = self::get_max_execution_time();
5541 if ( $timeout < $min_timeout ) {
5542 $timeout = $min_timeout;
5543 set_time_limit( $timeout );
5544 }
5545 return $timeout;
5546 }
5547
5548 /**
5549 * Takes the response from the Jetpack register new site endpoint and
5550 * verifies it worked properly.
5551 *
5552 * @since 2.6
5553 * @deprecated since 7.7.0
5554 * @see Automattic\Jetpack\Connection\Manager::validate_remote_register_response()
5555 **/
5556 public function validate_remote_register_response() {
5557 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::validate_remote_register_response' );
5558 }
5559
5560 /**
5561 * @deprecated since Jetpack 9.7.0
5562 * @see Automattic\Jetpack\Connection\Manager::try_registration()
5563 *
5564 * @return bool|WP_Error
5565 */
5566 public static function register() {
5567 _deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Manager::try_registration' );
5568 return static::connection()->try_registration( false );
5569 }
5570
5571 /**
5572 * Filters the registration request body to include tracking properties.
5573 *
5574 * @deprecated since Jetpack 9.7.0
5575 * @see Automattic\Jetpack\Connection\Utils::filter_register_request_body()
5576 *
5577 * @param array $properties
5578 * @return array amended properties.
5579 */
5580 public static function filter_register_request_body( $properties ) {
5581 _deprecated_function( __METHOD__, 'jetpack-9.7', 'Automattic\\Jetpack\\Connection\\Utils::filter_register_request_body' );
5582 return Connection_Utils::filter_register_request_body( $properties );
5583 }
5584
5585 /**
5586 * Filters the token request body to include tracking properties.
5587 *
5588 * @param array $properties
5589 * @return array amended properties.
5590 */
5591 public static function filter_token_request_body( $properties ) {
5592 $tracking = new Tracking();
5593 $tracks_identity = $tracking->tracks_get_identity( get_current_user_id() );
5594
5595 return array_merge(
5596 $properties,
5597 array(
5598 '_ui' => $tracks_identity['_ui'],
5599 '_ut' => $tracks_identity['_ut'],
5600 )
5601 );
5602 }
5603
5604 /**
5605 * If the db version is showing something other that what we've got now, bump it to current.
5606 *
5607 * @return bool: True if the option was incorrect and updated, false if nothing happened.
5608 */
5609 public static function maybe_set_version_option() {
5610 list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
5611 if ( JETPACK__VERSION != $version ) {
5612 Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
5613
5614 if ( version_compare( JETPACK__VERSION, $version, '>' ) ) {
5615 /** This action is documented in class.jetpack.php */
5616 do_action( 'updating_jetpack_version', JETPACK__VERSION, $version );
5617 }
5618
5619 return true;
5620 }
5621 return false;
5622 }
5623
5624 /* Client Server API */
5625
5626 /**
5627 * Loads the Jetpack XML-RPC client.
5628 * No longer necessary, as the XML-RPC client will be automagically loaded.
5629 *
5630 * @deprecated since 7.7.0
5631 */
5632 public static function load_xml_rpc_client() {
5633 _deprecated_function( __METHOD__, 'jetpack-7.7' );
5634 }
5635
5636 /**
5637 * Resets the saved authentication state in between testing requests.
5638 *
5639 * @deprecated since 8.9.0
5640 * @see Automattic\Jetpack\Connection\Rest_Authentication::reset_saved_auth_state()
5641 */
5642 public function reset_saved_auth_state() {
5643 _deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::reset_saved_auth_state' );
5644 Connection_Rest_Authentication::init()->reset_saved_auth_state();
5645 }
5646
5647 /**
5648 * Verifies the signature of the current request.
5649 *
5650 * @deprecated since 7.7.0
5651 * @see Automattic\Jetpack\Connection\Manager::verify_xml_rpc_signature()
5652 *
5653 * @return false|array
5654 */
5655 public function verify_xml_rpc_signature() {
5656 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::verify_xml_rpc_signature' );
5657 return self::connection()->verify_xml_rpc_signature();
5658 }
5659
5660 /**
5661 * Verifies the signature of the current request.
5662 *
5663 * This function has side effects and should not be used. Instead,
5664 * use the memoized version `->verify_xml_rpc_signature()`.
5665 *
5666 * @deprecated since 7.7.0
5667 * @see Automattic\Jetpack\Connection\Manager::internal_verify_xml_rpc_signature()
5668 * @internal
5669 */
5670 private function internal_verify_xml_rpc_signature() {
5671 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::internal_verify_xml_rpc_signature' );
5672 }
5673
5674 /**
5675 * Authenticates XML-RPC and other requests from the Jetpack Server.
5676 *
5677 * @deprecated since 7.7.0
5678 * @see Automattic\Jetpack\Connection\Manager::authenticate_jetpack()
5679 *
5680 * @param \WP_User|mixed $user User object if authenticated.
5681 * @param string $username Username.
5682 * @param string $password Password string.
5683 * @return \WP_User|mixed Authenticated user or error.
5684 */
5685 public function authenticate_jetpack( $user, $username, $password ) {
5686 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::authenticate_jetpack' );
5687
5688 if ( ! $this->connection_manager ) {
5689 $this->connection_manager = new Connection_Manager();
5690 }
5691
5692 return $this->connection_manager->authenticate_jetpack( $user, $username, $password );
5693 }
5694
5695 /**
5696 * Authenticates requests from Jetpack server to WP REST API endpoints.
5697 * Uses the existing XMLRPC request signing implementation.
5698 *
5699 * @deprecated since 8.9.0
5700 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authenticate()
5701 */
5702 function wp_rest_authenticate( $user ) {
5703 _deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenticate' );
5704 return Connection_Rest_Authentication::init()->wp_rest_authenticate( $user );
5705 }
5706
5707 /**
5708 * Report authentication status to the WP REST API.
5709 *
5710 * @deprecated since 8.9.0
5711 * @see Automattic\Jetpack\Connection\Rest_Authentication::wp_rest_authentication_errors()
5712 *
5713 * @param WP_Error|mixed $result Error from another authentication handler, null if we should handle it, or another value if not
5714 * @return WP_Error|boolean|null {@see WP_JSON_Server::check_authentication}
5715 */
5716 public function wp_rest_authentication_errors( $value ) {
5717 _deprecated_function( __METHOD__, 'jetpack-8.9', 'Automattic\\Jetpack\\Connection\\Rest_Authentication::wp_rest_authenication_errors' );
5718 return Connection_Rest_Authentication::init()->wp_rest_authentication_errors( $value );
5719 }
5720
5721 /**
5722 * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
5723 * Capture it here so we can verify the signature later.
5724 *
5725 * @deprecated since 7.7.0
5726 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_methods()
5727 *
5728 * @param array $methods XMLRPC methods.
5729 * @return array XMLRPC methods, with the $HTTP_RAW_POST_DATA one.
5730 */
5731 public function xmlrpc_methods( $methods ) {
5732 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_methods' );
5733
5734 if ( ! $this->connection_manager ) {
5735 $this->connection_manager = new Connection_Manager();
5736 }
5737
5738 return $this->connection_manager->xmlrpc_methods( $methods );
5739 }
5740
5741 /**
5742 * Register additional public XMLRPC methods.
5743 *
5744 * @deprecated since 7.7.0
5745 * @see Automattic\Jetpack\Connection\Manager::public_xmlrpc_methods()
5746 *
5747 * @param array $methods Public XMLRPC methods.
5748 * @return array Public XMLRPC methods, with the getOptions one.
5749 */
5750 public function public_xmlrpc_methods( $methods ) {
5751 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::public_xmlrpc_methods' );
5752
5753 if ( ! $this->connection_manager ) {
5754 $this->connection_manager = new Connection_Manager();
5755 }
5756
5757 return $this->connection_manager->public_xmlrpc_methods( $methods );
5758 }
5759
5760 /**
5761 * Handles a getOptions XMLRPC method call.
5762 *
5763 * @deprecated since 7.7.0
5764 * @see Automattic\Jetpack\Connection\Manager::jetpack_getOptions()
5765 *
5766 * @param array $args method call arguments.
5767 * @return array an amended XMLRPC server options array.
5768 */
5769 public function jetpack_getOptions( $args ) { // phpcs:ignore WordPress.NamingConventions.ValidFunctionName.MethodNameInvalid
5770 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::jetpack_getOptions' );
5771
5772 if ( ! $this->connection_manager ) {
5773 $this->connection_manager = new Connection_Manager();
5774 }
5775
5776 return $this->connection_manager->jetpack_getOptions( $args );
5777 }
5778
5779 /**
5780 * Adds Jetpack-specific options to the output of the XMLRPC options method.
5781 *
5782 * @deprecated since 7.7.0
5783 * @see Automattic\Jetpack\Connection\Manager::xmlrpc_options()
5784 *
5785 * @param array $options Standard Core options.
5786 * @return array Amended options.
5787 */
5788 public function xmlrpc_options( $options ) {
5789 _deprecated_function( __METHOD__, 'jetpack-7.7', 'Automattic\\Jetpack\\Connection\\Manager::xmlrpc_options' );
5790
5791 if ( ! $this->connection_manager ) {
5792 $this->connection_manager = new Connection_Manager();
5793 }
5794
5795 return $this->connection_manager->xmlrpc_options( $options );
5796 }
5797
5798 /**
5799 * State is passed via cookies from one request to the next, but never to subsequent requests.
5800 * SET: state( $key, $value );
5801 * GET: $value = state( $key );
5802 *
5803 * @param string $key
5804 * @param string $value
5805 * @param bool $restate private
5806 */
5807 public static function state( $key = null, $value = null, $restate = false ) {
5808 static $state = array();
5809 static $path, $domain;
5810 if ( ! isset( $path ) ) {
5811 require_once ABSPATH . 'wp-admin/includes/plugin.php';
5812 $admin_url = self::admin_url();
5813 $bits = wp_parse_url( $admin_url );
5814
5815 if ( is_array( $bits ) ) {
5816 $path = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
5817 $domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
5818 } else {
5819 $path = $domain = null;
5820 }
5821 }
5822
5823 // Extract state from cookies and delete cookies
5824 if ( isset( $_COOKIE['jetpackState'] ) && is_array( $_COOKIE['jetpackState'] ) ) {
5825 $yum = wp_unslash( $_COOKIE['jetpackState'] );
5826 unset( $_COOKIE['jetpackState'] );
5827 foreach ( $yum as $k => $v ) {
5828 if ( strlen( $v ) ) {
5829 $state[ $k ] = $v;
5830 }
5831 setcookie( "jetpackState[$k]", false, 0, $path, $domain );
5832 }
5833 }
5834
5835 if ( $restate ) {
5836 foreach ( $state as $k => $v ) {
5837 setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
5838 }
5839 return;
5840 }
5841
5842 // Get a state variable.
5843 if ( isset( $key ) && ! isset( $value ) ) {
5844 if ( array_key_exists( $key, $state ) ) {
5845 return $state[ $key ];
5846 }
5847 return null;
5848 }
5849
5850 // Set a state variable.
5851 if ( isset( $key ) && isset( $value ) ) {
5852 if ( is_array( $value ) && isset( $value[0] ) ) {
5853 $value = $value[0];
5854 }
5855 $state[ $key ] = $value;
5856 if ( ! headers_sent() ) {
5857 if ( self::should_set_cookie( $key ) ) {
5858 setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
5859 }
5860 }
5861 }
5862 }
5863
5864 public static function restate() {
5865 self::state( null, null, true );
5866 }
5867
5868 /**
5869 * Determines whether the jetpackState[$key] value should be added to the
5870 * cookie.
5871 *
5872 * @param string $key The state key.
5873 *
5874 * @return boolean Whether the value should be added to the cookie.
5875 */
5876 public static function should_set_cookie( $key ) {
5877 global $current_screen;
5878 $page = isset( $current_screen->base ) ? $current_screen->base : null;
5879
5880 if ( 'toplevel_page_jetpack' === $page && 'display_update_modal' === $key ) {
5881 return false;
5882 }
5883
5884 return true;
5885 }
5886
5887 public static function check_privacy( $file ) {
5888 static $is_site_publicly_accessible = null;
5889
5890 if ( is_null( $is_site_publicly_accessible ) ) {
5891 $is_site_publicly_accessible = false;
5892
5893 $rpc = new Jetpack_IXR_Client();
5894
5895 $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
5896 if ( $success ) {
5897 $response = $rpc->getResponse();
5898 if ( $response ) {
5899 $is_site_publicly_accessible = true;
5900 }
5901 }
5902
5903 Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
5904 }
5905
5906 if ( $is_site_publicly_accessible ) {
5907 return;
5908 }
5909
5910 $module_slug = self::get_module_slug( $file );
5911
5912 $privacy_checks = self::state( 'privacy_checks' );
5913 if ( ! $privacy_checks ) {
5914 $privacy_checks = $module_slug;
5915 } else {
5916 $privacy_checks .= ",$module_slug";
5917 }
5918
5919 self::state( 'privacy_checks', $privacy_checks );
5920 }
5921
5922 /**
5923 * Helper method for multicall XMLRPC.
5924 *
5925 * @deprecated since 8.9.0
5926 * @see Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call()
5927 *
5928 * @param ...$args Args for the async_call.
5929 */
5930 public static function xmlrpc_async_call( ...$args ) {
5931
5932 _deprecated_function( 'Jetpack::xmlrpc_async_call', 'jetpack-8.9.0', 'Automattic\\Jetpack\\Connection\\Xmlrpc_Async_Call::add_call' );
5933
5934 global $blog_id;
5935 static $clients = array();
5936
5937 $client_blog_id = is_multisite() ? $blog_id : 0;
5938
5939 if ( ! isset( $clients[ $client_blog_id ] ) ) {
5940 $clients[ $client_blog_id ] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => true ) );
5941 if ( function_exists( 'ignore_user_abort' ) ) {
5942 ignore_user_abort( true );
5943 }
5944 add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
5945 }
5946
5947 if ( ! empty( $args[0] ) ) {
5948 call_user_func_array( array( $clients[ $client_blog_id ], 'addCall' ), $args );
5949 } elseif ( is_multisite() ) {
5950 foreach ( $clients as $client_blog_id => $client ) {
5951 if ( ! $client_blog_id || empty( $client->calls ) ) {
5952 continue;
5953 }
5954
5955 $switch_success = switch_to_blog( $client_blog_id, true );
5956 if ( ! $switch_success ) {
5957 continue;
5958 }
5959
5960 flush();
5961 $client->query();
5962
5963 restore_current_blog();
5964 }
5965 } else {
5966 if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
5967 flush();
5968 $clients[0]->query();
5969 }
5970 }
5971 }
5972
5973 /**
5974 * Serve a WordPress.com static resource via a randomized wp.com subdomain.
5975 *
5976 * @deprecated 9.3.0 Use Assets::staticize_subdomain.
5977 *
5978 * @param string $url WordPress.com static resource URL.
5979 */
5980 public static function staticize_subdomain( $url ) {
5981 _deprecated_function( __METHOD__, 'jetpack-9.3.0', 'Automattic\Jetpack\Assets::staticize_subdomain' );
5982 return Assets::staticize_subdomain( $url );
5983 }
5984
5985 /* JSON API Authorization */
5986
5987 /**
5988 * Handles the login action for Authorizing the JSON API
5989 */
5990 function login_form_json_api_authorization() {
5991 $this->verify_json_api_authorization_request();
5992
5993 add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
5994
5995 add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
5996 add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
5997 add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
5998 }
5999
6000 // Make sure the login form is POSTed to the signed URL so we can reverify the request
6001 function post_login_form_to_signed_url( $url, $path, $scheme ) {
6002 if ( 'wp-login.php' !== $path || ( 'login_post' !== $scheme && 'login' !== $scheme ) ) {
6003 return $url;
6004 }
6005
6006 $parsed_url = wp_parse_url( $url );
6007 $url = strtok( $url, '?' );
6008 $url = "$url?{$_SERVER['QUERY_STRING']}";
6009 if ( ! empty( $parsed_url['query'] ) ) {
6010 $url .= "&{$parsed_url['query']}";
6011 }
6012
6013 return $url;
6014 }
6015
6016 // Make sure the POSTed request is handled by the same action
6017 function preserve_action_in_login_form_for_json_api_authorization() {
6018 echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
6019 echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
6020 }
6021
6022 // If someone logs in to approve API access, store the Access Code in usermeta
6023 function store_json_api_authorization_token( $user_login, $user ) {
6024 add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
6025 add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
6026 $token = wp_generate_password( 32, false );
6027 update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
6028 }
6029
6030 // Add public-api.wordpress.com to the safe redirect allowed list - only added when someone allows API access.
6031 function allow_wpcom_public_api_domain( $domains ) {
6032 $domains[] = 'public-api.wordpress.com';
6033 return $domains;
6034 }
6035
6036 static function is_redirect_encoded( $redirect_url ) {
6037 return preg_match( '/https?%3A%2F%2F/i', $redirect_url ) > 0;
6038 }
6039
6040 // Add all wordpress.com environments to the safe redirect allowed list.
6041 function allow_wpcom_environments( $domains ) {
6042 $domains[] = 'wordpress.com';
6043 $domains[] = 'wpcalypso.wordpress.com';
6044 $domains[] = 'horizon.wordpress.com';
6045 $domains[] = 'calypso.localhost';
6046 return $domains;
6047 }
6048
6049 // Add the Access Code details to the public-api.wordpress.com redirect
6050 function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
6051 return add_query_arg(
6052 urlencode_deep(
6053 array(
6054 'jetpack-code' => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
6055 'jetpack-user-id' => (int) $user->ID,
6056 'jetpack-state' => $this->json_api_authorization_request['state'],
6057 )
6058 ),
6059 $redirect_to
6060 );
6061 }
6062
6063 /**
6064 * Verifies the request by checking the signature
6065 *
6066 * @since 4.6.0 Method was updated to use `$_REQUEST` instead of `$_GET` and `$_POST`. Method also updated to allow
6067 * passing in an `$environment` argument that overrides `$_REQUEST`. This was useful for integrating with SSO.
6068 *
6069 * @param null|array $environment
6070 */
6071 function verify_json_api_authorization_request( $environment = null ) {
6072 $environment = is_null( $environment )
6073 ? $_REQUEST
6074 : $environment;
6075
6076 list( $env_token,, $env_user_id ) = explode( ':', $environment['token'] );
6077 $token = ( new Tokens() )->get_access_token( $env_user_id, $env_token );
6078 if ( ! $token || empty( $token->secret ) ) {
6079 wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.', 'jetpack' ) );
6080 }
6081
6082 $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' );
6083
6084 // Host has encoded the request URL, probably as a result of a bad http => https redirect
6085 if ( self::is_redirect_encoded( $_GET['redirect_to'] ) ) {
6086 /**
6087 * Jetpack authorisation request Error.
6088 *
6089 * @since 7.5.0
6090 */
6091 do_action( 'jetpack_verify_api_authorization_request_error_double_encode' );
6092 $die_error = sprintf(
6093 /* translators: %s is a URL */
6094 __( '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' ),
6095 Redirect::get_url( 'jetpack-support-double-encoding' )
6096 );
6097 }
6098
6099 $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
6100
6101 if ( isset( $environment['jetpack_json_api_original_query'] ) ) {
6102 $signature = $jetpack_signature->sign_request(
6103 $environment['token'],
6104 $environment['timestamp'],
6105 $environment['nonce'],
6106 '',
6107 'GET',
6108 $environment['jetpack_json_api_original_query'],
6109 null,
6110 true
6111 );
6112 } else {
6113 $signature = $jetpack_signature->sign_current_request(
6114 array(
6115 'body' => null,
6116 'method' => 'GET',
6117 )
6118 );
6119 }
6120
6121 if ( ! $signature ) {
6122 wp_die( $die_error );
6123 } elseif ( is_wp_error( $signature ) ) {
6124 wp_die( $die_error );
6125 } elseif ( ! hash_equals( $signature, $environment['signature'] ) ) {
6126 if ( is_ssl() ) {
6127 // 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
6128 $signature = $jetpack_signature->sign_current_request(
6129 array(
6130 'scheme' => 'http',
6131 'body' => null,
6132 'method' => 'GET',
6133 )
6134 );
6135 if ( ! $signature || is_wp_error( $signature ) || ! hash_equals( $signature, $environment['signature'] ) ) {
6136 wp_die( $die_error );
6137 }
6138 } else {
6139 wp_die( $die_error );
6140 }
6141 }
6142
6143 $timestamp = (int) $environment['timestamp'];
6144 $nonce = stripslashes( (string) $environment['nonce'] );
6145
6146 if ( ! $this->connection_manager ) {
6147 $this->connection_manager = new Connection_Manager();
6148 }
6149
6150 if ( ! ( new Nonce_Handler() )->add( $timestamp, $nonce ) ) {
6151 // De-nonce the nonce, at least for 5 minutes.
6152 // 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)
6153 $old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
6154 if ( $old_nonce_time < time() - 300 ) {
6155 wp_die( esc_html__( 'The authorization process expired. Please go back and try again.', 'jetpack' ) );
6156 }
6157 }
6158
6159 $data = json_decode( base64_decode( stripslashes( $environment['data'] ) ) );
6160 $data_filters = array(
6161 'state' => 'opaque',
6162 'client_id' => 'int',
6163 'client_title' => 'string',
6164 'client_image' => 'url',
6165 );
6166
6167 foreach ( $data_filters as $key => $sanitation ) {
6168 if ( ! isset( $data->$key ) ) {
6169 wp_die( $die_error );
6170 }
6171
6172 switch ( $sanitation ) {
6173 case 'int':
6174 $this->json_api_authorization_request[ $key ] = (int) $data->$key;
6175 break;
6176 case 'opaque':
6177 $this->json_api_authorization_request[ $key ] = (string) $data->$key;
6178 break;
6179 case 'string':
6180 $this->json_api_authorization_request[ $key ] = wp_kses( (string) $data->$key, array() );
6181 break;
6182 case 'url':
6183 $this->json_api_authorization_request[ $key ] = esc_url_raw( (string) $data->$key );
6184 break;
6185 }
6186 }
6187
6188 if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
6189 wp_die( $die_error );
6190 }
6191 }
6192
6193 function login_message_json_api_authorization( $message ) {
6194 return '<p class="message">' . sprintf(
6195 /* translators: Name/image of the client requesting authorization */
6196 esc_html__( '%s wants to access your site’s data. Log in to authorize that access.', 'jetpack' ),
6197 '<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
6198 ) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
6199 }
6200
6201 /**
6202 * Get $content_width, but with a <s>twist</s> filter.
6203 */
6204 public static function get_content_width() {
6205 $content_width = ( isset( $GLOBALS['content_width'] ) && is_numeric( $GLOBALS['content_width'] ) )
6206 ? $GLOBALS['content_width']
6207 : false;
6208 /**
6209 * Filter the Content Width value.
6210 *
6211 * @since 2.2.3
6212 *
6213 * @param string $content_width Content Width value.
6214 */
6215 return apply_filters( 'jetpack_content_width', $content_width );
6216 }
6217
6218 /**
6219 * Pings the WordPress.com Mirror Site for the specified options.
6220 *
6221 * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
6222 *
6223 * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
6224 */
6225 public function get_cloud_site_options( $option_names ) {
6226 $option_names = array_filter( (array) $option_names, 'is_string' );
6227
6228 $xml = new Jetpack_IXR_Client();
6229 $xml->query( 'jetpack.fetchSiteOptions', $option_names );
6230 if ( $xml->isError() ) {
6231 return array(
6232 'error_code' => $xml->getErrorCode(),
6233 'error_msg' => $xml->getErrorMessage(),
6234 );
6235 }
6236 $cloud_site_options = $xml->getResponse();
6237
6238 return $cloud_site_options;
6239 }
6240
6241 /**
6242 * Checks if the site is currently in an identity crisis.
6243 *
6244 * @return array|bool Array of options that are in a crisis, or false if everything is OK.
6245 */
6246 public static function check_identity_crisis() {
6247 if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() || ! Identity_Crisis::validate_sync_error_idc_option() ) {
6248 return false;
6249 }
6250
6251 return Jetpack_Options::get_option( 'sync_error_idc' );
6252 }
6253
6254 /**
6255 * Checks whether the home and siteurl specifically are allowed.
6256 * Written so that we don't have re-check $key and $value params every time
6257 * we want to check if this site is allowed, for example in footer.php
6258 *
6259 * @since 3.8.0
6260 * @return bool True = already allowed False = not on the allowed list.
6261 */
6262 public static function is_staging_site() {
6263 _deprecated_function( 'Jetpack::is_staging_site', 'jetpack-8.1', '/Automattic/Jetpack/Status->is_staging_site' );
6264 return ( new Status() )->is_staging_site();
6265 }
6266
6267 /**
6268 * Checks whether the sync_error_idc option is valid or not, and if not, will do cleanup.
6269 *
6270 * @since 4.4.0
6271 * @since 5.4.0 Do not call get_sync_error_idc_option() unless site is in IDC
6272 *
6273 * @return bool
6274 */
6275 public static function validate_sync_error_idc_option() {
6276 _deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::validate_sync_error_idc_option' );
6277 return Identity_Crisis::validate_sync_error_idc_option();
6278 }
6279
6280 /**
6281 * Normalizes a url by doing three things:
6282 * - Strips protocol
6283 * - Strips www
6284 * - Adds a trailing slash
6285 *
6286 * @since 4.4.0
6287 * @param string $url
6288 * @return WP_Error|string
6289 */
6290 public static function normalize_url_protocol_agnostic( $url ) {
6291 $parsed_url = wp_parse_url( trailingslashit( esc_url_raw( $url ) ) );
6292 if ( ! $parsed_url || empty( $parsed_url['host'] ) || empty( $parsed_url['path'] ) ) {
6293 return new WP_Error( 'cannot_parse_url', sprintf( esc_html__( 'Cannot parse URL %s', 'jetpack' ), $url ) );
6294 }
6295
6296 // Strip www and protocols
6297 $url = preg_replace( '/^www\./i', '', $parsed_url['host'] . $parsed_url['path'] );
6298 return $url;
6299 }
6300
6301 /**
6302 * Gets the value that is to be saved in the jetpack_sync_error_idc option.
6303 *
6304 * @since 4.4.0
6305 * @since 5.4.0 Add transient since home/siteurl retrieved directly from DB
6306 *
6307 * @param array $response
6308 * @return array Array of the local urls, wpcom urls, and error code
6309 */
6310 public static function get_sync_error_idc_option( $response = array() ) {
6311 _deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::get_sync_error_idc_option' );
6312 return Identity_Crisis::get_sync_error_idc_option( $response );
6313 }
6314
6315 /**
6316 * Returns the value of the jetpack_sync_idc_optin filter, or constant.
6317 * If set to true, the site will be put into staging mode.
6318 *
6319 * @since 4.3.2
6320 * @return bool
6321 */
6322 public static function sync_idc_optin() {
6323 _deprecated_function( __METHOD__, 'jetpack-9.8', '\\Automattic\\Jetpack\\Identity_Crisis::sync_idc_optin' );
6324 return Identity_Crisis::sync_idc_optin();
6325 }
6326
6327 /**
6328 * Maybe Use a .min.css stylesheet, maybe not.
6329 *
6330 * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
6331 */
6332 public static function maybe_min_asset( $url, $path, $plugin ) {
6333 // Short out on things trying to find actual paths.
6334 if ( ! $path || empty( $plugin ) ) {
6335 return $url;
6336 }
6337
6338 $path = ltrim( $path, '/' );
6339
6340 // Strip out the abspath.
6341 $base = dirname( plugin_basename( $plugin ) );
6342
6343 // Short out on non-Jetpack assets.
6344 if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
6345 return $url;
6346 }
6347
6348 // File name parsing.
6349 $file = "{$base}/{$path}";
6350 $full_path = JETPACK__PLUGIN_DIR . substr( $file, 8 );
6351 $file_name = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
6352 $file_name_parts_r = array_reverse( explode( '.', $file_name ) );
6353 $extension = array_shift( $file_name_parts_r );
6354
6355 if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
6356 // Already pointing at the minified version.
6357 if ( 'min' === $file_name_parts_r[0] ) {
6358 return $url;
6359 }
6360
6361 $min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
6362 if ( file_exists( $min_full_path ) ) {
6363 $url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
6364 // If it's a CSS file, stash it so we can set the .min suffix for rtl-ing.
6365 if ( 'css' === $extension ) {
6366 $key = str_replace( JETPACK__PLUGIN_DIR, 'jetpack/', $min_full_path );
6367 self::$min_assets[ $key ] = $path;
6368 }
6369 }
6370 }
6371
6372 return $url;
6373 }
6374
6375 /**
6376 * If the asset is minified, let's flag .min as the suffix.
6377 *
6378 * Attached to `style_loader_src` filter.
6379 *
6380 * @param string $tag The tag that would link to the external asset.
6381 * @param string $handle The registered handle of the script in question.
6382 * @param string $href The url of the asset in question.
6383 */
6384 public static function set_suffix_on_min( $src, $handle ) {
6385 if ( false === strpos( $src, '.min.css' ) ) {
6386 return $src;
6387 }
6388
6389 if ( ! empty( self::$min_assets ) ) {
6390 foreach ( self::$min_assets as $file => $path ) {
6391 if ( false !== strpos( $src, $file ) ) {
6392 wp_style_add_data( $handle, 'suffix', '.min' );
6393 return $src;
6394 }
6395 }
6396 }
6397
6398 return $src;
6399 }
6400
6401 /**
6402 * Maybe inlines a stylesheet.
6403 *
6404 * If you'd like to inline a stylesheet instead of printing a link to it,
6405 * wp_style_add_data( 'handle', 'jetpack-inline', true );
6406 *
6407 * Attached to `style_loader_tag` filter.
6408 *
6409 * @param string $tag The tag that would link to the external asset.
6410 * @param string $handle The registered handle of the script in question.
6411 *
6412 * @return string
6413 */
6414 public static function maybe_inline_style( $tag, $handle ) {
6415 global $wp_styles;
6416 $item = $wp_styles->registered[ $handle ];
6417
6418 if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
6419 return $tag;
6420 }
6421
6422 if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
6423 $href = $matches[1];
6424 // Strip off query string
6425 if ( $pos = strpos( $href, '?' ) ) {
6426 $href = substr( $href, 0, $pos );
6427 }
6428 // Strip off fragment
6429 if ( $pos = strpos( $href, '#' ) ) {
6430 $href = substr( $href, 0, $pos );
6431 }
6432 } else {
6433 return $tag;
6434 }
6435
6436 $plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
6437 if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
6438 return $tag;
6439 }
6440
6441 // If this stylesheet has a RTL version, and the RTL version replaces normal...
6442 if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
6443 // And this isn't the pass that actually deals with the RTL version...
6444 if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
6445 // Short out, as the RTL version will deal with it in a moment.
6446 return $tag;
6447 }
6448 }
6449
6450 $file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
6451 $css = self::absolutize_css_urls( file_get_contents( $file ), $href );
6452 if ( $css ) {
6453 $tag = "<!-- Inline {$item->handle} -->\r\n";
6454 if ( empty( $item->extra['after'] ) ) {
6455 wp_add_inline_style( $handle, $css );
6456 } else {
6457 array_unshift( $item->extra['after'], $css );
6458 wp_style_add_data( $handle, 'after', $item->extra['after'] );
6459 }
6460 }
6461
6462 return $tag;
6463 }
6464
6465 /**
6466 * Loads a view file from the views
6467 *
6468 * Data passed in with the $data parameter will be available in the
6469 * template file as $data['value']
6470 *
6471 * @param string $template - Template file to load
6472 * @param array $data - Any data to pass along to the template
6473 * @return boolean - If template file was found
6474 **/
6475 public function load_view( $template, $data = array() ) {
6476 $views_dir = JETPACK__PLUGIN_DIR . 'views/';
6477
6478 if ( file_exists( $views_dir . $template ) ) {
6479 require_once $views_dir . $template;
6480 return true;
6481 }
6482
6483 error_log( "Jetpack: Unable to find view file $views_dir$template" );
6484 return false;
6485 }
6486
6487 /**
6488 * Throws warnings for deprecated hooks to be removed from Jetpack that cannot remain in the original place in the code.
6489 */
6490 public function deprecated_hooks() {
6491 $filter_deprecated_list = array(
6492 'jetpack_bail_on_shortcode' => array(
6493 'replacement' => 'jetpack_shortcodes_to_include',
6494 'version' => 'jetpack-3.1.0',
6495 ),
6496 'wpl_sharing_2014_1' => array(
6497 'replacement' => null,
6498 'version' => 'jetpack-3.6.0',
6499 ),
6500 'jetpack-tools-to-include' => array(
6501 'replacement' => 'jetpack_tools_to_include',
6502 'version' => 'jetpack-3.9.0',
6503 ),
6504 'jetpack_identity_crisis_options_to_check' => array(
6505 'replacement' => null,
6506 'version' => 'jetpack-4.0.0',
6507 ),
6508 'update_option_jetpack_single_user_site' => array(
6509 'replacement' => null,
6510 'version' => 'jetpack-4.3.0',
6511 ),
6512 'audio_player_default_colors' => array(
6513 'replacement' => null,
6514 'version' => 'jetpack-4.3.0',
6515 ),
6516 'add_option_jetpack_featured_images_enabled' => array(
6517 'replacement' => null,
6518 'version' => 'jetpack-4.3.0',
6519 ),
6520 'add_option_jetpack_update_details' => array(
6521 'replacement' => null,
6522 'version' => 'jetpack-4.3.0',
6523 ),
6524 'add_option_jetpack_updates' => array(
6525 'replacement' => null,
6526 'version' => 'jetpack-4.3.0',
6527 ),
6528 'add_option_jetpack_network_name' => array(
6529 'replacement' => null,
6530 'version' => 'jetpack-4.3.0',
6531 ),
6532 'add_option_jetpack_network_allow_new_registrations' => array(
6533 'replacement' => null,
6534 'version' => 'jetpack-4.3.0',
6535 ),
6536 'add_option_jetpack_network_add_new_users' => array(
6537 'replacement' => null,
6538 'version' => 'jetpack-4.3.0',
6539 ),
6540 'add_option_jetpack_network_site_upload_space' => array(
6541 'replacement' => null,
6542 'version' => 'jetpack-4.3.0',
6543 ),
6544 'add_option_jetpack_network_upload_file_types' => array(
6545 'replacement' => null,
6546 'version' => 'jetpack-4.3.0',
6547 ),
6548 'add_option_jetpack_network_enable_administration_menus' => array(
6549 'replacement' => null,
6550 'version' => 'jetpack-4.3.0',
6551 ),
6552 'add_option_jetpack_is_multi_site' => array(
6553 'replacement' => null,
6554 'version' => 'jetpack-4.3.0',
6555 ),
6556 'add_option_jetpack_is_main_network' => array(
6557 'replacement' => null,
6558 'version' => 'jetpack-4.3.0',
6559 ),
6560 'add_option_jetpack_main_network_site' => array(
6561 'replacement' => null,
6562 'version' => 'jetpack-4.3.0',
6563 ),
6564 'jetpack_sync_all_registered_options' => array(
6565 'replacement' => null,
6566 'version' => 'jetpack-4.3.0',
6567 ),
6568 'jetpack_has_identity_crisis' => array(
6569 'replacement' => 'jetpack_sync_error_idc_validation',
6570 'version' => 'jetpack-4.4.0',
6571 ),
6572 'jetpack_is_post_mailable' => array(
6573 'replacement' => null,
6574 'version' => 'jetpack-4.4.0',
6575 ),
6576 'jetpack_seo_site_host' => array(
6577 'replacement' => null,
6578 'version' => 'jetpack-5.1.0',
6579 ),
6580 'jetpack_installed_plugin' => array(
6581 'replacement' => 'jetpack_plugin_installed',
6582 'version' => 'jetpack-6.0.0',
6583 ),
6584 'jetpack_holiday_snow_option_name' => array(
6585 'replacement' => null,
6586 'version' => 'jetpack-6.0.0',
6587 ),
6588 'jetpack_holiday_chance_of_snow' => array(
6589 'replacement' => null,
6590 'version' => 'jetpack-6.0.0',
6591 ),
6592 'jetpack_holiday_snow_js_url' => array(
6593 'replacement' => null,
6594 'version' => 'jetpack-6.0.0',
6595 ),
6596 'jetpack_is_holiday_snow_season' => array(
6597 'replacement' => null,
6598 'version' => 'jetpack-6.0.0',
6599 ),
6600 'jetpack_holiday_snow_option_updated' => array(
6601 'replacement' => null,
6602 'version' => 'jetpack-6.0.0',
6603 ),
6604 'jetpack_holiday_snowing' => array(
6605 'replacement' => null,
6606 'version' => 'jetpack-6.0.0',
6607 ),
6608 'jetpack_sso_auth_cookie_expirtation' => array(
6609 'replacement' => 'jetpack_sso_auth_cookie_expiration',
6610 'version' => 'jetpack-6.1.0',
6611 ),
6612 'jetpack_cache_plans' => array(
6613 'replacement' => null,
6614 'version' => 'jetpack-6.1.0',
6615 ),
6616
6617 'jetpack_lazy_images_skip_image_with_atttributes' => array(
6618 'replacement' => 'jetpack_lazy_images_skip_image_with_attributes',
6619 'version' => 'jetpack-6.5.0',
6620 ),
6621 'jetpack_enable_site_verification' => array(
6622 'replacement' => null,
6623 'version' => 'jetpack-6.5.0',
6624 ),
6625 'can_display_jetpack_manage_notice' => array(
6626 'replacement' => null,
6627 'version' => 'jetpack-7.3.0',
6628 ),
6629 'atd_http_post_timeout' => array(
6630 'replacement' => null,
6631 'version' => 'jetpack-7.3.0',
6632 ),
6633 'atd_service_domain' => array(
6634 'replacement' => null,
6635 'version' => 'jetpack-7.3.0',
6636 ),
6637 'atd_load_scripts' => array(
6638 'replacement' => null,
6639 'version' => 'jetpack-7.3.0',
6640 ),
6641 'jetpack_widget_authors_exclude' => array(
6642 'replacement' => 'jetpack_widget_authors_params',
6643 'version' => 'jetpack-7.7.0',
6644 ),
6645 // Removed in Jetpack 7.9.0
6646 'jetpack_pwa_manifest' => array(
6647 'replacement' => null,
6648 'version' => 'jetpack-7.9.0',
6649 ),
6650 'jetpack_pwa_background_color' => array(
6651 'replacement' => null,
6652 'version' => 'jetpack-7.9.0',
6653 ),
6654 'jetpack_check_mobile' => array(
6655 'replacement' => null,
6656 'version' => 'jetpack-8.3.0',
6657 ),
6658 'jetpack_mobile_stylesheet' => array(
6659 'replacement' => null,
6660 'version' => 'jetpack-8.3.0',
6661 ),
6662 'jetpack_mobile_template' => array(
6663 'replacement' => null,
6664 'version' => 'jetpack-8.3.0',
6665 ),
6666 'jetpack_mobile_theme_menu' => array(
6667 'replacement' => null,
6668 'version' => 'jetpack-8.3.0',
6669 ),
6670 'minileven_show_featured_images' => array(
6671 'replacement' => null,
6672 'version' => 'jetpack-8.3.0',
6673 ),
6674 'minileven_attachment_size' => array(
6675 'replacement' => null,
6676 'version' => 'jetpack-8.3.0',
6677 ),
6678 'instagram_cache_oembed_api_response_body' => array(
6679 'replacement' => null,
6680 'version' => 'jetpack-9.1.0',
6681 ),
6682 'jetpack_can_make_outbound_https' => array(
6683 'replacement' => null,
6684 'version' => 'jetpack-9.1.0',
6685 ),
6686 );
6687
6688 foreach ( $filter_deprecated_list as $tag => $args ) {
6689 if ( has_filter( $tag ) ) {
6690 apply_filters_deprecated( $tag, array( null ), $args['version'], $args['replacement'] );
6691 }
6692 }
6693
6694 $action_deprecated_list = array(
6695 'jetpack_updated_theme' => array(
6696 'replacement' => 'jetpack_updated_themes',
6697 'version' => 'jetpack-6.2.0',
6698 ),
6699 'atd_http_post_error' => array(
6700 'replacement' => null,
6701 'version' => 'jetpack-7.3.0',
6702 ),
6703 'mobile_reject_mobile' => array(
6704 'replacement' => null,
6705 'version' => 'jetpack-8.3.0',
6706 ),
6707 'mobile_force_mobile' => array(
6708 'replacement' => null,
6709 'version' => 'jetpack-8.3.0',
6710 ),
6711 'mobile_app_promo_download' => array(
6712 'replacement' => null,
6713 'version' => 'jetpack-8.3.0',
6714 ),
6715 'mobile_setup' => array(
6716 'replacement' => null,
6717 'version' => 'jetpack-8.3.0',
6718 ),
6719 'jetpack_mobile_footer_before' => array(
6720 'replacement' => null,
6721 'version' => 'jetpack-8.3.0',
6722 ),
6723 'wp_mobile_theme_footer' => array(
6724 'replacement' => null,
6725 'version' => 'jetpack-8.3.0',
6726 ),
6727 'minileven_credits' => array(
6728 'replacement' => null,
6729 'version' => 'jetpack-8.3.0',
6730 ),
6731 'jetpack_mobile_header_before' => array(
6732 'replacement' => null,
6733 'version' => 'jetpack-8.3.0',
6734 ),
6735 'jetpack_mobile_header_after' => array(
6736 'replacement' => null,
6737 'version' => 'jetpack-8.3.0',
6738 ),
6739 );
6740
6741 foreach ( $action_deprecated_list as $tag => $args ) {
6742 if ( has_action( $tag ) ) {
6743 do_action_deprecated( $tag, array(), $args['version'], $args['replacement'] );
6744 }
6745 }
6746 }
6747
6748 /**
6749 * Converts any url in a stylesheet, to the correct absolute url.
6750 *
6751 * Considerations:
6752 * - Normal, relative URLs `feh.png`
6753 * - Data URLs `data:image/gif;base64,eh129ehiuehjdhsa==`
6754 * - Schema-agnostic URLs `//domain.com/feh.png`
6755 * - Absolute URLs `http://domain.com/feh.png`
6756 * - Domain root relative URLs `/feh.png`
6757 *
6758 * @param $css string: The raw CSS -- should be read in directly from the file.
6759 * @param $css_file_url : The URL that the file can be accessed at, for calculating paths from.
6760 *
6761 * @return mixed|string
6762 */
6763 public static function absolutize_css_urls( $css, $css_file_url ) {
6764 $pattern = '#url\((?P<path>[^)]*)\)#i';
6765 $css_dir = dirname( $css_file_url );
6766 $p = wp_parse_url( $css_dir );
6767 $domain = sprintf(
6768 '%1$s//%2$s%3$s%4$s',
6769 isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
6770 isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
6771 $p['host'],
6772 isset( $p['port'] ) ? ":{$p['port']}" : ''
6773 );
6774
6775 if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
6776 $find = $replace = array();
6777 foreach ( $matches as $match ) {
6778 $url = trim( $match['path'], "'\" \t" );
6779
6780 // If this is a data url, we don't want to mess with it.
6781 if ( 'data:' === substr( $url, 0, 5 ) ) {
6782 continue;
6783 }
6784
6785 // If this is an absolute or protocol-agnostic url,
6786 // we don't want to mess with it.
6787 if ( preg_match( '#^(https?:)?//#i', $url ) ) {
6788 continue;
6789 }
6790
6791 switch ( substr( $url, 0, 1 ) ) {
6792 case '/':
6793 $absolute = $domain . $url;
6794 break;
6795 default:
6796 $absolute = $css_dir . '/' . $url;
6797 }
6798
6799 $find[] = $match[0];
6800 $replace[] = sprintf( 'url("%s")', $absolute );
6801 }
6802 $css = str_replace( $find, $replace, $css );
6803 }
6804
6805 return $css;
6806 }
6807
6808 /**
6809 * This methods removes all of the registered css files on the front end
6810 * from Jetpack in favor of using a single file. In effect "imploding"
6811 * all the files into one file.
6812 *
6813 * Pros:
6814 * - Uses only ONE css asset connection instead of 15
6815 * - Saves a minimum of 56k
6816 * - Reduces server load
6817 * - Reduces time to first painted byte
6818 *
6819 * Cons:
6820 * - Loads css for ALL modules. However all selectors are prefixed so it
6821 * should not cause any issues with themes.
6822 * - Plugins/themes dequeuing styles no longer do anything. See
6823 * jetpack_implode_frontend_css filter for a workaround
6824 *
6825 * For some situations developers may wish to disable css imploding and
6826 * instead operate in legacy mode where each file loads seperately and
6827 * can be edited individually or dequeued. This can be accomplished with
6828 * the following line:
6829 *
6830 * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
6831 *
6832 * @since 3.2
6833 **/
6834 public function implode_frontend_css( $travis_test = false ) {
6835 $do_implode = true;
6836 if ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) {
6837 $do_implode = false;
6838 }
6839
6840 // Do not implode CSS when the page loads via the AMP plugin.
6841 if ( Jetpack_AMP_Support::is_amp_request() ) {
6842 $do_implode = false;
6843 }
6844
6845 /**
6846 * Allow CSS to be concatenated into a single jetpack.css file.
6847 *
6848 * @since 3.2.0
6849 *
6850 * @param bool $do_implode Should CSS be concatenated? Default to true.
6851 */
6852 $do_implode = apply_filters( 'jetpack_implode_frontend_css', $do_implode );
6853
6854 // Do not use the imploded file when default behavior was altered through the filter
6855 if ( ! $do_implode ) {
6856 return;
6857 }
6858
6859 // We do not want to use the imploded file in dev mode, or if not connected
6860 if ( ( new Status() )->is_offline_mode() || ! self::is_connection_ready() ) {
6861 if ( ! $travis_test ) {
6862 return;
6863 }
6864 }
6865
6866 // Do not use the imploded file if sharing css was dequeued via the sharing settings screen
6867 if ( get_option( 'sharedaddy_disable_resources' ) ) {
6868 return;
6869 }
6870
6871 /*
6872 * Now we assume Jetpack is connected and able to serve the single
6873 * file.
6874 *
6875 * In the future there will be a check here to serve the file locally
6876 * or potentially from the Jetpack CDN
6877 *
6878 * For now:
6879 * - Enqueue a single imploded css file
6880 * - Zero out the style_loader_tag for the bundled ones
6881 * - Be happy, drink scotch
6882 */
6883
6884 add_filter( 'style_loader_tag', array( $this, 'concat_remove_style_loader_tag' ), 10, 2 );
6885
6886 $version = self::is_development_version() ? filemtime( JETPACK__PLUGIN_DIR . 'css/jetpack.css' ) : JETPACK__VERSION;
6887
6888 wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ), array(), $version );
6889 wp_style_add_data( 'jetpack_css', 'rtl', 'replace' );
6890 }
6891
6892 function concat_remove_style_loader_tag( $tag, $handle ) {
6893 if ( in_array( $handle, $this->concatenated_style_handles ) ) {
6894 $tag = '';
6895 if ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
6896 $tag = '<!-- `' . esc_html( $handle ) . "` is included in the concatenated jetpack.css -->\r\n";
6897 }
6898 }
6899
6900 return $tag;
6901 }
6902
6903 /**
6904 * @deprecated
6905 * @see Automattic\Jetpack\Assets\add_aync_script
6906 */
6907 public function script_add_async( $tag, $handle, $src ) {
6908 _deprecated_function( __METHOD__, 'jetpack-8.6.0' );
6909 }
6910
6911 /*
6912 * Check the heartbeat data
6913 *
6914 * Organizes the heartbeat data by severity. For example, if the site
6915 * is in an ID crisis, it will be in the $filtered_data['bad'] array.
6916 *
6917 * Data will be added to "caution" array, if it either:
6918 * - Out of date Jetpack version
6919 * - Out of date WP version
6920 * - Out of date PHP version
6921 *
6922 * $return array $filtered_data
6923 */
6924 public static function jetpack_check_heartbeat_data() {
6925 $raw_data = Jetpack_Heartbeat::generate_stats_array();
6926
6927 $good = array();
6928 $caution = array();
6929 $bad = array();
6930
6931 foreach ( $raw_data as $stat => $value ) {
6932
6933 // Check jetpack version
6934 if ( 'version' == $stat ) {
6935 if ( version_compare( $value, JETPACK__VERSION, '<' ) ) {
6936 $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__VERSION;
6937 continue;
6938 }
6939 }
6940
6941 // Check WP version
6942 if ( 'wp-version' == $stat ) {
6943 if ( version_compare( $value, JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
6944 $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_WP_VERSION;
6945 continue;
6946 }
6947 }
6948
6949 // Check PHP version
6950 if ( 'php-version' == $stat ) {
6951 if ( version_compare( PHP_VERSION, JETPACK__MINIMUM_PHP_VERSION, '<' ) ) {
6952 $caution[ $stat ] = $value . ' - min supported is ' . JETPACK__MINIMUM_PHP_VERSION;
6953 continue;
6954 }
6955 }
6956
6957 // Check ID crisis
6958 if ( 'identitycrisis' == $stat ) {
6959 if ( 'yes' == $value ) {
6960 $bad[ $stat ] = $value;
6961 continue;
6962 }
6963 }
6964
6965 // The rest are good :)
6966 $good[ $stat ] = $value;
6967 }
6968
6969 $filtered_data = array(
6970 'good' => $good,
6971 'caution' => $caution,
6972 'bad' => $bad,
6973 );
6974
6975 return $filtered_data;
6976 }
6977
6978 /*
6979 * This method is used to organize all options that can be reset
6980 * without disconnecting Jetpack.
6981 *
6982 * It is used in class.jetpack-cli.php to reset options
6983 *
6984 * @since 5.4.0 Logic moved to Jetpack_Options class. Method left in Jetpack class for backwards compat.
6985 *
6986 * @return array of options to delete.
6987 */
6988 public static function get_jetpack_options_for_reset() {
6989 return Jetpack_Options::get_options_for_reset();
6990 }
6991
6992 /*
6993 * Strip http:// or https:// from a url, replaces forward slash with ::,
6994 * so we can bring them directly to their site in calypso.
6995 *
6996 * @deprecated 9.2.0 Use Automattic\Jetpack\Status::get_site_suffix
6997 *
6998 * @param string | url
6999 * @return string | url without the guff
7000 */
7001 public static function build_raw_urls( $url ) {
7002 _deprecated_function( __METHOD__, 'jetpack-9.2.0', 'Automattic\Jetpack\Status::get_site_suffix' );
7003
7004 return ( new Status() )->get_site_suffix( $url );
7005 }
7006
7007 /**
7008 * Stores and prints out domains to prefetch for page speed optimization.
7009 *
7010 * @deprecated 8.8.0 Use Jetpack::add_resource_hints.
7011 *
7012 * @param string|array $urls URLs to hint.
7013 */
7014 public static function dns_prefetch( $urls = null ) {
7015 _deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Automattic\Jetpack\Assets::add_resource_hint' );
7016 if ( $urls ) {
7017 Assets::add_resource_hint( $urls );
7018 }
7019 }
7020
7021 public function wp_dashboard_setup() {
7022 if ( self::is_connection_ready() ) {
7023 add_action( 'jetpack_dashboard_widget', array( __CLASS__, 'dashboard_widget_footer' ), 999 );
7024 }
7025
7026 if ( has_action( 'jetpack_dashboard_widget' ) ) {
7027 $jetpack_logo = new Jetpack_Logo();
7028 $widget_title = sprintf(
7029 /* translators: Placeholder is a Jetpack logo. */
7030 __( 'Stats by %s', 'jetpack' ),
7031 $jetpack_logo->get_jp_emblem( true )
7032 );
7033
7034 // Wrap title in span so Logo can be properly styled.
7035 $widget_title = sprintf(
7036 '<span>%s</span>',
7037 $widget_title
7038 );
7039
7040 wp_add_dashboard_widget(
7041 'jetpack_summary_widget',
7042 $widget_title,
7043 array( __CLASS__, 'dashboard_widget' )
7044 );
7045 wp_enqueue_style( 'jetpack-dashboard-widget', plugins_url( 'css/dashboard-widget.css', JETPACK__PLUGIN_FILE ), array(), JETPACK__VERSION );
7046 wp_style_add_data( 'jetpack-dashboard-widget', 'rtl', 'replace' );
7047
7048 // If we're inactive and not in offline mode, sort our box to the top.
7049 if ( ! self::is_connection_ready() && ! ( new Status() )->is_offline_mode() ) {
7050 global $wp_meta_boxes;
7051
7052 $dashboard = $wp_meta_boxes['dashboard']['normal']['core'];
7053 $ours = array( 'jetpack_summary_widget' => $dashboard['jetpack_summary_widget'] );
7054
7055 $wp_meta_boxes['dashboard']['normal']['core'] = array_merge( $ours, $dashboard );
7056 }
7057 }
7058 }
7059
7060 /**
7061 * @param mixed $result Value for the user's option
7062 * @return mixed
7063 */
7064 function get_user_option_meta_box_order_dashboard( $sorted ) {
7065 if ( ! is_array( $sorted ) ) {
7066 return $sorted;
7067 }
7068
7069 foreach ( $sorted as $box_context => $ids ) {
7070 if ( false === strpos( $ids, 'dashboard_stats' ) ) {
7071 // If the old id isn't anywhere in the ids, don't bother exploding and fail out.
7072 continue;
7073 }
7074
7075 $ids_array = explode( ',', $ids );
7076 $key = array_search( 'dashboard_stats', $ids_array );
7077
7078 if ( false !== $key ) {
7079 // If we've found that exact value in the option (and not `google_dashboard_stats` for example)
7080 $ids_array[ $key ] = 'jetpack_summary_widget';
7081 $sorted[ $box_context ] = implode( ',', $ids_array );
7082 // We've found it, stop searching, and just return.
7083 break;
7084 }
7085 }
7086
7087 return $sorted;
7088 }
7089
7090 public static function dashboard_widget() {
7091 /**
7092 * Fires when the dashboard is loaded.
7093 *
7094 * @since 3.4.0
7095 */
7096 do_action( 'jetpack_dashboard_widget' );
7097 }
7098
7099 public static function dashboard_widget_footer() {
7100 ?>
7101 <footer>
7102
7103 <div class="protect">
7104 <h3><?php esc_html_e( 'Brute force attack protection', 'jetpack' ); ?></h3>
7105 <?php if ( self::is_module_active( 'protect' ) ) : ?>
7106 <p class="blocked-count">
7107 <?php echo number_format_i18n( get_site_option( 'jetpack_protect_blocked_attempts', 0 ) ); ?>
7108 </p>
7109 <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>
7110 <?php elseif ( current_user_can( 'jetpack_activate_modules' ) && ! ( new Status() )->is_offline_mode() ) : ?>
7111 <a href="
7112 <?php
7113 echo esc_url(
7114 wp_nonce_url(
7115 self::admin_url(
7116 array(
7117 'action' => 'activate',
7118 'module' => 'protect',
7119 )
7120 ),
7121 'jetpack_activate-protect'
7122 )
7123 );
7124 ?>
7125 " class="button button-jetpack" title="<?php esc_attr_e( 'Protect helps to keep you secure from brute-force login attacks.', 'jetpack' ); ?>">
7126 <?php esc_html_e( 'Activate brute force attack protection', 'jetpack' ); ?>
7127 </a>
7128 <?php else : ?>
7129 <?php esc_html_e( 'Brute force attack protection is inactive.', 'jetpack' ); ?>
7130 <?php endif; ?>
7131 </div>
7132
7133 <div class="akismet">
7134 <h3><?php esc_html_e( 'Anti-spam', 'jetpack' ); ?></h3>
7135 <?php if ( is_plugin_active( 'akismet/akismet.php' ) ) : ?>
7136 <p class="blocked-count">
7137 <?php echo number_format_i18n( get_option( 'akismet_spam_count', 0 ) ); ?>
7138 </p>
7139 <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>
7140 <?php elseif ( current_user_can( 'activate_plugins' ) && ! is_wp_error( validate_plugin( 'akismet/akismet.php' ) ) ) : ?>
7141 <a href="
7142 <?php
7143 echo esc_url(
7144 wp_nonce_url(
7145 add_query_arg(
7146 array(
7147 'action' => 'activate',
7148 'plugin' => 'akismet/akismet.php',
7149 ),
7150 admin_url( 'plugins.php' )
7151 ),
7152 'activate-plugin_akismet/akismet.php'
7153 )
7154 );
7155 ?>
7156 " class="button button-jetpack">
7157 <?php esc_html_e( 'Activate Anti-spam', 'jetpack' ); ?>
7158 </a>
7159 <?php else : ?>
7160 <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>
7161 <?php endif; ?>
7162 </div>
7163
7164 </footer>
7165 <?php
7166 }
7167
7168 /*
7169 * Adds a "blank" column in the user admin table to display indication of user connection.
7170 */
7171 function jetpack_icon_user_connected( $columns ) {
7172 $columns['user_jetpack'] = '';
7173 return $columns;
7174 }
7175
7176 /*
7177 * Show Jetpack icon if the user is linked.
7178 */
7179 function jetpack_show_user_connected_icon( $val, $col, $user_id ) {
7180 if ( 'user_jetpack' === $col && self::connection()->is_user_connected( $user_id ) ) {
7181 $jetpack_logo = new Jetpack_Logo();
7182 $emblem_html = sprintf(
7183 '<a title="%1$s" class="jp-emblem-user-admin">%2$s</a>',
7184 esc_attr__( 'This user is linked and ready to fly with Jetpack.', 'jetpack' ),
7185 $jetpack_logo->get_jp_emblem()
7186 );
7187 return $emblem_html;
7188 }
7189
7190 return $val;
7191 }
7192
7193 /*
7194 * Style the Jetpack user column
7195 */
7196 function jetpack_user_col_style() {
7197 global $current_screen;
7198 if ( ! empty( $current_screen->base ) && 'users' == $current_screen->base ) {
7199 ?>
7200 <style>
7201 .fixed .column-user_jetpack {
7202 width: 21px;
7203 }
7204 .jp-emblem-user-admin svg {
7205 width: 20px;
7206 height: 20px;
7207 }
7208 .jp-emblem-user-admin path {
7209 fill: #00BE28;
7210 }
7211 </style>
7212 <?php
7213 }
7214 }
7215
7216 /**
7217 * Checks if Akismet is active and working.
7218 *
7219 * We dropped support for Akismet 3.0 with Jetpack 6.1.1 while introducing a check for an Akismet valid key
7220 * that implied usage of methods present since more recent version.
7221 * See https://github.com/Automattic/jetpack/pull/9585
7222 *
7223 * @since 5.1.0
7224 *
7225 * @return bool True = Akismet available. False = Aksimet not available.
7226 */
7227 public static function is_akismet_active() {
7228 static $status = null;
7229
7230 if ( ! is_null( $status ) ) {
7231 return $status;
7232 }
7233
7234 // Check if a modern version of Akismet is active.
7235 if ( ! method_exists( 'Akismet', 'http_post' ) ) {
7236 $status = false;
7237 return $status;
7238 }
7239
7240 // Make sure there is a key known to Akismet at all before verifying key.
7241 $akismet_key = Akismet::get_api_key();
7242 if ( ! $akismet_key ) {
7243 $status = false;
7244 return $status;
7245 }
7246
7247 // Possible values: valid, invalid, failure via Akismet. false if no status is cached.
7248 $akismet_key_state = get_transient( 'jetpack_akismet_key_is_valid' );
7249
7250 // 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.
7251 $recheck = ( is_admin() || ( defined( 'REST_REQUEST' ) && REST_REQUEST ) ) && 'valid' !== $akismet_key_state;
7252 // We cache the result of the Akismet key verification for ten minutes.
7253 if ( ! $akismet_key_state || $recheck ) {
7254 $akismet_key_state = Akismet::verify_key( $akismet_key );
7255 set_transient( 'jetpack_akismet_key_is_valid', $akismet_key_state, 10 * MINUTE_IN_SECONDS );
7256 }
7257
7258 $status = 'valid' === $akismet_key_state;
7259
7260 return $status;
7261 }
7262
7263 /**
7264 * @deprecated
7265 *
7266 * @see Automattic\Jetpack\Sync\Modules\Users::is_function_in_backtrace
7267 */
7268 public static function is_function_in_backtrace() {
7269 _deprecated_function( __METHOD__, 'jetpack-7.6.0' );
7270 }
7271
7272 /**
7273 * Given a minified path, and a non-minified path, will return
7274 * a minified or non-minified file URL based on whether SCRIPT_DEBUG is set and truthy.
7275 *
7276 * Both `$min_base` and `$non_min_base` are expected to be relative to the
7277 * root Jetpack directory.
7278 *
7279 * @since 5.6.0
7280 *
7281 * @param string $min_path
7282 * @param string $non_min_path
7283 * @return string The URL to the file
7284 */
7285 public static function get_file_url_for_environment( $min_path, $non_min_path ) {
7286 return Assets::get_file_url_for_environment( $min_path, $non_min_path );
7287 }
7288
7289 /**
7290 * Checks for whether Jetpack Backup is enabled.
7291 * Will return true if the state of Backup is anything except "unavailable".
7292 *
7293 * @return bool|int|mixed
7294 */
7295 public static function is_rewind_enabled() {
7296 // Rewind is a paid feature, therefore requires a user-level connection.
7297 if ( ! static::connection()->has_connected_owner() ) {
7298 return false;
7299 }
7300
7301 $rewind_enabled = get_transient( 'jetpack_rewind_enabled' );
7302 if ( false === $rewind_enabled ) {
7303 jetpack_require_lib( 'class.core-rest-api-endpoints' );
7304 $rewind_data = (array) Jetpack_Core_Json_Api_Endpoints::rewind_data();
7305 $rewind_enabled = ( ! is_wp_error( $rewind_data )
7306 && ! empty( $rewind_data['state'] )
7307 && 'active' === $rewind_data['state'] )
7308 ? 1
7309 : 0;
7310
7311 set_transient( 'jetpack_rewind_enabled', $rewind_enabled, 10 * MINUTE_IN_SECONDS );
7312 }
7313 return $rewind_enabled;
7314 }
7315
7316 /**
7317 * Return Calypso environment value; used for developing Jetpack and pairing
7318 * it with different Calypso enrionments, such as localhost.
7319 *
7320 * @since 7.4.0
7321 *
7322 * @return string Calypso environment
7323 */
7324 public static function get_calypso_env() {
7325 if ( isset( $_GET['calypso_env'] ) ) {
7326 return sanitize_key( $_GET['calypso_env'] );
7327 }
7328
7329 if ( getenv( 'CALYPSO_ENV' ) ) {
7330 return sanitize_key( getenv( 'CALYPSO_ENV' ) );
7331 }
7332
7333 if ( defined( 'CALYPSO_ENV' ) && CALYPSO_ENV ) {
7334 return sanitize_key( CALYPSO_ENV );
7335 }
7336
7337 return '';
7338 }
7339
7340 /**
7341 * Returns the hostname with protocol for Calypso.
7342 * Used for developing Jetpack with Calypso.
7343 *
7344 * @since 8.4.0
7345 *
7346 * @return string Calypso host.
7347 */
7348 public static function get_calypso_host() {
7349 $calypso_env = self::get_calypso_env();
7350 switch ( $calypso_env ) {
7351 case 'development':
7352 return 'http://calypso.localhost:3000/';
7353 case 'wpcalypso':
7354 return 'https://wpcalypso.wordpress.com/';
7355 case 'horizon':
7356 return 'https://horizon.wordpress.com/';
7357 default:
7358 return 'https://wordpress.com/';
7359 }
7360 }
7361
7362 /**
7363 * Handles activating default modules as well general cleanup for the new connection.
7364 *
7365 * @param boolean $activate_sso Whether to activate the SSO module when activating default modules.
7366 * @param boolean $redirect_on_activation_error Whether to redirect on activation error.
7367 * @param boolean $send_state_messages Whether to send state messages.
7368 * @return void
7369 */
7370 public static function handle_post_authorization_actions(
7371 $activate_sso = false,
7372 $redirect_on_activation_error = false,
7373 $send_state_messages = true
7374 ) {
7375 $other_modules = $activate_sso
7376 ? array( 'sso' )
7377 : array();
7378
7379 if ( Jetpack_Options::get_option( 'active_modules_initialized' ) ) {
7380 $active_modules = Jetpack_Options::get_option( 'active_modules' );
7381 self::delete_active_modules();
7382
7383 self::activate_default_modules( 999, 1, array_merge( $active_modules, $other_modules ), $redirect_on_activation_error, $send_state_messages );
7384 } else {
7385 // Default modules that don't require a user were already activated on site_register.
7386 // 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.
7387 self::activate_default_modules( false, false, $other_modules, $redirect_on_activation_error, $send_state_messages, null, true );
7388 Jetpack_Options::update_option( 'active_modules_initialized', true );
7389 }
7390
7391 // Since this is a fresh connection, be sure to clear out IDC options
7392 Identity_Crisis::clear_all_idc_options();
7393
7394 if ( $send_state_messages ) {
7395 self::state( 'message', 'authorized' );
7396 }
7397 }
7398
7399 /**
7400 * Returns a boolean for whether backups UI should be displayed or not.
7401 *
7402 * @return bool Should backups UI be displayed?
7403 */
7404 public static function show_backups_ui() {
7405 /**
7406 * Whether UI for backups should be displayed.
7407 *
7408 * @since 6.5.0
7409 *
7410 * @param bool $show_backups Should UI for backups be displayed? True by default.
7411 */
7412 return self::is_plugin_active( 'vaultpress/vaultpress.php' ) || apply_filters( 'jetpack_show_backups', true );
7413 }
7414
7415 /*
7416 * Deprecated manage functions
7417 */
7418 function prepare_manage_jetpack_notice() {
7419 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7420 }
7421 function manage_activate_screen() {
7422 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7423 }
7424 function admin_jetpack_manage_notice() {
7425 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7426 }
7427 function opt_out_jetpack_manage_url() {
7428 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7429 }
7430 function opt_in_jetpack_manage_url() {
7431 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7432 }
7433 function opt_in_jetpack_manage_notice() {
7434 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7435 }
7436 function can_display_jetpack_manage_notice() {
7437 _deprecated_function( __METHOD__, 'jetpack-7.3' );
7438 }
7439
7440 /**
7441 * Clean leftoveruser meta.
7442 *
7443 * Delete Jetpack-related user meta when it is no longer needed.
7444 *
7445 * @since 7.3.0
7446 *
7447 * @param int $user_id User ID being updated.
7448 */
7449 public static function user_meta_cleanup( $user_id ) {
7450 $meta_keys = array(
7451 // AtD removed from Jetpack 7.3
7452 'AtD_options',
7453 'AtD_check_when',
7454 'AtD_guess_lang',
7455 'AtD_ignored_phrases',
7456 );
7457
7458 foreach ( $meta_keys as $meta_key ) {
7459 if ( get_user_meta( $user_id, $meta_key ) ) {
7460 delete_user_meta( $user_id, $meta_key );
7461 }
7462 }
7463 }
7464
7465 /**
7466 * Checks if a Jetpack site is both active and not in offline mode.
7467 *
7468 * This is a DRY function to avoid repeating `Jetpack::is_active && ! Automattic\Jetpack\Status->is_offline_mode`.
7469 *
7470 * @deprecated 8.8.0
7471 *
7472 * @return bool True if Jetpack is active and not in offline mode.
7473 */
7474 public static function is_active_and_not_development_mode() {
7475 _deprecated_function( __FUNCTION__, 'jetpack-8.8.0', 'Jetpack::is_active_and_not_offline_mode' );
7476 if ( ! self::is_active() || ( new Status() )->is_offline_mode() ) {
7477 return false;
7478 }
7479 return true;
7480 }
7481
7482 /**
7483 * Checks if a Jetpack site is both active and not in offline mode.
7484 *
7485 * This is a DRY function to avoid repeating `Jetpack::is_connection_ready && ! Automattic\Jetpack\Status->is_offline_mode`.
7486 *
7487 * @since 8.8.0
7488 *
7489 * @return bool True if Jetpack is active and not in offline mode.
7490 */
7491 public static function is_active_and_not_offline_mode() {
7492 if ( ! self::is_connection_ready() || ( new Status() )->is_offline_mode() ) {
7493 return false;
7494 }
7495 return true;
7496 }
7497
7498 /**
7499 * Returns the list of products that we have available for purchase.
7500 */
7501 public static function get_products_for_purchase() {
7502 $products = array();
7503 if ( ! is_multisite() ) {
7504 $products[] = array(
7505 'key' => 'backup',
7506 'title' => __( 'Jetpack Backup', 'jetpack' ),
7507 'short_description' => __( 'Always-on backups ensure you never lose your site.', 'jetpack' ),
7508 'learn_more' => __( 'Which backup option is best for me?', 'jetpack' ),
7509 'description' => __( 'Always-on backups ensure you never lose your site. Your changes are saved as you edit and you have unlimited backup archives.', 'jetpack' ),
7510 'options_label' => __( 'Select a backup option:', 'jetpack' ),
7511 'options' => array(
7512 array(
7513 'type' => 'daily',
7514 'slug' => 'jetpack-backup-daily',
7515 'key' => 'jetpack_backup_daily',
7516 'name' => __( 'Daily Backups', 'jetpack' ),
7517 'description' => __( 'Your data is being securely backed up daily.', 'jetpack' ),
7518 ),
7519 array(
7520 'type' => 'realtime',
7521 'slug' => 'jetpack-backup-realtime',
7522 'key' => 'jetpack_backup_realtime',
7523 'name' => __( 'Real-Time Backups', 'jetpack' ),
7524 'description' => __( 'Your data is being securely backed up as you edit.', 'jetpack' ),
7525 ),
7526 ),
7527 'default_option' => 'realtime',
7528 'show_promotion' => true,
7529 'discount_percent' => 70,
7530 'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'daily-backup-plan', 'realtime-backup-plan' ),
7531 );
7532
7533 $products[] = array(
7534 'key' => 'scan',
7535 'title' => __( 'Jetpack Scan', 'jetpack' ),
7536 'short_description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7537 'learn_more' => __( 'Learn More', 'jetpack' ),
7538 'description' => __( 'Automatic scanning and one-click fixes keep your site one step ahead of security threats.', 'jetpack' ),
7539 'show_promotion' => true,
7540 'discount_percent' => 30,
7541 'options' => array(
7542 array(
7543 'type' => 'scan',
7544 'slug' => 'jetpack-scan',
7545 'key' => 'jetpack_scan',
7546 'name' => __( 'Daily Scan', 'jetpack' ),
7547 ),
7548 ),
7549 'default_option' => 'scan',
7550 'included_in_plans' => array( 'premium-plan', 'business-plan', 'scan-plan' ),
7551 );
7552 }
7553
7554 $products[] = array(
7555 'key' => 'search',
7556 'title' => __( 'Jetpack Search', 'jetpack' ),
7557 'short_description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7558 'learn_more' => __( 'Learn More', 'jetpack' ),
7559 'description' => __( 'Incredibly powerful and customizable, Jetpack Search helps your visitors instantly find the right content – right when they need it.', 'jetpack' ),
7560 'label_popup' => __( 'Records are all posts, pages, custom post types, and other types of content indexed by Jetpack Search.', 'jetpack' ),
7561 'options' => array(
7562 array(
7563 'type' => 'search',
7564 'slug' => 'jetpack-search',
7565 'key' => 'jetpack_search',
7566 'name' => __( 'Search', 'jetpack' ),
7567 ),
7568 ),
7569 'tears' => array(),
7570 'default_option' => 'search',
7571 'show_promotion' => false,
7572 'included_in_plans' => array( 'search-plan' ),
7573 );
7574
7575 $products[] = array(
7576 'key' => 'anti-spam',
7577 'title' => __( 'Jetpack Anti-Spam', 'jetpack' ),
7578 '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' ),
7579 'learn_more' => __( 'Learn More', 'jetpack' ),
7580 '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' ),
7581 'options' => array(
7582 array(
7583 'type' => 'anti-spam',
7584 'slug' => 'jetpack-anti-spam',
7585 'key' => 'jetpack_anti_spam',
7586 'name' => __( 'Anti-Spam', 'jetpack' ),
7587 ),
7588 ),
7589 'default_option' => 'anti-spam',
7590 'included_in_plans' => array( 'personal-plan', 'premium-plan', 'business-plan', 'anti-spam-plan' ),
7591 );
7592
7593 return $products;
7594 }
7595
7596 /**
7597 * Determine if the current user is allowed to make Jetpack purchases without
7598 * a WordPress.com account
7599 *
7600 * @return boolean True if the user can make purchases, false if not
7601 */
7602 public static function current_user_can_purchase() {
7603
7604 // The site must be site-connected to Jetpack (no users connected).
7605 if ( ! self::connection()->is_site_connection() ) {
7606 return false;
7607 }
7608
7609 // Make sure only administrators can make purchases.
7610 if ( ! current_user_can( 'manage_options' ) ) {
7611 return false;
7612 }
7613
7614 return true;
7615 }
7616
7617 }
7618