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

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