Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Newer
Older
100644 97 lines (84 sloc) 2.956 kb
08cb4a0 @jwpage Added the weightbot class, and filled out the readme
jwpage authored
1 <?php
2
3 /**
4 * A PHP API for accessing user data from weightbot.com
5 *
6 **/
7 class Weightbot {
8
9 private $_cookie_file = 'cookies';
10 private $_email;
11 private $_password;
12
13 /**
14 * Creates a Weightbot object for a given user.
15 **/
16 public function __construct($email, $password) {
17 $this->_email = $email;
18 $this->_password = $password;
19 }
20
21 /**
22 * Creates a cURL object for remote requests.
23 * @param $url string the URL to connect to.
24 * @return cURL object
25 **/
26 private function _prep_curl($url) {
27 $ch = curl_init($url);
28 curl_setopt($ch, CURLOPT_HEADER, false);
29 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
30 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
31 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
32 curl_setopt($ch, CURLOPT_COOKIEJAR, $this->_cookie_file);
33 curl_setopt($ch, CURLOPT_COOKIEFILE, $this->_cookie_file);
34 return $ch;
35 }
36
37 /**
38 * Fetches a remote Weightbot page and retrieves the CSRF token in the
39 * page's form.
40 * @param $url string the remote Weightbot page
41 * @return string the CSRF token, if present
42 */
43 private function _get_token($url) {
44 $ch = $this->_prep_curl($url);
45 $result = curl_exec($ch);
46 curl_close($ch);
47
48 $matches = array();
49 preg_match("/input name=\"authenticity_token\" type=\"hidden\" value=\"(.*?)\"/", $result, $matches);
50 return isset($matches[1]) ? $matches[1] : false;
51 }
52
53 /**
54 * Logs the user in and stores details in the COOKIE_FILE.
55 * @return boolean login success/failure
56 */
57 public function login() {
58 $email = $this->_email;
59 $password = $this->_password;
60
61 $token = $this->_get_token("https://weightbot.com/account/login");
62 $ch = $this->_prep_curl("https://weightbot.com/account/login");
63
64 $post = array(
65 'email' => $email,
66 'password' => $password,
67 'authenticity_token' => $token,
68 );
69
70 curl_setopt($ch, CURLOPT_POST, true);
71 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
72
73 $result = curl_exec($ch);
74 curl_close($ch);
75 // Could be better...
76 return (strstr($result, 'You are being') !== false);
77 }
78
79 /**
80 * Gets the Weightbot CSV user data.
81 * @return string csv user data
82 */
83 public function get_csv() {
84 $token = $this->_get_token("https://weightbot.com");
85
86 // Now that we have the token, let's finally get the CSV.
87 $ch = $this->_prep_curl("https://weightbot.com/export");
88 $post = array(
89 'authenticity_token' => $token,
90 );
91 curl_setopt($ch, CURLOPT_POST, true);
92 curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
93 $result = curl_exec($ch);
94 curl_close($ch);
95 return $result;
96 }
97 }
Something went wrong with that request. Please try again.