/fitbitphp.php
https://github.com/clyons/fitbitphp · PHP · 2346 lines · 1532 code · 247 blank · 567 comment · 241 complexity · 2b025815e76b06b666885d4274e6ed57 MD5 · raw file
Large files are truncated click here to view the full file
- <?php
- /**
- * FitbitPHP v.0.70. Basic Fitbit API wrapper for PHP using OAuth
- *
- * Note: Library is in beta and provided as-is. We hope to add features as API grows, however
- * feel free to fork, extend and send pull requests to us.
- *
- * - https://github.com/heyitspavel/fitbitphp
- *
- *
- * Date: 2011/12/09
- * Requires OAuth 1.0.0, SimpleXML
- * @version 0.70 ($Id$)
- */
- class FitBitPHP
- {
- /**
- * API Constants
- *
- */
- private $authHost = 'www.fitbit.com';
- private $apiHost = 'api.fitbit.com';
- private $baseApiUrl;
- private $authUrl;
- private $requestTokenUrl;
- private $accessTokenUrl;
- /**
- * Class Variables
- *
- */
- protected $oauth;
- protected $oauth_Token, $oauth_Secret;
- protected $userId = '-';
- protected $metric = 0;
- protected $userAgent = 'FitbitPHP 0.70';
- protected $debug;
- protected $clientDebug;
- /**
- * @param string $consumer_key Application consumer key for Fitbit API
- * @param string $consumer_secret Application secret
- * @param int $debug Debug mode (0/1) enables OAuth internal debug
- * @param string $userAgent User-agent to use in API calls
- */
- public function __construct($consumer_key, $consumer_secret, $debug = 1, $userAgent = null)
- {
- $this->initUrls();
- $this->consumer_key = $consumer_key;
- $this->consumer_secret = $consumer_secret;
- $this->oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
- $this->debug = $debug;
- if (isset($userAgent))
- $this->userAgent = $userAgent;
- if ($debug)
- $this->oauth->enableDebug();
- }
- /**
- * @param string $consumer_key Application consumer key for Fitbit API
- * @param string $consumer_secret Application secret
- */
- public function reinit($consumer_key, $consumer_secret)
- {
- $this->consumer_key = $consumer_key;
- $this->consumer_secret = $consumer_secret;
- $this->oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_AUTHORIZATION);
- if ($debug)
- $this->oauth->enableDebug();
- }
- /**
- * @param string $apiHost API host, i.e. api.fitbit.com (do you know any others?)
- * @param string $authHost Auth host, i.e. www.fitbit.com
- */
- public function setEndpointBase($apiHost, $authHost, $https = true, $httpsApi = false)
- {
- $this->apiHost = $apiHost;
- $this->authHost = $authHost;
- $this->initUrls($https, $httpsApi);
- }
- private function initUrls($https = true, $httpsApi = false)
- {
- if ($httpsApi)
- $this->baseApiUrl = 'https://' . $this->apiHost . '/1/';
- else
- $this->baseApiUrl = 'http://' . $this->apiHost . '/1/';
- if ($https) {
- $this->authUrl = 'https://' . $this->authHost . '/oauth/authorize';
- $this->requestTokenUrl = 'https://' . $this->apiHost . '/oauth/request_token';
- $this->accessTokenUrl = 'https://' . $this->apiHost . '/oauth/access_token';
- } else {
- $this->authUrl = 'http://' . $this->authHost . '/oauth/authorize';
- $this->requestTokenUrl = 'http://' . $this->apiHost . '/oauth/request_token';
- $this->accessTokenUrl = 'http://' . $this->apiHost . '/oauth/access_token';
- }
- }
- /**
- * @return OAuth debugInfo object for previous call. Debug should be enabled in __construct
- */
- public function oauthDebug()
- {
- return $this->oauth->debugInfo;
- }
- /**
- * @return OAuth debugInfo object for previous client_customCall. Debug should be enabled in __construct
- */
- public function client_oauthDebug()
- {
- return $this->clientDebug;
- }
- /**
- * Returns Fitbit session status for frontend (i.e. 'Sign in with Fitbit' implementations)
- *
- * @return int (0 - no session, 1 - just after successful authorization, 2 - session exist)
- */
- public static function sessionStatus()
- {
- $session = session_id();
- if (empty($session)) {
- session_start();
- }
- if (empty($_SESSION['fitbit_Session']))
- $_SESSION['fitbit_Session'] = 0;
- return (int)$_SESSION['fitbit_Session'];
- }
- /**
- * Initialize session. Inits OAuth session, handles redirects to Fitbit login/authorization if needed
- *
- * @param $callbackUrl Callback for 'Sign in with Fitbit'
- * @param $cookie Use persistent cookie for authorization, or session cookie only
- * @return int (1 - just after successful authorization, 2 - if session already exist)
- */
- public function initSession($callbackUrl, $cookie = true)
- {
- $session = session_id();
- if (empty($session)) {
- session_start();
- }
- if (empty($_SESSION['fitbit_Session']))
- $_SESSION['fitbit_Session'] = 0;
- if (!isset($_GET['oauth_token']) && $_SESSION['fitbit_Session'] == 1)
- $_SESSION['fitbit_Session'] = 0;
- if ($_SESSION['fitbit_Session'] == 0) {
- $request_token_info = $this->oauth->getRequestToken($this->requestTokenUrl, $callbackUrl);
- $_SESSION['fitbit_Secret'] = $request_token_info['oauth_token_secret'];
- $_SESSION['fitbit_Session'] = 1;
- header('Location: ' . $this->authUrl . '?oauth_token=' . $request_token_info['oauth_token']);
- exit;
- } else if ($_SESSION['fitbit_Session'] == 1) {
- $this->oauth->setToken($_GET['oauth_token'], $_SESSION['fitbit_Secret']);
- $access_token_info = $this->oauth->getAccessToken($this->accessTokenUrl);
- $_SESSION['fitbit_Session'] = 2;
- $_SESSION['fitbit_Token'] = $access_token_info['oauth_token'];
- $_SESSION['fitbit_Secret'] = $access_token_info['oauth_token_secret'];
- $this->setOAuthDetails($_SESSION['fitbit_Token'], $_SESSION['fitbit_Secret']);
- return 1;
- } else if ($_SESSION['fitbit_Session'] == 2) {
- $this->setOAuthDetails($_SESSION['fitbit_Token'], $_SESSION['fitbit_Secret']);
- return 2;
- }
- }
- /**
- * Reset session
- *
- * @return void
- */
- public function resetSession()
- {
- $_SESSION['fitbit_Session'] = 0;
- }
- /**
- * Sets OAuth token/secret. Use if library used in internal calls without session handling
- *
- * @param $token
- * @param $secret
- * @return void
- */
- public function setOAuthDetails($token, $secret)
- {
- $this->oauth_Token = $token;
- $this->oauth_Secret = $secret;
- $this->oauth->setToken($this->oauth_Token, $this->oauth_Secret);
- }
- /**
- * Get OAuth token
- *
- * @return string
- */
- public function getOAuthToken()
- {
- return $this->oauth_Token;
- }
- /**
- * Get OAuth secret
- *
- * @return string
- */
- public function getOAuthSecret()
- {
- return $this->oauth_Secret;
- }
- /**
- * Set Fitbit userId for future API calls
- *
- * @param $userId 'XXXXX'
- * @return void
- */
- public function setUser($userId)
- {
- $this->userId = $userId;
- }
- /**
- * Set Unit System for all future calls (see http://wiki.fitbit.com/display/API/API-Unit-System)
- * 0 (Metric), 1 (en_US), 2 (en_GB)
- *
- * @param int $metric
- * @return void
- */
- public function setMetric($metric)
- {
- $this->metric = $metric;
- }
- /**
- * API wrappers
- *
- */
- /**
- * Get user profile
- *
- * @throws FitBitException
- * @param string $userId UserId of public profile, if none using set with setUser or '-' by default
- * @return SimpleXMLElement
- */
- public function getProfile()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/profile.xml", null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Update user profile
- *
- * @throws FitBitException
- * @param string $gender 'FEMALE', 'MALE' or 'NA'
- * @param DateTime $birthday Date of birth
- * @param string $height Height in cm/inches (as set with setMetric)
- * @param string $nickname Nickname
- * @param string $fullName Full name
- * @param string $timezone Timezone in the format 'America/Los_Angeles'
- * @return SimpleXMLElement
- */
- public function updateProfile($gender = null, $birthday = null, $height = null, $nickname = null, $fullName = null, $timezone = null)
- {
- $headers = $this->getHeaders();
- $parameters = array();
- if (isset($gender))
- $parameters['gender'] = $gender;
- if (isset($birthday))
- $parameters['birthday'] = $birthday->format('Y-m-d');
- if (isset($height))
- $parameters['height'] = $height;
- if (isset($nickname))
- $parameters['nickname'] = $nickname;
- if (isset($fullName))
- $parameters['fullName'] = $fullName;
- if (isset($timezone))
- $parameters['timezone'] = $timezone;
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/profile.xml",
- $parameters, OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user activities for specific date
- *
- * @throws FitBitException
- * @param DateTime $date
- * @param String $dateStr
- * @return SimpleXMLElement
- */
- public function getActivities($date, $dateStr = null)
- {
- $headers = $this->getHeaders();
- if (!isset($dateStr)) {
- $dateStr = $date->format('Y-m-d');
- }
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/activities/date/" . $dateStr . ".xml",
- null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user recent activities
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getRecentActivities()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities/recent.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user frequent activities
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getFrequentActivities()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities/frequent.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user favorite activities
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getFavoriteActivities()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities/favorite.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Log user activity
- *
- * @throws FitBitException
- * @param DateTime $date Activity date and time (set proper timezone, which could be fetched via getProfile)
- * @param string $activityId Activity Id (or Intensity Level Id) from activities database,
- * see http://wiki.fitbit.com/display/API/API-Log-Activity
- * @param string $duration Duration millis
- * @param string $calories Manual calories to override Fitbit estimate
- * @param string $distance Distance in km/miles (as set with setMetric)
- * @param string $distanceUnit Distance unit string (see http://wiki.fitbit.com/display/API/API-Distance-Unit)
- * @return SimpleXMLElement
- */
- public function logActivity($date, $activityId, $duration, $calories = null, $distance = null, $distanceUnit = null, $activityName = null)
- {
- $distanceUnits = array('Centimeter', 'Foot', 'Inch', 'Kilometer', 'Meter', 'Mile', 'Millimeter', 'Steps', 'Yards');
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['date'] = $date->format('Y-m-d');
- $parameters['startTime'] = $date->format('H:i');
- if (isset($activityName)) {
- $parameters['activityName'] = $activityName;
- $parameters['manualCalories'] = $calories;
- } else {
- $parameters['activityId'] = $activityId;
- if (isset($calories))
- $parameters['manualCalories'] = $calories;
- }
- $parameters['durationMillis'] = $duration;
- if (isset($distance))
- $parameters['distance'] = $distance;
- if (isset($distanceUnit) && in_array($distanceUnit, $distanceUnits))
- $parameters['distanceUnit'] = $distanceUnit;
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities.xml", $parameters,
- OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Delete user activity
- *
- * @throws FitBitException
- * @param string $id Activity log id
- * @return bool
- */
- public function deleteActivity($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_DELETE, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '204')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Add user favorite activity
- *
- * @throws FitBitException
- * @param string $id Activity log id
- * @return bool
- */
- public function addFavoriteActivity($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities/log/favorite/" . $id . ".xml",
- null, OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Delete user favorite activity
- *
- * @throws FitBitException
- * @param string $id Activity log id
- * @return bool
- */
- public function deleteFavoriteActivity($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/activities/log/favorite/" . $id . ".xml",
- null, OAUTH_HTTP_METHOD_DELETE, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '204')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get full description of specific activity
- *
- * @throws FitBitException
- * @param string $id Activity log Id
- * @return SimpleXMLElement
- */
- public function getActivity($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "activities/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get a tree of all valid Fitbit public activities as well as private custom activities the user createds
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function browseActivities()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "activities.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user foods for specific date
- *
- * @throws FitBitException
- * @param DateTime $date
- * @param String $dateStr
- * @return SimpleXMLElement
- */
- public function getFoods($date, $dateStr = null)
- {
- $headers = $this->getHeaders();
- if (!isset($dateStr)) {
- $dateStr = $date->format('Y-m-d');
- }
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/foods/log/date/" . $dateStr . ".xml",
- null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user recent foods
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getRecentFoods()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/recent.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user frequent foods
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getFrequentFoods()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/frequent.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user favorite foods
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getFavoriteFoods()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/favorite.xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Log user food
- *
- * @throws FitBitException
- * @param DateTime $date Food log date
- * @param string $foodId Food Id from foods database (see searchFoods)
- * @param string $mealTypeId Meal Type Id from foods database (see searchFoods)
- * @param string $unitId Unit Id, should be allowed for this food (see getFoodUnits and searchFoods)
- * @param string $amount Amount in specified units
- * @return SimpleXMLElement
- */
- public function logFood($date, $foodId, $mealTypeId, $unitId, $amount, $foodName = null, $calories = null, $brandName = null, $nutrition = null)
- {
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['date'] = $date->format('Y-m-d');
- if (isset($foodName)) {
- $parameters['foodName'] = $foodName;
- $parameters['calories'] = $calories;
- if (isset($brandName))
- $parameters['brandName'] = $brandName;
- if (isset($nutrition)) {
- foreach ($nutrition as $i => $value) {
- $parameters[$i] = $nutrition[$i];
- }
- }
- } else {
- $parameters['foodId'] = $foodId;
- }
- $parameters['mealTypeId'] = $mealTypeId;
- $parameters['unitId'] = $unitId;
- $parameters['amount'] = $amount;
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log.xml", $parameters,
- OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Delete user food
- *
- * @throws FitBitException
- * @param string $id Food log id
- * @return bool
- */
- public function deleteFood($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_DELETE, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '204')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Add user favorite food
- *
- * @throws FitBitException
- * @param string $id Food log id
- * @return bool
- */
- public function addFavoriteFood($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/favorite/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Delete user favorite food
- *
- * @throws FitBitException
- * @param string $id Food log id
- * @return bool
- */
- public function deleteFavoriteFood($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/favorite/" . $id . ".xml",
- null, OAUTH_HTTP_METHOD_DELETE, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '204')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user meal sets
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getMeals()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/meals.xml",
- null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get food units library
- *
- * @throws FitBitException
- * @return SimpleXMLElement
- */
- public function getFoodUnits()
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "foods/units.xml", null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Search for foods in foods database
- *
- * @throws FitBitException
- * @param string $query Search query
- * @return SimpleXMLElement
- */
- public function searchFoods($query)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "foods/search.xml?query=" . rawurlencode($query), null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get description of specific food from food db (or private for the user)
- *
- * @throws FitBitException
- * @param string $id Food Id
- * @return SimpleXMLElement
- */
- public function getFood($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "foods/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Create private foods for a user
- *
- * @throws FitBitException
- * @param string $name Food name
- * @param string $defaultFoodMeasurementUnitId Unit id of the default measurement unit
- * @param string $defaultServingSize Default serving size in measurement units
- * @param string $calories Calories in default serving
- * @param string $description
- * @param string $formType ("LIQUID" or "DRY)
- * @param string $nutrition Array of nutritional values, see http://wiki.fitbit.com/display/API/API-Create-Food
- * @return SimpleXMLElement
- */
- public function createFood($name, $defaultFoodMeasurementUnitId, $defaultServingSize, $calories, $description = null, $formType = null, $nutrition = null)
- {
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['name'] = $name;
- $parameters['defaultFoodMeasurementUnitId'] = $defaultFoodMeasurementUnitId;
- $parameters['defaultServingSize'] = $defaultServingSize;
- $parameters['calories'] = $calories;
- if (isset($description))
- $parameters['description'] = $description;
- if (isset($formType))
- $parameters['formType'] = $formType;
- if (isset($nutrition)) {
- foreach ($nutrition as $i => $value) {
- $parameters[$i] = $nutrition[$i];
- }
- }
- try {
- $this->oauth->fetch($this->baseApiUrl . "foods.xml", $parameters, OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user water log entries for specific date
- *
- * @throws FitBitException
- * @param DateTime $date
- * @param String $dateStr
- * @return SimpleXMLElement
- */
- public function getWater($date, $dateStr)
- {
- $headers = $this->getHeaders();
- if (!isset($dateStr)) {
- $dateStr = $date->format('Y-m-d');
- }
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/water/date/" . $dateStr . ".xml", null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Log user water
- *
- * @throws FitBitException
- * @param DateTime $date Log entry date (set proper timezone, which could be fetched via getProfile)
- * @param string $amount Amount in ml/fl oz (as set with setMetric) or waterUnit
- * @param string $waterUnit Water Unit ("ml", "fl oz" or "cup")
- * @return SimpleXMLElement
- */
- public function logWater($date, $amount, $waterUnit = null)
- {
- $waterUnits = array('ml', 'fl oz', 'cup');
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['date'] = $date->format('Y-m-d');
- $parameters['amount'] = $amount;
- if (isset($waterUnit) && in_array($waterUnit, $waterUnits))
- $parameters['unit'] = $waterUnit;
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/water.xml", $parameters,
- OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Delete user water record
- *
- * @throws FitBitException
- * @param string $id Water log id
- * @return bool
- */
- public function deleteWater($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/foods/log/water/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_DELETE, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '204')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user sleep log entries for specific date
- *
- * @throws FitBitException
- * @param DateTime $date
- * @param String $dateStr
- * @return SimpleXMLElement
- */
- public function getSleep($date, $dateStr = null)
- {
- $headers = $this->getHeaders();
- if (!isset($dateStr)) {
- $dateStr = $date->format('Y-m-d');
- }
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/sleep/date/" . $dateStr . ".xml",
- null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Log user sleep
- *
- * @throws FitBitException
- * @param DateTime $date Sleep date and time (set proper timezone, which could be fetched via getProfile)
- * @param string $duration Duration millis
- * @return SimpleXMLElement
- */
- public function logSleep($date, $duration)
- {
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['date'] = $date->format('Y-m-d');
- $parameters['startTime'] = $date->format('H:i');
- $parameters['duration'] = $duration;
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/sleep.xml", $parameters,
- OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Delete user sleep record
- *
- * @throws FitBitException
- * @param string $id Activity log id
- * @return bool
- */
- public function deleteSleep($id)
- {
- $headers = $this->getHeaders();
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/sleep/" . $id . ".xml", null,
- OAUTH_HTTP_METHOD_DELETE, $headers);
- } catch (Exception $E) {
- }
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '204')) {
- return true;
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Get user body measurements
- *
- * @throws FitBitException
- * @param DateTime $date
- * @param String $dateStr
- * @return SimpleXMLElement
- */
- public function getBody($date, $dateStr = null)
- {
- $headers = $this->getHeaders();
- if (!isset($dateStr)) {
- $dateStr = $date->format('Y-m-d');
- }
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/" . $this->userId . "/body/date/" . $dateStr . ".xml",
- null, OAUTH_HTTP_METHOD_GET, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '200')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Log user body measurements
- *
- * @throws FitBitException
- * @param string $weight Float number. For en_GB units, provide floating number of stones (i.e. 11 st. 4 lbs = 11.2857143)
- * @param string $fat Float number
- * @param string $bicep Float number
- * @param string $calf Float number
- * @param string $chest Float number
- * @param string $forearm Float number
- * @param string $hips Float number
- * @param string $neck Float number
- * @param string $thigh Float number
- * @param string $waist Float number
- * @param DateTime $date Date Log entry date (set proper timezone, which could be fetched via getProfile)
- * @return SimpleXMLElement
- */
- public function logBody($date, $weight = null, $fat = null, $bicep = null, $calf = null, $chest = null, $forearm = null, $hips = null, $neck = null, $thigh = null, $waist = null)
- {
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['date'] = $date->format('Y-m-d');
- if (isset($weight))
- $parameters['weight'] = $weight;
- if (isset($fat))
- $parameters['fat'] = $fat;
- if (isset($bicep))
- $parameters['bicep'] = $bicep;
- if (isset($calf))
- $parameters['calf'] = $calf;
- if (isset($chest))
- $parameters['chest'] = $chest;
- if (isset($forearm))
- $parameters['forearm'] = $forearm;
- if (isset($hips))
- $parameters['hips'] = $hips;
- if (isset($neck))
- $parameters['neck'] = $neck;
- if (isset($thigh))
- $parameters['thigh'] = $thigh;
- if (isset($waist))
- $parameters['waist'] = $waist;
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/body.xml",
- $parameters, OAUTH_HTTP_METHOD_POST, $headers);
- } catch (Exception $E) {
- }
- $response = $this->oauth->getLastResponse();
- $responseInfo = $this->oauth->getLastResponseInfo();
- if (!strcmp($responseInfo['http_code'], '201')) {
- $xml = simplexml_load_string($response);
- if ($xml)
- return $xml;
- else
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- } else {
- $xml = simplexml_load_string($response);
- if (!$xml)
- throw new FitBitException($responseInfo['http_code'], 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- else
- throw new FitBitException($responseInfo['http_code'], $xml->errors->apiError->message, 'Fitbit request failed. Code: ' . $responseInfo['http_code']);
- }
- }
- /**
- * Log user weight
- *
- * @throws FitBitException
- * @param string $weight Float number. For en_GB units, provide floating number of stones (i.e. 11 st. 4 lbs = 11.2857143)
- * @param DateTime $date If present, log entry date, now by default (set proper timezone, which could be fetched via getProfile)
- * @return bool
- */
- public function logWeight($weight, $date = null)
- {
- $headers = $this->getHeaders();
- $parameters = array();
- $parameters['weight'] = $weight;
- if (isset($date))
- $parameters['date'] = $date->format('Y-m-d');
- try {
- $this->oauth->fetch($this->baseApiUrl . "user/-/body/weight.xml",
- $parameters, OAUTH_…