Permalink
Find file
6379 lines (5518 sloc) 212 KB
<?php
/*
Options:
jetpack_options (array)
An array of options.
@see Jetpack_Options::get_option_names()
jetpack_register (string)
Temporary verification secrets.
jetpack_activated (int)
1: the plugin was activated normally
2: the plugin was activated on this site because of a network-wide activation
3: the plugin was auto-installed
4: the plugin was manually disconnected (but is still installed)
jetpack_active_modules (array)
Array of active module slugs.
jetpack_do_activate (bool)
Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
*/
class Jetpack {
public $xmlrpc_server = null;
private $xmlrpc_verification = null;
private $rest_authentication_status = null;
public $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
/**
* @var array The handles of styles that are concatenated into jetpack.css
*/
public $concatenated_style_handles = array(
'jetpack-carousel',
'grunion.css',
'the-neverending-homepage',
'jetpack_likes',
'jetpack_related-posts',
'sharedaddy',
'jetpack-slideshow',
'presentations',
'jetpack-subscriptions',
'jetpack-responsive-videos-style',
'jetpack-social-menu',
'tiled-gallery',
'jetpack_display_posts_widget',
'gravatar-profile-widget',
'goodreads-widget',
'jetpack_social_media_icons_widget',
'jetpack-top-posts-widget',
'jetpack_image_widget',
'jetpack-my-community-widget',
'wordads',
);
public $plugins_to_deactivate = array(
'stats' => array( 'stats/stats.php', 'WordPress.com Stats' ),
'shortlinks' => array( 'stats/stats.php', 'WordPress.com Stats' ),
'sharedaddy' => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
'twitter-widget' => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
'after-the-deadline' => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
'contact-form' => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
'contact-form' => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
'custom-css' => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
'random-redirect' => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
'videopress' => array( 'video/video.php', 'VideoPress' ),
'widget-visibility' => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
'widget-visibility' => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
'sharedaddy' => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
'omnisearch' => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
'latex' => array( 'wp-latex/wp-latex.php', 'WP LaTeX' )
);
static $capability_translations = array(
'administrator' => 'manage_options',
'editor' => 'edit_others_posts',
'author' => 'publish_posts',
'contributor' => 'edit_posts',
'subscriber' => 'read',
);
/**
* Map of modules that have conflicts with plugins and should not be auto-activated
* if the plugins are active. Used by filter_default_modules
*
* Plugin Authors: If you'd like to prevent a single module from auto-activating,
* change `module-slug` and add this to your plugin:
*
* add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
* function my_jetpack_get_default_modules( $modules ) {
* return array_diff( $modules, array( 'module-slug' ) );
* }
*
* @var array
*/
private $conflicting_plugins = array(
'comments' => array(
'Intense Debate' => 'intensedebate/intensedebate.php',
'Disqus' => 'disqus-comment-system/disqus.php',
'Livefyre' => 'livefyre-comments/livefyre.php',
'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
'Google+ Comments' => 'google-plus-comments/google-plus-comments.php',
'WP-SpamShield Anti-Spam' => 'wp-spamshield/wp-spamshield.php',
),
'contact-form' => array(
'Contact Form 7' => 'contact-form-7/wp-contact-form-7.php',
'Gravity Forms' => 'gravityforms/gravityforms.php',
'Contact Form Plugin' => 'contact-form-plugin/contact_form.php',
'Easy Contact Forms' => 'easy-contact-forms/easy-contact-forms.php',
'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
),
'minileven' => array(
'WPtouch' => 'wptouch/wptouch.php',
),
'latex' => array(
'LaTeX for WordPress' => 'latex/latex.php',
'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
'Easy WP LaTeX' => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
'MathJax-LaTeX' => 'mathjax-latex/mathjax-latex.php',
'Enable Latex' => 'enable-latex/enable-latex.php',
'WP QuickLaTeX' => 'wp-quicklatex/wp-quicklatex.php',
),
'protect' => array(
'Limit Login Attempts' => 'limit-login-attempts/limit-login-attempts.php',
'Captcha' => 'captcha/captcha.php',
'Brute Force Login Protection' => 'brute-force-login-protection/brute-force-login-protection.php',
'Login Security Solution' => 'login-security-solution/login-security-solution.php',
'WPSecureOps Brute Force Protect' => 'wpsecureops-bruteforce-protect/wpsecureops-bruteforce-protect.php',
'BulletProof Security' => 'bulletproof-security/bulletproof-security.php',
'SiteGuard WP Plugin' => 'siteguard/siteguard.php',
'Security-protection' => 'security-protection/security-protection.php',
'Login Security' => 'login-security/login-security.php',
'Botnet Attack Blocker' => 'botnet-attack-blocker/botnet-attack-blocker.php',
'Wordfence Security' => 'wordfence/wordfence.php',
'All In One WP Security & Firewall' => 'all-in-one-wp-security-and-firewall/wp-security.php',
'iThemes Security' => 'better-wp-security/better-wp-security.php',
),
'random-redirect' => array(
'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
),
'related-posts' => array(
'YARPP' => 'yet-another-related-posts-plugin/yarpp.php',
'WordPress Related Posts' => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
'nrelate Related Content' => 'nrelate-related-content/nrelate-related.php',
'Contextual Related Posts' => 'contextual-related-posts/contextual-related-posts.php',
'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
'outbrain' => 'outbrain/outbrain.php',
'Shareaholic' => 'shareaholic/shareaholic.php',
'Sexybookmarks' => 'sexybookmarks/shareaholic.php',
),
'sharedaddy' => array(
'AddThis' => 'addthis/addthis_social_widget.php',
'Add To Any' => 'add-to-any/add-to-any.php',
'ShareThis' => 'share-this/sharethis.php',
'Shareaholic' => 'shareaholic/shareaholic.php',
),
'seo-tools' => array(
'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
),
'verification-tools' => array(
'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
),
'widget-visibility' => array(
'Widget Logic' => 'widget-logic/widget_logic.php',
'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
),
'sitemaps' => array(
'Google XML Sitemaps' => 'google-sitemap-generator/sitemap.php',
'Better WordPress Google XML Sitemaps' => 'bwp-google-xml-sitemaps/bwp-simple-gxs.php',
'Google XML Sitemaps for qTranslate' => 'google-xml-sitemaps-v3-for-qtranslate/sitemap.php',
'XML Sitemap & Google News feeds' => 'xml-sitemap-feed/xml-sitemap.php',
'Google Sitemap by BestWebSoft' => 'google-sitemap-plugin/google-sitemap-plugin.php',
'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
'All in One SEO Pack Pro' => 'all-in-one-seo-pack-pro/all_in_one_seo_pack.php',
'Sitemap' => 'sitemap/sitemap.php',
'Simple Wp Sitemap' => 'simple-wp-sitemap/simple-wp-sitemap.php',
'Simple Sitemap' => 'simple-sitemap/simple-sitemap.php',
'XML Sitemaps' => 'xml-sitemaps/xml-sitemaps.php',
'MSM Sitemaps' => 'msm-sitemap/msm-sitemap.php',
),
);
/**
* Plugins for which we turn off our Facebook OG Tags implementation.
*
* Note: All in One SEO Pack, All in one SEO Pack Pro, WordPress SEO by Yoast, and WordPress SEO Premium by Yoast automatically deactivate
* Jetpack's Open Graph tags via filter when their Social Meta modules are active.
*
* Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
* add_filter( 'jetpack_enable_open_graph', '__return_false' );
*/
private $open_graph_conflicting_plugins = array(
'2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
// 2 Click Social Media Buttons
'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook
'add-meta-tags/add-meta-tags.php', // Add Meta Tags
'autodescription/autodescription.php', // The SEO Framework
'easy-facebook-share-thumbnails/esft.php', // Easy Facebook Share Thumbnail
'heateor-open-graph-meta-tags/heateor-open-graph-meta-tags.php',
// Open Graph Meta Tags by Heateor
'facebook/facebook.php', // Facebook (official plugin)
'facebook-awd/AWD_facebook.php', // Facebook AWD All in one
'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
// Facebook Featured Image & OG Meta Tags
'facebook-meta-tags/facebook-metatags.php', // Facebook Meta Tags
'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
// Facebook Open Graph Meta Tags for WordPress
'facebook-revised-open-graph-meta-tag/index.php', // Facebook Revised Open Graph Meta Tag
'facebook-thumb-fixer/_facebook-thumb-fixer.php', // Facebook Thumb Fixer
'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
// Fedmich's Facebook Open Graph Meta
'header-footer/plugin.php', // Header and Footer
'network-publisher/networkpub.php', // Network Publisher
'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG
'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
// NextScripts SNAP
'og-tags/og-tags.php', // OG Tags
'opengraph/opengraph.php', // Open Graph
'open-graph-protocol-framework/open-graph-protocol-framework.php',
// Open Graph Protocol Framework
'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments
'seo-ultimate/seo-ultimate.php', // SEO Ultimate
'sexybookmarks/sexy-bookmarks.php', // Shareaholic
'shareaholic/sexy-bookmarks.php', // Shareaholic
'sharepress/sharepress.php', // SharePress
'simple-facebook-connect/sfc.php', // Simple Facebook Connect
'social-discussions/social-discussions.php', // Social Discussions
'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit
'socialize/socialize.php', // Socialize
'squirrly-seo/squirrly.php', // SEO by SQUIRRLY™
'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
// Tweet, Like, Google +1 and Share
'wordbooker/wordbooker.php', // Wordbooker
'wpsso/wpsso.php', // WordPress Social Sharing Optimization
'wp-caregiver/wp-caregiver.php', // WP Caregiver
'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
// WP Facebook Like Send & Open Graph Meta
'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol
'wp-ogp/wp-ogp.php', // WP-OGP
'zoltonorg-social-plugin/zosp.php', // Zolton.org Social Plugin
'wp-fb-share-like-button/wp_fb_share-like_widget.php' // WP Facebook Like Button
);
/**
* Plugins for which we turn off our Twitter Cards Tags implementation.
*/
private $twitter_cards_conflicting_plugins = array(
// 'twitter/twitter.php', // The official one handles this on its own.
// // https://github.com/twitter/wordpress/blob/master/src/Twitter/WordPress/Cards/Compatibility.php
'eewee-twitter-card/index.php', // Eewee Twitter Card
'ig-twitter-cards/ig-twitter-cards.php', // IG:Twitter Cards
'jm-twitter-cards/jm-twitter-cards.php', // JM Twitter Cards
'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
// Pure Web Brilliant's Social Graph Twitter Cards Extension
'twitter-cards/twitter-cards.php', // Twitter Cards
'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
'wp-twitter-cards/twitter_cards.php', // WP Twitter Cards
);
/**
* Message to display in admin_notice
* @var string
*/
public $message = '';
/**
* Error to display in admin_notice
* @var string
*/
public $error = '';
/**
* Modules that need more privacy description.
* @var string
*/
public $privacy_checks = '';
/**
* Stats to record once the page loads
*
* @var array
*/
public $stats = array();
/**
* Jetpack_Sync object
*/
public $sync;
/**
* Verified data for JSON authorization request
*/
public $json_api_authorization_request = array();
/**
* Holds the singleton instance of this class
* @since 2.3.3
* @var Jetpack
*/
static $instance = false;
/**
* Singleton
* @static
*/
public static function init() {
if ( ! self::$instance ) {
self::$instance = new Jetpack;
self::$instance->plugin_upgrade();
}
return self::$instance;
}
/**
* Must never be called statically
*/
function plugin_upgrade() {
if ( Jetpack::is_active() ) {
list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
if ( JETPACK__VERSION != $version ) {
// Check which active modules actually exist and remove others from active_modules list
$unfiltered_modules = Jetpack::get_active_modules();
$modules = array_filter( $unfiltered_modules, array( 'Jetpack', 'is_module' ) );
if ( array_diff( $unfiltered_modules, $modules ) ) {
Jetpack::update_active_modules( $modules );
}
add_action( 'init', array( __CLASS__, 'activate_new_modules' ) );
// Upgrade to 4.3.0
if ( Jetpack_Options::get_option( 'identity_crisis_whitelist' ) ) {
Jetpack_Options::delete_option( 'identity_crisis_whitelist' );
}
Jetpack::maybe_set_version_option();
}
}
}
static function activate_manage( ) {
if ( did_action( 'init' ) || current_filter() == 'init' ) {
self::activate_module( 'manage', false, false );
} else if ( ! has_action( 'init' , array( __CLASS__, 'activate_manage' ) ) ) {
add_action( 'init', array( __CLASS__, 'activate_manage' ) );
}
}
static function update_active_modules( $modules ) {
$current_modules = Jetpack_Options::get_option( 'active_modules', array() );
$success = Jetpack_Options::update_option( 'active_modules', array_unique( $modules ) );
if ( is_array( $modules ) && is_array( $current_modules ) ) {
$new_active_modules = array_diff( $modules, $current_modules );
foreach( $new_active_modules as $module ) {
/**
* Fires when a specific module is activated.
*
* @since 1.9.0
*
* @param string $module Module slug.
* @param boolean $success whether the module was activated. @since 4.2
*/
do_action( 'jetpack_activate_module', $module, $success );
/**
* Fires when a module is activated.
* The dynamic part of the filter, $module, is the module slug.
*
* @since 1.9.0
*
* @param string $module Module slug.
*/
do_action( "jetpack_activate_module_$module", $module );
}
$new_deactive_modules = array_diff( $current_modules, $modules );
foreach( $new_deactive_modules as $module ) {
/**
* Fired after a module has been deactivated.
*
* @since 4.2.0
*
* @param string $module Module slug.
* @param boolean $success whether the module was deactivated.
*/
do_action( 'jetpack_deactivate_module', $module, $success );
/**
* Fires when a module is deactivated.
* The dynamic part of the filter, $module, is the module slug.
*
* @since 1.9.0
*
* @param string $module Module slug.
*/
do_action( "jetpack_deactivate_module_$module", $module );
}
}
return $success;
}
static function delete_active_modules() {
self::update_active_modules( array() );
}
/**
* Constructor. Initializes WordPress hooks
*/
private function __construct() {
/*
* Check for and alert any deprecated hooks
*/
add_action( 'init', array( $this, 'deprecated_hooks' ) );
/*
* Load things that should only be in Network Admin.
*
* For now blow away everything else until a more full
* understanding of what is needed at the network level is
* available
*/
if( is_multisite() ) {
Jetpack_Network::init();
}
add_action( 'set_user_role', array( $this, 'maybe_clear_other_linked_admins_transient' ), 10, 3 );
// Unlink user before deleting the user from .com
add_action( 'deleted_user', array( $this, 'unlink_user' ), 10, 1 );
add_action( 'remove_user_from_blog', array( $this, 'unlink_user' ), 10, 1 );
if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
@ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
$this->xmlrpc_server = new Jetpack_XMLRPC_Server();
$this->require_jetpack_authentication();
if ( Jetpack::is_active() ) {
// Hack to preserve $HTTP_RAW_POST_DATA
add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
$signed = $this->verify_xml_rpc_signature();
if ( $signed && ! is_wp_error( $signed ) ) {
// The actual API methods.
add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
} else {
// The jetpack.authorize method should be available for unauthenticated users on a site with an
// active Jetpack connection, so that additional users can link their account.
add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'authorize_xmlrpc_methods' ) );
}
} else {
// The bootstrap API methods.
add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
}
// Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
} elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
$this->require_jetpack_authentication();
$this->add_remote_request_handlers();
} else {
if ( Jetpack::is_active() ) {
add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
add_filter( 'xmlrpc_methods', array( $this, 'public_xmlrpc_methods' ) );
}
}
if ( Jetpack::is_active() ) {
Jetpack_Heartbeat::init();
}
add_filter( 'determine_current_user', array( $this, 'wp_rest_authenticate' ) );
add_filter( 'rest_authentication_errors', array( $this, 'wp_rest_authentication_errors' ) );
add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
}
add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
add_action( 'admin_init', array( $this, 'admin_init' ) );
add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
add_action( 'wp_dashboard_setup', array( $this, 'wp_dashboard_setup' ) );
// Filter the dashboard meta box order to swap the new one in in place of the old one.
add_filter( 'get_user_option_meta-box-order_dashboard', array( $this, 'get_user_option_meta_box_order_dashboard' ) );
// returns HTTPS support status
add_action( 'wp_ajax_jetpack-recheck-ssl', array( $this, 'ajax_recheck_ssl' ) );
// If any module option is updated before Jump Start is dismissed, hide Jump Start.
add_action( 'update_option', array( $this, 'jumpstart_has_updated_module_option' ) );
// JITM AJAX callback function
add_action( 'wp_ajax_jitm_ajax', array( $this, 'jetpack_jitm_ajax_callback' ) );
// Universal ajax callback for all tracking events triggered via js
add_action( 'wp_ajax_jetpack_tracks', array( $this, 'jetpack_admin_ajax_tracks_callback' ) );
add_action( 'wp_loaded', array( $this, 'register_assets' ) );
add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
/**
* These actions run checks to load additional files.
* They check for external files or plugins, so they need to run as late as possible.
*/
add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
// A filter to control all just in time messages
add_filter( 'jetpack_just_in_time_msgs', '__return_true' );
// Update the Jetpack plan from API on heartbeats
add_action( 'jetpack_heartbeat', array( $this, 'refresh_active_plan_from_wpcom' ) );
/**
* This is the hack to concatinate all css files into one.
* For description and reasoning see the implode_frontend_css method
*
* Super late priority so we catch all the registered styles
*/
if( !is_admin() ) {
add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
}
}
function jetpack_admin_ajax_tracks_callback() {
// Check for nonce
if ( ! isset( $_REQUEST['tracksNonce'] ) || ! wp_verify_nonce( $_REQUEST['tracksNonce'], 'jp-tracks-ajax-nonce' ) ) {
wp_die( 'Permissions check failed.' );
}
if ( ! isset( $_REQUEST['tracksEventName'] ) || ! isset( $_REQUEST['tracksEventType'] ) ) {
wp_die( 'No valid event name or type.' );
}
$tracks_data = array();
if ( 'click' === $_REQUEST['tracksEventType'] && isset( $_REQUEST['tracksEventProp'] ) ) {
$tracks_data = array( 'clicked' => $_REQUEST['tracksEventProp'] );
}
JetpackTracking::record_user_event( $_REQUEST['tracksEventName'], $tracks_data );
wp_send_json_success();
wp_die();
}
/**
* The callback for the JITM ajax requests.
*/
function jetpack_jitm_ajax_callback() {
// Check for nonce
if ( ! isset( $_REQUEST['jitmNonce'] ) || ! wp_verify_nonce( $_REQUEST['jitmNonce'], 'jetpack-jitm-nonce' ) ) {
wp_die( 'Module activation failed due to lack of appropriate permissions' );
}
if ( isset( $_REQUEST['jitmActionToTake'] ) && 'activate' == $_REQUEST['jitmActionToTake'] ) {
$module_slug = $_REQUEST['jitmModule'];
Jetpack::log( 'activate', $module_slug );
Jetpack::activate_module( $module_slug, false, false );
Jetpack::state( 'message', 'no_message' );
//A Jetpack module is being activated through a JITM, track it
$this->stat( 'jitm', $module_slug.'-activated-' . JETPACK__VERSION );
$this->do_stats( 'server_side' );
wp_send_json_success();
}
if ( isset( $_REQUEST['jitmActionToTake'] ) && 'dismiss' == $_REQUEST['jitmActionToTake'] ) {
// get the hide_jitm options array
$jetpack_hide_jitm = Jetpack_Options::get_option( 'hide_jitm' );
$module_slug = $_REQUEST['jitmModule'];
if( ! $jetpack_hide_jitm ) {
$jetpack_hide_jitm = array(
$module_slug => 'hide'
);
} else {
$jetpack_hide_jitm[$module_slug] = 'hide';
}
Jetpack_Options::update_option( 'hide_jitm', $jetpack_hide_jitm );
//jitm is being dismissed forever, track it
$this->stat( 'jitm', $module_slug.'-dismissed-' . JETPACK__VERSION );
$this->do_stats( 'server_side' );
wp_send_json_success();
}
if ( isset( $_REQUEST['jitmActionToTake'] ) && 'launch' == $_REQUEST['jitmActionToTake'] ) {
$module_slug = $_REQUEST['jitmModule'];
// User went to WordPress.com, track this
$this->stat( 'jitm', $module_slug.'-wordpress-tools-' . JETPACK__VERSION );
$this->do_stats( 'server_side' );
wp_send_json_success();
}
if ( isset( $_REQUEST['jitmActionToTake'] ) && 'viewed' == $_REQUEST['jitmActionToTake'] ) {
$track = $_REQUEST['jitmModule'];
// User is viewing JITM, track it.
$this->stat( 'jitm', $track . '-viewed-' . JETPACK__VERSION );
$this->do_stats( 'server_side' );
wp_send_json_success();
}
}
/**
* If there are any stats that need to be pushed, but haven't been, push them now.
*/
function __destruct() {
if ( ! empty( $this->stats ) ) {
$this->do_stats( 'server_side' );
}
}
function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
switch( $cap ) {
case 'jetpack_connect' :
case 'jetpack_reconnect' :
if ( Jetpack::is_development_mode() ) {
$caps = array( 'do_not_allow' );
break;
}
/**
* Pass through. If it's not development mode, these should match disconnect.
* Let users disconnect if it's development mode, just in case things glitch.
*/
case 'jetpack_disconnect' :
/**
* In multisite, can individual site admins manage their own connection?
*
* Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
*/
if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
/**
* We need to update the option name -- it's terribly unclear which
* direction the override goes.
*
* @todo: Update the option name to `sub-sites-can-manage-own-connections`
*/
$caps = array( 'do_not_allow' );
break;
}
}
$caps = array( 'manage_options' );
break;
case 'jetpack_manage_modules' :
case 'jetpack_activate_modules' :
case 'jetpack_deactivate_modules' :
$caps = array( 'manage_options' );
break;
case 'jetpack_configure_modules' :
$caps = array( 'manage_options' );
break;
case 'jetpack_network_admin_page':
case 'jetpack_network_settings_page':
$caps = array( 'manage_network_plugins' );
break;
case 'jetpack_network_sites_page':
$caps = array( 'manage_sites' );
break;
case 'jetpack_admin_page' :
if ( Jetpack::is_development_mode() ) {
$caps = array( 'manage_options' );
break;
} else {
$caps = array( 'read' );
}
break;
case 'jetpack_connect_user' :
if ( Jetpack::is_development_mode() ) {
$caps = array( 'do_not_allow' );
break;
}
$caps = array( 'read' );
break;
}
return $caps;
}
function require_jetpack_authentication() {
// Don't let anyone authenticate
$_COOKIE = array();
remove_all_filters( 'authenticate' );
remove_all_actions( 'wp_login_failed' );
if ( Jetpack::is_active() ) {
// Allow Jetpack authentication
add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
}
}
/**
* Load language files
* @action plugins_loaded
*/
public static function plugin_textdomain() {
// Note to self, the third argument must not be hardcoded, to account for relocated folders.
load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
}
/**
* Register assets for use in various modules and the Jetpack admin page.
*
* @uses wp_script_is, wp_register_script, plugins_url
* @action wp_loaded
* @return null
*/
public function register_assets() {
if ( ! wp_script_is( 'spin', 'registered' ) ) {
wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
}
if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
}
if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
}
if ( ! wp_script_is( 'jetpack-twitter-timeline', 'registered' ) ) {
wp_register_script( 'jetpack-twitter-timeline', plugins_url( '_inc/twitter-timeline.js', JETPACK__PLUGIN_FILE ) , array( 'jquery' ), '4.0.0', true );
}
if ( ! wp_script_is( 'jetpack-facebook-embed', 'registered' ) ) {
wp_register_script( 'jetpack-facebook-embed', plugins_url( '_inc/facebook-embed.js', __FILE__ ), array( 'jquery' ), null, true );
/** This filter is documented in modules/sharedaddy/sharing-sources.php */
$fb_app_id = apply_filters( 'jetpack_sharing_facebook_app_id', '249643311490' );
if ( ! is_numeric( $fb_app_id ) ) {
$fb_app_id = '';
}
wp_localize_script(
'jetpack-facebook-embed',
'jpfbembed',
array(
'appid' => $fb_app_id,
'locale' => $this->get_locale(),
)
);
}
/**
* As jetpack_register_genericons is by default fired off a hook,
* the hook may have already fired by this point.
* So, let's just trigger it manually.
*/
require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
jetpack_register_genericons();
/**
* Register the social logos
*/
require_once( JETPACK__PLUGIN_DIR . '_inc/social-logos.php' );
jetpack_register_social_logos();
if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
}
/**
* Guess locale from language code.
*
* @param string $lang Language code.
* @return string|bool
*/
function guess_locale_from_lang( $lang ) {
if ( 'en' === $lang || 'en_US' === $lang || ! $lang ) {
return 'en_US';
}
if ( ! class_exists( 'GP_Locales' ) ) {
if ( ! defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) || ! file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
return false;
}
require JETPACK__GLOTPRESS_LOCALES_PATH;
}
if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
// WP.com: get_locale() returns 'it'
$locale = GP_Locales::by_slug( $lang );
} else {
// Jetpack: get_locale() returns 'it_IT';
$locale = GP_Locales::by_field( 'facebook_locale', $lang );
}
if ( ! $locale ) {
return false;
}
if ( empty( $locale->facebook_locale ) ) {
if ( empty( $locale->wp_locale ) ) {
return false;
} else {
// Facebook SDK is smart enough to fall back to en_US if a
// locale isn't supported. Since supported Facebook locales
// can fall out of sync, we'll attempt to use the known
// wp_locale value and rely on said fallback.
return $locale->wp_locale;
}
}
return $locale->facebook_locale;
}
/**
* Get the locale.
*
* @return string|bool
*/
function get_locale() {
$locale = $this->guess_locale_from_lang( get_locale() );
if ( ! $locale ) {
$locale = 'en_US';
}
return $locale;
}
/**
* Device Pixels support
* This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
*/
function devicepx() {
if ( Jetpack::is_active() ) {
wp_enqueue_script( 'devicepx', 'https://s0.wp.com/wp-content/js/devicepx-jetpack.js', array(), gmdate( 'oW' ), true );
}
}
/**
* Return the network_site_url so that .com knows what network this site is a part of.
* @param bool $option
* @return string
*/
public function jetpack_main_network_site_option( $option ) {
return network_site_url();
}
/**
* Network Name.
*/
static function network_name( $option = null ) {
global $current_site;
return $current_site->site_name;
}
/**
* Does the network allow new user and site registrations.
* @return string
*/
static function network_allow_new_registrations( $option = null ) {
return ( in_array( get_site_option( 'registration' ), array('none', 'user', 'blog', 'all' ) ) ? get_site_option( 'registration') : 'none' );
}
/**
* Does the network allow admins to add new users.
* @return boolian
*/
static function network_add_new_users( $option = null ) {
return (bool) get_site_option( 'add_new_users' );
}
/**
* File upload psace left per site in MB.
* -1 means NO LIMIT.
* @return number
*/
static function network_site_upload_space( $option = null ) {
// value in MB
return ( get_site_option( 'upload_space_check_disabled' ) ? -1 : get_space_allowed() );
}
/**
* Network allowed file types.
* @return string
*/
static function network_upload_file_types( $option = null ) {
return get_site_option( 'upload_filetypes', 'jpg jpeg png gif' );
}
/**
* Maximum file upload size set by the network.
* @return number
*/
static function network_max_upload_file_size( $option = null ) {
// value in KB
return get_site_option( 'fileupload_maxk', 300 );
}
/**
* Lets us know if a site allows admins to manage the network.
* @return array
*/
static function network_enable_administration_menus( $option = null ) {
return get_site_option( 'menu_items' );
}
/**
* If a user has been promoted to or demoted from admin, we need to clear the
* jetpack_other_linked_admins transient.
*
* @since 4.3.2
* @since 4.4.0 $old_roles is null by default and if it's not passed, the transient is cleared.
*
* @param int $user_id The user ID whose role changed.
* @param string $role The new role.
* @param array $old_roles An array of the user's previous roles.
*/
function maybe_clear_other_linked_admins_transient( $user_id, $role, $old_roles = null ) {
if ( 'administrator' == $role
|| ( is_array( $old_roles ) && in_array( 'administrator', $old_roles ) )
|| is_null( $old_roles )
) {
delete_transient( 'jetpack_other_linked_admins' );
}
}
/**
* Checks to see if there are any other users available to become primary
* Users must both:
* - Be linked to wpcom
* - Be an admin
*
* @return mixed False if no other users are linked, Int if there are.
*/
static function get_other_linked_admins() {
$other_linked_users = get_transient( 'jetpack_other_linked_admins' );
if ( false === $other_linked_users ) {
$admins = get_users( array( 'role' => 'administrator' ) );
if ( count( $admins ) > 1 ) {
$available = array();
foreach ( $admins as $admin ) {
if ( Jetpack::is_user_connected( $admin->ID ) ) {
$available[] = $admin->ID;
}
}
$count_connected_admins = count( $available );
if ( count( $available ) > 1 ) {
$other_linked_users = $count_connected_admins;
} else {
$other_linked_users = 0;
}
} else {
$other_linked_users = 0;
}
set_transient( 'jetpack_other_linked_admins', $other_linked_users, HOUR_IN_SECONDS );
}
return ( 0 === $other_linked_users ) ? false : $other_linked_users;
}
/**
* Return whether we are dealing with a multi network setup or not.
* The reason we are type casting this is because we want to avoid the situation where
* the result is false since when is_main_network_option return false it cases
* the rest the get_option( 'jetpack_is_multi_network' ); to return the value that is set in the
* database which could be set to anything as opposed to what this function returns.
* @param bool $option
*
* @return boolean
*/
public function is_main_network_option( $option ) {
// return '1' or ''
return (string) (bool) Jetpack::is_multi_network();
}
/**
* Return true if we are with multi-site or multi-network false if we are dealing with single site.
*
* @param string $option
* @return boolean
*/
public function is_multisite( $option ) {
return (string) (bool) is_multisite();
}
/**
* Implemented since there is no core is multi network function
* Right now there is no way to tell if we which network is the dominant network on the system
*
* @since 3.3
* @return boolean
*/
public static function is_multi_network() {
global $wpdb;
// if we don't have a multi site setup no need to do any more
if ( ! is_multisite() ) {
return false;
}
$num_sites = $wpdb->get_var( "SELECT COUNT(*) FROM {$wpdb->site}" );
if ( $num_sites > 1 ) {
return true;
} else {
return false;
}
}
/**
* Trigger an update to the main_network_site when we update the siteurl of a site.
* @return null
*/
function update_jetpack_main_network_site_option() {
_deprecated_function( __METHOD__, 'jetpack-4.2' );
}
/**
* Triggered after a user updates the network settings via Network Settings Admin Page
*
*/
function update_jetpack_network_settings() {
_deprecated_function( __METHOD__, 'jetpack-4.2' );
// Only sync this info for the main network site.
}
/**
* Get back if the current site is single user site.
*
* @return bool
*/
public static function is_single_user_site() {
global $wpdb;
if ( false === ( $some_users = get_transient( 'jetpack_is_single_user' ) ) ) {
$some_users = $wpdb->get_var( "SELECT COUNT(*) FROM (SELECT user_id FROM $wpdb->usermeta WHERE meta_key = '{$wpdb->prefix}capabilities' LIMIT 2) AS someusers" );
set_transient( 'jetpack_is_single_user', (int) $some_users, 12 * HOUR_IN_SECONDS );
}
return 1 === (int) $some_users;
}
/**
* Returns true if the site has file write access false otherwise.
* @return string ( '1' | '0' )
**/
public static function file_system_write_access() {
if ( ! function_exists( 'get_filesystem_method' ) ) {
require_once( ABSPATH . 'wp-admin/includes/file.php' );
}
require_once( ABSPATH . 'wp-admin/includes/template.php' );
$filesystem_method = get_filesystem_method();
if ( $filesystem_method === 'direct' ) {
return 1;
}
ob_start();
$filesystem_credentials_are_stored = request_filesystem_credentials( self_admin_url() );
ob_end_clean();
if ( $filesystem_credentials_are_stored ) {
return 1;
}
return 0;
}
/**
* Finds out if a site is using a version control system.
* @return string ( '1' | '0' )
**/
public static function is_version_controlled() {
_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Functions::is_version_controlled' );
return (string) (int) Jetpack_Sync_Functions::is_version_controlled();
}
/**
* Determines whether the current theme supports featured images or not.
* @return string ( '1' | '0' )
*/
public static function featured_images_enabled() {
_deprecated_function( __METHOD__, 'jetpack-4.2' );
return current_theme_supports( 'post-thumbnails' ) ? '1' : '0';
}
/**
* jetpack_updates is saved in the following schema:
*
* array (
* 'plugins' => (int) Number of plugin updates available.
* 'themes' => (int) Number of theme updates available.
* 'wordpress' => (int) Number of WordPress core updates available.
* 'translations' => (int) Number of translation updates available.
* 'total' => (int) Total of all available updates.
* 'wp_update_version' => (string) The latest available version of WordPress, only present if a WordPress update is needed.
* )
* @return array
*/
public static function get_updates() {
$update_data = wp_get_update_data();
// Stores the individual update counts as well as the total count.
if ( isset( $update_data['counts'] ) ) {
$updates = $update_data['counts'];
}
// If we need to update WordPress core, let's find the latest version number.
if ( ! empty( $updates['wordpress'] ) ) {
$cur = get_preferred_from_update_core();
if ( isset( $cur->response ) && 'upgrade' === $cur->response ) {
$updates['wp_update_version'] = $cur->current;
}
}
return isset( $updates ) ? $updates : array();
}
public static function get_update_details() {
$update_details = array(
'update_core' => get_site_transient( 'update_core' ),
'update_plugins' => get_site_transient( 'update_plugins' ),
'update_themes' => get_site_transient( 'update_themes' ),
);
return $update_details;
}
public static function refresh_update_data() {
_deprecated_function( __METHOD__, 'jetpack-4.2' );
}
public static function refresh_theme_data() {
_deprecated_function( __METHOD__, 'jetpack-4.2' );
}
/**
* Is Jetpack active?
*/
public static function is_active() {
return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
}
/**
* Make an API call to WordPress.com for plan status
*
* @uses Jetpack_Options::get_option()
* @uses Jetpack_Client::wpcom_json_api_request_as_blog()
* @uses update_option()
*
* @access public
* @static
*
* @return bool True if plan is updated, false if no update
*/
public static function refresh_active_plan_from_wpcom() {
// Make the API request
$request = sprintf( '/sites/%d', Jetpack_Options::get_option( 'id' ) );
$response = Jetpack_Client::wpcom_json_api_request_as_blog( $request, '1.1' );
// Bail if there was an error or malformed response
if ( is_wp_error( $response ) || ! is_array( $response ) || ! isset( $response['body'] ) ) {
return false;
}
// Decode the results
$results = json_decode( $response['body'], true );
// Bail if there were no results or plan details returned
if ( ! is_array( $results ) || ! isset( $results['plan'] ) ) {
return false;
}
// Store the option and return true if updated
return update_option( 'jetpack_active_plan', $results['plan'] );
}
/**
* Get the plan that this Jetpack site is currently using
*
* @uses get_option()
*
* @access public
* @static
*
* @return array Active Jetpack plan details
*/
public static function get_active_plan() {
$plan = get_option( 'jetpack_active_plan' );
// Set the default options
if ( ! $plan ) {
$plan = array(
'product_slug' => 'jetpack_free',
'supports' => array(),
'class' => 'free',
);
}
// Define what paid modules are supported by personal plans
$personal_plans = array(
'jetpack_personal',
'jetpack_personal_monthly',
);
if ( in_array( $plan['product_slug'], $personal_plans ) ) {
$plan['supports'] = array(
'akismet',
);
$plan['class'] = 'personal';
}
// Define what paid modules are supported by premium plans
$premium_plans = array(
'jetpack_premium',
'jetpack_premium_monthly',
);
if ( in_array( $plan['product_slug'], $premium_plans ) ) {
$plan['supports'] = array(
'videopress',
'akismet',
'vaultpress',
'wordads',
);
$plan['class'] = 'premium';
}
// Define what paid modules are supported by professional plans
$business_plans = array(
'jetpack_business',
'jetpack_business_monthly',
);
if ( in_array( $plan['product_slug'], $business_plans ) ) {
$plan['supports'] = array(
'videopress',
'akismet',
'vaultpress',
'seo-tools',
'google-analytics',
'wordads',
);
$plan['class'] = 'business';
}
// Make sure we have an array here in the event database data is stale
if ( ! isset( $plan['supports'] ) ) {
$plan['supports'] = array();
}
return $plan;
}
/**
* Determine whether the active plan supports a particular feature
*
* @uses Jetpack::get_active_plan()
*
* @access public
* @static
*
* @return bool True if plan supports feature, false if not
*/
public static function active_plan_supports( $feature ) {
$plan = Jetpack::get_active_plan();
if ( in_array( $feature, $plan['supports'] ) ) {
return true;
}
return false;
}
/**
* Is Jetpack in development (offline) mode?
*/
public static function is_development_mode() {
$development_mode = false;
if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
$development_mode = JETPACK_DEV_DEBUG;
} elseif ( $site_url = site_url() ) {
$development_mode = false === strpos( $site_url, '.' );
}
/**
* Filters Jetpack's development mode.
*
* @see https://jetpack.com/support/development-mode/
*
* @since 2.2.1
*
* @param bool $development_mode Is Jetpack's development mode active.
*/
return apply_filters( 'jetpack_development_mode', $development_mode );
}
/**
* Get Jetpack development mode notice text and notice class.
*
* Mirrors the checks made in Jetpack::is_development_mode
*
*/
public static function show_development_mode_notice() {
if ( Jetpack::is_development_mode() ) {
if ( defined( 'JETPACK_DEV_DEBUG' ) && JETPACK_DEV_DEBUG ) {
$notice = sprintf(
/* translators: %s is a URL */
__( 'In <a href="%s" target="_blank">Development Mode</a>, via the JETPACK_DEV_DEBUG constant being defined in wp-config.php or elsewhere.', 'jetpack' ),
'https://jetpack.com/support/development-mode/'
);
} elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
$notice = sprintf(
/* translators: %s is a URL */
__( 'In <a href="%s" target="_blank">Development Mode</a>, via site URL lacking a dot (e.g. http://localhost).', 'jetpack' ),
'https://jetpack.com/support/development-mode/'
);
} else {
$notice = sprintf(
/* translators: %s is a URL */
__( 'In <a href="%s" target="_blank">Development Mode</a>, via the jetpack_development_mode filter.', 'jetpack' ),
'https://jetpack.com/support/development-mode/'
);
}
echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
}
// Throw up a notice if using a development version and as for feedback.
if ( Jetpack::is_development_version() ) {
/* translators: %s is a URL */
$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/' );
echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
}
// Throw up a notice if using staging mode
if ( Jetpack::is_staging_site() ) {
/* translators: %s is a URL */
$notice = sprintf( __( 'You are running Jetpack on a <a href="%s" target="_blank">staging server</a>.', 'jetpack' ), 'https://jetpack.com/support/staging-sites/' );
echo '<div class="updated" style="border-color: #f0821e;"><p>' . $notice . '</p></div>';
}
}
/**
* Whether Jetpack's version maps to a public release, or a development version.
*/
public static function is_development_version() {
/**
* Allows filtering whether this is a development version of Jetpack.
*
* This filter is especially useful for tests.
*
* @since 4.3.0
*
* @param bool $development_version Is this a develoment version of Jetpack?
*/
return (bool) apply_filters(
'jetpack_development_version',
! preg_match( '/^\d+(\.\d+)+$/', Jetpack_Constants::get_constant( 'JETPACK__VERSION' ) )
);
}
/**
* Is a given user (or the current user if none is specified) linked to a WordPress.com user?
*/
public static function is_user_connected( $user_id = false ) {
$user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
if ( ! $user_id ) {
return false;
}
return (bool) Jetpack_Data::get_access_token( $user_id );
}
/**
* Get the wpcom user data of the current|specified connected user.
*/
public static function get_connected_user_data( $user_id = null ) {
if ( ! $user_id ) {
$user_id = get_current_user_id();
}
$transient_key = "jetpack_connected_user_data_$user_id";
if ( $cached_user_data = get_transient( $transient_key ) ) {
return $cached_user_data;
}
Jetpack::load_xml_rpc_client();
$xml = new Jetpack_IXR_Client( array(
'user_id' => $user_id,
) );
$xml->query( 'wpcom.getUser' );
if ( ! $xml->isError() ) {
$user_data = $xml->getResponse();
set_transient( $transient_key, $xml->getResponse(), DAY_IN_SECONDS );
return $user_data;
}
return false;
}
/**
* Get the wpcom email of the current|specified connected user.
*/
public static function get_connected_user_email( $user_id = null ) {
if ( ! $user_id ) {
$user_id = get_current_user_id();
}
Jetpack::load_xml_rpc_client();
$xml = new Jetpack_IXR_Client( array(
'user_id' => $user_id,
) );
$xml->query( 'wpcom.getUserEmail' );
if ( ! $xml->isError() ) {
return $xml->getResponse();
}
return false;
}
/**
* Get the wpcom email of the master user.
*/
public static function get_master_user_email() {
$master_user_id = Jetpack_Options::get_option( 'master_user' );
if ( $master_user_id ) {
return self::get_connected_user_email( $master_user_id );
}
return '';
}
function current_user_is_connection_owner() {
$user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
}
/**
* Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
*/
function extra_oembed_providers() {
// Cloudup: https://dev.cloudup.com/#oembed
wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
wp_oembed_add_provider( 'https://me.sh/*', 'https://me.sh/oembed?format=json' );
wp_oembed_add_provider( '#https?://(www\.)?gfycat\.com/.*#i', 'https://api.gfycat.com/v1/oembed', true );
wp_oembed_add_provider( '#https?://[^.]+\.(wistia\.com|wi\.st)/(medias|embed)/.*#', 'https://fast.wistia.com/oembed', true );
wp_oembed_add_provider( '#https?://sketchfab\.com/.*#i', 'https://sketchfab.com/oembed', true );
}
/**
* Synchronize connected user role changes
*/
function user_role_change( $user_id ) {
_deprecated_function( __METHOD__, 'jetpack-4.2', 'Jetpack_Sync_Users::user_role_change()' );
Jetpack_Sync_Users::user_role_change( $user_id );
}
/**
* Loads the currently active modules.
*/
public static function load_modules() {
if ( ! self::is_active() && !self::is_development_mode() ) {
if ( ! is_multisite() || ! get_site_option( 'jetpack_protect_active' ) ) {
return;
}
}
$version = Jetpack_Options::get_option( 'version' );
if ( ! $version ) {
$version = $old_version = JETPACK__VERSION . ':' . time();
/** This action is documented in class.jetpack.php */
do_action( 'updating_jetpack_version', $version, false );
Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
}
list( $version ) = explode( ':', $version );
$modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
$modules_data = array();
// Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
$updated_modules = array();
foreach ( $modules as $module ) {
$modules_data[ $module ] = Jetpack::get_module( $module );
if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
continue;
}
if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
continue;
}
$updated_modules[] = $module;
}
$modules = array_diff( $modules, $updated_modules );
}
$is_development_mode = Jetpack::is_development_mode();
foreach ( $modules as $index => $module ) {
// If we're in dev mode, disable modules requiring a connection
if ( $is_development_mode ) {
// Prime the pump if we need to
if ( empty( $modules_data[ $module ] ) ) {
$modules_data[ $module ] = Jetpack::get_module( $module );
}
// If the module requires a connection, but we're in local mode, don't include it.
if ( $modules_data[ $module ]['requires_connection'] ) {
continue;
}
}
if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
continue;
}
if ( ! @include( Jetpack::get_module_path( $module ) ) ) {
unset( $modules[ $index ] );
self::update_active_modules( array_values( $modules ) );
continue;
}
/**
* Fires when a specific module is loaded.
* The dynamic part of the hook, $module, is the module slug.
*
* @since 1.1.0
*/
do_action( 'jetpack_module_loaded_' . $module );
}
/**
* Fires when all the modules are loaded.
*
* @since 1.1.0
*/
do_action( 'jetpack_modules_loaded' );
// 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.
if ( Jetpack::is_active() || Jetpack::is_development_mode() )
require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
}
/**
* Check if Jetpack's REST API compat file should be included
* @action plugins_loaded
* @return null
*/
public function check_rest_api_compat() {
/**
* Filters the list of REST API compat files to be included.
*
* @since 2.2.5
*
* @param array $args Array of REST API compat files to include.
*/
$_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
if ( function_exists( 'bbpress' ) )
$_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
require_once $_jetpack_rest_api_compat_include;
}
/**
* Gets all plugins currently active in values, regardless of whether they're
* traditionally activated or network activated.
*
* @todo Store the result in core's object cache maybe?
*/
public static function get_active_plugins() {
$active_plugins = (array) get_option( 'active_plugins', array() );
if ( is_multisite() ) {
// Due to legacy code, active_sitewide_plugins stores them in the keys,
// whereas active_plugins stores them in the values.
$network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
if ( $network_plugins ) {
$active_plugins = array_merge( $active_plugins, $network_plugins );
}
}
sort( $active_plugins );
return array_unique( $active_plugins );
}
/**
* Gets and parses additional plugin data to send with the heartbeat data
*
* @since 3.8.1
*
* @return array Array of plugin data
*/
public static function get_parsed_plugin_data() {
if ( ! function_exists( 'get_plugins' ) ) {
require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
}
/** This filter is documented in wp-admin/includes/class-wp-plugins-list-table.php */
$all_plugins = apply_filters( 'all_plugins', get_plugins() );
$active_plugins = Jetpack::get_active_plugins();
$plugins = array();
foreach ( $all_plugins as $path => $plugin_data ) {
$plugins[ $path ] = array(
'is_active' => in_array( $path, $active_plugins ),
'file' => $path,
'name' => $plugin_data['Name'],
'version' => $plugin_data['Version'],
'author' => $plugin_data['Author'],
);
}
return $plugins;
}
/**
* Gets and parses theme data to send with the heartbeat data
*
* @since 3.8.1
*
* @return array Array of theme data
*/
public static function get_parsed_theme_data() {
$all_themes = wp_get_themes( array( 'allowed' => true ) );
$header_keys = array( 'Name', 'Author', 'Version', 'ThemeURI', 'AuthorURI', 'Status', 'Tags' );
$themes = array();
foreach ( $all_themes as $slug => $theme_data ) {
$theme_headers = array();
foreach ( $header_keys as $header_key ) {
$theme_headers[ $header_key ] = $theme_data->get( $header_key );
}
$themes[ $slug ] = array(
'is_active_theme' => $slug == wp_get_theme()->get_template(),
'slug' => $slug,
'theme_root' => $theme_data->get_theme_root_uri(),
'parent' => $theme_data->parent(),
'headers' => $theme_headers
);
}
return $themes;
}
/**
* Checks whether a specific plugin is active.
*
* We don't want to store these in a static variable, in case
* there are switch_to_blog() calls involved.
*/
public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
return in_array( $plugin, self::get_active_plugins() );
}
/**
* Check if Jetpack's Open Graph tags should be used.
* If certain plugins are active, Jetpack's og tags are suppressed.
*
* @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
* @action plugins_loaded
* @return null
*/
public function check_open_graph() {
if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
}
$active_plugins = self::get_active_plugins();
if ( ! empty( $active_plugins ) ) {
foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
if ( in_array( $plugin, $active_plugins ) ) {
add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
break;
}
}
}
/**
* Allow the addition of Open Graph Meta Tags to all pages.
*
* @since 2.0.3
*
* @param bool false Should Open Graph Meta tags be added. Default to false.
*/
if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
}
}
/**
* Check if Jetpack's Twitter tags should be used.
* If certain plugins are active, Jetpack's twitter tags are suppressed.
*
* @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
* @action plugins_loaded
* @return null
*/
public function check_twitter_tags() {
$active_plugins = self::get_active_plugins();
if ( ! empty( $active_plugins ) ) {
foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
if ( in_array( $plugin, $active_plugins ) ) {
add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
break;
}
}
}
/**
* Allow Twitter Card Meta tags to be disabled.
*
* @since 2.6.0
*
* @param bool true Should Twitter Card Meta tags be disabled. Default to true.
*/
if ( ! apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
}
}
/**
* Allows plugins to submit security reports.
*
* @param string $type Report type (login_form, backup, file_scanning, spam)
* @param string $plugin_file Plugin __FILE__, so that we can pull plugin data
* @param array $args See definitions above
*/
public static function submit_security_report( $type = '', $plugin_file = '', $args = array() ) {
_deprecated_function( __FUNCTION__, 'jetpack-4.2', null );
}
/* Jetpack Options API */
public static function get_option_names( $type = 'compact' ) {
return Jetpack_Options::get_option_names( $type );
}
/**
* Returns the requested option. Looks in jetpack_options or jetpack_$name as appropriate.
*
* @param string $name Option name
* @param mixed $default (optional)
*/
public static function get_option( $name, $default = false ) {
return Jetpack_Options::get_option( $name, $default );
}
/**
* Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
* Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
* $name must be a registered option name.
*/
public static function create_nonce( $name ) {
$secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
Jetpack_Options::update_option( $name, $secret );
@list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
return new Jetpack_Error( 'missing_secrets' );
return array(
'secret_1' => $secret_1,
'secret_2' => $secret_2,
'eol' => $eol,
);
}
/**
* Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
*
* @deprecated 3.4 use Jetpack_Options::update_option() instead.
* @param string $name Option name
* @param mixed $value Option value
*/
public static function update_option( $name, $value ) {
_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_option()' );
return Jetpack_Options::update_option( $name, $value );
}
/**
* Updates the multiple given options. Updates jetpack_options and/or jetpack_$name as appropriate.
*
* @deprecated 3.4 use Jetpack_Options::update_options() instead.
* @param array $array array( option name => option value, ... )
*/
public static function update_options( $array ) {
_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::update_options()' );
return Jetpack_Options::update_options( $array );
}
/**
* Deletes the given option. May be passed multiple option names as an array.
* Updates jetpack_options and/or deletes jetpack_$name as appropriate.
*
* @deprecated 3.4 use Jetpack_Options::delete_option() instead.
* @param string|array $names
*/
public static function delete_option( $names ) {
_deprecated_function( __METHOD__, 'jetpack-3.4', 'Jetpack_Options::delete_option()' );
return Jetpack_Options::delete_option( $names );
}
/**
* Enters a user token into the user_tokens option
*
* @param int $user_id
* @param string $token
* return bool
*/
public static function update_user_token( $user_id, $token, $is_master_user ) {
// not designed for concurrent updates
$user_tokens = Jetpack_Options::get_option( 'user_tokens' );
if ( ! is_array( $user_tokens ) )
$user_tokens = array();
$user_tokens[$user_id] = $token;
if ( $is_master_user ) {
$master_user = $user_id;
$options = compact( 'user_tokens', 'master_user' );
} else {
$options = compact( 'user_tokens' );
}
return Jetpack_Options::update_options( $options );
}
/**
* Returns an array of all PHP files in the specified absolute path.
* Equivalent to glob( "$absolute_path/*.php" ).
*
* @param string $absolute_path The absolute path of the directory to search.
* @return array Array of absolute paths to the PHP files.
*/
public static function glob_php( $absolute_path ) {
if ( function_exists( 'glob' ) ) {
return glob( "$absolute_path/*.php" );
}
$absolute_path = untrailingslashit( $absolute_path );
$files = array();
if ( ! $dir = @opendir( $absolute_path ) ) {
return $files;
}
while ( false !== $file = readdir( $dir ) ) {
if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
continue;
}
$file = "$absolute_path/$file";
if ( ! is_file( $file ) ) {
continue;
}
$files[] = $file;
}
closedir( $dir );
return $files;
}
public static function activate_new_modules( $redirect = false ) {
if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
return;
}
$jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
if ( ! $jetpack_old_version ) {
$jetpack_old_version = $version = $old_version = '1.1:' . time();
/** This action is documented in class.jetpack.php */
do_action( 'updating_jetpack_version', $version, false );
Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
}
list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
return;
}
$active_modules = Jetpack::get_active_modules();
$reactivate_modules = array();
foreach ( $active_modules as $active_module ) {
$module = Jetpack::get_module( $active_module );
if ( ! isset( $module['changed'] ) ) {
continue;
}
if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
continue;
}
$reactivate_modules[] = $active_module;
Jetpack::deactivate_module( $active_module );
}
$new_version = JETPACK__VERSION . ':' . time();
/** This action is documented in class.jetpack.php */
do_action( 'updating_jetpack_version', $new_version, $jetpack_old_version );
Jetpack_Options::update_options(
array(
'version' => $new_version,
'old_version' => $jetpack_old_version,
)
);
Jetpack::state( 'message', 'modules_activated' );
Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
if ( $redirect ) {
$page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
if ( isset( $_GET['page'] ) && in_array( $_GET['page'], array( 'jetpack', 'jetpack_modules' ) ) ) {
$page = $_GET['page'];
}
wp_safe_redirect( Jetpack::admin_url( 'page=' . $page ) );
exit;
}
}
/**
* List available Jetpack modules. Simply lists .php files in /modules/.
* Make sure to tuck away module "library" files in a sub-directory.
*/
public static function get_available_modules( $min_version = false, $max_version = false ) {
static $modules = null;
if ( ! isset( $modules ) ) {
$available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
// Use the cache if we're on the front-end and it's available...
if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
$modules = $available_modules_option[ JETPACK__VERSION ];
} else {
$files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
$modules = array();
foreach ( $files as $file ) {
if ( ! $headers = Jetpack::get_module( $file ) ) {
continue;
}
$modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
}
Jetpack_Options::update_option( 'available_modules', array(
JETPACK__VERSION => $modules,
) );
}
}
/**
* Filters the array of modules available to be activated.
*
* @since 2.4.0
*
* @param array $modules Array of available modules.
* @param string $min_version Minimum version number required to use modules.
* @param string $max_version Maximum version number required to use modules.
*/
$mods = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
if ( ! $min_version && ! $max_version ) {
return array_keys( $mods );
}
$r = array();
foreach ( $mods as $slug => $introduced ) {
if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
continue;
}
if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
continue;
}
$r[] = $slug;
}
return $r;
}
/**
* Default modules loaded on activation.
*/
public static function get_default_modules( $min_version = false, $max_version = false ) {
$return = array();
foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
$module_data = Jetpack::get_module( $module );
switch ( strtolower( $module_data['auto_activate'] ) ) {
case 'yes' :
$return[] = $module;
break;
case 'public' :
if ( Jetpack_Options::get_option( 'public' ) ) {
$return[] = $module;
}
break;
case 'no' :
default :
break;
}
}
/**
* Filters the array of default modules.
*
* @since 2.5.0
*
* @param array $return Array of default modules.
* @param string $min_version Minimum version number required to use modules.
* @param string $max_version Maximum version number required to use modules.
*/
return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
}
/**
* Checks activated modules during auto-activation to determine
* if any of those modules are being deprecated. If so, close
* them out, and add any replacement modules.
*
* Runs at priority 99 by default.
*
* This is run late, so that it can still activate a module if
* the new module is a replacement for another that the user
* currently has active, even if something at the normal priority
* would kibosh everything.
*
* @since 2.6
* @uses jetpack_get_default_modules filter
* @param array $modules
* @return array
*/
function handle_deprecated_modules( $modules ) {
$deprecated_modules = array(
'debug' => null, // Closed out and moved to ./class.jetpack-debugger.php
'wpcc' => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
'gplus-authorship' => null, // Closed out in 3.2 -- Google dropped support.
);
// Don't activate SSO if they never completed activating WPCC.
if ( Jetpack::is_module_active( 'wpcc' ) ) {
$wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
$deprecated_modules['wpcc'] = null;
}
}
foreach ( $deprecated_modules as $module => $replacement ) {
if ( Jetpack::is_module_active( $module ) ) {
self::deactivate_module( $module );
if ( $replacement ) {
$modules[] = $replacement;
}
}
}
return array_unique( $modules );
}
/**
* Checks activated plugins during auto-activation to determine
* if any of those plugins are in the list with a corresponding module
* that is not compatible with the plugin. The module will not be allowed
* to auto-activate.
*
* @since 2.6
* @uses jetpack_get_default_modules filter
* @param array $modules
* @return array
*/
function filter_default_modules( $modules ) {
$active_plugins = self::get_active_plugins();
if ( ! empty( $active_plugins ) ) {
// For each module we'd like to auto-activate...
foreach ( $modules as $key => $module ) {
// If there are potential conflicts for it...
if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
// For each potential conflict...
foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
// If that conflicting plugin is active...
if ( in_array( $plugin, $active_plugins ) ) {
// Remove that item from being auto-activated.
unset( $modules[ $key ] );
}
}
}
}
}
return $modules;
}
/**
* Extract a module's slug from its full path.
*/
public static function get_module_slug( $file ) {
return str_replace( '.php', '', basename( $file ) );
}
/**
* Generate a module's path from its slug.
*/
public static function get_module_path( $slug ) {
return JETPACK__PLUGIN_DIR . "modules/$slug.php";
}
/**
* Load module data from module file. Headers differ from WordPress
* plugin headers to avoid them being identified as standalone
* plugins on the WordPress plugins page.
*/
public static function get_module( $module ) {
$headers = array(
'name' => 'Module Name',
'description' => 'Module Description',
'jumpstart_desc' => 'Jumpstart Description',
'sort' => 'Sort Order',
'recommendation_order' => 'Recommendation Order',
'introduced' => 'First Introduced',
'changed' => 'Major Changes In',
'deactivate' => 'Deactivate',
'free' => 'Free',
'requires_connection' => 'Requires Connection',
'auto_activate' => 'Auto Activate',
'module_tags' => 'Module Tags',
'feature' => 'Feature',
'additional_search_queries' => 'Additional Search Queries',
);
$file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
$mod = Jetpack::get_file_data( $file, $headers );
if ( empty( $mod['name'] ) ) {
return false;
}
$mod['sort'] = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
$mod['recommendation_order'] = empty( $mod['recommendation_order'] ) ? 20 : (int) $mod['recommendation_order'];
$mod['deactivate'] = empty( $mod['deactivate'] );
$mod['free'] = empty( $mod['free'] );
$mod['requires_connection'] = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
$mod['auto_activate'] = 'No';
} else {
$mod['auto_activate'] = (string) $mod['auto_activate'];
}
if ( $mod['module_tags'] ) {
$mod['module_tags'] = explode( ',', $mod['module_tags'] );
$mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
$mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
} else {
$mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
}
if ( $mod['feature'] ) {
$mod['feature'] = explode( ',', $mod['feature'] );
$mod['feature'] = array_map( 'trim', $mod['feature'] );
} else {
$mod['feature'] = array( self::translate_module_tag( 'Other' ) );
}
/**
* Filters the feature array on a module.
*
* This filter allows you to control where each module is filtered: Recommended,
* Jumpstart, and the default "Other" listing.
*
* @since 3.5.0
*
* @param array $mod['feature'] The areas to feature this module:
* 'Jumpstart' adds to the "Jumpstart" option to activate many modules at once.
* 'Recommended' shows on the main Jetpack admin screen.
* 'Other' should be the default if no other value is in the array.
* @param string $module The slug of the module, e.g. sharedaddy.
* @param array $mod All the currently assembled module data.
*/
$mod['feature'] = apply_filters( 'jetpack_module_feature', $mod['feature'], $module, $mod );
/**
* Filter the returned data about a module.
*
* This filter allows overriding any info about Jetpack modules. It is dangerous,
* so please be careful.
*
* @since 3.6.0
*
* @param array $mod The details of the requested module.
* @param string $module The slug of the module, e.g. sharedaddy
* @param string $file The path to the module source file.
*/
return apply_filters( 'jetpack_get_module', $mod, $module, $file );
}
/**
* Like core's get_file_data implementation, but caches the result.
*/
public static function get_file_data( $file, $headers ) {
//Get just the filename from $file (i.e. exclude full path) so that a consistent hash is generated
$file_name = basename( $file );
$file_data_option = Jetpack_Options::get_option( 'file_data', array() );
$key = md5( $file_name . serialize( $headers ) );
$refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
// If we don't need to refresh the cache, and already have the value, short-circuit!
if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
return $file_data_option[ JETPACK__VERSION ][ $key ];
}
$data = get_file_data( $file, $headers );
// Strip out any old Jetpack versions that are cluttering the option.
$file_data_option = array_intersect_key( (array) $file_data_option, array( JETPACK__VERSION => null ) );
$file_data_option[ JETPACK__VERSION ][ $key ] = $data;
Jetpack_Options::update_option( 'file_data', $file_data_option );
return $data;
}
/**
* Return translated module tag.
*
* @param string $tag Tag as it appears in each module heading.
*
* @return mixed
*/
public static function translate_module_tag( $tag ) {
return jetpack_get_module_i18n_tag( $tag );
}
/**
* Return module name translation. Uses matching string created in modules/module-headings.php.
*
* @since 3.9.2
*
* @param array $modules
*
* @return string|void
*/
public static function get_translated_modules( $modules ) {
foreach ( $modules as $index => $module ) {
$i18n_module = jetpack_get_module_i18n( $module['module'] );
if ( isset( $module['name'] ) ) {
$modules[ $index ]['name'] = $i18n_module['name'];
}
if ( isset( $module['description'] ) ) {
$modules[ $index ]['description'] = $i18n_module['description'];
$modules[ $index ]['short_description'] = $i18n_module['description'];
}
}
return $modules;
}
/**
* Get a list of activated modules as an array of module slugs.
*/
public static function get_active_modules() {
$active = Jetpack_Options::get_option( 'active_modules' );
if ( ! is_array( $active ) ) {
$active = array();
}
if ( class_exists( 'VaultPress' ) || function_exists( 'vaultpress_contact_service' ) ) {
$active[] = 'vaultpress';
} else {
$active = array_diff( $active, array( 'vaultpress' ) );
}
//If protect is active on the main site of a multisite, it should be active on all sites.
if ( ! in_array( 'protect', $active ) && is_multisite() && get_site_option( 'jetpack_protect_active' ) ) {
$active[] = 'protect';
}
return array_unique( $active );
}
/**
* Check whether or not a Jetpack module is active.
*
* @param string $module The slug of a Jetpack module.
* @return bool
*
* @static
*/
public static function is_module_active( $module ) {
return in_array( $module, self::get_active_modules() );
}
public static function is_module( $module ) {
return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
}
/**
* Catches PHP errors. Must be used in conjunction with output buffering.
*
* @param bool $catch True to start catching, False to stop.
*
* @static
*/
public static function catch_errors( $catch ) {
static $display_errors, $error_reporting;
if ( $catch ) {
$display_errors = @ini_set( 'display_errors', 1 );
$error_reporting = @error_reporting( E_ALL );
add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
} else {
@ini_set( 'display_errors', $display_errors );
@error_reporting( $error_reporting );
remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
}
}
/**
* Saves any generated PHP errors in ::state( 'php_errors', {errors} )
*/
public static function catch_errors_on_shutdown() {
Jetpack::state( 'php_errors', ob_get_clean() );
}
public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array(), $redirect = true ) {
$jetpack = Jetpack::init();
$modules = Jetpack::get_default_modules( $min_version, $max_version );
$modules = array_merge( $other_modules, $modules );
// Look for standalone plugins and disable if active.
$to_deactivate = array();
foreach ( $modules as $module ) {
if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
$to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
}
}
$deactivated = array();
foreach ( $to_deactivate as $module => $deactivate_me ) {
list( $probable_file, $probable_title ) = $deactivate_me;
if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
$deactivated[] = $module;
}
}
if ( $deactivated && $redirect ) {
Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
$url = add_query_arg(
array(
'action' => 'activate_default_modules',
'_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
),
add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
);
wp_safe_redirect( $url );
exit;
}
/**
* Fires before default modules are activated.
*
* @since 1.9.0
*
* @param string $min_version Minimum version number required to use modules.
* @param string $max_version Maximum version number required to use modules.
* @param array $other_modules Array of other modules to activate alongside the default modules.
*/
do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
// Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
Jetpack::restate();
Jetpack::catch_errors( true );
$active = Jetpack::get_active_modules();
foreach ( $modules as $module ) {
if ( did_action( "jetpack_module_loaded_$module" ) ) {
$active[] = $module;
self::update_active_modules( $active );
continue;
}
if ( in_array( $module, $active ) ) {
$module_info = Jetpack::get_module( $module );
if ( ! $module_info['deactivate'] ) {
$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
if ( $active_state = Jetpack::state( $state ) ) {
$active_state = explode( ',', $active_state );
} else {
$active_state = array();
}
$active_state[] = $module;
Jetpack::state( $state, implode( ',', $active_state ) );
}
continue;
}
$file = Jetpack::get_module_path( $module );
if ( ! file_exists( $file ) ) {
continue;
}
// we'll override this later if the plugin can be included without fatal error
if ( $redirect ) {
wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
}
Jetpack::state( 'error', 'module_activation_failed' );
Jetpack::state( 'module', $module );
ob_start();
require $file;
$active[] = $module;
$state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
if ( $active_state = Jetpack::state( $state ) ) {
$active_state = explode( ',', $active_state );
} else {
$active_state = array();
}
$active_state[] = $module;
Jetpack::state( $state, implode( ',', $active_state ) );
Jetpack::update_active_modules( $active );
ob_end_clean();
}
Jetpack::state( 'error', false );
Jetpack::state( 'module', false );
Jetpack::catch_errors( false );
/**
* Fires when default modules are activated.
*
* @since 1.9.0
*
* @param string $min_version Minimum version number required to use modules.
* @param string $max_version Maximum version number required to use modules.
* @param array $other_modules Array of other modules to activate alongside the default modules.
*/
do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
}
public static function activate_module( $module, $exit = true, $redirect = true ) {
/**
* Fires before a module is activated.
*
* @since 2.6.0
*
* @param string $module Module slug.
* @param bool $exit Should we exit after the module has been activated. Default to true.
* @param bool $redirect Should the user be redirected after module activation? Default to true.
*/
do_action( 'jetpack_pre_activate_module', $module, $exit, $redirect );
$jetpack = Jetpack::init();
if ( ! strlen( $module ) )
return false;
if ( ! Jetpack::is_module( $module ) )
return false;
// If it's already active, then don't do it again
$active = Jetpack::get_active_modules();
foreach ( $active as $act ) {
if ( $act == $module )
return true;
}
$module_data = Jetpack::get_module( $module );
if ( ! Jetpack::is_active() ) {
if ( !Jetpack::is_development_mode() )
return false;
// If we're not connected but in development mode, make sure the module doesn't require a connection
if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
return false;
}
// Check and see if the old plugin is active
if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
// Deactivate the old plugin
if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
// If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
// We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
Jetpack::state( 'deactivated_plugins', $module );
wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
exit;
}
}
// Protect won't work with mis-configured IPs
if ( 'protect' === $module ) {
include_once JETPACK__PLUGIN_DIR . 'modules/protect/shared-functions.php';
if ( ! jetpack_protect_get_ip() ) {
Jetpack::state( 'message', 'protect_misconfigured_ip' );
return false;
}
}
// Check the file for fatal errors, a la wp-admin/plugins.php::activate
Jetpack::state( 'module', $module );
Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
Jetpack::catch_errors( true );
ob_start();
require Jetpack::get_module_path( $module );
/** This action is documented in class.jetpack.php */
do_action( 'jetpack_activate_module', $module );
$active[] = $module;
Jetpack::update_active_modules( $active );
Jetpack::state( 'error', false ); // the override
ob_end_clean();
Jetpack::catch_errors( false );
// A flag for Jump Start so it's not shown again. Only set if it hasn't been yet.
if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
//Jump start is being dismissed send data to MC Stats
$jetpack->stat( 'jumpstart', 'manual,'.$module );
$jetpack->do_stats( 'server_side' );
}
if ( $redirect ) {
wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
}
if ( $exit ) {
exit;
}
return true;
}
function activate_module_actions( $module ) {
_deprecated_function( __METHOD__, 'jeptack-4.2' );
}
public static function deactivate_module( $module ) {
/**
* Fires when a module is deactivated.
*
* @since 1.9.0
*
* @param string $module Module slug.
*/
do_action( 'jetpack_pre_deactivate_module', $module );
$jetpack = Jetpack::init();
$active = Jetpack::get_active_modules();
$new = array_filter( array_diff( $active, (array) $module ) );
// A flag for Jump Start so it's not shown again.
if ( 'new_connection' === Jetpack_Options::get_option( 'jumpstart' ) ) {
Jetpack_Options::update_option( 'jumpstart', 'jetpack_action_taken' );
//Jump start is being dismissed send data to MC Stats
$jetpack->stat( 'jumpstart', 'manual,deactivated-'.$module );
$jetpack->do_stats( 'server_side' );
}
return self::update_active_modules( $new );
}
public static function enable_module_configurable( $module ) {
$module = Jetpack::get_module_slug( $module );
add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
}
public static function module_configuration_url( $module ) {
$module = Jetpack::get_module_slug( $module );
return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
}
public static function module_configuration_load( $module, $method ) {
$module = Jetpack::get_module_slug( $module );
add_action( 'jetpack_module_configuration_load_' . $module, $method );
}
public static function module_configuration_head( $module, $method ) {
$module = Jetpack::get_module_slug( $module );
add_action( 'jetpack_module_configuration_head_' . $module, $method );
}
public static function module_configuration_screen( $module, $method ) {
$module = Jetpack::get_module_slug( $module );
add_action( 'jetpack_module_configuration_screen_' . $module, $method );
}
public static function module_configuration_activation_screen( $module, $method ) {
$module = Jetpack::get_module_slug( $module );
add_action( 'display_activate_module_setting_' . $module, $method );
}
/* Installation */
public static function bail_on_activation( $message, $deactivate = true ) {
?>
<!doctype html>
<html>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<style>
* {