PageRenderTime 109ms CodeModel.GetById 39ms RepoModel.GetById 2ms app.codeStats 1ms

/class.jetpack.php

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