diff --git a/lib/API.class.php b/lib/API.class.php index d35f6c9..33631e7 100755 --- a/lib/API.class.php +++ b/lib/API.class.php @@ -17,10 +17,6 @@ class WPStrava_API { private $rideMapDetailsUrlV2 = "http://www.strava.com/api/v2/rides/:id/map_details"; */ - public $ridesLinkUrl = "http://app.strava.com/rides/"; - public $athletesLinkUrl = "http://app.strava.com/athletes/"; - public $feedback = ''; - public function post( $uri, $data = NULL, $version = 2 ) { $url = ( $version == 2 ) ? self::STRAVA_V2_API : self::STRAVA_V1_API; @@ -33,22 +29,49 @@ class WPStrava_API { $response = wp_remote_post( $url . $uri, $args ); - if ( empty( $response['response']['code'] ) || $response['response']['code'] != 200 ) { - $this->feedback .= sprintf( __( 'ERROR - %s', 'wp-strava'), print_r( $response, true ) ); - return false; + if ( $response['response']['code'] != 200 ) { + //see if there's useful info in the body + $body = json_decode( $response['body'] ); + $error = ''; + if ( ! empty( $body->error ) ) + $error = $body->error; + else + $error = print_r( $response, true ); + + return new WP_Error( 'wp-strava_post', + sprintf( __( 'ERROR %s %s - %s', 'wp-strava'), $response['response']['code'], $response['response']['message'], $error ), + $response ); } return json_decode( $response['body'] ); } - public function get( $uri, $version = 2 ) { + public function get( $uri, $args = NULL, $version = 2 ) { $url = ( $version == 2 ) ? self::STRAVA_V2_API : self::STRAVA_V1_API; - $response = wp_remote_get( $url . $uri ); + $url .= $uri; - if ( empty( $response['response']['code'] ) || $response['response']['code'] != 200 ) { - $this->feedback .= sprintf( __( 'ERROR - %s', 'wp-strava'), print_r( $response, true ) ); - return false; + if ( ! empty( $args ) ) + $url = add_query_arg( $args, $url ); + + $response = wp_remote_get( $url ); + + 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 + $error = print_r( $response, true ); + + return new WP_Error( 'wp-strava_get', + sprintf( __( 'ERROR %s %s - %s', 'wp-strava'), $response['response']['code'], $response['response']['message'], $error ), + $response ); } return json_decode( $response['body'] ); diff --git a/lib/LatestMapWidget.class.php b/lib/LatestMapWidget.class.php index a68cdea..8cd6717 100644 --- a/lib/LatestMapWidget.class.php +++ b/lib/LatestMapWidget.class.php @@ -66,7 +66,9 @@ class WPStrava_LatestMapWidget extends WP_Widget { $ride = $ride_transient; if ( ! $ride ) { - $rides = $this->getRides( $ride_index_params ); + die('
'.print_r($ride_index_params, true));
+			$rides = WPStrava::get_instance()->rides->getRidesAdvanced( $ride_index_params );
+			//$rides = $this->getRides( $ride_index_params );
 			if ( ! empty( $rides ) ) {
 			
 				if ( ! empty( $distance_min ) )
@@ -164,6 +166,6 @@ class WPStrava_LatestMapWidget extends WP_Widget {
 		
 	private function getMapDetails( $ride_id ) {
 		$token = WPStrava::get_instance()->settings->token;
-		return WPStrava::get_instance()->api->get( "rides/{$ride_id}/map_details?token={$token}" );
+		return WPStrava::get_instance()->api->get( "rides/{$ride_id}/map_details", array( 'token' => $token ) );
 	}
 }
\ No newline at end of file
diff --git a/lib/LatestRidesWidget.class.php b/lib/LatestRidesWidget.class.php
index 6af3bad..e84a4bb 100644
--- a/lib/LatestRidesWidget.class.php
+++ b/lib/LatestRidesWidget.class.php
@@ -4,15 +4,15 @@
  * WP Strava Latest Rides Widget Class
  */
 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');
+		wp_enqueue_style('wp-strava'); //TODO only load this when wigit is loaded
 	}
 	
 	/** @see WP_Widget::widget */
-	public function widget($args, $instance) {
+	public function widget( $args, $instance ) {
 		extract($args);
 		
 		//$widget_id = $args['widget_id'];
@@ -21,9 +21,7 @@ class WPStrava_LatestRidesWidget extends WP_Widget {
 		$strava_search_id = empty($instance['strava_search_id']) ? '' : $instance['strava_search_id'];
 		$quantity = empty($instance['quantity']) ? '5' : $instance['quantity'];
 
-		$wpstrava = WPStrava::get_instance();
-		$strava_som_option = $wpstrava->settings->som;
-	   
+	   	$this->som = WPStrava_SOM::get_som();
 		?>
 		
 			
@@ -86,54 +84,44 @@ 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 ) {
-		$response = "";
 	
 		//Check if the username is empty.
-		if (empty($strava_search_id)) {
-			$response .= __("Please configure the Strava search id on the widget options.", "wp-strava");
-		} else {
-			require_once WPSTRAVA_PLUGIN_DIR . 'lib/Rides.class.php';
-			$strava_rides = new WPStrava_Rides(); 
-			$strava_rides->getLatestRides($strava_search_option, $strava_search_id, $quantity);
-			$rides_details = $strava_rides->getRidesDetails($strava_som_option);
+		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;
 		
-			if ($strava_som_option == "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_option == "english") {
-				$units = array(
-					'elapsedTime' => __('hours','wp-strava'),
-					'movingTime' => __('hours','wp-strava'),
-					'distance' => __('miles','wp-strava'),
-					'averageSpeed' => __('mph','wp-strava'),
-					'maximumSpeed' => __('mph','wp-strava'),
-					'elevationGain' => __('feet','wp-strava')
-							   );
-			}
+		$rides = $strava_rides->getRidesSimple( $strava_search_option, $strava_search_id );
+		if ( is_wp_error( $rides ) )
+			return $rides->get_error_message();
+
+		//adjust quantity
+		$rides = array_slice( $rides, 0, $quantity );
 		
-			$response .= "";
 		return $response;
 	} // Function strava_request_handler
 	
diff --git a/lib/Rides.class.php b/lib/Rides.class.php
index a31aea0..c8c7567 100755
--- a/lib/Rides.class.php
+++ b/lib/Rides.class.php
@@ -3,99 +3,65 @@
  * Rides is a class wrapper for the Strava REST API functions.
  */
 class WPStrava_Rides {
-	public $stravaRides;
-	public $feedback;
-		
-	public function getRideDetails($rideId, $systemOfMeasurement) {
-		$url = preg_replace('/:id/', $rideId, $this->rideUrl);
-		$json = file_get_contents($url);
 
-		if($json) {
-			$strava_ride = json_decode($json);
-			
-			//Transform data to a ready to be displayed format
-			$startDate = date("F j, Y - H:i a", strtotime($strava_ride->ride->startDateLocal));
-			$elapsedTime = date("H:i:s", mktime(0, 0, $strava_ride->ride->elapsedTime));
-			$movingTime = date("H:i:s", mktime(0, 0, $strava_ride->ride->movingTime));
-			
-			if ($systemOfMeasurement == "metric") {
-				//To km
-				$distance = number_format($strava_ride->ride->distance/1000, 2);
-				//To km/h
-				$averageSpeed = number_format($strava_ride->ride->averageSpeed * 3.6, 2);
-				//To km/h
-				// Removed on version 2 of the Strava API
-				//$maximumSpeed = number_format($strava_ride->ride->maximumSpeed/1000, 2);
-				//It is already in meters
-				$elevationGain = number_format($strava_ride->ride->elevationGain, 2);
-			} elseif ($systemOfMeasurement == "english") {
-				//To miles
-				$distance = number_format($strava_ride->ride->distance/1609.34, 2);
-				//To miles/h
-				$averageSpeed = number_format($strava_ride->ride->averageSpeed * 2.2369, 2);
-				//To miles/h
-				// Removed on version 2 of the Strava API
-				//$maximumSpeed = number_format($strava_ride->ride->maximumSpeed/1609.34, 2);
-				//To foot
-				$elevationGain = number_format($strava_ride->ride->elevationGain/0.3048, 2);
-			}
-			
-			$ride_details = array(
-				'id' => $rideId,
-				'name' => $strava_ride->ride->name,
-				'athleteId' => $strava_ride->ride->athlete->id,
-				'athleteName' => $strava_ride->ride->athlete->name,
-				'athleteUserName' => $strava_ride->ride->athlete->username,
-				'startDate' => $startDate,
-				'elapsedTime' => $elapsedTime,
-				'movingTime' => $movingTime,
-				'distance' => $distance,
-				'averageSpeed' => $averageSpeed,
-				//'maximumSpeed' => $maximumSpeed,
-				'elevationGain' => $elevationGain
-			);
-			return $ride_details;
-		} else {
-			$this->feedback .= _e("Could not get information from strava.com for the ride id: ") . $stravaRide->id;
-			return false;
-		}
-	} // getRideDetails
+	const RIDES_URL = "http://app.strava.com/rides/";
+	const ATHLETES_URL = "http://app.strava.com/athletes/";
 	
-	public function getRidesDetails($systemOfMeasurement) {
-		if($this->stravaRides) {
-			$rides_details = array();
-			foreach($this->stravaRides as $stravaRide) {
-				$rides_details[] = $this->getRideDetails($stravaRide->id, $systemOfMeasurement);
-			}
-			return $rides_details;
-		} else {
-			$this->feedback .= _e("Please provide the rides array to be processed.", "wp-strava");
-			return false;
+	public function getRideDetails( $rideId ) {
+		return WPStrava::get_instance()->api->get( "rides/{$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 getLatestRides($searchOption, $searchId, $quantity) {
-		$url = $this->ridesUrl;
+	public function getRidesSimple( $searchOption, $searchId ) {
+		$api = WPStrava::get_instance()->api;
+
+		$data = NULL;
 		//Get the json results using the constructor specified values.
-		if($searchOption == "athlete") {
-			if(is_numeric($searchId)) {
-				$json = file_get_contents($url . '?athleteId=' . urlencode($searchId));
+		if ( $searchOption == 'athlete' ) {
+			if ( is_numeric( $searchId ) ) {
+				$data = $api->get( 'rides', array( 'athleteId' => $searchId ), 1 );
 			} else {
-				$json = file_get_contents($url . '?athleteName=' . urlencode($searchId));
+				$data = $api->get( 'rides', array( 'athleteName' => $searchId ), 1 );
 			}
-		} elseif ($searchOption == "club" AND is_numeric($searchId)) {
-			$json = file_get_contents($url . '?clubId=' . urlencode($searchId));
+		} elseif ($searchOption == 'club' && is_numeric($searchId)) {
+			$data = $api->get( 'rides', array( 'clubId' => $searchId ), 1 );
 		} else {
-			$this->feedback .= _e("There's an error on the widget options combination.", "wp-strava");
+			return new WP_Error( 'wp-strava_options', __("There's an error in your simple options.", 'wp-strava') );
 		}
-		if($json) {
-			$strava_rides = json_decode($json);
-			$this->stravaRides = array_slice($strava_rides->rides, 0, $quantity);
-		} else {
-			$this->feedback .= _e("There was an error pulling data of strava.com.", "wp-strava");
-			return false;
-		}
-	} // getLatestRides
+
+		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', explode( "\n", $params ), 1 ); //version 1
+
+		if ( is_wp_error( $data ) )
+			return $data;
+		
+		if ( isset( $data->rides ) )
+			return $data->rides;
+		
+		return array();	
+	}
 	    
     public function getRideMap($rideId, $token, $efforts, $threshold) {
     	if($rideId != 0 AND $token != "") {
diff --git a/lib/SOM.class.php b/lib/SOM.class.php
index e114a33..7340d76 100644
--- a/lib/SOM.class.php
+++ b/lib/SOM.class.php
@@ -22,4 +22,11 @@ abstract class WPStrava_SOM {
 	abstract public function elevation( $m );
 	abstract public function get_elevation_label();
 
+	public function time( $seconds ) {
+		return date( 'H:i:s', mktime( 0, 0, $seconds ) );
+	}
+
+	public function get_time_label() {
+		return __( 'hours', 'wp-strava' );
+	}
 }
\ No newline at end of file
diff --git a/lib/Strava.class.php b/lib/Strava.class.php
index a24aa1a..2f97d8d 100644
--- a/lib/Strava.class.php
+++ b/lib/Strava.class.php
@@ -10,6 +10,7 @@ class WPStrava {
 	private static $instance = NULL;
 	private $settings = NULL;
 	private $api = NULL;
+	private $rides = NULL;
 	
 	private function __construct() {
 		$this->settings = new WPStrava_Settings();
@@ -19,8 +20,8 @@ class WPStrava {
 		}
 
 		// 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', function() { return register_widget( 'WPStrava_LatestRidesWidget' ); } );
+		add_action( 'widgets_init', function() { return register_widget( 'WPStrava_LatestMapWidget' ); } );
 		
 	}
 
@@ -34,9 +35,13 @@ class WPStrava {
 		if ( isset( $this->{$name} ) )
 			return $this->{$name};
 
+		//on-demand classes
 		if ( $name == 'api' )
 			return $this->get_api();
 
+		if ( $name == 'rides' )
+			return $this->get_rides();
+
 		return NULL;
 	}
 
@@ -48,4 +53,13 @@ class WPStrava {
 
 		return $this->api;
 	}
+	
+	public function get_rides() {
+		if ( ! $this->rides ) {
+			require_once WPSTRAVA_PLUGIN_DIR . 'lib/Rides.class.php';
+			$this->rides = new WPStrava_Rides();
+		}
+
+		return $this->rides;
+	}
 }
\ No newline at end of file
diff --git a/readme.txt b/readme.txt
index f9381f4..c2c68d8 100755
--- a/readme.txt
+++ b/readme.txt
@@ -16,6 +16,7 @@ This plugin uses the REST strava.com API to pull the data out and show the infor
 == Changelog ==
 
 = 0.70 =
+Use WordPress HTTP API for all remote calls
 Use WordPress Settings API for settings page
 
 = 0.62 =
diff --git a/wp-strava.php b/wp-strava.php
index e6e3eb4..045ab76 100755
--- a/wp-strava.php
+++ b/wp-strava.php
@@ -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.63
+Version: 0.70
 Author: Carlos Santa Cruz (cmanon), Justin Foell 
 Author URI: http://cmanon.com
 License: GPL2