1<?php
2
3/*
4 * Abraham Williams (abraham@abrah.am) http://abrah.am
5 *
6 * The first PHP Library to support OAuth for Twitter's REST API.
7 */
8
9/* Load OAuth lib. You can find it at http://oauth.net */
10require_once('OAuth.php');
11
12/**
13 * Twitter OAuth class
14 */
15class TwitterOAuth {
16  /* Contains the last HTTP status code returned. */
17  public $http_code;
18  /* Contains the last API call. */
19  public $url;
20  /* Set up the API root URL. */
21  public $host = "https://api.twitter.com/1/";
22  /* Set timeout default. */
23  public $timeout = 30;
24  /* Set connect timeout. */
25  public $connecttimeout = 30;
26  /* Verify SSL Cert. */
27  public $ssl_verifypeer = FALSE;
28  /* Respons format. */
29  public $format = 'json';
30  /* Decode returned json data. */
31  public $decode_json = TRUE;
32  /* Contains the last HTTP headers returned. */
33  public $http_info;
34  /* Set the useragnet. */
35  public $useragent = 'TwitterOAuth v0.2.0-beta2';
36  /* Immediately retry the API call if the response was not successful. */
37  //public $retry = TRUE;
38
39
40
41
42  /**
43   * Set API URLS
44   */
45  function accessTokenURL()  { return 'https://api.twitter.com/oauth/access_token'; }
46  function authenticateURL() { return 'https://twitter.com/oauth/authenticate'; }
47  function authorizeURL()    { return 'https://twitter.com/oauth/authorize'; }
48  function requestTokenURL() { return 'https://api.twitter.com/oauth/request_token'; }
49
50  /**
51   * Debug helpers
52   */
53  function lastStatusCode() { return $this->http_status; }
54  function lastAPICall() { return $this->last_api_call; }
55
56  /**
57   * construct TwitterOAuth object
58   */
59  function __construct($consumer_key, $consumer_secret, $oauth_token = NULL, $oauth_token_secret = NULL) {
60    $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
61    $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
62    if (!empty($oauth_token) && !empty($oauth_token_secret)) {
63      $this->token = new OAuthConsumer($oauth_token, $oauth_token_secret);
64    } else {
65      $this->token = NULL;
66    }
67  }
68
69
70  /**
71   * Get a request_token from Twitter
72   *
73   * @returns a key/value array containing oauth_token and oauth_token_secret
74   */
75  function getRequestToken($oauth_callback = NULL) {
76    $parameters = array();
77    if (!empty($oauth_callback)) {
78      $parameters['oauth_callback'] = $oauth_callback;
79    }
80    $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters);
81    $token = OAuthUtil::parse_parameters($request);
82    $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
83    return $token;
84  }
85
86  /**
87   * Get the authorize URL
88   *
89   * @returns a string
90   */
91  function getAuthorizeURL($token, $sign_in_with_twitter = TRUE) {
92    if (is_array($token)) {
93      $token = $token['oauth_token'];
94    }
95    if (empty($sign_in_with_twitter)) {
96      return $this->authorizeURL() . "?oauth_token={$token}";
97    } else {
98       return $this->authenticateURL() . "?oauth_token={$token}";
99    }
100  }
101
102  /**
103   * Exchange request token and secret for an access token and
104   * secret, to sign API calls.
105   *
106   * @returns array("oauth_token" => "the-access-token",
107   *                "oauth_token_secret" => "the-access-secret",
108   *                "user_id" => "9436992",
109   *                "screen_name" => "abraham")
110   */
111  function getAccessToken($oauth_verifier = FALSE) {
112    $parameters = array();
113    if (!empty($oauth_verifier)) {
114      $parameters['oauth_verifier'] = $oauth_verifier;
115    }
116    $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
117    $token = OAuthUtil::parse_parameters($request);
118    $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
119    return $token;
120  }
121
122  /**
123   * One time exchange of username and password for access token and secret.
124   *
125   * @returns array("oauth_token" => "the-access-token",
126   *                "oauth_token_secret" => "the-access-secret",
127   *                "user_id" => "9436992",
128   *                "screen_name" => "abraham",
129   *                "x_auth_expires" => "0")
130   */
131  function getXAuthToken($username, $password) {
132    $parameters = array();
133    $parameters['x_auth_username'] = $username;
134    $parameters['x_auth_password'] = $password;
135    $parameters['x_auth_mode'] = 'client_auth';
136    $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters);
137    $token = OAuthUtil::parse_parameters($request);
138    $this->token = new OAuthConsumer($token['oauth_token'], $token['oauth_token_secret']);
139    return $token;
140  }
141
142  /**
143   * GET wrapper for oAuthRequest.
144   */
145  function get($url, $parameters = array()) {
146    $response = $this->oAuthRequest($url, 'GET', $parameters);
147    if ($this->format === 'json' && $this->decode_json) {
148      return json_decode($response);
149    }
150    return $response;
151  }
152
153  /**
154   * POST wrapper for oAuthRequest.
155   */
156  function post($url, $parameters = array()) {
157    $response = $this->oAuthRequest($url, 'POST', $parameters);
158    if ($this->format === 'json' && $this->decode_json) {
159      return json_decode($response);
160    }
161    return $response;
162  }
163
164  /**
165   * DELETE wrapper for oAuthReqeust.
166   */
167  function delete($url, $parameters = array()) {
168    $response = $this->oAuthRequest($url, 'DELETE', $parameters);
169    if ($this->format === 'json' && $this->decode_json) {
170      return json_decode($response);
171    }
172    return $response;
173  }
174
175  /**
176   * Format and sign an OAuth / API request
177   */
178  function oAuthRequest($url, $method, $parameters) {
179    if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
180      $url = "{$this->host}{$url}.{$this->format}";
181    }
182    $request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $url, $parameters);
183    $request->sign_request($this->sha1_method, $this->consumer, $this->token);
184    switch ($method) {
185    case 'GET':
186      return $this->http($request->to_url(), 'GET');
187    default:
188      return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
189    }
190  }
191
192  /**
193   * Make an HTTP request
194   *
195   * @return API results
196   */
197  function http($url, $method, $postfields = NULL) {
198    $this->http_info = array();
199    $ci = curl_init();
200    /* Curl settings */
201    curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
202    curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
203    curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
204    curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
205    curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
206    curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
207    curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
208    curl_setopt($ci, CURLOPT_HEADER, FALSE);
209
210    switch ($method) {
211      case 'POST':
212        curl_setopt($ci, CURLOPT_POST, TRUE);
213        if (!empty($postfields)) {
214          curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
215        }
216        break;
217      case 'DELETE':
218        curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
219        if (!empty($postfields)) {
220          $url = "{$url}?{$postfields}";
221        }
222    }
223
224    curl_setopt($ci, CURLOPT_URL, $url);
225    $response = curl_exec($ci);
226    $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
227    $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
228    $this->url = $url;
229    curl_close ($ci);
230    return $response;
231  }
232
233  /**
234   * Get the header info to store.
235   */
236  function getHeader($ch, $header) {
237    $i = strpos($header, ':');
238    if (!empty($i)) {
239      $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
240      $value = trim(substr($header, $i + 2));
241      $this->http_header[$key] = $value;
242    }
243    return strlen($header);
244  }
245}
246