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