Merge pull request #5 from jrfoell/master

V3 API
This commit is contained in:
cmanon
2014-12-10 08:41:06 -06:00
13 changed files with 372 additions and 381 deletions
+1
View File
@@ -1 +1,2 @@
*~
.svn
+2 -2
View File
@@ -8,7 +8,7 @@
background-position: -224px -160px;
margin: 0 6px 2px 0;
}
.table {
.wp-strava-ride-container {
display: table;
margin: 0 auto;
}
@@ -32,6 +32,6 @@
.ride-details-table-units {
font-size: 0.8em;
}
.map img {
.wp-strava-ride-container img {
max-width: none;
}
+24 -20
View File
@@ -4,29 +4,26 @@
*/
class WPStrava_API {
const STRAVA_V1_API = 'http://www.strava.com/api/v1/'; //rides?athleteId=134698
const STRAVA_V2_API = 'http://www.strava.com/api/v2/'; //rides/:ride_id/map_details
//deactivated
//const STRAVA_V1_API = 'http://www.strava.com/api/v1/'; //rides?athleteId=134698
//const STRAVA_V2_API = 'http://www.strava.com/api/v2/'; //rides/:ride_id/map_details
const STRAVA_V3_API = 'https://www.strava.com/api/v3/';
/*
private $rideUrl = "http://www.strava.com/api/v1/rides/:id";
private $rideUrlV2 = "http://www.strava.com/api/v2/rides/:id";
private $ridesUrl = "http://www.strava.com/api/v1/rides";
private $authenticationUrl = "https://www.strava.com/api/v1/authentication/login";
private $authenticationUrlV2 = "https://www.strava.com/api/v2/authentication/login";
private $rideMapDetailsUrl = "http://www.strava.com/api/v1/rides/:id/map_details";
private $rideMapDetailsUrlV2 = "http://www.strava.com/api/v2/rides/:id/map_details";
*/
public function __construct( $access_token ) {
$this->access_token = $access_token;
}
public function post( $uri, $data = NULL, $version = 2 ) {
$url = ( $version == 2 ) ? self::STRAVA_V2_API : self::STRAVA_V1_API;
public function post( $uri, $data = NULL ) {
$url = self::STRAVA_V3_API;
$args = array(
'body' => http_build_query( $data ),
'sslverify' => false,
'headers' => array(
'Authorization' => 'Bearer ' . $this->access_token,
)
);
if ( $version == 2 )
$args['sslverify'] = false;
$response = wp_remote_post( $url . $uri, $args );
if ( $response['response']['code'] != 200 ) {
@@ -46,26 +43,33 @@ class WPStrava_API {
return json_decode( $response['body'] );
}
public function get( $uri, $args = NULL, $version = 2 ) {
$url = ( $version == 2 ) ? self::STRAVA_V2_API : self::STRAVA_V1_API;
public function get( $uri, $args = NULL ) {
$url = self::STRAVA_V3_API;
$url .= $uri;
if ( ! empty( $args ) )
$url = add_query_arg( $args, $url );
$response = wp_remote_get( $url );
$get_args = array(
'headers' => array(
'Authorization' => 'Bearer ' . $this->access_token,
)
);
$response = wp_remote_get( $url, $get_args );
if ( is_wp_error( $response ) )
return $response;
if ( $response['response']['code'] != 200 ) {
die($url);
//see if there's useful info in the body
$body = json_decode( $response['body'] );
$error = '';
if ( ! empty( $body->error ) )
$error = $body->error;
else if ( $response['response']['code'] == 503 )
$error = __( 'Strava Temporarily Unavailable', 'wp-strava' );
else
$error = print_r( $response, true );
+25 -51
View File
@@ -17,7 +17,7 @@ class WPStrava_LatestMapWidget extends WP_Widget {
public function form( $instance ) {
// outputs the options form on admin
$distance_min = isset( $instance['distance_min'] ) ? esc_attr( $instance['distance_min'] ) : '';
$ride_index_params = isset( $instance['ride_index_params'] ) ? esc_attr( $instance['ride_index_params'] ) : '';
$strava_club_id = isset( $instance['strava_club_id'] ) ? esc_attr( $instance['strava_club_id'] ) : '';
//provide some defaults
//$ride_index_params = $ride_index_params ? $ride_index_params : 'athleteId=21';
@@ -27,35 +27,25 @@ class WPStrava_LatestMapWidget extends WP_Widget {
<label for="<?php echo $this->get_field_id( 'distance_min' ); ?>"><?php echo sprintf( __( 'Min. Distance (%s):', 'wp-strava' ), $this->som->get_distance_label() ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'distance_min' ); ?>" name="<?php echo $this->get_field_name( 'distance_min' ); ?>" type="text" value="<?php echo $distance_min; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id( 'ride_index_params' ); ?>"><?php _e( 'Ride Search Parameters (one per line): ' ); ?>
<a href="https://stravasite-main.pbworks.com/w/page/51754146/Strava%20REST%20API%20Method%3A%20rides%20index" target="_blank"><?php _e( 'help' ); ?></a></label>
<textarea name="<?php echo $this->get_field_name( 'ride_index_params' ); ?>" id="<?php echo $this->get_field_id( 'ride_index_params' ); ?>" cols="10" rows="5" class="widefat"><?php echo $ride_index_params; ?></textarea>
</p>
<p>
<label for="<?php echo $this->get_field_id('strava_club_id'); ?>"><?php _e('Club ID (leave blank to show Athlete):'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('strava_club_id'); ?>" name="<?php echo $this->get_field_name('strava_club_id'); ?>" type="text" value="<?php echo $strava_club_id; ?>" />
</p>
<?php
}
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved from the admin
$instance = $old_instance;
$instance['ride_index_params'] = strip_tags( $new_instance['ride_index_params'] );
$instance['strava_club_id'] = strip_tags( $new_instance['strava_club_id'] );
$instance['distance_min'] = strip_tags( $new_instance['distance_min'] );
/*
if ( empty( $instance['ride_index_params'] ) ) {
$instance['ride_index_params'] = "athleteId={$auth->athlete->id}";
}
*/
//$instance['athlete_hash'] = strip_tags( $new_instance['athlete_hash'] );
return $instance;
}
public function widget( $args, $instance ) {
extract( $args );
$ride_index_params = $instance['ride_index_params'];
$distance_min = $instance['distance_min'];
$strava_club_id = empty( $instance['strava_club_id'] ) ? NULL : $instance['strava_club_id'];
$build_new = false;
//try our transient first
@@ -64,12 +54,23 @@ class WPStrava_LatestMapWidget extends WP_Widget {
if ( $ride_transient )
$ride = $ride_transient;
if ( ! $ride ) {
$strava_rides = WPStrava::get_instance()->rides;
$ride_index_params = implode( '&', explode( "\n", $ride_index_params ) );
parse_str( $ride_index_params, $params );
$rides = $strava_rides->getRidesAdvanced( $params );
$rides = $strava_rides->getRides( $strava_club_id );
if ( is_wp_error( $rides ) ) {
echo $before_widget;
if ( WPSTRAVA_DEBUG ) {
echo '<pre>';
print_r($rides);
echo '</pre>';
} else {
echo $rides->get_error_message();
}
echo $after_widget;
return;
}
if ( ! empty( $rides ) ) {
@@ -92,47 +93,20 @@ class WPStrava_LatestMapWidget extends WP_Widget {
if ( $ride ):
echo $before_widget;
?><h3 class="widget-title">Latest Ride</h3>
<a title="<?php echo $ride->ride->name ?>" href="http://app.strava.com/activities/<?php echo $ride->id ?>"><?php
<a title="<?php echo $ride->name ?>" href="http://app.strava.com/activities/<?php echo $ride->id ?>"><?php
echo $this->getStaticImage( $ride->id, $build_new );
?></a><?php
echo $after_widget;
endif;
}
private function buildImage( $map_details ) {
$url = 'http://maps.google.com/maps/api/staticmap?maptype=terrain&size=390x260&sensor=false&path=color:0xFF0000BF|weight:2|';
$url_len = strlen( $url );
$point_len = 0;
$num = 50;
$count = count( $map_details->latlng );
$full_url = '';
$max_chars = 1865;
//get the longest usable URL
while ( $url_len + $point_len < $max_chars ) {
$mod = (int) ( $count / $num );
$points = array();
for ( $i = 0; $i < $count; $i += $mod ) {
$point = $map_details->latlng[$i];
$points[] = number_format( $point[0], 4 ) . ',' . number_format( $point[1], 4 );
}
$url_points = join( '|', $points );
$point_len = strlen( $url_points );
if ( $url_len + $point_len < $max_chars )
$full_url = $url . $url_points;
$num++;
}
return "<img src='{$full_url}' />";
}
private function getStaticImage( $ride_id, $build_new ) {
$img = get_option( 'strava_latest_map' );
if ( $build_new || ! $img ) {
$map_details = WPStrava::get_instance()->rides->getMapDetails( $ride_id );
$img = $this->buildImage( $map_details );
$ride = WPStrava::get_instance()->rides->getRide( $ride_id );
$img = WPStrava_StaticMap::get_image_tag( $ride );
update_option( 'strava_latest_map', $img );
}
+31 -52
View File
@@ -6,73 +6,64 @@
class WPStrava_LatestRidesWidget extends WP_Widget {
public function __construct() {
$widget_ops = array('classname' => 'LatestRidesWidget', 'description' => __( 'Will publish your latest rides activity from strava.com.') );
parent::__construct('wp-strava', $name = 'Strava Latest Rides', $widget_ops);
wp_enqueue_style('wp-strava'); //TODO only load this when wigit is loaded
$widget_ops = array( 'classname' => 'LatestRidesWidget', 'description' => __( 'Will publish your latest rides activity from strava.com.' ) );
parent::__construct( 'wp-strava', $name = 'Strava Latest Rides', $widget_ops );
add_action( 'wp_enqueue_scripts', array( $this, 'maybe_enqueue' ) );
}
public function maybe_enqueue() {
if ( is_active_widget( false, false, $this->id_base ) ) {
wp_enqueue_style( 'wp-strava-style' ); //only load this when wigit is loaded
}
}
/** @see WP_Widget::widget */
public function widget( $args, $instance ) {
extract($args);
extract( $args );
//$widget_id = $args['widget_id'];
$title = apply_filters('widget_title', empty($instance['title']) ? _e('Rides', 'wp-strava') : $instance['title']);
$strava_search_option = empty($instance['strava_search_option']) ? 'athlete' : $instance['strava_search_option'];
$strava_search_id = empty($instance['strava_search_id']) ? '' : $instance['strava_search_id'];
$quantity = empty($instance['quantity']) ? '5' : $instance['quantity'];
$title = apply_filters( 'widget_title', empty( $instance['title'] ) ? __( 'Rides', 'wp-strava' ) : $instance['title'] );
$strava_club_id = empty( $instance['strava_club_id'] ) ? '' : $instance['strava_club_id'];
$quantity = empty( $instance['quantity'] ) ? '5' : $instance['quantity'];
$this->som = WPStrava_SOM::get_som();
?>
<?php echo $before_widget; ?>
<?php if ( $title ) echo $before_title . $title . $after_title; ?>
<?php echo $this->strava_request_handler($strava_search_option, $strava_search_id, $strava_som_option, $quantity); ?>
<?php echo $this->strava_request_handler( $strava_club_id, $strava_som_option, $quantity ); ?>
<?php echo $after_widget; ?>
<?php
}
/** @see WP_Widget::update */
public function update($new_instance, $old_instance) {
public function update( $new_instance, $old_instance ) {
$instance = $old_instance;
$instance['title'] = strip_tags($new_instance['title']);
if(in_array($new_instance['strava_search_option'], array('athlete', 'club'))) {
$instance['strava_search_option'] = $new_instance['strava_search_option'];
} else {
$instance['strava_search_option'] = 'athlete';
}
if(in_array($new_instance['strava_som_option'], array('metric', 'english'))) {
$instance['title'] = strip_tags( $new_instance['title'] );
if( in_array( $new_instance['strava_som_option'], array( 'metric', 'english' ) ) ) {
$instance['strava_som_option'] = $new_instance['strava_som_option'];
} else {
$instance['strava_som_option'] = 'metric';
}
$instance['strava_search_id'] = strip_tags($new_instance['strava_search_id']);
$instance['strava_club_id'] = strip_tags( $new_instance['strava_club_id'] );
$instance['quantity'] = $new_instance['quantity'];
return $instance;
}
/** @see WP_Widget::form */
public function form($instance) {
$title = isset($instance['title']) ? esc_attr($instance['title']) : _e('Rides', 'wp-strava');
$strava_search_option = isset($instance['strava_search_option']) ? esc_attr($instance['strava_search_option']) : "athlete";
$strava_search_id = isset($instance['strava_search_id']) ? esc_attr($instance['strava_search_id']) : "";
$quantity = isset($instance['quantity']) ? absint($instance['quantity']) : 5;
public function form( $instance ) {
$title = isset( $instance['title'] ) ? esc_attr( $instance['title'] ) : __( 'Rides', 'wp-strava' );
$strava_club_id = isset( $instance['strava_club_id'] ) ? esc_attr( $instance['strava_club_id'] ) : '';
$quantity = isset( $instance['quantity'] ) ? absint( $instance['quantity'] ) : 5;
?>
<p>
<label for="<?php echo $this->get_field_id('title'); ?>"><?php _e('Title:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<!-- TODO: make an 'advanced' option -->
<p>
<label for="<?php echo $this->get_field_id('strava_search_option'); ?>"><?php _e('Search Option:'); ?></label>
<select class="widefat" id="<?php echo $this->get_field_id('strava_search_option'); ?>" name="<?php echo $this->get_field_name('strava_search_option'); ?>">
<option value="athlete" <?php selected($strava_search_option, 'athlete'); ?>><?php _e("Athlete", "wp-strava")?></option>
<option value="club" <?php selected($strava_search_option, 'club'); ?>><?php _e("Club", "wp-strava")?></option>
</select>
<label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e( 'Title:' ); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id( 'title' ); ?>" name="<?php echo $this->get_field_name( 'title' ); ?>" type="text" value="<?php echo $title; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('strava_search_id'); ?>"><?php _e('Search Id:'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('strava_search_id'); ?>" name="<?php echo $this->get_field_name('strava_search_id'); ?>" type="text" value="<?php echo $strava_search_id; ?>" />
<label for="<?php echo $this->get_field_id('strava_club_id'); ?>"><?php _e('Club ID (leave blank to show Athlete):'); ?></label>
<input class="widefat" id="<?php echo $this->get_field_id('strava_club_id'); ?>" name="<?php echo $this->get_field_name('strava_club_id'); ?>" type="text" value="<?php echo $strava_club_id; ?>" />
</p>
<p>
<label for="<?php echo $this->get_field_id('quantity'); ?>"><?php _e('Quantity:'); ?></label>
@@ -83,41 +74,29 @@ class WPStrava_LatestRidesWidget extends WP_Widget {
// The handler to the ajax call, we will avoid this if Strava support jsonp request and we can do it
// the parsing directly on the jQuery ajax call, the returned text will be enclosed in the $response variable.
private function strava_request_handler( $strava_search_option, $strava_search_id, $strava_som_option, $quantity ) {
private function strava_request_handler( $strava_club_id, $strava_som_option, $quantity ) {
//Check if the username is empty.
if ( empty( $strava_search_id ) )
return __("Please configure the Strava search id on the widget options.", "wp-strava");
//else
$strava_rides = WPStrava::get_instance()->rides;
$rides = $strava_rides->getRidesSimple( $strava_search_option, $strava_search_id );
$rides = $strava_rides->getRides( $strava_club_id, $quantity );
if ( is_wp_error( $rides ) )
return $rides->get_error_message();
//adjust quantity
$rides = array_slice( $rides, 0, $quantity );
$rides_details = $strava_rides->getRidesDetails( $rides );
if ( is_wp_error( $rides_details ) )
return $rides_details->get_error_message();
$response = "<ul id='rides'>";
foreach($rides_details as $ride_obj) {
$ride = $ride_obj->ride;
foreach( $rides as $ride ) {
$response .= "<li class='ride'>";
$response .= "<a href='" . WPStrava_Rides::RIDES_URL . $ride->id . "' >" . $ride->name . "</a>";
$response .= "<div class='ride-item'>";
$unixtime = strtotime( $ride->start_date_local );
$response .= sprintf( __("On %s %s", "wp-strava"), date_i18n( get_option( 'date_format' ), $unixtime ), date_i18n( get_option( 'time_format' ), $unixtime ) );
if ($strava_search_option == "club") {
if ( is_numeric( $strava_club_id ) ) {
$response .= " <a href='" . WPStrava_Rides::ATHLETES_URL . $ride->athlete_id . "'>" . $ride->athlete_name . "</a>";
}
$response .= sprintf( __(" rode %s %s", "wp-strava"), $this->som->distance( $ride->distance ), $this->som->get_distance_label() );
$response .= sprintf( __( " during %s %s", "wp-strava" ), $this->som->time( $ride->elapsed_time ), $this->som->get_time_label() );
$response .= sprintf( __( " climbing %s %s", "wp-strava" ), $this->som->elevation( $ride->elevation_gain ), $this->som->get_elevation_label() );
$response .= sprintf( __( " climbing %s %s", "wp-strava" ), $this->som->elevation( $ride->total_elevation_gain ), $this->som->get_elevation_label() );
$response .= "</div>";
$response .= "</li>";
}
+56 -98
View File
@@ -5,122 +5,80 @@ class WPStrava_RideShortcode {
static function init() {
add_shortcode('ride', array(__CLASS__, 'handler'));
add_action('init', array(__CLASS__, 'registerScripts'));
add_action('wp_footer', array(__CLASS__, 'printScripts'));
}
// Shortcode handler function
// [ride id=id som=metric efforts=false threshold=5 map-width="100%" map-height="400px"] tag
// [ride id=id som=metric map_width="100%" map_height="400px"]
function handler($atts) {
self::$add_script = true;
$token = get_option('strava_token');
$defaults = array(
'id' => 0,
'som' => WPStrava::get_instance()->settings->som,
'map_width' => '480',
'map_height' => '320',
);
extract(shortcode_atts($defaults, $atts));
if($token) {
$pairs = array(
'id' => 0,
'som' => "metric",
'efforts' => false,
'threshold' => 0,
'map_width' => "100%",
'map_height' => "400px"
);
extract(shortcode_atts($pairs, $atts));
$strava_som = WPStrava_SOM::get_som( $som );
$strava_ride = WPStrava::get_instance()->rides;
$rideDetails = $strava_ride->getRide( $id );
if (isset($som)) {
$strava_som = $som;
} else {
$strava_som = get_option('strava_som_option', 'metric');
}
$ride = new Rides();
$rideDetails = $ride->getRideDetails($id, $strava_som);
$rideCoordinates = $ride->getRideMap($id, $token, $efforts, $threshold);
if ($strava_som == "metric") {
$units = array(
'elapsedTime' => __('hours','wp-strava'),
'movingTime' => __('hours','wp-strava'),
'distance' => __('km','wp-strava'),
'averageSpeed' => __('km/h','wp-strava'),
//'maximumSpeed' => __('km/h','wp-strava'),
'elevationGain' => __('meters','wp-strava')
);
} elseif ($strava_som == "english") {
$units = array(
'elapsedTime' => __('hours','wp-strava'),
'movingTime' => __('hours','wp-strava'),
'distance' => __('miles','wp-strava'),
'averageSpeed' => __('miles/h','wp-strava'),
//'maximumSpeed' => __('miles/h','wp-strava'),
'elevationGain' => __('feet','wp-strava')
);
}
if($rideCoordinates) {
return "
<div id='ride-header-{$id}' class='table'>
<table id='ride-details-table'>
<thead>
<tr>
<th>Elapsed Time</th>
<th>Moving Time</th>
<th>Distance</th>
<th>Average Speed</th>
<th>Elevation Gain</th>
</tr>
</thead>
<tbody>
<tr class='ride-details-table-info'>
<td>{$rideDetails['elapsedTime']}</td>
<td>{$rideDetails['movingTime']}</td>
<td>{$rideDetails['distance']}</td>
<td>{$rideDetails['averageSpeed']}</td>
<td>{$rideDetails['elevationGain']}</td>
</tr>
<tr class='ride-details-table-units'>
<td>{$units['elapsedTime']}</td>
<td>{$units['movingTime']}</td>
<td>{$units['distance']}</td>
<td>{$units['averageSpeed']}</td>
<td>{$units['elevationGain']}</td>
</tr>
</tbody>
</table>
</div>
<div id='{$id}' class='map' style='width: {$map_width}; height: {$map_height}; border: 1px solid lightgrey;'></div>
<script type='text/javascript'>
if (window.coordinates === undefined) {
window.coordinates = [];
}
window.coordinates[{$id}] = eval({$rideCoordinates});
</script>
";
}
} else {
return _e('Please first get your strava token using the settings wp strava page.', 'wp-strava');
//sanitize width & height
$map_width = str_replace( '%', '', $map_width );
$map_height = str_replace( '%', '', $map_height );
$map_width = str_replace( 'px', '', $map_width );
$map_height = str_replace( 'px', '', $map_height );
if( $rideDetails ) {
return '
<div id="ride-header-' . $id . '" class="wp-strava-ride-container">
<table id="ride-details-table">
<thead>
<tr>
<th>' . __( 'Elapsed Time', 'wp-strava' ) . '</th>
<th>' . __( 'Moving Time', 'wp-strava' ) . '</th>
<th>' . __( 'Distance', 'wp-strava' ) . '</th>
<th>' . __( 'Average Speed', 'wp-strava' ) . '</th>
<th>' . __( 'Max Speed', 'wp-strava' ) . '</th>
<th>' . __( 'Elevation Gain', 'wp-strava' ) . '</th>
</tr>
</thead>
<tbody>
<tr class="ride-details-table-info">
<td>' . $strava_som->time( $rideDetails->elapsed_time ) . '</td>
<td>' . $strava_som->time( $rideDetails->moving_time ) . '</td>
<td>' . $strava_som->distance( $rideDetails->distance ) . '</td>
<td>' . $strava_som->speed( $rideDetails->average_speed ) . '</td>
<td>' . $strava_som->speed( $rideDetails->max_speed ) . '</td>
<td>' . $strava_som->elevation( $rideDetails->total_elevation_gain ) . '</td>
</tr>
<tr class="ride-details-table-units">
<td>' . $strava_som->get_time_label() . '</td>
<td>' . $strava_som->get_time_label() . '</td>
<td>' . $strava_som->get_distance_label() . '</td>
<td>' . $strava_som->get_speed_label() . '</td>
<td>' . $strava_som->get_speed_label() . '</td>
<td>' . $strava_som->get_elevation_label() . '</td>
</tr>
</tbody>
</table>' .
WPStrava_StaticMap::get_image_tag( $rideDetails, $map_height, $map_width ) .
'</div>';
}
} // handler
static function registerScripts() {
wp_register_style('wp-strava-style', plugins_url('css/wp-strava.css', __FILE__));
wp_register_script('wp-strava-script', plugins_url('js/wp-strava.js', __FILE__), array('jquery'), '1.0', true);
wp_register_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false');
}
static function printScripts() {
if (self::$add_script) {
wp_enqueue_style('wp-strava-style');
wp_enqueue_script('jquery');
wp_print_scripts('google-maps');
wp_print_scripts('wp-strava-script');
//wp_print_scripts('google-maps');
//wp_print_scripts('wp-strava-script');
}
}
}
// Initialize short code
RideShortcode::init();
WPStrava_RideShortcode::init();
+14 -68
View File
@@ -7,101 +7,47 @@ class WPStrava_Rides {
const RIDES_URL = "http://app.strava.com/rides/";
const ATHLETES_URL = "http://app.strava.com/athletes/";
public function getRideDetails( $rideId ) {
return WPStrava::get_instance()->api->get( "rides/{$rideId}" );
public function getRide( $rideId ) {
return WPStrava::get_instance()->api->get( "activities/{$rideId}" );
} // getRideDetails
public function getRidesDetails( $rides ) {
$rides_details = array();
foreach ( $rides as $stravaRide ) {
$detail = $this->getRideDetails( $stravaRide->id );
if ( is_wp_error( $detail ) )
return $detail;
$rides_details[] = $detail;
}
return $rides_details;
} // getRidesDetails
public function getRidesSimple( $searchOption, $searchId ) {
public function getRides( $club_id = NULL, $quantity = NULL ) {
$api = WPStrava::get_instance()->api;
$data = NULL;
$args = $quantity ? array( 'per_page' => $quantity ) : NULL;
//Get the json results using the constructor specified values.
if ( $searchOption == 'athlete' ) {
if ( is_numeric( $searchId ) ) {
$data = $api->get( 'rides', array( 'athleteId' => $searchId ), 1 );
} else {
$data = $api->get( 'rides', array( 'athleteName' => $searchId ), 1 );
}
} elseif ($searchOption == 'club' && is_numeric($searchId)) {
$data = $api->get( 'rides', array( 'clubId' => $searchId ), 1 );
if ( is_numeric( $club_id ) ) {
$data = $api->get( "clubs/{$club_id}/activities", $args );
} else {
return new WP_Error( 'wp-strava_options', __("There's an error in your simple options.", 'wp-strava') );
$data = $api->get( 'athlete/activities', $args );
}
if ( is_wp_error( $data ) )
return $data;
if ( isset( $data->rides ) )
return $data->rides;
return array();
} // getRidesSimple
public function getRidesAdvanced( $params ) {
$data = WPStrava::get_instance()->api->get( 'rides', $params, 1 ); //version 1
if ( is_wp_error( $data ) )
if ( is_array( $data ) )
return $data;
if ( isset( $data->rides ) )
return $data->rides;
return array();
}
public function getRideMap($rideId, $token, $efforts, $threshold) {
if($rideId != 0 AND $token != "") {
$url = preg_replace('/:id/', $rideId, $this->rideMapDetailsUrlV2);
$json = file_get_contents($url . '?token=' . $token . '&threshold=' . $threshold);
if($json) {
//$map_details = json_decode($json);
//return $map_details;
return $json;
} else {
$this->feedback .= _e("There was an error pulling data of strava.com.", "wp-strava");
return false;
}
} else {
$this->feedback .= _e("You need to provide both parameters to complete the call.", "wp-strava");
return false;
}
} // getRideDetails
} // getRides
public function getRidesLongerThan( $rides, $dist ) {
$som = WPStrava_SOM::get_som();
$meters = $som->distance_inverse( $dist );
$long_rides = array();
foreach ( $rides as $ride ) {
$ride_info = $this->getRideDetails( $ride->id );
if ( $ride_info->ride->distance > $meters ) {
foreach ( $rides as $ride_info ) {
if ( $ride_info->distance > $meters ) {
$long_rides[] = $ride_info;
}
}
return $long_rides;
}
public function getMapDetails( $ride_id ) {
$token = WPStrava::get_instance()->settings->token;
return WPStrava::get_instance()->api->get( "rides/{$ride_id}/map_details", array( 'token' => $token ) );
}
} // class Rides
?>
+4 -4
View File
@@ -4,12 +4,12 @@ abstract class WPStrava_SOM {
public static function get_som( $som = NULL ) {
$som = $som ? $som : WPStrava::get_instance()->settings->som;
if ( $som == 'metric' ) {
require_once WPSTRAVA_PLUGIN_DIR . 'lib/SOMMetric.class.php';
return new WPStrava_SOMMetric();
} else {
if ( $som == 'english' ) {
require_once WPSTRAVA_PLUGIN_DIR . 'lib/SOMEnglish.class.php';
return new WPStrava_SOMEnglish();
} else { //default to metric
require_once WPSTRAVA_PLUGIN_DIR . 'lib/SOMMetric.class.php';
return new WPStrava_SOMMetric();
}
}
+147 -55
View File
@@ -1,35 +1,105 @@
<?php
/**
* v3 - http://strava.github.io/api/v3/oauth/
*
* Set up an "API Application" at Strava
* Save the Client ID and Client Secret in WordPress - redirect to strava oauth/authorize URL for permission
* Get redirected back to this settings page with ?code= or ?error=
* Use code to retrieve auth token
*/
class WPStrava_Settings {
private $feedback;
private $token;
private $page_name = 'wp-strava-options';
private $option_page = 'wp-strava-settings-group';
//register admin menus
public function hook() {
add_action( 'admin_init', array( $this, 'register_strava_settings' ) );
add_action( 'admin_menu', array( $this, 'add_strava_menu' ) );
add_filter( 'pre_set_transient_settings_errors', array( $this, 'maybe_oauth' ), 10 );
add_filter( 'plugin_action_links_' . WPSTRAVA_PLUGIN_NAME, array( $this, 'settings_link' ) );
//for process debugging
//add_action( 'all', array( $this, 'hook_debug' ) );
//add_filter( 'all', array( $this, 'hook_debug' ) );
}
public function hook_debug( $name ) {
echo "<!-- {$name} -->\n";
}
/**
* This runs after options are saved
*/
public function maybe_oauth( $value ) {
//redirect only if all the right options are in place
if ( isset( $value[0]['type'] ) && $value[0]['type'] == 'updated' ) { //make sure there were no settings errors
if ( isset( $_POST['option_page'] ) && $_POST['option_page'] == $this->option_page ) { //make sure we're on our settings page
//user is clearing to start-over, don't oauth
if ( isset( $_POST['strava_token'] ) && empty( $_POST['strava_token'] ) )
return;
$client_id = get_option( 'strava_client_id' );
$client_secret = get_option( 'strava_client_secret' );
if ( $client_id && $client_secret ) {
$redirect = admin_url( "options-general.php?page={$this->page_name}" );
$url = "https://www.strava.com/oauth/authorize?client_id={$client_id}&response_type=code&redirect_uri={$redirect}&approval_prompt=force";
wp_redirect( $url );
exit();
}
}
}
return $value;
}
public function add_strava_menu() {
add_options_page( __( 'Strava Settings', 'wp-strava' ),
__( 'Strava', 'wp-strava' ),
'manage_options',
'wp-strava-options',
$this->page_name,
array( $this, 'print_strava_options' ) );
}
public function init() {
//only update when redirected back from strava
if ( ! isset( $_GET['settings-updated'] ) && isset( $_GET['page'] ) && $_GET['page'] == $this->page_name ) {
if ( isset( $_GET['code'] ) ) {
$token = $this->get_token( $_GET['code'] );
if ( $token ) {
add_settings_error( 'strava_token', 'strava_token', sprintf( __( 'New Strava token retrieved. %s', 'wp-strava' ), $this->feedback ) , 'updated' );
update_option( 'strava_token', $token );
} else {
add_settings_error( 'strava_token', 'strava_token', $this->feedback );
}
} else if ( isset( $_GET['error'] ) ) {
add_settings_error( 'strava_token', 'strava_token', sprintf( __( 'Error authenticating at Strava: %s', 'wp-strava' ), str_replace( '_', ' ', $_GET['error'] ) ) );
}
}
$this->token = get_option( 'strava_token' );
}
public function register_strava_settings() {
register_setting('wp-strava-settings-group','strava_email', array( $this, 'sanitize_email' ) );
register_setting('wp-strava-settings-group','strava_password', NULL );
register_setting('wp-strava-settings-group','strava_token', array( $this, 'sanitize_token' ) );
$this->init();
add_settings_section( 'strava_api', __( 'Strava API', 'wp-strava' ), array( $this, 'print_api_instructions' ), 'wp-strava' ); //NULL / NULL no section label needed
add_settings_field( 'strava_email', __( 'Strava Email', 'wp-strava' ), array( $this, 'print_email_input' ), 'wp-strava', 'strava_api' );
add_settings_field( 'strava_password', __( 'Strava Password', 'wp-strava' ), array( $this, 'print_password_input' ), 'wp-strava', 'strava_api' );
add_settings_field( 'strava_token', __( 'Strava Token', 'wp-strava' ), array( $this, 'print_token_input' ), 'wp-strava', 'strava_api' );
if ( ! $this->token ) {
register_setting( $this->option_page, 'strava_client_id', array( $this, 'sanitize_client_id' ) );
register_setting( $this->option_page, 'strava_client_secret', array( $this, 'sanitize_client_secret' ) );
register_setting('wp-strava-settings-group','strava_som', array( $this, 'sanitize_som' ) );
add_settings_field( 'strava_client_id', __( 'Strava Client ID', 'wp-strava' ), array( $this, 'print_client_input' ), 'wp-strava', 'strava_api' );
add_settings_field( 'strava_client_secret', __( 'Strava Client Secret', 'wp-strava' ), array( $this, 'print_secret_input' ), 'wp-strava', 'strava_api' );
} else {
register_setting( $this->option_page, 'strava_token', array( $this, 'sanitize_token' ) );
add_settings_field( 'strava_token', __( 'Strava Token', 'wp-strava' ), array( $this, 'print_token_input' ), 'wp-strava', 'strava_api' );
}
register_setting( $this->option_page, 'strava_som', array( $this, 'sanitize_som' ) );
add_settings_section( 'strava_options', __( 'Options', 'wp-strava' ), NULL, 'wp-strava' );
@@ -37,7 +107,26 @@ class WPStrava_Settings {
}
public function print_api_instructions() {
?><p><?php _e( 'Please specify the options below in order to obtain an authentication token, this will work with the Strava shortcodes supported by this plugin, the widget options are independant.', 'wp-strava');?> </p><?php
$signup_url = 'http://www.strava.com/developers';
$settings_url = 'https://www.strava.com/settings/api';
$blog_name = get_bloginfo( 'name' );
$app_name = $blog_name . ' Strava';
$url_parts = parse_url( site_url() );
$site_url = $url_parts['host']; //strip http/https for copying/pasting into strava
$description = 'WP-Strava for ' . $blog_name;
printf( __( "<p>Steps:</p>
<ol>
<li>Create your API Application here: <a href='%s' target='_blank'>%s</a> using the following information:</li>
<ul>
<li>Application Name: <strong>%s</strong></li>
<li>Website: <strong>%s</strong></li>
<li>Application Description: <strong>%s</strong></li>
<li>Authorization Callback Domain: <strong>%s</strong></li>
</ul>
<li>Once you've created your API Application at strava.com, enter the Client ID and Client Secret below, which can be found at <a href='%s' target='_blank'>%s</a></li>
<li>After saving your Client ID and Secret, you'll be redirected to strava to authorize your API Application. If successful, your Strava Token will display instead of Client ID and Client Secret.</li>
<li>If you need to re-authorize your API Application, erase your Strava Token here and click 'Save Changes' to start over.</li>
</ol>", 'wp-strava' ), $signup_url, $signup_url, $app_name, $site_url, $description, $site_url, $settings_url, $settings_url );
}
public function print_strava_options() {
@@ -47,7 +136,7 @@ class WPStrava_Settings {
<h2><?php _e( 'Strava Settings', 'wp-strava' ); ?></h2>
<form method="post" action="<?php echo admin_url( 'options.php' ); ?>">
<?php settings_fields( 'wp-strava-settings-group' ); ?>
<?php settings_fields( $this->option_page ); ?>
<?php do_settings_sections( 'wp-strava' ); ?>
<p class="submit">
@@ -57,74 +146,70 @@ class WPStrava_Settings {
</div>
<?php
}
public function print_email_input() {
?><input type="text" id="strava_email" name="strava_email" value="<?php echo get_option('strava_email'); ?>" /><?php
public function print_client_input() {
?><input type="text" id="strava_client_id" name="strava_client_id" value="<?php echo get_option('strava_client_id'); ?>" /><?php
}
public function print_password_input() {
?>
<input type="password" id="strava_password" name="strava_password" value="" />
<p class="description"><?php _e( 'Your Password WILL NOT be saved. Only enter your password if you wish to retrieve a new API Token', 'wp-strava' ); ?></p>
<?php
public function print_secret_input() {
?><input type="text" id="strava_client_secret" name="strava_client_secret" value="<?php echo get_option('strava_client_secret'); ?>" /><?php
}
public function print_token_input() {
?><input type="text" id="strava_token" name="strava_token" value="<?php echo get_option('strava_token'); ?>" /><?php
}
public function sanitize_email( $email ) {
if ( is_email( $email ) )
return $email;
add_settings_error( 'strava_email', 'strava_email', 'Invalid Email' );
return NULL;
public function sanitize_client_id( $client_id ) {
if ( ! is_numeric( $client_id ) ) {
add_settings_error( 'strava_client_id', 'strava_client_id', __( 'Client ID must be a number.', 'wp-strava' ) );
}
return $client_id;
}
public function sanitize_client_secret( $client_secret ) {
if ( trim( $client_secret ) == '' ) {
add_settings_error( 'strava_client_secret', 'strava_client_secret', __( 'Client Secret is required.', 'wp-strava' ) );
}
return $client_secret;
}
public function sanitize_token( $token ) {
if ( ! empty( $_POST['strava_password'] ) ) {
$token = $this->get_authentication_token( $this->email, $_POST['strava_password'] );
if ( $token ) {
add_settings_error( 'strava_token', 'strava_token', sprintf( __( 'New Strava Token Retrieved: %s', 'wp-strava' ), $this->feedback ) , 'updated' );
return $token;
} else {
add_settings_error( 'strava_token', 'strava_token', $this->feedback );
return NULL;
}
}
return $token;
}
private function get_authentication_token( $email, $password ) {
$data = array( 'email' => $email, 'password' => $password );
$strava_login = WPStrava::get_instance()->api->post( 'authentication/login', $data );
private function get_token( $code ) {
$client_id = get_option( 'strava_client_id' );
$client_secret = get_option( 'strava_client_secret' );
if( $strava_login ) {
if( ! isset( $strava_login->error ) ) {
$this->feedback .= __( 'Successfully authenticated.', 'wp-strava' );
return $strava_login->token;
if ( $client_id && $client_secret ) {
$data = array( 'client_id' => $client_id, 'client_secret' => $client_secret, 'code' => $code );
$strava_info = WPStrava::get_instance()->api->post( 'oauth/token', $data );
if( $strava_info ) {
if( isset( $strava_info->access_token ) ) {
$this->feedback .= __( 'Successfully authenticated.', 'wp-strava' );
return $strava_info->access_token;
} else {
$this->feedback .= __( 'Authentication failed, please check your credentials.', 'wp-strava' );
return false;
}
} else {
$this->feedback .= __( 'Authentication failed, please check your credentials.', 'wp-strava' );
$this->feedback .= __( sprintf( 'There was an error receiving data from Strava: %s', print_r( $strava_info, true ) ), 'wp-strava' );
return false;
}
} else {
$this->feedback .= __( 'There was an error pulling data of strava.com.', 'wp-strava' );
$this->feedback .= __( 'Missing Client ID or Client Secret.', 'wp-strava' );
return false;
}
} // get_authentication_token
public function print_options_label() {
?><p>Options</p><?php
}
}
public function print_som_input() {
$strava_som = get_option( 'strava_som' );
?>
<select id="strava_som" name="strava_som">
<option value="metric" <?php selected( $strava_som, 'metric' ); ?>><?php _e( 'Metric', 'wp-strava' )?></option>
<option value="english" <?php selected( $strava_som, 'english' ); ?>><?php _e( 'English', 'wp-strava' )?></option>
</select>
<select id="strava_som" name="strava_som">
<option value="metric" <?php selected( $strava_som, 'metric' ); ?>><?php _e( 'Metric', 'wp-strava' )?></option>
<option value="english" <?php selected( $strava_som, 'english' ); ?>><?php _e( 'English', 'wp-strava' )?></option>
</select>
<?php
}
@@ -135,4 +220,11 @@ class WPStrava_Settings {
public function __get( $name ) {
return get_option( "strava_{$name}" );
}
public function settings_link( $links ) {
$settings_link = '<a href="' . admin_url( "options-general.php?page={$this->page_name}" ) . '">' . __( 'Settings' ) . '</a>';
$links[] = $settings_link;
return $links;
}
}
+18
View File
@@ -0,0 +1,18 @@
<?php
class WPStrava_StaticMap {
public static function get_image_tag( $ride, $height = 320, $width = 480 ) {
$url = "http://maps.google.com/maps/api/staticmap?maptype=terrain&size={$width}x{$height}&sensor=false&path=color:0xFF0000BF|weight:2|enc:";
$url_len = strlen( $url );
$max_chars = 1865;
if ( $url_len + strlen( $ride->map->polyline ) < $max_chars )
$url .= $ride->map->polyline;
else
$url .= $ride->map->summary_polyline;
return "<img src='{$url}' />";
}
}
+19 -9
View File
@@ -4,6 +4,8 @@ require_once WPSTRAVA_PLUGIN_DIR . 'lib/Settings.class.php';
require_once WPSTRAVA_PLUGIN_DIR . 'lib/SOM.class.php';
require_once WPSTRAVA_PLUGIN_DIR . 'lib/LatestRidesWidget.class.php';
require_once WPSTRAVA_PLUGIN_DIR . 'lib/LatestMapWidget.class.php';
require_once WPSTRAVA_PLUGIN_DIR . 'lib/RideShortcode.class.php';
require_once WPSTRAVA_PLUGIN_DIR . 'lib/StaticMap.class.php';
class WPStrava {
@@ -17,24 +19,24 @@ class WPStrava {
if ( is_admin() ) {
$this->settings->hook();
} else {
add_action( 'wp_enqueue_scripts', array( $this, 'register_scripts' ) );
}
// Register StravaLatestRidesWidget widget
add_action( 'widgets_init', function() { return register_widget( 'WPStrava_LatestRidesWidget' ); } );
add_action( 'widgets_init', function() { return register_widget( 'WPStrava_LatestMapWidget' ); } );
add_action( 'widgets_init', create_function('', 'return register_widget( "WPStrava_LatestRidesWidget" );') );
add_action( 'widgets_init', create_function('', 'return register_widget( "WPStrava_LatestMapWidget" );' ) );
}
public static function get_instance() {
if ( ! self::$instance )
self::$instance = new WPStrava();
if ( ! self::$instance ) {
$class = __CLASS__;
self::$instance = new $class();
}
return self::$instance;
}
public function __get( $name ) {
if ( isset( $this->{$name} ) )
return $this->{$name};
//on-demand classes
if ( $name == 'api' )
return $this->get_api();
@@ -42,13 +44,16 @@ class WPStrava {
if ( $name == 'rides' )
return $this->get_rides();
if ( isset( $this->{$name} ) )
return $this->{$name};
return NULL;
}
public function get_api() {
if ( ! $this->api ) {
require_once WPSTRAVA_PLUGIN_DIR . 'lib/API.class.php';
$this->api = new WPStrava_API();
$this->api = new WPStrava_API( get_option('strava_token') );
}
return $this->api;
@@ -62,4 +67,9 @@ class WPStrava {
return $this->rides;
}
public function register_scripts() {
// Register a personalized stylesheet
wp_register_style( 'wp-strava-style', WPSTRAVA_PLUGIN_URL . 'css/wp-strava.css' );
}
}
+28 -6
View File
@@ -1,20 +1,42 @@
=== Plugin Name ===
Contributors: cmanon, jrfoell
Donate link: http://cmanon.com/
Tags: bicycle, cycling, strava
Requires at least: 2.0
Tested up to: 3.5.1
Stable tag: 0.62
Tags: strava, bicycle, cycling, biking, running, run, swimming, swim, gps, shortcode, widget, plugin
Requires at least: 3.0
Tested up to: 4.0
Stable tag: 1.0
License: GPLv2 or later
This plugin is intended to show your strava.com information in your WordPress site.
Show your Strava activity on your WordPress site.
== Description ==
This plugin uses the REST strava.com API to pull the data out and show the information in your WordPress site.
This plugin uses the Strava V3 API to embed maps and activity for
athletes and clubs on your WordPress site. Included are several
widgets and shortcodes for showing maps and activity summaries.
= Shortcodes =
[ride id=NUMBER] - add to any page or post. Also takes the following
optional parameters:
* som - english/metric (system of measure - override from default setting)
* map_width - width (width of image in pixels)
* map_height - height (height of image in pixels)
= Widgets =
Strava Latest Rides - shows a list of the last few activities
Strava Latest Map - shows map of latest activity with option to limit
latest map to activities of a certain minimum distance
== Changelog ==
= 1.0 =
Change to Strava API V3
Switch ride shortcode to use static map
= 0.70 =
Use WordPress HTTP API for all remote calls
Use WordPress Settings API for settings page
+3 -16
View File
@@ -3,7 +3,7 @@
Plugin Name: WP Strava
Plugin URI: http://cmanon.com
Description: Plugin to show your strava.com information in your wordpress blog. Some Icons are Copyright © Yusuke Kamiyamane. All rights reserved. Licensed under a Creative Commons Attribution 3.0 license.
Version: 0.70
Version: 1.0
Author: Carlos Santa Cruz (cmanon), Justin Foell <justin@foell.org>
Author URI: http://cmanon.com
License: GPL2
@@ -27,6 +27,8 @@ License: GPL2
define( 'WPSTRAVA_PLUGIN_DIR', trailingslashit( dirname( __FILE__) ) );
define( 'WPSTRAVA_PLUGIN_URL', plugins_url( '/', __FILE__ ) );
define( 'WPSTRAVA_PLUGIN_NAME', plugin_basename(__FILE__) );
define( 'WPSTRAVA_DEBUG', false );
// Load the multilingual support.
if( file_exists( WPSTRAVA_PLUGIN_DIR . 'lang/' . get_locale() . '.mo' ) ) {
@@ -35,18 +37,3 @@ if( file_exists( WPSTRAVA_PLUGIN_DIR . 'lang/' . get_locale() . '.mo' ) ) {
require_once WPSTRAVA_PLUGIN_DIR . 'lib/Strava.class.php';
$wpstrava = WPStrava::get_instance();
//@TODO only load these when needed using is_active_widget()
function load_styles() {
// Register a personalized stylesheet
wp_register_style('wp-strava-style', WPSTRAVA_PLUGIN_URL . 'css/wp-strava.css' );
wp_enqueue_style('wp-strava');
}
add_action('wp_enqueue_script', 'load_styles');
function load_scripts() {
// Load required javascript libraries
wp_enqueue_script('jquery');
//wp_enqueue_script('google-maps', 'http://maps.google.com/maps/api/js?sensor=false');
}
add_action('wp-enqueue_script', 'load_scripts');