PageRenderTime 110ms CodeModel.GetById 25ms RepoModel.GetById 1ms app.codeStats 1ms

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

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