/modules/stats.php

  1. <?php 
  2. /** 
  3. * Module Name: Site Stats 
  4. * Module Description: Collect traffic stats and insights. 
  5. * Sort Order: 1 
  6. * Recommendation Order: 2 
  7. * First Introduced: 1.1 
  8. * Requires Connection: Yes 
  9. * Auto Activate: Yes 
  10. * Module Tags: Site Stats, Recommended 
  11. * Feature: Recommended, Traffic 
  12. * Additional Search Queries: statistics, tracking, analytics, views, traffic, stats 
  13. */ 
  14.  
  15. if ( defined( 'STATS_VERSION' ) ) { 
  16. return; 
  17.  
  18. define( 'STATS_VERSION', '9' ); 
  19. defined( 'STATS_DASHBOARD_SERVER' ) or define( 'STATS_DASHBOARD_SERVER', 'dashboard.wordpress.com' ); 
  20.  
  21. add_action( 'jetpack_modules_loaded', 'stats_load' ); 
  22.  
  23. // Tell HQ about changed settings 
  24. Jetpack_Sync::sync_options( __FILE__,  
  25. 'stats_options',  
  26. 'home',  
  27. 'siteurl',  
  28. 'blogname',  
  29. 'blogdescription',  
  30. 'gmt_offset',  
  31. 'timezone_string',  
  32. 'page_on_front',  
  33. 'permalink_structure',  
  34. 'category_base',  
  35. 'tag_base' 
  36. ); 
  37.  
  38. function stats_load() { 
  39. global $wp_roles; 
  40.  
  41. Jetpack::enable_module_configurable( __FILE__ ); 
  42. Jetpack::module_configuration_load( __FILE__, 'stats_configuration_load' ); 
  43. Jetpack::module_configuration_head( __FILE__, 'stats_configuration_head' ); 
  44. Jetpack::module_configuration_screen( __FILE__, 'stats_configuration_screen' ); 
  45.  
  46. // Tell HQ about changed posts 
  47. $post_stati = get_post_stati( array( 'public' => true ) ); // All public post stati 
  48. $post_stati[] = 'private'; // Content from private stati will be redacted 
  49. Jetpack_Sync::sync_posts( __FILE__, array( 
  50. 'post_types' => get_post_types( array( 'public' => true ) ), // All public post types 
  51. 'post_stati' => $post_stati,  
  52. ) ); 
  53.  
  54. // Generate the tracking code after wp() has queried for posts. 
  55. add_action( 'template_redirect', 'stats_template_redirect', 1 ); 
  56.  
  57. add_action( 'wp_head', 'stats_admin_bar_head', 100 ); 
  58.  
  59. add_action( 'wp_head', 'stats_hide_smile_css' ); 
  60.  
  61. add_action( 'jetpack_admin_menu', 'stats_admin_menu' ); 
  62.  
  63. // Map stats caps 
  64. add_filter( 'map_meta_cap', 'stats_map_meta_caps', 10, 4 ); 
  65.  
  66. if ( isset( $_GET['oldwidget'] ) ) { 
  67. // Old one. 
  68. add_action( 'wp_dashboard_setup', 'stats_register_dashboard_widget' ); 
  69. } else { 
  70. add_action( 'admin_init', 'stats_merged_widget_admin_init' ); 
  71.  
  72. add_filter( 'jetpack_xmlrpc_methods', 'stats_xmlrpc_methods' ); 
  73.  
  74.  
  75. add_filter( 'pre_option_db_version', 'stats_ignore_db_version' ); 
  76.  
  77. /** 
  78. * Delay conditional for current_user_can to after init. 
  79. */ 
  80. function stats_merged_widget_admin_init() { 
  81. if ( current_user_can( 'view_stats' ) ) { 
  82. add_action( 'load-index.php', 'stats_enqueue_dashboard_head' ); 
  83. add_action( 'wp_dashboard_setup', 'stats_register_widget_control_callback' ); // hacky but works 
  84. add_action( 'jetpack_dashboard_widget', 'stats_jetpack_dashboard_widget' ); 
  85.  
  86. function stats_enqueue_dashboard_head() { 
  87. add_action( 'admin_head', 'stats_dashboard_head' ); 
  88.  
  89. /** 
  90. * Prevent sparkline img requests being redirected to upgrade.php. 
  91. * See wp-admin/admin.php where it checks $wp_db_version. 
  92. */ 
  93. function stats_ignore_db_version( $version ) { 
  94. if ( 
  95. is_admin() && 
  96. isset( $_GET['page'] ) && $_GET['page'] == 'stats' && 
  97. isset( $_GET['chart'] ) && strpos($_GET['chart'], 'admin-bar-hours') === 0 
  98. ) { 
  99. global $wp_db_version; 
  100. return $wp_db_version; 
  101. return $version; 
  102.  
  103. /** 
  104. * Maps view_stats cap to read cap as needed 
  105. * 
  106. * @return array Possibly mapped capabilities for meta capability 
  107. */ 
  108. function stats_map_meta_caps( $caps, $cap, $user_id, $args ) { 
  109. // Map view_stats to exists 
  110. if ( 'view_stats' == $cap ) { 
  111. $user = new WP_User( $user_id ); 
  112. $user_role = array_shift( $user->roles ); 
  113. $stats_roles = stats_get_option( 'roles' ); 
  114.  
  115. // Is the users role in the available stats roles? 
  116. if ( is_array( $stats_roles ) && in_array( $user_role, $stats_roles ) ) { 
  117. $caps = array( 'read' ); 
  118.  
  119. return $caps; 
  120.  
  121. function stats_template_redirect() { 
  122. global $wp_the_query, $current_user, $stats_footer; 
  123.  
  124. if ( is_feed() || is_robots() || is_trackback() || is_preview() ) 
  125. return; 
  126.  
  127. // Should we be counting this user's views? 
  128. if ( !empty( $current_user->ID ) ) { 
  129. $count_roles = stats_get_option( 'count_roles' ); 
  130. if ( ! array_intersect( $current_user->roles, $count_roles ) ) 
  131. return; 
  132.  
  133. add_action( 'wp_footer', 'stats_footer', 101 ); 
  134. add_action( 'wp_head', 'stats_add_shutdown_action' ); 
  135.  
  136. $blog = Jetpack_Options::get_option( 'id' ); 
  137. $tz = get_option( 'gmt_offset' ); 
  138. $v = 'ext'; 
  139. $blog_url = parse_url( site_url() ); 
  140. $srv = $blog_url['host']; 
  141. $j = sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ); 
  142. if ( $wp_the_query->is_single || $wp_the_query->is_page || $wp_the_query->is_posts_page ) { 
  143. // Store and reset the queried_object and queried_object_id 
  144. // Otherwise, redirect_canonical() will redirect to home_url( '/' ) for show_on_front = page sites where home_url() is not all lowercase. 
  145. // Repro: 
  146. // 1. Set home_url = http://ExamPle.com/ 
  147. // 2. Set show_on_front = page 
  148. // 3. Set page_on_front = something 
  149. // 4. Visit http://example.com/ 
  150.  
  151. $queried_object = ( isset( $wp_the_query->queried_object ) ) ? $wp_the_query->queried_object : null; 
  152. $queried_object_id = ( isset( $wp_the_query->queried_object_id ) ) ? $wp_the_query->queried_object_id : null; 
  153. $post = $wp_the_query->get_queried_object_id(); 
  154. $wp_the_query->queried_object = $queried_object; 
  155. $wp_the_query->queried_object_id = $queried_object_id; 
  156. } else { 
  157. $post = '0'; 
  158.  
  159. $script = set_url_scheme( '//stats.wp.com/e-' . gmdate( 'YW' ) . '.js' ); 
  160. $data = stats_array( compact( 'v', 'j', 'blog', 'post', 'tz', 'srv' ) ); 
  161.  
  162. $stats_footer = <<<END 
  163. <script type='text/javascript' src='{$script}' async defer></script> 
  164. <script type='text/javascript'> 
  165. _stq = window._stq || []; 
  166. _stq.push([ 'view', {{$data}} ]); 
  167. _stq.push([ 'clickTrackerInit', '{$blog}', '{$post}' ]); 
  168. </script> 
  169.  
  170. END; 
  171.  
  172. function stats_add_shutdown_action() { 
  173. // just in case wp_footer isn't in your theme 
  174. add_action( 'shutdown', 'stats_footer', 101 ); 
  175.  
  176. function stats_footer() { 
  177. global $stats_footer; 
  178. print $stats_footer; 
  179. $stats_footer = ''; 
  180.  
  181. function stats_get_options() { 
  182. $options = get_option( 'stats_options' ); 
  183.  
  184. if ( !isset( $options['version'] ) || $options['version'] < STATS_VERSION ) 
  185. $options = stats_upgrade_options( $options ); 
  186.  
  187. return $options; 
  188.  
  189. function stats_get_option( $option ) { 
  190. $options = stats_get_options(); 
  191.  
  192. if ( $option == 'blog_id' ) 
  193. return Jetpack_Options::get_option( 'id' ); 
  194.  
  195. if ( isset( $options[$option] ) ) 
  196. return $options[$option]; 
  197.  
  198. return null; 
  199.  
  200. function stats_set_option( $option, $value ) { 
  201. $options = stats_get_options(); 
  202.  
  203. $options[$option] = $value; 
  204.  
  205. stats_set_options($options); 
  206.  
  207. function stats_set_options($options) { 
  208. update_option( 'stats_options', $options ); 
  209.  
  210. function stats_upgrade_options( $options ) { 
  211. $defaults = array( 
  212. 'admin_bar' => true,  
  213. 'roles' => array( 'administrator' ),  
  214. 'count_roles' => array(),  
  215. 'blog_id' => Jetpack_Options::get_option( 'id' ),  
  216. 'do_not_track' => true, // @todo 
  217. 'hide_smile' => true,  
  218. ); 
  219.  
  220. if ( isset( $options['reg_users'] ) ) { 
  221. if ( ! function_exists( 'get_editable_roles' ) ) 
  222. require_once( ABSPATH . 'wp-admin/includes/user.php' ); 
  223. if ( $options['reg_users'] ) 
  224. $options['count_roles'] = array_keys( get_editable_roles() ); 
  225. unset( $options['reg_users'] ); 
  226.  
  227. if ( is_array( $options ) && !empty( $options ) ) 
  228. $new_options = array_merge( $defaults, $options ); 
  229. else 
  230. $new_options = $defaults; 
  231.  
  232. $new_options['version'] = STATS_VERSION; 
  233.  
  234. stats_set_options( $new_options ); 
  235.  
  236. stats_update_blog(); 
  237.  
  238. return $new_options; 
  239.  
  240. function stats_array( $kvs ) { 
  241. /** 
  242. * Filter the options added to the JavaScript Stats tracking code. 
  243. * 
  244. * @module stats 
  245. * 
  246. * @since 1.1.0 
  247. * 
  248. * @param array $kvs Array of options about the site and page you're on. 
  249. */ 
  250. $kvs = apply_filters( 'stats_array', $kvs ); 
  251. $kvs = array_map( 'addslashes', $kvs ); 
  252. foreach ( $kvs as $k => $v ) 
  253. $jskvs[] = "$k:'$v'"; 
  254. return join( ', ', $jskvs ); 
  255.  
  256. /** 
  257. * Admin Pages 
  258. */ 
  259. function stats_admin_menu() { 
  260. global $pagenow; 
  261.  
  262. // If we're at an old Stats URL, redirect to the new one. 
  263. // Don't even bother with caps, menu_page_url(), etc. Just do it. 
  264. if ( 'index.php' == $pagenow && isset( $_GET['page'] ) && 'stats' == $_GET['page'] ) { 
  265. $redirect_url = str_replace( array( '/wp-admin/index.php?', '/wp-admin/?' ), '/wp-admin/admin.php?', $_SERVER['REQUEST_URI'] ); 
  266. $relative_pos = strpos( $redirect_url, '/wp-admin/' ); 
  267. if ( false !== $relative_pos ) { 
  268. wp_safe_redirect( admin_url( substr( $redirect_url, $relative_pos + 10 ) ) ); 
  269. exit; 
  270.  
  271. $hook = add_submenu_page( 'jetpack', __( 'Site Stats', 'jetpack' ), __( 'Site Stats', 'jetpack' ), 'view_stats', 'stats', 'stats_reports_page' ); 
  272. add_action( "load-$hook", 'stats_reports_load' ); 
  273.  
  274. function stats_admin_path() { 
  275. return Jetpack::module_configuration_url( __FILE__ ); 
  276.  
  277. function stats_reports_load() { 
  278. wp_enqueue_script( 'jquery' ); 
  279. wp_enqueue_script( 'postbox' ); 
  280. wp_enqueue_script( 'underscore' ); 
  281.  
  282. add_action( 'admin_print_styles', 'stats_reports_css' ); 
  283.  
  284. if ( isset( $_GET['nojs'] ) && $_GET['nojs'] ) { 
  285. $parsed = parse_url( admin_url() ); 
  286. // Remember user doesn't want JS 
  287. setcookie( 'stnojs', '1', time() + 172800, $parsed['path'] ); // 2 days 
  288.  
  289. if ( isset( $_COOKIE['stnojs'] ) && $_COOKIE['stnojs'] ) { 
  290. // Detect if JS is on. If so, remove cookie so next page load is via JS 
  291. add_action( 'admin_print_footer_scripts', 'stats_js_remove_stnojs_cookie' ); 
  292. } else if ( !isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) ) { 
  293. // Normal page load. Load page content via JS. 
  294. add_action( 'admin_print_footer_scripts', 'stats_js_load_page_via_ajax' ); 
  295.  
  296. function stats_reports_css() { 
  297. ?> 
  298. <style type="text/css"> 
  299. #stats-loading-wrap p { 
  300. text-align: center; 
  301. font-size: 2em; 
  302. margin: 7.5em 15px 0 0; 
  303. height: 64px; 
  304. line-height: 64px; 
  305. </style> 
  306. <?php 
  307.  
  308. // Detect if JS is on. If so, remove cookie so next page load is via JS
  309. function stats_js_remove_stnojs_cookie() { 
  310. $parsed = parse_url( admin_url() ); 
  311. ?> 
  312. <script type="text/javascript"> 
  313. /* <![CDATA[ */ 
  314. document.cookie = 'stnojs=0; expires=Wed, 9 Mar 2011 16:55:50 UTC; path=<?php echo esc_js( $parsed['path'] ); ?>'; 
  315. /* ]]> */ 
  316. </script> 
  317. <?php 
  318.  
  319. // Normal page load. Load page content via JS. 
  320. function stats_js_load_page_via_ajax() { 
  321. ?> 
  322. <script type="text/javascript"> 
  323. /* <![CDATA[ */ 
  324. if ( -1 == document.location.href.indexOf( 'noheader' ) ) { 
  325. jQuery( function( $ ) { 
  326. $.get( document.location.href + '&noheader', function( responseText ) { 
  327. $( '#stats-loading-wrap' ).replaceWith( responseText ); 
  328. } ); 
  329. } ); 
  330. /* ]]> */ 
  331. </script> 
  332. <?php 
  333.  
  334. function stats_reports_page() { 
  335. if ( isset( $_GET['dashboard'] ) ) 
  336. return stats_dashboard_widget_content(); 
  337.  
  338. $blog_id = stats_get_option( 'blog_id' ); 
  339.  
  340. if ( !isset( $_GET['noheader'] ) && empty( $_GET['nojs'] ) && empty( $_COOKIE['stnojs'] ) ) { 
  341. $nojs_url = add_query_arg( 'nojs', '1' ); 
  342. $http = is_ssl() ? 'https' : 'http'; 
  343. // Loading message 
  344. // No JS fallback message 
  345. ?> 
  346. <div class="wrap"> 
  347. <h2><?php esc_html_e( 'Site Stats', 'jetpack'); ?> <?php if ( current_user_can( 'jetpack_manage_modules' ) ) : ?><a style="font-size:13px;" href="<?php echo esc_url( admin_url('admin.php?page=jetpack&configure=stats') ); ?>"><?php esc_html_e( 'Configure', 'jetpack'); ?></a><?php endif; ?></h2> 
  348. </div> 
  349. <div id="stats-loading-wrap" class="wrap"> 
  350. <p class="hide-if-no-js"><img width="32" height="32" alt="<?php esc_attr_e( 'Loading…', 'jetpack' ); ?>" src="<?php 
  351. /** This filter is documented in modules/shortcodes/audio.php */ 
  352. echo esc_url( apply_filters( 'jetpack_static_url', "{$http}://en.wordpress.com/i/loading/loading-64.gif" ) ); ?>" /></p> 
  353. <p style="font-size: 11pt; margin: 0;"><a href="https://wordpress.com/stats/<?php echo $blog_id; ?>"><?php esc_html_e( 'View stats on WordPress.com right now', 'jetpack' ); ?></a></p> 
  354. <p class="hide-if-js"><?php esc_html_e( 'Your Site Stats work better with Javascript enabled.', 'jetpack' ); ?><br /> 
  355. <a href="<?php echo esc_url( $nojs_url ); ?>"><?php esc_html_e( 'View Site Stats without Javascript', 'jetpack' ); ?></a>.</p> 
  356. </div> 
  357. <?php 
  358. return; 
  359.  
  360. $day = isset( $_GET['day'] ) && preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_GET['day'] ) ? $_GET['day'] : false; 
  361. $q = array( 
  362. 'noheader' => 'true',  
  363. 'proxy' => '',  
  364. 'page' => 'stats',  
  365. 'day' => $day,  
  366. 'blog' => $blog_id,  
  367. 'charset' => get_option( 'blog_charset' ),  
  368. 'color' => get_user_option( 'admin_color' ),  
  369. 'ssl' => is_ssl(),  
  370. 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),  
  371. ); 
  372. if ( get_locale() !== 'en_US' ) { 
  373. $q['jp_lang'] = get_locale(); 
  374. $args = array( 
  375. 'view' => array( 'referrers', 'postviews', 'searchterms', 'clicks', 'post', 'table' ),  
  376. 'numdays' => 'int',  
  377. 'day' => 'date',  
  378. 'unit' => array( 1, 7, 31, 'human' ),  
  379. 'humanize' => array( 'true' ),  
  380. 'num' => 'int',  
  381. 'summarize' => null,  
  382. 'post' => 'int',  
  383. 'width' => 'int',  
  384. 'height' => 'int',  
  385. 'data' => 'data',  
  386. 'blog_subscribers' => 'int',  
  387. 'comment_subscribers' => null,  
  388. 'type' => array( 'wpcom', 'email', 'pending' ),  
  389. 'pagenum' => 'int',  
  390. ); 
  391. foreach ( $args as $var => $vals ) { 
  392. if ( !isset( $_REQUEST[$var] ) ) 
  393. continue; 
  394. if ( is_array( $vals ) ) { 
  395. if ( in_array( $_REQUEST[$var], $vals ) ) 
  396. $q[$var] = $_REQUEST[$var]; 
  397. } elseif ( $vals == 'int' ) { 
  398. $q[$var] = intval( $_REQUEST[$var] ); 
  399. } elseif ( $vals == 'date' ) { 
  400. if ( preg_match( '/^\d{4}-\d{2}-\d{2}$/', $_REQUEST[$var] ) ) 
  401. $q[$var] = $_REQUEST[$var]; 
  402. } elseif ( $vals == null ) { 
  403. $q[$var] = ''; 
  404. } elseif ( $vals == 'data' ) { 
  405. if ( substr( $_REQUEST[$var], 0, 9 ) == 'index.php' ) 
  406. $q[$var] = $_REQUEST[$var]; 
  407.  
  408. if ( isset( $_GET['chart'] ) ) { 
  409. if ( preg_match( '/^[a-z0-9-]+$/', $_GET['chart'] ) ) { 
  410. $chart = sanitize_title( $_GET['chart'] ); 
  411. $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-includes/charts/{$chart}.php"; 
  412. } else { 
  413. $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php"; 
  414.  
  415. $url = add_query_arg( $q, $url ); 
  416. $method = 'GET'; 
  417. $timeout = 90; 
  418. $user_id = JETPACK_MASTER_USER; // means send the wp.com user_id 
  419.  
  420. $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) ); 
  421. $get_code = wp_remote_retrieve_response_code( $get ); 
  422. if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) { 
  423. stats_print_wp_remote_error( $get, $url ); 
  424. } else { 
  425. if ( !empty( $get['headers']['content-type'] ) ) { 
  426. $type = $get['headers']['content-type']; 
  427. if ( substr( $type, 0, 5 ) == 'image' ) { 
  428. $img = $get['body']; 
  429. header( 'Content-Type: ' . $type ); 
  430. header( 'Content-Length: ' . strlen( $img ) ); 
  431. echo $img; 
  432. die(); 
  433. $body = stats_convert_post_titles( $get['body'] ); 
  434. $body = stats_convert_chart_urls( $body ); 
  435. $body = stats_convert_image_urls( $body ); 
  436. $body = stats_convert_admin_urls( $body ); 
  437. echo $body; 
  438. if ( isset( $_GET['noheader'] ) ) 
  439. die; 
  440.  
  441. function stats_convert_admin_urls( $html ) { 
  442. return str_replace( 'index.php?page=stats', 'admin.php?page=stats', $html ); 
  443.  
  444. function stats_convert_image_urls( $html ) { 
  445. $url = set_url_scheme( 'https://' . STATS_DASHBOARD_SERVER ); 
  446. $html = preg_replace( '|(["\'])(/i/stats.+)\\1|', '$1' . $url . '$2$1', $html ); 
  447. return $html; 
  448.  
  449. function stats_convert_chart_urls( $html ) { 
  450. $html = preg_replace_callback( '|https?://[-.a-z0-9]+/wp-includes/charts/([-.a-z0-9]+).php(\??)|',  
  451. create_function( 
  452. '$matches',  
  453. // If there is a query string, change the beginning '?' to a '&' so it fits into the middle of this query string 
  454. 'return "admin.php?page=stats&noheader&chart=" . $matches[1] . str_replace( "?", "&", $matches[2] );' 
  455. ),  
  456. $html ); 
  457. return $html; 
  458.  
  459. function stats_convert_post_titles( $html ) { 
  460. global $wpdb, $stats_posts; 
  461. $pattern = "<span class='post-(\d+)-link'>.*?</span>"; 
  462. if ( !preg_match_all( "!$pattern!", $html, $matches ) ) 
  463. return $html; 
  464. $posts = get_posts( array( 
  465. 'include' => implode( ', ', $matches[1] ),  
  466. 'post_type' => 'any',  
  467. 'post_status' => 'any',  
  468. 'numberposts' => -1,  
  469. )); 
  470. foreach ( $posts as $post ) 
  471. $stats_posts[$post->ID] = $post; 
  472. $html = preg_replace_callback( "!$pattern!", 'stats_convert_post_title', $html ); 
  473. return $html; 
  474.  
  475. function stats_convert_post_title( $matches ) { 
  476. global $stats_posts; 
  477. $post_id = $matches[1]; 
  478. if ( isset( $stats_posts[$post_id] ) ) 
  479. return '<a href="' . get_permalink( $post_id ) . '" target="_blank">' . get_the_title( $post_id ) . '</a>'; 
  480. return $matches[0]; 
  481.  
  482. function stats_configuration_load() { 
  483. if ( isset( $_POST['action'] ) && $_POST['action'] == 'save_options' && $_POST['_wpnonce'] == wp_create_nonce( 'stats' ) ) { 
  484. $options = stats_get_options(); 
  485. $options['admin_bar'] = isset( $_POST['admin_bar'] ) && $_POST['admin_bar']; 
  486. $options['hide_smile'] = isset( $_POST['hide_smile'] ) && $_POST['hide_smile']; 
  487.  
  488. $options['roles'] = array( 'administrator' ); 
  489. foreach ( get_editable_roles() as $role => $details ) 
  490. if ( isset( $_POST["role_$role"] ) && $_POST["role_$role"] ) 
  491. $options['roles'][] = $role; 
  492.  
  493. $options['count_roles'] = array(); 
  494. foreach ( get_editable_roles() as $role => $details ) 
  495. if ( isset( $_POST["count_role_$role"] ) && $_POST["count_role_$role"] ) 
  496. $options['count_roles'][] = $role; 
  497.  
  498. stats_set_options( $options ); 
  499. stats_update_blog(); 
  500. Jetpack::state( 'message', 'module_configured' ); 
  501. wp_safe_redirect( Jetpack::module_configuration_url( 'stats' ) ); 
  502. exit; 
  503.  
  504. function stats_configuration_head() { 
  505. ?> 
  506. <style type="text/css"> 
  507. #statserror { 
  508. border: 1px solid #766; 
  509. background-color: #d22; 
  510. padding: 1em 3em; 
  511. .stats-smiley { 
  512. vertical-align: 1px; 
  513. </style> 
  514. <?php 
  515.  
  516. function stats_configuration_screen() { 
  517. $options = stats_get_options(); 
  518. ?> 
  519. <div class="narrow"> 
  520. <p><?php printf( __( 'Visit <a href="%s">Site Stats</a> to see your stats.', 'jetpack' ), esc_url( menu_page_url( 'stats', false ) ) ); ?></p> 
  521. <form method="post"> 
  522. <input type='hidden' name='action' value='save_options' /> 
  523. <?php wp_nonce_field( 'stats' ); ?> 
  524. <table id="menu" class="form-table"> 
  525. <tr valign="top"><th scope="row"><label for="admin_bar"><?php _e( 'Admin bar' , 'jetpack' ); ?></label></th> 
  526. <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> 
  527. <tr valign="top"><th scope="row"><?php _e( 'Registered users', 'jetpack' ); ?></th> 
  528. <td> 
  529. <?php _e( "Count the page views of registered users who are logged in.", 'jetpack' ); ?><br/> 
  530. <?php 
  531. $count_roles = stats_get_option( 'count_roles' ); 
  532. foreach ( get_editable_roles() as $role => $details ) { 
  533. ?> 
  534. <label><input type='checkbox' name='count_role_<?php echo $role; ?>'<?php checked( in_array( $role, $count_roles ) ); ?> /> <?php echo translate_user_role( $details['name'] ); ?></label><br/> 
  535. <?php 
  536. ?> 
  537. </td></tr> 
  538. <tr valign="top"><th scope="row"><?php _e( 'Smiley' , 'jetpack' ); ?></th> 
  539. <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( 'images/stats-smiley.gif', dirname( __FILE__ ) ) ); ?>" width="6" height="5" /></span></td></tr> 
  540. <tr valign="top"><th scope="row"><?php _e( 'Report visibility' , 'jetpack' ); ?></th> 
  541. <td> 
  542. <?php _e( 'Select the roles that will be able to view stats reports.', 'jetpack' ); ?><br/> 
  543. <?php 
  544. $stats_roles = stats_get_option( 'roles' ); 
  545. foreach ( get_editable_roles() as $role => $details ) { 
  546. ?> 
  547. <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/> 
  548. <?php 
  549. ?> 
  550. </td></tr> 
  551. </table> 
  552. <p class="submit"><input type='submit' class='button-primary' value='<?php echo esc_attr( __( 'Save configuration', 'jetpack' ) ); ?>' /></p> 
  553. </form> 
  554. </div> 
  555. <?php 
  556.  
  557. function stats_hide_smile_css() { 
  558. $options = stats_get_options(); 
  559. if ( isset( $options['hide_smile'] ) && $options['hide_smile'] ) { 
  560. ?> 
  561. <style type='text/css'>img#wpstats{display:none}</style><?php 
  562.  
  563. function stats_admin_bar_head() { 
  564. if ( !stats_get_option( 'admin_bar' ) ) 
  565. return; 
  566.  
  567. if ( !current_user_can( 'view_stats' ) ) 
  568. return; 
  569.  
  570. if ( function_exists( 'is_admin_bar_showing' ) && !is_admin_bar_showing() ) { 
  571. return; 
  572.  
  573. add_action( 'admin_bar_menu', 'stats_admin_bar_menu', 100 ); 
  574. ?> 
  575.  
  576. <style type='text/css'> 
  577. #wpadminbar .quicklinks li#wp-admin-bar-stats { 
  578. height: 28px; 
  579. #wpadminbar .quicklinks li#wp-admin-bar-stats a { 
  580. height: 28px; 
  581. padding: 0; 
  582. #wpadminbar .quicklinks li#wp-admin-bar-stats a div { 
  583. height: 28px; 
  584. width: 95px; 
  585. overflow: hidden; 
  586. margin: 0 10px; 
  587. #wpadminbar .quicklinks li#wp-admin-bar-stats a:hover div { 
  588. width: auto; 
  589. margin: 0 8px 0 10px; 
  590. #wpadminbar .quicklinks li#wp-admin-bar-stats a img { 
  591. height: 24px; 
  592. padding: 2px 0; 
  593. max-width: none; 
  594. border: none; 
  595. </style> 
  596. <?php 
  597.  
  598. function stats_admin_bar_menu( &$wp_admin_bar ) { 
  599. $url = add_query_arg( 'page', 'stats', admin_url( 'admin.php' ) ); // no menu_page_url() blog-side. 
  600.  
  601. $img_src = esc_attr( add_query_arg( array( 'noheader'=>'', 'proxy'=>'', 'chart'=>'admin-bar-hours-scale' ), $url ) ); 
  602. $img_src_2x = esc_attr( add_query_arg( array( 'noheader'=>'', 'proxy'=>'', 'chart'=>'admin-bar-hours-scale-2x' ), $url ) ); 
  603.  
  604. $alt = esc_attr( __( 'Stats', 'jetpack' ) ); 
  605.  
  606. $title = esc_attr( __( 'Views over 48 hours. Click for more Site Stats.', 'jetpack' ) ); 
  607.  
  608. $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 ); 
  609.  
  610. $wp_admin_bar->add_menu( $menu ); 
  611.  
  612. function stats_update_blog() { 
  613. Jetpack::xmlrpc_async_call( 'jetpack.updateBlog', stats_get_blog() ); 
  614.  
  615. function stats_get_blog() { 
  616. $home = parse_url( trailingslashit( get_option( 'home' ) ) ); 
  617. $blog = array( 
  618. 'host' => $home['host'],  
  619. 'path' => $home['path'],  
  620. 'blogname' => get_option( 'blogname' ),  
  621. 'blogdescription' => get_option( 'blogdescription' ),  
  622. 'siteurl' => get_option( 'siteurl' ),  
  623. 'gmt_offset' => get_option( 'gmt_offset' ),  
  624. 'timezone_string' => get_option( 'timezone_string' ),  
  625. 'stats_version' => STATS_VERSION,  
  626. 'stats_api' => 'jetpack',  
  627. 'page_on_front' => get_option( 'page_on_front' ),  
  628. 'permalink_structure' => get_option( 'permalink_structure' ),  
  629. 'category_base' => get_option( 'category_base' ),  
  630. 'tag_base' => get_option( 'tag_base' ),  
  631. ); 
  632. $blog = array_merge( stats_get_options(), $blog ); 
  633. unset( $blog['roles'], $blog['blog_id'] ); 
  634. return stats_esc_html_deep( $blog ); 
  635.  
  636. /** 
  637. * Modified from stripslashes_deep() 
  638. */ 
  639. function stats_esc_html_deep( $value ) { 
  640. if ( is_array( $value ) ) { 
  641. $value = array_map( 'stats_esc_html_deep', $value ); 
  642. } elseif ( is_object( $value ) ) { 
  643. $vars = get_object_vars( $value ); 
  644. foreach ( $vars as $key => $data ) { 
  645. $value->{$key} = stats_esc_html_deep( $data ); 
  646. } elseif ( is_string( $value ) ) { 
  647. $value = esc_html( $value ); 
  648.  
  649. return $value; 
  650.  
  651. function stats_xmlrpc_methods( $methods ) { 
  652. $my_methods = array( 
  653. 'jetpack.getBlog' => 'stats_get_blog',  
  654. ); 
  655.  
  656. return array_merge( $methods, $my_methods ); 
  657.  
  658. function stats_register_dashboard_widget() { 
  659. if ( ! current_user_can( 'view_stats' ) ) 
  660. return; 
  661.  
  662. // wp_dashboard_empty: we load in the content after the page load via JS 
  663. wp_add_dashboard_widget( 'dashboard_stats', __( 'Site Stats', 'jetpack' ), 'wp_dashboard_empty', 'stats_dashboard_widget_control' ); 
  664.  
  665. add_action( 'admin_head', 'stats_dashboard_head' ); 
  666.  
  667. function stats_dashboard_widget_options() { 
  668. $defaults = array( 'chart' => 1, 'top' => 1, 'search' => 7 ); 
  669. if ( ( !$options = get_option( 'stats_dashboard_widget' ) ) || !is_array( $options ) ) 
  670. $options = array(); 
  671.  
  672. // Ignore obsolete option values 
  673. $intervals = array( 1, 7, 31, 90, 365 ); 
  674. foreach ( array( 'top', 'search' ) as $key ) 
  675. if ( isset( $options[$key] ) && !in_array( $options[$key], $intervals ) ) 
  676. unset( $options[$key] ); 
  677.  
  678. return array_merge( $defaults, $options ); 
  679.  
  680. function stats_dashboard_widget_control() { 
  681. $periods = array( 
  682. '1' => __( 'day', 'jetpack' ),  
  683. '7' => __( 'week', 'jetpack' ),  
  684. '31' => __( 'month', 'jetpack' ),  
  685. ); 
  686. $intervals = array( 
  687. '1' => __( 'the past day', 'jetpack' ),  
  688. '7' => __( 'the past week', 'jetpack' ),  
  689. '31' => __( 'the past month', 'jetpack' ),  
  690. '90' => __( 'the past quarter', 'jetpack' ),  
  691. '365' => __( 'the past year', 'jetpack' ),  
  692. ); 
  693. $defaults = array( 
  694. 'top' => 1,  
  695. 'search' => 7,  
  696. ); 
  697.  
  698. $options = stats_dashboard_widget_options(); 
  699.  
  700. if ( 'post' == strtolower( $_SERVER['REQUEST_METHOD'] ) && isset( $_POST['widget_id'] ) && 'dashboard_stats' == $_POST['widget_id'] ) { 
  701. if ( isset( $periods[ $_POST['chart'] ] ) ) 
  702. $options['chart'] = $_POST['chart']; 
  703. foreach ( array( 'top', 'search' ) as $key ) { 
  704. if ( isset( $intervals[ $_POST[$key] ] ) ) 
  705. $options[$key] = $_POST[$key]; 
  706. else 
  707. $options[$key] = $defaults[$key]; 
  708. update_option( 'stats_dashboard_widget', $options ); 
  709. ?> 
  710. <p> 
  711. <label for="chart"><?php _e( 'Chart stats by' , 'jetpack' ); ?></label> 
  712. <select id="chart" name="chart"> 
  713. <?php 
  714. foreach ( $periods as $val => $label ) { 
  715. ?> 
  716. <option value="<?php echo $val; ?>"<?php selected( $val, $options['chart'] ); ?>><?php echo esc_html( $label ); ?></option> 
  717. <?php 
  718. ?> 
  719. </select>. 
  720. </p> 
  721.  
  722. <p> 
  723. <label for="top"><?php _e( 'Show top posts over', 'jetpack' ); ?></label> 
  724. <select id="top" name="top"> 
  725. <?php 
  726. foreach ( $intervals as $val => $label ) { 
  727. ?> 
  728. <option value="<?php echo $val; ?>"<?php selected( $val, $options['top'] ); ?>><?php echo esc_html( $label ); ?></option> 
  729. <?php 
  730. ?> 
  731. </select>. 
  732. </p> 
  733.  
  734. <p> 
  735. <label for="search"><?php _e( 'Show top search terms over', 'jetpack' ); ?></label> 
  736. <select id="search" name="search"> 
  737. <?php 
  738. foreach ( $intervals as $val => $label ) { 
  739. ?> 
  740. <option value="<?php echo $val; ?>"<?php selected( $val, $options['search'] ); ?>><?php echo esc_html( $label ); ?></option> 
  741. <?php 
  742. ?> 
  743. </select>. 
  744. </p> 
  745. <?php 
  746.  
  747. function stats_jetpack_dashboard_widget() { 
  748. ?> 
  749. <h3> 
  750. <span class="js-toggle-stats_dashboard_widget_control"> 
  751. <?php esc_html_e( 'Configure', 'jetpack' ); ?> 
  752. </span> 
  753. <?php esc_html_e( 'Site Stats', 'jetpack' ); ?> 
  754. </h3> 
  755. <form id="stats_dashboard_widget_control" action="<?php esc_url( admin_url() ); ?>" method="post"> 
  756. <?php stats_dashboard_widget_control(); ?> 
  757. <?php wp_nonce_field( 'edit-dashboard-widget_dashboard_stats', 'dashboard-widget-nonce' ); ?> 
  758. <input type="hidden" name="widget_id" value="dashboard_stats" /> 
  759. <?php submit_button( __( 'Submit', 'jetpack' ) ); ?> 
  760. </form> 
  761. <div id="dashboard_stats"> 
  762. <div class="inside"> 
  763. <div style="height: 250px;"></div> 
  764. </div> 
  765. </div> 
  766. <script> 
  767. jQuery(document).ready(function($) { 
  768. $('.js-toggle-stats_dashboard_widget_control').click(function(e) { 
  769. e.preventDefault(); 
  770. $(this).parent().toggleClass('controlVisible'); 
  771. $('#stats_dashboard_widget_control').slideToggle(); 
  772. }); 
  773. }); 
  774. </script> 
  775. <style> 
  776. .js-toggle-stats_dashboard_widget_control { 
  777. float: right; 
  778. font-weight: 400; 
  779. color: #444; 
  780. font-size: .8em; 
  781. text-decoration: underline; 
  782. cursor: pointer; 
  783. #stats_dashboard_widget_control { 
  784. display: none; 
  785. padding: 0 10px; 
  786. overflow: hidden; 
  787. #stats_dashboard_widget_control .button-primary { 
  788. float: right; 
  789. #dashboard_stats { 
  790. box-sizing: border-box; 
  791. width: 100%; 
  792. padding: 0 10px; 
  793. </style> 
  794. <?php 
  795.  
  796. function stats_register_widget_control_callback() { 
  797. $GLOBALS['wp_dashboard_control_callbacks']['dashboard_stats'] = 'stats_dashboard_widget_control'; 
  798. // Javascript and CSS for dashboard widget 
  799. function stats_dashboard_head() { ?> 
  800. <script type="text/javascript"> 
  801. /* <![CDATA[ */ 
  802. jQuery(window).load( function() { 
  803. jQuery( function($) { 
  804. resizeChart(); 
  805. jQuery(window).resize( _.debounce( function() { 
  806. resizeChart(); 
  807. }, 100) ); 
  808. } ); 
  809.  
  810. function resizeChart() { 
  811. var dashStats = jQuery( '#dashboard_stats div.inside' ); 
  812.  
  813. if ( dashStats.find( '.dashboard-widget-control-form' ).length ) { 
  814. return; 
  815.  
  816. if ( ! dashStats.length ) { 
  817. dashStats = jQuery( '#dashboard_stats div.dashboard-widget-content' ); 
  818. var h = parseInt( dashStats.parent().height() ) - parseInt( dashStats.prev().height() ); 
  819. var args = 'width=' + dashStats.width() + '&height=' + h.toString(); 
  820. } else { 
  821. if ( jQuery('#dashboard_stats' ).hasClass('postbox') ) { 
  822. var args = 'width=' + ( dashStats.prev().width() * 2 ).toString(); 
  823. } else { 
  824. var args = 'width=' + ( dashStats.width() * 2 ).toString(); 
  825.  
  826. dashStats.not( '.dashboard-widget-control' ).load( 'admin.php?page=stats&noheader&dashboard&' + args ); 
  827. } ); 
  828. /* ]]> */ 
  829. </script> 
  830. <style type="text/css"> 
  831. /* <![CDATA[ */ 
  832. #stat-chart { 
  833. background: none !important; 
  834. #dashboard_stats .inside { 
  835. margin: 10px 0 0 0 !important; 
  836. #dashboard_stats #stats-graph { 
  837. margin: 0; 
  838. #stats-info { 
  839. border-top: 1px solid #dfdfdf; 
  840. margin: 7px -10px 0 -10px; 
  841. padding: 10px; 
  842. background: #fcfcfc; 
  843. -moz-box-shadow:inset 0 1px 0 #fff; 
  844. -webkit-box-shadow:inset 0 1px 0 #fff; 
  845. box-shadow:inset 0 1px 0 #fff; 
  846. overflow: hidden; 
  847. border-radius: 0 0 2px 2px; 
  848. -webkit-border-radius: 0 0 2px 2px; 
  849. -moz-border-radius: 0 0 2px 2px; 
  850. -khtml-border-radius: 0 0 2px 2px; 
  851. #stats-info #top-posts, #stats-info #top-search { 
  852. float: left; 
  853. width: 50%; 
  854. #top-posts .stats-section-inner p { 
  855. white-space: nowrap; 
  856. overflow: hidden; 
  857. #top-posts .stats-section-inner p a { 
  858. overflow: hidden; 
  859. text-overflow: ellipsis; 
  860. #stats-info div#active { 
  861. border-top: 1px solid #dfdfdf; 
  862. margin: 0 -10px; 
  863. padding: 10px 10px 0 10px; 
  864. -moz-box-shadow:inset 0 1px 0 #fff; 
  865. -webkit-box-shadow:inset 0 1px 0 #fff; 
  866. box-shadow:inset 0 1px 0 #fff; 
  867. overflow: hidden; 
  868. #top-search p { 
  869. color: #999; 
  870. #stats-info h4 { 
  871. font-size: 1em; 
  872. margin: 0 0 .5em 0 !important; 
  873. #stats-info p { 
  874. margin: 0 0 .25em; 
  875. color: #999; 
  876. #stats-info p.widget-loading { 
  877. margin: 1em 0 0; 
  878. color: #333; 
  879. #stats-info p a { 
  880. display: block; 
  881. #stats-info p a.button { 
  882. display: inline; 
  883. /* ]]> */ 
  884. </style> 
  885. <?php 
  886.  
  887. function stats_dashboard_widget_content() { 
  888. if ( !isset( $_GET['width'] ) || ( !$width = (int) ( $_GET['width'] / 2 ) ) || $width < 250 ) 
  889. $width = 370; 
  890. if ( !isset( $_GET['height'] ) || ( !$height = (int) $_GET['height'] - 36 ) || $height < 230 ) 
  891. $height = 180; 
  892.  
  893. $_width = $width - 5; 
  894. $_height = $height - ( $GLOBALS['is_winIE'] ? 16 : 5 ); // hack! 
  895.  
  896. $options = stats_dashboard_widget_options(); 
  897. $blog_id = Jetpack_Options::get_option( 'id' ); 
  898.  
  899. $q = array( 
  900. 'noheader' => 'true',  
  901. 'proxy' => '',  
  902. 'blog' => $blog_id,  
  903. 'page' => 'stats',  
  904. 'chart' => '',  
  905. 'unit' => $options['chart'],  
  906. 'color' => get_user_option( 'admin_color' ),  
  907. 'width' => $_width,  
  908. 'height' => $_height,  
  909. 'ssl' => is_ssl(),  
  910. 'j' => sprintf( '%s:%s', JETPACK__API_VERSION, JETPACK__VERSION ),  
  911. ); 
  912.  
  913. $url = 'https://' . STATS_DASHBOARD_SERVER . "/wp-admin/index.php"; 
  914.  
  915. $url = add_query_arg( $q, $url ); 
  916. $method = 'GET'; 
  917. $timeout = 90; 
  918. $user_id = JETPACK_MASTER_USER; 
  919.  
  920. $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) ); 
  921. $get_code = wp_remote_retrieve_response_code( $get ); 
  922. if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) { 
  923. stats_print_wp_remote_error( $get, $url ); 
  924. } else { 
  925. $body = stats_convert_post_titles($get['body']); 
  926. $body = stats_convert_chart_urls($body); 
  927. $body = stats_convert_image_urls($body); 
  928. echo $body; 
  929.  
  930. $post_ids = array(); 
  931.  
  932. $csv_end_date = date( 'Y-m-d', current_time( 'timestamp' ) ); 
  933. $csv_args = array( 'top' => "&limit=8&end=$csv_end_date", 'search' => "&limit=5&end=$csv_end_date" ); 
  934. /** translators: Stats dashboard widget postviews list: "$post_title $views Views" */ 
  935. $printf = __( '%1$s %2$s Views' , 'jetpack' ); 
  936.  
  937. foreach ( $top_posts = stats_get_csv( 'postviews', "days=$options[top]$csv_args[top]" ) as $i => $post ) { 
  938. if ( $post['post_id'] == 0 ) { 
  939. unset( $top_posts[$i] ); 
  940. continue; 
  941. $post_ids[] = $post['post_id']; 
  942.  
  943. // cache 
  944. get_posts( array( 'include' => join( ', ', array_unique( $post_ids ) ) ) ); 
  945.  
  946. $searches = array(); 
  947. foreach ( $search_terms = stats_get_csv( 'searchterms', "days=$options[search]$csv_args[search]" ) as $search_term ) { 
  948. if ( $search_term['searchterm'] == 'encrypted_search_terms' ) 
  949. continue; 
  950. $searches[] = esc_html( $search_term['searchterm'] ); 
  951.  
  952. ?> 
  953. <a class="button" href="admin.php?page=stats"><?php _e( 'View All', 'jetpack' ); ?></a> 
  954. <div id="stats-info"> 
  955. <div id="top-posts" class='stats-section'> 
  956. <div class="stats-section-inner"> 
  957. <h4 class="heading"><?php _e( 'Top Posts' , 'jetpack' ); ?></h4> 
  958. <?php 
  959. if ( empty( $top_posts ) ) { 
  960. ?> 
  961. <p class="nothing"><?php _e( 'Sorry, nothing to report.', 'jetpack' ); ?></p> 
  962. <?php 
  963. } else { 
  964. foreach ( $top_posts as $post ) { 
  965. if ( !get_post( $post['post_id'] ) ) 
  966. continue; 
  967. ?> 
  968. <p><?php printf( 
  969. $printf,  
  970. '<a href="' . get_permalink( $post['post_id'] ) . '">' . get_the_title( $post['post_id'] ) . '</a>',  
  971. number_format_i18n( $post['views'] ) 
  972. ); ?></p> 
  973. <?php 
  974. ?> 
  975. </div> 
  976. </div> 
  977. <div id="top-search" class='stats-section'> 
  978. <div class="stats-section-inner"> 
  979. <h4 class="heading"><?php _e( 'Top Searches' , 'jetpack' ); ?></h4> 
  980. <?php 
  981. if ( empty( $searches ) ) { 
  982. ?> 
  983. <p class="nothing"><?php _e( 'Sorry, nothing to report.', 'jetpack' ); ?></p> 
  984. <?php 
  985. } else { 
  986. ?> 
  987. <p><?php echo join( ',   ', $searches );?></p> 
  988. <?php 
  989. ?> 
  990. </div> 
  991. </div> 
  992. </div> 
  993. <div class="clear"></div> 
  994. <?php 
  995. exit; 
  996.  
  997. function stats_print_wp_remote_error( $get, $url ) { 
  998. $state_name = 'stats_remote_error_' . substr( md5( $url ), 0, 8 ); 
  999. $previous_error = Jetpack::state( $state_name ); 
  1000. $error = md5( serialize( compact( 'get', 'url' ) ) ); 
  1001. Jetpack::state( $state_name, $error ); 
  1002. if ( $error !== $previous_error ) { 
  1003. ?> 
  1004. <div class="wrap"> 
  1005. <p><?php _e( 'We were unable to get your stats just now. Please reload this page to try again.', 'jetpack' ); ?></p> 
  1006. </div> 
  1007. <?php 
  1008. return; 
  1009. ?> 
  1010. <div class="wrap"> 
  1011. <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> 
  1012. <pre> 
  1013. User Agent: "<?php echo esc_html( $_SERVER['HTTP_USER_AGENT'] ); ?>" 
  1014. Page URL: "http<?php echo (is_ssl()?'s':'') . '://' . esc_html( $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'] ); ?>" 
  1015. API URL: "<?php echo esc_url( $url ); ?>" 
  1016. <?php 
  1017. if ( is_wp_error( $get ) ) { 
  1018. foreach ( $get->get_error_codes() as $code ) { 
  1019. foreach ( $get->get_error_messages($code) as $message ) { 
  1020. ?> 
  1021. <?php print $code . ': "' . $message . '"' ?> 
  1022.  
  1023. <?php 
  1024. } else { 
  1025. $get_code = wp_remote_retrieve_response_code( $get ); 
  1026. $content_length = strlen( wp_remote_retrieve_body( $get ) ); 
  1027. ?> 
  1028. Response code: "<?php print $get_code ?>" 
  1029. Content length: "<?php print $content_length ?>" 
  1030.  
  1031. <?php 
  1032. ?></pre> 
  1033. </div> 
  1034. <?php 
  1035.  
  1036. /** 
  1037. * Get stats from WordPress.com 
  1038. * 
  1039. * @param string $table The stats which you want to retrieve: postviews, or searchterms 
  1040. * @param array $args { 
  1041. * An associative array of arguments. 
  1042. * 
  1043. * @type bool $end The last day of the desired time frame. Format is 'Y-m-d' (e.g. 2007-05-01) 
  1044. * and default timezone is UTC date. Default value is Now. 
  1045. * @type string $days The length of the desired time frame. Default is 30. Maximum 90 days. 
  1046. * @type int $limit The maximum number of records to return. Default is 10. Maximum 100. 
  1047. * @type int $post_id The ID of the post to retrieve stats data for 
  1048. * @type string $summarize If present, summarizes all matching records. Default Null. 
  1049. * 
  1050. * } 
  1051. * 
  1052. * @return array { 
  1053. * An array of post view data, each post as an array 
  1054. * 
  1055. * array { 
  1056. * The post view data for a single post 
  1057. * 
  1058. * @type string $post_id The ID of the post 
  1059. * @type string $post_title The title of the post 
  1060. * @type string $post_permalink The permalink for the post 
  1061. * @type string $views The number of views for the post within the $num_days specified 
  1062. * } 
  1063. * } 
  1064. */ 
  1065. function stats_get_csv( $table, $args = null ) { 
  1066. $defaults = array( 'end' => false, 'days' => false, 'limit' => 3, 'post_id' => false, 'summarize' => '' ); 
  1067.  
  1068. $args = wp_parse_args( $args, $defaults ); 
  1069. $args['table'] = $table; 
  1070. $args['blog_id'] = Jetpack_Options::get_option( 'id' ); 
  1071.  
  1072. $stats_csv_url = add_query_arg( $args, 'http://stats.wordpress.com/csv.php' ); 
  1073.  
  1074. $key = md5( $stats_csv_url ); 
  1075.  
  1076. // Get cache 
  1077. $stats_cache = get_option( 'stats_cache' ); 
  1078. if ( !$stats_cache || !is_array( $stats_cache ) ) 
  1079. $stats_cache = array(); 
  1080.  
  1081. // Return or expire this key 
  1082. if ( isset( $stats_cache[$key] ) ) { 
  1083. $time = key( $stats_cache[$key] ); 
  1084. if ( time() - $time < 300 ) 
  1085. return $stats_cache[$key][$time]; 
  1086. unset( $stats_cache[$key] ); 
  1087.  
  1088. $stats_rows = array(); 
  1089. do { 
  1090. if ( !$stats = stats_get_remote_csv( $stats_csv_url ) ) 
  1091. break; 
  1092.  
  1093. $labels = array_shift( $stats ); 
  1094.  
  1095. if ( 0 === stripos( $labels[0], 'error' ) ) 
  1096. break; 
  1097.  
  1098. $stats_rows = array(); 
  1099. for ( $s = 0; isset( $stats[$s] ); $s++ ) { 
  1100. $row = array(); 
  1101. foreach ( $labels as $col => $label ) 
  1102. $row[$label] = $stats[$s][$col]; 
  1103. $stats_rows[] = $row; 
  1104. } while( 0 ); 
  1105.  
  1106. // Expire old keys 
  1107. foreach ( $stats_cache as $k => $cache ) 
  1108. if ( !is_array( $cache ) || 300 < time() - key($cache) ) 
  1109. unset( $stats_cache[$k] ); 
  1110.  
  1111. // Set cache 
  1112. $stats_cache[$key] = array( time() => $stats_rows ); 
  1113. update_option( 'stats_cache', $stats_cache ); 
  1114.  
  1115. return $stats_rows; 
  1116.  
  1117. function stats_get_remote_csv( $url ) { 
  1118. $method = 'GET'; 
  1119. $timeout = 90; 
  1120. $user_id = JETPACK_MASTER_USER; 
  1121.  
  1122. $get = Jetpack_Client::remote_request( compact( 'url', 'method', 'timeout', 'user_id' ) ); 
  1123. $get_code = wp_remote_retrieve_response_code( $get ); 
  1124. if ( is_wp_error( $get ) || ( 2 != intval( $get_code / 100 ) && 304 != $get_code ) || empty( $get['body'] ) ) { 
  1125. return array(); // @todo: return an error? 
  1126. } else { 
  1127. return stats_str_getcsv( $get['body'] ); 
  1128.  
  1129. // rather than parsing the csv and its special cases, we create a new file and do fgetcsv on it. 
  1130. function stats_str_getcsv( $csv ) { 
  1131. if ( function_exists( 'str_getcsv' ) ) { 
  1132. $lines = str_getcsv( $csv, "\n" ); 
  1133. return array_map( 'str_getcsv', $lines ); 
  1134. if ( !$temp = tmpfile() ) // tmpfile() automatically unlinks 
  1135. return false; 
  1136.  
  1137. $data = array(); 
  1138.  
  1139. fwrite( $temp, $csv, strlen( $csv ) ); 
  1140. fseek( $temp, 0 ); 
  1141. while ( false !== $row = fgetcsv( $temp, 2000 ) ) 
  1142. $data[] = $row; 
  1143. fclose( $temp ); 
  1144.  
  1145. return $data; 
  1146.  
  1147. /** 
  1148. * Abstract out building the rest api stats path. 
  1149. * 
  1150. * @param string $resource 
  1151. * @return string 
  1152. */ 
  1153. function jetpack_stats_api_path( $resource = '' ) { 
  1154. $resource = ltrim( $resource, '/' ); 
  1155. return sprintf( '/sites/%d/stats/%s', stats_get_option( 'blog_id' ), $resource ); 
  1156.  
  1157. /** 
  1158. * Fetches stats data from the REST API. Caches locally for 5 minutes. 
  1159. * 
  1160. * @link: https://developer.wordpress.com/docs/api/1.1/get/sites/%24site/stats/ 
  1161. * 
  1162. * @param array|string $args The args that are passed to the endpoint 
  1163. * @param string $resource Optional sub-endpoint following /stats/ 
  1164. * @return array|WP_Error 
  1165. */ 
  1166. function stats_get_from_restapi( $args = array(), $resource = '' ) { 
  1167. $endpoint = jetpack_stats_api_path( $resource ); 
  1168. $api_version = '1.1'; 
  1169. $args = wp_parse_args( $args, array() ); 
  1170. $cache_key = md5( implode( '|', array( $endpoint, $api_version, serialize( $args ) ) ) ); 
  1171.  
  1172. // Get cache 
  1173. $stats_cache = Jetpack_Options::get_option( 'restapi_stats_cache', array() ); 
  1174. if ( ! is_array( $stats_cache ) ) { 
  1175. $stats_cache = array(); 
  1176.  
  1177. // Return or expire this key 
  1178. if ( isset( $stats_cache[ $cache_key ] ) ) { 
  1179. $time = key( $stats_cache[ $cache_key ] ); 
  1180. if ( time() - $time < ( 5 * MINUTE_IN_SECONDS ) ) { 
  1181. $cached_stats = $stats_cache[ $cache_key ][ $time ]; 
  1182. $cached_stats = (object) array_merge( array( 'cached_at' => $time ), (array) $cached_stats ); 
  1183. return $cached_stats; 
  1184. unset( $stats_cache[ $cache_key ] ); 
  1185.  
  1186. // Do the dirty work. 
  1187. $response = Jetpack_Client::wpcom_json_api_request_as_blog( $endpoint, $api_version, $args ); 
  1188. if ( 200 !== wp_remote_retrieve_response_code( $response ) ) { 
  1189. // If bad, just return it, don't cache. 
  1190. return $response; 
  1191.  
  1192. $data = json_decode( wp_remote_retrieve_body( $response ) ); 
  1193.  
  1194. // Expire old keys 
  1195. foreach ( $stats_cache as $k => $cache ) { 
  1196. if ( ! is_array( $cache ) || ( 5 * MINUTE_IN_SECONDS ) < time() - key( $cache ) ) { 
  1197. unset( $stats_cache[ $k ] ); 
  1198.  
  1199. // Set cache 
  1200. $stats_cache[ $cache_key ] = array( 
  1201. time() => $data,  
  1202. ); 
  1203. Jetpack_Options::update_option( 'restapi_stats_cache', $stats_cache, false ); 
  1204.  
  1205. return $data; 
.