PageRenderTime 589ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/class.jetpack.php

https://github.com/ru100fa/jetpack
PHP | 4427 lines | 3110 code | 626 blank | 691 comment | 571 complexity | 4755b1a6deb20f0aa16bcce42a6f1243 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. ),
  70. 'contact-form' => array(
  71. 'Contact Form 7' => 'contact-form-7/wp-contact-form-7.php',
  72. 'Gravity Forms' => 'gravityforms/gravityforms.php',
  73. 'Contact Form Plugin' => 'contact-form-plugin/contact_form.php',
  74. 'Easy Contact Forms' => 'easy-contact-forms/easy-contact-forms.php',
  75. 'Fast Secure Contact Form' => 'si-contact-form/si-contact-form.php',
  76. ),
  77. 'gplus-authorship' => array(
  78. 'WP SEO by Yoast' => 'wordpress-seo/wp-seo.php',
  79. ),
  80. 'minileven' => array(
  81. 'WPtouch' => 'wptouch/wptouch.php',
  82. ),
  83. 'latex' => array(
  84. 'LaTeX for WordPress' => 'latex/latex.php',
  85. 'Youngwhans Simple Latex' => 'youngwhans-simple-latex/yw-latex.php',
  86. 'Easy WP LaTeX' => 'easy-wp-latex-lite/easy-wp-latex-lite.php',
  87. 'MathJax-LaTeX' => 'mathjax-latex/mathjax-latex.php',
  88. 'Enable Latex' => 'enable-latex/enable-latex.php',
  89. 'WP QuickLaTeX' => 'wp-quicklatex/wp-quicklatex.php',
  90. ),
  91. 'random-redirect' => array(
  92. 'Random Redirect 2' => 'random-redirect-2/random-redirect.php',
  93. ),
  94. 'related-posts' => array(
  95. 'YARPP' => 'yet-another-related-posts-plugin/yarpp.php',
  96. 'WordPress Related Posts' => 'wordpress-23-related-posts-plugin/wp_related_posts.php',
  97. 'nrelate Related Content' => 'nrelate-related-content/nrelate-related.php',
  98. 'Contextual Related Posts' => 'contextual-related-posts/contextual-related-posts.php',
  99. 'Related Posts for WordPress' => 'microkids-related-posts/microkids-related-posts.php',
  100. 'outbrain' => 'outbrain/outbrain.php',
  101. 'Shareaholic' => 'shareaholic/shareaholic.php',
  102. 'Sexybookmarks' => 'sexybookmarks/shareaholic.php',
  103. ),
  104. 'sharedaddy' => array(
  105. 'AddThis' => 'addthis/addthis_social_widget.php',
  106. 'Add To Any' => 'add-to-any/add-to-any.php',
  107. 'ShareThis' => 'share-this/sharethis.php',
  108. 'Shareaholic' => 'shareaholic/shareaholic.php',
  109. ),
  110. 'verification-tools' => array(
  111. 'WordPress SEO by Yoast' => 'wordpress-seo/wp-seo.php',
  112. 'WordPress SEO Premium by Yoast' => 'wordpress-seo-premium/wp-seo-premium.php',
  113. 'All in One SEO Pack' => 'all-in-one-seo-pack/all_in_one_seo_pack.php',
  114. ),
  115. 'widget-visibility' => array(
  116. 'Widget Logic' => 'widget-logic/widget_logic.php',
  117. 'Dynamic Widgets' => 'dynamic-widgets/dynamic-widgets.php',
  118. ),
  119. );
  120. /**
  121. * Plugins for which we turn off our Facebook OG Tags implementation.
  122. */
  123. private $open_graph_conflicting_plugins = array(
  124. 'facebook/facebook.php', // Official Facebook plugin
  125. 'wordpress-seo/wp-seo.php', // WordPress SEO by Yoast
  126. 'add-link-to-facebook/add-link-to-facebook.php', // Add Link to Facebook
  127. 'facebook-awd/AWD_facebook.php', // Facebook AWD All in one
  128. 'header-footer/plugin.php', // Header and Footer
  129. 'nextgen-facebook/nextgen-facebook.php', // NextGEN Facebook OG
  130. 'seo-facebook-comments/seofacebook.php', // SEO Facebook Comments
  131. 'seo-ultimate/seo-ultimate.php', // SEO Ultimate
  132. 'sexybookmarks/sexy-bookmarks.php', // Shareaholic
  133. 'shareaholic/sexy-bookmarks.php', // Shareaholic
  134. 'social-discussions/social-discussions.php', // Social Discussions
  135. 'social-networks-auto-poster-facebook-twitter-g/NextScripts_SNAP.php',
  136. // NextScripts SNAP
  137. 'wordbooker/wordbooker.php', // Wordbooker
  138. 'socialize/socialize.php', // Socialize
  139. 'simple-facebook-connect/sfc.php', // Simple Facebook Connect
  140. 'social-sharing-toolkit/social_sharing_toolkit.php', // Social Sharing Toolkit
  141. 'wp-facebook-open-graph-protocol/wp-facebook-ogp.php', // WP Facebook Open Graph protocol
  142. 'opengraph/opengraph.php', // Open Graph
  143. 'sharepress/sharepress.php', // SharePress
  144. 'wp-facebook-like-send-open-graph-meta/wp-facebook-like-send-open-graph-meta.php',
  145. // WP Facebook Like Send & Open Graph Meta
  146. 'network-publisher/networkpub.php', // Network Publisher
  147. 'wp-ogp/wp-ogp.php', // WP-OGP
  148. 'open-graph-protocol-framework/open-graph-protocol-framework.php',
  149. // Open Graph Protocol Framework
  150. 'all-in-one-seo-pack/all_in_one_seo_pack.php', // All in One SEO Pack
  151. 'facebook-featured-image-and-open-graph-meta-tags/fb-featured-image.php',
  152. // Facebook Featured Image & OG Meta Tags
  153. 'add-meta-tags/add-meta-tags.php', // Add Meta Tags
  154. 'only-tweet-like-share-and-google-1/tweet-like-plusone.php',
  155. // Tweet, Like, Google +1 and Share
  156. 'easy-facebook-share-thumbnails/esft.php', // Easy Facebook Share Thumbnail
  157. '2-click-socialmedia-buttons/2-click-socialmedia-buttons.php',
  158. // 2 Click Social Media Buttons
  159. 'facebook-thumb-fixer/_facebook-thumb-fixer.php', // Facebook Thumb Fixer
  160. 'zoltonorg-social-plugin/zosp.php', // Zolton.org Social Plugin
  161. 'wp-caregiver/wp-caregiver.php', // WP Caregiver
  162. 'facebook-revised-open-graph-meta-tag/index.php', // Facebook Revised Open Graph Meta Tag
  163. 'facebook-and-digg-thumbnail-generator/facebook-and-digg-thumbnail-generator.php',
  164. // Fedmich's Facebook Open Graph Meta
  165. 'facebook-meta-tags/facebook-metatags.php', // Facebook Meta Tags
  166. 'wordpress-seo-premium/wp-seo-premium.php', // WordPress SEO Premium by Yoast
  167. );
  168. /**
  169. * Plugins for which we turn off our Twitter Cards Tags implementation.
  170. */
  171. private $twitter_cards_conflicting_plugins = array(
  172. 'twitter-cards/twitter-cards.php', // Twitter Cards
  173. 'twitter-cards-meta/twitter-cards-meta.php', // Twitter Cards Meta
  174. 'ig-twitter-cards/ig-twitter-cards.php', // IG:Twitter Cards
  175. 'jm-twitter-cards/jm-twitter-cards.php', // JM Twitter Cards
  176. 'wp-twitter-cards/twitter_cards.php', // WP Twitter Cards
  177. 'eewee-twitter-card/index.php', // Eewee Twitter Card
  178. 'kevinjohn-gallagher-pure-web-brilliants-social-graph-twitter-cards-extention/kevinjohn_gallagher___social_graph_twitter_output.php',
  179. // Pure Web Brilliant's Social Graph Twitter Cards Extension
  180. );
  181. /**
  182. * Message to display in admin_notice
  183. * @var string
  184. */
  185. var $message = '';
  186. /**
  187. * Error to display in admin_notice
  188. * @var string
  189. */
  190. var $error = '';
  191. /**
  192. * Modules that need more privacy description.
  193. * @var string
  194. */
  195. var $privacy_checks = '';
  196. /**
  197. * Stats to record once the page loads
  198. *
  199. * @var array
  200. */
  201. var $stats = array();
  202. /**
  203. * Jetpack_Sync object
  204. */
  205. var $sync;
  206. /**
  207. * Verified data for JSON authorization request
  208. */
  209. var $json_api_authorization_request = array();
  210. /**
  211. * Holds the singleton instance of this class
  212. * @since 2.3.3
  213. * @var Jetpack
  214. */
  215. static $instance = false;
  216. /**
  217. * Singleton
  218. * @static
  219. */
  220. public static function init() {
  221. if ( ! self::$instance ) {
  222. if ( did_action( 'plugins_loaded' ) )
  223. self::plugin_textdomain();
  224. else
  225. add_action( 'plugins_loaded', array( __CLASS__, 'plugin_textdomain' ) );
  226. self::$instance = new Jetpack;
  227. self::$instance->plugin_upgrade();
  228. }
  229. return self::$instance;
  230. }
  231. /**
  232. * Must never be called statically
  233. */
  234. function plugin_upgrade() {
  235. // Upgrade: 1.1 -> 1.2
  236. if ( get_option( 'jetpack_id' ) ) {
  237. // Move individual jetpack options to single array of options
  238. $options = array();
  239. foreach ( Jetpack_Options::get_option_names() as $option ) {
  240. if ( false !== $value = get_option( "jetpack_$option" ) ) {
  241. $options[$option] = $value;
  242. }
  243. }
  244. if ( $options ) {
  245. Jetpack_Options::update_options( $options );
  246. foreach ( array_keys( $options ) as $option ) {
  247. delete_option( "jetpack_$option" );
  248. }
  249. }
  250. // Add missing version and old_version options
  251. if ( ! $version = Jetpack_Options::get_option( 'version' ) ) {
  252. $version = $old_version = '1.1:' . time();
  253. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  254. }
  255. }
  256. // Upgrade from a single user token to a user_id-indexed array and a master_user ID
  257. if ( ! Jetpack_Options::get_option( 'user_tokens' ) ) {
  258. if ( $user_token = Jetpack_Options::get_option( 'user_token' ) ) {
  259. $token_parts = explode( '.', $user_token );
  260. if ( isset( $token_parts[2] ) ) {
  261. $master_user = $token_parts[2];
  262. $user_tokens = array( $master_user => $user_token );
  263. Jetpack_Options::update_options( compact( 'master_user', 'user_tokens' ) );
  264. Jetpack_Options::delete_option( 'user_token' );
  265. } else {
  266. // @todo: is this even possible?
  267. trigger_error( sprintf( 'Jetpack::plugin_upgrade found no user_id in user_token "%s"', $user_token ), E_USER_WARNING );
  268. }
  269. }
  270. }
  271. }
  272. /**
  273. * Constructor. Initializes WordPress hooks
  274. */
  275. private function Jetpack() {
  276. /**
  277. * Do things that should run even in the network admin
  278. * here, before we potentially fail out.
  279. */
  280. add_filter( 'jetpack_require_lib_dir', array( $this, 'require_lib_dir' ) );
  281. /*
  282. * Load things that should only be in Network Admin.
  283. *
  284. * For now blow away everything else until a more full
  285. * understanding of what is needed at the network level is
  286. * available
  287. */
  288. if( is_multisite() ) {
  289. Jetpack_Network::init();
  290. if( is_network_admin() )
  291. return; // End here to prevent single site actions from firing
  292. }
  293. $this->sync = new Jetpack_Sync;
  294. // Modules should do Jetpack_Sync::sync_options( __FILE__, $option, ... ); instead
  295. // We access the "internal" method here only because the Jetpack object isn't instantiated yet
  296. $this->sync->options(
  297. JETPACK__PLUGIN_DIR . 'jetpack.php',
  298. 'home',
  299. 'siteurl',
  300. 'blogname',
  301. 'gmt_offset',
  302. 'timezone_string'
  303. );
  304. if ( defined( 'XMLRPC_REQUEST' ) && XMLRPC_REQUEST && isset( $_GET['for'] ) && 'jetpack' == $_GET['for'] ) {
  305. @ini_set( 'display_errors', false ); // Display errors can cause the XML to be not well formed.
  306. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-xmlrpc-server.php';
  307. $this->xmlrpc_server = new Jetpack_XMLRPC_Server();
  308. $this->require_jetpack_authentication();
  309. if ( Jetpack::is_active() ) {
  310. // Hack to preserve $HTTP_RAW_POST_DATA
  311. add_filter( 'xmlrpc_methods', array( $this, 'xmlrpc_methods' ) );
  312. $signed = $this->verify_xml_rpc_signature();
  313. if ( $signed && ! is_wp_error( $signed ) ) {
  314. // The actual API methods.
  315. add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'xmlrpc_methods' ) );
  316. } else {
  317. add_filter( 'xmlrpc_methods', '__return_empty_array' );
  318. }
  319. } else {
  320. // The bootstrap API methods.
  321. add_filter( 'xmlrpc_methods', array( $this->xmlrpc_server, 'bootstrap_xmlrpc_methods' ) );
  322. }
  323. // Now that no one can authenticate, and we're whitelisting all XML-RPC methods, force enable_xmlrpc on.
  324. add_filter( 'pre_option_enable_xmlrpc', '__return_true' );
  325. } elseif ( is_admin() && isset( $_POST['action'] ) && 'jetpack_upload_file' == $_POST['action'] ) {
  326. $this->require_jetpack_authentication();
  327. $this->add_remote_request_handlers();
  328. } else {
  329. if ( Jetpack::is_active() ) {
  330. add_action( 'login_form_jetpack_json_api_authorization', array( &$this, 'login_form_json_api_authorization' ) );
  331. }
  332. }
  333. if ( Jetpack::is_active() ) {
  334. Jetpack_Heartbeat::init();
  335. }
  336. add_action( 'jetpack_clean_nonces', array( 'Jetpack', 'clean_nonces' ) );
  337. if ( ! wp_next_scheduled( 'jetpack_clean_nonces' ) ) {
  338. wp_schedule_event( time(), 'hourly', 'jetpack_clean_nonces' );
  339. }
  340. add_filter( 'xmlrpc_blog_options', array( $this, 'xmlrpc_options' ) );
  341. add_action( 'admin_menu', array( $this, 'admin_menu' ), 999 ); // run late so that other plugins hooking into this menu don't get left out
  342. add_action( 'admin_init', array( $this, 'admin_init' ) );
  343. add_action( 'admin_init', array( $this, 'dismiss_jetpack_notice' ) );
  344. add_filter( 'admin_body_class', array( $this, 'admin_body_class' ) );
  345. add_action( 'wp_ajax_jetpack-check-news-subscription', array( $this, 'check_news_subscription' ) );
  346. add_action( 'wp_ajax_jetpack-subscribe-to-news', array( $this, 'subscribe_to_news' ) );
  347. add_action( 'wp_ajax_jetpack-sync-reindex-trigger', array( $this, 'sync_reindex_trigger' ) );
  348. add_action( 'wp_ajax_jetpack-sync-reindex-status', array( $this, 'sync_reindex_status' ) );
  349. add_action( 'wp_loaded', array( $this, 'register_assets' ) );
  350. add_action( 'wp_enqueue_scripts', array( $this, 'devicepx' ) );
  351. add_action( 'customize_controls_enqueue_scripts', array( $this, 'devicepx' ) );
  352. add_action( 'admin_enqueue_scripts', array( $this, 'devicepx' ) );
  353. // add_action( 'jetpack_admin_menu', array( $this, 'admin_menu_modules' ) );
  354. add_action( 'jetpack_activate_module', array( $this, 'activate_module_actions' ) );
  355. add_action( 'plugins_loaded', array( $this, 'extra_oembed_providers' ) );
  356. /**
  357. * These actions run checks to load additional files.
  358. * They check for external files or plugins, so they need to run as late as possible.
  359. */
  360. add_action( 'wp_head', array( $this, 'check_open_graph' ), 1 );
  361. add_action( 'plugins_loaded', array( $this, 'check_twitter_tags' ), 999 );
  362. add_action( 'plugins_loaded', array( $this, 'check_rest_api_compat' ), 1000 );
  363. add_filter( 'map_meta_cap', array( $this, 'jetpack_custom_caps' ), 1, 4 );
  364. add_filter( 'jetpack_get_default_modules', array( $this, 'filter_default_modules' ) );
  365. add_filter( 'jetpack_get_default_modules', array( $this, 'handle_deprecated_modules' ), 99 );
  366. }
  367. /**
  368. * If there are any stats that need to be pushed, but haven't been, push them now.
  369. */
  370. function __destruct() {
  371. if ( ! empty( $this->stats ) ) {
  372. $this->do_stats( 'server_side' );
  373. }
  374. }
  375. function jetpack_custom_caps( $caps, $cap, $user_id, $args ) {
  376. switch( $cap ) {
  377. case 'jetpack_connect' :
  378. case 'jetpack_reconnect' :
  379. if ( Jetpack::is_development_mode() ) {
  380. $caps = array( 'do_not_allow' );
  381. break;
  382. }
  383. /**
  384. * Pass through. If it's not development mode, these should match disconnect.
  385. * Let users disconnect if it's development mode, just in case things glitch.
  386. */
  387. case 'jetpack_disconnect' :
  388. /**
  389. * In multisite, can individual site admins manage their own connection?
  390. *
  391. * Ideally, this should be extracted out to a separate filter in the Jetpack_Network class.
  392. */
  393. if ( is_multisite() && ! is_super_admin() && is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
  394. if ( ! Jetpack_Network::init()->get_option( 'sub-site-connection-override' ) ) {
  395. /**
  396. * We need to update the option name -- it's terribly unclear which
  397. * direction the override goes.
  398. *
  399. * @todo: Update the option name to `sub-sites-can-manage-own-connections`
  400. */
  401. $caps = array( 'do_not_allow' );
  402. break;
  403. }
  404. }
  405. $caps = array( 'manage_options' );
  406. break;
  407. case 'jetpack_manage_modules' :
  408. case 'jetpack_activate_modules' :
  409. case 'jetpack_deactivate_modules' :
  410. $caps = array( 'manage_options' );
  411. break;
  412. case 'jetpack_configure_modules' :
  413. $caps = array( 'manage_options' );
  414. break;
  415. case 'jetpack_admin_page' :
  416. if ( Jetpack::is_development_mode() ) {
  417. $caps = array( 'manage_options' );
  418. break;
  419. }
  420. /**
  421. * Pass through. If it's not development mode, these should match the admin page.
  422. * Let users disconnect if it's development mode, just in case things glitch.
  423. */
  424. case 'jetpack_connect_user' :
  425. if ( Jetpack::is_development_mode() ) {
  426. $caps = array( 'do_not_allow' );
  427. break;
  428. }
  429. $caps = array( 'read' );
  430. break;
  431. }
  432. return $caps;
  433. }
  434. function require_jetpack_authentication() {
  435. // Don't let anyone authenticate
  436. $_COOKIE = array();
  437. remove_all_filters( 'authenticate' );
  438. /**
  439. * For the moment, remove Limit Login Attempts if its xmlrpc for Jetpack.
  440. * If Limit Login Attempts is installed as a mu-plugin, it can occasionally
  441. * generate false-positives.
  442. */
  443. remove_filter( 'wp_login_failed', 'limit_login_failed' );
  444. if ( Jetpack::is_active() ) {
  445. // Allow Jetpack authentication
  446. add_filter( 'authenticate', array( $this, 'authenticate_jetpack' ), 10, 3 );
  447. }
  448. }
  449. /**
  450. * Load language files
  451. */
  452. public static function plugin_textdomain() {
  453. load_plugin_textdomain( 'jetpack', false, dirname( plugin_basename( __FILE__ ) ) . '/languages/' );
  454. }
  455. /**
  456. * Register assets for use in various modules and the Jetpack admin page.
  457. *
  458. * @uses wp_script_is, wp_register_script, plugins_url
  459. * @action wp_loaded
  460. * @return null
  461. */
  462. public function register_assets() {
  463. if ( ! wp_script_is( 'spin', 'registered' ) )
  464. wp_register_script( 'spin', plugins_url( '_inc/spin.js', __FILE__ ), false, '1.3' );
  465. if ( ! wp_script_is( 'jquery.spin', 'registered' ) )
  466. wp_register_script( 'jquery.spin', plugins_url( '_inc/jquery.spin.js', __FILE__ ) , array( 'jquery', 'spin' ), '1.3' );
  467. if ( ! wp_script_is( 'jetpack-gallery-settings', 'registered' ) )
  468. wp_register_script( 'jetpack-gallery-settings', plugins_url( '_inc/gallery-settings.js', __FILE__ ), array( 'media-views' ), '20121225' );
  469. /**
  470. * As jetpack_register_genericons is by default fired off a hook,
  471. * the hook may have already fired by this point.
  472. * So, let's just trigger it manually.
  473. */
  474. require_once( JETPACK__PLUGIN_DIR . '_inc/genericons.php' );
  475. jetpack_register_genericons();
  476. if ( ! wp_style_is( 'jetpack-icons', 'registered' ) )
  477. wp_register_style( 'jetpack-icons', plugins_url( '_inc/jetpack-icons/jetpack-icons.css', __FILE__ ), false, JETPACK__VERSION );
  478. }
  479. /**
  480. * Device Pixels support
  481. * This improves the resolution of gravatars and wordpress.com uploads on hi-res and zoomed browsers.
  482. */
  483. function devicepx() {
  484. if ( Jetpack::is_active() ) {
  485. wp_enqueue_script( 'devicepx', set_url_scheme( 'http://s0.wp.com/wp-content/js/devicepx-jetpack.js' ), array(), gmdate( 'oW' ), true );
  486. }
  487. }
  488. /*
  489. * Returns the location of Jetpack's lib directory. This filter is applied
  490. * in require_lib().
  491. *
  492. * @filter require_lib_dir
  493. */
  494. function require_lib_dir( $lib_dir ) {
  495. return JETPACK__PLUGIN_DIR . '_inc/lib';
  496. }
  497. /**
  498. * Is Jetpack active?
  499. */
  500. public static function is_active() {
  501. return (bool) Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  502. }
  503. /**
  504. * Is Jetpack in development (offline) mode?
  505. */
  506. public static function is_development_mode() {
  507. $development_mode = false;
  508. if ( defined( 'JETPACK_DEV_DEBUG' ) ) {
  509. $development_mode = JETPACK_DEV_DEBUG;
  510. }
  511. elseif ( site_url() && false === strpos( site_url(), '.' ) ) {
  512. $development_mode = true;
  513. }
  514. return apply_filters( 'jetpack_development_mode', $development_mode );
  515. }
  516. /**
  517. * Is a given user (or the current user if none is specified) linked to a WordPress.com user?
  518. */
  519. public static function is_user_connected( $user_id = false ) {
  520. $user_id = false === $user_id ? get_current_user_id() : absint( $user_id );
  521. if ( ! $user_id ) {
  522. return false;
  523. }
  524. return (bool) Jetpack_Data::get_access_token( $user_id );
  525. }
  526. /**
  527. * Get the wpcom email of the current connected user.
  528. */
  529. public static function get_connected_user_email() {
  530. Jetpack::load_xml_rpc_client();
  531. $xml = new Jetpack_IXR_Client( array(
  532. 'user_id' => get_current_user_id()
  533. ) );
  534. $xml->query( 'wpcom.getUserEmail' );
  535. if ( ! $xml->isError() ) {
  536. return $xml->getResponse();
  537. }
  538. return false;
  539. }
  540. function current_user_is_connection_owner() {
  541. $user_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  542. return $user_token && is_object( $user_token ) && isset( $user_token->external_user_id ) && get_current_user_id() === $user_token->external_user_id;
  543. }
  544. /**
  545. * Add any extra oEmbed providers that we know about and use on wpcom for feature parity.
  546. */
  547. function extra_oembed_providers() {
  548. // Cloudup: https://dev.cloudup.com/#oembed
  549. wp_oembed_add_provider( 'https://cloudup.com/*' , 'https://cloudup.com/oembed' );
  550. }
  551. /**
  552. * Synchronize connected user role changes
  553. */
  554. function user_role_change( $user_id ) {
  555. if ( Jetpack::is_active() && Jetpack::is_user_connected( $user_id ) ) {
  556. $current_user_id = get_current_user_id();
  557. wp_set_current_user( $user_id );
  558. $role = $this->translate_current_user_to_role();
  559. $signed_role = $this->sign_role( $role );
  560. wp_set_current_user( $current_user_id );
  561. $master_token = Jetpack_Data::get_access_token( JETPACK_MASTER_USER );
  562. $master_user_id = absint( $master_token->external_user_id );
  563. if ( ! $master_user_id )
  564. return; // this shouldn't happen
  565. Jetpack::xmlrpc_async_call( 'jetpack.updateRole', $user_id, $signed_role );
  566. //@todo retry on failure
  567. //try to choose a new master if we're demoting the current one
  568. if ( $user_id == $master_user_id && 'administrator' != $role ) {
  569. $query = new WP_User_Query(
  570. array(
  571. 'fields' => array( 'id' ),
  572. 'role' => 'administrator',
  573. 'orderby' => 'id',
  574. 'exclude' => array( $master_user_id ),
  575. )
  576. );
  577. $new_master = false;
  578. foreach ( $query->results as $result ) {
  579. $uid = absint( $result->id );
  580. if ( $uid && Jetpack::is_user_connected( $uid ) ) {
  581. $new_master = $uid;
  582. break;
  583. }
  584. }
  585. if ( $new_master ) {
  586. Jetpack_Options::update_option( 'master_user', $new_master );
  587. }
  588. // else disconnect..?
  589. }
  590. }
  591. }
  592. /**
  593. * Loads the currently active modules.
  594. */
  595. public static function load_modules() {
  596. /*
  597. if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
  598. return;
  599. }
  600. */
  601. $version = Jetpack_Options::get_option( 'version' );
  602. if ( ! $version ) {
  603. $version = $old_version = JETPACK__VERSION . ':' . time();
  604. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  605. }
  606. list( $version ) = explode( ':', $version );
  607. $modules = array_filter( Jetpack::get_active_modules(), array( 'Jetpack', 'is_module' ) );
  608. $modules_data = array();
  609. // Don't load modules that have had "Major" changes since the stored version until they have been deactivated/reactivated through the lint check.
  610. if ( version_compare( $version, JETPACK__VERSION, '<' ) ) {
  611. $updated_modules = array();
  612. foreach ( $modules as $module ) {
  613. $modules_data[ $module ] = Jetpack::get_module( $module );
  614. if ( ! isset( $modules_data[ $module ]['changed'] ) ) {
  615. continue;
  616. }
  617. if ( version_compare( $modules_data[ $module ]['changed'], $version, '<=' ) ) {
  618. continue;
  619. }
  620. $updated_modules[] = $module;
  621. }
  622. $modules = array_diff( $modules, $updated_modules );
  623. }
  624. foreach ( $modules as $module ) {
  625. // If not connected and we're in dev mode, disable modules requiring a connection
  626. if ( ! Jetpack::is_active() ) {
  627. if ( empty( $modules_data[ $module ] ) ) {
  628. $modules_data[ $module ] = Jetpack::get_module( $module );
  629. }
  630. if ( $modules_data[ $module ]['requires_connection'] || ! Jetpack::is_development_mode() ) {
  631. continue;
  632. }
  633. }
  634. if ( did_action( 'jetpack_module_loaded_' . $module ) ) {
  635. continue;
  636. }
  637. require Jetpack::get_module_path( $module );
  638. do_action( 'jetpack_module_loaded_' . $module );
  639. }
  640. do_action( 'jetpack_modules_loaded' );
  641. // 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.
  642. if ( Jetpack::is_active() || Jetpack::is_development_mode() )
  643. require_once( JETPACK__PLUGIN_DIR . 'modules/module-extras.php' );
  644. }
  645. /**
  646. * Check if Jetpack's REST API compat file should be included
  647. * @action plugins_loaded
  648. * @return null
  649. */
  650. public function check_rest_api_compat() {
  651. $_jetpack_rest_api_compat_includes = apply_filters( 'jetpack_rest_api_compat', array() );
  652. if ( function_exists( 'bbpress' ) )
  653. $_jetpack_rest_api_compat_includes[] = JETPACK__PLUGIN_DIR . 'class.jetpack-bbpress-json-api-compat.php';
  654. foreach ( $_jetpack_rest_api_compat_includes as $_jetpack_rest_api_compat_include )
  655. require_once $_jetpack_rest_api_compat_include;
  656. }
  657. /**
  658. * Gets all plugins currently active in values, regardless of whether they're
  659. * traditionally activated or network activated.
  660. *
  661. * @todo Store the result in core's object cache maybe?
  662. */
  663. public static function get_active_plugins() {
  664. $active_plugins = (array) get_option( 'active_plugins', array() );
  665. if ( is_multisite() ) {
  666. // Due to legacy code, active_sitewide_plugins stores them in the keys,
  667. // whereas active_plugins stores them in the values.
  668. $network_plugins = array_keys( get_site_option( 'active_sitewide_plugins', array() ) );
  669. if ( $network_plugins ) {
  670. $active_plugins = array_merge( $active_plugins, $network_plugins );
  671. }
  672. }
  673. sort( $active_plugins );
  674. return $active_plugins;
  675. }
  676. /**
  677. * Checks whether a specific plugin is active.
  678. *
  679. * We don't want to store these in a static variable, in case
  680. * there are switch_to_blog() calls involved.
  681. */
  682. public static function is_plugin_active( $plugin = 'jetpack/jetpack.php' ) {
  683. return in_array( $plugin, self::get_active_plugins() );
  684. }
  685. /**
  686. * Check if Jetpack's Open Graph tags should be used.
  687. * If certain plugins are active, Jetpack's og tags are suppressed.
  688. *
  689. * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
  690. * @action plugins_loaded
  691. * @return null
  692. */
  693. public function check_open_graph() {
  694. if ( in_array( 'publicize', Jetpack::get_active_modules() ) || in_array( 'sharedaddy', Jetpack::get_active_modules() ) ) {
  695. add_filter( 'jetpack_enable_open_graph', '__return_true', 0 );
  696. }
  697. $active_plugins = self::get_active_plugins();
  698. if ( ! empty( $active_plugins ) ) {
  699. foreach ( $this->open_graph_conflicting_plugins as $plugin ) {
  700. if ( in_array( $plugin, $active_plugins ) ) {
  701. add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );
  702. break;
  703. }
  704. }
  705. }
  706. if ( apply_filters( 'jetpack_enable_open_graph', false ) ) {
  707. require_once JETPACK__PLUGIN_DIR . 'functions.opengraph.php';
  708. }
  709. }
  710. /**
  711. * Check if Jetpack's Twitter tags should be used.
  712. * If certain plugins are active, Jetpack's twitter tags are suppressed.
  713. *
  714. * @uses Jetpack::get_active_modules, add_filter, get_option, apply_filters
  715. * @action plugins_loaded
  716. * @return null
  717. */
  718. public function check_twitter_tags() {
  719. $active_plugins = self::get_active_plugins();
  720. if ( ! empty( $active_plugins ) ) {
  721. foreach ( $this->twitter_cards_conflicting_plugins as $plugin ) {
  722. if ( in_array( $plugin, $active_plugins ) ) {
  723. add_filter( 'jetpack_disable_twitter_cards', '__return_true', 99 );
  724. break;
  725. }
  726. }
  727. }
  728. if ( apply_filters( 'jetpack_disable_twitter_cards', true ) ) {
  729. require_once JETPACK__PLUGIN_DIR . 'class.jetpack-twitter-cards.php';
  730. }
  731. }
  732. /* Jetpack Options API */
  733. public static function get_option_names( $type = 'compact' ) {
  734. return Jetpack_Options::get_option_names( $type );
  735. }
  736. /**
  737. * Returns the requested option. Looks in jetpack_options or jetpack_$name as appropriate.
  738. *
  739. * @param string $name Option name
  740. * @param mixed $default (optional)
  741. */
  742. public static function get_option( $name, $default = false ) {
  743. return Jetpack_Options::get_option( $name, $default );
  744. }
  745. /**
  746. * Stores two secrets and a timestamp so WordPress.com can make a request back and verify an action
  747. * Does some extra verification so urls (such as those to public-api, register, etc) can't just be crafted
  748. * $name must be a registered option name.
  749. */
  750. public static function create_nonce( $name ) {
  751. $secret = wp_generate_password( 32, false ) . ':' . wp_generate_password( 32, false ) . ':' . ( time() + 600 );
  752. Jetpack_Options::update_option( $name, $secret );
  753. @list( $secret_1, $secret_2, $eol ) = explode( ':', Jetpack_Options::get_option( $name ) );
  754. if ( empty( $secret_1 ) || empty( $secret_2 ) || $eol < time() )
  755. return new Jetpack_Error( 'missing_secrets' );
  756. return array(
  757. 'secret_1' => $secret_1,
  758. 'secret_2' => $secret_2,
  759. 'eol' => $eol,
  760. );
  761. }
  762. /**
  763. * Updates the single given option. Updates jetpack_options or jetpack_$name as appropriate.
  764. *
  765. * @param string $name Option name
  766. * @param mixed $value Option value
  767. */
  768. public static function update_option( $name, $value ) {
  769. return Jetpack_Options::update_option( $name, $value );
  770. }
  771. /**
  772. * Updates the multiple given options. Updates jetpack_options and/or jetpack_$name as appropriate.
  773. *
  774. * @param array $array array( option name => option value, ... )
  775. */
  776. public static function update_options( $array ) {
  777. return Jetpack_Options::update_options( $array );
  778. }
  779. /**
  780. * Deletes the given option. May be passed multiple option names as an array.
  781. * Updates jetpack_options and/or deletes jetpack_$name as appropriate.
  782. *
  783. * @param string|array $names
  784. */
  785. public static function delete_option( $names ) {
  786. return Jetpack_Options::delete_option( $names );
  787. }
  788. /**
  789. * Enters a user token into the user_tokens option
  790. *
  791. * @param int $user_id
  792. * @param string $token
  793. * return bool
  794. */
  795. public static function update_user_token( $user_id, $token, $is_master_user ) {
  796. // not designed for concurrent updates
  797. $user_tokens = Jetpack_Options::get_option( 'user_tokens' );
  798. if ( ! is_array( $user_tokens ) )
  799. $user_tokens = array();
  800. $user_tokens[$user_id] = $token;
  801. if ( $is_master_user ) {
  802. $master_user = $user_id;
  803. $options = compact( 'user_tokens', 'master_user' );
  804. } else {
  805. $options = compact( 'user_tokens' );
  806. }
  807. return Jetpack_Options::update_options( $options );
  808. }
  809. /**
  810. * Returns an array of all PHP files in the specified absolute path.
  811. * Equivalent to glob( "$absolute_path/*.php" ).
  812. *
  813. * @param string $absolute_path The absolute path of the directory to search.
  814. * @return array Array of absolute paths to the PHP files.
  815. */
  816. public static function glob_php( $absolute_path ) {
  817. $absolute_path = untrailingslashit( $absolute_path );
  818. $files = array();
  819. if ( ! $dir = @opendir( $absolute_path ) ) {
  820. return $files;
  821. }
  822. while ( false !== $file = readdir( $dir ) ) {
  823. if ( '.' == substr( $file, 0, 1 ) || '.php' != substr( $file, -4 ) ) {
  824. continue;
  825. }
  826. $file = "$absolute_path/$file";
  827. if ( ! is_file( $file ) ) {
  828. continue;
  829. }
  830. $files[] = $file;
  831. }
  832. closedir( $dir );
  833. return $files;
  834. }
  835. public function activate_new_modules() {
  836. if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
  837. return;
  838. }
  839. $jetpack_old_version = Jetpack_Options::get_option( 'version' ); // [sic]
  840. if ( ! $jetpack_old_version ) {
  841. $jetpack_old_version = $version = $old_version = '1.1:' . time();
  842. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  843. }
  844. list( $jetpack_version ) = explode( ':', $jetpack_old_version ); // [sic]
  845. if ( version_compare( JETPACK__VERSION, $jetpack_version, '<=' ) ) {
  846. return;
  847. }
  848. $active_modules = Jetpack::get_active_modules();
  849. $reactivate_modules = array();
  850. foreach ( $active_modules as $active_module ) {
  851. $module = Jetpack::get_module( $active_module );
  852. if ( ! isset( $module['changed'] ) ) {
  853. continue;
  854. }
  855. if ( version_compare( $module['changed'], $jetpack_version, '<=' ) ) {
  856. continue;
  857. }
  858. $reactivate_modules[] = $active_module;
  859. Jetpack::deactivate_module( $active_module );
  860. }
  861. if ( version_compare( $jetpack_version, '1.9.2', '<' ) && version_compare( '1.9-something', JETPACK__VERSION, '<' ) ) {
  862. add_action( 'jetpack_activate_default_modules', array( $this->sync, 'sync_all_registered_options' ), 1000 );
  863. }
  864. Jetpack_Options::update_options(
  865. array(
  866. 'version' => JETPACK__VERSION . ':' . time(),
  867. 'old_version' => $jetpack_old_version,
  868. )
  869. );
  870. Jetpack::state( 'message', 'modules_activated' );
  871. Jetpack::activate_default_modules( $jetpack_version, JETPACK__VERSION, $reactivate_modules );
  872. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  873. exit;
  874. }
  875. /**
  876. * List available Jetpack modules. Simply lists .php files in /modules/.
  877. * Make sure to tuck away module "library" files in a sub-directory.
  878. */
  879. public static function get_available_modules( $min_version = false, $max_version = false ) {
  880. static $modules = null;
  881. if ( ! isset( $modules ) ) {
  882. $files = Jetpack::glob_php( JETPACK__PLUGIN_DIR . 'modules' );
  883. $modules = array();
  884. foreach ( $files as $file ) {
  885. if ( ! $headers = Jetpack::get_module( $file ) ) {
  886. continue;
  887. }
  888. $modules[ Jetpack::get_module_slug( $file ) ] = $headers['introduced'];
  889. }
  890. }
  891. $modules = apply_filters( 'jetpack_get_available_modules', $modules, $min_version, $max_version );
  892. if ( ! $min_version && ! $max_version ) {
  893. return array_keys( $modules );
  894. }
  895. $r = array();
  896. foreach ( $modules as $slug => $introduced ) {
  897. if ( $min_version && version_compare( $min_version, $introduced, '>=' ) ) {
  898. continue;
  899. }
  900. if ( $max_version && version_compare( $max_version, $introduced, '<' ) ) {
  901. continue;
  902. }
  903. $r[] = $slug;
  904. }
  905. return $r;
  906. }
  907. /**
  908. * Default modules loaded on activation.
  909. */
  910. public static function get_default_modules( $min_version = false, $max_version = false ) {
  911. $return = array();
  912. foreach ( Jetpack::get_available_modules( $min_version, $max_version ) as $module ) {
  913. $module_data = Jetpack::get_module( $module );
  914. switch ( strtolower( $module_data['auto_activate'] ) ) {
  915. case 'yes' :
  916. $return[] = $module;
  917. break;
  918. case 'public' :
  919. if ( Jetpack_Options::get_option( 'public' ) ) {
  920. $return[] = $module;
  921. }
  922. break;
  923. case 'no' :
  924. default :
  925. break;
  926. }
  927. }
  928. return apply_filters( 'jetpack_get_default_modules', $return, $min_version, $max_version );
  929. }
  930. /**
  931. * Checks activated modules during auto-activation to determine
  932. * if any of those modules are being deprecated. If so, close
  933. * them out, and add any replacement modules.
  934. *
  935. * Runs at priority 99 by default.
  936. *
  937. * This is run late, so that it can still activate a module if
  938. * the new module is a replacement for another that the user
  939. * currently has active, even if something at the normal priority
  940. * would kibosh everything.
  941. *
  942. * @since 2.6
  943. * @uses jetpack_get_default_modules filter
  944. * @param array $modules
  945. * @return array
  946. */
  947. function handle_deprecated_modules( $modules ) {
  948. $deprecated_modules = array(
  949. 'debug' => null, // Closed out and moved to ./class.jetpack-debugger.php
  950. 'wpcc' => 'sso', // Closed out in 2.6 -- SSO provides the same functionality.
  951. );
  952. // Don't activate SSO if they never completed activating WPCC.
  953. if ( Jetpack::is_module_active( 'wpcc' ) ) {
  954. $wpcc_options = Jetpack_Options::get_option( 'wpcc_options' );
  955. if ( empty( $wpcc_options ) || empty( $wpcc_options['client_id'] ) || empty( $wpcc_options['client_id'] ) ) {
  956. $deprecated_modules['wpcc'] = null;
  957. }
  958. }
  959. foreach ( $deprecated_modules as $module => $replacement ) {
  960. if ( Jetpack::is_module_active( $module ) ) {
  961. self::deactivate_module( $module );
  962. if ( $replacement ) {
  963. $modules[] = $replacement;
  964. }
  965. }
  966. }
  967. return array_unique( $modules );
  968. }
  969. /**
  970. * Checks activated plugins during auto-activation to determine
  971. * if any of those plugins are in the list with a corresponding module
  972. * that is not compatible with the plugin. The module will not be allowed
  973. * to auto-activate.
  974. *
  975. * @since 2.6
  976. * @uses jetpack_get_default_modules filter
  977. * @param array $modules
  978. * @return array
  979. */
  980. function filter_default_modules( $modules ) {
  981. $active_plugins = self::get_active_plugins();
  982. if ( ! empty( $active_plugins ) ) {
  983. // For each module we'd like to auto-activate...
  984. foreach ( $modules as $key => $module ) {
  985. // If there are potential conflicts for it...
  986. if ( ! empty( $this->conflicting_plugins[ $module ] ) ) {
  987. // For each potential conflict...
  988. foreach ( $this->conflicting_plugins[ $module ] as $title => $plugin ) {
  989. // If that conflicting plugin is active...
  990. if ( in_array( $plugin, $active_plugins ) ) {
  991. // Remove that item from being auto-activated.
  992. unset( $modules[ $key ] );
  993. }
  994. }
  995. }
  996. }
  997. }
  998. return $modules;
  999. }
  1000. /**
  1001. * Extract a module's slug from its full path.
  1002. */
  1003. public static function get_module_slug( $file ) {
  1004. return str_replace( '.php', '', basename( $file ) );
  1005. }
  1006. /**
  1007. * Generate a module's path from its slug.
  1008. */
  1009. public static function get_module_path( $slug ) {
  1010. return JETPACK__PLUGIN_DIR . "modules/$slug.php";
  1011. }
  1012. /**
  1013. * Load module data from module file. Headers differ from WordPress
  1014. * plugin headers to avoid them being identified as standalone
  1015. * plugins on the WordPress plugins page.
  1016. */
  1017. public static function get_module( $module ) {
  1018. $headers = array(
  1019. 'name' => 'Module Name',
  1020. 'description' => 'Module Description',
  1021. 'sort' => 'Sort Order',
  1022. 'introduced' => 'First Introduced',
  1023. 'changed' => 'Major Changes In',
  1024. 'deactivate' => 'Deactivate',
  1025. 'free' => 'Free',
  1026. 'requires_connection' => 'Requires Connection',
  1027. 'auto_activate' => 'Auto Activate',
  1028. 'module_tags' => 'Module Tags',
  1029. );
  1030. $file = Jetpack::get_module_path( Jetpack::get_module_slug( $module ) );
  1031. if ( ! file_exists( $file ) )
  1032. return false;
  1033. $mod = get_file_data( $file, $headers );
  1034. if ( empty( $mod['name'] ) )
  1035. return false;
  1036. $mod['name'] = translate( $mod['name'], 'jetpack' );
  1037. $mod['description'] = translate( $mod['description'], 'jetpack' );
  1038. $mod['sort'] = empty( $mod['sort'] ) ? 10 : (int) $mod['sort'];
  1039. $mod['deactivate'] = empty( $mod['deactivate'] );
  1040. $mod['free'] = empty( $mod['free'] );
  1041. $mod['requires_connection'] = ( ! empty( $mod['requires_connection'] ) && 'No' == $mod['requires_connection'] ) ? false : true;
  1042. if ( empty( $mod['auto_activate'] ) || ! in_array( strtolower( $mod['auto_activate'] ), array( 'yes', 'no', 'public' ) ) ) {
  1043. $mod['auto_activate'] = 'No';
  1044. } else {
  1045. $mod['auto_activate'] = (string) $mod['auto_activate'];
  1046. }
  1047. if ( $mod['module_tags'] ) {
  1048. $mod['module_tags'] = explode( ',', $mod['module_tags'] );
  1049. $mod['module_tags'] = array_map( 'trim', $mod['module_tags'] );
  1050. $mod['module_tags'] = array_map( array( __CLASS__, 'translate_module_tag' ), $mod['module_tags'] );
  1051. } else {
  1052. $mod['module_tags'] = array( self::translate_module_tag( 'Other' ) );
  1053. }
  1054. return $mod;
  1055. }
  1056. public static function translate_module_tag( $untranslated_tag ) {
  1057. return _x( $untranslated_tag, 'Module Tag', 'jetpack' );
  1058. // Calls here are to populate translation files.
  1059. _x( 'Photos and Videos', 'Module Tag', 'jetpack' );
  1060. _x( 'Social', 'Module Tag', 'jetpack' );
  1061. _x( 'WordPress.com Stats', 'Module Tag', 'jetpack' );
  1062. _x( 'Writing', 'Module Tag', 'jetpack' );
  1063. _x( 'Appearance', 'Module Tag', 'jetpack' );
  1064. _x( 'Developers', 'Module Tag', 'jetpack' );
  1065. _x( 'Mobile', 'Module Tag', 'jetpack' );
  1066. _x( 'Other', 'Module Tag', 'jetpack' );
  1067. }
  1068. /**
  1069. * Get a list of activated modules as an array of module slugs.
  1070. */
  1071. public static function get_active_modules() {
  1072. $active = Jetpack_Options::get_option( 'active_modules' );
  1073. if ( ! is_array( $active ) )
  1074. $active = array();
  1075. if ( is_admin() ) {
  1076. $active[] = 'vaultpress';
  1077. } else {
  1078. $active = array_diff( $active, array( 'vaultpress' ) );
  1079. }
  1080. return array_unique( $active );
  1081. }
  1082. /**
  1083. * Check whether or not a Jetpack module is active.
  1084. *
  1085. * @param string $module The slug of a Jetpack module.
  1086. * @return bool
  1087. *
  1088. * @static
  1089. */
  1090. public static function is_module_active( $module ) {
  1091. return in_array( $module, self::get_active_modules() );
  1092. }
  1093. public static function is_module( $module ) {
  1094. return ! empty( $module ) && ! validate_file( $module, Jetpack::get_available_modules() );
  1095. }
  1096. /**
  1097. * Catches PHP errors. Must be used in conjunction with output buffering.
  1098. *
  1099. * @param bool $catch True to start catching, False to stop.
  1100. *
  1101. * @static
  1102. */
  1103. public static function catch_errors( $catch ) {
  1104. static $display_errors, $error_reporting;
  1105. if ( $catch ) {
  1106. $display_errors = @ini_set( 'display_errors', 1 );
  1107. $error_reporting = @error_reporting( E_ALL );
  1108. add_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 0 );
  1109. } else {
  1110. @ini_set( 'display_errors', $display_errors );
  1111. @error_reporting( $error_reporting );
  1112. remove_action( 'shutdown', array( 'Jetpack', 'catch_errors_on_shutdown' ), 1 );
  1113. }
  1114. }
  1115. /**
  1116. * Saves any generated PHP errors in ::state( 'php_errors', {errors} )
  1117. */
  1118. public static function catch_errors_on_shutdown() {
  1119. Jetpack::state( 'php_errors', ob_get_clean() );
  1120. }
  1121. public static function activate_default_modules( $min_version = false, $max_version = false, $other_modules = array() ) {
  1122. $jetpack = Jetpack::init();
  1123. $modules = Jetpack::get_default_modules( $min_version, $max_version );
  1124. $modules = array_merge( $other_modules, $modules );
  1125. // Look for standalone plugins and disable if active.
  1126. $to_deactivate = array();
  1127. foreach ( $modules as $module ) {
  1128. if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
  1129. $to_deactivate[$module] = $jetpack->plugins_to_deactivate[$module];
  1130. }
  1131. }
  1132. $deactivated = array();
  1133. foreach ( $to_deactivate as $module => $deactivate_me ) {
  1134. list( $probable_file, $probable_title ) = $deactivate_me;
  1135. if ( Jetpack_Client_Server::deactivate_plugin( $probable_file, $probable_title ) ) {
  1136. $deactivated[] = $module;
  1137. }
  1138. }
  1139. if ( $deactivated ) {
  1140. Jetpack::state( 'deactivated_plugins', join( ',', $deactivated ) );
  1141. $url = add_query_arg(
  1142. array(
  1143. 'action' => 'activate_default_modules',
  1144. '_wpnonce' => wp_create_nonce( 'activate_default_modules' ),
  1145. ),
  1146. add_query_arg( compact( 'min_version', 'max_version', 'other_modules' ), Jetpack::admin_url( 'page=jetpack' ) )
  1147. );
  1148. wp_safe_redirect( $url );
  1149. exit;
  1150. }
  1151. do_action( 'jetpack_before_activate_default_modules', $min_version, $max_version, $other_modules );
  1152. // Check each module for fatal errors, a la wp-admin/plugins.php::activate before activating
  1153. Jetpack::restate();
  1154. Jetpack::catch_errors( true );
  1155. foreach ( $modules as $module ) {
  1156. if ( did_action( "jetpack_module_loaded_$module" ) ) {
  1157. $active[] = $module;
  1158. Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
  1159. continue;
  1160. }
  1161. $active = Jetpack::get_active_modules();
  1162. if ( in_array( $module, $active ) ) {
  1163. $module_info = Jetpack::get_module( $module );
  1164. if ( ! $module_info['deactivate'] ) {
  1165. $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
  1166. if ( $active_state = Jetpack::state( $state ) ) {
  1167. $active_state = explode( ',', $active_state );
  1168. } else {
  1169. $active_state = array();
  1170. }
  1171. $active_state[] = $module;
  1172. Jetpack::state( $state, implode( ',', $active_state ) );
  1173. }
  1174. continue;
  1175. }
  1176. $file = Jetpack::get_module_path( $module );
  1177. if ( ! file_exists( $file ) ) {
  1178. continue;
  1179. }
  1180. // we'll override this later if the plugin can be included without fatal error
  1181. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  1182. Jetpack::state( 'error', 'module_activation_failed' );
  1183. Jetpack::state( 'module', $module );
  1184. ob_start();
  1185. require $file;
  1186. do_action( 'jetpack_activate_module', $module );
  1187. $active[] = $module;
  1188. $state = in_array( $module, $other_modules ) ? 'reactivated_modules' : 'activated_modules';
  1189. if ( $active_state = Jetpack::state( $state ) ) {
  1190. $active_state = explode( ',', $active_state );
  1191. } else {
  1192. $active_state = array();
  1193. }
  1194. $active_state[] = $module;
  1195. Jetpack::state( $state, implode( ',', $active_state ) );
  1196. Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
  1197. ob_end_clean();
  1198. }
  1199. Jetpack::state( 'error', false );
  1200. Jetpack::state( 'module', false );
  1201. Jetpack::catch_errors( false );
  1202. do_action( 'jetpack_activate_default_modules', $min_version, $max_version, $other_modules );
  1203. }
  1204. public static function activate_module( $module, $exit = true ) {
  1205. do_action( 'jetpack_pre_activate_module', $module, $exit );
  1206. $jetpack = Jetpack::init();
  1207. if ( ! strlen( $module ) )
  1208. return false;
  1209. if ( ! Jetpack::is_module( $module ) )
  1210. return false;
  1211. // If it's already active, then don't do it again
  1212. $active = Jetpack::get_active_modules();
  1213. foreach ( $active as $act ) {
  1214. if ( $act == $module )
  1215. return true;
  1216. }
  1217. $module_data = Jetpack::get_module( $module );
  1218. if ( ! Jetpack::is_active() ) {
  1219. if ( ! Jetpack::is_development_mode() )
  1220. return false;
  1221. // If we're not connected but in development mode, make sure the module doesn't require a connection
  1222. if ( Jetpack::is_development_mode() && $module_data['requires_connection'] )
  1223. return false;
  1224. }
  1225. // Check and see if the old plugin is active
  1226. if ( isset( $jetpack->plugins_to_deactivate[$module] ) ) {
  1227. // Deactivate the old plugin
  1228. if ( Jetpack_Client_Server::deactivate_plugin( $jetpack->plugins_to_deactivate[$module][0], $jetpack->plugins_to_deactivate[$module][1] ) ) {
  1229. // If we deactivated the old plugin, remembere that with ::state() and redirect back to this page to activate the module
  1230. // We can't activate the module on this page load since the newly deactivated old plugin is still loaded on this page load.
  1231. Jetpack::state( 'deactivated_plugins', $module );
  1232. wp_safe_redirect( add_query_arg( 'jetpack_restate', 1 ) );
  1233. exit;
  1234. }
  1235. }
  1236. // Check the file for fatal errors, a la wp-admin/plugins.php::activate
  1237. Jetpack::state( 'module', $module );
  1238. Jetpack::state( 'error', 'module_activation_failed' ); // we'll override this later if the plugin can be included without fatal error
  1239. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  1240. Jetpack::catch_errors( true );
  1241. ob_start();
  1242. require Jetpack::get_module_path( $module );
  1243. do_action( 'jetpack_activate_module', $module );
  1244. $active[] = $module;
  1245. Jetpack_Options::update_option( 'active_modules', array_unique( $active ) );
  1246. Jetpack::state( 'error', false ); // the override
  1247. Jetpack::state( 'message', 'module_activated' );
  1248. Jetpack::state( 'module', $module );
  1249. ob_end_clean();
  1250. Jetpack::catch_errors( false );
  1251. if ( $exit ) {
  1252. exit;
  1253. }
  1254. }
  1255. function activate_module_actions( $module ) {
  1256. do_action( "jetpack_activate_module_$module" );
  1257. $this->sync->sync_all_module_options( $module );
  1258. }
  1259. public static function deactivate_module( $module ) {
  1260. do_action( 'jetpack_pre_deactivate_module', $module );
  1261. $active = Jetpack::get_active_modules();
  1262. $new = array_filter( array_diff( $active, (array) $module ) );
  1263. do_action( "jetpack_deactivate_module_$module" );
  1264. return Jetpack_Options::update_option( 'active_modules', array_unique( $new ) );
  1265. }
  1266. public static function enable_module_configurable( $module ) {
  1267. $module = Jetpack::get_module_slug( $module );
  1268. add_filter( 'jetpack_module_configurable_' . $module, '__return_true' );
  1269. }
  1270. public static function module_configuration_url( $module ) {
  1271. $module = Jetpack::get_module_slug( $module );
  1272. return Jetpack::admin_url( array( 'page' => 'jetpack', 'configure' => $module ) );
  1273. }
  1274. public static function module_configuration_load( $module, $method ) {
  1275. $module = Jetpack::get_module_slug( $module );
  1276. add_action( 'jetpack_module_configuration_load_' . $module, $method );
  1277. }
  1278. public static function module_configuration_head( $module, $method ) {
  1279. $module = Jetpack::get_module_slug( $module );
  1280. add_action( 'jetpack_module_configuration_head_' . $module, $method );
  1281. }
  1282. public static function module_configuration_screen( $module, $method ) {
  1283. $module = Jetpack::get_module_slug( $module );
  1284. add_action( 'jetpack_module_configuration_screen_' . $module, $method );
  1285. }
  1286. /* Installation */
  1287. public static function bail_on_activation( $message, $deactivate = true ) {
  1288. ?>
  1289. <!doctype html>
  1290. <html>
  1291. <head>
  1292. <meta charset="<?php bloginfo( 'charset' ); ?>">
  1293. <style>
  1294. * {
  1295. text-align: center;
  1296. margin: 0;
  1297. padding: 0;
  1298. font-family: "Lucida Grande",Verdana,Arial,"Bitstream Vera Sans",sans-serif;
  1299. }
  1300. p {
  1301. margin-top: 1em;
  1302. font-size: 18px;
  1303. }
  1304. </style>
  1305. <body>
  1306. <p><?php echo esc_html( $message ); ?></p>
  1307. </body>
  1308. </html>
  1309. <?php
  1310. if ( $deactivate ) {
  1311. $plugins = get_option( 'active_plugins' );
  1312. $jetpack = plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' );
  1313. $update = false;
  1314. foreach ( $plugins as $i => $plugin ) {
  1315. if ( $plugin === $jetpack ) {
  1316. $plugins[$i] = false;
  1317. $update = true;
  1318. }
  1319. }
  1320. if ( $update ) {
  1321. update_option( 'active_plugins', array_filter( $plugins ) );
  1322. }
  1323. }
  1324. exit;
  1325. }
  1326. /**
  1327. * Attached to activate_{ plugin_basename( __FILES__ ) } by register_activation_hook()
  1328. * @static
  1329. */
  1330. public static function plugin_activation( $network_wide ) {
  1331. Jetpack_Options::update_option( 'activated', 1 );
  1332. if ( version_compare( $GLOBALS['wp_version'], JETPACK__MINIMUM_WP_VERSION, '<' ) ) {
  1333. Jetpack::bail_on_activation( sprintf( __( 'Jetpack requires WordPress version %s or later.', 'jetpack' ), JETPACK__MINIMUM_WP_VERSION ) );
  1334. }
  1335. if ( $network_wide )
  1336. Jetpack::state( 'network_nag', true );
  1337. Jetpack::plugin_initialize();
  1338. }
  1339. /**
  1340. * Sets the internal version number and activation state.
  1341. * @static
  1342. */
  1343. public static function plugin_initialize() {
  1344. if ( ! Jetpack_Options::get_option( 'activated' ) ) {
  1345. Jetpack_Options::update_option( 'activated', 2 );
  1346. }
  1347. if ( ! Jetpack_Options::get_option( 'version' ) ) {
  1348. $version = $old_version = JETPACK__VERSION . ':' . time();
  1349. Jetpack_Options::update_options( compact( 'version', 'old_version' ) );
  1350. }
  1351. Jetpack::load_modules();
  1352. Jetpack_Options::delete_option( 'do_activate' );
  1353. }
  1354. /**
  1355. * Removes all connection options
  1356. * @static
  1357. */
  1358. public static function plugin_deactivation( ) {
  1359. require_once( ABSPATH . '/wp-admin/includes/plugin.php' );
  1360. if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
  1361. Jetpack_Network::init()->deactivate();
  1362. } else {
  1363. Jetpack::disconnect( false );
  1364. //Jetpack_Heartbeat::init()->deactivate();
  1365. }
  1366. }
  1367. /**
  1368. * Disconnects from the Jetpack servers.
  1369. * Forgets all connection details and tells the Jetpack servers to do the same.
  1370. * @static
  1371. */
  1372. public static function disconnect( $update_activated_state = true ) {
  1373. wp_clear_scheduled_hook( 'jetpack_clean_nonces' );
  1374. Jetpack::clean_nonces( true );
  1375. Jetpack::load_xml_rpc_client();
  1376. $xml = new Jetpack_IXR_Client();
  1377. $xml->query( 'jetpack.deregister' );
  1378. Jetpack_Options::delete_option(
  1379. array(
  1380. 'register',
  1381. 'blog_token',
  1382. 'user_token',
  1383. 'user_tokens',
  1384. 'master_user',
  1385. 'time_diff',
  1386. 'fallback_no_verify_ssl_certs',
  1387. )
  1388. );
  1389. if ( $update_activated_state ) {
  1390. Jetpack_Options::update_option( 'activated', 4 );
  1391. }
  1392. // Disable the Heartbeat cron
  1393. Jetpack_Heartbeat::init()->deactivate();
  1394. }
  1395. /**
  1396. * Unlinks the current user from the linked WordPress.com user
  1397. */
  1398. public static function unlink_user( $user_id = null ) {
  1399. if ( ! $tokens = Jetpack_Options::get_option( 'user_tokens' ) )
  1400. return false;
  1401. $user_id = empty( $user_id ) ? get_current_user_id() : intval( $user_id );
  1402. if ( Jetpack_Options::get_option( 'master_user' ) == $user_id )
  1403. return false;
  1404. if ( ! isset( $tokens[ $user_id ] ) )
  1405. return false;
  1406. Jetpack::load_xml_rpc_client();
  1407. $xml = new Jetpack_IXR_Client( compact( 'user_id' ) );
  1408. $xml->query( 'jetpack.unlink_user', $user_id );
  1409. unset( $tokens[ $user_id ] );
  1410. Jetpack_Options::update_option( 'user_tokens', $tokens );
  1411. return true;
  1412. }
  1413. /**
  1414. * Attempts Jetpack registration. If it fail, a state flag is set: @see ::admin_page_load()
  1415. */
  1416. public static function try_registration() {
  1417. $result = Jetpack::register();
  1418. // If there was an error with registration and the site was not registered, record this so we can show a message.
  1419. if ( ! $result || is_wp_error( $result ) ) {
  1420. return $result;
  1421. } else {
  1422. return true;
  1423. }
  1424. }
  1425. /**
  1426. * Tracking an internal event log. Try not to put too much chaff in here.
  1427. *
  1428. * [Everyone Loves a Log!](https://www.youtube.com/watch?v=2C7mNr5WMjA)
  1429. */
  1430. public static function log( $code, $data = null ) {
  1431. $log = Jetpack_Options::get_option( 'log', array() );
  1432. // Append our event to the log
  1433. $log_entry = array(
  1434. 'time' => time(),
  1435. 'user_id' => get_current_user_id(),
  1436. 'blog_id' => Jetpack_Options::get_option( 'id' ),
  1437. 'code' => $code,
  1438. );
  1439. // Don't bother storing it unless we've got some.
  1440. if ( ! is_null( $data ) ) {
  1441. $log_entry['data'] = $data;
  1442. }
  1443. $log[] = $log_entry;
  1444. // Try add_option first, to make sure it's not autoloaded.
  1445. // @todo: Add an add_option method to Jetpack_Options
  1446. if ( ! add_option( 'jetpack_log', $log, null, 'no' ) ) {
  1447. Jetpack_Options::update_option( 'log', $log );
  1448. }
  1449. do_action( 'jetpack_log_entry', $log_entry );
  1450. }
  1451. /**
  1452. * Get the internal event log.
  1453. */
  1454. public static function get_log() {
  1455. return Jetpack_Options::get_option( 'log', array() );
  1456. }
  1457. /* Admin Pages */
  1458. function admin_init() {
  1459. // If the plugin is not connected, display a connect message.
  1460. if (
  1461. // the plugin was auto-activated and needs its candy
  1462. Jetpack_Options::get_option( 'do_activate' )
  1463. ||
  1464. // the plugin is active, but was never activated. Probably came from a site-wide network activation
  1465. ! Jetpack_Options::get_option( 'activated' )
  1466. ) {
  1467. Jetpack::plugin_initialize();
  1468. }
  1469. if ( ! Jetpack::is_active() && ! Jetpack::is_development_mode() ) {
  1470. if ( 4 != Jetpack_Options::get_option( 'activated' ) ) {
  1471. // Show connect notice on dashboard and plugins pages
  1472. add_action( 'load-index.php', array( $this, 'prepare_connect_notice' ) );
  1473. add_action( 'load-plugins.php', array( $this, 'prepare_connect_notice' ) );
  1474. }
  1475. } elseif ( false === Jetpack_Options::get_option( 'fallback_no_verify_ssl_certs' ) ) {
  1476. // Upgrade: 1.1 -> 1.1.1
  1477. // Check and see if host can verify the Jetpack servers' SSL certificate
  1478. $args = array();
  1479. Jetpack_Client::_wp_remote_request(
  1480. Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'test' ) ),
  1481. $args,
  1482. true
  1483. );
  1484. }
  1485. /* Toggle this off as it's not ready for prime time just yet.
  1486. if( current_user_can( 'manage_options' ) && self::check_identity_crisis() ) {
  1487. add_action( 'admin_notices', array( $this, 'alert_identity_crisis' ) );
  1488. }
  1489. /**/
  1490. if ( current_user_can( 'manage_options' ) && 'ALWAYS' == JETPACK_CLIENT__HTTPS && ! self::permit_ssl() ) {
  1491. add_action( 'admin_notices', array( $this, 'alert_required_ssl_fail' ) );
  1492. }
  1493. add_action( 'load-plugins.php', array( $this, 'intercept_plugin_error_scrape_init' ) );
  1494. add_action( 'admin_enqueue_scripts', array( $this, 'admin_menu_css' ) );
  1495. add_filter( 'plugin_action_links_' . plugin_basename( JETPACK__PLUGIN_DIR . 'jetpack.php' ), array( $this, 'plugin_action_links' ) );
  1496. if ( Jetpack::is_active() || Jetpack::is_development_mode() ) {
  1497. // Artificially throw errors in certain whitelisted cases during plugin activation
  1498. add_action( 'activate_plugin', array( $this, 'throw_error_on_activate_plugin' ) );
  1499. // Kick off synchronization of user role when it changes
  1500. add_action( 'set_user_role', array( $this, 'user_role_change' ) );
  1501. }
  1502. }
  1503. function admin_body_class( $admin_body_class = '' ) {
  1504. $classes = explode( ' ', trim( $admin_body_class ) );
  1505. $classes[] = self::is_active() ? 'jetpack-connected' : 'jetpack-disconnected';
  1506. // Handle pre-mp6 styling by adding a 'pre-mp6' body class.
  1507. include( ABSPATH . WPINC . '/version.php' );
  1508. if ( version_compare( $wp_version, '3.8-alpha', '<' ) ) {
  1509. $classes[] = 'pre-mp6';
  1510. }
  1511. return implode( ' ', array_unique( $classes ) );
  1512. }
  1513. static function add_jetpack_pagestyles( $admin_body_class = '' ) {
  1514. return $admin_body_class . ' jetpack-pagestyles';
  1515. }
  1516. function prepare_connect_notice() {
  1517. add_action( 'admin_print_styles', array( $this, 'admin_banner_styles' ) );
  1518. add_action( 'admin_notices', array( $this, 'admin_connect_notice' ) );
  1519. if ( Jetpack::state( 'network_nag' ) )
  1520. add_action( 'network_admin_notices', array( $this, 'network_connect_notice' ) );
  1521. }
  1522. /**
  1523. * Sometimes a plugin can activate without causing errors, but it will cause errors on the next page load.
  1524. * This function artificially throws errors for such cases (whitelisted).
  1525. *
  1526. * @param string $plugin The activated plugin.
  1527. */
  1528. function throw_error_on_activate_plugin( $plugin ) {
  1529. $active_modules = Jetpack::get_active_modules();
  1530. // The Shortlinks module and the Stats plugin conflict, but won't cause errors on activation because of some function_exists() checks.
  1531. if ( function_exists( 'stats_get_api_key' ) && in_array( 'shortlinks', $active_modules ) ) {
  1532. $throw = false;
  1533. // Try and make sure it really was the stats plugin
  1534. if ( ! class_exists( 'ReflectionFunction' ) ) {
  1535. if ( 'stats.php' == basename( $plugin ) ) {
  1536. $throw = true;
  1537. }
  1538. } else {
  1539. $reflection = new ReflectionFunction( 'stats_get_api_key' );
  1540. if ( basename( $plugin ) == basename( $reflection->getFileName() ) ) {
  1541. $throw = true;
  1542. }
  1543. }
  1544. if ( $throw ) {
  1545. trigger_error( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), 'WordPress.com Stats' ), E_USER_ERROR );
  1546. }
  1547. }
  1548. }
  1549. function intercept_plugin_error_scrape_init() {
  1550. add_action( 'check_admin_referer', array( $this, 'intercept_plugin_error_scrape' ), 10, 2 );
  1551. }
  1552. function intercept_plugin_error_scrape( $action, $result ) {
  1553. if ( ! $result ) {
  1554. return;
  1555. }
  1556. foreach ( $this->plugins_to_deactivate as $deactivate_me ) {
  1557. if ( "plugin-activation-error_{$deactivate_me[0]}" == $action ) {
  1558. Jetpack::bail_on_activation( sprintf( __( 'Jetpack contains the most recent version of the old &#8220;%1$s&#8221; plugin.', 'jetpack' ), $deactivate_me[1] ), false );
  1559. }
  1560. }
  1561. }
  1562. function admin_menu() {
  1563. list( $jetpack_version ) = explode( ':', Jetpack_Options::get_option( 'version' ) );
  1564. if (
  1565. $jetpack_version
  1566. &&
  1567. $jetpack_version != JETPACK__VERSION
  1568. &&
  1569. ( $new_modules = Jetpack::get_default_modules( $jetpack_version, JETPACK__VERSION ) )
  1570. &&
  1571. is_array( $new_modules )
  1572. &&
  1573. ( $new_modules_count = count( $new_modules ) )
  1574. &&
  1575. ( Jetpack::is_active() || Jetpack::is_development_mode() )
  1576. ) {
  1577. $new_modules_count_i18n = number_format_i18n( $new_modules_count );
  1578. $span_title = esc_attr( sprintf( _n( 'One New Jetpack Module', '%s New Jetpack Modules', $new_modules_count, 'jetpack' ), $new_modules_count_i18n ) );
  1579. $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>" );
  1580. } else {
  1581. $title = __( 'Jetpack', 'jetpack' );
  1582. }
  1583. $hook = add_menu_page( 'Jetpack', $title, 'read', 'jetpack', array( $this, 'admin_page' ), 'div' );
  1584. $debugger_hook = add_submenu_page( null, __( 'Jetpack Debugging Center', 'jetpack' ), '', 'manage_options', 'jetpack-debugger', array( $this, 'debugger_page' ) );
  1585. add_action( "admin_head-$debugger_hook", array( 'Jetpack_Debugger', 'jetpack_debug_admin_head' ) );
  1586. add_action( "load-$hook", array( $this, 'admin_page_load' ) );
  1587. if ( version_compare( $GLOBALS['wp_version'], '3.3', '<' ) ) {
  1588. if ( isset( $_GET['page'] ) && 'jetpack' == $_GET['page'] ) {
  1589. add_contextual_help( $hook, $this->jetpack_help() );
  1590. }
  1591. } else {
  1592. add_action( "load-$hook", array( $this, 'admin_help' ) );
  1593. }
  1594. add_action( "admin_head-$hook", array( $this, 'admin_head' ) );
  1595. add_filter( 'custom_menu_order', array( $this, 'admin_menu_order' ) );
  1596. add_filter( 'menu_order', array( $this, 'jetpack_menu_order' ) );
  1597. add_action( "admin_print_styles-$hook", array( $this, 'admin_styles' ) );
  1598. add_action( "admin_print_scripts-$hook", array( $this, 'admin_scripts' ) );
  1599. do_action( 'jetpack_admin_menu', $hook );
  1600. }
  1601. function add_remote_request_handlers() {
  1602. add_action( 'wp_ajax_nopriv_jetpack_upload_file', array( $this, 'remote_request_handlers' ) );
  1603. }
  1604. function remote_request_handlers() {
  1605. switch ( current_filter() ) {
  1606. case 'wp_ajax_nopriv_jetpack_upload_file' :
  1607. $response = $this->upload_handler();
  1608. break;
  1609. default :
  1610. $response = new Jetpack_Error( 'unknown_handler', 'Unknown Handler', 400 );
  1611. break;
  1612. }
  1613. if ( ! $response ) {
  1614. $response = new Jetpack_Error( 'unknown_error', 'Unknown Error', 400 );
  1615. }
  1616. if ( is_wp_error( $response ) ) {
  1617. $status_code = $response->get_error_data();
  1618. $error = $response->get_error_code();
  1619. $error_description = $response->get_error_message();
  1620. if ( ! is_int( $status_code ) ) {
  1621. $status_code = 400;
  1622. }
  1623. status_header( $status_code );
  1624. die( json_encode( (object) compact( 'error', 'error_description' ) ) );
  1625. }
  1626. status_header( 200 );
  1627. if ( true === $response ) {
  1628. exit;
  1629. }
  1630. die( json_encode( (object) $response ) );
  1631. }
  1632. function upload_handler() {
  1633. if ( 'POST' !== strtoupper( $_SERVER['REQUEST_METHOD'] ) ) {
  1634. return new Jetpack_Error( 405, get_status_header_desc( 405 ), 405 );
  1635. }
  1636. $user = wp_authenticate( '', '' );
  1637. if ( ! $user || is_wp_error( $user ) ) {
  1638. return new Jetpack_Error( 403, get_status_header_desc( 403 ), 403 );
  1639. }
  1640. wp_set_current_user( $user->ID );
  1641. if ( ! current_user_can( 'upload_files' ) ) {
  1642. return new Jetpack_Error( 'cannot_upload_files', 'User does not have permission to upload files', 403 );
  1643. }
  1644. if ( empty( $_FILES ) ) {
  1645. return new Jetpack_Error( 'no_files_uploaded', 'No files were uploaded: nothing to process', 400 );
  1646. }
  1647. foreach ( array_keys( $_FILES ) as $files_key ) {
  1648. if ( ! isset( $_POST["_jetpack_file_hmac_{$files_key}"] ) ) {
  1649. return new Jetpack_Error( 'missing_hmac', 'An HMAC for one or more files is missing', 400 );
  1650. }
  1651. }
  1652. $media_keys = array_keys( $_FILES['media'] );
  1653. $token = Jetpack_Data::get_access_token( get_current_user_id() );
  1654. if ( ! $token || is_wp_error( $token ) ) {
  1655. return new Jetpack_Error( 'unknown_token', 'Unknown Jetpack token', 403 );
  1656. }
  1657. $uploaded_files = array();
  1658. $global_post = isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null;
  1659. unset( $GLOBALS['post'] );
  1660. foreach ( $_FILES['media']['name'] as $index => $name ) {
  1661. $file = array();
  1662. foreach ( $media_keys as $media_key ) {
  1663. $file[$media_key] = $_FILES['media'][$media_key][$index];
  1664. }
  1665. list( $hmac_provided, $salt ) = explode( ':', $_POST['_jetpack_file_hmac_media'][$index] );
  1666. $hmac_file = hash_hmac_file( 'sha1', $file['tmp_name'], $salt . $token->secret );
  1667. if ( $hmac_provided !== $hmac_file ) {
  1668. $uploaded_files[$index] = (object) array( 'error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match' );
  1669. continue;
  1670. }
  1671. $_FILES['.jetpack.upload.'] = $file;
  1672. $post_id = isset( $_POST['post_id'][$index] ) ? absint( $_POST['post_id'][$index] ) : 0;
  1673. if ( ! current_user_can( 'edit_post', $post_id ) ) {
  1674. $post_id = 0;
  1675. }
  1676. $attachment_id = media_handle_upload(
  1677. '.jetpack.upload.',
  1678. $post_id,
  1679. array(),
  1680. array(
  1681. 'action' => 'jetpack_upload_file',
  1682. )
  1683. );
  1684. if ( ! $attachment_id ) {
  1685. $uploaded_files[$index] = (object) array( 'error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site' );
  1686. } elseif ( is_wp_error( $attachment_id ) ) {
  1687. $uploaded_files[$index] = (object) array( 'error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message() );
  1688. } else {
  1689. $attachment = get_post( $attachment_id );
  1690. $uploaded_files[$index] = (object) array(
  1691. 'id' => (string) $attachment_id,
  1692. 'file' => $attachment->post_title,
  1693. 'url' => wp_get_attachment_url( $attachment_id ),
  1694. 'type' => $attachment->post_mime_type,
  1695. 'meta' => wp_get_attachment_metadata( $attachment_id ),
  1696. );
  1697. }
  1698. }
  1699. if ( ! is_null( $global_post ) ) {
  1700. $GLOBALS['post'] = $global_post;
  1701. }
  1702. return $uploaded_files;
  1703. }
  1704. /**
  1705. * Add help to the Jetpack page
  1706. *
  1707. * Deprecated. Remove when Jetpack requires WP 3.3+
  1708. */
  1709. function jetpack_help() {
  1710. return
  1711. '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
  1712. '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
  1713. '<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>' .
  1714. '<p><strong>' . __( 'Jetpack Module Options', 'jetpack' ) . '</strong></p>' .
  1715. '<p>' . __( '<strong>To Activate/Deactivate a Module</strong> - Click on Learn More. An Activate or Deactivate button will now appear next to the Learn More button. Click the Activate/Deactivate button.', 'jetpack' ) . '</p>' .
  1716. '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
  1717. '<p><a href="http://jetpack.me/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
  1718. '<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>';
  1719. }
  1720. /**
  1721. * Add help to the Jetpack page
  1722. *
  1723. * @since Jetpack (1.2.3)
  1724. * @return false if not the Jetpack page
  1725. */
  1726. function admin_help() {
  1727. $current_screen = get_current_screen();
  1728. // Overview
  1729. $current_screen->add_help_tab(
  1730. array(
  1731. 'id' => 'overview',
  1732. 'title' => __( 'Overview', 'jetpack' ),
  1733. 'content' =>
  1734. '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
  1735. '<p>' . __( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ) . '</p>' .
  1736. '<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>',
  1737. )
  1738. );
  1739. // Screen Content
  1740. if ( current_user_can( 'manage_options' ) ) {
  1741. $current_screen->add_help_tab(
  1742. array(
  1743. 'id' => 'modules',
  1744. 'title' => __( 'Modules', 'jetpack' ),
  1745. 'content' =>
  1746. '<p><strong>' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</strong></p>' .
  1747. '<p>' . __( 'You can activate or deactivate individual Jetpack modules to suit your needs.', 'jetpack' ) . '</p>' .
  1748. '<ol>' .
  1749. '<li>' . __( 'Find the component you want to manage', 'jetpack' ) . '</li>' .
  1750. '<li>' . __( 'Click on Learn More', 'jetpack' ) . '</li>' .
  1751. '<li>' . __( 'An Activate or Deactivate button will appear', 'jetpack' ) . '</li>' .
  1752. '<li>' . __( 'If additional settings are available, a link to them will appear', 'jetpack' ) . '</li>' .
  1753. '</ol>',
  1754. )
  1755. );
  1756. }
  1757. // Help Sidebar
  1758. $current_screen->set_help_sidebar(
  1759. '<p><strong>' . __( 'For more information:', 'jetpack' ) . '</strong></p>' .
  1760. '<p><a href="http://jetpack.me/faq/" target="_blank">' . __( 'Jetpack FAQ', 'jetpack' ) . '</a></p>' .
  1761. '<p><a href="http://jetpack.me/support/" target="_blank">' . __( 'Jetpack Support', 'jetpack' ) . '</a></p>' .
  1762. '<p><a href="' . Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ) .'">' . __( 'Jetpack Debugging Center', 'jetpack' ) . '</a></p>'
  1763. );
  1764. }
  1765. function admin_menu_css() {
  1766. // Make sure we're working off a clean version.
  1767. include( ABSPATH . WPINC . '/version.php' );
  1768. if ( version_compare( $wp_version, '3.8-alpha', '>=' ) ) {
  1769. wp_enqueue_style( 'jetpack-icons' );
  1770. $css = "
  1771. #toplevel_page_jetpack .wp-menu-image:before {
  1772. font-family: 'Jetpack' !important;
  1773. content: '\\e600';
  1774. }
  1775. #toplevel_page_jetpack .wp-menu-image {
  1776. background-repeat: no-repeat;
  1777. }
  1778. #menu-posts-feedback .wp-menu-image:before {
  1779. font-family: dashicons !important;
  1780. content: '\\f175';
  1781. }
  1782. #adminmenu #menu-posts-feedback div.wp-menu-image {
  1783. background: none !important;
  1784. background-repeat: no-repeat;
  1785. }";
  1786. } else {
  1787. $css = "
  1788. #toplevel_page_jetpack .wp-menu-image {
  1789. background: url( " . plugins_url( '_inc/images/menuicon-sprite.png', __FILE__ ) . " ) 0 90% no-repeat;
  1790. }
  1791. /* Retina Jetpack Menu Icon */
  1792. @media only screen and (-moz-min-device-pixel-ratio: 1.5),
  1793. only screen and (-o-min-device-pixel-ratio: 3/2),
  1794. only screen and (-webkit-min-device-pixel-ratio: 1.5),
  1795. only screen and (min-device-pixel-ratio: 1.5) {
  1796. #toplevel_page_jetpack .wp-menu-image {
  1797. background: url( " . plugins_url( '_inc/images/menuicon-sprite-2x.png', __FILE__ ) . " ) 0 90% no-repeat;
  1798. background-size:30px 64px;
  1799. }
  1800. }
  1801. #toplevel_page_jetpack.current .wp-menu-image,
  1802. #toplevel_page_jetpack.wp-has-current-submenu .wp-menu-image,
  1803. #toplevel_page_jetpack:hover .wp-menu-image {
  1804. background-position: top left;
  1805. }";
  1806. }
  1807. wp_add_inline_style( 'wp-admin', $css );
  1808. }
  1809. function admin_menu_order() {
  1810. return true;
  1811. }
  1812. function jetpack_menu_order( $menu_order ) {
  1813. $jp_menu_order = array();
  1814. foreach ( $menu_order as $index => $item ) {
  1815. if ( $item != 'jetpack' )
  1816. $jp_menu_order[] = $item;
  1817. if ( $index == 0 )
  1818. $jp_menu_order[] = 'jetpack';
  1819. }
  1820. return $jp_menu_order;
  1821. }
  1822. function admin_head() {
  1823. if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) )
  1824. do_action( 'jetpack_module_configuration_head_' . $_GET['configure'] );
  1825. }
  1826. function admin_styles() {
  1827. global $wp_styles;
  1828. $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
  1829. wp_enqueue_style( 'jetpack', plugins_url( "_inc/jetpack{$min}.css", __FILE__ ), false, JETPACK__VERSION . '-20121016' );
  1830. $wp_styles->add_data( 'jetpack', 'rtl', true );
  1831. }
  1832. function admin_banner_styles() {
  1833. global $wp_styles;
  1834. $min = ( defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ) ? '' : '.min';
  1835. wp_enqueue_style( 'jetpack', plugins_url( "_inc/jetpack-banners{$min}.css", __FILE__ ), false, JETPACK__VERSION . '-20121016' );
  1836. $wp_styles->add_data( 'jetpack', 'rtl', true );
  1837. }
  1838. function admin_scripts() {
  1839. wp_enqueue_script( 'jetpack-icanhaz', plugins_url( '_inc/icanhaz.js', __FILE__ ), array( ), JETPACK__VERSION . '-20121111' );
  1840. wp_enqueue_script( 'jetpack-js', plugins_url( '_inc/jp.js', __FILE__ ), array( 'jquery' ), JETPACK__VERSION . '-20121111' );
  1841. wp_localize_script(
  1842. 'jetpack-js',
  1843. 'jetpackL10n',
  1844. array(
  1845. 'ays_disconnect' => "This will deactivate all Jetpack modules.\nAre you sure you want to disconnect?",
  1846. '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?",
  1847. 'ays_dismiss' => "This will deactivate Jetpack.\nAre you sure you want to deactivate Jetpack?",
  1848. )
  1849. );
  1850. add_action( 'admin_footer', array( $this, 'do_stats' ) );
  1851. }
  1852. function plugin_action_links( $actions ) {
  1853. return array_merge(
  1854. array( 'settings' => sprintf( '<a href="%s">%s</a>', Jetpack::admin_url(), __( 'Settings', 'jetpack' ) ) ),
  1855. $actions
  1856. );
  1857. return $actions;
  1858. }
  1859. function admin_connect_notice() {
  1860. // Don't show the connect notice on the jetpack settings page. @todo: must be a better way?
  1861. if ( false !== strpos( $_SERVER['QUERY_STRING'], 'page=jetpack' ) )
  1862. return;
  1863. if ( ! current_user_can( 'jetpack_connect' ) )
  1864. return;
  1865. $dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
  1866. ?>
  1867. <div id="message" class="updated jetpack-message jp-connect" style="display:block !important;">
  1868. <div id="jp-dismiss" class="jetpack-close-button-container">
  1869. <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>
  1870. </div>
  1871. <div class="jetpack-wrap-container">
  1872. <div class="jetpack-install-container">
  1873. <?php if ( 1 == Jetpack_Options::get_option( 'activated' ) ) : ?>
  1874. <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>
  1875. <?php else : ?>
  1876. <p class="submit"><a href="<?php echo Jetpack::admin_url() ?>" class="button-connector" id="wpcom-connect"><?php _e( 'Learn More', 'jetpack' ); ?></a></p>
  1877. <?php endif; ?>
  1878. </div>
  1879. <div class="jetpack-text-container">
  1880. <?php if ( 1 == Jetpack_Options::get_option( 'activated' ) ) : ?>
  1881. <p><?php _e( '<strong>Your Jetpack is almost ready!</strong>', 'jetpack' ); ?></p>
  1882. <p><?php _e( 'Connect now to enable features like Stats, Likes, and Social Sharing.', 'jetpack' ); ?></p>
  1883. <?php else : ?>
  1884. <p><?php _e( '<strong>Jetpack is installed</strong>', 'jetpack' ) ?></p>
  1885. <p><?php _e( 'It\'s ready to bring awesome, WordPress.com cloud-powered features to your site.', 'jetpack' ) ?></p>
  1886. <?php endif; ?>
  1887. </div>
  1888. </div>
  1889. </div>
  1890. <?php
  1891. }
  1892. function network_connect_notice() {
  1893. ?>
  1894. <div id="message" class="updated jetpack-message">
  1895. <div class="squeezer">
  1896. <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>
  1897. </div>
  1898. </div>
  1899. <?php
  1900. }
  1901. public static function jetpack_comment_notice() {
  1902. if ( in_array( 'comments', Jetpack::get_active_modules() ) ) {
  1903. return '';
  1904. }
  1905. $jetpack_old_version = explode( ':', Jetpack_Options::get_option( 'old_version' ) );
  1906. $jetpack_new_version = explode( ':', Jetpack_Options::get_option( 'version' ) );
  1907. if ( $jetpack_old_version ) {
  1908. if ( version_compare( $jetpack_old_version[0], '1.4', '>=' ) ) {
  1909. return '';
  1910. }
  1911. }
  1912. if ( $jetpack_new_version ) {
  1913. if ( version_compare( $jetpack_new_version[0], '1.4-something', '<' ) ) {
  1914. return '';
  1915. }
  1916. }
  1917. return '<br /><br />' . sprintf(
  1918. __( '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' ),
  1919. wp_nonce_url(
  1920. Jetpack::admin_url(
  1921. array(
  1922. 'page' => 'jetpack',
  1923. 'action' => 'activate',
  1924. 'module' => 'comments',
  1925. )
  1926. ),
  1927. 'jetpack_activate-comments'
  1928. ),
  1929. __( 'click here', 'jetpack' )
  1930. );
  1931. }
  1932. /*
  1933. * Registration flow:
  1934. * 1 - ::admin_page_load() action=register
  1935. * 2 - ::try_registration()
  1936. * 3 - ::register()
  1937. * - Creates jetpack_register option containing two secrets and a timestamp
  1938. * - Calls https://jetpack.wordpress.com/jetpack.register/1/ with
  1939. * siteurl, home, gmt_offset, timezone_string, site_name, secret_1, secret_2, site_lang, timeout, stats_id
  1940. * - That request to jetpack.wordpress.com does not immediately respond. It first makes a request BACK to this site's
  1941. * xmlrpc.php?for=jetpack: RPC method: jetpack.verifyRegistration, Parameters: secret_1
  1942. * - The XML-RPC request verifies secret_1, deletes both secrets and responds with: secret_2
  1943. * - https://jetpack.wordpress.com/jetpack.register/1/ verifies that XML-RPC response (secret_2) then finally responds itself with
  1944. * jetpack_id, jetpack_secret, jetpack_public
  1945. * - ::register() then stores jetpack_options: id => jetpack_id, blog_token => jetpack_secret
  1946. * 4 - redirect to https://jetpack.wordpress.com/jetpack.authorize/1/
  1947. * 5 - user logs in with WP.com account
  1948. * 6 - redirect to this site's wp-admin/index.php?page=jetpack&action=authorize with
  1949. * code <-- OAuth2 style authorization code
  1950. * 7 - ::admin_page_load() action=authorize
  1951. * 8 - Jetpack_Client_Server::authorize()
  1952. * 9 - Jetpack_Client_Server::get_token()
  1953. * 10- GET https://jetpack.wordpress.com/jetpack.token/1/ with
  1954. * client_id, client_secret, grant_type, code, redirect_uri:action=authorize, state, scope, user_email, user_login
  1955. * 11- which responds with
  1956. * access_token, token_type, scope
  1957. * 12- Jetpack_Client_Server::authorize() stores jetpack_options: user_token => access_token.$user_id
  1958. * 13- Jetpack::activate_default_modules()
  1959. * Deactivates deprecated plugins
  1960. * Activates all default modules
  1961. * Catches errors: redirects to wp-admin/index.php?page=jetpack state:error=something
  1962. * 14- redirect to this site's wp-admin/index.php?page=jetpack with state:message=authorized
  1963. * Done!
  1964. */
  1965. /**
  1966. * Handles the page load events for the Jetpack admin page
  1967. */
  1968. function admin_page_load() {
  1969. $error = false;
  1970. // Make sure we have the right body class to hook stylings for subpages off of.
  1971. add_filter( 'admin_body_class', array( __CLASS__, 'add_jetpack_pagestyles' ) );
  1972. if ( ! empty( $_GET['jetpack_restate'] ) ) {
  1973. // Should only be used in intermediate redirects to preserve state across redirects
  1974. Jetpack::restate();
  1975. }
  1976. if ( isset( $_GET['connect_url_redirect'] ) ) {
  1977. // User clicked in the iframe to link their accounts
  1978. if ( ! Jetpack::is_user_connected() ) {
  1979. $connect_url = $this->build_connect_url( true );
  1980. if ( isset( $_GET['notes_iframe'] ) )
  1981. $connect_url .= '&notes_iframe';
  1982. wp_redirect( $connect_url );
  1983. exit;
  1984. } else {
  1985. Jetpack::state( 'message', 'already_authorized' );
  1986. wp_safe_redirect( Jetpack::admin_url() );
  1987. exit;
  1988. }
  1989. }
  1990. if ( isset( $_GET['action'] ) ) {
  1991. switch ( $_GET['action'] ) {
  1992. case 'authorize' :
  1993. if ( Jetpack::is_active() && Jetpack::is_user_connected() ) {
  1994. Jetpack::state( 'message', 'already_authorized' );
  1995. wp_safe_redirect( Jetpack::admin_url() );
  1996. exit;
  1997. }
  1998. Jetpack::log( 'authorize' );
  1999. $client_server = new Jetpack_Client_Server;
  2000. $client_server->authorize();
  2001. exit;
  2002. case 'register' :
  2003. check_admin_referer( 'jetpack-register' );
  2004. Jetpack::log( 'register' );
  2005. $registered = Jetpack::try_registration();
  2006. if ( is_wp_error( $registered ) ) {
  2007. $error = $registered->get_error_code();
  2008. Jetpack::state( 'error_description', $registered->get_error_message() );
  2009. break;
  2010. }
  2011. wp_redirect( $this->build_connect_url( true ) );
  2012. exit;
  2013. case 'activate' :
  2014. if ( ! current_user_can( 'jetpack_activate_modules' ) ) {
  2015. $error = 'cheatin';
  2016. break;
  2017. }
  2018. $module = stripslashes( $_GET['module'] );
  2019. check_admin_referer( "jetpack_activate-$module" );
  2020. Jetpack::log( 'activate', $module );
  2021. Jetpack::activate_module( $module );
  2022. // The following two lines will rarely happen, as Jetpack::activate_module normally exits at the end.
  2023. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  2024. exit;
  2025. case 'activate_default_modules' :
  2026. check_admin_referer( 'activate_default_modules' );
  2027. Jetpack::log( 'activate_default_modules' );
  2028. Jetpack::restate();
  2029. $min_version = isset( $_GET['min_version'] ) ? $_GET['min_version'] : false;
  2030. $max_version = isset( $_GET['max_version'] ) ? $_GET['max_version'] : false;
  2031. $other_modules = isset( $_GET['other_modules'] ) && is_array( $_GET['other_modules'] ) ? $_GET['other_modules'] : array();
  2032. Jetpack::activate_default_modules( $min_version, $max_version, $other_modules );
  2033. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  2034. exit;
  2035. case 'disconnect' :
  2036. if ( ! current_user_can( 'jetpack_disconnect' ) ) {
  2037. $error = 'cheatin';
  2038. break;
  2039. }
  2040. check_admin_referer( 'jetpack-disconnect' );
  2041. Jetpack::log( 'disconnect' );
  2042. Jetpack::disconnect();
  2043. wp_safe_redirect( Jetpack::admin_url() );
  2044. exit;
  2045. case 'reconnect' :
  2046. if ( ! current_user_can( 'jetpack_reconnect' ) ) {
  2047. $error = 'cheatin';
  2048. break;
  2049. }
  2050. check_admin_referer( 'jetpack-reconnect' );
  2051. Jetpack::log( 'reconnect' );
  2052. $this->disconnect();
  2053. wp_redirect( $this->build_connect_url( true ) );
  2054. exit;
  2055. case 'deactivate' :
  2056. if ( ! current_user_can( 'jetpack_deactivate_modules' ) ) {
  2057. $error = 'cheatin';
  2058. break;
  2059. }
  2060. $modules = stripslashes( $_GET['module'] );
  2061. check_admin_referer( "jetpack_deactivate-$modules" );
  2062. foreach ( explode( ',', $modules ) as $module ) {
  2063. Jetpack::log( 'deactivate', $module );
  2064. Jetpack::deactivate_module( $module );
  2065. Jetpack::state( 'message', 'module_deactivated' );
  2066. }
  2067. Jetpack::state( 'module', $modules );
  2068. wp_safe_redirect( Jetpack::admin_url( 'page=jetpack' ) );
  2069. exit;
  2070. case 'unlink' :
  2071. check_admin_referer( 'jetpack-unlink' );
  2072. Jetpack::log( 'unlink' );
  2073. $this->unlink_user();
  2074. Jetpack::state( 'message', 'unlinked' );
  2075. wp_safe_redirect( Jetpack::admin_url() );
  2076. exit;
  2077. default:
  2078. do_action( 'jetpack_unrecognized_action', sanitize_key( $_GET['action'] ) );
  2079. }
  2080. }
  2081. if ( ! $error = $error ? $error : Jetpack::state( 'error' ) ) {
  2082. $this->activate_new_modules();
  2083. }
  2084. switch ( $error ) {
  2085. case 'cheatin' :
  2086. $this->error = __( 'Cheatin&#8217; uh?', 'jetpack' );
  2087. break;
  2088. case 'access_denied' :
  2089. $this->error = __( 'You need to authorize the Jetpack connection between your site and WordPress.com to enable the awesome features.', 'jetpack' );
  2090. break;
  2091. case 'wrong_state' :
  2092. $this->error = __( 'Don&#8217;t cross the streams! You need to stay logged in to your WordPress blog while you authorize Jetpack.', 'jetpack' );
  2093. break;
  2094. case 'invalid_client' :
  2095. // @todo re-register instead of deactivate/reactivate
  2096. $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' );
  2097. break;
  2098. case 'invalid_grant' :
  2099. $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' );
  2100. break;
  2101. case 'site_inaccessible' :
  2102. case 'site_requires_authorization' :
  2103. $this->error = sprintf( __( 'Your website needs to be publicly accessible to use Jetpack: %s', 'jetpack' ), "<code>$error</code>" );
  2104. break;
  2105. case 'module_activation_failed' :
  2106. $module = Jetpack::state( 'module' );
  2107. if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
  2108. $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'] );
  2109. if ( isset( $this->plugins_to_deactivate[$module] ) ) {
  2110. $this->error .= ' ' . sprintf( __( 'Do you still have the %s plugin installed?', 'jetpack' ), $this->plugins_to_deactivate[$module][1] );
  2111. }
  2112. } else {
  2113. $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' );
  2114. }
  2115. if ( $php_errors = Jetpack::state( 'php_errors' ) ) {
  2116. $this->error .= "<br />\n";
  2117. $this->error .= $php_errors;
  2118. }
  2119. break;
  2120. case 'master_user_required' :
  2121. $module = Jetpack::state( 'module' );
  2122. $module_name = '';
  2123. if ( ! empty( $module ) && $mod = Jetpack::get_module( $module ) ) {
  2124. $module_name = $mod['name'];
  2125. }
  2126. $master_user = Jetpack_Options::get_option( 'master_user' );
  2127. $master_userdata = get_userdata( $master_user ) ;
  2128. if ( $master_userdata ) {
  2129. if ( ! in_array( $module, Jetpack::get_active_modules() ) ) {
  2130. $this->error = sprintf( __( '%s was not activated.' , 'jetpack' ), $module_name );
  2131. } else {
  2132. $this->error = sprintf( __( '%s was not deactivated.' , 'jetpack' ), $module_name );
  2133. }
  2134. $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 ) );
  2135. } else {
  2136. $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 );
  2137. }
  2138. break;
  2139. case 'not_public' :
  2140. $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' );
  2141. break;
  2142. case 'wpcom_408' :
  2143. case 'wpcom_5??' :
  2144. case 'wpcom_bad_response' :
  2145. case 'wpcom_outage' :
  2146. $this->error = __( 'WordPress.com is currently having problems and is unable to fuel up your Jetpack. Please try again later.', 'jetpack' );
  2147. break;
  2148. case 'register_http_request_failed' :
  2149. case 'token_http_request_failed' :
  2150. $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>" );
  2151. break;
  2152. default :
  2153. if ( empty( $error ) ) {
  2154. break;
  2155. }
  2156. $error = trim( substr( strip_tags( $error ), 0, 20 ) );
  2157. // no break: fall through
  2158. case 'no_role' :
  2159. case 'no_cap' :
  2160. case 'no_code' :
  2161. case 'no_state' :
  2162. case 'invalid_state' :
  2163. case 'invalid_request' :
  2164. case 'invalid_scope' :
  2165. case 'unsupported_response_type' :
  2166. case 'invalid_token' :
  2167. case 'no_token' :
  2168. case 'missing_secrets' :
  2169. case 'home_missing' :
  2170. case 'siteurl_missing' :
  2171. case 'gmt_offset_missing' :
  2172. case 'site_name_missing' :
  2173. case 'secret_1_missing' :
  2174. case 'secret_2_missing' :
  2175. case 'site_lang_missing' :
  2176. case 'home_malformed' :
  2177. case 'siteurl_malformed' :
  2178. case 'gmt_offset_malformed' :
  2179. case 'timezone_string_malformed' :
  2180. case 'site_name_malformed' :
  2181. case 'secret_1_malformed' :
  2182. case 'secret_2_malformed' :
  2183. case 'site_lang_malformed' :
  2184. case 'secrets_mismatch' :
  2185. case 'verify_secret_1_missing' :
  2186. case 'verify_secret_1_malformed' :
  2187. case 'verify_secrets_missing' :
  2188. case 'verify_secrets_mismatch' :
  2189. $error = esc_html( $error );
  2190. $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>" );
  2191. if ( ! Jetpack::is_active() ) {
  2192. $this->error .= '<br />';
  2193. $this->error .= sprintf( __( 'Try connecting again.', 'jetpack' ) );
  2194. }
  2195. break;
  2196. }
  2197. $message_code = Jetpack::state( 'message' );
  2198. $active_state = Jetpack::state( 'activated_modules' );
  2199. if ( ! empty( $active_state ) ) {
  2200. $available = Jetpack::get_available_modules();
  2201. $active_state = explode( ',', $active_state );
  2202. $active_state = array_intersect( $active_state, $available );
  2203. if ( count( $active_state ) ) {
  2204. foreach ( $active_state as $mod ) {
  2205. $this->stat( 'module-activated', $mod );
  2206. }
  2207. } else {
  2208. $active_state = false;
  2209. }
  2210. }
  2211. switch ( $message_code ) {
  2212. case 'modules_activated' :
  2213. $this->message = sprintf(
  2214. __( 'Welcome to <strong>Jetpack %s</strong>!', 'jetpack' ),
  2215. JETPACK__VERSION
  2216. );
  2217. if ( $active_state ) {
  2218. $titles = array();
  2219. foreach ( $active_state as $mod ) {
  2220. if ( $mod_headers = Jetpack::get_module( $mod ) ) {
  2221. $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
  2222. }
  2223. }
  2224. if ( $titles ) {
  2225. $this->message .= '<br /><br />' . wp_sprintf( __( 'The following new modules have been activated: %l.', 'jetpack' ), $titles );
  2226. }
  2227. }
  2228. if ( $reactive_state = Jetpack::state( 'reactivated_modules' ) ) {
  2229. $titles = array();
  2230. foreach ( explode( ',', $reactive_state ) as $mod ) {
  2231. if ( $mod_headers = Jetpack::get_module( $mod ) ) {
  2232. $titles[] = '<strong>' . preg_replace( '/\s+(?![^<>]++>)/', '&nbsp;', $mod_headers['name'] ) . '</strong>';
  2233. }
  2234. }
  2235. if ( $titles ) {
  2236. $this->message .= '<br /><br />' . wp_sprintf( __( 'The following modules have been updated: %l.', 'jetpack' ), $titles );
  2237. }
  2238. }
  2239. $this->message .= Jetpack::jetpack_comment_notice();
  2240. break;
  2241. case 'module_activated' :
  2242. if ( $module = Jetpack::get_module( Jetpack::state( 'module' ) ) ) {
  2243. $this->message = sprintf( __( '<strong>%s Activated!</strong> You can deactivate at any time by clicking Learn More and then Deactivate on the module card.', 'jetpack' ), $module['name'] );
  2244. $this->stat( 'module-activated', Jetpack::state( 'module' ) );
  2245. }
  2246. break;
  2247. case 'module_deactivated' :
  2248. $modules = Jetpack::state( 'module' );
  2249. if ( ! $modules ) {
  2250. break;
  2251. }
  2252. $module_names = array();
  2253. foreach ( explode( ',', $modules ) as $module_slug ) {
  2254. $module = Jetpack::get_module( $module_slug );
  2255. if ( $module ) {
  2256. $module_names[] = $module['name'];
  2257. }
  2258. $this->stat( 'module-deactivated', $module_slug );
  2259. }
  2260. if ( ! $module_names ) {
  2261. break;
  2262. }
  2263. $this->message = wp_sprintf(
  2264. _nx(
  2265. '<strong>%l Deactivated!</strong> You can activate it again at any time using the activate button on the module card.',
  2266. '<strong>%l Deactivated!</strong> You can activate them again at any time using the activate buttons on their module cards.',
  2267. count( $module_names ),
  2268. '%l = list of Jetpack module/feature names',
  2269. 'jetpack'
  2270. ),
  2271. $module_names
  2272. );
  2273. break;
  2274. case 'module_configured' :
  2275. $this->message = __( '<strong>Module settings were saved.</strong> ', 'jetpack' );
  2276. break;
  2277. case 'already_authorized' :
  2278. $this->message = __( '<strong>Your Jetpack is already connected.</strong> ', 'jetpack' );
  2279. break;
  2280. case 'authorized' :
  2281. $this->message = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
  2282. $this->message .= "<br />\n";
  2283. $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' ) );
  2284. $this->message .= Jetpack::jetpack_comment_notice();
  2285. break;
  2286. case 'linked' :
  2287. $this->message = __( '<strong>You&#8217;re fueled up and ready to go.</strong> ', 'jetpack' );
  2288. $this->message .= Jetpack::jetpack_comment_notice();
  2289. break;
  2290. case 'unlinked' :
  2291. $user = wp_get_current_user();
  2292. $this->message = sprintf( __( '<strong>You have unlinked your account (%s) from WordPress.com.</strong>', 'jetpack' ), $user->user_login );
  2293. break;
  2294. }
  2295. $deactivated_plugins = Jetpack::state( 'deactivated_plugins' );
  2296. if ( ! empty( $deactivated_plugins ) ) {
  2297. $deactivated_plugins = explode( ',', $deactivated_plugins );
  2298. $deactivated_titles = array();
  2299. foreach ( $deactivated_plugins as $deactivated_plugin ) {
  2300. if ( ! isset( $this->plugins_to_deactivate[$deactivated_plugin] ) ) {
  2301. continue;
  2302. }
  2303. $deactivated_titles[] = '<strong>' . str_replace( ' ', '&nbsp;', $this->plugins_to_deactivate[$deactivated_plugin][1] ) . '</strong>';
  2304. }
  2305. if ( $deactivated_titles ) {
  2306. if ( $this->message ) {
  2307. $this->message .= "<br /><br />\n";
  2308. }
  2309. $this->message .= wp_sprintf(
  2310. _n(
  2311. 'Jetpack contains the most recent version of the old %l plugin.',
  2312. 'Jetpack contains the most recent versions of the old %l plugins.',
  2313. count( $deactivated_titles ),
  2314. 'jetpack'
  2315. ),
  2316. $deactivated_titles
  2317. );
  2318. $this->message .= "<br />\n";
  2319. $this->message .= _n(
  2320. 'The old version has been deactivated and can be removed from your site.',
  2321. 'The old versions have been deactivated and can be removed from your site.',
  2322. count( $deactivated_titles ),
  2323. 'jetpack'
  2324. );
  2325. }
  2326. }
  2327. $this->privacy_checks = Jetpack::state( 'privacy_checks' );
  2328. if ( $this->message || $this->error || $this->privacy_checks ) {
  2329. add_action( 'jetpack_notices', array( $this, 'admin_notices' ) );
  2330. }
  2331. if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
  2332. do_action( 'jetpack_module_configuration_load_' . $_GET['configure'] );
  2333. }
  2334. add_filter( 'jetpack_short_module_description', 'wptexturize' );
  2335. }
  2336. function admin_notices() {
  2337. if ( $this->error ) {
  2338. ?>
  2339. <div id="message" class="jetpack-message jetpack-err">
  2340. <div class="squeezer">
  2341. <h4><?php echo wp_kses( $this->error, array( 'code' => true, 'strong' => true, 'br' => true, 'b' => true ) ); ?></h4>
  2342. <?php if ( $desc = Jetpack::state( 'error_description' ) ) : ?>
  2343. <p><?php echo esc_html( stripslashes( $desc ) ); ?></p>
  2344. <?php endif; ?>
  2345. </div>
  2346. </div>
  2347. <?php
  2348. }
  2349. if ( $this->message ) {
  2350. ?>
  2351. <div id="message" class="jetpack-message">
  2352. <div class="squeezer">
  2353. <h4><?php echo wp_kses( $this->message, array( 'strong' => array(), 'a' => array( 'href' => true ), 'br' => true ) ); ?></h4>
  2354. </div>
  2355. </div>
  2356. <?php
  2357. }
  2358. if ( $this->privacy_checks ) :
  2359. $module_names = $module_slugs = array();
  2360. $privacy_checks = explode( ',', $this->privacy_checks );
  2361. foreach ( $privacy_checks as $module_slug ) {
  2362. $module = Jetpack::get_module( $module_slug );
  2363. if ( ! $module ) {
  2364. continue;
  2365. }
  2366. $module_slugs[] = $module_slug;
  2367. $module_names[] = "<strong>{$module['name']}</strong>";
  2368. }
  2369. $module_slugs = join( ',', $module_slugs );
  2370. ?>
  2371. <div id="message" class="jetpack-message jetpack-err">
  2372. <div class="squeezer">
  2373. <h4><strong><?php esc_html_e( 'Is this site private?', 'jetpack' ); ?></strong></h4><br />
  2374. <p><?php
  2375. echo wp_kses(
  2376. wptexturize(
  2377. wp_sprintf(
  2378. _nx(
  2379. "Like your site's RSS feeds, %l allows access to your posts and other content to third parties.",
  2380. "Like your site's RSS feeds, %l allow access to your posts and other content to third parties.",
  2381. count( $privacy_checks ),
  2382. '%l = list of Jetpack module/feature names',
  2383. 'jetpack'
  2384. ),
  2385. $module_names
  2386. )
  2387. ),
  2388. array( 'strong' => true )
  2389. );
  2390. echo "\n<br />\n";
  2391. echo wp_kses(
  2392. sprintf(
  2393. _nx(
  2394. 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating this feature</a>.',
  2395. 'If your site is not publicly accessible, consider <a href="%1$s" title="%2$s">deactivating these features</a>.',
  2396. count( $privacy_checks ),
  2397. '%1$s = deactivation URL, %2$s = "Deactivate {list of Jetpack module/feature names}',
  2398. 'jetpack'
  2399. ),
  2400. wp_nonce_url(
  2401. Jetpack::admin_url(
  2402. array(
  2403. 'page' => 'jetpack',
  2404. 'action' => 'deactivate',
  2405. 'module' => urlencode( $module_slugs ),
  2406. )
  2407. ),
  2408. "jetpack_deactivate-$module_slugs"
  2409. ),
  2410. esc_attr( wp_kses( wp_sprintf( _x( 'Deactivate %l', '%l = list of Jetpack module/feature names', 'jetpack' ), $module_names ), array() ) )
  2411. ),
  2412. array( 'a' => array( 'href' => true, 'title' => true ) )
  2413. );
  2414. ?></p>
  2415. </div>
  2416. </div>
  2417. <?php endif;
  2418. }
  2419. /**
  2420. * Record a stat for later output. This will only currently output in the admin_footer.
  2421. */
  2422. function stat( $group, $detail ) {
  2423. if ( ! isset( $this->stats[ $group ] ) )
  2424. $this->stats[ $group ] = array();
  2425. $this->stats[ $group ][] = $detail;
  2426. }
  2427. /**
  2428. * Load stats pixels. $group is auto-prefixed with "x_jetpack-"
  2429. */
  2430. function do_stats( $method = '' ) {
  2431. if ( is_array( $this->stats ) && count( $this->stats ) ) {
  2432. foreach ( $this->stats as $group => $stats ) {
  2433. if ( is_array( $stats ) && count( $stats ) ) {
  2434. $args = array( "x_jetpack-{$group}" => implode( ',', $stats ) );
  2435. if ( 'server_side' === $method ) {
  2436. self::do_server_side_stat( $args );
  2437. } else {
  2438. echo '<img src="' . esc_url( self::build_stats_url( $args ) ) . '" width="1" height="1" style="display:none;" />';
  2439. }
  2440. }
  2441. unset( $this->stats[ $group ] );
  2442. }
  2443. }
  2444. }
  2445. /**
  2446. * Runs stats code for a one-off, server-side.
  2447. *
  2448. * @param $args array|string The arguments to append to the URL. Should include `x_jetpack-{$group}={$stats}` or whatever we want to store.
  2449. *
  2450. * @return bool If it worked.
  2451. */
  2452. static function do_server_side_stat( $args ) {
  2453. $response = wp_remote_get( self::build_stats_url( $args ) );
  2454. if ( is_wp_error( $response ) )
  2455. return false;
  2456. if ( 200 !== wp_remote_retrieve_response_code( $response ) )
  2457. return false;
  2458. return true;
  2459. }
  2460. /**
  2461. * Builds the stats url.
  2462. *
  2463. * @param $args array|string The arguments to append to the URL.
  2464. *
  2465. * @return string The URL to be pinged.
  2466. */
  2467. static function build_stats_url( $args ) {
  2468. $defaults = array(
  2469. 'v' => 'wpcom2',
  2470. 'rand' => md5( mt_rand( 0, 999 ) . time() ),
  2471. );
  2472. $args = wp_parse_args( $args, $defaults );
  2473. $base_url = apply_filters(
  2474. 'jetpack_stats_base_url',
  2475. set_url_scheme( 'http://stats.wordpress.com/g.gif' )
  2476. );
  2477. $url = add_query_arg( $args, $base_url );
  2478. return $url;
  2479. }
  2480. function translate_current_user_to_role() {
  2481. foreach ( $this->capability_translations as $role => $cap ) {
  2482. if ( current_user_can( $role ) || current_user_can( $cap ) ) {
  2483. return $role;
  2484. }
  2485. }
  2486. return false;
  2487. }
  2488. function translate_role_to_cap( $role ) {
  2489. if ( ! isset( $this->capability_translations[$role] ) ) {
  2490. return false;
  2491. }
  2492. return $this->capability_translations[$role];
  2493. }
  2494. function sign_role( $role ) {
  2495. if ( ! $user_id = (int) get_current_user_id() ) {
  2496. return false;
  2497. }
  2498. $token = Jetpack_Data::get_access_token();
  2499. if ( ! $token || is_wp_error( $token ) ) {
  2500. return false;
  2501. }
  2502. return $role . ':' . hash_hmac( 'md5', "{$role}|{$user_id}", $token->secret );
  2503. }
  2504. function build_connect_url( $raw = false, $redirect = false ) {
  2505. if ( ! Jetpack_Options::get_option( 'blog_token' ) ) {
  2506. $url = Jetpack::nonce_url_no_esc( Jetpack::admin_url( 'action=register' ), 'jetpack-register' );
  2507. if( is_network_admin() ) {
  2508. $url = add_query_arg( 'is_multisite', network_admin_url(
  2509. 'admin.php?page=jetpack-settings' ), $url );
  2510. }
  2511. } else {
  2512. $role = $this->translate_current_user_to_role();
  2513. $signed_role = $this->sign_role( $role );
  2514. $user = wp_get_current_user();
  2515. $redirect = $redirect ? esc_url_raw( $redirect ) : '';
  2516. if( isset( $_REQUEST['is_multisite'] ) ) {
  2517. $redirect = Jetpack_Network::init()->get_url( 'network_admin_page' );
  2518. }
  2519. $args = urlencode_deep(
  2520. array(
  2521. 'response_type' => 'code',
  2522. 'client_id' => Jetpack_Options::get_option( 'id' ),
  2523. 'redirect_uri' => add_query_arg(
  2524. array(
  2525. 'action' => 'authorize',
  2526. '_wpnonce' => wp_create_nonce( "jetpack-authorize_{$role}_{$redirect}" ),
  2527. 'redirect' => $redirect ? urlencode( $redirect ) : false,
  2528. ),
  2529. menu_page_url( 'jetpack', false )
  2530. ),
  2531. 'state' => $user->ID,
  2532. 'scope' => $signed_role,
  2533. 'user_email' => $user->user_email,
  2534. 'user_login' => $user->user_login,
  2535. 'is_active' => Jetpack::is_active(),
  2536. 'jp_version' => JETPACK__VERSION,
  2537. )
  2538. );
  2539. $url = add_query_arg( $args, Jetpack::api_url( 'authorize' ) );
  2540. }
  2541. return $raw ? $url : esc_url( $url );
  2542. }
  2543. function build_reconnect_url( $raw = false ) {
  2544. $url = wp_nonce_url( Jetpack::admin_url( 'action=reconnect' ), 'jetpack-reconnect' );
  2545. return $raw ? $url : esc_url( $url );
  2546. }
  2547. public static function admin_url( $args = null ) {
  2548. $args = wp_parse_args( $args, array( 'page' => 'jetpack' ) );
  2549. $url = add_query_arg( $args, admin_url( 'admin.php' ) );
  2550. return $url;
  2551. }
  2552. public static function nonce_url_no_esc( $actionurl, $action = -1, $name = '_wpnonce' ) {
  2553. $actionurl = str_replace( '&amp;', '&', $actionurl );
  2554. return add_query_arg( $name, wp_create_nonce( $action ), $actionurl );
  2555. }
  2556. function dismiss_jetpack_notice() {
  2557. 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' ) ) ) {
  2558. require_once ABSPATH . 'wp-admin/includes/plugin.php';
  2559. deactivate_plugins( JETPACK__PLUGIN_DIR . 'jetpack.php', false, false );
  2560. wp_safe_redirect( admin_url() . 'plugins.php?deactivate=true&plugin_status=all&paged=1&s=' );
  2561. exit;
  2562. }
  2563. }
  2564. /**
  2565. * This is the old pre-3.0 admin page. It is replaced by the Jetpack_Admin class.
  2566. * Tentatively left here for comparison purposes.
  2567. */
  2568. function admin_page() {
  2569. global $current_user;
  2570. $is_connected = Jetpack::is_active();
  2571. $user_token = Jetpack_Data::get_access_token( $current_user->ID );
  2572. $is_user_connected = $user_token && ! is_wp_error( $user_token );
  2573. $is_master_user = $current_user->ID == Jetpack_Options::get_option( 'master_user' );
  2574. $can_reconnect_jpms = true;
  2575. if( is_plugin_active_for_network( 'jetpack/jetpack.php' ) ) {
  2576. $jpms = Jetpack_Network::init();
  2577. $can_reconnect_jpms = ( $jpms->get_option( 'sub-site-connection-override' ) ) ? 1: 0;
  2578. }
  2579. ?>
  2580. <div class="wrap" id="jetpack-settings">
  2581. <div id="jp-header"<?php if ( $is_connected ) : ?> class="small"<?php endif; ?>>
  2582. <div id="jp-clouds">
  2583. <?php if ( $is_connected && $can_reconnect_jpms ) : ?>
  2584. <div id="jp-disconnectors">
  2585. <?php if ( current_user_can( 'jetpack_disconnect' ) ) : ?>
  2586. <div id="jp-disconnect" class="jp-disconnect">
  2587. <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>
  2588. </div>
  2589. <?php endif; ?>
  2590. <?php if ( $is_user_connected && ! $is_master_user ) : ?>
  2591. <div id="jp-unlink" class="jp-disconnect">
  2592. <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>
  2593. </div>
  2594. <?php endif; ?>
  2595. </div>
  2596. <?php endif; ?>
  2597. <h3><?php _e( 'Jetpack by WordPress.com', 'jetpack' ) ?></h3>
  2598. <?php if ( ! $is_connected ) : ?>
  2599. <div id="jp-notice">
  2600. <p><?php _e( 'Jetpack supercharges your self-hosted WordPress site with the awesome cloud power of WordPress.com.', 'jetpack' ); ?></p>
  2601. </div>
  2602. <?php endif; ?>
  2603. </div>
  2604. </div>
  2605. <h2 style="display: none"></h2> <!-- For WP JS message relocation -->
  2606. <?php Jetpack::init()->load_view( 'admin/network-activated-notice.php' ); ?>
  2607. <?php do_action( 'jetpack_notices' ) ?>
  2608. <?php
  2609. // If the connection has not been made then show the marketing text.
  2610. if( !$can_reconnect_jpms && !$is_connected ) {
  2611. ?>
  2612. <div id="message" class="updated jetpack-message jp-connect jp-multisite" style="display:block !important">
  2613. <div class="jetpack-wrap-container">
  2614. <div class="jetpack-text-container">
  2615. <h4>
  2616. <p><?php _e( 'To use Jetpack please contact your WordPress administrator to connect it for you.', 'jetpack' ) ?></p>
  2617. </h4>
  2618. </div>
  2619. </div>
  2620. </div> <?php
  2621. }
  2622. if ( ! Jetpack::is_development_mode() && $can_reconnect_jpms ) :
  2623. ?>
  2624. <?php if ( ! $is_connected ) :
  2625. $dismiss_and_deactivate_url = wp_nonce_url( Jetpack::admin_url( '?page=jetpack&jetpack-notice=dismiss' ), 'jetpack-deactivate' );
  2626. ?>
  2627. <div id="message" class="updated jetpack-message jp-connect" style="display:block !important;">
  2628. <div id="jp-dismiss" class="jetpack-close-button-container">
  2629. <a class="jetpack-close-button" href="<?php echo esc_url( $dismiss_and_deactivate_url ); ?>"><?php _e( 'Dismiss this notice.', 'jetpack' ); ?></a>
  2630. </div>
  2631. <div class="jetpack-wrap-container">
  2632. <div class="jetpack-text-container">
  2633. <h4>
  2634. <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>
  2635. </h4>
  2636. </div>
  2637. <div class="jetpack-install-container">
  2638. <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>
  2639. </div>
  2640. </div>
  2641. </div>
  2642. <?php else /* blog and user are connected */ : ?>
  2643. <?php /* TODO: if not master user, show user disconnect button? */ ?>
  2644. <?php endif; ?>
  2645. <?php endif; // ! Jetpack::is_development_mode() ?>
  2646. <?php if ( Jetpack::is_active() && !Jetpack::is_development_mode() && ! $is_user_connected ) : ?>
  2647. <div id="message" class="updated jetpack-message jp-connect" style="display:block !important;">
  2648. <div class="jetpack-wrap-container">
  2649. <div class="jetpack-text-container">
  2650. <h4>
  2651. <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>
  2652. </h4>
  2653. </div>
  2654. <div class="jetpack-install-container">
  2655. <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>
  2656. </div>
  2657. </div>
  2658. </div>
  2659. <?php endif; ?>
  2660. <?php
  2661. if ( isset( $_GET['configure'] ) && Jetpack::is_module( $_GET['configure'] ) && current_user_can( 'manage_options' ) ) {
  2662. $this->admin_screen_configure_module( $_GET['configure'] );
  2663. } else {
  2664. $this->admin_screen_list_modules();
  2665. }
  2666. ?>
  2667. <div id="survey" class="jp-survey">
  2668. <div class="jp-survey-container">
  2669. <div class="jp-survey-text">
  2670. <h4><?php _e( 'Have feedback on Jetpack?', 'jetpack' ); ?></h4>
  2671. <br />
  2672. <?php _e( 'Answer a short survey to let us know how we&#8217;re doing and what to add in the future.', 'jetpack' ); ?>
  2673. </div>
  2674. <div class="jp-survey-button-container">
  2675. <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>
  2676. </div>
  2677. </div>
  2678. </div>
  2679. <?php if ( $is_connected && $this->current_user_is_connection_owner() ) : ?>
  2680. <p id="news-sub"><?php _e( 'Checking email updates status&hellip;', 'jetpack' ); ?></p>
  2681. <script type="text/javascript">
  2682. jQuery(document).ready(function($){
  2683. $.get( ajaxurl, { action: 'jetpack-check-news-subscription', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
  2684. if ( 'subscribed' == data ) {
  2685. $( '#news-sub' ).html( '<?php printf(
  2686. esc_js( _x( 'You are currently subscribed to email updates. %s', '%s = Unsubscribe link', 'jetpack' ) ),
  2687. '<a href="#" class="jp-news-link button">' . esc_js( __( 'Unsubscribe', 'jetpack' ) ) . '</a>'
  2688. ); ?>' );
  2689. } else {
  2690. $( '#news-sub' ).html( '<?php printf(
  2691. esc_js( _x( 'Want to receive updates about Jetpack by email? %s', '%s = Subscribe link', 'jetpack' ) ),
  2692. '<a href="#" class="jp-news-link button-primary">' . esc_js( __( 'Subscribe', 'jetpack' ) ) . '</a>'
  2693. ); ?>' );
  2694. }
  2695. $( '.jp-news-link' ).click( function() {
  2696. $( '#news-sub' ).append( ' <img src="<?php echo esc_js( esc_url( admin_url( 'images/loading.gif' ) ) ); ?>" align="absmiddle" id="jp-news-loading" />' );
  2697. $.get( ajaxurl, { action: 'jetpack-subscribe-to-news', rand: jQuery.now().toString() + Math.random().toString() }, function( data ) {
  2698. if ( 'subscribed' == data ) {
  2699. $( '#news-sub' ).text( '<?php echo esc_js( __( 'You have been subscribed to receive email updates.', 'jetpack' ) ); ?>' );
  2700. } else {
  2701. $( '#news-sub' ).text( '<?php echo esc_js( __( 'You will no longer receive email updates about Jetpack.', 'jetpack' ) ); ?>' );
  2702. }
  2703. $( '#jp-news-loading' ).remove();
  2704. } );
  2705. return false;
  2706. } );
  2707. } );
  2708. } );
  2709. </script>
  2710. <?php endif; ?>
  2711. <div id="jp-footer">
  2712. <p class="automattic"><?php _e( 'An <span>Automattic</span> Airline', 'jetpack' ) ?></p>
  2713. <p class="small">
  2714. <a href="http://jetpack.me/" target="_blank">Jetpack <?php echo esc_html( JETPACK__VERSION ); ?></a> |
  2715. <a href="http://automattic.com/privacy/" target="_blank"><?php _e( 'Privacy Policy', 'jetpack' ); ?></a> |
  2716. <a href="http://wordpress.com/tos/" target="_blank"><?php _e( 'Terms of Service', 'jetpack' ); ?></a> |
  2717. <?php if ( current_user_can( 'manage_options' ) ) : ?>
  2718. <a href="<?php echo Jetpack::admin_url( array( 'page' => 'jetpack-debugger' ) ); ?>"><?php _e( 'Debug', 'jetpack' ); ?></a> |
  2719. <?php endif; ?>
  2720. <a href="http://jetpack.me/support/" target="_blank"><?php _e( 'Support', 'jetpack' ); ?></a>
  2721. </p>
  2722. </div>
  2723. <div id="jetpack-configuration" style="display:none;">
  2724. <p><img width="16" src="<?php echo esc_url( plugins_url( '_inc/images/wpspin_light-2x.gif', __FILE__ ) ); ?>" alt="Loading ..." /></p>
  2725. </div>
  2726. </div>
  2727. <?php
  2728. }
  2729. function debugger_page() {
  2730. nocache_headers();
  2731. if ( ! current_user_can( 'manage_options' ) ) {
  2732. die( '-1' );
  2733. }
  2734. Jetpack_Debugger::jetpack_debug_display_handler();
  2735. exit;
  2736. }
  2737. public static function admin_screen_configure_module( $module_id ) {
  2738. if ( ! in_array( $module_id, Jetpack::get_active_modules() ) || ! current_user_can( 'manage_options' ) )
  2739. return false; ?>
  2740. <div id="jp-settings-screen" style="position: relative">
  2741. <h3>
  2742. <?php
  2743. $module = Jetpack::get_module( $module_id );
  2744. echo '<a href="' . Jetpack::admin_url( 'page=jetpack_modules' ) . '">' . __( 'Jetpack by WordPress.com', 'jetpack' ) . '</a> &rarr; ';
  2745. printf( __( 'Configure %s', 'jetpack' ), $module['name'] );
  2746. ?>
  2747. </h3>
  2748. <?php do_action( 'jetpack_module_configuration_screen_' . $module_id ); ?>
  2749. </div><?php
  2750. }
  2751. public static function sort_modules( $a, $b ) {
  2752. if ( $a['sort'] == $b['sort'] )
  2753. return 0;
  2754. return ( $a['sort'] < $b['sort'] ) ? -1 : 1;
  2755. }
  2756. function admin_screen_list_modules() {
  2757. require_once JETPACK__PLUGIN_DIR . 'modules/module-info.php';
  2758. $jetpack_connected = true;
  2759. if ( ! Jetpack::is_active() )
  2760. $jetpack_connected = false;
  2761. ?>
  2762. <div class="module-container">
  2763. <?php
  2764. $avail_raw = Jetpack::get_available_modules();
  2765. $available = array();
  2766. $active = Jetpack::get_active_modules();
  2767. $counter = 0;
  2768. foreach ( (array) $avail_raw as $module ) {
  2769. if ( $plugin = Jetpack::get_module( $module ) ) {
  2770. $plugin['module'] = $module;
  2771. $available[] = $plugin;
  2772. }
  2773. }
  2774. unset( $avail_raw );
  2775. usort( $available, array( 'Jetpack', 'sort_modules' ) );
  2776. $jetpack_version = Jetpack_Options::get_option( 'version' );
  2777. if ( $jetpack_version ) {
  2778. list( $jetpack_version, $jetpack_version_time ) = explode( ':', $jetpack_version );
  2779. } else {
  2780. $jetpack_version = 0;
  2781. $jetpack_version_time = 0;
  2782. }
  2783. $jetpack_old_version = Jetpack_Options::get_option( 'old_version' );
  2784. if ( $jetpack_old_version ) {
  2785. list( $jetpack_old_version ) = explode( ':', $jetpack_old_version );
  2786. } else {
  2787. $jetpack_old_version = 0;
  2788. }
  2789. $now = time();
  2790. foreach ( (array) $available as $module_data ) {
  2791. $module = $module_data['module'];
  2792. $activated = in_array( $module, $active );
  2793. if ( $activated ) {
  2794. $css = 'active';
  2795. $toggle = __( 'Deactivate', 'jetpack' );
  2796. $toggle_url = wp_nonce_url(
  2797. Jetpack::admin_url(
  2798. array(
  2799. 'page' => 'jetpack',
  2800. 'action' => 'deactivate',
  2801. 'module' => $module,
  2802. )
  2803. ),
  2804. "jetpack_deactivate-$module"
  2805. );
  2806. } else {
  2807. $css = 'inactive';
  2808. $toggle = __( 'Activate', 'jetpack' );
  2809. $toggle_url = wp_nonce_url(
  2810. Jetpack::admin_url(
  2811. array(
  2812. 'page' => 'jetpack',
  2813. 'action' => 'activate',
  2814. 'module' => $module,
  2815. )
  2816. ),
  2817. "jetpack_activate-$module"
  2818. );
  2819. }
  2820. if ( $counter % 4 == 0 ) {
  2821. $classes = $css . ' jetpack-newline';
  2822. $counter = 0;
  2823. } else {
  2824. $classes = $css;
  2825. }
  2826. $free_text = esc_html( $module_data['free'] ? __( 'Free', 'jetpack' ) : __( 'Purchase', 'jetpack' ) );
  2827. $free_text = apply_filters( 'jetpack_module_free_text_' . $module, $free_text );
  2828. $badge_text = $free_text;
  2829. if ( ( ! $jetpack_connected && ! Jetpack::is_development_mode() ) ) {
  2830. $classes = 'x disabled';
  2831. } elseif ( $jetpack_version_time + 604800 > $now ) { // 1 week
  2832. if ( version_compare( $module_data['introduced'], $jetpack_old_version, '>' ) ) {
  2833. $badge_text = esc_html__( 'New', 'jetpack' );
  2834. $classes .= ' jetpack-new-module';
  2835. } elseif ( isset( $module_data['changed'] ) && version_compare( $module_data['changed'], $jetpack_old_version, '>' ) ) {
  2836. $badge_text = esc_html__( 'Updated', 'jetpack' );
  2837. $classes .= ' jetpack-updated-module';
  2838. } else {
  2839. $badge_text = $free_text;
  2840. }
  2841. }
  2842. ?>
  2843. <div class="jetpack-module jetpack-<?php echo $classes; ?>" id="<?php echo $module ?>">
  2844. <h3><?php echo esc_html( $module_data['name'] ); ?></h3>
  2845. <div class="jetpack-module-description">
  2846. <div class="module-image">
  2847. <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>
  2848. </div>
  2849. <p><?php echo apply_filters( 'jetpack_short_module_description', $module_data['description'], $module ); ?></p>
  2850. </div>
  2851. <div class="jetpack-module-actions">
  2852. <?php if ( $jetpack_connected || ( Jetpack::is_development_mode() && ! $module_data['requires_connection'] ) ) : ?>
  2853. <?php if ( ! $activated && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
  2854. <a href="<?php echo esc_url( $toggle_url ); ?>" class="<?php echo ( 'inactive' == $css ? ' button-primary' : ' button-secondary' ); ?>"><?php echo $toggle; ?></a>&nbsp;
  2855. <?php endif; ?>
  2856. <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
  2857. <?php
  2858. if ( current_user_can( 'manage_options' ) && apply_filters( 'jetpack_module_configurable_' . $module, false ) ) {
  2859. echo '<a href="' . esc_url( Jetpack::module_configuration_url( $module ) ) . '" class="jetpack-configure-button button-secondary">' . __( 'Configure', 'jetpack' ) . '</a>';
  2860. }
  2861. ?><?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; ?>
  2862. <?php else : ?>
  2863. <?php do_action( 'jetpack_learn_more_button_' . $module ) ?>
  2864. <?php endif; ?>
  2865. </div>
  2866. </div>
  2867. <?php if ( 'inactive' == $css && $jetpack_connected && current_user_can( 'manage_options' ) && apply_filters( 'jetpack_can_activate_' . $module, true ) ) : ?>
  2868. <script type="text/javascript">
  2869. jQuery( '#<?php echo esc_js( $module ); ?>' ).bind( 'click', function(e){
  2870. if ( ! jQuery(e.target).hasClass('more-info-link') )
  2871. document.location.href = '<?php echo str_replace( '&amp;', '&', esc_js( esc_url( $toggle_url ) ) ); ?>';
  2872. } );
  2873. </script>
  2874. <?php else : ?>
  2875. <style>
  2876. #<?php echo $module; ?> { cursor: default; }
  2877. </style>
  2878. <?php endif; ?>
  2879. <div id="jp-more-info-<?php echo esc_attr( $module ); ?>" style="display:none;">
  2880. <?php
  2881. if ( $jetpack_connected && has_action( 'jetpack_module_more_info_connected_' . $module ) )
  2882. do_action( 'jetpack_module_more_info_connected_' . $module );
  2883. else
  2884. do_action( 'jetpack_module_more_info_' . $module );
  2885. ?>
  2886. </div>
  2887. <?php
  2888. $counter++;
  2889. }
  2890. // Add in some "Coming soon..." placeholders to fill up the current row and one more
  2891. for ( $i = 0; $i < 4; $i++ ) { ?>
  2892. <div class="jetpack-module placeholder"<?php if ( $i > 8 - $counter ) echo ' style="display: none;"'; ?>>
  2893. <h3><?php _e( 'Coming soon&#8230;', 'jetpack' ) ?></h3>
  2894. </div>
  2895. <?php
  2896. }
  2897. echo '</div><!-- .module-container -->';
  2898. }
  2899. function check_news_subscription() {
  2900. if ( ! $this->current_user_is_connection_owner() ) {
  2901. exit;
  2902. }
  2903. Jetpack::load_xml_rpc_client();
  2904. $xml = new Jetpack_IXR_Client(
  2905. array(
  2906. 'user_id' => JETPACK_MASTER_USER,
  2907. )
  2908. );
  2909. $xml->query( 'jetpack.checkNewsSubscription' );
  2910. if ( $xml->isError() ) {
  2911. printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
  2912. } else {
  2913. print_r( $xml->getResponse() );
  2914. }
  2915. exit;
  2916. }
  2917. function subscribe_to_news() {
  2918. if ( ! $this->current_user_is_connection_owner() ) {
  2919. exit;
  2920. }
  2921. Jetpack::load_xml_rpc_client();
  2922. $xml = new Jetpack_IXR_Client(
  2923. array(
  2924. 'user_id' => JETPACK_MASTER_USER,
  2925. )
  2926. );
  2927. $xml->query( 'jetpack.subscribeToNews' );
  2928. if ( $xml->isError() ) {
  2929. printf( '%s: %s', $xml->getErrorCode(), $xml->getErrorMessage() );
  2930. } else {
  2931. print_r( $xml->getResponse() );
  2932. }
  2933. exit;
  2934. }
  2935. function sync_reindex_trigger() {
  2936. if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
  2937. echo json_encode( $this->sync->reindex_trigger() );
  2938. } else {
  2939. echo '{"status":"ERROR"}';
  2940. }
  2941. exit;
  2942. }
  2943. function sync_reindex_status(){
  2944. if ( $this->current_user_is_connection_owner() && current_user_can( 'manage_options' ) ) {
  2945. echo json_encode( $this->sync->reindex_status() );
  2946. } else {
  2947. echo '{"status":"ERROR"}';
  2948. }
  2949. exit;
  2950. }
  2951. /* Client API */
  2952. /**
  2953. * Returns the requested Jetpack API URL
  2954. *
  2955. * @return string
  2956. */
  2957. public static function api_url( $relative_url ) {
  2958. return trailingslashit( JETPACK__API_BASE . $relative_url ) . JETPACK__API_VERSION . '/';
  2959. }
  2960. /**
  2961. * Some hosts disable the OpenSSL extension and so cannot make outgoing HTTPS requsets
  2962. */
  2963. public static function fix_url_for_bad_hosts( $url ) {
  2964. if ( 0 !== strpos( $url, 'https://' ) ) {
  2965. return $url;
  2966. }
  2967. switch ( JETPACK_CLIENT__HTTPS ) {
  2968. case 'ALWAYS' :
  2969. return $url;
  2970. case 'NEVER' :
  2971. return self::force_url_to_non_ssl( $url );
  2972. // default : case 'AUTO' :
  2973. }
  2974. // Yay! Your host is good!
  2975. if ( self::permit_ssl() && wp_http_supports( array( 'ssl' => true ) ) ) {
  2976. return $url;
  2977. }
  2978. // Boo! Your host is bad and makes Jetpack cry!
  2979. return self::force_url_to_non_ssl( $url );
  2980. }
  2981. /**
  2982. * Checks to see if the URL is using SSL to connect with Jetpack
  2983. *
  2984. * @since 2.3.3
  2985. * @return boolean
  2986. */
  2987. public static function permit_ssl( $force_recheck = false ) {
  2988. // Do some fancy tests to see if ssl is being supported
  2989. if ( $force_recheck || false === ( $ssl = get_transient( 'jetpack_https_test' ) ) ) {
  2990. if ( 'https' !== substr( JETPACK__API_BASE, 0, 5 ) ) {
  2991. $ssl = 0;
  2992. } else {
  2993. switch ( JETPACK_CLIENT__HTTPS ) {
  2994. case 'NEVER':
  2995. $ssl = 0;
  2996. break;
  2997. case 'ALWAYS':
  2998. case 'AUTO':
  2999. default:
  3000. $ssl = 1;
  3001. break;
  3002. }
  3003. // If it's not 'NEVER', test to see
  3004. if ( $ssl ) {
  3005. $response = wp_remote_get( JETPACK__API_BASE . 'test/1/' );
  3006. if ( is_wp_error( $response ) || ( 'OK' !== wp_remote_retrieve_body( $response ) ) ) {
  3007. $ssl = 0;
  3008. }
  3009. }
  3010. }
  3011. set_transient( 'jetpack_https_test', $ssl, DAY_IN_SECONDS );
  3012. }
  3013. return (bool) $ssl;
  3014. }
  3015. /**
  3016. * Take any URL, and if it starts with https:// change it to http://
  3017. */
  3018. public static function force_url_to_non_ssl( $url ) {
  3019. return preg_replace( '#^https://#i', 'http://', $url );
  3020. }
  3021. /*
  3022. * Displays an admin_notice, alerting the user to their JETPACK_CLIENT__HTTPS constant being 'ALWAYS' but SSL isn't working.
  3023. */
  3024. public function alert_required_ssl_fail() {
  3025. if ( ! current_user_can( 'manage_options' ) )
  3026. return;
  3027. ?>
  3028. <div id="message" class="error jetpack-message jp-identity-crisis">
  3029. <div class="jetpack-wrap-container">
  3030. <div class="jetpack-text-container">
  3031. <h3><?php _e( 'Something is being cranky!', 'jetpack' ); ?></h3>
  3032. <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>
  3033. </div>
  3034. </div>
  3035. </div>
  3036. <?php
  3037. }
  3038. /**
  3039. * Returns the Jetpack XML-RPC API
  3040. *
  3041. * @return string
  3042. */
  3043. public static function xmlrpc_api_url() {
  3044. $base = preg_replace( '#(https?://[^?/]+)(/?.*)?$#', '\\1', JETPACK__API_BASE );
  3045. return untrailingslashit( $base ) . '/xmlrpc.php';
  3046. }
  3047. /**
  3048. * Creates two secret tokens and the end of life timestamp for them.
  3049. *
  3050. * Note these tokens are unique per call, NOT static per site for connecting.
  3051. *
  3052. * @since 2.6
  3053. * @return array
  3054. */
  3055. public function generate_secrets() {
  3056. $secrets = array(
  3057. wp_generate_password( 32, false ), // secret_1
  3058. wp_generate_password( 32, false ), // secret_2
  3059. ( time() + 600 ), // eol ( End of Life )
  3060. );
  3061. return $secrets;
  3062. }
  3063. /**
  3064. * Builds the timeout limit for queries talking with the wpcom servers.
  3065. *
  3066. * Based on local php max_execution_time in php.ini
  3067. *
  3068. * @since 2.6
  3069. * @return int
  3070. **/
  3071. public function get_remote_query_timeout_limit() {
  3072. $timeout = (int) ini_get( 'max_execution_time' );
  3073. if ( ! $timeout ) // Ensure exec time set in php.ini
  3074. $timeout = 30;
  3075. return intval( $timeout / 2 );
  3076. }
  3077. /**
  3078. * Takes the response from the Jetpack register new site endpoint and
  3079. * verifies it worked properly.
  3080. *
  3081. * @since 2.6
  3082. * @return true or Jetpack_Error
  3083. **/
  3084. public function validate_remote_register_response( $response ) {
  3085. if ( is_wp_error( $response ) ) {
  3086. return new Jetpack_Error( 'register_http_request_failed', $response->get_error_message() );
  3087. }
  3088. $code = wp_remote_retrieve_response_code( $response );
  3089. $entity = wp_remote_retrieve_body( $response );
  3090. if ( $entity )
  3091. $json = json_decode( $entity );
  3092. else
  3093. $json = false;
  3094. $code_type = intval( $code / 100 );
  3095. if ( 5 == $code_type ) {
  3096. return new Jetpack_Error( 'wpcom_5??', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
  3097. } elseif ( 408 == $code ) {
  3098. return new Jetpack_Error( 'wpcom_408', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
  3099. } elseif ( ! empty( $json->error ) ) {
  3100. $error_description = isset( $json->error_description ) ? sprintf( __( 'Error Details: %s', 'jetpack' ), (string) $json->error_description ) : '';
  3101. return new Jetpack_Error( (string) $json->error, $error_description, $code );
  3102. } elseif ( 200 != $code ) {
  3103. return new Jetpack_Error( 'wpcom_bad_response', sprintf( __( 'Error Details: %s', 'jetpack' ), $code ), $code );
  3104. }
  3105. // Jetpack ID error block
  3106. if ( empty( $json->jetpack_id ) ) {
  3107. return new Jetpack_Error( 'jetpack_id', sprintf( __( 'Error Details: Jetpack ID is empty. Do not publicly post this error message! %s', 'jetpack' ), $entity ), $entity );
  3108. } elseif ( ! is_scalar( $json->jetpack_id ) ) {
  3109. 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 );
  3110. } elseif ( preg_match( '/[^0-9]/', $json->jetpack_id ) ) {
  3111. 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 );
  3112. }
  3113. return true;
  3114. }
  3115. /**
  3116. * @return bool|WP_Error
  3117. */
  3118. public static function register() {
  3119. add_action( 'pre_update_jetpack_option_register', array( 'Jetpack_Options', 'delete_option' ) );
  3120. $secrets = Jetpack::init()->generate_secrets();
  3121. Jetpack_Options::update_option( 'register', $secrets[0] . ':' . $secrets[1].
  3122. ':' . $secrets[2] );
  3123. @list( $secret_1, $secret_2, $secret_eol ) = explode( ':', Jetpack_Options::get_option( 'register' ) );
  3124. if ( empty( $secret_1 ) || empty( $secret_2 ) || empty( $secret_eol ) || $secret_eol < time() )
  3125. return new Jetpack_Error( 'missing_secrets' );
  3126. $timeout = Jetpack::init()->get_remote_query_timeout_limit();
  3127. $gmt_offset = get_option( 'gmt_offset' );
  3128. if ( ! $gmt_offset ) {
  3129. $gmt_offset = 0;
  3130. }
  3131. $stats_options = get_option( 'stats_options' );
  3132. $stats_id = isset($stats_options['blog_id']) ? $stats_options['blog_id'] : null;
  3133. $args = array(
  3134. 'method' => 'POST',
  3135. 'body' => array(
  3136. 'siteurl' => site_url(),
  3137. 'home' => home_url(),
  3138. 'gmt_offset' => $gmt_offset,
  3139. 'timezone_string' => (string) get_option( 'timezone_string' ),
  3140. 'site_name' => (string) get_option( 'blogname' ),
  3141. 'secret_1' => $secret_1,
  3142. 'secret_2' => $secret_2,
  3143. 'site_lang' => get_locale(),
  3144. 'timeout' => $timeout,
  3145. 'stats_id' => $stats_id,
  3146. ),
  3147. 'headers' => array(
  3148. 'Accept' => 'application/json',
  3149. ),
  3150. 'timeout' => $timeout,
  3151. );
  3152. $response = Jetpack_Client::_wp_remote_request( Jetpack::fix_url_for_bad_hosts( Jetpack::api_url( 'register' ) ), $args, true );
  3153. // Make sure the response is valid and does not contain any Jetpack errors
  3154. $valid_response = Jetpack::init()->validate_remote_register_response( $response );
  3155. if( is_wp_error( $valid_response ) || !$valid_response ) {
  3156. return $valid_response;
  3157. }
  3158. // Grab the response values to work with
  3159. $code = wp_remote_retrieve_response_code( $response );
  3160. $entity = wp_remote_retrieve_body( $response );
  3161. if ( $entity )
  3162. $json = json_decode( $entity );
  3163. else
  3164. $json = false;
  3165. if ( empty( $json->jetpack_secret ) || ! is_string( $json->jetpack_secret ) )
  3166. return new Jetpack_Error( 'jetpack_secret', '', $code );
  3167. if ( isset( $json->jetpack_public ) ) {
  3168. $jetpack_public = (int) $json->jetpack_public;
  3169. } else {
  3170. $jetpack_public = false;
  3171. }
  3172. Jetpack_Options::update_options(
  3173. array(
  3174. 'id' => (int) $json->jetpack_id,
  3175. 'blog_token' => (string) $json->jetpack_secret,
  3176. 'public' => $jetpack_public,
  3177. )
  3178. );
  3179. return true;
  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='" . site_url( stripslashes( $_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 static 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 = self::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. // Then kick an error!
  3712. $errors[ $cloud_key ] = $cloud_value;
  3713. }
  3714. }
  3715. }
  3716. }
  3717. return apply_filters( 'jetpack_has_identity_crisis', $errors, $force_recheck );
  3718. }
  3719. /**
  3720. * Adds a value to the whitelist for the specified key.
  3721. *
  3722. * @param string $key The option name that we're whitelisting the value for.
  3723. * @param string $value The value that we're intending to add to the whitelist.
  3724. *
  3725. * @return bool Whether the value was added to the whitelist, or false if it was already there.
  3726. */
  3727. public static function whitelist_identity_crisis_value( $key, $value ) {
  3728. if ( self::is_identity_crisis_url_whitelisted( $key, $value ) ) {
  3729. return false;
  3730. }
  3731. $whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
  3732. if ( empty( $whitelist[ $key ] ) || ! is_array( $whitelist[ $key ] ) ) {
  3733. $whitelist[ $key ] = array();
  3734. }
  3735. array_push( $whitelist[ $key ], $value );
  3736. Jetpack_Options::update_option( 'identity_crisis_whitelist', $whitelist );
  3737. return true;
  3738. }
  3739. /**
  3740. * Checks whether a value is already whitelisted.
  3741. *
  3742. * @param string $key The option name that we're checking the value for.
  3743. * @param string $value The value that we're curious to see if it's on the whitelist.
  3744. *
  3745. * @return bool Whether the value is whitelisted.
  3746. */
  3747. public static function is_identity_crisis_value_whitelisted( $key, $value ) {
  3748. $whitelist = Jetpack_Options::get_option( 'identity_crisis_whitelist', array() );
  3749. if ( ! empty( $whitelist[ $key ] ) && is_array( $whitelist[ $key ] ) && in_array( $value, $whitelist[ $key ] ) ) {
  3750. return true;
  3751. }
  3752. return false;
  3753. }
  3754. /**
  3755. * Displays an admin_notice, alerting the user to an identity crisis.
  3756. */
  3757. public function alert_identity_crisis() {
  3758. if ( ! current_user_can( 'manage_options' ) )
  3759. return;
  3760. if ( ! $errors = self::check_identity_crisis() )
  3761. return;
  3762. ?>
  3763. <div id="message" class="updated jetpack-message jp-identity-crisis">
  3764. <div class="jetpack-wrap-container">
  3765. <div class="jetpack-text-container">
  3766. <h3><?php _e( 'Something has gotten mixed up!', 'jetpack' ); ?></h3>
  3767. <?php foreach ( $errors as $key => $value ) : ?>
  3768. <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>
  3769. <?php endforeach; ?>
  3770. <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>
  3771. <p><a href="#"><?php _e( 'Ignore the difference. This is just a staging site for the real site referenced above.', 'jetpack' ); ?></a></p>
  3772. <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>
  3773. </div>
  3774. </div>
  3775. </div>
  3776. <?php
  3777. }
  3778. /**
  3779. * Loads a view file from the views
  3780. *
  3781. * Data passed in with the $data parameter will be available in the
  3782. * template file as $data['value']
  3783. *
  3784. * @param string $template - Template file to load
  3785. * @param array $data - Any data to pass along to the template
  3786. * @return boolean - If template file was found
  3787. **/
  3788. public function load_view( $template, $data = array() ) {
  3789. $views_dir = JETPACK__PLUGIN_DIR . 'views/';
  3790. if( file_exists( $views_dir . $template ) ) {
  3791. require_once( $views_dir . $template );
  3792. return true;
  3793. }
  3794. error_log( "Jetpack: Unable to find view file $views_dir$template" );
  3795. return false;
  3796. }
  3797. }