Advertisement
Guest User

Untitled

a guest
Mar 25th, 2017
103
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 9.85 KB | None | 0 0
  1. <?php
  2. namespace MapMyRun;
  3. //require 'RuntasticActivityList.php';
  4. class MapMyRun
  5. {
  6.     /**
  7.      * HTTP Responses
  8.      */
  9.     const HTTP_OK   = 200;
  10.  
  11.     /**
  12.      * MapMyRun API Urls
  13.      */
  14.     const MAP_MY_RUN_URL_ACTIVITY = "https://oauth2-api.mapmyapi.com/v7.1/allday_activity/69649/";
  15.     const MAP_MY_RUN_URL_USER     = "https://oauth2-api.mapmyapi.com/v7.1/user/69649/?field_set=is_mvp";
  16.  
  17.     /**
  18.      * Runtastic Credentials
  19.      */
  20.     private $loginUsername ="maiagabriel@live.com";
  21.     private $loginPassword = "phpmapmyrun95";
  22.     //private $start_datetime_utc;
  23.     //private $end_datetime_utc;
  24.     //private $created_datetime;
  25.    //private $updated_datetime;
  26.     private $user;
  27.     private $uexternal_id;
  28.     private $has_time_series;
  29.     private $time_series;
  30.     private $aggregates;
  31.   //  private $aggregates_total_steps;
  32.     //private $aggregates.total_active_time;
  33.     //private $aggregates.total_energy_expended;
  34.     //private $aggregates.total_distance;
  35.  
  36.     private $timeout   = 30;
  37.     public function __construct()
  38.     {
  39.         libxml_use_internal_errors(true);
  40.         $this->doc = new \DOMDocument();
  41.     }
  42.  
  43.     public function setUser($user)
  44.     {
  45.         $this->user = $user;
  46.  
  47.         return $this;
  48.     }
  49.  
  50.     public function setPassword($loginPassword)
  51.     {
  52.         $this->loginPassword = $loginPassword;
  53.  
  54.         return $this;
  55.     }
  56.  
  57.     public function setTimeout($timeout)
  58.     {
  59.         $this->timeout = $timeout;
  60.  
  61.         return $this;
  62.     }
  63.  
  64.     public function setuexternal_id($uexternal_id)
  65.     {
  66.         $this->uexternal_id = $uexternal_id;
  67.  
  68.         return $this;
  69.     }
  70.     public function getUser()
  71.     {
  72.         return $this->user;
  73.     }
  74.  
  75.     public function getuexternal_id()
  76.     {
  77.         return $this->uexternal_id;
  78.     }
  79.  
  80.  
  81.     public function getResponseStatusCode()
  82.     {
  83.         if (isset($this->lastRequestInfo['http_code'])) {
  84.             return $this->lastRequestInfo['http_code'];
  85.         }
  86.  
  87.         return null;
  88.     }
  89.  
  90.  
  91.     private function setDataFromResponse($response)
  92.     {
  93.         $this->doc->loadHTML($response);
  94.  
  95.         $inputTags = $this->doc->getElementsByTagName('input');
  96.         foreach ($inputTags as $inputTag) {
  97.             if ($inputTag->getAttribute("name") == "authenticity_token") {
  98.                 $this->token = $inputTag->getAttribute("value");
  99.                 break;
  100.             }
  101.         }
  102.  
  103.         $aTags = $this->doc->getElementsByTagName('a');
  104.         foreach ($aTags as $aTag) {
  105.             if (preg_match("/\/en\/users\/(.*)\/dashboard/", $aTag->getAttribute("href"), $matches)) {
  106.                 $this->username = $matches[1];
  107.                 break;
  108.             }
  109.         }
  110.  
  111.         $scriptTags = $this->doc->getElementsByTagName('script');
  112.         foreach ($scriptTags as $scriptTag) {
  113.             if (strstr($scriptTag->nodeValue, 'index_data')) {
  114.                 $this->rawData = $scriptTag->nodeValue;
  115.                 break;
  116.             }
  117.         }
  118.  
  119.         preg_match("/uid: (.*)\,/", $this->rawData, $matches);
  120.         if (isset($matches[1])) {
  121.             $this->uid = $matches[1];
  122.         }
  123.     }
  124.  
  125.     /**
  126.      * Login User to Runtastic
  127.      *
  128.      * @return bool
  129.      */
  130.     public function login()
  131.     {
  132.         $this->loggedIn = false;
  133.  
  134.         $postData = [
  135.             "user[email]"           => $this->loginUsername,
  136.             "user[password]"        => $this->loginPassword,
  137.         ];
  138.  
  139.         $responseOutputJson = $this->post(self::RUNTASTIC_LOGIN_URL, $postData);
  140.  
  141.         if ($this->getResponseStatusCode() == self::HTTP_OK) {
  142.             $this->setDataFromResponse($responseOutputJson->update);
  143.  
  144.             $frontpageOutput = $this->get(sprintf(self::RUNTASTIC_SPORT_SESSIONS_URL, $this->getUsername()), [], false);
  145.             $this->setDataFromResponse($frontpageOutput);
  146.  
  147.             $this->loggedIn = true;
  148.         }
  149.  
  150.         return $this->loggedIn;
  151.     }
  152.  
  153.     /**
  154.      * Logout User's Session
  155.      *
  156.      * @return void
  157.      */
  158.     public function logout()
  159.     {
  160.         $this->get(self::RUNTASTIC_LOGOUT_URL);
  161.  
  162.         if ($this->getResponseStatusCode() == self::HTTP_OK) {
  163.             $this->loggedIn = false;
  164.         }
  165.     }
  166.  
  167.     public function getActivities($iWeek = null, $iMonth = null, $iYear = null)
  168.     {
  169.         $response = [];
  170.  
  171.         if (!$this->loggedIn) {
  172.             $this->login();
  173.         }
  174.  
  175.         if ($this->loggedIn) {
  176.             preg_match("/var index_data = (.*)\;/", $this->rawData, $matches);
  177.             $itemJsonData = json_decode($matches[1]);
  178.             $items = [];
  179.  
  180.             // Complete $iMonth with leading zeros
  181.             if (!is_null($iMonth)) {
  182.                 $iMonth = str_pad($iMonth, 2, '0', STR_PAD_LEFT);
  183.             }
  184.  
  185.             if (is_null($iYear)) {
  186.                 $iYear = date("Y");
  187.             }
  188.  
  189.             foreach ($itemJsonData as $item) {
  190.                 if (!is_null($iWeek)) { /* Get week statistics */
  191.                     $sMonday = date("Y-m-d", strtotime("{$iYear}-W{$iWeek}"));
  192.                     $sSunday = date("Y-m-d", strtotime("{$iYear}-W{$iWeek}-7"));
  193.                     if ($sMonday <= $item[1] && $sSunday >= $item[1]) {
  194.                         $items[] = $item[0];
  195.                     }
  196.                 } elseif (!is_null($iMonth)) { /* Get month statistics */
  197.                     $tmpDate = $iYear."-".$iMonth."-";
  198.                     if ($tmpDate."01" <= $item[1] && $tmpDate."31" >= $item[1]) {
  199.                         $items[] = $item[0];
  200.                     }
  201.                 } elseif (!is_null($iYear)) { /* Get year statistics */
  202.                     $tmpDate = $iYear."-";
  203.                     if ($tmpDate."01-01" <= $item[1] && $tmpDate."12-31" >= $item[1]) {
  204.                         $items[] = $item[0];
  205.                     }
  206.                 } else { /* Get all statistics */
  207.                     $items[] = $item[0];
  208.                 }
  209.             }
  210.  
  211.             // Sort activities by ID (which is the same that sorting by date)
  212.             arsort($items);
  213.  
  214.             $postData = [
  215.                 "user_id"            => $this->getUid(),
  216.                 "items"              => join(',', $items),
  217.                 "authenticity_token" => $this->getToken(),
  218.             ];
  219.  
  220.             $response = $this->post(self::RUNTASTIC_SESSIONS_URL, $postData);
  221.         }
  222.  
  223.         return new RuntasticActivityList($response);
  224.     }
  225.  
  226.     /**
  227.      * Appends query array onto URL
  228.      *
  229.      * @param  string $url
  230.      * @param  array  $query
  231.      * @return string
  232.      */
  233.     protected function parseGet($url, $query)
  234.     {
  235.         if (!empty($query)) {
  236.             $append = strpos($url, '?') === false ? '?' : '&';
  237.  
  238.             return $url.$append.http_build_query($query);
  239.         }
  240.  
  241.         return $url;
  242.     }
  243.  
  244.     /**
  245.      * Parses JSON as PHP object
  246.      *
  247.      * @param  string $response
  248.      * @return object
  249.      */
  250.     protected function parseResponse($response)
  251.     {
  252.         return @json_decode($response, false, 512, JSON_BIGINT_AS_STRING);
  253.     }
  254.  
  255.     /**
  256.      * Makes HTTP Request to the API
  257.      *
  258.      * @param  string      $url
  259.      * @param  array       $parameters
  260.      * @param  string|null $request
  261.      * @param  bool        $json
  262.      * @return object|null
  263.      */
  264.     protected function request($url, $parameters = [], $request = null, $json = true)
  265.     {
  266.         $this->lastRequest     = $url;
  267.         $this->lastRequestData = $parameters;
  268.  
  269.         $curl = curl_init($url);
  270.  
  271.         $curlOptions = array(
  272.             CURLOPT_URL             => $url,
  273.             CURLOPT_RETURNTRANSFER  => true,
  274.             CURLOPT_COOKIEFILE      => $this->cookieJar,
  275.             CURLOPT_COOKIEJAR       => $this->cookieJar,
  276.             CURLOPT_TIMEOUT         => $this->timeout,
  277.         );
  278.  
  279.         if (!empty($parameters) || !empty($request)) {
  280.             if (!empty($request)) {
  281.                 $curlOptions[CURLOPT_CUSTOMREQUEST] = $request;
  282.                 $parameters = http_build_query($parameters);
  283.             } else {
  284.                 $curlOptions[CURLOPT_POST] = true;
  285.             }
  286.  
  287.             $curlOptions[CURLOPT_POSTFIELDS] = $parameters;
  288.         }
  289.  
  290.         curl_setopt_array($curl, $curlOptions);
  291.         $response = curl_exec($curl);
  292.         $this->lastRequestInfo = curl_getinfo($curl);
  293.         curl_close($curl);
  294.  
  295.         return !$response ? null : ($json ? $this->parseResponse($response) : $response);
  296.     }
  297.  
  298.     /**
  299.      * Sends GET request to specified API endpoint
  300.      *
  301.      * @param  string $request
  302.      * @param  array  $parameters
  303.      * @param  bool   $json
  304.      * @return string
  305.      */
  306.     public function get($request, $parameters = [], $json = true)
  307.     {
  308.         $requestUrl = $this->parseGet($request, $parameters);
  309.  
  310.         return $this->request($requestUrl, [], null, $json);
  311.     }
  312.  
  313.     /**
  314.      * Sends PUT request to specified API endpoint
  315.      *
  316.      * @param  string $request
  317.      * @param  array  $parameters
  318.      * @param  bool   $json
  319.      * @return string
  320.      */
  321.     public function put($request, $parameters = [], $json = true)
  322.     {
  323.         return $this->request($request, $parameters, 'PUT', $json);
  324.     }
  325.  
  326.     /**
  327.      * Sends POST request to specified API endpoint
  328.      *
  329.      * @param  string $request
  330.      * @param  array  $parameters
  331.      * @param  bool   $json
  332.      * @return string
  333.      */
  334.     public function post($request, $parameters = [], $json = true)
  335.     {
  336.         return $this->request($request, $parameters, null, $json);
  337.     }
  338.  
  339.     /**
  340.      * Sends DELETE request to specified API endpoint
  341.      */
  342.      * @param  string $request
  343.      * @param  array  $parameters
  344.      * @param  bool   $json
  345.      * @return string
  346.      */
  347.     public function delete($request, $parameters = [], $json = true)
  348.     {
  349.         return $this->request($request, $parameters, 'DELETE', $json);
  350.     }
  351. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement