'7d' ). * @return array|WP_Error The answer, or what went wrong in words the owner can act on. */ function readercount_api( $endpoint, $args = array() ) { $key = (string) get_option( READERCOUNT_KEY_OPTION, '' ); if ( '' === $key ) { return new WP_Error( 'readercount_no_key', __( 'Add a ReaderCount API key in Settings, ReaderCount to see your stats here.', 'readercount' ) ); } $response = wp_remote_get( add_query_arg( array_map( 'rawurlencode', $args ), READERCOUNT_API . $endpoint ), array( 'timeout' => 10, 'headers' => array( 'Authorization' => 'Bearer ' . $key, 'Accept' => 'application/json', ), ) ); if ( is_wp_error( $response ) ) { return new WP_Error( 'readercount_offline', __( 'We couldn\'t reach ReaderCount just now. Try again in a minute.', 'readercount' ) ); } $status = (int) wp_remote_retrieve_response_code( $response ); $body = json_decode( wp_remote_retrieve_body( $response ), true ); if ( 200 === $status && is_array( $body ) ) { return $body; } if ( 401 === $status ) { return new WP_Error( 'readercount_key', __( 'ReaderCount doesn\'t recognise this API key. It may have been deleted. Make a new one on your stats page and add it in Settings, ReaderCount.', 'readercount' ) ); } if ( 402 === $status ) { return new WP_Error( 'readercount_plan', __( 'Your ReaderCount trial has ended. Pick a plan on ReaderCount to see your stats again. Counting carries on in the meantime.', 'readercount' ) ); } if ( 429 === $status ) { return new WP_Error( 'readercount_busy', __( 'Too many requests to ReaderCount in the last minute. Try again shortly.', 'readercount' ) ); } $message = is_array( $body ) && isset( $body['error'] ) ? (string) $body['error'] : __( 'ReaderCount didn\'t answer as expected. Try again in a minute.', 'readercount' ); return new WP_Error( 'readercount_error', $message ); } /** * The last 7 days' stats, kept for 10 minutes so the Dashboard doesn't ask ReaderCount on every visit. * * @return array|WP_Error */ function readercount_week() { $cached = get_transient( 'readercount_week' ); if ( is_array( $cached ) ) { return $cached; } $answer = readercount_api( 'overview', array( 'period' => '7d' ) ); if ( ! is_wp_error( $answer ) ) { set_transient( 'readercount_week', $answer, 10 * MINUTE_IN_SECONDS ); } return $answer; } /** * Forgets the kept stats, for when the key changes. */ function readercount_forget_stats() { delete_transient( 'readercount_week' ); }