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

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

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