PageRenderTime 43ms CodeModel.GetById 19ms RepoModel.GetById 0ms app.codeStats 1ms

/wp-content/plugins/jetpack/class.jetpack.php

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