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

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