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

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