PageRenderTime 150ms CodeModel.GetById 25ms RepoModel.GetById 5ms app.codeStats 1ms

/class.jetpack.php

https://github.com/danielbachhuber/jetpack
PHP | 4763 lines | 3214 code | 652 blank | 897 comment | 604 complexity | 76bf47cc08d14c82a2a4519df6af89e2 MD5 | raw file
Possible License(s): GPL-2.0
  1. <?php
  2. /*
  3. Options:
  4. jetpack_options (array)
  5. An array of options.
  6. @see Jetpack_Options::get_option_names()
  7. jetpack_register (string)
  8. Temporary verification secrets.
  9. jetpack_activated (int)
  10. 1: the plugin was activated normally
  11. 2: the plugin was activated on this site because of a network-wide activation
  12. 3: the plugin was auto-installed
  13. 4: the plugin was manually disconnected (but is still installed)
  14. jetpack_active_modules (array)
  15. Array of active module slugs.
  16. jetpack_do_activate (bool)
  17. Flag for "activating" the plugin on sites where the activation hook never fired (auto-installs)
  18. */
  19. class Jetpack {
  20. var $xmlrpc_server = null;
  21. private $xmlrpc_verification = null;
  22. var $HTTP_RAW_POST_DATA = null; // copy of $GLOBALS['HTTP_RAW_POST_DATA']
  23. var $plugins_to_deactivate = array(
  24. 'stats' => array( 'stats/stats.php', 'WordPress.com Stats' ),
  25. 'shortlinks' => array( 'stats/stats.php', 'WordPress.com Stats' ),
  26. 'sharedaddy' => array( 'sharedaddy/sharedaddy.php', 'Sharedaddy' ),
  27. 'twitter-widget' => array( 'wickett-twitter-widget/wickett-twitter-widget.php', 'Wickett Twitter Widget' ),
  28. 'after-the-deadline' => array( 'after-the-deadline/after-the-deadline.php', 'After The Deadline' ),
  29. 'contact-form' => array( 'grunion-contact-form/grunion-contact-form.php', 'Grunion Contact Form' ),
  30. 'contact-form' => array( 'mullet/mullet-contact-form.php', 'Mullet Contact Form' ),
  31. 'custom-css' => array( 'safecss/safecss.php', 'WordPress.com Custom CSS' ),
  32. 'random-redirect' => array( 'random-redirect/random-redirect.php', 'Random Redirect' ),
  33. 'videopress' => array( 'video/video.php', 'VideoPress' ),
  34. 'widget-visibility' => array( 'jetpack-widget-visibility/widget-visibility.php', 'Jetpack Widget Visibility' ),
  35. 'widget-visibility' => array( 'widget-visibility-without-jetpack/widget-visibility-without-jetpack.php', 'Widget Visibility Without Jetpack' ),
  36. 'sharedaddy' => array( 'jetpack-sharing/sharedaddy.php', 'Jetpack Sharing' ),
  37. 'omnisearch' => array( 'jetpack-omnisearch/omnisearch.php', 'Jetpack Omnisearch' ),
  38. 'gravatar-hovercards' => array( 'jetpack-gravatar-hovercards/gravatar-hovercards.php', 'Jetpack Gravatar Hovercards' ),
  39. 'latex' => array( 'wp-latex/wp-latex.php', 'WP LaTeX' ),
  40. );
  41. var $capability_translations = array(
  42. 'administrator' => 'manage_options',
  43. 'editor' => 'edit_others_posts',
  44. 'author' => 'publish_posts',
  45. 'contributor' => 'edit_posts',
  46. 'subscriber' => 'read',
  47. );
  48. /**
  49. * Map of modules that have conflicts with plugins and should not be auto-activated
  50. * if the plugins are active. Used by filter_default_modules
  51. *
  52. * Plugin Authors: If you'd like to prevent a single module from auto-activating,
  53. * change `module-slug` and add this to your plugin:
  54. *
  55. * add_filter( 'jetpack_get_default_modules', 'my_jetpack_get_default_modules' );
  56. * function my_jetpack_get_default_modules( $modules ) {
  57. * return array_diff( $modules, array( 'module-slug' ) );
  58. * }
  59. *
  60. * @var array
  61. */
  62. private $conflicting_plugins = array(
  63. 'comments' => array(
  64. 'Intense Debate' => 'intensedebate/intensedebate.php',
  65. 'Disqus' => 'disqus-comment-system/disqus.php',
  66. 'Livefyre' => 'livefyre-comments/livefyre.php',
  67. 'Comments Evolved for WordPress' => 'gplus-comments/comments-evolved.php',
  68. 'Google+ Comments' => 'google-plus-comments/google-plus-comments.php',
  69. 'WP-SpamShield Anti-Spam' => 'wp-spamshield/wp-spamshield.php',
  70. ),
  71. 'contact-form' => array(
  72. 'Contact Form 7' => 'contact-form-7/wp-contact-form-7.php',
  73. 'Gravity Forms' => 'gravityforms/gravityforms.php',
  74. 'Contact Form Plugin' => 'contact-form-plugin/contact_form.php',
  75. 'Easy Contact Forms' => 'easy-contact-forms/easy-contact-forms.php',
  76. 'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
  77. ),
  78. 'gplus-authorship' => array(
  79. 'WP SEO by Yoast' => 'wordpress-seo/wp-seo.php',
  80. ),
  81. 'minileven' => array(
  82. 'WPtouch' => 'wptouch/wptouch.php',
  83. ),
  84. 'latex' => array(
  85. 'LaTeX for WordPress' => 'latex/latex.php',
  86. 'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
  87. 'Easy WP LaTeX' => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
  88. 'MathJax-LaTeX' => 'mathjax-latex/mathjax-latex.php',
  89. 'Enable Latex' => 'enable-latex/enable-latex.php',
  90. 'WP QuickLaTeX' => 'wp-quicklatex/wp-quicklatex.php',
  91. ),
  92. 'random-redirect' => array(
  93. 'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
  94. ),
  95. 'related-posts' => array(
  96. 'YARPP' => 'yet-another-related-posts-plugin/yarpp.php',
  97. 'WordPress Related Posts' => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
  98. 'nrelate Related Content' => 'nrelate-related-content/nrelate-related.php',
  99. 'Contextual Related Posts' => 'contextual-related-posts/contextual-related-posts.php',
  100. 'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
  101. 'outbrain' => 'outbrain/outbrain.php',
  102. 'Shareaholic' => 'shareaholic/shareaholic.php',
  103. 'Sexybookmarks' => 'sexybookmarks/shareaholic.php',
  104. ),
  105. 'sharedaddy' => array(
  106. 'AddThis' => 'addthis/addthis_social_widget.php',
  107. 'Add To Any' => 'add-to-any/add-to-any.php',
  108. 'ShareThis' => 'share-this/sharethis.php',
  109. 'Shareaholic' => 'shareaholic/shareaholic.php',
  110. ),
  111. 'verification-tools' => array(
  112. 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
  113. 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
  114. 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
  115. ),
  116. 'widget-visibility' => array(
  117. 'Widget Logic' => 'widget-logic/widget_logic.php',
  118. 'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
  119. ),
  120. );
  121. /**
  122. * Plugins for which we turn off our Facebook OG Tags implementation.
  123. *
  124. * Note: WordPress SEO by Yoast, WordPress SEO Premium by Yoast, All in One SEO Pack and All in One SEO Pack Pro automatically deactivate
  125. * Jetpack's Open Graph tags via filter when their Social Meta modules are active.
  126. *
  127. * Plugin authors: If you'd like to prevent Jetpack's Open Graph tag generation in your plugin, you can do so via this filter:
  128. * add_filter( 'jetpack_enable_open_graph', '__return_false' );
  129. */
  130. private $open_graph_conflicting_plugins = array(
  131. '2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
  132. // 2 Click Social Media Buttons
  133. 'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook
  134. 'add-meta-tags/add-meta-tags.php', // Add Meta Tags
  135. 'easy-facebook-share-thumbnails/esft.php', // Easy Facebook Share Thumbnail
  136. 'facebook/facebook.php', // Facebook (official plugin)
  137. 'facebook-awd/AWD_facebook.php', // Facebook AWD All in one
  138. 'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
  139. // Facebook Featured Image & OG Meta Tags
  140. 'facebook-meta-tags/facebook-metatags.php', // Facebook Meta Tags
  141. 'wonderm00ns-simple-facebook-open-graph-tags/wonderm00n-open-graph.php',
  142. // Facebook Open Graph Meta Tags for WordPress
  143. 'facebook-revised-open-graph-meta-tag/index.php', // Facebook Revised Open Graph Meta Tag
  144. 'facebook-thumb-fixer/_facebook-thumb-fixer.php', // Facebook Thumb Fixer
  145. 'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
  146. // Fedmich's Facebook Open Graph Meta
  147. 'header-footer/plugin.php', // Header and Footer
  148. 'network-publisher/networkpub.php', // Network Publisher
  149. 'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG
  150. 'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
  151. // NextScripts SNAP
  152. 'opengraph/opengraph.php', // Open Graph
  153. 'open-graph-protocol-framework/open-graph-protocol-framework.php',
  154. // Open Graph Protocol Framework
  155. 'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments
  156. 'seo-ultimate/seo-ultimate.php', // SEO Ultimate
  157. 'sexybookmarks/sexy-bookmarks.php', // Shareaholic
  158. 'shareaholic/sexy-bookmarks.php', // Shareaholic
  159. 'sharepress/sharepress.php', // SharePress
  160. 'simple-facebook-connect/sfc.php', // Simple Facebook Connect
  161. 'social-discussions/social-discussions.php', // Social Discussions
  162. 'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit
  163. 'socialize/socialize.php', // Socialize
  164. 'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
  165. // Tweet, Like, Google +1 and Share
  166. 'wordbooker/wordbooker.php', // Wordbooker
  167. 'wpsso/wpsso.php', // WordPress Social Sharing Optimization
  168. 'wp-caregiver/wp-caregiver.php', // WP Caregiver
  169. 'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
  170. // WP Facebook Like Send & Open Graph Meta
  171. 'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol
  172. 'wp-ogp/wp-ogp.php', // WP-OGP
  173. 'zoltonorg-social-plugin/zosp.php', // Zolton.org Social Plugin
  174. );
  175. /**
  176. * Plugins for which we turn off our Twitter Cards Tags implementation.
  177. */
  178. private $twitter_cards_conflicting_plugins = array(
  179. 'eewee-twitter-card/index.php', // Eewee Twitter Card
  180. 'ig-twitter-cards/ig-twitter-cards.php', // IG:Twitter Cards
  181. 'jm-twitter-cards/jm-twitter-cards.php', // JM Twitter Cards
  182. 'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
  183. // Pure Web Brilliant's Social Graph Twitter Cards Extension
  184. 'twitter-cards/twitter-cards.php', // Twitter Cards
  185. 'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
  186. 'wp-twitter-cards/twitter_cards.php', // WP Twitter Cards
  187. );
  188. /**
  189. * Message to display in admin_notice
  190. * @var string
  191. */
  192. var $message = '';
  193. /**
  194. * Error to display in admin_notice
  195. * @var string
  196. */
  197. var $error = '';
  198. /**
  199. * Modules that need more privacy description.
  200. * @var string
  201. */
  202. var $privacy_checks = '';
  203. /**
  204. * Stats to record once the page loads
  205. *
  206. * @var array
  207. */
  208. var $stats = array();
  209. /**
  210. * Jetpack_Sync object
  211. */
  212. var $sync;
  213. /**
  214. * Verified data for JSON authorization request
  215. */
  216. var $json_api_authorization_request = array();
  217. /**
  218. * Holds the singleton instance of this class
  219. * @since 2.3.3
  220. * @var Jetpack
  221. */
  222. static $instance = false;
  223. /**
  224. * Singleton
  225. * @static
  226. */
  227. public static function init() {
  228. if ( ! self::$instance ) {
  229. if ( did_action( 'plugins_loaded' ) )
  230. self::plugin_textdomain();
  231. else
  232. add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ), 99 );
  233. self::$instance = new Jetpack;
  234. self::$instance->plugin_upgrade();
  235. }
  236. return self::$instance;
  237. }
  238. /**
  239. * Must never be called statically
  240. */
  241. function plugin_upgrade() {
  242. // Upgrade: 1.1 -> 1.2
  243. if ( get_option( 'jetpack_id' ) ) {
  244. // Move individual jetpack options to single array of options
  245. $options = array();
  246. foreach ( Jetpack_Options::get_option_names() as $option ) {
  247. if ( false !== $value = get_option( "jetpack_$option" ) ) {
  248. $options[$option] = $value;
  249. }
  250. }
  251. if ( $options ) {
  252. Jetpack_Options::update_options( $options );
  253. foreach ( array_keys( $options ) as $option ) {
  254. delete_option( "jetpack_$option" );
  255. }
  256. }
  257. // Add missing version and old_version options
  258. if ( ! $version = Jetpack_Options::get_option( 'version' ) ) {
  259. $version = $old_version = '1.1:' . time();
  260. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  261. }
  262. }
  263. // Upgrade from a single user token to a user_id-indexed array and a master_user ID
  264. if ( ! Jetpack_Options::get_option( 'user_tokens' ) ) {
  265. if ( $user_token = Jetpack_Options::get_option( 'user_token' ) ) {
  266. $token_parts = explode( '.', $user_token );
  267. if ( isset( $token_parts[2] ) ) {
  268. $master_user = $token_parts[2];
  269. $user_tokens = array( $master_user => $user_token );
  270. Jetpack_Options::update_options( compact( 'master_user', 'user_tokens' ) );
  271. Jetpack_Options::delete_option( 'user_token' );
  272. } else {
  273. // @todo: is this even possible?
  274. trigger_error( sprintf( 'Jetpack::plugin_upgrade found no user_id in user_token "%s"', $user_token ), E_USER_WARNING );
  275. }
  276. }
  277. }
  278. }
  279. /**
  280. * Constructor. Initializes WordPress hooks
  281. */
  282. private function Jetpack() {
  283. /*
  284. * Check for and alert any deprecated hooks
  285. */
  286. add_action( 'init', array( $this, 'deprecated_hooks' ) );
  287. /*
  288. * Do things that should run even in the network admin
  289. * here, before we potentially fail out.
  290. */
  291. add_filter( 'jetpack_require_lib_dir', array( $this, 'require_lib_dir' ) );
  292. /*
  293. * Load things that should only be in Network Admin.
  294. *
  295. * For now blow away everything else until a more full
  296. * understanding of what is needed at the network level is
  297. * available
  298. */
  299. if( is_multisite() ) {
  300. Jetpack_Network::init();
  301. if( is_network_admin() )
  302. return; // End here to prevent single site actions from firing
  303. }
  304. $this->sync = new Jetpack_Sync;
  305. // Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
  306. // We access the "internal" method here only because the Jetpack object isn't instantiated yet
  307. $this->sync->options(
  308. JETPACK__PLUGIN_DIR . 'jetpack.php',
  309. 'home',
  310. 'siteurl',
  311. 'blogname',
  312. 'gmt_offset',
  313. 'timezone_string'
  314. );
  315. if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
  316. @ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
  317. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
  318. $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
  319. $this->require_jetpack_authentication();
  320. if ( Jetpack::is_active() ) {
  321. // Hack to preserve $HTTP_RAW_POST_DATA
  322. add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
  323. $signed = $this->verify_xml_rpc_signature();
  324. if ( $signed && ! is_wp_error( $signed ) ) {
  325. // The actual API methods.
  326. add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
  327. } else {
  328. add_filter( 'xmlrpc_methods', '__return_empty_array' );
  329. }
  330. } else {
  331. // The bootstrap API methods.
  332. add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
  333. }
  334. // Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
  335. add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
  336. } elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
  337. $this->require_jetpack_authentication();
  338. $this->add_remote_request_handlers();
  339. } else {
  340. if ( Jetpack::is_active() ) {
  341. add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
  342. }
  343. }
  344. if ( Jetpack::is_active() ) {
  345. Jetpack_Heartbeat::init();
  346. }
  347. add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
  348. if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
  349. wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
  350. }
  351. add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
  352. add_action( 'admin_menu', array( $this, 'admin_menu' ), 999 ); // run late so that other plugins hooking into this menu don't get left out
  353. add_action( 'admin_init', array( $this, 'admin_init' ) );
  354. add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
  355. add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
  356. add_action( 'wp_ajax_jetpack-check-news-subscription', array( $this, 'check_news_subscription' ) );
  357. add_action( 'wp_ajax_jetpack-subscribe-to-news', array( $this, 'subscribe_to_news' ) );
  358. add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
  359. add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
  360. add_action( 'wp_loaded', array( $this, 'register_assets' ) );
  361. add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
  362. add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
  363. add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
  364. // add_action( 'jetpack_admin_menu', array( $this, 'admin_menu_modules' ) );
  365. add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
  366. add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ), 100 );
  367. /**
  368. * These actions run checks to load additional files.
  369. * They check for external files or plugins, so they need to run as late as possible.
  370. */
  371. add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
  372. add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
  373. add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
  374. add_filter( 'plugins_url', array( 'Jetpack', 'maybe_min_asset' ), 1, 3 );
  375. add_filter( 'style_loader_tag', array( 'Jetpack', 'maybe_inline_style' ), 10, 2 );
  376. add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
  377. add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
  378. add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
  379. /**
  380. * This is the hack to concatinate all css files into one.
  381. * For description and reasoning see the implode_frontend_css method
  382. *
  383. * Super late priority so we catch all the registered styles
  384. */
  385. if( !is_admin() ) {
  386. add_action( 'wp_print_styles', array( $this, 'implode_frontend_css' ), -1 ); // Run first
  387. add_action( 'wp_print_footer_scripts', array( $this, 'implode_frontend_css' ), -1 ); // Run first to trigger before `print_late_styles`
  388. }
  389. }
  390. /**
  391. * If there are any stats that need to be pushed, but haven't been, push them now.
  392. */
  393. function __destruct() {
  394. if ( ! empty( $this->stats ) ) {
  395. $this->do_stats( 'server_side' );
  396. }
  397. }
  398. function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
  399. switch( $cap ) {
  400. case 'jetpack_connect' :
  401. case 'jetpack_reconnect' :
  402. if ( Jetpack::is_development_mode() ) {
  403. $caps = array( 'do_not_allow' );
  404. break;
  405. }
  406. /**
  407. * Pass through. If it's not development mode, these should match disconnect.
  408. * Let users disconnect if it's development mode, just in case things glitch.
  409. */
  410. case 'jetpack_disconnect' :
  411. /**
  412. * In multisite, can individual site admins manage their own connection?
  413. *
  414. * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
  415. */
  416. if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
  417. if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
  418. /**
  419. * We need to update the option name -- it's terribly unclear which
  420. * direction the override goes.
  421. *
  422. * @todo: Update the option name to `sub-sites-can-manage-own-connections`
  423. */
  424. $caps = array( 'do_not_allow' );
  425. break;
  426. }
  427. }
  428. $caps = array( 'manage_options' );
  429. break;
  430. case 'jetpack_manage_modules' :
  431. case 'jetpack_activate_modules' :
  432. case 'jetpack_deactivate_modules' :
  433. $caps = array( 'manage_options' );
  434. break;
  435. case 'jetpack_configure_modules' :
  436. $caps = array( 'manage_options' );
  437. break;
  438. case 'jetpack_admin_page' :
  439. if ( Jetpack::is_development_mode() ) {
  440. $caps = array( 'manage_options' );
  441. break;
  442. }
  443. /**
  444. * Pass through. If it's not development mode, these should match the admin page.
  445. * Let users disconnect if it's development mode, just in case things glitch.
  446. */
  447. case 'jetpack_connect_user' :
  448. if ( Jetpack::is_development_mode() ) {
  449. $caps = array( 'do_not_allow' );
  450. break;
  451. }
  452. $caps = array( 'read' );
  453. break;
  454. }
  455. return $caps;
  456. }
  457. function require_jetpack_authentication() {
  458. // Don't let anyone authenticate
  459. $_COOKIE = array();
  460. remove_all_filters( 'authenticate' );
  461. /**
  462. * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
  463. * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
  464. * generate false-positives.
  465. */
  466. remove_filter( 'wp_login_failed', 'limit_login_failed' );
  467. if ( Jetpack::is_active() ) {
  468. // Allow Jetpack authentication
  469. add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
  470. }
  471. }
  472. /**
  473. * Load language files
  474. */
  475. public static function plugin_textdomain() {
  476. // Note to self, the third argument must not be hardcoded, to account for relocated folders.
  477. load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( JETPACK__PLUGIN_FILE ) ) . '/languages/' );
  478. }
  479. /**
  480. * Register assets for use in various modules and the Jetpack admin page.
  481. *
  482. * @uses wp_script_is, wp_register_script, plugins_url
  483. * @action wp_loaded
  484. * @return null
  485. */
  486. public function register_assets() {
  487. if ( ! wp_script_is( 'spin', 'registered' ) ) {
  488. wp_register_script( 'spin', plugins_url( '_inc/spin.js', JETPACK__PLUGIN_FILE ), false, '1.3' );
  489. }
  490. if ( ! wp_script_is( 'jquery.spin', 'registered' ) ) {
  491. wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', JETPACK__PLUGIN_FILE ) , array( 'jquery', 'spin' ), '1.3' );
  492. }
  493. if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) ) {
  494. wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', JETPACK__PLUGIN_FILE ), array( 'media-views' ), '20121225' );
  495. }
  496. /**
  497. * As jetpack_register_genericons is by default fired off a hook,
  498. * the hook may have already fired by this point.
  499. * So, let's just trigger it manually.
  500. */
  501. require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
  502. jetpack_register_genericons();
  503. if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
  504. wp_register_style( 'jetpack-icons', plugins_url( 'css/jetpack-icons.min.css', JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION );
  505. }
  506. /**
  507. * Device Pixels support
  508. * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
  509. */
  510. function devicepx() {
  511. if ( Jetpack::is_active() ) {
  512. wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
  513. }
  514. }
  515. /*
  516. * Returns the location of Jetpack's lib directory. This filter is applied
  517. * in require_lib().
  518. *
  519. * @filter require_lib_dir
  520. */
  521. function require_lib_dir( $lib_dir ) {
  522. return JETPACK__PLUGIN_DIR . '_inc/lib';
  523. }
  524. /**
  525. * Is Jetpack active?
  526. */
  527. public static function is_active() {
  528. return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  529. }
  530. /**
  531. * Is Jetpack in development (offline) mode?
  532. */
  533. public static function is_development_mode() {
  534. $development_mode = false;
  535. if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
  536. $development_mode = JETPACK_DEV_DEBUG;
  537. }
  538. elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
  539. $development_mode = true;
  540. }
  541. return apply_filters( 'jetpack_development_mode', $development_mode );
  542. }
  543. /**
  544. * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
  545. */
  546. public static function is_user_connected( $user_id = false ) {
  547. $user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
  548. if ( ! $user_id ) {
  549. return false;
  550. }
  551. return (bool) Jetpack_Data::get_access_token( $user_id );
  552. }
  553. /**
  554. * Get the wpcom email of the current connected user.
  555. */
  556. public static function get_connected_user_email() {
  557. Jetpack::load_xml_rpc_client();
  558. $xml = new Jetpack_IXR_Client( array(
  559. 'user_id' => get_current_user_id()
  560. ) );
  561. $xml->query( 'wpcom.getUserEmail' );
  562. if ( ! $xml->isError() ) {
  563. return $xml->getResponse();
  564. }
  565. return false;
  566. }
  567. function current_user_is_connection_owner() {
  568. $user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  569. return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
  570. }
  571. /**
  572. * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
  573. */
  574. function extra_oembed_providers() {
  575. // Cloudup: https://dev.cloudup.com/#oembed
  576. wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
  577. }
  578. /**
  579. * Synchronize connected user role changes
  580. */
  581. function user_role_change( $user_id ) {
  582. if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
  583. $current_user_id = get_current_user_id();
  584. wp_set_current_user( $user_id );
  585. $role = $this->translate_current_user_to_role();
  586. $signed_role = $this->sign_role( $role );
  587. wp_set_current_user( $current_user_id );
  588. $master_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  589. $master_user_id = absint( $master_token->external_user_id );
  590. if ( ! $master_user_id )
  591. return; // this shouldn't happen
  592. Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
  593. //@todo retry on failure
  594. //try to choose a new master if we're demoting the current one
  595. if ( $user_id == $master_user_id && 'administrator' != $role ) {
  596. $query = new WP_User_Query(
  597. array(
  598. 'fields' => array( 'id' ),
  599. 'role' => 'administrator',
  600. 'orderby' => 'id',
  601. 'exclude' => array( $master_user_id ),
  602. )
  603. );
  604. $new_master = false;
  605. foreach ( $query->results as $result ) {
  606. $uid = absint( $result->id );
  607. if ( $uid && Jetpack::is_user_connected( $uid ) ) {
  608. $new_master = $uid;
  609. break;
  610. }
  611. }
  612. if ( $new_master ) {
  613. Jetpack_Options::update_option( 'master_user', $new_master );
  614. }
  615. // else disconnect..?
  616. }
  617. }
  618. }
  619. /**
  620. * Loads the currently active modules.
  621. */
  622. public static function load_modules() {
  623. if( !self::is_active() && !self::is_development_mode() ) {
  624. return;
  625. }
  626. $version = Jetpack_Options::get_option( 'version' );
  627. if ( ! $version ) {
  628. $version = $old_version = JETPACK__VERSION . ':' . time();
  629. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  630. }
  631. list( $version ) = explode( ':', $version );
  632. $modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
  633. $modules_data = array();
  634. // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
  635. if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
  636. $updated_modules = array();
  637. foreach ( $modules as $module ) {
  638. $modules_data[ $module ] = Jetpack::get_module( $module );
  639. if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
  640. continue;
  641. }
  642. if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
  643. continue;
  644. }
  645. $updated_modules[] = $module;
  646. }
  647. $modules = array_diff( $modules, $updated_modules );
  648. }
  649. $is_development_mode = Jetpack::is_development_mode();
  650. foreach ( $modules as $module ) {
  651. // If we're in dev mode, disable modules requiring a connection
  652. if ( $is_development_mode ) {
  653. // Prime the pump if we need to
  654. if ( empty( $modules_data[ $module ] ) ) {
  655. $modules_data[ $module ] = Jetpack::get_module( $module );
  656. }
  657. // If the module requires a connection, but we're in local mode, don't include it.
  658. if ( $modules_data[ $module ]['requires_connection'] ) {
  659. continue;
  660. }
  661. }
  662. if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
  663. continue;
  664. }
  665. require Jetpack::get_module_path( $module );
  666. do_action( 'jetpack_module_loaded_' . $module );
  667. }
  668. do_action( 'jetpack_modules_loaded' );
  669. // 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.
  670. if ( Jetpack::is_active() || Jetpack::is_development_mode() )
  671. require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
  672. }
  673. /**
  674. * Check if Jetpack's REST API compat file should be included
  675. * @action plugins_loaded
  676. * @return null
  677. */
  678. public function check_rest_api_compat() {
  679. $_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
  680. if ( function_exists( 'bbpress' ) )
  681. $_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
  682. foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
  683. require_once $_jetpack_rest_api_compat_include;
  684. }
  685. /**
  686. * Gets all plugins currently active in values, regardless of whether they're
  687. * traditionally activated or network activated.
  688. *
  689. * @todo Store the result in core's object cache maybe?
  690. */
  691. public static function get_active_plugins() {
  692. $active_plugins = (array) get_option( 'active_plugins', array() );
  693. if ( is_multisite() ) {
  694. // Due to legacy code, active_sitewide_plugins stores them in the keys,
  695. // whereas active_plugins stores them in the values.
  696. $network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
  697. if ( $network_plugins ) {
  698. $active_plugins = array_merge( $active_plugins, $network_plugins );
  699. }
  700. }
  701. sort( $active_plugins );
  702. return $active_plugins;
  703. }
  704. /**
  705. * Checks whether a specific plugin is active.
  706. *
  707. * We don't want to store these in a static variable, in case
  708. * there are switch_to_blog() calls involved.
  709. */
  710. public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
  711. return in_array( $plugin, self::get_active_plugins() );
  712. }
  713. /**
  714. * Check if Jetpack's Open Graph tags should be used.
  715. * If certain plugins are active, Jetpack's og tags are suppressed.
  716. *
  717. * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
  718. * @action plugins_loaded
  719. * @return null
  720. */
  721. public function check_open_graph() {
  722. if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
  723. add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
  724. }
  725. $active_plugins = self::get_active_plugins();
  726. if ( ! empty( $active_plugins ) ) {
  727. foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
  728. if ( in_array( $plugin, $active_plugins ) ) {
  729. add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
  730. break;
  731. }
  732. }
  733. }
  734. if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
  735. require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
  736. }
  737. }
  738. /**
  739. * Check if Jetpack's Twitter tags should be used.
  740. * If certain plugins are active, Jetpack's twitter tags are suppressed.
  741. *
  742. * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
  743. * @action plugins_loaded
  744. * @return null
  745. */
  746. public function check_twitter_tags() {
  747. $active_plugins = self::get_active_plugins();
  748. if ( ! empty( $active_plugins ) ) {
  749. foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
  750. if ( in_array( $plugin, $active_plugins ) ) {
  751. add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
  752. break;
  753. }
  754. }
  755. }
  756. if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
  757. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
  758. }
  759. }
  760. /* Jetpack Options API */
  761. public static function get_option_names( $type = 'compact' ) {
  762. return Jetpack_Options::get_option_names( $type );
  763. }
  764. /**
  765. * Returns the requested option. Looks in jetpack_options or jetpack_$name as appropriate.
  766. *
  767. * @param string $name Option name
  768. * @param mixed $default (optional)
  769. */
  770. public static function get_option( $name, $default = false ) {
  771. return Jetpack_Options::get_option( $name, $default );
  772. }
  773. /**
  774. * Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
  775. * Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
  776. * $name must be a registered option name.
  777. */
  778. public static function create_nonce( $name ) {
  779. $secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
  780. Jetpack_Options::update_option( $name, $secret );
  781. @list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
  782. if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
  783. return new Jetpack_Error( 'missing_secrets' );
  784. return array(
  785. 'secret_1' => $secret_1,
  786. 'secret_2' => $secret_2,
  787. 'eol' => $eol,
  788. );
  789. }
  790. /**
  791. * Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
  792. *
  793. * @param string $name Option name
  794. * @param mixed $value Option value
  795. */
  796. public static function update_option( $name, $value ) {
  797. return Jetpack_Options::update_option( $name, $value );
  798. }
  799. /**
  800. * Updates the multiple given options. Updates jetpack_options and/or jetpack_$name as appropriate.
  801. *
  802. * @param array $array array( option name => option value, ... )
  803. */
  804. public static function update_options( $array ) {
  805. return Jetpack_Options::update_options( $array );
  806. }
  807. /**
  808. * Deletes the given option. May be passed multiple option names as an array.
  809. * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
  810. *
  811. * @param string|array $names
  812. */
  813. public static function delete_option( $names ) {
  814. return Jetpack_Options::delete_option( $names );
  815. }
  816. /**
  817. * Enters a user token into the user_tokens option
  818. *
  819. * @param int $user_id
  820. * @param string $token
  821. * return bool
  822. */
  823. public static function update_user_token( $user_id, $token, $is_master_user ) {
  824. // not designed for concurrent updates
  825. $user_tokens = Jetpack_Options::get_option( 'user_tokens' );
  826. if ( ! is_array( $user_tokens ) )
  827. $user_tokens = array();
  828. $user_tokens[$user_id] = $token;
  829. if ( $is_master_user ) {
  830. $master_user = $user_id;
  831. $options = compact( 'user_tokens', 'master_user' );
  832. } else {
  833. $options = compact( 'user_tokens' );
  834. }
  835. return Jetpack_Options::update_options( $options );
  836. }
  837. /**
  838. * Returns an array of all PHP files in the specified absolute path.
  839. * Equivalent to glob( "$absolute_path/*.php" ).
  840. *
  841. * @param string $absolute_path The absolute path of the directory to search.
  842. * @return array Array of absolute paths to the PHP files.
  843. */
  844. public static function glob_php( $absolute_path ) {
  845. if ( function_exists( 'glob' ) ) {
  846. return glob( "$absolute_path/*.php" );
  847. }
  848. $absolute_path = untrailingslashit( $absolute_path );
  849. $files = array();
  850. if ( ! $dir = @opendir( $absolute_path ) ) {
  851. return $files;
  852. }
  853. while ( false !== $file = readdir( $dir ) ) {
  854. if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
  855. continue;
  856. }
  857. $file = "$absolute_path/$file";
  858. if ( ! is_file( $file ) ) {
  859. continue;
  860. }
  861. $files[] = $file;
  862. }
  863. closedir( $dir );
  864. return $files;
  865. }
  866. public function activate_new_modules() {
  867. if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
  868. return;
  869. }
  870. $jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
  871. if ( ! $jetpack_old_version ) {
  872. $jetpack_old_version = $version = $old_version = '1.1:' . time();
  873. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  874. }
  875. list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
  876. if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
  877. return;
  878. }
  879. $active_modules = Jetpack::get_active_modules();
  880. $reactivate_modules = array();
  881. foreach ( $active_modules as $active_module ) {
  882. $module = Jetpack::get_module( $active_module );
  883. if ( ! isset( $module['changed'] ) ) {
  884. continue;
  885. }
  886. if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
  887. continue;
  888. }
  889. $reactivate_modules[] = $active_module;
  890. Jetpack::deactivate_module( $active_module );
  891. }
  892. if ( version_compare( $jetpack_version, '1.9.2', '<' ) && version_compare( '1.9-something', JETPACK__VERSION, '<' ) ) {
  893. add_action( 'jetpack_activate_default_modules', array( $this->sync, 'sync_all_registered_options' ), 1000 );
  894. }
  895. Jetpack_Options::update_options(
  896. array(
  897. 'version' => JETPACK__VERSION . ':' . time(),
  898. 'old_version' => $jetpack_old_version,
  899. )
  900. );
  901. Jetpack::state( 'message', 'modules_activated' );
  902. Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
  903. $page = 'jetpack'; // make sure we redirect to either settings or the jetpack page
  904. if( isset( $_GET['page'] ) && in_array( $_GET['page'] , array( 'jetpack', 'jetpack_modules' ) ) ) {
  905. $page = $_GET['page'];
  906. }
  907. wp_safe_redirect( Jetpack::admin_url( 'page='.$page ) );
  908. exit;
  909. }
  910. /**
  911. * List available Jetpack modules. Simply lists .php files in /modules/.
  912. * Make sure to tuck away module "library" files in a sub-directory.
  913. */
  914. public static function get_available_modules( $min_version = false, $max_version = false ) {
  915. static $modules = null;
  916. if ( ! isset( $modules ) ) {
  917. $available_modules_option = Jetpack_Options::get_option( 'available_modules', array() );
  918. // Use the cache if we're on the front-end and it's available...
  919. if ( ! is_admin() && ! empty( $available_modules_option[ JETPACK__VERSION ] ) ) {
  920. $modules = $available_modules_option[ JETPACK__VERSION ];
  921. } else {
  922. $files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
  923. $modules = array();
  924. foreach ( $files as $file ) {
  925. if ( ! $headers = Jetpack::get_module( $file ) ) {
  926. continue;
  927. }
  928. $modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
  929. }
  930. Jetpack_Options::update_option( 'available_modules', array(
  931. JETPACK__VERSION => $modules,
  932. ) );
  933. }
  934. }
  935. $modules = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
  936. if ( ! $min_version && ! $max_version ) {
  937. return array_keys( $modules );
  938. }
  939. $r = array();
  940. foreach ( $modules as $slug => $introduced ) {
  941. if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
  942. continue;
  943. }
  944. if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
  945. continue;
  946. }
  947. $r[] = $slug;
  948. }
  949. return $r;
  950. }
  951. /**
  952. * Default modules loaded on activation.
  953. */
  954. public static function get_default_modules( $min_version = false, $max_version = false ) {
  955. $return = array();
  956. foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
  957. $module_data = Jetpack::get_module( $module );
  958. switch ( strtolower( $module_data['auto_activate'] ) ) {
  959. case 'yes' :
  960. $return[] = $module;
  961. break;
  962. case 'public' :
  963. if ( Jetpack_Options::get_option( 'public' ) ) {
  964. $return[] = $module;
  965. }
  966. break;
  967. case 'no' :
  968. default :
  969. break;
  970. }
  971. }
  972. return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
  973. }
  974. /**
  975. * Checks activated modules during auto-activation to determine
  976. * if any of those modules are being deprecated. If so, close
  977. * them out, and add any replacement modules.
  978. *
  979. * Runs at priority 99 by default.
  980. *
  981. * This is run late, so that it can still activate a module if
  982. * the new module is a replacement for another that the user
  983. * currently has active, even if something at the normal priority
  984. * would kibosh everything.
  985. *
  986. * @since 2.6
  987. * @uses jetpack_get_default_modules filter
  988. * @param array $modules
  989. * @return array
  990. */
  991. function handle_deprecated_modules( $modules ) {
  992. $deprecated_modules = array(
  993. 'debug' => null, // Closed out and moved to ./class.jetpack-debugger.php
  994. 'wpcc' => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
  995. );
  996. // Don't activate SSO if they never completed activating WPCC.
  997. if ( Jetpack::is_module_active( 'wpcc' ) ) {
  998. $wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
  999. if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
  1000. $deprecated_modules['wpcc'] = null;
  1001. }
  1002. }
  1003. foreach ( $deprecated_modules as $module => $replacement ) {
  1004. if ( Jetpack::is_module_active( $module ) ) {
  1005. self::deactivate_module( $module );
  1006. if ( $replacement ) {
  1007. $modules[] = $replacement;
  1008. }
  1009. }
  1010. }
  1011. return array_unique( $modules );
  1012. }
  1013. /**
  1014. * Checks activated plugins during auto-activation to determine
  1015. * if any of those plugins are in the list with a corresponding module
  1016. * that is not compatible with the plugin. The module will not be allowed
  1017. * to auto-activate.
  1018. *
  1019. * @since 2.6
  1020. * @uses jetpack_get_default_modules filter
  1021. * @param array $modules
  1022. * @return array
  1023. */
  1024. function filter_default_modules( $modules ) {
  1025. $active_plugins = self::get_active_plugins();
  1026. if ( ! empty( $active_plugins ) ) {
  1027. // For each module we'd like to auto-activate...
  1028. foreach ( $modules as $key => $module ) {
  1029. // If there are potential conflicts for it...
  1030. if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
  1031. // For each potential conflict...
  1032. foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
  1033. // If that conflicting plugin is active...
  1034. if ( in_array( $plugin, $active_plugins ) ) {
  1035. // Remove that item from being auto-activated.
  1036. unset( $modules[ $key ] );
  1037. }
  1038. }
  1039. }
  1040. }
  1041. }
  1042. return $modules;
  1043. }
  1044. /**
  1045. * Extract a module's slug from its full path.
  1046. */
  1047. public static function get_module_slug( $file ) {
  1048. return str_replace( '.php', '', basename( $file ) );
  1049. }
  1050. /**
  1051. * Generate a module's path from its slug.
  1052. */
  1053. public static function get_module_path( $slug ) {
  1054. return JETPACK__PLUGIN_DIR . "modules/$slug.php";
  1055. }
  1056. /**
  1057. * Load module data from module file. Headers differ from WordPress
  1058. * plugin headers to avoid them being identified as standalone
  1059. * plugins on the WordPress plugins page.
  1060. */
  1061. public static function get_module( $module ) {
  1062. $headers = array(
  1063. 'name' => 'Module Name',
  1064. 'description' => 'Module Description',
  1065. 'sort' => 'Sort Order',
  1066. 'introduced' => 'First Introduced',
  1067. 'changed' => 'Major Changes In',
  1068. 'deactivate' => 'Deactivate',
  1069. 'free' => 'Free',
  1070. 'requires_connection' => 'Requires Connection',
  1071. 'auto_activate' => 'Auto Activate',
  1072. 'module_tags' => 'Module Tags',
  1073. );
  1074. $file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
  1075. $mod = Jetpack::get_file_data( $file, $headers );
  1076. if ( empty( $mod['name'] ) ) {
  1077. return false;
  1078. }
  1079. $mod['name'] = translate( $mod['name'], 'jetpack' );
  1080. $mod['description'] = translate( $mod['description'], 'jetpack' );
  1081. $mod['sort'] = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
  1082. $mod['deactivate'] = empty( $mod['deactivate'] );
  1083. $mod['free'] = empty( $mod['free'] );
  1084. $mod['requires_connection'] = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
  1085. if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
  1086. $mod['auto_activate'] = 'No';
  1087. } else {
  1088. $mod['auto_activate'] = (string) $mod['auto_activate'];
  1089. }
  1090. if ( $mod['module_tags'] ) {
  1091. $mod['module_tags'] = explode( ',', $mod['module_tags'] );
  1092. $mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
  1093. $mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
  1094. } else {
  1095. $mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
  1096. }
  1097. return $mod;
  1098. }
  1099. /**
  1100. * Like core's get_file_data implementation, but caches the result.
  1101. */
  1102. public static function get_file_data( $file, $headers ) {
  1103. $file_data_option = Jetpack_Options::get_option( 'file_data', array() );
  1104. $key = md5( $file . serialize( $headers ) );
  1105. $refresh_cache = is_admin() && isset( $_GET['page'] ) && 'jetpack' === substr( $_GET['page'], 0, 7 );
  1106. // If we don't need to refresh the cache, and already have the value, short-circuit!
  1107. if ( ! $refresh_cache && isset( $file_data_option[ JETPACK__VERSION ][ $key ] ) ) {
  1108. return $file_data_option[ JETPACK__VERSION ][ $key ];
  1109. }
  1110. $data = get_file_data( $file, $headers );
  1111. // Strip out any old Jetpack versions that are cluttering the option.
  1112. $file_data_option = array_intersect_key( $file_data_option, array( JETPACK__VERSION => null ) );
  1113. $file_data_option[ JETPACK__VERSION ][ $key ] = $data;
  1114. Jetpack_Options::update_option( 'file_data', $file_data_option );
  1115. return $data;
  1116. }
  1117. public static function translate_module_tag( $untranslated_tag ) {
  1118. return _x( $untranslated_tag, 'Module Tag', 'jetpack' );
  1119. // Calls here are to populate translation files.
  1120. _x( 'Photos and Videos', 'Module Tag', 'jetpack' );
  1121. _x( 'Social', 'Module Tag', 'jetpack' );
  1122. _x( 'WordPress.com Stats', 'Module Tag', 'jetpack' );
  1123. _x( 'Writing', 'Module Tag', 'jetpack' );
  1124. _x( 'Appearance', 'Module Tag', 'jetpack' );
  1125. _x( 'Developers', 'Module Tag', 'jetpack' );
  1126. _x( 'Mobile', 'Module Tag', 'jetpack' );
  1127. _x( 'Other', 'Module Tag', 'jetpack' );
  1128. }
  1129. /**
  1130. * Get a list of activated modules as an array of module slugs.
  1131. */
  1132. public static function get_active_modules() {
  1133. $active = Jetpack_Options::get_option( 'active_modules' );
  1134. if ( ! is_array( $active ) )
  1135. $active = array();
  1136. if ( is_admin() ) {
  1137. $active[] = 'vaultpress';
  1138. } else {
  1139. $active = array_diff( $active, array( 'vaultpress' ) );
  1140. }
  1141. return array_unique( $active );
  1142. }
  1143. /**
  1144. * Check whether or not a Jetpack module is active.
  1145. *
  1146. * @param string $module The slug of a Jetpack module.
  1147. * @return bool
  1148. *
  1149. * @static
  1150. */
  1151. public static function is_module_active( $module ) {
  1152. return in_array( $module, self::get_active_modules() );
  1153. }
  1154. public static function is_module( $module ) {
  1155. return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
  1156. }
  1157. /**
  1158. * Catches PHP errors. Must be used in conjunction with output buffering.
  1159. *
  1160. * @param bool $catch True to start catching, False to stop.
  1161. *
  1162. * @static
  1163. */
  1164. public static function catch_errors( $catch ) {
  1165. static $display_errors, $error_reporting;
  1166. if ( $catch ) {
  1167. $display_errors = @ini_set( 'display_errors', 1 );
  1168. $error_reporting = @error_reporting( E_ALL );
  1169. add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
  1170. } else {
  1171. @ini_set( 'display_errors', $display_errors );
  1172. @error_reporting( $error_reporting );
  1173. remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 1 );
  1174. }
  1175. }
  1176. /**
  1177. * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
  1178. */
  1179. public static function catch_errors_on_shutdown() {
  1180. Jetpack::state( 'php_errors', ob_get_clean() );
  1181. }
  1182. public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array() ) {
  1183. $jetpack = Jetpack::init();
  1184. $modules = Jetpack::get_default_modules( $min_version, $max_version );
  1185. $modules = array_merge( $other_modules, $modules );
  1186. // Look for standalone plugins and disable if active.
  1187. $to_deactivate = array();
  1188. foreach ( $modules as $module ) {
  1189. if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
  1190. $to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
  1191. }
  1192. }
  1193. $deactivated = array();
  1194. foreach ( $to_deactivate as $module => $deactivate_me ) {
  1195. list( $probable_file, $probable_title ) = $deactivate_me;
  1196. if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
  1197. $deactivated[] = $module;
  1198. }
  1199. }
  1200. if ( $deactivated ) {
  1201. Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
  1202. $url = add_query_arg(
  1203. array(
  1204. 'action' => 'activate_default_modules',
  1205. '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
  1206. ),
  1207. add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
  1208. );
  1209. wp_safe_redirect( $url );
  1210. exit;
  1211. }
  1212. do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
  1213. // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
  1214. Jetpack::restate();
  1215. Jetpack::catch_errors( true );
  1216. $active = Jetpack::get_active_modules();
  1217. foreach ( $modules as $module ) {
  1218. if ( did_action( "jetpack_module_loaded_$module" ) ) {
  1219. $active[] = $module;
  1220. Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
  1221. continue;
  1222. }
  1223. if ( in_array( $module, $active ) ) {
  1224. $module_info = Jetpack::get_module( $module );
  1225. if ( ! $module_info['deactivate'] ) {
  1226. $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
  1227. if ( $active_state = Jetpack::state( $state ) ) {
  1228. $active_state = explode( ',', $active_state );
  1229. } else {
  1230. $active_state = array();
  1231. }
  1232. $active_state[] = $module;
  1233. Jetpack::state( $state, implode( ',', $active_state ) );
  1234. }
  1235. continue;
  1236. }
  1237. $file = Jetpack::get_module_path( $module );
  1238. if ( ! file_exists( $file ) ) {
  1239. continue;
  1240. }
  1241. // we'll override this later if the plugin can be included without fatal error
  1242. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  1243. Jetpack::state( 'error', 'module_activation_failed' );
  1244. Jetpack::state( 'module', $module );
  1245. ob_start();
  1246. require $file;
  1247. do_action( 'jetpack_activate_module', $module );
  1248. $active[] = $module;
  1249. $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
  1250. if ( $active_state = Jetpack::state( $state ) ) {
  1251. $active_state = explode( ',', $active_state );
  1252. } else {
  1253. $active_state = array();
  1254. }
  1255. $active_state[] = $module;
  1256. Jetpack::state( $state, implode( ',', $active_state ) );
  1257. Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
  1258. ob_end_clean();
  1259. }
  1260. Jetpack::state( 'error', false );
  1261. Jetpack::state( 'module', false );
  1262. Jetpack::catch_errors( false );
  1263. do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
  1264. }
  1265. public static function activate_module( $module, $exit = true, $redirect = true ) {
  1266. do_action( 'jetpack_pre_activate_module', $module, $exit );
  1267. $jetpack = Jetpack::init();
  1268. if ( ! strlen( $module ) )
  1269. return false;
  1270. if ( ! Jetpack::is_module( $module ) )
  1271. return false;
  1272. // If it's already active, then don't do it again
  1273. $active = Jetpack::get_active_modules();
  1274. foreach ( $active as $act ) {
  1275. if ( $act == $module )
  1276. return true;
  1277. }
  1278. $module_data = Jetpack::get_module( $module );
  1279. if ( ! Jetpack::is_active() ) {
  1280. if ( !Jetpack::is_development_mode() )
  1281. return false;
  1282. // If we're not connected but in development mode, make sure the module doesn't require a connection
  1283. if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
  1284. return false;
  1285. }
  1286. // Check and see if the old plugin is active
  1287. if ( isset( $jetpack->plugins_to_deactivate[ $module ] ) ) {
  1288. // Deactivate the old plugin
  1289. if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[ $module ][0], $jetpack->plugins_to_deactivate[ $module ][1] ) ) {
  1290. // If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
  1291. // We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
  1292. Jetpack::state( 'deactivated_plugins', $module );
  1293. wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
  1294. exit;
  1295. }
  1296. }
  1297. // Check the file for fatal errors, a la wp-admin/plugins.php::activate
  1298. Jetpack::state( 'module', $module );
  1299. Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
  1300. Jetpack::catch_errors( true );
  1301. ob_start();
  1302. require Jetpack::get_module_path( $module );
  1303. do_action( 'jetpack_activate_module', $module );
  1304. $active[] = $module;
  1305. Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
  1306. Jetpack::state( 'error', false ); // the override
  1307. Jetpack::state( 'message', 'module_activated' );
  1308. Jetpack::state( 'module', $module );
  1309. ob_end_clean();
  1310. Jetpack::catch_errors( false );
  1311. if ( $redirect ) {
  1312. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  1313. }
  1314. if ( $exit ) {
  1315. exit;
  1316. }
  1317. }
  1318. function activate_module_actions( $module ) {
  1319. do_action( "jetpack_activate_module_$module", $module );
  1320. $this->sync->sync_all_module_options( $module );
  1321. }
  1322. public static function deactivate_module( $module ) {
  1323. do_action( 'jetpack_pre_deactivate_module', $module );
  1324. $active = Jetpack::get_active_modules();
  1325. $new = array_filter( array_diff( $active, (array) $module ) );
  1326. do_action( "jetpack_deactivate_module_$module", $module );
  1327. return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
  1328. }
  1329. public static function enable_module_configurable( $module ) {
  1330. $module = Jetpack::get_module_slug( $module );
  1331. add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
  1332. }
  1333. public static function module_configuration_url( $module ) {
  1334. $module = Jetpack::get_module_slug( $module );
  1335. return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
  1336. }
  1337. public static function module_configuration_load( $module, $method ) {
  1338. $module = Jetpack::get_module_slug( $module );
  1339. add_action( 'jetpack_module_configuration_load_' . $module, $method );
  1340. }
  1341. public static function module_configuration_head( $module, $method ) {
  1342. $module = Jetpack::get_module_slug( $module );
  1343. add_action( 'jetpack_module_configuration_head_' . $module, $method );
  1344. }
  1345. public static function module_configuration_screen( $module, $method ) {
  1346. $module = Jetpack::get_module_slug( $module );
  1347. add_action( 'jetpack_module_configuration_screen_' . $module, $method );
  1348. }
  1349. /* Installation */
  1350. public static function bail_on_activation( $message, $deactivate = true ) {
  1351. ?>
  1352. <!doctype html>
  1353. <html>
  1354. <head>
  1355. <meta charset="<?php bloginfo( 'charset' ); ?>">
  1356. <style>
  1357. * {
  1358. text-align: center;
  1359. margin: 0;
  1360. padding: 0;
  1361. font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
  1362. }
  1363. p {
  1364. margin-top: 1em;
  1365. font-size: 18px;
  1366. }
  1367. </style>
  1368. <body>
  1369. <p><?php echo esc_html( $message ); ?></p>
  1370. </body>
  1371. </html>
  1372. <?php
  1373. if ( $deactivate ) {
  1374. $plugins = get_option( 'active_plugins' );
  1375. $jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
  1376. $update = false;
  1377. foreach ( $plugins as $i => $plugin ) {
  1378. if ( $plugin === $jetpack ) {
  1379. $plugins[$i] = false;
  1380. $update = true;
  1381. }
  1382. }
  1383. if ( $update ) {
  1384. update_option( 'active_plugins', array_filter( $plugins ) );
  1385. }
  1386. }
  1387. exit;
  1388. }
  1389. /**
  1390. * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
  1391. * @static
  1392. */
  1393. public static function plugin_activation( $network_wide ) {
  1394. Jetpack_Options::update_option( 'activated', 1 );
  1395. if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
  1396. Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
  1397. }
  1398. if ( $network_wide )
  1399. Jetpack::state( 'network_nag', true );
  1400. Jetpack::plugin_initialize();
  1401. }
  1402. /**
  1403. * Sets the internal version number and activation state.
  1404. * @static
  1405. */
  1406. public static function plugin_initialize() {
  1407. if ( ! Jetpack_Options::get_option( 'activated' ) ) {
  1408. Jetpack_Options::update_option( 'activated', 2 );
  1409. }
  1410. if ( ! Jetpack_Options::get_option( 'version' ) ) {
  1411. $version = $old_version = JETPACK__VERSION . ':' . time();
  1412. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  1413. }
  1414. Jetpack::load_modules();
  1415. Jetpack_Options::delete_option( 'do_activate' );
  1416. }
  1417. /**
  1418. * Removes all connection options
  1419. * @static
  1420. */
  1421. public static function plugin_deactivation( ) {
  1422. require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
  1423. if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
  1424. Jetpack_Network::init()->deactivate();
  1425. } else {
  1426. Jetpack::disconnect( false );
  1427. //Jetpack_Heartbeat::init()->deactivate();
  1428. }
  1429. }
  1430. /**
  1431. * Disconnects from the Jetpack servers.
  1432. * Forgets all connection details and tells the Jetpack servers to do the same.
  1433. * @static
  1434. */
  1435. public static function disconnect( $update_activated_state = true ) {
  1436. wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
  1437. Jetpack::clean_nonces( true );
  1438. Jetpack::load_xml_rpc_client();
  1439. $xml = new Jetpack_IXR_Client();
  1440. $xml->query( 'jetpack.deregister' );
  1441. Jetpack_Options::delete_option(
  1442. array(
  1443. 'register',
  1444. 'blog_token',
  1445. 'user_token',
  1446. 'user_tokens',
  1447. 'master_user',
  1448. 'time_diff',
  1449. 'fallback_no_verify_ssl_certs',
  1450. )
  1451. );
  1452. if ( $update_activated_state ) {
  1453. Jetpack_Options::update_option( 'activated', 4 );
  1454. }
  1455. // Disable the Heartbeat cron
  1456. Jetpack_Heartbeat::init()->deactivate();
  1457. }
  1458. /**
  1459. * Unlinks the current user from the linked WordPress.com user
  1460. */
  1461. public static function unlink_user( $user_id = null ) {
  1462. if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
  1463. return false;
  1464. $user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
  1465. if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
  1466. return false;
  1467. if ( ! isset( $tokens[ $user_id ] ) )
  1468. return false;
  1469. Jetpack::load_xml_rpc_client();
  1470. $xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
  1471. $xml->query( 'jetpack.unlink_user', $user_id );
  1472. unset( $tokens[ $user_id ] );
  1473. Jetpack_Options::update_option( 'user_tokens', $tokens );
  1474. return true;
  1475. }
  1476. /**
  1477. * Attempts Jetpack registration. If it fail, a state flag is set: @see ::admin_page_load()
  1478. */
  1479. public static function try_registration() {
  1480. $result = Jetpack::register();
  1481. // If there was an error with registration and the site was not registered, record this so we can show a message.
  1482. if ( ! $result || is_wp_error( $result ) ) {
  1483. return $result;
  1484. } else {
  1485. return true;
  1486. }
  1487. }
  1488. /**
  1489. * Tracking an internal event log. Try not to put too much chaff in here.
  1490. *
  1491. * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
  1492. */
  1493. public static function log( $code, $data = null ) {
  1494. $log = Jetpack_Options::get_option( 'log', array() );
  1495. // Append our event to the log
  1496. $log_entry = array(
  1497. 'time' => time(),
  1498. 'user_id' => get_current_user_id(),
  1499. 'blog_id' => Jetpack_Options::get_option( 'id' ),
  1500. 'code' => $code,
  1501. );
  1502. // Don't bother storing it unless we've got some.
  1503. if ( ! is_null( $data ) ) {
  1504. $log_entry['data'] = $data;
  1505. }
  1506. $log[] = $log_entry;
  1507. // Try add_option first, to make sure it's not autoloaded.
  1508. // @todo: Add an add_option method to Jetpack_Options
  1509. if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
  1510. Jetpack_Options::update_option( 'log', $log );
  1511. }
  1512. do_action( 'jetpack_log_entry', $log_entry );
  1513. }
  1514. /**
  1515. * Get the internal event log.
  1516. */
  1517. public static function get_log() {
  1518. return Jetpack_Options::get_option( 'log', array() );
  1519. }
  1520. /* Admin Pages */
  1521. function admin_init() {
  1522. // If the plugin is not connected, display a connect message.
  1523. if (
  1524. // the plugin was auto-activated and needs its candy
  1525. Jetpack_Options::get_option( 'do_activate' )
  1526. ||
  1527. // the plugin is active, but was never activated. Probably came from a site-wide network activation
  1528. ! Jetpack_Options::get_option( 'activated' )
  1529. ) {
  1530. Jetpack::plugin_initialize();
  1531. }
  1532. if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
  1533. if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
  1534. // Show connect notice on dashboard and plugins pages
  1535. add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
  1536. add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
  1537. }
  1538. } elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
  1539. // Upgrade: 1.1 -> 1.1.1
  1540. // Check and see if host can verify the Jetpack servers' SSL certificate
  1541. $args = array();
  1542. Jetpack_Client::_wp_remote_request(
  1543. Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
  1544. $args,
  1545. true
  1546. );
  1547. }
  1548. /* Toggle this off as it's not ready for prime time just yet.
  1549. if( current_user_can( 'manage_options' ) && self::check_identity_crisis() ) {
  1550. add_action( 'admin_notices', array( $this, 'alert_identity_crisis' ) );
  1551. }
  1552. /**/
  1553. if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
  1554. add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
  1555. }
  1556. add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
  1557. add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
  1558. add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
  1559. if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
  1560. // Artificially throw errors in certain whitelisted cases during plugin activation
  1561. add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
  1562. // Kick off synchronization of user role when it changes
  1563. add_action( 'set_user_role', array( $this, 'user_role_change' ) );
  1564. }
  1565. }
  1566. function admin_body_class( $admin_body_class = '' ) {
  1567. $classes = explode( ' ', trim( $admin_body_class ) );
  1568. $classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
  1569. return implode( ' ', array_unique( $classes ) );
  1570. }
  1571. static function add_jetpack_pagestyles( $admin_body_class = '' ) {
  1572. return $admin_body_class . ' jetpack-pagestyles';
  1573. }
  1574. function prepare_connect_notice() {
  1575. add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
  1576. add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
  1577. if ( Jetpack::state( 'network_nag' ) )
  1578. add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
  1579. }
  1580. /**
  1581. * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
  1582. * This function artificially throws errors for such cases (whitelisted).
  1583. *
  1584. * @param string $plugin The activated plugin.
  1585. */
  1586. function throw_error_on_activate_plugin( $plugin ) {
  1587. $active_modules = Jetpack::get_active_modules();
  1588. // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
  1589. if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
  1590. $throw = false;
  1591. // Try and make sure it really was the stats plugin
  1592. if ( ! class_exists( 'ReflectionFunction' ) ) {
  1593. if ( 'stats.php' == basename( $plugin ) ) {
  1594. $throw = true;
  1595. }
  1596. } else {
  1597. $reflection = new ReflectionFunction( 'stats_get_api_key' );
  1598. if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
  1599. $throw = true;
  1600. }
  1601. }
  1602. if ( $throw ) {
  1603. trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
  1604. }
  1605. }
  1606. }
  1607. function intercept_plugin_error_scrape_init() {
  1608. add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
  1609. }
  1610. function intercept_plugin_error_scrape( $action, $result ) {
  1611. if ( ! $result ) {
  1612. return;
  1613. }
  1614. foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
  1615. if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
  1616. Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
  1617. }
  1618. }
  1619. }
  1620. function admin_menu() {
  1621. list( $jetpack_version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
  1622. if (
  1623. $jetpack_version
  1624. &&
  1625. $jetpack_version != JETPACK__VERSION
  1626. &&
  1627. ( $new_modules = Jetpack::get_default_modules( $jetpack_version, JETPACK__VERSION ) )
  1628. &&
  1629. is_array( $new_modules )
  1630. &&
  1631. ( $new_modules_count = count( $new_modules ) )
  1632. &&
  1633. ( Jetpack::is_active() || Jetpack::is_development_mode() )
  1634. ) {
  1635. $new_modules_count_i18n = number_format_i18n( $new_modules_count );
  1636. $span_title = esc_attr( sprintf( _n( 'One New Jetpack Module', '%s New Jetpack Modules', $new_modules_count, 'jetpack' ), $new_modules_count_i18n ) );
  1637. $title = sprintf( 'Jetpack %s', "<span class='update-plugins count-{$new_modules_count}' title='$span_title'><span class='update-count'>$new_modules_count_i18n</span></span>" );
  1638. } else {
  1639. $title = __( 'Jetpack', 'jetpack' );
  1640. }
  1641. $hook = add_menu_page( 'Jetpack', $title, 'read', 'jetpack', array( $this, 'admin_page' ), 'div' );
  1642. $debugger_hook = add_submenu_page( null, __( 'Jetpack Debugging Center', 'jetpack' ), '', 'manage_options', 'jetpack-debugger', array( $this, 'debugger_page' ) );
  1643. add_action( "admin_head-$debugger_hook", array( 'Jetpack_Debugger', 'jetpack_debug_admin_head' ) );
  1644. add_action( "load-$hook", array( $this, 'admin_page_load' ) );
  1645. add_action( "load-$hook", array( $this, 'admin_help' ) );
  1646. add_action( "admin_head-$hook", array( $this, 'admin_head' ) );
  1647. add_filter( 'custom_menu_order', array( $this, 'admin_menu_order' ) );
  1648. add_filter( 'menu_order', array( $this, 'jetpack_menu_order' ) );
  1649. add_action( "admin_print_styles-$hook", array( $this, 'admin_styles' ) );
  1650. add_action( "admin_print_scripts-$hook", array( $this, 'admin_scripts' ) );
  1651. do_action( 'jetpack_admin_menu', $hook );
  1652. }
  1653. function add_remote_request_handlers() {
  1654. add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
  1655. }
  1656. function remote_request_handlers() {
  1657. switch ( current_filter() ) {
  1658. case 'wp_ajax_nopriv_jetpack_upload_file' :
  1659. $response = $this->upload_handler();
  1660. break;
  1661. default :
  1662. $response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
  1663. break;
  1664. }
  1665. if ( ! $response ) {
  1666. $response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
  1667. }
  1668. if ( is_wp_error( $response ) ) {
  1669. $status_code = $response->get_error_data();
  1670. $error = $response->get_error_code();
  1671. $error_description = $response->get_error_message();
  1672. if ( ! is_int( $status_code ) ) {
  1673. $status_code = 400;
  1674. }
  1675. status_header( $status_code );
  1676. die( json_encode( (object) compact( 'error', 'error_description' ) ) );
  1677. }
  1678. status_header( 200 );
  1679. if ( true === $response ) {
  1680. exit;
  1681. }
  1682. die( json_encode( (object) $response ) );
  1683. }
  1684. function upload_handler() {
  1685. if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
  1686. return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
  1687. }
  1688. $user = wp_authenticate( '', '' );
  1689. if ( ! $user || is_wp_error( $user ) ) {
  1690. return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
  1691. }
  1692. wp_set_current_user( $user->ID );
  1693. if ( ! current_user_can( 'upload_files' ) ) {
  1694. return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
  1695. }
  1696. if ( empty( $_FILES ) ) {
  1697. return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
  1698. }
  1699. foreach ( array_keys( $_FILES ) as $files_key ) {
  1700. if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
  1701. return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
  1702. }
  1703. }
  1704. $media_keys = array_keys( $_FILES['media'] );
  1705. $token = Jetpack_Data::get_access_token( get_current_user_id() );
  1706. if ( ! $token || is_wp_error( $token ) ) {
  1707. return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
  1708. }
  1709. $uploaded_files = array();
  1710. $global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
  1711. unset( $GLOBALS['post'] );
  1712. foreach ( $_FILES['media']['name'] as $index => $name ) {
  1713. $file = array();
  1714. foreach ( $media_keys as $media_key ) {
  1715. $file[$media_key] = $_FILES['media'][$media_key][$index];
  1716. }
  1717. list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
  1718. $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
  1719. if ( $hmac_provided !== $hmac_file ) {
  1720. $uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
  1721. continue;
  1722. }
  1723. $_FILES['.jetpack.upload.'] = $file;
  1724. $post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
  1725. if ( ! current_user_can( 'edit_post', $post_id ) ) {
  1726. $post_id = 0;
  1727. }
  1728. $attachment_id = media_handle_upload(
  1729. '.jetpack.upload.',
  1730. $post_id,
  1731. array(),
  1732. array(
  1733. 'action' => 'jetpack_upload_file',
  1734. )
  1735. );
  1736. if ( ! $attachment_id ) {
  1737. $uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
  1738. } elseif ( is_wp_error( $attachment_id ) ) {
  1739. $uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
  1740. } else {
  1741. $attachment = get_post( $attachment_id );
  1742. $uploaded_files[$index] = (object) array(
  1743. 'id' => (string) $attachment_id,
  1744. 'file' => $attachment->post_title,
  1745. 'url' => wp_get_attachment_url( $attachment_id ),
  1746. 'type' => $attachment->post_mime_type,
  1747. 'meta' => wp_get_attachment_metadata( $attachment_id ),
  1748. );
  1749. }
  1750. }
  1751. if ( ! is_null( $global_post ) ) {
  1752. $GLOBALS['post'] = $global_post;
  1753. }
  1754. return $uploaded_files;
  1755. }
  1756. /**
  1757. * Add help to the Jetpack page
  1758. *
  1759. * @since Jetpack (1.2.3)
  1760. * @return false if not the Jetpack page
  1761. */
  1762. function admin_help() {
  1763. $current_screen = get_current_screen();
  1764. // Overview
  1765. $current_screen->add_help_tab(
  1766. array(
  1767. 'id' => 'home',
  1768. 'title' => __( 'Home', 'jetpack' ),
  1769. 'content' =>
  1770. '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
  1771. '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
  1772. '<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>',
  1773. )
  1774. );
  1775. // Screen Content
  1776. if ( current_user_can( 'manage_options' ) ) {
  1777. $current_screen->add_help_tab(
  1778. array(
  1779. 'id' => 'settings',
  1780. 'title' => __( 'Settings', 'jetpack' ),
  1781. 'content' =>
  1782. '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
  1783. '<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
  1784. '<ol>' .
  1785. '<li>' . __( 'Each module has an Activate or Deactivate link so you can toggle one individually.', 'jetpack' ) . '</li>' .
  1786. '<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>' .
  1787. '</ol>' .
  1788. '<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>'
  1789. )
  1790. );
  1791. }
  1792. // Help Sidebar
  1793. $current_screen->set_help_sidebar(
  1794. '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
  1795. '<p><a href="http://jetpack.me/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
  1796. '<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
  1797. '<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
  1798. );
  1799. }
  1800. function admin_menu_css() {
  1801. wp_enqueue_style( 'jetpack-icons' );
  1802. }
  1803. function admin_menu_order() {
  1804. return true;
  1805. }
  1806. function jetpack_menu_order( $menu_order ) {
  1807. $jp_menu_order = array();
  1808. foreach ( $menu_order as $index => $item ) {
  1809. if ( $item != 'jetpack' )
  1810. $jp_menu_order[] = $item;
  1811. if ( $index == 0 )
  1812. $jp_menu_order[] = 'jetpack';
  1813. }
  1814. return $jp_menu_order;
  1815. }
  1816. function admin_head() {
  1817. if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
  1818. do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
  1819. }
  1820. function admin_banner_styles() {
  1821. global $wp_styles;
  1822. $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
  1823. wp_enqueue_style( 'jetpack', plugins_url( "css/jetpack-banners{$min}.css", JETPACK__PLUGIN_FILE ), false, JETPACK__VERSION . '-20121016' );
  1824. $wp_styles->add_data( 'jetpack', 'rtl', true );
  1825. }
  1826. function admin_scripts() {
  1827. wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', JETPACK__PLUGIN_FILE ), array( 'jquery', 'wp-util' ), JETPACK__VERSION . '-20121111' );
  1828. wp_localize_script(
  1829. 'jetpack-js',
  1830. 'jetpackL10n',
  1831. array(
  1832. 'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
  1833. 'ays_unlink' => "This will prevent user-specific modules such as Publicize, Notifications and Post By Email from working.\nAre you sure you want to unlink?",
  1834. 'ays_dismiss' => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
  1835. )
  1836. );
  1837. add_action( 'admin_footer', array( $this, 'do_stats' ) );
  1838. }
  1839. function plugin_action_links( $actions ) {
  1840. $jetpack_home = array( 'jetpack-home' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack' ), __( 'Jetpack', 'jetpack' ) ) );
  1841. if( current_user_can( 'jetpack_manage_modules' ) && ( Jetpack::is_active() || Jetpack::is_development_mode() ) ) {
  1842. return array_merge(
  1843. $jetpack_home,
  1844. array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url( 'page=jetpack_modules' ), __( 'Settings', 'jetpack' ) ) ),
  1845. $actions
  1846. );
  1847. }
  1848. return array_merge( $jetpack_home, $actions );
  1849. }
  1850. function admin_connect_notice() {
  1851. // Don't show the connect notice on the jetpack settings page. @todo: must be a better way?
  1852. if ( false !== strpos( $_SERVER['QUERY_STRING'], 'page=jetpack' ) )
  1853. return;
  1854. if ( ! current_user_can( 'jetpack_connect' ) )
  1855. return;
  1856. $dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
  1857. ?>
  1858. <div id="message" class="updated jetpack-message jp-connect" style="display:block !important;">
  1859. <div id="jp-dismiss" class="jetpack-close-button-container">
  1860. <a class="jetpack-close-button" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>" title="<?php _e( 'Dismiss this notice and deactivate Jetpack.', 'jetpack' ); ?>"></a>
  1861. </div>
  1862. <div class="jetpack-wrap-container">
  1863. <div class="jetpack-install-container">
  1864. <?php if ( 1 == Jetpack_Options::get_option( 'activated' ) ) : ?>
  1865. <p class="submit"><a href="<?php echo $this->build_connect_url() ?>" class="download-jetpack" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a></p>
  1866. <?php else : ?>
  1867. <p class="submit"><a href="<?php echo Jetpack::admin_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a></p>
  1868. <?php endif; ?>
  1869. </div>
  1870. <div class="jetpack-text-container">
  1871. <?php if ( 1 == Jetpack_Options::get_option( 'activated' ) ) : ?>
  1872. <p><?php _e( '<strong>Your Jetpack is almost ready!</strong>', 'jetpack' ); ?></p>
  1873. <p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
  1874. <?php else : ?>
  1875. <p><?php _e( '<strong>Jetpack is installed</strong>', 'jetpack' ) ?></p>
  1876. <p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
  1877. <?php endif; ?>
  1878. </div>
  1879. </div>
  1880. </div>
  1881. <?php
  1882. }
  1883. function network_connect_notice() {
  1884. ?>
  1885. <div id="message" class="updated jetpack-message">
  1886. <div class="squeezer">
  1887. <h4><?php _e( '<strong>Jetpack is activated!</strong> Each site on your network must be connected individually by an admin on that site.', 'jetpack' ) ?></h4>
  1888. </div>
  1889. </div>
  1890. <?php
  1891. }
  1892. public static function jetpack_comment_notice() {
  1893. if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
  1894. return '';
  1895. }
  1896. $jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
  1897. $jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
  1898. if ( $jetpack_old_version ) {
  1899. if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
  1900. return '';
  1901. }
  1902. }
  1903. if ( $jetpack_new_version ) {
  1904. if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
  1905. return '';
  1906. }
  1907. }
  1908. return '<br /><br />' . sprintf(
  1909. __( 'Jetpack now includes Jetpack Comments, which enables your visitors to use their WordPress.com, Twitter, or Facebook accounts when commenting on your site. To activate Jetpack Comments, <a href="%s">%s</a>.', 'jetpack' ),
  1910. wp_nonce_url(
  1911. Jetpack::admin_url(
  1912. array(
  1913. 'page' => 'jetpack',
  1914. 'action' => 'activate',
  1915. 'module' => 'comments',
  1916. )
  1917. ),
  1918. 'jetpack_activate-comments'
  1919. ),
  1920. __( 'click here', 'jetpack' )
  1921. );
  1922. }
  1923. /*
  1924. * Registration flow:
  1925. * 1 - ::admin_page_load() action=register
  1926. * 2 - ::try_registration()
  1927. * 3 - ::register()
  1928. * - Creates jetpack_register option containing two secrets and a timestamp
  1929. * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
  1930. * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
  1931. * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
  1932. * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
  1933. * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
  1934. * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
  1935. * jetpack_id, jetpack_secret, jetpack_public
  1936. * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
  1937. * 4 - redirect to https://jetpack.wordpress.com/jetpack.authorize/1/
  1938. * 5 - user logs in with WP.com account
  1939. * 6 - redirect to this site's wp-admin/index.php?page=jetpack&action=authorize with
  1940. * code <-- OAuth2 style authorization code
  1941. * 7 - ::admin_page_load() action=authorize
  1942. * 8 - Jetpack_Client_Server::authorize()
  1943. * 9 - Jetpack_Client_Server::get_token()
  1944. * 10- GET https://jetpack.wordpress.com/jetpack.token/1/ with
  1945. * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
  1946. * 11- which responds with
  1947. * access_token, token_type, scope
  1948. * 12- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
  1949. * 13- Jetpack::activate_default_modules()
  1950. * Deactivates deprecated plugins
  1951. * Activates all default modules
  1952. * Catches errors: redirects to wp-admin/index.php?page=jetpack state:error=something
  1953. * 14- redirect to this site's wp-admin/index.php?page=jetpack with state:message=authorized
  1954. * Done!
  1955. */
  1956. /**
  1957. * Handles the page load events for the Jetpack admin page
  1958. */
  1959. function admin_page_load() {
  1960. $error = false;
  1961. // Make sure we have the right body class to hook stylings for subpages off of.
  1962. add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
  1963. if ( ! empty( $_GET['jetpack_restate'] ) ) {
  1964. // Should only be used in intermediate redirects to preserve state across redirects
  1965. Jetpack::restate();
  1966. }
  1967. if ( isset( $_GET['connect_url_redirect'] ) ) {
  1968. // User clicked in the iframe to link their accounts
  1969. if ( ! Jetpack::is_user_connected() ) {
  1970. $connect_url = $this->build_connect_url( true );
  1971. if ( isset( $_GET['notes_iframe'] ) )
  1972. $connect_url .= '&notes_iframe';
  1973. wp_redirect( $connect_url );
  1974. exit;
  1975. } else {
  1976. Jetpack::state( 'message', 'already_authorized' );
  1977. wp_safe_redirect( Jetpack::admin_url() );
  1978. exit;
  1979. }
  1980. }
  1981. if ( isset( $_GET['action'] ) ) {
  1982. switch ( $_GET['action'] ) {
  1983. case 'authorize' :
  1984. if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
  1985. Jetpack::state( 'message', 'already_authorized' );
  1986. wp_safe_redirect( Jetpack::admin_url() );
  1987. exit;
  1988. }
  1989. Jetpack::log( 'authorize' );
  1990. $client_server = new Jetpack_Client_Server;
  1991. $client_server->authorize();
  1992. exit;
  1993. case 'register' :
  1994. check_admin_referer( 'jetpack-register' );
  1995. Jetpack::log( 'register' );
  1996. Jetpack::maybe_set_version_option();
  1997. $registered = Jetpack::try_registration();
  1998. if ( is_wp_error( $registered ) ) {
  1999. $error = $registered->get_error_code();
  2000. Jetpack::state( 'error_description', $registered->get_error_message() );
  2001. break;
  2002. }
  2003. wp_redirect( $this->build_connect_url( true ) );
  2004. exit;
  2005. case 'activate' :
  2006. if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
  2007. $error = 'cheatin';
  2008. break;
  2009. }
  2010. $module = stripslashes( $_GET['module'] );
  2011. check_admin_referer( "jetpack_activate-$module" );
  2012. Jetpack::log( 'activate', $module );
  2013. Jetpack::activate_module( $module );
  2014. // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
  2015. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  2016. exit;
  2017. case 'activate_default_modules' :
  2018. check_admin_referer( 'activate_default_modules' );
  2019. Jetpack::log( 'activate_default_modules' );
  2020. Jetpack::restate();
  2021. $min_version = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
  2022. $max_version = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
  2023. $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
  2024. Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
  2025. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  2026. exit;
  2027. case 'disconnect' :
  2028. if ( ! current_user_can( 'jetpack_disconnect' ) ) {
  2029. $error = 'cheatin';
  2030. break;
  2031. }
  2032. check_admin_referer( 'jetpack-disconnect' );
  2033. Jetpack::log( 'disconnect' );
  2034. Jetpack::disconnect();
  2035. wp_safe_redirect( Jetpack::admin_url() );
  2036. exit;
  2037. case 'reconnect' :
  2038. if ( ! current_user_can( 'jetpack_reconnect' ) ) {
  2039. $error = 'cheatin';
  2040. break;
  2041. }
  2042. check_admin_referer( 'jetpack-reconnect' );
  2043. Jetpack::log( 'reconnect' );
  2044. $this->disconnect();
  2045. wp_redirect( $this->build_connect_url( true ) );
  2046. exit;
  2047. case 'deactivate' :
  2048. if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
  2049. $error = 'cheatin';
  2050. break;
  2051. }
  2052. $modules = stripslashes( $_GET['module'] );
  2053. check_admin_referer( "jetpack_deactivate-$modules" );
  2054. foreach ( explode( ',', $modules ) as $module ) {
  2055. Jetpack::log( 'deactivate', $module );
  2056. Jetpack::deactivate_module( $module );
  2057. Jetpack::state( 'message', 'module_deactivated' );
  2058. }
  2059. Jetpack::state( 'module', $modules );
  2060. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  2061. exit;
  2062. case 'unlink' :
  2063. check_admin_referer( 'jetpack-unlink' );
  2064. Jetpack::log( 'unlink' );
  2065. $this->unlink_user();
  2066. Jetpack::state( 'message', 'unlinked' );
  2067. wp_safe_redirect( Jetpack::admin_url() );
  2068. exit;
  2069. default:
  2070. do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
  2071. }
  2072. }
  2073. if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
  2074. $this->activate_new_modules();
  2075. }
  2076. switch ( $error ) {
  2077. case 'cheatin' :
  2078. $this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
  2079. break;
  2080. case 'access_denied' :
  2081. $this->error = __( 'You need to authorize the Jetpack connection between your site and WordPress.com to enable the awesome features.', 'jetpack' );
  2082. break;
  2083. case 'wrong_state' :
  2084. $this->error = __( 'Don&#8217;t cross the streams! You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
  2085. break;
  2086. case 'invalid_client' :
  2087. // @todo re-register instead of deactivate/reactivate
  2088. $this->error = __( 'Return to sender. Whoops! It looks like you got the wrong Jetpack in the mail; deactivate then reactivate the Jetpack plugin to get a new one.', 'jetpack' );
  2089. break;
  2090. case 'invalid_grant' :
  2091. $this->error = __( 'Wrong size. Hm&#8230; it seems your Jetpack doesn&#8217;t quite fit. Have you lost weight? Click &#8220;Connect to WordPress.com&#8221; again to get your Jetpack adjusted.', 'jetpack' );
  2092. break;
  2093. case 'site_inaccessible' :
  2094. case 'site_requires_authorization' :
  2095. $this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
  2096. break;
  2097. case 'module_activation_failed' :
  2098. $module = Jetpack::state( 'module' );
  2099. if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
  2100. $this->error = sprintf( __( '%s could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' ), $mod['name'] );
  2101. if ( isset( $this->plugins_to_deactivate[$module] ) ) {
  2102. $this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
  2103. }
  2104. } else {
  2105. $this->error = __( 'Module could not be activated because it triggered a <strong>fatal error</strong>. Perhaps there is a conflict with another plugin you have installed?', 'jetpack' );
  2106. }
  2107. if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
  2108. $this->error .= "<br />\n";
  2109. $this->error .= $php_errors;
  2110. }
  2111. break;
  2112. case 'master_user_required' :
  2113. $module = Jetpack::state( 'module' );
  2114. $module_name = '';
  2115. if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
  2116. $module_name = $mod['name'];
  2117. }
  2118. $master_user = Jetpack_Options::get_option( 'master_user' );
  2119. $master_userdata = get_userdata( $master_user ) ;
  2120. if ( $master_userdata ) {
  2121. if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
  2122. $this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
  2123. } else {
  2124. $this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
  2125. }
  2126. $this->error .= ' ' . sprintf( __( 'This module can only be altered by %s, the user who initiated the Jetpack connection on this site.' , 'jetpack' ), esc_html( $master_userdata->display_name ) );
  2127. } else {
  2128. $this->error = sprintf( __( 'Only the user who initiated the Jetpack connection on this site can toggle %s, but that user no longer exists. This should not happen.', 'jetpack' ), $module_name );
  2129. }
  2130. break;
  2131. case 'not_public' :
  2132. $this->error = __( '<strong>Your Jetpack has a glitch.</strong> Connecting this site with WordPress.com is not possible. This usually means your site is not publicly accessible (localhost).', 'jetpack' );
  2133. break;
  2134. case 'wpcom_408' :
  2135. case 'wpcom_5??' :
  2136. case 'wpcom_bad_response' :
  2137. case 'wpcom_outage' :
  2138. $this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack. Please try again later.', 'jetpack' );
  2139. break;
  2140. case 'register_http_request_failed' :
  2141. case 'token_http_request_failed' :
  2142. $this->error = sprintf( __( 'Jetpack could not contact WordPress.com: %s. This usually means something is incorrectly configured on your web host.', 'jetpack' ), "<code>$error</code>" );
  2143. break;
  2144. default :
  2145. if ( empty( $error ) ) {
  2146. break;
  2147. }
  2148. $error = trim( substr( strip_tags( $error ), 0, 20 ) );
  2149. // no break: fall through
  2150. case 'no_role' :
  2151. case 'no_cap' :
  2152. case 'no_code' :
  2153. case 'no_state' :
  2154. case 'invalid_state' :
  2155. case 'invalid_request' :
  2156. case 'invalid_scope' :
  2157. case 'unsupported_response_type' :
  2158. case 'invalid_token' :
  2159. case 'no_token' :
  2160. case 'missing_secrets' :
  2161. case 'home_missing' :
  2162. case 'siteurl_missing' :
  2163. case 'gmt_offset_missing' :
  2164. case 'site_name_missing' :
  2165. case 'secret_1_missing' :
  2166. case 'secret_2_missing' :
  2167. case 'site_lang_missing' :
  2168. case 'home_malformed' :
  2169. case 'siteurl_malformed' :
  2170. case 'gmt_offset_malformed' :
  2171. case 'timezone_string_malformed' :
  2172. case 'site_name_malformed' :
  2173. case 'secret_1_malformed' :
  2174. case 'secret_2_malformed' :
  2175. case 'site_lang_malformed' :
  2176. case 'secrets_mismatch' :
  2177. case 'verify_secret_1_missing' :
  2178. case 'verify_secret_1_malformed' :
  2179. case 'verify_secrets_missing' :
  2180. case 'verify_secrets_mismatch' :
  2181. $error = esc_html( $error );
  2182. $this->error = sprintf( __( '<strong>Your Jetpack has a glitch.</strong> Something went wrong that&#8217;s never supposed to happen. Guess you&#8217;re just lucky: %s', 'jetpack' ), "<code>$error</code>" );
  2183. if ( ! Jetpack::is_active() ) {
  2184. $this->error .= '<br />';
  2185. $this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
  2186. }
  2187. break;
  2188. }
  2189. $message_code = Jetpack::state( 'message' );
  2190. $active_state = Jetpack::state( 'activated_modules' );
  2191. if ( ! empty( $active_state ) ) {
  2192. $available = Jetpack::get_available_modules();
  2193. $active_state = explode( ',', $active_state );
  2194. $active_state = array_intersect( $active_state, $available );
  2195. if ( count( $active_state ) ) {
  2196. foreach ( $active_state as $mod ) {
  2197. $this->stat( 'module-activated', $mod );
  2198. }
  2199. } else {
  2200. $active_state = false;
  2201. }
  2202. }
  2203. switch ( $message_code ) {
  2204. case 'modules_activated' :
  2205. $this->message = sprintf(
  2206. __( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
  2207. JETPACK__VERSION
  2208. );
  2209. if ( $active_state ) {
  2210. $titles = array();
  2211. foreach ( $active_state as $mod ) {
  2212. if ( $mod_headers = Jetpack::get_module( $mod ) ) {
  2213. $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
  2214. }
  2215. }
  2216. if ( $titles ) {
  2217. $this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
  2218. }
  2219. }
  2220. if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
  2221. $titles = array();
  2222. foreach ( explode( ',', $reactive_state ) as $mod ) {
  2223. if ( $mod_headers = Jetpack::get_module( $mod ) ) {
  2224. $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
  2225. }
  2226. }
  2227. if ( $titles ) {
  2228. $this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
  2229. }
  2230. }
  2231. $this->message .= Jetpack::jetpack_comment_notice();
  2232. break;
  2233. case 'module_activated' :
  2234. if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
  2235. $this->message = sprintf( __( '<strong>%s Activated!</strong> You can deactivate at any time by clicking the Deactivate link next to each module.', 'jetpack' ), $module['name'] );
  2236. $this->stat( 'module-activated', Jetpack::state( 'module' ) );
  2237. }
  2238. break;
  2239. case 'module_deactivated' :
  2240. $modules = Jetpack::state( 'module' );
  2241. if ( ! $modules ) {
  2242. break;
  2243. }
  2244. $module_names = array();
  2245. foreach ( explode( ',', $modules ) as $module_slug ) {
  2246. $module = Jetpack::get_module( $module_slug );
  2247. if ( $module ) {
  2248. $module_names[] = $module['name'];
  2249. }
  2250. $this->stat( 'module-deactivated', $module_slug );
  2251. }
  2252. if ( ! $module_names ) {
  2253. break;
  2254. }
  2255. $this->message = wp_sprintf(
  2256. _nx(
  2257. '<strong>%l Deactivated!</strong> You can activate it again at any time using the activate link next to each module.',
  2258. '<strong>%l Deactivated!</strong> You can activate them again at any time using the activate links next to each module.',
  2259. count( $module_names ),
  2260. '%l = list of Jetpack module/feature names',
  2261. 'jetpack'
  2262. ),
  2263. $module_names
  2264. );
  2265. break;
  2266. case 'module_configured' :
  2267. $this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
  2268. break;
  2269. case 'already_authorized' :
  2270. $this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
  2271. break;
  2272. case 'authorized' :
  2273. $this->message = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
  2274. $this->message .= "<br />\n";
  2275. $this->message .= sprintf( __( 'Jetpack is now active. Browse through each Jetpack feature below. Visit the <a href="%s">settings page</a> to activate/deactivate features.', 'jetpack' ), admin_url( 'admin.php?page=jetpack_modules' ) );
  2276. $this->message .= Jetpack::jetpack_comment_notice();
  2277. break;
  2278. case 'linked' :
  2279. $this->message = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
  2280. $this->message .= Jetpack::jetpack_comment_notice();
  2281. break;
  2282. case 'unlinked' :
  2283. $user = wp_get_current_user();
  2284. $this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
  2285. break;
  2286. }
  2287. $deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
  2288. if ( ! empty( $deactivated_plugins ) ) {
  2289. $deactivated_plugins = explode( ',', $deactivated_plugins );
  2290. $deactivated_titles = array();
  2291. foreach ( $deactivated_plugins as $deactivated_plugin ) {
  2292. if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
  2293. continue;
  2294. }
  2295. $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
  2296. }
  2297. if ( $deactivated_titles ) {
  2298. if ( $this->message ) {
  2299. $this->message .= "<br /><br />\n";
  2300. }
  2301. $this->message .= wp_sprintf(
  2302. _n(
  2303. 'Jetpack contains the most recent version of the old %l plugin.',
  2304. 'Jetpack contains the most recent versions of the old %l plugins.',
  2305. count( $deactivated_titles ),
  2306. 'jetpack'
  2307. ),
  2308. $deactivated_titles
  2309. );
  2310. $this->message .= "<br />\n";
  2311. $this->message .= _n(
  2312. 'The old version has been deactivated and can be removed from your site.',
  2313. 'The old versions have been deactivated and can be removed from your site.',
  2314. count( $deactivated_titles ),
  2315. 'jetpack'
  2316. );
  2317. }
  2318. }
  2319. $this->privacy_checks = Jetpack::state( 'privacy_checks' );
  2320. if ( $this->message || $this->error || $this->privacy_checks ) {
  2321. add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
  2322. }
  2323. if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
  2324. do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
  2325. }
  2326. add_filter( 'jetpack_short_module_description', 'wptexturize' );
  2327. }
  2328. function admin_notices() {
  2329. if ( $this->error ) {
  2330. ?>
  2331. <div id="message" class="jetpack-message jetpack-err">
  2332. <div class="squeezer">
  2333. <h4><?php echo wp_kses( $this->error, array( 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h4>
  2334. <?php if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
  2335. <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
  2336. <?php endif; ?>
  2337. </div>
  2338. </div>
  2339. <?php
  2340. }
  2341. if ( $this->message ) {
  2342. ?>
  2343. <div id="message" class="jetpack-message">
  2344. <div class="squeezer">
  2345. <h4><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h4>
  2346. </div>
  2347. </div>
  2348. <?php
  2349. }
  2350. if ( $this->privacy_checks ) :
  2351. $module_names = $module_slugs = array();
  2352. $privacy_checks = explode( ',', $this->privacy_checks );
  2353. $privacy_checks = array_filter( $privacy_checks, array( 'Jetpack', 'is_module' ) );
  2354. foreach ( $privacy_checks as $module_slug ) {
  2355. $module = Jetpack::get_module( $module_slug );
  2356. if ( ! $module ) {
  2357. continue;
  2358. }
  2359. $module_slugs[] = $module_slug;
  2360. $module_names[] = "<strong>{$module['name']}</strong>";
  2361. }
  2362. $module_slugs = join( ',', $module_slugs );
  2363. ?>
  2364. <div id="message" class="jetpack-message jetpack-err">
  2365. <div class="squeezer">
  2366. <h4><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h4><br />
  2367. <p><?php
  2368. echo wp_kses(
  2369. wptexturize(
  2370. wp_sprintf(
  2371. _nx(
  2372. "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
  2373. "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
  2374. count( $privacy_checks ),
  2375. '%l = list of Jetpack module/feature names',
  2376. 'jetpack'
  2377. ),
  2378. $module_names
  2379. )
  2380. ),
  2381. array( 'strong' => true )
  2382. );
  2383. echo "\n<br />\n";
  2384. echo wp_kses(
  2385. sprintf(
  2386. _nx(
  2387. 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
  2388. 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
  2389. count( $privacy_checks ),
  2390. '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
  2391. 'jetpack'
  2392. ),
  2393. wp_nonce_url(
  2394. Jetpack::admin_url(
  2395. array(
  2396. 'page' => 'jetpack',
  2397. 'action' => 'deactivate',
  2398. 'module' => urlencode( $module_slugs ),
  2399. )
  2400. ),
  2401. "jetpack_deactivate-$module_slugs"
  2402. ),
  2403. esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
  2404. ),
  2405. array( 'a' => array( 'href' => true, 'title' => true ) )
  2406. );
  2407. ?></p>
  2408. </div>
  2409. </div>
  2410. <?php endif;
  2411. }
  2412. /**
  2413. * Record a stat for later output. This will only currently output in the admin_footer.
  2414. */
  2415. function stat( $group, $detail ) {
  2416. if ( ! isset( $this->stats[ $group ] ) )
  2417. $this->stats[ $group ] = array();
  2418. $this->stats[ $group ][] = $detail;
  2419. }
  2420. /**
  2421. * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
  2422. */
  2423. function do_stats( $method = '' ) {
  2424. if ( is_array( $this->stats ) && count( $this->stats ) ) {
  2425. foreach ( $this->stats as $group => $stats ) {
  2426. if ( is_array( $stats ) && count( $stats ) ) {
  2427. $args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
  2428. if ( 'server_side' === $method ) {
  2429. self::do_server_side_stat( $args );
  2430. } else {
  2431. echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
  2432. }
  2433. }
  2434. unset( $this->stats[ $group ] );
  2435. }
  2436. }
  2437. }
  2438. /**
  2439. * Runs stats code for a one-off, server-side.
  2440. *
  2441. * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
  2442. *
  2443. * @return bool If it worked.
  2444. */
  2445. static function do_server_side_stat( $args ) {
  2446. $response = wp_remote_get( self::build_stats_url( $args ) );
  2447. if ( is_wp_error( $response ) )
  2448. return false;
  2449. if ( 200 !== wp_remote_retrieve_response_code( $response ) )
  2450. return false;
  2451. return true;
  2452. }
  2453. /**
  2454. * Builds the stats url.
  2455. *
  2456. * @param $args array|string The arguments to append to the URL.
  2457. *
  2458. * @return string The URL to be pinged.
  2459. */
  2460. static function build_stats_url( $args ) {
  2461. $defaults = array(
  2462. 'v' => 'wpcom2',
  2463. 'rand' => md5( mt_rand( 0, 999 ) . time() ),
  2464. );
  2465. $args = wp_parse_args( $args, $defaults );
  2466. $base_url = apply_filters(
  2467. 'jetpack_stats_base_url',
  2468. set_url_scheme( 'http://pixel.wp.com/g.gif' )
  2469. );
  2470. $url = add_query_arg( $args, $base_url );
  2471. return $url;
  2472. }
  2473. function translate_current_user_to_role() {
  2474. foreach ( $this->capability_translations as $role => $cap ) {
  2475. if ( current_user_can( $role ) || current_user_can( $cap ) ) {
  2476. return $role;
  2477. }
  2478. }
  2479. return false;
  2480. }
  2481. function translate_role_to_cap( $role ) {
  2482. if ( ! isset( $this->capability_translations[$role] ) ) {
  2483. return false;
  2484. }
  2485. return $this->capability_translations[$role];
  2486. }
  2487. function sign_role( $role ) {
  2488. if ( ! $user_id = (int) get_current_user_id() ) {
  2489. return false;
  2490. }
  2491. $token = Jetpack_Data::get_access_token();
  2492. if ( ! $token || is_wp_error( $token ) ) {
  2493. return false;
  2494. }
  2495. return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
  2496. }
  2497. function build_connect_url( $raw = false, $redirect = false ) {
  2498. if ( ! Jetpack_Options::get_option( 'blog_token' ) ) {
  2499. $url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
  2500. if( is_network_admin() ) {
  2501. $url = add_query_arg( 'is_multisite', network_admin_url(
  2502. 'admin.php?page=jetpack-settings' ), $url );
  2503. }
  2504. } else {
  2505. $role = $this->translate_current_user_to_role();
  2506. $signed_role = $this->sign_role( $role );
  2507. $user = wp_get_current_user();
  2508. $redirect = $redirect ? esc_url_raw( $redirect ) : '';
  2509. if( isset( $_REQUEST['is_multisite'] ) ) {
  2510. $redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
  2511. }
  2512. $args = urlencode_deep(
  2513. array(
  2514. 'response_type' => 'code',
  2515. 'client_id' => Jetpack_Options::get_option( 'id' ),
  2516. 'redirect_uri' => add_query_arg(
  2517. array(
  2518. 'action' => 'authorize',
  2519. '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
  2520. 'redirect' => $redirect ? urlencode( $redirect ) : false,
  2521. ),
  2522. menu_page_url( 'jetpack', false )
  2523. ),
  2524. 'state' => $user->ID,
  2525. 'scope' => $signed_role,
  2526. 'user_email' => $user->user_email,
  2527. 'user_login' => $user->user_login,
  2528. 'is_active' => Jetpack::is_active(),
  2529. 'jp_version' => JETPACK__VERSION,
  2530. )
  2531. );
  2532. $url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
  2533. }
  2534. return $raw ? $url : esc_url( $url );
  2535. }
  2536. function build_reconnect_url( $raw = false ) {
  2537. $url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
  2538. return $raw ? $url : esc_url( $url );
  2539. }
  2540. public static function admin_url( $args = null ) {
  2541. $args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
  2542. $url = add_query_arg( $args, admin_url( 'admin.php' ) );
  2543. return $url;
  2544. }
  2545. public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
  2546. $actionurl = str_replace( '&amp;', '&', $actionurl );
  2547. return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
  2548. }
  2549. function dismiss_jetpack_notice() {
  2550. if ( isset( $_GET['jetpack-notice'] ) && 'dismiss' == $_GET['jetpack-notice'] && check_admin_referer( 'jetpack-deactivate' ) && ! is_plugin_active_for_network( plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ) ) ) {
  2551. require_once ABSPATH . 'wp-admin/includes/plugin.php';
  2552. deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
  2553. wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
  2554. exit;
  2555. }
  2556. }
  2557. /**
  2558. * This is the old pre-3.0 admin page. It is replaced by the Jetpack_Admin class.
  2559. * Tentatively left here for comparison purposes.
  2560. */
  2561. function admin_page() {
  2562. global $current_user;
  2563. $is_connected = Jetpack::is_active();
  2564. $user_token = Jetpack_Data::get_access_token( $current_user->ID );
  2565. $is_user_connected = $user_token && ! is_wp_error( $user_token );
  2566. $is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
  2567. $can_reconnect_jpms = true;
  2568. if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
  2569. $jpms = Jetpack_Network::init();
  2570. $can_reconnect_jpms = ( $jpms->get_option( 'sub-site-connection-override' ) ) ? 1: 0;
  2571. }
  2572. ?>
  2573. <div class="wrap" id="jetpack-settings">
  2574. <div id="jp-header"<?php if ( $is_connected ) : ?> class="small"<?php endif; ?>>
  2575. <div id="jp-clouds">
  2576. <?php if ( $is_connected && $can_reconnect_jpms ) : ?>
  2577. <div id="jp-disconnectors">
  2578. <?php if ( current_user_can( 'jetpack_disconnect' ) ) : ?>
  2579. <div id="jp-disconnect" class="jp-disconnect">
  2580. <a href="<?php echo wp_nonce_url( Jetpack::admin_url( 'action=disconnect' ), 'jetpack-disconnect' ); ?>"><div class="deftext"><?php _e( 'Connected to WordPress.com', 'jetpack' ); ?></div><div class="hovertext"><?php _e( 'Disconnect from WordPress.com', 'jetpack' ) ?></div></a>
  2581. </div>
  2582. <?php endif; ?>
  2583. <?php if ( $is_user_connected && ! $is_master_user ) : ?>
  2584. <div id="jp-unlink" class="jp-disconnect">
  2585. <a href="<?php echo wp_nonce_url( Jetpack::admin_url( 'action=unlink' ), 'jetpack-unlink' ); ?>"><div class="deftext"><?php _e( 'User linked to WordPress.com', 'jetpack' ); ?></div><div class="hovertext"><?php _e( 'Unlink user from WordPress.com', 'jetpack' ) ?></div></a>
  2586. </div>
  2587. <?php endif; ?>
  2588. </div>
  2589. <?php endif; ?>
  2590. <h3><?php _e( 'Jetpack by WordPress.com', 'jetpack' ) ?></h3>
  2591. <?php if ( ! $is_connected ) : ?>
  2592. <div id="jp-notice">
  2593. <p><?php _e( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ); ?></p>
  2594. </div>
  2595. <?php endif; ?>
  2596. </div>
  2597. </div>
  2598. <h2 style="display: none"></h2> <!-- For WP JS message relocation -->
  2599. <?php Jetpack::init()->load_view( 'admin/network-activated-notice.php' ); ?>
  2600. <?php do_action( 'jetpack_notices' ) ?>
  2601. <?php
  2602. // If the connection has not been made then show the marketing text.
  2603. if( !$can_reconnect_jpms && !$is_connected ) {
  2604. ?>
  2605. <div id="message" class="updated jetpack-message jp-connect jp-multisite" style="display:block !important">
  2606. <div class="jetpack-wrap-container">
  2607. <div class="jetpack-text-container">
  2608. <h4>
  2609. <p><?php _e( 'To use Jetpack please contact your WordPress administrator to connect it for you.', 'jetpack' ) ?></p>
  2610. </h4>
  2611. </div>
  2612. </div>
  2613. </div> <?php
  2614. }
  2615. if ( ! Jetpack::is_development_mode() && $can_reconnect_jpms ) :
  2616. ?>
  2617. <?php if ( ! $is_connected ) :
  2618. $dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
  2619. ?>
  2620. <div id="message" class="updated jetpack-message jp-connect" style="display:block !important;">
  2621. <div id="jp-dismiss" class="jetpack-close-button-container">
  2622. <a class="jetpack-close-button" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>"><?php _e( 'Dismiss this notice.', 'jetpack' ); ?></a>
  2623. </div>
  2624. <div class="jetpack-wrap-container">
  2625. <div class="jetpack-text-container">
  2626. <h4>
  2627. <p><?php _e( 'To enable all of the Jetpack features you&#8217;ll need to connect your website to WordPress.com using the button to the right. Once you&#8217;ve made the connection you&#8217;ll activate all the delightful features below.', 'jetpack' ) ?></p>
  2628. </h4>
  2629. </div>
  2630. <div class="jetpack-install-container">
  2631. <p class="submit"><a href="<?php echo $this->build_connect_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Connect to WordPress.com', 'jetpack' ); ?></a></p>
  2632. </div>
  2633. </div>
  2634. </div>
  2635. <?php else /* blog and user are connected */ : ?>
  2636. <?php /* TODO: if not master user, show user disconnect button? */ ?>
  2637. <?php endif; ?>
  2638. <?php endif; // ! Jetpack::is_development_mode() ?>
  2639. <?php if ( Jetpack::is_active() && !Jetpack::is_development_mode() && ! $is_user_connected ) : ?>
  2640. <div id="message" class="updated jetpack-message jp-connect" style="display:block !important;">
  2641. <div class="jetpack-wrap-container">
  2642. <div class="jetpack-text-container">
  2643. <h4>
  2644. <p><?php _e( 'To enable all of the Jetpack features you&#8217;ll need to link your account here to your WordPress.com account using the button to the right.', 'jetpack' ) ?></p>
  2645. </h4>
  2646. </div>
  2647. <div class="jetpack-install-container">
  2648. <p class="submit"><a href="<?php echo $this->build_connect_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Link account with WordPress.com', 'jetpack' ); ?></a></p>
  2649. </div>
  2650. </div>
  2651. </div>
  2652. <?php endif; ?>
  2653. <?php
  2654. if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
  2655. $this->admin_screen_configure_module( $_GET['configure'] );
  2656. } else {
  2657. $this->admin_screen_list_modules();
  2658. }
  2659. ?>
  2660. <div id="survey" class="jp-survey">
  2661. <div class="jp-survey-container">
  2662. <div class="jp-survey-text">
  2663. <h4><?php _e( 'Have feedback on Jetpack?', 'jetpack' ); ?></h4>
  2664. <br />
  2665. <?php _e( 'Answer a short survey to let us know how we&#8217;re doing and what to add in the future.', 'jetpack' ); ?>
  2666. </div>
  2667. <div class="jp-survey-button-container">
  2668. <p class="submit"><?php printf( '<a id="jp-survey-button" class="button-primary" target="_blank" href="%1$s">%2$s</a>', 'http://jetpack.me/survey/?rel=' . JETPACK__VERSION, __( 'Take Survey', 'jetpack' ) ); ?></p>
  2669. </div>
  2670. </div>
  2671. </div>
  2672. <?php if ( $is_connected && $this->current_user_is_connection_owner() ) : ?>
  2673. <p id="news-sub"><?php _e( 'Checking email updates status&hellip;', 'jetpack' ); ?></p>
  2674. <script type="text/javascript">
  2675. jQuery(document).ready(function($){
  2676. $.get( ajaxurl, { action: 'jetpack-check-news-subscription', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
  2677. if ( 'subscribed' == data ) {
  2678. $( '#news-sub' ).html( '<?php printf(
  2679. esc_js( _x( 'You are currently subscribed to email updates. %s', '%s = Unsubscribe link', 'jetpack' ) ),
  2680. '<a href="#" class="jp-news-link button">' . esc_js( __( 'Unsubscribe', 'jetpack' ) ) . '</a>'
  2681. ); ?>' );
  2682. } else {
  2683. $( '#news-sub' ).html( '<?php printf(
  2684. esc_js( _x( 'Want to receive updates about Jetpack by email? %s', '%s = Subscribe link', 'jetpack' ) ),
  2685. '<a href="#" class="jp-news-link button-primary">' . esc_js( __( 'Subscribe', 'jetpack' ) ) . '</a>'
  2686. ); ?>' );
  2687. }
  2688. $( '.jp-news-link' ).click( function() {
  2689. $( '#news-sub' ).append( ' <img src="<?php echo esc_js( esc_url( admin_url( 'images/loading.gif' ) ) ); ?>" align="absmiddle" id="jp-news-loading" />' );
  2690. $.get( ajaxurl, { action: 'jetpack-subscribe-to-news', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
  2691. if ( 'subscribed' == data ) {
  2692. $( '#news-sub' ).text( '<?php echo esc_js( __( 'You have been subscribed to receive email updates.', 'jetpack' ) ); ?>' );
  2693. } else {
  2694. $( '#news-sub' ).text( '<?php echo esc_js( __( 'You will no longer receive email updates about Jetpack.', 'jetpack' ) ); ?>' );
  2695. }
  2696. $( '#jp-news-loading' ).remove();
  2697. } );
  2698. return false;
  2699. } );
  2700. } );
  2701. } );
  2702. </script>
  2703. <?php endif; ?>
  2704. <div id="jp-footer">
  2705. <p class="automattic"><?php _e( 'An <span>Automattic</span> Airline', 'jetpack' ) ?></p>
  2706. <p class="small">
  2707. <a href="http://jetpack.me/" target="_blank">Jetpack <?php echo esc_html( JETPACK__VERSION ); ?></a> |
  2708. <a href="http://automattic.com/privacy/" target="_blank"><?php _e( 'Privacy Policy', 'jetpack' ); ?></a> |
  2709. <a href="http://wordpress.com/tos/" target="_blank"><?php _e( 'Terms of Service', 'jetpack' ); ?></a> |
  2710. <?php if ( current_user_can( 'manage_options' ) ) : ?>
  2711. <a href="<?php echo Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ); ?>"><?php _e( 'Debug', 'jetpack' ); ?></a> |
  2712. <?php endif; ?>
  2713. <a href="http://jetpack.me/support/" target="_blank"><?php _e( 'Support', 'jetpack' ); ?></a>
  2714. </p>
  2715. </div>
  2716. <div id="jetpack-configuration" style="display:none;">
  2717. <p><img width="16" src="<?php echo esc_url( plugins_url( 'images/wpspin_light-2x.gif', JETPACK__PLUGIN_FILE) ); ?>" alt="Loading ..." /></p>
  2718. </div>
  2719. </div>
  2720. <?php
  2721. }
  2722. function debugger_page() {
  2723. nocache_headers();
  2724. if ( ! current_user_can( 'manage_options' ) ) {
  2725. die( '-1' );
  2726. }
  2727. Jetpack_Debugger::jetpack_debug_display_handler();
  2728. exit;
  2729. }
  2730. public static function admin_screen_configure_module( $module_id ) {
  2731. if ( ! in_array( $module_id, Jetpack::get_active_modules() ) || ! current_user_can( 'manage_options' ) )
  2732. return false; ?>
  2733. <div id="jp-settings-screen" style="position: relative">
  2734. <h3>
  2735. <?php
  2736. $module = Jetpack::get_module( $module_id );
  2737. echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
  2738. printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
  2739. ?>
  2740. </h3>
  2741. <?php do_action( 'jetpack_module_configuration_screen_' . $module_id ); ?>
  2742. </div><?php
  2743. }
  2744. public static function sort_modules( $a, $b ) {
  2745. if ( $a['sort'] == $b['sort'] )
  2746. return 0;
  2747. return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
  2748. }
  2749. function admin_screen_list_modules() {
  2750. require_once JETPACK__PLUGIN_DIR . 'modules/module-info.php';
  2751. $jetpack_connected = true;
  2752. if ( ! Jetpack::is_active() )
  2753. $jetpack_connected = false;
  2754. ?>
  2755. <div class="module-container">
  2756. <?php
  2757. $avail_raw = Jetpack::get_available_modules();
  2758. $available = array();
  2759. $active = Jetpack::get_active_modules();
  2760. $counter = 0;
  2761. foreach ( (array) $avail_raw as $module ) {
  2762. if ( $plugin = Jetpack::get_module( $module ) ) {
  2763. $plugin['module'] = $module;
  2764. $available[] = $plugin;
  2765. }
  2766. }
  2767. unset( $avail_raw );
  2768. usort( $available, array( 'Jetpack', 'sort_modules' ) );
  2769. $jetpack_version = Jetpack_Options::get_option( 'version' );
  2770. if ( $jetpack_version ) {
  2771. list( $jetpack_version, $jetpack_version_time ) = explode( ':', $jetpack_version );
  2772. } else {
  2773. $jetpack_version = 0;
  2774. $jetpack_version_time = 0;
  2775. }
  2776. $jetpack_old_version = Jetpack_Options::get_option( 'old_version' );
  2777. if ( $jetpack_old_version ) {
  2778. list( $jetpack_old_version ) = explode( ':', $jetpack_old_version );
  2779. } else {
  2780. $jetpack_old_version = 0;
  2781. }
  2782. $now = time();
  2783. foreach ( (array) $available as $module_data ) {
  2784. $module = $module_data['module'];
  2785. $activated = in_array( $module, $active );
  2786. if ( $activated ) {
  2787. $css = 'active';
  2788. $toggle = __( 'Deactivate', 'jetpack' );
  2789. $toggle_url = wp_nonce_url(
  2790. Jetpack::admin_url(
  2791. array(
  2792. 'page' => 'jetpack',
  2793. 'action' => 'deactivate',
  2794. 'module' => $module,
  2795. )
  2796. ),
  2797. "jetpack_deactivate-$module"
  2798. );
  2799. } else {
  2800. $css = 'inactive';
  2801. $toggle = __( 'Activate', 'jetpack' );
  2802. $toggle_url = wp_nonce_url(
  2803. Jetpack::admin_url(
  2804. array(
  2805. 'page' => 'jetpack',
  2806. 'action' => 'activate',
  2807. 'module' => $module,
  2808. )
  2809. ),
  2810. "jetpack_activate-$module"
  2811. );
  2812. }
  2813. if ( $counter % 4 == 0 ) {
  2814. $classes = $css . ' jetpack-newline';
  2815. $counter = 0;
  2816. } else {
  2817. $classes = $css;
  2818. }
  2819. $free_text = esc_html( $module_data['free'] ? __( 'Free', 'jetpack' ) : __( 'Purchase', 'jetpack' ) );
  2820. $free_text = apply_filters( 'jetpack_module_free_text_' . $module, $free_text );
  2821. $badge_text = $free_text;
  2822. if ( ( ! $jetpack_connected && ! Jetpack::is_development_mode() ) ) {
  2823. $classes = 'x disabled';
  2824. } elseif ( $jetpack_version_time + 604800 > $now ) { // 1 week
  2825. if ( version_compare( $module_data['introduced'], $jetpack_old_version, '>' ) ) {
  2826. $badge_text = esc_html__( 'New', 'jetpack' );
  2827. $classes .= ' jetpack-new-module';
  2828. } elseif ( isset( $module_data['changed'] ) && version_compare( $module_data['changed'], $jetpack_old_version, '>' ) ) {
  2829. $badge_text = esc_html__( 'Updated', 'jetpack' );
  2830. $classes .= ' jetpack-updated-module';
  2831. } else {
  2832. $badge_text = $free_text;
  2833. }
  2834. }
  2835. ?>
  2836. <div class="jetpack-module jetpack-<?php echo $classes; ?>" id="<?php echo $module ?>">
  2837. <h3><?php echo esc_html( $module_data['name'] ); ?></h3>
  2838. <div class="jetpack-module-description">
  2839. <div class="module-image">
  2840. <p><span class="module-image-badge"><?php echo $badge_text; ?></span><span class="module-image-free" style="display: none"><?php echo $free_text; ?></span></p>
  2841. </div>
  2842. <p><?php echo apply_filters( 'jetpack_short_module_description', $module_data['description'], $module ); ?></p>
  2843. </div>
  2844. <div class="jetpack-module-actions">
  2845. <?php if ( $jetpack_connected || ( Jetpack::is_development_mode() && ! $module_data['requires_connection'] ) ) : ?>
  2846. <?php if ( ! $activated && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
  2847. <a href="<?php echo esc_url( $toggle_url ); ?>" class="<?php echo ( 'inactive' == $css ? ' button-primary' : ' button-secondary' ); ?>"><?php echo $toggle; ?></a>&nbsp;
  2848. <?php endif; ?>
  2849. <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
  2850. <?php
  2851. if ( current_user_can( 'manage_options' ) && apply_filters( 'jetpack_module_configurable_' . $module, false ) ) {
  2852. echo '<a href="' . esc_url( Jetpack::module_configuration_url( $module ) ) . '" class="jetpack-configure-button button-secondary">' . __( 'Configure', 'jetpack' ) . '</a>';
  2853. }
  2854. ?><?php if ( $activated && $module_data['deactivate'] && current_user_can( 'manage_options' ) ) : ?><a style="display: none;" href="<?php echo esc_url( $toggle_url ); ?>" class="jetpack-deactivate-button button-secondary"><?php echo $toggle; ?></a>&nbsp;<?php endif; ?>
  2855. <?php else : ?>
  2856. <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
  2857. <?php endif; ?>
  2858. </div>
  2859. </div>
  2860. <?php if ( 'inactive' == $css && $jetpack_connected && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
  2861. <script type="text/javascript">
  2862. jQuery( '#<?php echo esc_js( $module ); ?>' ).bind( 'click', function(e){
  2863. if ( ! jQuery(e.target).hasClass('more-info-link') )
  2864. document.location.href = '<?php echo str_replace( '&amp;', '&', esc_js( esc_url( $toggle_url ) ) ); ?>';
  2865. } );
  2866. </script>
  2867. <?php else : ?>
  2868. <style>
  2869. #<?php echo $module; ?> { cursor: default; }
  2870. </style>
  2871. <?php endif; ?>
  2872. <div id="jp-more-info-<?php echo esc_attr( $module ); ?>" style="display:none;">
  2873. <?php
  2874. if ( $jetpack_connected && has_action( 'jetpack_module_more_info_connected_' . $module ) )
  2875. do_action( 'jetpack_module_more_info_connected_' . $module );
  2876. else
  2877. do_action( 'jetpack_module_more_info_' . $module );
  2878. ?>
  2879. </div>
  2880. <?php
  2881. $counter++;
  2882. }
  2883. // Add in some "Coming soon..." placeholders to fill up the current row and one more
  2884. for ( $i = 0; $i < 4; $i++ ) { ?>
  2885. <div class="jetpack-module placeholder"<?php if ( $i > 8 - $counter ) echo ' style="display: none;"'; ?>>
  2886. <h3><?php _e( 'Coming soon&#8230;', 'jetpack' ) ?></h3>
  2887. </div>
  2888. <?php
  2889. }
  2890. echo '</div><!-- .module-container -->';
  2891. }
  2892. function check_news_subscription() {
  2893. if ( ! $this->current_user_is_connection_owner() ) {
  2894. exit;
  2895. }
  2896. Jetpack::load_xml_rpc_client();
  2897. $xml = new Jetpack_IXR_Client(
  2898. array(
  2899. 'user_id' => JETPACK_MASTER_USER,
  2900. )
  2901. );
  2902. $xml->query( 'jetpack.checkNewsSubscription' );
  2903. if ( $xml->isError() ) {
  2904. printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
  2905. } else {
  2906. print_r( $xml->getResponse() );
  2907. }
  2908. exit;
  2909. }
  2910. function subscribe_to_news() {
  2911. if ( ! $this->current_user_is_connection_owner() ) {
  2912. exit;
  2913. }
  2914. Jetpack::load_xml_rpc_client();
  2915. $xml = new Jetpack_IXR_Client(
  2916. array(
  2917. 'user_id' => JETPACK_MASTER_USER,
  2918. )
  2919. );
  2920. $xml->query( 'jetpack.subscribeToNews' );
  2921. if ( $xml->isError() ) {
  2922. printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
  2923. } else {
  2924. print_r( $xml->getResponse() );
  2925. }
  2926. exit;
  2927. }
  2928. function sync_reindex_trigger() {
  2929. if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
  2930. echo json_encode( $this->sync->reindex_trigger() );
  2931. } else {
  2932. echo '{"status":"ERROR"}';
  2933. }
  2934. exit;
  2935. }
  2936. function sync_reindex_status(){
  2937. if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
  2938. echo json_encode( $this->sync->reindex_status() );
  2939. } else {
  2940. echo '{"status":"ERROR"}';
  2941. }
  2942. exit;
  2943. }
  2944. /* Client API */
  2945. /**
  2946. * Returns the requested Jetpack API URL
  2947. *
  2948. * @return string
  2949. */
  2950. public static function api_url( $relative_url ) {
  2951. return trailingslashit( JETPACK__API_BASE . $relative_url ) . JETPACK__API_VERSION . '/';
  2952. }
  2953. /**
  2954. * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
  2955. */
  2956. public static function fix_url_for_bad_hosts( $url ) {
  2957. if ( 0 !== strpos( $url, 'https://' ) ) {
  2958. return $url;
  2959. }
  2960. switch ( JETPACK_CLIENT__HTTPS ) {
  2961. case 'ALWAYS' :
  2962. return $url;
  2963. case 'NEVER' :
  2964. return set_url_scheme( $url, 'http' );
  2965. // default : case 'AUTO' :
  2966. }
  2967. // Yay! Your host is good!
  2968. if ( self::permit_ssl() && wp_http_supports( array( 'ssl' => true ) ) ) {
  2969. return $url;
  2970. }
  2971. // Boo! Your host is bad and makes Jetpack cry!
  2972. return set_url_scheme( $url, 'http' );
  2973. }
  2974. /**
  2975. * Checks to see if the URL is using SSL to connect with Jetpack
  2976. *
  2977. * @since 2.3.3
  2978. * @return boolean
  2979. */
  2980. public static function permit_ssl( $force_recheck = false ) {
  2981. // Do some fancy tests to see if ssl is being supported
  2982. if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
  2983. if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
  2984. $ssl = 0;
  2985. } else {
  2986. switch ( JETPACK_CLIENT__HTTPS ) {
  2987. case 'NEVER':
  2988. $ssl = 0;
  2989. break;
  2990. case 'ALWAYS':
  2991. case 'AUTO':
  2992. default:
  2993. $ssl = 1;
  2994. break;
  2995. }
  2996. // If it's not 'NEVER', test to see
  2997. if ( $ssl ) {
  2998. $response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
  2999. if ( is_wp_error( $response ) || ( 'OK' !== wp_remote_retrieve_body( $response ) ) ) {
  3000. $ssl = 0;
  3001. }
  3002. }
  3003. }
  3004. set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
  3005. }
  3006. return (bool) $ssl;
  3007. }
  3008. /*
  3009. * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'ALWAYS' but SSL isn't working.
  3010. */
  3011. public function alert_required_ssl_fail() {
  3012. if ( ! current_user_can( 'manage_options' ) )
  3013. return;
  3014. ?>
  3015. <div id="message" class="error jetpack-message jp-identity-crisis">
  3016. <div class="jetpack-wrap-container">
  3017. <div class="jetpack-text-container">
  3018. <h3><?php _e( 'Something is being cranky!', 'jetpack' ); ?></h3>
  3019. <p><?php _e( 'Your site is configured to only permit SSL connections to Jetpack, but SSL connections don\'t seem to be functional!', 'jetpack' ); ?></p>
  3020. </div>
  3021. </div>
  3022. </div>
  3023. <?php
  3024. }
  3025. /**
  3026. * Returns the Jetpack XML-RPC API
  3027. *
  3028. * @return string
  3029. */
  3030. public static function xmlrpc_api_url() {
  3031. $base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
  3032. return untrailingslashit( $base ) . '/xmlrpc.php';
  3033. }
  3034. /**
  3035. * Creates two secret tokens and the end of life timestamp for them.
  3036. *
  3037. * Note these tokens are unique per call, NOT static per site for connecting.
  3038. *
  3039. * @since 2.6
  3040. * @return array
  3041. */
  3042. public function generate_secrets() {
  3043. $secrets = array(
  3044. wp_generate_password( 32, false ), // secret_1
  3045. wp_generate_password( 32, false ), // secret_2
  3046. ( time() + 600 ), // eol ( End of Life )
  3047. );
  3048. return $secrets;
  3049. }
  3050. /**
  3051. * Builds the timeout limit for queries talking with the wpcom servers.
  3052. *
  3053. * Based on local php max_execution_time in php.ini
  3054. *
  3055. * @since 2.6
  3056. * @return int
  3057. **/
  3058. public function get_remote_query_timeout_limit() {
  3059. $timeout = (int) ini_get( 'max_execution_time' );
  3060. if ( ! $timeout ) // Ensure exec time set in php.ini
  3061. $timeout = 30;
  3062. return intval( $timeout / 2 );
  3063. }
  3064. /**
  3065. * Takes the response from the Jetpack register new site endpoint and
  3066. * verifies it worked properly.
  3067. *
  3068. * @since 2.6
  3069. * @return true or Jetpack_Error
  3070. **/
  3071. public function validate_remote_register_response( $response ) {
  3072. if ( is_wp_error( $response ) ) {
  3073. return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
  3074. }
  3075. $code = wp_remote_retrieve_response_code( $response );
  3076. $entity = wp_remote_retrieve_body( $response );
  3077. if ( $entity )
  3078. $json = json_decode( $entity );
  3079. else
  3080. $json = false;
  3081. $code_type = intval( $code / 100 );
  3082. if ( 5 == $code_type ) {
  3083. return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
  3084. } elseif ( 408 == $code ) {
  3085. return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
  3086. } elseif ( ! empty( $json->error ) ) {
  3087. $error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
  3088. return new Jetpack_Error( (string) $json->error, $error_description, $code );
  3089. } elseif ( 200 != $code ) {
  3090. return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
  3091. }
  3092. // Jetpack ID error block
  3093. if ( empty( $json->jetpack_id ) ) {
  3094. return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
  3095. } elseif ( ! is_scalar( $json->jetpack_id ) ) {
  3096. 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 );
  3097. } elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
  3098. 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 );
  3099. }
  3100. return true;
  3101. }
  3102. /**
  3103. * @return bool|WP_Error
  3104. */
  3105. public static function register() {
  3106. add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
  3107. $secrets = Jetpack::init()->generate_secrets();
  3108. Jetpack_Options::update_option( 'register', $secrets[0] . ':' . $secrets[1] . ':' . $secrets[2] );
  3109. @list( $secret_1, $secret_2, $secret_eol ) = explode( ':', Jetpack_Options::get_option( 'register' ) );
  3110. if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() ) {
  3111. return new Jetpack_Error( 'missing_secrets' );
  3112. }
  3113. $timeout = Jetpack::init()->get_remote_query_timeout_limit();
  3114. $gmt_offset = get_option( 'gmt_offset' );
  3115. if ( ! $gmt_offset ) {
  3116. $gmt_offset = 0;
  3117. }
  3118. $stats_options = get_option( 'stats_options' );
  3119. $stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
  3120. $args = array(
  3121. 'method' => 'POST',
  3122. 'body' => array(
  3123. 'siteurl' => site_url(),
  3124. 'home' => home_url(),
  3125. 'gmt_offset' => $gmt_offset,
  3126. 'timezone_string' => (string) get_option( 'timezone_string' ),
  3127. 'site_name' => (string) get_option( 'blogname' ),
  3128. 'secret_1' => $secret_1,
  3129. 'secret_2' => $secret_2,
  3130. 'site_lang' => get_locale(),
  3131. 'timeout' => $timeout,
  3132. 'stats_id' => $stats_id,
  3133. ),
  3134. 'headers' => array(
  3135. 'Accept' => 'application/json',
  3136. ),
  3137. 'timeout' => $timeout,
  3138. );
  3139. $response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
  3140. // Make sure the response is valid and does not contain any Jetpack errors
  3141. $valid_response = Jetpack::init()->validate_remote_register_response( $response );
  3142. if( is_wp_error( $valid_response ) || !$valid_response ) {
  3143. return $valid_response;
  3144. }
  3145. // Grab the response values to work with
  3146. $code = wp_remote_retrieve_response_code( $response );
  3147. $entity = wp_remote_retrieve_body( $response );
  3148. if ( $entity )
  3149. $json = json_decode( $entity );
  3150. else
  3151. $json = false;
  3152. if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
  3153. return new Jetpack_Error( 'jetpack_secret', '', $code );
  3154. if ( isset( $json->jetpack_public ) ) {
  3155. $jetpack_public = (int) $json->jetpack_public;
  3156. } else {
  3157. $jetpack_public = false;
  3158. }
  3159. Jetpack_Options::update_options(
  3160. array(
  3161. 'id' => (int) $json->jetpack_id,
  3162. 'blog_token' => (string) $json->jetpack_secret,
  3163. 'public' => $jetpack_public,
  3164. )
  3165. );
  3166. return true;
  3167. }
  3168. /**
  3169. * If the db version is showing something other that what we've got now, bump it to current.
  3170. *
  3171. * @return bool: True if the option was incorrect and updated, false if nothing happened.
  3172. */
  3173. public static function maybe_set_version_option() {
  3174. list( $version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
  3175. if ( JETPACK__VERSION != $version ) {
  3176. Jetpack_Options::update_option( 'version', JETPACK__VERSION . ':' . time() );
  3177. return true;
  3178. }
  3179. return false;
  3180. }
  3181. /* Client Server API */
  3182. /**
  3183. * Loads the Jetpack XML-RPC client
  3184. */
  3185. public static function load_xml_rpc_client() {
  3186. require_once ABSPATH . WPINC . '/class-IXR.php';
  3187. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-ixr-client.php';
  3188. }
  3189. function verify_xml_rpc_signature() {
  3190. if ( $this->xmlrpc_verification ) {
  3191. return $this->xmlrpc_verification;
  3192. }
  3193. // It's not for us
  3194. if ( ! isset( $_GET['token'] ) || empty( $_GET['signature'] ) ) {
  3195. return false;
  3196. }
  3197. @list( $token_key, $version, $user_id ) = explode( ':', $_GET['token'] );
  3198. if (
  3199. empty( $token_key )
  3200. ||
  3201. empty( $version ) || strval( JETPACK__API_VERSION ) !== $version
  3202. ) {
  3203. return false;
  3204. }
  3205. if ( '0' === $user_id ) {
  3206. $token_type = 'blog';
  3207. $user_id = 0;
  3208. } else {
  3209. $token_type = 'user';
  3210. if ( empty( $user_id ) || ! ctype_digit( $user_id ) ) {
  3211. return false;
  3212. }
  3213. $user_id = (int) $user_id;
  3214. $user = new WP_User( $user_id );
  3215. if ( ! $user || ! $user->exists() ) {
  3216. return false;
  3217. }
  3218. }
  3219. $token = Jetpack_Data::get_access_token( $user_id );
  3220. if ( ! $token ) {
  3221. return false;
  3222. }
  3223. if ( 0 !== strpos( $token->secret, "$token_key." ) ) {
  3224. return false;
  3225. }
  3226. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
  3227. $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
  3228. if ( isset( $_POST['_jetpack_is_multipart'] ) ) {
  3229. $post_data = $_POST;
  3230. $file_hashes = array();
  3231. foreach ( $post_data as $post_data_key => $post_data_value ) {
  3232. if ( 0 !== strpos( $post_data_key, '_jetpack_file_hmac_' ) ) {
  3233. continue;
  3234. }
  3235. $post_data_key = substr( $post_data_key, strlen( '_jetpack_file_hmac_' ) );
  3236. $file_hashes[$post_data_key] = $post_data_value;
  3237. }
  3238. foreach ( $file_hashes as $post_data_key => $post_data_value ) {
  3239. unset( $post_data["_jetpack_file_hmac_{$post_data_key}"] );
  3240. $post_data[$post_data_key] = $post_data_value;
  3241. }
  3242. ksort( $post_data );
  3243. $body = http_build_query( stripslashes_deep( $post_data ) );
  3244. } elseif ( is_null( $this->HTTP_RAW_POST_DATA ) ) {
  3245. $body = file_get_contents( 'php://input' );
  3246. } else {
  3247. $body = null;
  3248. }
  3249. $signature = $jetpack_signature->sign_current_request(
  3250. array( 'body' => is_null( $body ) ? $this->HTTP_RAW_POST_DATA : $body, )
  3251. );
  3252. if ( ! $signature ) {
  3253. return false;
  3254. } else if ( is_wp_error( $signature ) ) {
  3255. return $signature;
  3256. } else if ( $signature !== $_GET['signature'] ) {
  3257. return false;
  3258. }
  3259. $timestamp = (int) $_GET['timestamp'];
  3260. $nonce = stripslashes( (string) $_GET['nonce'] );
  3261. if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
  3262. return false;
  3263. }
  3264. $this->xmlrpc_verification = array(
  3265. 'type' => $token_type,
  3266. 'user_id' => $token->external_user_id,
  3267. );
  3268. return $this->xmlrpc_verification;
  3269. }
  3270. /**
  3271. * Authenticates XML-RPC and other requests from the Jetpack Server
  3272. */
  3273. function authenticate_jetpack( $user, $username, $password ) {
  3274. if ( is_a( $user, 'WP_User' ) ) {
  3275. return $user;
  3276. }
  3277. $token_details = $this->verify_xml_rpc_signature();
  3278. if ( ! $token_details || is_wp_error( $token_details ) ) {
  3279. return $user;
  3280. }
  3281. if ( 'user' !== $token_details['type'] ) {
  3282. return $user;
  3283. }
  3284. if ( ! $token_details['user_id'] ) {
  3285. return $user;
  3286. }
  3287. nocache_headers();
  3288. return new WP_User( $token_details['user_id'] );
  3289. }
  3290. function add_nonce( $timestamp, $nonce ) {
  3291. global $wpdb;
  3292. static $nonces_used_this_request = array();
  3293. if ( isset( $nonces_used_this_request["$timestamp:$nonce"] ) ) {
  3294. return $nonces_used_this_request["$timestamp:$nonce"];
  3295. }
  3296. // This should always have gone through Jetpack_Signature::sign_request() first to check $timestamp an $nonce
  3297. $timestamp = (int) $timestamp;
  3298. $nonce = esc_sql( $nonce );
  3299. // Raw query so we can avoid races: add_option will also update
  3300. $show_errors = $wpdb->show_errors( false );
  3301. $old_nonce = $wpdb->get_row(
  3302. $wpdb->prepare( "SELECT * FROM `$wpdb->options` WHERE option_name = %s", "jetpack_nonce_{$timestamp}_{$nonce}" )
  3303. );
  3304. if ( is_null( $old_nonce ) ) {
  3305. $return = $wpdb->query(
  3306. $wpdb->prepare(
  3307. "INSERT INTO `$wpdb->options` (`option_name`, `option_value`, `autoload`) VALUES (%s, %s, %s)",
  3308. "jetpack_nonce_{$timestamp}_{$nonce}",
  3309. time(),
  3310. 'no'
  3311. )
  3312. );
  3313. } else {
  3314. $return = false;
  3315. }
  3316. $wpdb->show_errors( $show_errors );
  3317. $nonces_used_this_request["$timestamp:$nonce"] = $return;
  3318. return $return;
  3319. }
  3320. /**
  3321. * In some setups, $HTTP_RAW_POST_DATA can be emptied during some IXR_Server paths since it is passed by reference to various methods.
  3322. * Capture it here so we can verify the signature later.
  3323. */
  3324. function xmlrpc_methods( $methods ) {
  3325. $this->HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
  3326. return $methods;
  3327. }
  3328. function xmlrpc_options( $options ) {
  3329. $options['jetpack_version'] = array(
  3330. 'desc' => __( 'Jetpack Plugin Version', 'jetpack' ),
  3331. 'readonly' => true,
  3332. 'value' => JETPACK__VERSION,
  3333. );
  3334. $options['jetpack_client_id'] = array(
  3335. 'desc' => __( 'The Client ID/WP.com Blog ID of this site', 'jetpack' ),
  3336. 'readonly' => true,
  3337. 'value' => Jetpack_Options::get_option( 'id' ),
  3338. );
  3339. return $options;
  3340. }
  3341. public static function clean_nonces( $all = false ) {
  3342. global $wpdb;
  3343. $sql = "DELETE FROM `$wpdb->options` WHERE `option_name` LIKE %s";
  3344. if ( method_exists ( $wpdb , 'esc_like' ) ) {
  3345. $sql_args = array( $wpdb->esc_like( 'jetpack_nonce_' ) . '%' );
  3346. } else {
  3347. $sql_args = array( like_escape( 'jetpack_nonce_' ) . '%' );
  3348. }
  3349. if ( true !== $all ) {
  3350. $sql .= ' AND CAST( `option_value` AS UNSIGNED ) < %d';
  3351. $sql_args[] = time() - 3600;
  3352. }
  3353. $sql .= ' ORDER BY `option_id` LIMIT 100';
  3354. $sql = $wpdb->prepare( $sql, $sql_args );
  3355. for ( $i = 0; $i < 1000; $i++ ) {
  3356. if ( ! $wpdb->query( $sql ) ) {
  3357. break;
  3358. }
  3359. }
  3360. }
  3361. /**
  3362. * State is passed via cookies from one request to the next, but never to subsequent requests.
  3363. * SET: state( $key, $value );
  3364. * GET: $value = state( $key );
  3365. *
  3366. * @param string $key
  3367. * @param string $value
  3368. * @param bool $restate private
  3369. */
  3370. public static function state( $key = null, $value = null, $restate = false ) {
  3371. static $state = array();
  3372. static $path, $domain;
  3373. if ( ! isset( $path ) ) {
  3374. require_once( ABSPATH . 'wp-admin/includes/plugin.php' );
  3375. $admin_url = Jetpack::admin_url();
  3376. $bits = parse_url( $admin_url );
  3377. if ( is_array( $bits ) ) {
  3378. $path = ( isset( $bits['path'] ) ) ? dirname( $bits['path'] ) : null;
  3379. $domain = ( isset( $bits['host'] ) ) ? $bits['host'] : null;
  3380. } else {
  3381. $path = $domain = null;
  3382. }
  3383. }
  3384. // Extract state from cookies and delete cookies
  3385. if ( isset( $_COOKIE[ 'jetpackState' ] ) && is_array( $_COOKIE[ 'jetpackState' ] ) ) {
  3386. $yum = $_COOKIE[ 'jetpackState' ];
  3387. unset( $_COOKIE[ 'jetpackState' ] );
  3388. foreach ( $yum as $k => $v ) {
  3389. if ( strlen( $v ) )
  3390. $state[ $k ] = $v;
  3391. setcookie( "jetpackState[$k]", false, 0, $path, $domain );
  3392. }
  3393. }
  3394. if ( $restate ) {
  3395. foreach ( $state as $k => $v ) {
  3396. setcookie( "jetpackState[$k]", $v, 0, $path, $domain );
  3397. }
  3398. return;
  3399. }
  3400. // Get a state variable
  3401. if ( isset( $key ) && ! isset( $value ) ) {
  3402. if ( array_key_exists( $key, $state ) )
  3403. return $state[ $key ];
  3404. return null;
  3405. }
  3406. // Set a state variable
  3407. if ( isset ( $key ) && isset( $value ) ) {
  3408. if( is_array( $value ) && isset( $value[0] ) ) {
  3409. $value = $value[0];
  3410. }
  3411. $state[ $key ] = $value;
  3412. setcookie( "jetpackState[$key]", $value, 0, $path, $domain );
  3413. }
  3414. }
  3415. public static function restate() {
  3416. Jetpack::state( null, null, true );
  3417. }
  3418. public static function check_privacy( $file ) {
  3419. static $is_site_publicly_accessible = null;
  3420. if ( is_null( $is_site_publicly_accessible ) ) {
  3421. $is_site_publicly_accessible = false;
  3422. Jetpack::load_xml_rpc_client();
  3423. $rpc = new Jetpack_IXR_Client();
  3424. $success = $rpc->query( 'jetpack.isSitePubliclyAccessible', home_url() );
  3425. if ( $success ) {
  3426. $response = $rpc->getResponse();
  3427. if ( $response ) {
  3428. $is_site_publicly_accessible = true;
  3429. }
  3430. }
  3431. Jetpack_Options::update_option( 'public', (int) $is_site_publicly_accessible );
  3432. }
  3433. if ( $is_site_publicly_accessible ) {
  3434. return;
  3435. }
  3436. $module_slug = self::get_module_slug( $file );
  3437. $privacy_checks = Jetpack::state( 'privacy_checks' );
  3438. if ( ! $privacy_checks ) {
  3439. $privacy_checks = $module_slug;
  3440. } else {
  3441. $privacy_checks .= ",$module_slug";
  3442. }
  3443. Jetpack::state( 'privacy_checks', $privacy_checks );
  3444. }
  3445. /**
  3446. * Helper method for multicall XMLRPC.
  3447. */
  3448. public static function xmlrpc_async_call() {
  3449. global $blog_id;
  3450. static $clients = array();
  3451. $client_blog_id = is_multisite() ? $blog_id : 0;
  3452. if ( ! isset( $clients[$client_blog_id] ) ) {
  3453. Jetpack::load_xml_rpc_client();
  3454. $clients[$client_blog_id] = new Jetpack_IXR_ClientMulticall( array( 'user_id' => JETPACK_MASTER_USER, ) );
  3455. if ( function_exists( 'ignore_user_abort' ) ) {
  3456. ignore_user_abort( true );
  3457. }
  3458. add_action( 'shutdown', array( 'Jetpack', 'xmlrpc_async_call' ) );
  3459. }
  3460. $args = func_get_args();
  3461. if ( ! empty( $args[0] ) ) {
  3462. call_user_func_array( array( $clients[$client_blog_id], 'addCall' ), $args );
  3463. } elseif ( is_multisite() ) {
  3464. foreach ( $clients as $client_blog_id => $client ) {
  3465. if ( ! $client_blog_id || empty( $client->calls ) ) {
  3466. continue;
  3467. }
  3468. $switch_success = switch_to_blog( $client_blog_id, true );
  3469. if ( ! $switch_success ) {
  3470. continue;
  3471. }
  3472. flush();
  3473. $client->query();
  3474. restore_current_blog();
  3475. }
  3476. } else {
  3477. if ( isset( $clients[0] ) && ! empty( $clients[0]->calls ) ) {
  3478. flush();
  3479. $clients[0]->query();
  3480. }
  3481. }
  3482. }
  3483. public static function staticize_subdomain( $url ) {
  3484. $host = parse_url( $url, PHP_URL_HOST );
  3485. if ( ! preg_match( '/.?(?:wordpress|wp)\.com$/', $host ) ) {
  3486. return $url;
  3487. }
  3488. if ( is_ssl() ) {
  3489. return preg_replace( '|https?://[^/]++/|', 'https://s-ssl.wordpress.com/', $url );
  3490. }
  3491. srand( crc32( basename( $url ) ) );
  3492. $static_counter = rand( 0, 2 );
  3493. srand(); // this resets everything that relies on this, like array_rand() and shuffle()
  3494. return preg_replace( '|://[^/]+?/|', "://s$static_counter.wp.com/", $url );
  3495. }
  3496. /* JSON API Authorization */
  3497. /**
  3498. * Handles the login action for Authorizing the JSON API
  3499. */
  3500. function login_form_json_api_authorization() {
  3501. $this->verify_json_api_authorization_request();
  3502. add_action( 'wp_login', array( &$this, 'store_json_api_authorization_token' ), 10, 2 );
  3503. add_action( 'login_message', array( &$this, 'login_message_json_api_authorization' ) );
  3504. add_action( 'login_form', array( &$this, 'preserve_action_in_login_form_for_json_api_authorization' ) );
  3505. add_filter( 'site_url', array( &$this, 'post_login_form_to_signed_url' ), 10, 3 );
  3506. }
  3507. // Make sure the login form is POSTed to the signed URL so we can reverify the request
  3508. function post_login_form_to_signed_url( $url, $path, $scheme ) {
  3509. if ( 'wp-login.php' !== $path || 'login_post' !== $scheme ) {
  3510. return $url;
  3511. }
  3512. $parsed_url = parse_url( $url );
  3513. $url = strtok( $url, '?' );
  3514. $url = "$url?{$_SERVER['QUERY_STRING']}";
  3515. if ( ! empty( $parsed_url['query'] ) )
  3516. $url .= "&{$parsed_url['query']}";
  3517. return $url;
  3518. }
  3519. // Make sure the POSTed request is handled by the same action
  3520. function preserve_action_in_login_form_for_json_api_authorization() {
  3521. echo "<input type='hidden' name='action' value='jetpack_json_api_authorization' />\n";
  3522. echo "<input type='hidden' name='jetpack_json_api_original_query' value='" . esc_url( set_url_scheme( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ) ) . "' />\n";
  3523. }
  3524. // If someone logs in to approve API access, store the Access Code in usermeta
  3525. function store_json_api_authorization_token( $user_login, $user ) {
  3526. add_filter( 'login_redirect', array( &$this, 'add_token_to_login_redirect_json_api_authorization' ), 10, 3 );
  3527. add_filter( 'allowed_redirect_hosts', array( &$this, 'allow_wpcom_public_api_domain' ) );
  3528. $token = wp_generate_password( 32, false );
  3529. update_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], $token );
  3530. }
  3531. // Add public-api.wordpress.com to the safe redirect whitelist - only added when someone allows API access
  3532. function allow_wpcom_public_api_domain( $domains ) {
  3533. $domains[] = 'public-api.wordpress.com';
  3534. return $domains;
  3535. }
  3536. // Add the Access Code details to the public-api.wordpress.com redirect
  3537. function add_token_to_login_redirect_json_api_authorization( $redirect_to, $original_redirect_to, $user ) {
  3538. return add_query_arg(
  3539. urlencode_deep(
  3540. array(
  3541. 'jetpack-code' => get_user_meta( $user->ID, 'jetpack_json_api_' . $this->json_api_authorization_request['client_id'], true ),
  3542. 'jetpack-user-id' => (int) $user->ID,
  3543. 'jetpack-state' => $this->json_api_authorization_request['state'],
  3544. )
  3545. ),
  3546. $redirect_to
  3547. );
  3548. }
  3549. // Verifies the request by checking the signature
  3550. function verify_json_api_authorization_request() {
  3551. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-signature.php';
  3552. $token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  3553. if ( ! $token || empty( $token->secret ) ) {
  3554. wp_die( __( 'You must connect your Jetpack plugin to WordPress.com to use this feature.' , 'jetpack' ) );
  3555. }
  3556. $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' );
  3557. $jetpack_signature = new Jetpack_Signature( $token->secret, (int) Jetpack_Options::get_option( 'time_diff' ) );
  3558. if ( isset( $_POST['jetpack_json_api_original_query'] ) ) {
  3559. $signature = $jetpack_signature->sign_request( $_GET['token'], $_GET['timestamp'], $_GET['nonce'], '', 'GET', $_POST['jetpack_json_api_original_query'], null, true );
  3560. } else {
  3561. $signature = $jetpack_signature->sign_current_request( array( 'body' => null, 'method' => 'GET' ) );
  3562. }
  3563. if ( ! $signature ) {
  3564. wp_die( $die_error );
  3565. } else if ( is_wp_error( $signature ) ) {
  3566. wp_die( $die_error );
  3567. } else if ( $signature !== $_GET['signature'] ) {
  3568. if ( is_ssl() ) {
  3569. // 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
  3570. $signature = $jetpack_signature->sign_current_request( array( 'scheme' => 'http', 'body' => null, 'method' => 'GET' ) );
  3571. if ( ! $signature || is_wp_error( $signature ) || $signature !== $_GET['signature'] ) {
  3572. wp_die( $die_error );
  3573. }
  3574. } else {
  3575. wp_die( $die_error );
  3576. }
  3577. }
  3578. $timestamp = (int) $_GET['timestamp'];
  3579. $nonce = stripslashes( (string) $_GET['nonce'] );
  3580. if ( ! $this->add_nonce( $timestamp, $nonce ) ) {
  3581. // De-nonce the nonce, at least for 5 minutes.
  3582. // 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)
  3583. $old_nonce_time = get_option( "jetpack_nonce_{$timestamp}_{$nonce}" );
  3584. if ( $old_nonce_time < time() - 300 ) {
  3585. wp_die( __( 'The authorization process expired. Please go back and try again.' , 'jetpack' ) );
  3586. }
  3587. }
  3588. $data = json_decode( base64_decode( stripslashes( $_GET['data'] ) ) );
  3589. $data_filters = array(
  3590. 'state' => 'opaque',
  3591. 'client_id' => 'int',
  3592. 'client_title' => 'string',
  3593. 'client_image' => 'url',
  3594. );
  3595. foreach ( $data_filters as $key => $sanitation ) {
  3596. if ( ! isset( $data->$key ) ) {
  3597. wp_die( $die_error );
  3598. }
  3599. switch ( $sanitation ) {
  3600. case 'int' :
  3601. $this->json_api_authorization_request[$key] = (int) $data->$key;
  3602. break;
  3603. case 'opaque' :
  3604. $this->json_api_authorization_request[$key] = (string) $data->$key;
  3605. break;
  3606. case 'string' :
  3607. $this->json_api_authorization_request[$key] = wp_kses( (string) $data->$key, array() );
  3608. break;
  3609. case 'url' :
  3610. $this->json_api_authorization_request[$key] = esc_url_raw( (string) $data->$key );
  3611. break;
  3612. }
  3613. }
  3614. if ( empty( $this->json_api_authorization_request['client_id'] ) ) {
  3615. wp_die( $die_error );
  3616. }
  3617. }
  3618. function login_message_json_api_authorization( $message ) {
  3619. return '<p class="message">' . sprintf(
  3620. esc_html__( '%s wants to access your site&#8217;s data. Log in to authorize that access.' , 'jetpack' ),
  3621. '<strong>' . esc_html( $this->json_api_authorization_request['client_title'] ) . '</strong>'
  3622. ) . '<img src="' . esc_url( $this->json_api_authorization_request['client_image'] ) . '" /></p>';
  3623. }
  3624. /**
  3625. * Get $content_width, but with a <s>twist</s> filter.
  3626. */
  3627. public static function get_content_width() {
  3628. $content_width = isset( $GLOBALS['content_width'] ) ? $GLOBALS['content_width'] : false;
  3629. return apply_filters( 'jetpack_content_width', $content_width );
  3630. }
  3631. /**
  3632. * Centralize the function here until it gets added to core.
  3633. *
  3634. * @param int|string|object $id_or_email A user ID, email address, or comment object
  3635. * @param int $size Size of the avatar image
  3636. * @param string $default URL to a default image to use if no avatar is available
  3637. * @param bool $force_display Whether to force it to return an avatar even if show_avatars is disabled
  3638. *
  3639. * @return array First element is the URL, second is the class.
  3640. */
  3641. public static function get_avatar_url( $id_or_email, $size = 96, $default = '', $force_display = false ) {
  3642. // Don't bother adding the __return_true filter if it's already there.
  3643. $has_filter = has_filter( 'pre_option_show_avatars', '__return_true' );
  3644. if ( $force_display && ! $has_filter )
  3645. add_filter( 'pre_option_show_avatars', '__return_true' );
  3646. $avatar = get_avatar( $id_or_email, $size, $default );
  3647. if ( $force_display && ! $has_filter )
  3648. remove_filter( 'pre_option_show_avatars', '__return_true' );
  3649. // If no data, fail out.
  3650. if ( is_wp_error( $avatar ) || ! $avatar )
  3651. return array( null, null );
  3652. // Pull out the URL. If it's not there, fail out.
  3653. if ( ! preg_match( '/src=["\']([^"\']+)["\']/', $avatar, $url_matches ) )
  3654. return array( null, null );
  3655. $url = wp_specialchars_decode( $url_matches[1], ENT_QUOTES );
  3656. // Pull out the class, but it's not a big deal if it's missing.
  3657. $class = '';
  3658. if ( preg_match( '/class=["\']([^"\']+)["\']/', $avatar, $class_matches ) )
  3659. $class = wp_specialchars_decode( $class_matches[1], ENT_QUOTES );
  3660. return array( $url, $class );
  3661. }
  3662. /**
  3663. * Pings the WordPress.com Mirror Site for the specified options.
  3664. *
  3665. * @param string|array $option_names The option names to request from the WordPress.com Mirror Site
  3666. *
  3667. * @return array An associative array of the option values as stored in the WordPress.com Mirror Site
  3668. */
  3669. public function get_cloud_site_options( $option_names ) {
  3670. $option_names = array_filter( (array) $option_names, 'is_string' );
  3671. Jetpack::load_xml_rpc_client();
  3672. $xml = new Jetpack_IXR_Client( array( 'user_id' => JETPACK_MASTER_USER, ) );
  3673. $xml->query( 'jetpack.fetchSiteOptions', $option_names );
  3674. if ( $xml->isError() ) {
  3675. return array_flip( $option_names );
  3676. }
  3677. $cloud_site_options = $xml->getResponse();
  3678. return $cloud_site_options;
  3679. }
  3680. /**
  3681. * Fetch the filtered array of options that we should compare to determine an identity crisis.
  3682. *
  3683. * @return array An array of options to check.
  3684. */
  3685. public static function identity_crisis_options_to_check() {
  3686. $options = array(
  3687. 'siteurl',
  3688. 'home',
  3689. );
  3690. return apply_filters( 'jetpack_identity_crisis_options_to_check', $options );
  3691. }
  3692. /**
  3693. * Checks to make sure that local options have the same values as remote options. Will cache the results for up to 24 hours.
  3694. *
  3695. * @param bool $force_recheck Whether to ignore any cached transient and manually re-check.
  3696. *
  3697. * @return array An array of options that do not match. If everything is good, it will evaluate to false.
  3698. */
  3699. public static function check_identity_crisis( $force_recheck = false ) {
  3700. if ( ! Jetpack::is_active() || Jetpack::is_development_mode() )
  3701. return false;
  3702. if ( $force_recheck || false === ( $errors = get_transient( 'jetpack_has_identity_crisis' ) ) ) {
  3703. $options_to_check = self::identity_crisis_options_to_check();
  3704. $cloud_options = Jetpack::init()->get_cloud_site_options( $options_to_check );
  3705. $errors = array();
  3706. foreach ( $cloud_options as $cloud_key => $cloud_value ) {
  3707. // If it's not the same as the local value...
  3708. if ( $cloud_value !== get_option( $cloud_key ) ) {
  3709. // And it's not been added to the whitelist...
  3710. if ( ! self::is_identity_crisis_value_whitelisted( $cloud_key, $cloud_value ) ) {
  3711. /*
  3712. * This should be a temporary hack until a cleaner solution is found.
  3713. *
  3714. * The siteurl and home can be set to use http in General > Settings
  3715. * however some constants can be defined that can force https in wp-admin
  3716. * when this happens wpcom can confuse wporg with a fake identity
  3717. * crisis with a mismatch of http vs https when it should be allowed.
  3718. * we need to check that here.
  3719. *
  3720. * @see https://github.com/Automattic/jetpack/issues/1006
  3721. */
  3722. if( ( 'home' == $cloud_key || 'siteurl' == $cloud_key )
  3723. && ( substr( $cloud_value, 0, 8 ) == "https://" )
  3724. && Jetpack::init()->is_ssl_required_to_visit_site() ) {
  3725. // Ok, we found a mismatch of http and https because of wp-config, not an invalid url
  3726. continue;
  3727. }
  3728. // Then kick an error!
  3729. $errors[ $cloud_key ] = $cloud_value;
  3730. }
  3731. }
  3732. }
  3733. }
  3734. return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
  3735. }
  3736. /**
  3737. * Adds a value to the whitelist for the specified key.
  3738. *
  3739. * @param string $key The option name that we're whitelisting the value for.
  3740. * @param string $value The value that we're intending to add to the whitelist.
  3741. *
  3742. * @return bool Whether the value was added to the whitelist, or false if it was already there.
  3743. */
  3744. public static function whitelist_identity_crisis_value( $key, $value ) {
  3745. if ( self::is_identity_crisis_url_whitelisted( $key, $value ) ) {
  3746. return false;
  3747. }
  3748. $whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
  3749. if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
  3750. $whitelist[ $key ] = array();
  3751. }
  3752. array_push( $whitelist[ $key ], $value );
  3753. Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
  3754. return true;
  3755. }
  3756. /**
  3757. * Checks whether a value is already whitelisted.
  3758. *
  3759. * @param string $key The option name that we're checking the value for.
  3760. * @param string $value The value that we're curious to see if it's on the whitelist.
  3761. *
  3762. * @return bool Whether the value is whitelisted.
  3763. */
  3764. public static function is_identity_crisis_value_whitelisted( $key, $value ) {
  3765. $whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
  3766. if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
  3767. return true;
  3768. }
  3769. return false;
  3770. }
  3771. /**
  3772. * Displays an admin_notice, alerting the user to an identity crisis.
  3773. */
  3774. public function alert_identity_crisis() {
  3775. if ( ! current_user_can( 'manage_options' ) )
  3776. return;
  3777. if ( ! $errors = self::check_identity_crisis() )
  3778. return;
  3779. ?>
  3780. <div id="message" class="updated jetpack-message jp-identity-crisis">
  3781. <div class="jetpack-wrap-container">
  3782. <div class="jetpack-text-container">
  3783. <h3><?php _e( 'Something has gotten mixed up!', 'jetpack' ); ?></h3>
  3784. <?php foreach ( $errors as $key => $value ) : ?>
  3785. <p><?php printf( __( 'Your <code>%1$s</code> option is set up as <strong>%2$s</strong>, but your WordPress.com connection lists it as <strong>%3$s</strong>!', 'jetpack' ), $key, (string) get_option( $key ), $value ); ?></p>
  3786. <?php endforeach; ?>
  3787. <p><a href="<?php echo $this->build_reconnect_url() ?>"><?php _e( 'The data listed above is not for my current site. Please disconnect, and then form a new connection to WordPress.com for this site using my current settings.', 'jetpack' ); ?></a></p>
  3788. <p><a href="#"><?php _e( 'Ignore the difference. This is just a staging site for the real site referenced above.', 'jetpack' ); ?></a></p>
  3789. <p><a href="#"><?php _e( 'That used to be my URL for this site before I changed it. Update the WordPress.com Cloud\'s data to match my current settings.', 'jetpack' ); ?></a></p>
  3790. </div>
  3791. </div>
  3792. </div>
  3793. <?php
  3794. }
  3795. /**
  3796. * Maybe Use a .min.css stylesheet, maybe not.
  3797. *
  3798. * Hooks onto `plugins_url` filter at priority 1, and accepts all 3 args.
  3799. */
  3800. public static function maybe_min_asset( $url, $path, $plugin ) {
  3801. // Short out on things trying to find actual paths.
  3802. if ( ! $path || empty( $plugin ) ) {
  3803. return $url;
  3804. }
  3805. // Strip out the abspath.
  3806. $base = dirname( plugin_basename( $plugin ) );
  3807. // Short out on non-Jetpack assets.
  3808. if ( 'jetpack/' !== substr( $base, 0, 8 ) ) {
  3809. return $url;
  3810. }
  3811. // File name parsing.
  3812. $file = "{$base}/{$path}";
  3813. $full_path = JETPACK__PLUGIN_DIR . substr( $file, 8 );
  3814. $file_name = substr( $full_path, strrpos( $full_path, '/' ) + 1 );
  3815. $file_name_parts_r = array_reverse( explode( '.', $file_name ) );
  3816. $extension = array_shift( $file_name_parts_r );
  3817. if ( in_array( strtolower( $extension ), array( 'css', 'js' ) ) ) {
  3818. // Already pointing at the minified version.
  3819. if ( 'min' === $file_name_parts_r[0] ) {
  3820. return $url;
  3821. }
  3822. $min_full_path = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $full_path );
  3823. if ( file_exists( $min_full_path ) ) {
  3824. $url = preg_replace( "#\.{$extension}$#", ".min.{$extension}", $url );
  3825. }
  3826. }
  3827. return $url;
  3828. }
  3829. /**
  3830. * Maybe inlines a stylesheet.
  3831. *
  3832. * If you'd like to inline a stylesheet instead of printing a link to it,
  3833. * wp_style_add_data( 'handle', 'jetpack-inline', true );
  3834. *
  3835. * Attached to `style_loader_tag` filter.
  3836. *
  3837. * @param string $tag The tag that would link to the external asset.
  3838. * @param string $handle The registered handle of the script in question.
  3839. */
  3840. public static function maybe_inline_style( $tag, $handle ) {
  3841. global $wp_styles;
  3842. $item = $wp_styles->registered[ $handle ];
  3843. if ( ! isset( $item->extra['jetpack-inline'] ) || ! $item->extra['jetpack-inline'] ) {
  3844. return $tag;
  3845. }
  3846. if ( preg_match( '# href=\'([^\']+)\' #i', $tag, $matches ) ) {
  3847. $href = $matches[1];
  3848. // Strip off query string
  3849. if ( $pos = strpos( $href, '?' ) ) {
  3850. $href = substr( $href, 0, $pos );
  3851. }
  3852. // Strip off fragment
  3853. if ( $pos = strpos( $href, '#' ) ) {
  3854. $href = substr( $href, 0, $pos );
  3855. }
  3856. } else {
  3857. return $tag;
  3858. }
  3859. $plugins_dir = plugin_dir_url( JETPACK__PLUGIN_FILE );
  3860. if ( $plugins_dir !== substr( $href, 0, strlen( $plugins_dir ) ) ) {
  3861. return $tag;
  3862. }
  3863. // If this stylesheet has a RTL version, and the RTL version replaces normal...
  3864. if ( isset( $item->extra['rtl'] ) && 'replace' === $item->extra['rtl'] && is_rtl() ) {
  3865. // And this isn't the pass that actually deals with the RTL version...
  3866. if ( false === strpos( $tag, " id='$handle-rtl-css' " ) ) {
  3867. // Short out, as the RTL version will deal with it in a moment.
  3868. return $tag;
  3869. }
  3870. }
  3871. $file = JETPACK__PLUGIN_DIR . substr( $href, strlen( $plugins_dir ) );
  3872. $css = Jetpack::absolutize_css_urls( file_get_contents( $file ), $href );
  3873. if ( $css ) {
  3874. $tag = "<!-- Inline {$item->handle} -->\r\n";
  3875. if ( empty( $item->extra['after'] ) ) {
  3876. wp_add_inline_style( $handle, $css );
  3877. } else {
  3878. array_unshift( $item->extra['after'], $css );
  3879. wp_style_add_data( $handle, 'after', $item->extra['after'] );
  3880. }
  3881. }
  3882. return $tag;
  3883. }
  3884. /**
  3885. * Loads a view file from the views
  3886. *
  3887. * Data passed in with the $data parameter will be available in the
  3888. * template file as $data['value']
  3889. *
  3890. * @param string $template - Template file to load
  3891. * @param array $data - Any data to pass along to the template
  3892. * @return boolean - If template file was found
  3893. **/
  3894. public function load_view( $template, $data = array() ) {
  3895. $views_dir = JETPACK__PLUGIN_DIR . 'views/';
  3896. if( file_exists( $views_dir . $template ) ) {
  3897. require_once( $views_dir . $template );
  3898. return true;
  3899. }
  3900. error_log( "Jetpack: Unable to find view file $views_dir$template" );
  3901. return false;
  3902. }
  3903. /**
  3904. * Sends a ping to the Jetpack servers to toggle on/off remote portions
  3905. * required by some modules.
  3906. *
  3907. * @param string $module_slug
  3908. */
  3909. public function toggle_module_on_wpcom( $module_slug ) {
  3910. Jetpack::init()->sync->register( 'noop' );
  3911. if ( false !== strpos( current_filter(), 'jetpack_activate_module_' ) ) {
  3912. self::check_privacy( $module_slug );
  3913. }
  3914. }
  3915. /**
  3916. * Throws warnings for deprecated hooks to be removed from Jetpack
  3917. */
  3918. public function deprecated_hooks() {
  3919. global $wp_filter;
  3920. /*
  3921. * Format:
  3922. * deprecated_filter_name => replacement_name
  3923. *
  3924. * If there is no replacement us null for replacement_name
  3925. */
  3926. $deprecated_list = array(
  3927. 'jetpack_bail_on_shortcode' => 'jetpack_shortcodes_to_include',
  3928. );
  3929. // This is a silly loop depth. Better way?
  3930. foreach( $deprecated_list AS $hook => $hook_alt ) {
  3931. if( isset( $wp_filter[ $hook ] ) && is_array( $wp_filter[ $hook ] ) ) {
  3932. foreach( $wp_filter[$hook] AS $func => $values ) {
  3933. foreach( $values AS $hooked ) {
  3934. _deprecated_function( $hook . ' used for ' . $hooked['function'], null, $hook_alt );
  3935. }
  3936. }
  3937. }
  3938. }
  3939. }
  3940. /**
  3941. * Converts any url in a stylesheet, to the correct absolute url.
  3942. *
  3943. * Considerations:
  3944. * - Normal, relative URLs `feh.png`
  3945. * - Data URLs `data:image/gif;base64,eh129ehiuehjdhsa==`
  3946. * - Schema-agnostic URLs `//domain.com/feh.png`
  3947. * - Absolute URLs `http://domain.com/feh.png`
  3948. * - Domain root relative URLs `/feh.png`
  3949. *
  3950. * @param $css string: The raw CSS -- should be read in directly from the file.
  3951. * @param $css_file_url: The URL that the file can be accessed at, for calculating paths from.
  3952. */
  3953. public static function absolutize_css_urls( $css, $css_file_url ) {
  3954. $pattern = '#url\((?P<path>[^)]*)\)#i';
  3955. $css_dir = dirname( $css_file_url );
  3956. $p = parse_url( $css_dir );
  3957. $domain = sprintf(
  3958. '%1$s//%2$s%3$s%4$s',
  3959. isset( $p['scheme'] ) ? "{$p['scheme']}:" : '',
  3960. isset( $p['user'], $p['pass'] ) ? "{$p['user']}:{$p['pass']}@" : '',
  3961. $p['host'],
  3962. isset( $p['port'] ) ? ":{$p['port']}" : ''
  3963. );
  3964. if ( preg_match_all( $pattern, $css, $matches, PREG_SET_ORDER ) ) {
  3965. $find = $replace = array();
  3966. foreach ( $matches as $match ) {
  3967. $url = trim( $match['path'], "'\" \t" );
  3968. // If this is a data url, we don't want to mess with it.
  3969. if ( 'data:' === substr( $url, 0, 5 ) ) {
  3970. continue;
  3971. }
  3972. // If this is an absolute or protocol-agnostic url,
  3973. // we don't want to mess with it.
  3974. if ( preg_match( '#^(https?:)?//#i', $url ) ) {
  3975. continue;
  3976. }
  3977. switch ( substr( $url, 0, 1 ) ) {
  3978. case '/':
  3979. $absolute = $domain . $url;
  3980. break;
  3981. default:
  3982. $absolute = $css_dir . '/' . $url;
  3983. }
  3984. $find[] = $match[0];
  3985. $replace[] = sprintf( 'url("%s")', $absolute );
  3986. }
  3987. $css = str_replace( $find, $replace, $css );
  3988. }
  3989. return $css;
  3990. }
  3991. /**
  3992. * This method checks to see if SSL is required by the site in
  3993. * order to visit it in some way other than only setting the
  3994. * https value in the home or siteurl values.
  3995. *
  3996. * @since 3.2
  3997. * @return boolean
  3998. **/
  3999. private function is_ssl_required_to_visit_site() {
  4000. $ssl = is_ssl();
  4001. if ( force_ssl_login() ) {
  4002. $ssl = true;
  4003. } else if ( force_ssl_admin() ) {
  4004. $ssl = true;
  4005. }
  4006. return $ssl;
  4007. }
  4008. /**
  4009. * This methods removes all of the registered css files on the frontend
  4010. * from Jetpack in favor of using a single file. In effect "imploding"
  4011. * all the files into one file.
  4012. *
  4013. * Pros:
  4014. * - Uses only ONE css asset connection instead of 15
  4015. * - Saves a minimum of 56k
  4016. * - Reduces server load
  4017. * - Reduces time to first painted byte
  4018. *
  4019. * Cons:
  4020. * - Loads css for ALL modules. However all selectors are prefixed so it
  4021. * should not cause any issues with themes.
  4022. * - Plugins/themes dequeuing styles no longer do anything. See
  4023. * jetpack_implode_frontend_css filter for a workaround
  4024. *
  4025. * For some situations developers may wish to disable css imploding and
  4026. * instead operate in legacy mode where each file loads seperately and
  4027. * can be edited individually or dequeued. This can be accomplished with
  4028. * the following line:
  4029. *
  4030. * add_filter( 'jetpack_implode_frontend_css', '__return_false' );
  4031. *
  4032. * @since 3.2
  4033. **/
  4034. public function implode_frontend_css() {
  4035. global $wp_styles;
  4036. $do_implode = apply_filters( 'jetpack_implode_frontend_css', true );
  4037. // Do not use the imploded file when default behaviour was altered through the filter
  4038. if ( ! $do_implode ) {
  4039. return;
  4040. }
  4041. // We do not want to use the imploded file in dev mode
  4042. if ( Jetpack::is_development_mode() ) {
  4043. return;
  4044. }
  4045. // Do not use the imploded file if sharing css was dequeued via the sharing settings screen
  4046. if ( get_option( 'sharedaddy_disable_resources' ) ) {
  4047. return;
  4048. }
  4049. /*
  4050. * Now we assume Jetpack is connected and able to serve the single
  4051. * file.
  4052. *
  4053. * In the future there will be a check here to serve the file locally
  4054. * or potentially from the Jetpack CDN
  4055. *
  4056. * For now:
  4057. * - Dequeue ALL of the frontend css files
  4058. * - Enqueue a single imploded css file
  4059. * - Be happy, drink scotch
  4060. */
  4061. $to_dequeue = array(
  4062. 'jetpack-carousel',
  4063. 'grunion.css',
  4064. 'gplus',
  4065. 'the-neverending-homepage',
  4066. 'jetpack_likes',
  4067. 'jetpack_related-posts',
  4068. 'sharedaddy',
  4069. 'jetpack-slideshow',
  4070. 'presentations',
  4071. 'jetpack-subscriptions',
  4072. 'tiled-gallery',
  4073. 'widget-conditions',
  4074. 'jetpack_display_posts_widget',
  4075. 'gravatar-profile-widget',
  4076. 'widget-grid-and-list',
  4077. 'jetpack-widgets'
  4078. );
  4079. $wp_styles->remove( $to_dequeue );
  4080. if( is_rtl() ) {
  4081. wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack-rtl.css', __FILE__ ) );
  4082. } else {
  4083. wp_enqueue_style( 'jetpack_css', plugins_url( 'css/jetpack.css', __FILE__ ) );
  4084. }
  4085. }
  4086. }