4 * Twitter-API-PHP : Simple PHP wrapper for the v1.1 API
8 * @category Awesomeness
9 * @package Twitter-API-PHP
10 * @author James Mallison <me@j7mbo.co.uk>
11 * @license MIT License
13 * @link http://github.com/j7mbo/twitter-api-php
15 class TwitterAPIExchange
20 private $oauth_access_token;
25 private $oauth_access_token_secret;
30 private $consumer_key;
35 private $consumer_secret;
60 public $requestMethod;
63 * The HTTP status code from the previous request
67 protected $httpStatusCode;
70 * Create the API access object. Requires an array of settings::
71 * oauth access token, oauth access token secret, consumer key, consumer secret
72 * These are all available by creating your own application on dev.twitter.com
73 * Requires the cURL library
75 * @throws \RuntimeException When cURL isn't loaded
76 * @throws \InvalidArgumentException When incomplete settings parameters are provided
78 * @param array $settings
80 public function __construct(array $settings)
82 if (!function_exists('curl_init'))
84 throw new RuntimeException('TwitterAPIExchange requires cURL extension to be loaded, see: http://curl.haxx.se/docs/install.html');
87 if (!isset($settings['oauth_access_token'])
88 || !isset($settings['oauth_access_token_secret'])
89 || !isset($settings['consumer_key'])
90 || !isset($settings['consumer_secret']))
92 throw new InvalidArgumentException('Incomplete settings passed to TwitterAPIExchange');
95 $this->oauth_access_token = $settings['oauth_access_token'];
96 $this->oauth_access_token_secret = $settings['oauth_access_token_secret'];
97 $this->consumer_key = $settings['consumer_key'];
98 $this->consumer_secret = $settings['consumer_secret'];
102 * Set postfields array, example: array('screen_name' => 'J7mbo')
104 * @param array $array Array of parameters to send to API
106 * @throws \Exception When you are trying to set both get and post fields
108 * @return TwitterAPIExchange Instance of self for method chaining
110 public function setPostfields(array $array)
112 if (!is_null($this->getGetfield()))
114 throw new Exception('You can only choose get OR post fields (post fields include put).');
117 if (isset($array['status']) && substr($array['status'], 0, 1) === '@')
119 $array['status'] = sprintf("\0%s", $array['status']);
122 foreach ($array as $key => &$value)
126 $value = ($value === true) ? 'true' : 'false';
130 $this->postfields = $array;
133 if (isset($this->oauth['oauth_signature']))
135 $this->buildOauth($this->url, $this->requestMethod);
142 * Set getfield string, example: '?screen_name=J7mbo'
144 * @param string $string Get key and value pairs as string
148 * @return \TwitterAPIExchange Instance of self for method chaining
150 public function setGetfield($string)
152 if (!is_null($this->getPostfields()))
154 throw new Exception('You can only choose get OR post / post fields.');
157 $getfields = preg_replace('/^\?/', '', explode('&', $string));
160 foreach ($getfields as $field)
164 list($key, $value) = explode('=', $field);
165 $params[$key] = $value;
169 $this->getfield = '?' . http_build_query($params, '', '&');
175 * Get getfield string (simple getter)
177 * @return string $this->getfields
179 public function getGetfield()
181 return $this->getfield;
185 * Get postfields array (simple getter)
187 * @return array $this->postfields
189 public function getPostfields()
191 return $this->postfields;
195 * Build the Oauth object using params set in construct and additionals
196 * passed to this method. For v1.1, see: https://dev.twitter.com/docs/api/1.1
198 * @param string $url The API url to use. Example: https://api.twitter.com/1.1/search/tweets.json
199 * @param string $requestMethod Either POST or GET
203 * @return \TwitterAPIExchange Instance of self for method chaining
205 public function buildOauth($url, $requestMethod)
207 if (!in_array(strtolower($requestMethod), array('post', 'get', 'put', 'delete')))
209 throw new Exception('Request method must be either POST, GET or PUT or DELETE');
212 $consumer_key = $this->consumer_key;
213 $consumer_secret = $this->consumer_secret;
214 $oauth_access_token = $this->oauth_access_token;
215 $oauth_access_token_secret = $this->oauth_access_token_secret;
218 'oauth_consumer_key' => $consumer_key,
219 'oauth_nonce' => time(),
220 'oauth_signature_method' => 'HMAC-SHA1',
221 'oauth_token' => $oauth_access_token,
222 'oauth_timestamp' => time(),
223 'oauth_version' => '1.0'
226 $getfield = $this->getGetfield();
228 if (!is_null($getfield))
230 $getfields = str_replace('?', '', explode('&', $getfield));
232 foreach ($getfields as $g)
234 $split = explode('=', $g);
236 /** In case a null is passed through **/
237 if (isset($split[1]))
239 $oauth[$split[0]] = urldecode($split[1]);
244 $postfields = $this->getPostfields();
246 if (!is_null($postfields)) {
247 foreach ($postfields as $key => $value) {
248 $oauth[$key] = $value;
252 $base_info = $this->buildBaseString($url, $requestMethod, $oauth);
253 $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
254 $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
255 $oauth['oauth_signature'] = $oauth_signature;
258 $this->requestMethod = $requestMethod;
259 $this->oauth = $oauth;
265 * Perform the actual data retrieval from the API
267 * @param boolean $return If true, returns data. This is left in for backward compatibility reasons
268 * @param array $curlOptions Additional Curl options for this request
272 * @return string json If $return param is true, returns json data.
274 public function performRequest($return = true, $curlOptions = array())
276 if (!is_bool($return))
278 throw new Exception('performRequest parameter must be true or false');
281 $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
283 $getfield = $this->getGetfield();
284 $postfields = $this->getPostfields();
286 if (in_array(strtolower($this->requestMethod), array('put', 'delete')))
288 $curlOptions[CURLOPT_CUSTOMREQUEST] = $this->requestMethod;
291 $options = $curlOptions + array(
292 CURLOPT_HTTPHEADER => $header,
293 CURLOPT_HEADER => false,
294 CURLOPT_URL => $this->url,
295 CURLOPT_RETURNTRANSFER => true,
296 CURLOPT_TIMEOUT => 10,
299 if (!is_null($postfields))
301 $options[CURLOPT_POSTFIELDS] = http_build_query($postfields, '', '&');
305 if ($getfield !== '')
307 $options[CURLOPT_URL] .= $getfield;
312 curl_setopt_array($feed, $options);
313 $json = curl_exec($feed);
315 $this->httpStatusCode = curl_getinfo($feed, CURLINFO_HTTP_CODE);
317 if (($error = curl_error($feed)) !== '')
321 throw new \Exception($error);
330 * Private method to generate the base string used by cURL
332 * @param string $baseURI
333 * @param string $method
334 * @param array $params
336 * @return string Built base string
338 private function buildBaseString($baseURI, $method, $params)
343 foreach($params as $key => $value)
345 $return[] = rawurlencode($key) . '=' . rawurlencode($value);
348 return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $return));
352 * Private method to generate authorization header used by cURL
354 * @param array $oauth Array of oauth data generated by buildOauth()
356 * @return string $return Header used by cURL for request
358 private function buildAuthorizationHeader(array $oauth)
360 $return = 'Authorization: OAuth ';
363 foreach($oauth as $key => $value)
365 if (in_array($key, array('oauth_consumer_key', 'oauth_nonce', 'oauth_signature',
366 'oauth_signature_method', 'oauth_timestamp', 'oauth_token', 'oauth_version'))) {
367 $values[] = "$key=\"" . rawurlencode($value) . "\"";
371 $return .= implode(', ', $values);
376 * Helper method to perform our request
379 * @param string $method
380 * @param string $data
381 * @param array $curlOptions
385 * @return string The json response from the server
387 public function request($url, $method = 'get', $data = null, $curlOptions = array())
389 if (strtolower($method) === 'get')
391 $this->setGetfield($data);
395 $this->setPostfields($data);
398 return $this->buildOauth($url, $method)->performRequest(true, $curlOptions);
402 * Get the HTTP status code for the previous request
406 public function getHttpStatusCode()
408 return $this->httpStatusCode;