PageRenderTime 53ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/wp-content/plugins/jetpack/modules/stats.php

https://bitbucket.org/cisash/fananeen
PHP | 1077 lines | 851 code | 144 blank | 82 comment | 150 complexity | bb867c4afb8241a4c72170c8c3af41ec MD5 | raw file
  1. <?php
  2. /**
  3. * Module Name: WordPress.com Stats
  4. * Module Description: Simple, concise site stats with no additional load on your server.
  5. * Sort Order: 1
  6. * First Introduced: 1.1
  7. */
  8. if ( defined( 'STATS_VERSION' ) ) {
  9. return;
  10. }
  11. define( 'STATS_VERSION', '7' );
  12. defined( 'STATS_DASHBOARD_SERVER' ) or define( 'STATS_DASHBOARD_SERVER', 'dashboard.wordpress.com' );
  13. add_action( 'jetpack_modules_loaded', 'stats_load' );
  14. // Tell HQ about changed settings
  15. Jetpack_Sync::sync_options( __FILE__,
  16. 'home',
  17. 'siteurl',
  18. 'blogname',
  19. 'blogdescription',
  20. 'gmt_offset',
  21. 'timezone_string',
  22. 'page_on_front',
  23. 'permalink_structure',
  24. 'category_base',
  25. 'tag_base'
  26. );
  27. function stats_load() {
  28. global $wp_roles;
  29. Jetpack::enable_module_configurable( __FILE__ );
  30. Jetpack::module_configuration_load( __FILE__, 'stats_configuration_load' );
  31. Jetpack::module_configuration_head( __FILE__, 'stats_configuration_head' );
  32. Jetpack::module_configuration_screen( __FILE__, 'stats_configuration_screen' );
  33. // Tell HQ about changed posts
  34. $post_stati = get_post_stati( array( 'public' => true ) ); // All public post stati
  35. $post_stati[] = 'private'; // Content from private stati will be redacted
  36. Jetpack_Sync::sync_posts( __FILE__, array(
  37. 'post_types' => get_post_types( array( 'public' => true ) ), // All public post types
  38. 'post_stati' => $post_stati,
  39. ) );
  40. // Generate the tracking code after wp() has queried for posts.
  41. add_action( 'template_redirect', 'stats_template_redirect', 1 );
  42. add_action( 'wp_head', 'stats_admin_bar_head', 100 );
  43. add_action( 'jetpack_admin_menu', 'stats_admin_menu' );
  44. add_action( 'wp_dashboard_setup', 'stats_register_dashboard_widget' );
  45. add_filter( 'jetpack_xmlrpc_methods', 'stats_xmlrpc_methods' );
  46. // Map stats caps
  47. add_filter( 'map_meta_cap', 'stats_map_meta_caps', 10, 4 );
  48. add_filter( 'pre_option_db_version', 'stats_ignore_db_version' );
  49. }
  50. /**
  51. * Prevent sparkline img requests being redirected to upgrade.php.
  52. * See wp-admin/admin.php where it checks $wp_db_version.
  53. */
  54. function stats_ignore_db_version( $version ) {
  55. if (
  56. is_admin() &&
  57. isset( $_GET['page'] ) && $_GET['page'] == 'stats' &&
  58. isset( $_GET['chart'] ) && strpos($_GET['chart'], 'admin-bar-hours') === 0
  59. ) {
  60. global $wp_db_version;
  61. return $wp_db_version;
  62. }
  63. return $version;
  64. }
  65. /**
  66. * Maps view_stats cap to read cap as needed
  67. *
  68. * @return array Possibly mapped capabilities for meta capability
  69. */
  70. function stats_map_meta_caps( $caps, $cap, $user_id, $args ) {
  71. // Map view_stats to exists
  72. if ( 'view_stats' == $cap ) {
  73. $user = new WP_User( $user_id );
  74. $user_role = array_shift( $user->roles );
  75. $stats_roles = stats_get_option( 'roles' );
  76. // Is the users role in the available stats roles?
  77. if ( in_array( $user_role, $stats_roles ) ) {
  78. $caps = array( 'read' );
  79. }
  80. }
  81. return $caps;
  82. }
  83. function stats_template_redirect() {
  84. global $wp_the_query, $current_user, $stats_footer;
  85. if ( is_feed() || is_robots() || is_trackback() )
  86. return;
  87. $options = stats_get_options();
  88. // Ensure this is always setup for the check below
  89. $options['reg_users'] = empty( $options['reg_users'] ) ? false : true;
  90. if ( !$options['reg_users'] && !empty( $current_user->ID ) )
  91. return;
  92. add_action( 'wp_footer', 'stats_footer', 101 );
  93. add_action( 'wp_head', 'stats_add_shutdown_action' );
  94. $blog = Jetpack::get_option( 'id' );
  95. $v = 'ext';
  96. $j = sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION );
  97. if ( $wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page ) {
  98. // Store and reset the queried_object and queried_object_id
  99. // Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase.
  100. // Repro:
  101. // 1. Set home_url = http://ExamPle.com/
  102. // 2. Set show_on_front = page
  103. // 3. Set page_on_front = something
  104. // 4. Visit http://example.com/
  105. $queried_object = ( isset( $wp_the_query->queried_object ) ) ? $wp_the_query->queried_object : null;
  106. $queried_object_id = ( isset( $wp_the_query->queried_object_id ) ) ? $wp_the_query->queried_object_id : null;
  107. $post = $wp_the_query->get_queried_object_id();
  108. $wp_the_query->queried_object = $queried_object;
  109. $wp_the_query->queried_object_id = $queried_object_id;
  110. } else {
  111. $post = '0';
  112. }
  113. $http = is_ssl() ? 'https' : 'http';
  114. $week = gmdate( 'YW' );
  115. $data = stats_array( compact( 'v', 'j', 'blog', 'post' ) );
  116. $stats_footer = <<<END
  117. <script src="$http://stats.wordpress.com/e-$week.js" type="text/javascript"></script>
  118. <script type="text/javascript">
  119. st_go({{$data}});
  120. var load_cmc = function(){linktracker_init($blog,$post,2);};
  121. if ( typeof addLoadEvent != 'undefined' ) addLoadEvent(load_cmc);
  122. else load_cmc();
  123. </script>
  124. END;
  125. if ( isset( $options['hide_smile'] ) && $options['hide_smile'] ) {
  126. $stats_footer .= "\n<style type='text/css'>img#wpstats{display:none}</style>";
  127. }
  128. }
  129. function stats_add_shutdown_action() {
  130. // just in case wp_footer isn't in your theme
  131. add_action( 'shutdown', 'stats_footer', 101 );
  132. }
  133. function stats_footer() {
  134. global $stats_footer;
  135. print $stats_footer;
  136. $stats_footer = '';
  137. }
  138. function stats_get_options() {
  139. $options = get_option( 'stats_options' );
  140. if ( !isset( $options['version'] ) || $options['version'] < STATS_VERSION )
  141. $options = stats_upgrade_options( $options );
  142. return $options;
  143. }
  144. function stats_get_option( $option ) {
  145. $options = stats_get_options();
  146. if ( $option == 'blog_id' )
  147. return Jetpack::get_option( 'id' );
  148. if ( isset( $options[$option] ) )
  149. return $options[$option];
  150. return null;
  151. }
  152. function stats_set_option( $option, $value ) {
  153. $options = stats_get_options();
  154. $options[$option] = $value;
  155. stats_set_options($options);
  156. }
  157. function stats_set_options($options) {
  158. update_option( 'stats_options', $options );
  159. }
  160. function stats_upgrade_options( $options ) {
  161. $defaults = array(
  162. 'admin_bar' => true,
  163. 'roles' => array( 'administrator' ),
  164. 'blog_id' => Jetpack::get_option( 'id' ),
  165. 'do_not_track' => true, // @todo
  166. 'hide_smile' => false,
  167. );
  168. if ( is_array( $options ) && !empty( $options ) )
  169. $new_options = array_merge( $defaults, $options );
  170. else
  171. $new_options = $defaults;
  172. $new_options['version'] = STATS_VERSION;
  173. stats_set_options( $new_options );
  174. stats_update_blog();
  175. return $new_options;
  176. }
  177. function stats_array( $kvs ) {
  178. $kvs = apply_filters( 'stats_array', $kvs );
  179. $kvs = array_map( 'addslashes', $kvs );
  180. foreach ( $kvs as $k => $v )
  181. $jskvs[] = "$k:'$v'";
  182. return join( ',', $jskvs );
  183. }
  184. /**
  185. * Admin Pages
  186. */
  187. function stats_admin_menu() {
  188. global $pagenow;
  189. // If we're at an old Stats URL, redirect to the new one.
  190. // Don't even bother with caps, menu_page_url(), etc. Just do it.
  191. if ( 'index.php' == $pagenow && isset( $_GET['page'] ) && 'stats' == $_GET['page'] ) {
  192. $redirect_url = str_replace( array( '/wp-admin/index.php?', '/wp-admin/?' ), '/wp-admin/admin.php?', $_SERVER['REQUEST_URI'] );
  193. $relative_pos = strpos( $redirect_url, '/wp-admin/' );
  194. if ( false !== $relative_pos ) {
  195. wp_safe_redirect( admin_url( substr( $redirect_url, $relative_pos + 10 ) ) );
  196. exit;
  197. }
  198. }
  199. $hook = add_submenu_page( 'jetpack', __( 'Site Stats', 'jetpack' ), __( 'Site Stats', 'jetpack' ), 'view_stats', 'stats', 'stats_reports_page' );
  200. add_action( "load-$hook", 'stats_reports_load' );
  201. }
  202. function stats_admin_path() {
  203. return Jetpack::module_configuration_url( __FILE__ );
  204. }
  205. function stats_reports_load() {
  206. wp_enqueue_script( 'jquery' );
  207. wp_enqueue_script( 'postbox' );
  208. add_action( 'admin_print_styles', 'stats_reports_css' );
  209. if ( isset( $_GET['nojs'] ) && $_GET['nojs'] ) {
  210. $parsed = parse_url( admin_url() );
  211. // Remember user doesn't want JS
  212. setcookie( 'stnojs', '1', time() + 172800, $parsed['path'] ); // 2 days
  213. }
  214. if ( isset( $_COOKIE['stnojs'] ) && $_COOKIE['stnojs'] ) {
  215. // Detect if JS is on. If so, remove cookie so next page load is via JS
  216. add_action( 'admin_print_footer_scripts', 'stats_js_remove_stnojs_cookie' );
  217. } else if ( !isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) ) {
  218. // Normal page load. Load page content via JS.
  219. add_action( 'admin_print_footer_scripts', 'stats_js_load_page_via_ajax' );
  220. }
  221. }
  222. function stats_reports_css() {
  223. ?>
  224. <style type="text/css">
  225. #stats-loading-wrap p {
  226. text-align: center;
  227. font-size: 2em;
  228. margin: 7.5em 15px 0 0;
  229. height: 64px;
  230. line-height: 64px;
  231. }
  232. </style>
  233. <?php
  234. }
  235. // Detect if JS is on. If so, remove cookie so next page load is via JS.
  236. function stats_js_remove_stnojs_cookie() {
  237. $parsed = parse_url( admin_url() );
  238. ?>
  239. <script type="text/javascript">
  240. /* <![CDATA[ */
  241. document.cookie = 'stnojs=0; expires=Wed, 9 Mar 2011 16:55:50 UTC; path=<?php echo esc_js( $parsed['path'] ); ?>';
  242. /* ]]> */
  243. </script>
  244. <?php
  245. }
  246. // Normal page load. Load page content via JS.
  247. function stats_js_load_page_via_ajax() {
  248. ?>
  249. <script type="text/javascript">
  250. /* <![CDATA[ */
  251. if ( -1 == document.location.href.indexOf( 'noheader' ) ) {
  252. jQuery( function( $ ) {
  253. $.get( document.location.href + '&noheader', function( responseText ) {
  254. $( '#stats-loading-wrap' ).replaceWith( responseText );
  255. } );
  256. } );
  257. }
  258. /* ]]> */
  259. </script>
  260. <?php
  261. }
  262. function stats_reports_page() {
  263. if ( isset( $_GET['dashboard'] ) )
  264. return stats_dashboard_widget_content();
  265. if ( !isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) {
  266. $nojs_url = add_query_arg( 'nojs', '1' );
  267. if ( 'classic' != $color = get_user_option( 'admin_color' ) ) {
  268. $color = 'fresh';
  269. }
  270. $http = is_ssl() ? 'https' : 'http';
  271. // Loading message
  272. // No JS fallback message
  273. ?>
  274. <style type="text/css">
  275. @media only screen and (-moz-min-device-pixel-ratio: 1.5), only screen and (-o-min-device-pixel-ratio: 3/2), only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-device-pixel-ratio: 1.5) {
  276. img.wpcom-loading-64 { width: 32px; height: 32px; }
  277. }
  278. </style>
  279. <div id="stats-loading-wrap" class="wrap">
  280. <p class="hide-if-no-js"><img class="wpcom-loading-64" alt="<?php esc_attr_e( 'Loading&hellip;', 'jetpack' ); ?>" src="<?php echo esc_url( "$http://" . STATS_DASHBOARD_SERVER . "/i/loading/$color-64.gif" ); ?>" /></p>
  281. <p class="hide-if-js"><?php esc_html_e( 'Your Site Stats work better with Javascript enabled.', 'jetpack' ); ?><br />
  282. <a href="<?php echo esc_url( $nojs_url ); ?>"><?php esc_html_e( 'View Site Stats without Javascript', 'jetpack' ); ?></a>.</p>
  283. </div>
  284. <?php
  285. return;
  286. }
  287. $blog_id = stats_get_option( 'blog_id' );
  288. $day = isset( $_GET['day'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_GET['day'] ) ? $_GET['day'] : false;
  289. $q = array(
  290. 'noheader' => 'true',
  291. 'proxy' => '',
  292. 'page' => 'stats',
  293. 'day' => $day,
  294. 'blog' => $blog_id,
  295. 'charset' => get_option( 'blog_charset' ),
  296. 'color' => get_user_option( 'admin_color' ),
  297. 'ssl' => is_ssl(),
  298. 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
  299. );
  300. $args = array(
  301. 'view' => array( 'referrers', 'postviews', 'searchterms', 'clicks', 'post', 'table' ),
  302. 'numdays' => 'int',
  303. 'day' => 'date',
  304. 'unit' => array( 1, 7, 31, 'human' ),
  305. 'humanize' => array( 'true' ),
  306. 'num' => 'int',
  307. 'summarize' => null,
  308. 'post' => 'int',
  309. 'width' => 'int',
  310. 'height' => 'int',
  311. 'data' => 'data',
  312. 'blog_subscribers' => 'int',
  313. 'comment_subscribers' => null,
  314. 'type' => array( 'email', 'pending' ),
  315. 'pagenum' => 'int',
  316. );
  317. foreach ( $args as $var => $vals ) {
  318. if ( !isset( $_REQUEST[$var] ) )
  319. continue;
  320. if ( is_array( $vals ) ) {
  321. if ( in_array( $_REQUEST[$var], $vals ) )
  322. $q[$var] = $_REQUEST[$var];
  323. } elseif ( $vals == 'int' ) {
  324. $q[$var] = intval( $_REQUEST[$var] );
  325. } elseif ( $vals == 'date' ) {
  326. if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_REQUEST[$var] ) )
  327. $q[$var] = $_REQUEST[$var];
  328. } elseif ( $vals == null ) {
  329. $q[$var] = '';
  330. } elseif ( $vals == 'data' ) {
  331. if ( substr( $_REQUEST[$var], 0, 9 ) == 'index.php' )
  332. $q[$var] = $_REQUEST[$var];
  333. }
  334. }
  335. if ( isset( $_REQUEST['chart'] ) ) {
  336. if ( preg_match( '/^[a-z0-9-]+$/', $_REQUEST['chart'] ) )
  337. $url = 'http://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$_GET['chart']}.php";
  338. } else {
  339. $url = 'http://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
  340. }
  341. $url = add_query_arg( $q, $url );
  342. $method = 'GET';
  343. $timeout = 90;
  344. $user_id = JETPACK_MASTER_USER; // means send the wp.com user_id
  345. $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
  346. $get_code = wp_remote_retrieve_response_code( $get );
  347. if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) {
  348. stats_print_wp_remote_error( $get, $url );
  349. } else {
  350. if ( !empty( $get['headers']['content-type'] ) ) {
  351. $type = $get['headers']['content-type'];
  352. if ( substr( $type, 0, 5 ) == 'image' ) {
  353. $img = $get['body'];
  354. header( 'Content-Type: ' . $type );
  355. header( 'Content-Length: ' . strlen( $img ) );
  356. echo $img;
  357. die();
  358. }
  359. }
  360. $body = stats_convert_post_titles( $get['body'] );
  361. $body = stats_convert_chart_urls( $body );
  362. $body = stats_convert_image_urls( $body );
  363. $body = stats_convert_admin_urls( $body );
  364. echo $body;
  365. }
  366. if ( isset( $_GET['noheader'] ) )
  367. die;
  368. }
  369. function stats_convert_admin_urls( $html ) {
  370. return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html );
  371. }
  372. function stats_convert_image_urls( $html ) {
  373. $url = ( is_ssl() ? 'https' : 'http' ) . '://' . STATS_DASHBOARD_SERVER;
  374. $html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html );
  375. return $html;
  376. }
  377. function stats_convert_chart_urls( $html ) {
  378. $html = preg_replace_callback( '|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',
  379. create_function(
  380. '$matches',
  381. // If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string
  382. 'return "admin.php?page=stats&noheader&chart=" . $matches[1] . str_replace( "?", "&", $matches[2] );'
  383. ),
  384. $html );
  385. return $html;
  386. }
  387. function stats_convert_post_titles( $html ) {
  388. global $wpdb, $stats_posts;
  389. $pattern = "<span class='post-(\d+)-link'>.*?</span>";
  390. if ( !preg_match_all( "!$pattern!", $html, $matches ) )
  391. return $html;
  392. $posts = get_posts( array(
  393. 'include' => implode( ',', $matches[1] ),
  394. 'post_type' => 'any',
  395. 'post_status' => 'any',
  396. 'numberposts' => -1,
  397. ));
  398. foreach ( $posts as $post )
  399. $stats_posts[$post->ID] = $post;
  400. $html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html );
  401. return $html;
  402. }
  403. function stats_convert_post_title( $matches ) {
  404. global $stats_posts;
  405. $post_id = $matches[1];
  406. if ( isset( $stats_posts[$post_id] ) )
  407. return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>';
  408. return $matches[0];
  409. }
  410. function stats_configuration_load() {
  411. if ( isset( $_POST['action'] ) && $_POST['action'] == 'save_options' && $_POST['_wpnonce'] == wp_create_nonce( 'stats' ) ) {
  412. $options = stats_get_options();
  413. $options['admin_bar'] = isset( $_POST['admin_bar'] ) && $_POST['admin_bar'];
  414. $options['reg_users'] = isset( $_POST['reg_users'] ) && $_POST['reg_users'];
  415. $options['hide_smile'] = isset( $_POST['hide_smile'] ) && $_POST['hide_smile'];
  416. $options['roles'] = array( 'administrator' );
  417. foreach ( get_editable_roles() as $role => $details )
  418. if ( isset( $_POST["role_$role"] ) && $_POST["role_$role"] )
  419. $options['roles'][] = $role;
  420. stats_set_options( $options );
  421. stats_update_blog();
  422. Jetpack::state( 'message', 'module_configured' );
  423. wp_safe_redirect( Jetpack::module_configuration_url( 'stats' ) );
  424. exit;
  425. }
  426. }
  427. function stats_configuration_head() {
  428. ?>
  429. <style type="text/css">
  430. #statserror {
  431. border: 1px solid #766;
  432. background-color: #d22;
  433. padding: 1em 3em;
  434. }
  435. .stats-smiley {
  436. vertical-align: 1px;
  437. }
  438. </style>
  439. <?php
  440. }
  441. function stats_configuration_screen() {
  442. $options = stats_get_options();
  443. $options['reg_users'] = empty( $options['reg_users'] ) ? false : true;
  444. ?>
  445. <div class="narrow">
  446. <p><?php printf( __( 'Visit <a href="%s">Site Stats</a> to see your stats.', 'jetpack' ), esc_url( menu_page_url( 'stats', false ) ) ); ?></p>
  447. <form method="post">
  448. <input type='hidden' name='action' value='save_options' />
  449. <?php wp_nonce_field( 'stats' ); ?>
  450. <table id="menu" class="form-table">
  451. <tr valign="top"><th scope="row"><label for="admin_bar"><?php _e( 'Admin bar' , 'jetpack' ); ?></label></th>
  452. <td><label><input type='checkbox'<?php checked( $options['admin_bar'] ); ?> name='admin_bar' id='admin_bar' /> <?php _e( "Put a chart showing 48 hours of views in the admin bar.", 'jetpack' ); ?></label></td></tr>
  453. <tr valign="top"><th scope="row"><label for="reg_users"><?php _e( 'Registered users', 'jetpack' ); ?></label></th>
  454. <td><label><input type='checkbox'<?php checked( $options['reg_users'] ); ?> name='reg_users' id='reg_users' /> <?php _e( "Count the page views of registered users who are logged in.", 'jetpack' ); ?></label></td></tr>
  455. <tr valign="top"><th scope="row"><?php _e( 'Smiley' , 'jetpack' ); ?></th>
  456. <td><label><input type='checkbox'<?php checked( isset( $options['hide_smile'] ) && $options['hide_smile'] ); ?> name='hide_smile' id='hide_smile' /> <?php _e( 'Hide the stats smiley face image.', 'jetpack' ); ?></label><br /> <span class="description"><?php _e( 'The image helps collect stats and <strong>makes the world a better place</strong> but should still work when hidden', 'jetpack' ); ?> <img class="stats-smiley" alt="<?php esc_attr_e( 'Smiley face', 'jetpack' ); ?>" src="<?php echo esc_url( plugins_url( '_inc/images/stats-smiley.gif', dirname( __FILE__ ) ) ); ?>" width="6" height="5" /></span></td></tr>
  457. <tr valign="top"><th scope="row"><?php _e( 'Report visibility' , 'jetpack' ); ?></th>
  458. <td>
  459. <?php _e( 'Select the roles that will be able to view stats reports.', 'jetpack' ); ?><br/>
  460. <?php
  461. $stats_roles = stats_get_option( 'roles' );
  462. foreach ( get_editable_roles() as $role => $details ) {
  463. ?>
  464. <label><input type='checkbox' <?php if ( $role == 'administrator' ) echo "disabled='disabled' "; ?>name='role_<?php echo $role; ?>'<?php checked( $role == 'administrator' || in_array( $role, $stats_roles ) ); ?> /> <?php echo translate_user_role( $details['name'] ); ?></label><br/>
  465. <?php
  466. }
  467. ?>
  468. </tr>
  469. </table>
  470. <p class="submit"><input type='submit' class='button-primary' value='<?php echo esc_attr( __( 'Save configuration', 'jetpack' ) ); ?>' /></p>
  471. </form>
  472. </div>
  473. <?php
  474. }
  475. function stats_admin_bar_head() {
  476. if ( !stats_get_option( 'admin_bar' ) )
  477. return;
  478. if ( !current_user_can( 'view_stats' ) )
  479. return;
  480. if ( function_exists( 'is_admin_bar_showing' ) && !is_admin_bar_showing() ) {
  481. return;
  482. }
  483. add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 );
  484. ?>
  485. <style type='text/css'>
  486. #wpadminbar .quicklinks li#wp-admin-bar-stats {
  487. height: 28px;
  488. }
  489. #wpadminbar .quicklinks li#wp-admin-bar-stats a {
  490. height: 28px;
  491. padding: 0;
  492. }
  493. #wpadminbar .quicklinks li#wp-admin-bar-stats a div {
  494. height: 28px;
  495. width: 95px;
  496. overflow: hidden;
  497. margin: 0 10px;
  498. }
  499. #wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div {
  500. width: auto;
  501. margin: 0 8px 0 10px;
  502. }
  503. #wpadminbar .quicklinks li#wp-admin-bar-stats a img {
  504. height: 24px;
  505. padding: 2px 0;
  506. max-width: none;
  507. border: none;
  508. }
  509. </style>
  510. <?php
  511. }
  512. function stats_admin_bar_menu( &$wp_admin_bar ) {
  513. $blog_id = stats_get_option( 'blog_id' );
  514. $url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ); // no menu_page_url() blog-side.
  515. $img_src = esc_attr( add_query_arg( array( 'noheader'=>'', 'proxy'=>'', 'chart'=>'admin-bar-hours-scale' ), $url ) );
  516. $img_src_2x = esc_attr( add_query_arg( array( 'noheader'=>'', 'proxy'=>'', 'chart'=>'admin-bar-hours-scale-2x' ), $url ) );
  517. $alt = esc_attr( __( 'Stats', 'jetpack' ) );
  518. $title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) );
  519. $menu = array( 'id' => 'stats', 'title' => "<div><script type='text/javascript'>var src;if(typeof(window.devicePixelRatio)=='undefined'||window.devicePixelRatio<2){src='$img_src';}else{src='$img_src_2x';}document.write('<img src=\''+src+'\' alt=\'$alt\' title=\'$title\' />');</script></div>", 'href' => $url );
  520. $wp_admin_bar->add_menu( $menu );
  521. }
  522. function stats_update_blog() {
  523. Jetpack::xmlrpc_async_call( 'jetpack.updateBlog', stats_get_blog() );
  524. }
  525. function stats_get_blog() {
  526. $home = parse_url( trailingslashit( get_option( 'home' ) ) );
  527. $blog = array(
  528. 'host' => $home['host'],
  529. 'path' => $home['path'],
  530. 'blogname' => get_option( 'blogname' ),
  531. 'blogdescription' => get_option( 'blogdescription' ),
  532. 'siteurl' => get_option( 'siteurl' ),
  533. 'gmt_offset' => get_option( 'gmt_offset' ),
  534. 'timezone_string' => get_option( 'timezone_string' ),
  535. 'stats_version' => STATS_VERSION,
  536. 'stats_api' => 'jetpack',
  537. 'page_on_front' => get_option( 'page_on_front' ),
  538. 'permalink_structure' => get_option( 'permalink_structure' ),
  539. 'category_base' => get_option( 'category_base' ),
  540. 'tag_base' => get_option( 'tag_base' ),
  541. );
  542. $blog = array_merge( stats_get_options(), $blog );
  543. unset( $blog['roles'], $blog['blog_id'] );
  544. return array_map( 'esc_html', $blog );
  545. }
  546. function stats_xmlrpc_methods( $methods ) {
  547. $my_methods = array(
  548. 'jetpack.getBlog' => 'stats_get_blog',
  549. );
  550. return array_merge( $methods, $my_methods );
  551. }
  552. function stats_register_dashboard_widget() {
  553. if ( ! current_user_can( 'view_stats' ) )
  554. return;
  555. // wp_dashboard_empty: we load in the content after the page load via JS
  556. wp_add_dashboard_widget( 'dashboard_stats', __( 'Site Stats', 'jetpack' ), 'wp_dashboard_empty', 'stats_dashboard_widget_control' );
  557. add_action( 'admin_head', 'stats_dashboard_head' );
  558. }
  559. function stats_dashboard_widget_options() {
  560. $defaults = array( 'chart' => 1, 'top' => 1, 'search' => 7 );
  561. if ( ( !$options = get_option( 'stats_dashboard_widget' ) ) || !is_array( $options ) )
  562. $options = array();
  563. // Ignore obsolete option values
  564. $intervals = array( 1, 7, 31, 90, 365 );
  565. foreach ( array( 'top', 'search' ) as $key )
  566. if ( isset( $options[$key] ) && !in_array( $options[$key], $intervals ) )
  567. unset( $options[$key] );
  568. return array_merge( $defaults, $options );
  569. }
  570. function stats_dashboard_widget_control() {
  571. $periods = array(
  572. '1' => __( 'day', 'jetpack' ),
  573. '7' => __( 'week', 'jetpack' ),
  574. '31' => __( 'month', 'jetpack' ),
  575. );
  576. $intervals = array(
  577. '1' => __( 'the past day', 'jetpack' ),
  578. '7' => __( 'the past week', 'jetpack' ),
  579. '31' => __( 'the past month', 'jetpack' ),
  580. '90' => __( 'the past quarter', 'jetpack' ),
  581. '365' => __( 'the past year', 'jetpack' ),
  582. );
  583. $defaults = array(
  584. 'top' => 1,
  585. 'search' => 7,
  586. );
  587. $options = stats_dashboard_widget_options();
  588. if ( 'post' == strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' == $_POST['widget_id'] ) {
  589. if ( isset( $periods[ $_POST['chart'] ] ) )
  590. $options['chart'] = $_POST['chart'];
  591. foreach ( array( 'top', 'search' ) as $key ) {
  592. if ( isset( $intervals[ $_POST[$key] ] ) )
  593. $options[$key] = $_POST[$key];
  594. else
  595. $options[$key] = $defaults[$key];
  596. }
  597. update_option( 'stats_dashboard_widget', $options );
  598. }
  599. ?>
  600. <p>
  601. <label for="chart"><?php _e( 'Chart stats by' , 'jetpack' ); ?></label>
  602. <select id="chart" name="chart">
  603. <?php
  604. foreach ( $periods as $val => $label ) {
  605. ?>
  606. <option value="<?php echo $val; ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option>
  607. <?php
  608. }
  609. ?>
  610. </select>.
  611. </p>
  612. <p>
  613. <label for="top"><?php _e( 'Show top posts over', 'jetpack' ); ?></label>
  614. <select id="top" name="top">
  615. <?php
  616. foreach ( $intervals as $val => $label ) {
  617. ?>
  618. <option value="<?php echo $val; ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option>
  619. <?php
  620. }
  621. ?>
  622. </select>.
  623. </p>
  624. <p>
  625. <label for="search"><?php _e( 'Show top search terms over', 'jetpack' ); ?></label>
  626. <select id="search" name="search">
  627. <?php
  628. foreach ( $intervals as $val => $label ) {
  629. ?>
  630. <option value="<?php echo $val; ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option>
  631. <?php
  632. }
  633. ?>
  634. </select>.
  635. </p>
  636. <?php
  637. }
  638. // Javascript and CSS for dashboard widget
  639. function stats_dashboard_head() { ?>
  640. <script type="text/javascript">
  641. /* <![CDATA[ */
  642. jQuery(window).load( function() {
  643. jQuery( function($) {
  644. var dashStats = $( '#dashboard_stats.postbox div.inside' );
  645. if ( dashStats.find( '.dashboard-widget-control-form' ).size() ) {
  646. return;
  647. }
  648. if ( ! dashStats.size() ) {
  649. dashStats = $( '#dashboard_stats div.dashboard-widget-content' );
  650. var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() );
  651. var args = 'width=' + dashStats.width() + '&height=' + h.toString();
  652. } else {
  653. var args = 'width=' + ( dashStats.prev().width() * 2 ).toString();
  654. }
  655. dashStats.not( '.dashboard-widget-control' ).load( 'admin.php?page=stats&noheader&dashboard&' + args );
  656. } );
  657. } );
  658. /* ]]> */
  659. </script>
  660. <style type="text/css">
  661. /* <![CDATA[ */
  662. #stat-chart {
  663. background: none !important;
  664. }
  665. #dashboard_stats .inside {
  666. margin: 10px 0 0 0 !important;
  667. }
  668. #dashboard_stats #stats-graph {
  669. margin: 0;
  670. }
  671. #stats-info {
  672. border-top: 1px solid #dfdfdf;
  673. margin: 7px -10px 0 -10px;
  674. padding: 10px;
  675. background: #fcfcfc;
  676. -moz-box-shadow:inset 0 1px 0 #fff;
  677. -webkit-box-shadow:inset 0 1px 0 #fff;
  678. box-shadow:inset 0 1px 0 #fff;
  679. overflow: hidden;
  680. border-radius: 0 0 2px 2px;
  681. -webkit-border-radius: 0 0 2px 2px;
  682. -moz-border-radius: 0 0 2px 2px;
  683. -khtml-border-radius: 0 0 2px 2px;
  684. }
  685. #stats-info #top-posts, #stats-info #top-search {
  686. float: left;
  687. width: 50%;
  688. }
  689. #top-posts .stats-section-inner p {
  690. white-space: nowrap;
  691. overflow: hidden;
  692. }
  693. #top-posts .stats-section-inner p a {
  694. overflow: hidden;
  695. text-overflow: ellipsis;
  696. }
  697. #stats-info div#active {
  698. border-top: 1px solid #dfdfdf;
  699. margin: 0 -10px;
  700. padding: 10px 10px 0 10px;
  701. -moz-box-shadow:inset 0 1px 0 #fff;
  702. -webkit-box-shadow:inset 0 1px 0 #fff;
  703. box-shadow:inset 0 1px 0 #fff;
  704. overflow: hidden;
  705. }
  706. #top-search p {
  707. color: #999;
  708. }
  709. #stats-info h4 {
  710. font-size: 1em;
  711. margin: 0 0 .5em 0 !important;
  712. }
  713. #stats-info p {
  714. margin: 0 0 .25em;
  715. color: #999;
  716. }
  717. #stats-info p.widget-loading {
  718. margin: 1em 0 0;
  719. color: #333;
  720. }
  721. #stats-info p a {
  722. display: block;
  723. }
  724. #stats-info p a.button {
  725. display: inline;
  726. }
  727. /* ]]> */
  728. </style>
  729. <?php
  730. }
  731. function stats_dashboard_widget_content() {
  732. if ( !isset( $_GET['width'] ) || ( !$width = (int) ( $_GET['width'] / 2 ) ) || $width < 250 )
  733. $width = 370;
  734. if ( !isset( $_GET['height'] ) || ( !$height = (int) $_GET['height'] - 36 ) || $height < 230 )
  735. $height = 180;
  736. $_width = $width - 5;
  737. $_height = $height - ( $GLOBALS['is_winIE'] ? 16 : 5 ); // hack!
  738. $options = stats_dashboard_widget_options();
  739. $blog_id = Jetpack::get_option( 'id' );
  740. $q = array(
  741. 'noheader' => 'true',
  742. 'proxy' => '',
  743. 'blog' => $blog_id,
  744. 'page' => 'stats',
  745. 'chart' => '',
  746. 'unit' => $options['chart'],
  747. 'color' => get_user_option( 'admin_color' ),
  748. 'width' => $_width,
  749. 'height' => $_height,
  750. 'ssl' => is_ssl(),
  751. 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),
  752. );
  753. $url = 'http://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php";
  754. $url = add_query_arg( $q, $url );
  755. $method = 'GET';
  756. $timeout = 90;
  757. $user_id = JETPACK_MASTER_USER;
  758. $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
  759. $get_code = wp_remote_retrieve_response_code( $get );
  760. if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) {
  761. stats_print_wp_remote_error( $get, $url );
  762. } else {
  763. $body = stats_convert_post_titles($get['body']);
  764. $body = stats_convert_chart_urls($body);
  765. $body = stats_convert_image_urls($body);
  766. echo $body;
  767. }
  768. $post_ids = array();
  769. $csv_args = array( 'top' => '&limit=8', 'search' => '&limit=5' );
  770. /* translators: Stats dashboard widget postviews list: "$post_title $views Views" */
  771. $printf = __( '%1$s %2$s Views' , 'jetpack' );
  772. foreach ( $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" ) as $post )
  773. $post_ids[] = $post['post_id'];
  774. // cache
  775. get_posts( array( 'include' => join( ',', array_unique( $post_ids ) ) ) );
  776. $searches = array();
  777. foreach ( $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" ) as $search_term )
  778. $searches[] = esc_html( $search_term['searchterm'] );
  779. ?>
  780. <a class="button" href="admin.php?page=stats"><?php _e( 'View All', 'jetpack' ); ?></a>
  781. <div id="stats-info">
  782. <div id="top-posts" class='stats-section'>
  783. <div class="stats-section-inner">
  784. <h4 class="heading"><?php _e( 'Top Posts' , 'jetpack' ); ?></h4>
  785. <?php
  786. if ( empty( $top_posts ) ) {
  787. ?>
  788. <p class="nothing"><?php _e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
  789. <?php
  790. } else {
  791. foreach ( $top_posts as $post ) {
  792. if ( !get_post( $post['post_id'] ) )
  793. continue;
  794. ?>
  795. <p><?php printf(
  796. $printf,
  797. '<a href="' . get_permalink( $post['post_id'] ) . '">' . get_the_title( $post['post_id'] ) . '</a>',
  798. number_format_i18n( $post['views'] )
  799. ); ?></p>
  800. <?php
  801. }
  802. }
  803. ?>
  804. </div>
  805. </div>
  806. <div id="top-search" class='stats-section'>
  807. <div class="stats-section-inner">
  808. <h4 class="heading"><?php _e( 'Top Searches' , 'jetpack' ); ?></h4>
  809. <?php
  810. if ( empty( $searches ) ) {
  811. ?>
  812. <p class="nothing"><?php _e( 'Sorry, nothing to report.', 'jetpack' ); ?></p>
  813. <?php
  814. } else {
  815. ?>
  816. <p><?php echo join( ',&nbsp; ', $searches );?></p>
  817. <?php
  818. }
  819. ?>
  820. </div>
  821. </div>
  822. </div>
  823. <div class="clear"></div>
  824. <?php
  825. exit;
  826. }
  827. function stats_print_wp_remote_error( $get, $url ) {
  828. $state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 );
  829. $previous_error = Jetpack::state( $state_name );
  830. $error = md5( serialize( compact( 'get', 'url' ) ) );
  831. Jetpack::state( $state_name, $error );
  832. if ( $error !== $previous_error ) {
  833. ?>
  834. <div class="wrap">
  835. <p><?php _e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p>
  836. </div>
  837. <?php
  838. return;
  839. }
  840. ?>
  841. <div class="wrap">
  842. <p><?php printf( __( 'We were unable to get your stats just now. Please reload this page to try again. If this error persists, please <a href="%1$s">contact support</a>. In your report please include the information below.', 'jetpack' ), 'http://support.wordpress.com/contact/?jetpack=needs-service' ); ?></p>
  843. <pre>
  844. User Agent: "<?php print htmlspecialchars( $_SERVER['HTTP_USER_AGENT'] ); ?>"
  845. Page URL: "http<?php print (is_ssl()?'s':'') . '://' . htmlspecialchars( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>"
  846. API URL: "<?php print clean_url( $url ); ?>"
  847. <?php
  848. if ( is_wp_error( $get ) ) {
  849. foreach ( $get->get_error_codes() as $code ) {
  850. foreach ( $get->get_error_messages($code) as $message ) {
  851. ?>
  852. <?php print $code . ': "' . $message . '"' ?>
  853. <?php
  854. }
  855. }
  856. } else {
  857. $get_code = wp_remote_retrieve_response_code( $get );
  858. $content_length = strlen( wp_remote_retrieve_body( $get ) );
  859. ?>
  860. Response code: "<?php print $get_code ?>"
  861. Content length: "<?php print $content_length ?>"
  862. <?php
  863. }
  864. ?></pre>
  865. </div>
  866. <?php
  867. }
  868. function stats_get_csv( $table, $args = null ) {
  869. $defaults = array( 'end' => false, 'days' => false, 'limit' => 3, 'post_id' => false, 'summarize' => '' );
  870. $args = wp_parse_args( $args, $defaults );
  871. $args['table'] = $table;
  872. $args['blog_id'] = Jetpack::get_option( 'id' );
  873. $stats_csv_url = add_query_arg( $args, 'http://stats.wordpress.com/csv.php' );
  874. $key = md5( $stats_csv_url );
  875. // Get cache
  876. $stats_cache = get_option( 'stats_cache' );
  877. if ( !$stats_cache || !is_array( $stats_cache ) )
  878. $stats_cache = array();
  879. // Return or expire this key
  880. if ( isset( $stats_cache[$key] ) ) {
  881. $time = key( $stats_cache[$key] );
  882. if ( time() - $time < 300 )
  883. return $stats_cache[$key][$time];
  884. unset( $stats_cache[$key] );
  885. }
  886. $stats_rows = array();
  887. do {
  888. if ( !$stats = stats_get_remote_csv( $stats_csv_url ) )
  889. break;
  890. $labels = array_shift( $stats );
  891. if ( 0 === stripos( $labels[0], 'error' ) )
  892. break;
  893. $stats_rows = array();
  894. for ( $s = 0; isset( $stats[$s] ); $s++ ) {
  895. $row = array();
  896. foreach ( $labels as $col => $label )
  897. $row[$label] = $stats[$s][$col];
  898. $stats_rows[] = $row;
  899. }
  900. } while( 0 );
  901. // Expire old keys
  902. foreach ( $stats_cache as $k => $cache )
  903. if ( !is_array( $cache ) || 300 < time() - key($cache) )
  904. unset( $stats_cache[$k] );
  905. // Set cache
  906. $stats_cache[$key] = array( time() => $stats_rows );
  907. update_option( 'stats_cache', $stats_cache );
  908. return $stats_rows;
  909. }
  910. function stats_get_remote_csv( $url ) {
  911. $method = 'GET';
  912. $timeout = 90;
  913. $user_id = JETPACK_MASTER_USER;
  914. $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) );
  915. $get_code = wp_remote_retrieve_response_code( $get );
  916. if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) {
  917. return array(); // @todo: return an error?
  918. } else {
  919. return stats_str_getcsv( $get['body'] );
  920. }
  921. }
  922. // rather than parsing the csv and its special cases, we create a new file and do fgetcsv on it.
  923. function stats_str_getcsv( $csv ) {
  924. if ( !$temp = tmpfile() ) // tmpfile() automatically unlinks
  925. return false;
  926. $data = array();
  927. fwrite( $temp, $csv, strlen( $csv ) );
  928. fseek( $temp, 0 );
  929. while ( false !== $row = fgetcsv( $temp, 2000 ) )
  930. $data[] = $row;
  931. fclose( $temp );
  932. return $data;
  933. }