6 * A Twitter library in PHP.
10 * @author J.M. <me@mynetx.net>
11 * @copyright 2010-2013 J.M. <me@mynetx.net>
13 * This program is free software: you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation, either version 3 of the License, or
16 * (at your option) any later version.
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <http://www.gnu.org/licenses/>.
30 $constants = explode(' ', 'OBJECT ARRAY JSON');
31 foreach ($constants as $i => $id) {
32 $id = 'CODEBIRD_RETURNFORMAT_' . $id;
33 defined($id) or define($id, $i);
36 'CURLE_SSL_CERTPROBLEM' => 58,
37 'CURLE_SSL_CACERT' => 60,
38 'CURLE_SSL_CACERT_BADFILE' => 77,
39 'CURLE_SSL_CRL_BADFILE' => 82,
40 'CURLE_SSL_ISSUER_ERROR' => 83
42 foreach ($constants as $id => $i) {
43 defined($id) or define($id, $i);
50 * A Twitter library in PHP.
53 * @subpackage codebird-php
58 * The current singleton instance
60 private static $_instance = null;
63 * The OAuth consumer key of your registered app
65 protected static $_oauth_consumer_key = null;
68 * The corresponding consumer secret
70 protected static $_oauth_consumer_secret = null;
73 * The app-only bearer token. Used to authorize app-only requests
75 protected static $_oauth_bearer_token = null;
78 * The API endpoint to use
80 protected static $_endpoint = 'https://api.twitter.com/1.1/';
83 * The API endpoint to use for OAuth requests
85 protected static $_endpoint_oauth = 'https://api.twitter.com/';
88 * The Request or access token. Used to sign requests
90 protected $_oauth_token = null;
93 * The corresponding request or access token secret
95 protected $_oauth_token_secret = null;
98 * The format of data to return from API calls
100 protected $_return_format = CODEBIRD_RETURNFORMAT_OBJECT;
103 * The file formats that Twitter accepts as image uploads
105 protected $_supported_media_files = array(IMAGETYPE_GIF, IMAGETYPE_JPEG, IMAGETYPE_PNG);
108 * The current Codebird version
110 protected $_version = '2.4.1';
113 * Returns singleton class instance
114 * Always use this method unless you're working with multiple authenticated users at once
116 * @return Codebird The instance
118 public static function getInstance()
120 if (self::$_instance == null) {
121 self::$_instance = new self;
123 return self::$_instance;
127 * Sets the OAuth consumer key and secret (App key)
129 * @param string $key OAuth consumer key
130 * @param string $secret OAuth consumer secret
134 public static function setConsumerKey($key, $secret)
136 self::$_oauth_consumer_key = $key;
137 self::$_oauth_consumer_secret = $secret;
141 * Sets the OAuth2 app-only auth bearer token
143 * @param string $token OAuth2 bearer token
147 public static function setBearerToken($token)
149 self::$_oauth_bearer_token = $token;
153 * Gets the current Codebird version
155 * @return string The version number
157 public function getVersion()
159 return $this->_version;
163 * Sets the OAuth request or access token and secret (User key)
165 * @param string $token OAuth request or access token
166 * @param string $secret OAuth request or access token secret
170 public function setToken($token, $secret)
172 $this->_oauth_token = $token;
173 $this->_oauth_token_secret = $secret;
177 * Sets the format for API replies
179 * @param int $return_format One of these:
180 * CODEBIRD_RETURNFORMAT_OBJECT (default)
181 * CODEBIRD_RETURNFORMAT_ARRAY
185 public function setReturnFormat($return_format)
187 $this->_return_format = $return_format;
191 * Main API handler working on any requests you issue
193 * @param string $fn The member function you called
194 * @param array $params The parameters you sent along
196 * @return mixed The API reply encoded in the set return_format
199 public function __call($fn, $params)
202 $apiparams = array();
203 if (count($params) > 0) {
204 if (is_array($params[0])) {
205 $apiparams = $params[0];
207 parse_str($params[0], $apiparams);
208 // remove auto-added slashes if on magic quotes steroids
209 if (get_magic_quotes_gpc()) {
210 foreach($apiparams as $key => $value) {
211 if (is_array($value)) {
212 $apiparams[$key] = array_map('stripslashes', $value);
214 $apiparams[$key] = stripslashes($value);
221 // stringify null and boolean parameters
222 foreach ($apiparams as $key => $value) {
223 if (! is_scalar($value)) {
226 if (is_null($value)) {
227 $apiparams[$key] = 'null';
228 } elseif (is_bool($value)) {
229 $apiparams[$key] = $value ? 'true' : 'false';
233 $app_only_auth = false;
234 if (count($params) > 1) {
235 $app_only_auth = !! $params[1];
238 // map function name to API method
242 $path = explode('_', $fn);
243 for ($i = 0; $i < count($path); $i++) {
247 $method .= $path[$i];
249 // undo replacement for URL parameters
250 $url_parameters_with_underscore = array('screen_name');
251 foreach ($url_parameters_with_underscore as $param) {
252 $param = strtoupper($param);
253 $replacement_was = str_replace('_', '/', $param);
254 $method = str_replace($replacement_was, $param, $method);
257 // replace AA by URL parameters
258 $method_template = $method;
260 if (preg_match('/[A-Z_]{2,}/', $method, $match)) {
261 foreach ($match as $param) {
262 $param_l = strtolower($param);
263 $method_template = str_replace($param, ':' . $param_l, $method_template);
264 if (!isset($apiparams[$param_l])) {
265 for ($i = 0; $i < 26; $i++) {
266 $method_template = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method_template);
268 throw new \Exception(
269 'To call the templated method "' . $method_template
270 . '", specify the parameter value for "' . $param_l . '".'
273 $method = str_replace($param, $apiparams[$param_l], $method);
274 unset($apiparams[$param_l]);
278 // replace A-Z by _a-z
279 for ($i = 0; $i < 26; $i++) {
280 $method = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method);
281 $method_template = str_replace(chr(65 + $i), '_' . chr(97 + $i), $method_template);
284 $httpmethod = $this->_detectMethod($method_template, $apiparams);
285 $multipart = $this->_detectMultipart($method_template);
287 return $this->_callApi(
298 * Uncommon API methods
302 * Gets the OAuth authenticate URL for the current request token
304 * @return string The OAuth authenticate URL
306 public function oauth_authenticate($force_login = NULL, $screen_name = NULL)
308 if ($this->_oauth_token == null) {
309 throw new \Exception('To get the authenticate URL, the OAuth token must be set.');
311 $url = self::$_endpoint_oauth . 'oauth/authenticate?oauth_token=' . $this->_url($this->_oauth_token);
313 $url .= "&force_login=1";
316 $url .= "&screen_name=" . $screen_name;
322 * Gets the OAuth authorize URL for the current request token
324 * @return string The OAuth authorize URL
326 public function oauth_authorize($force_login = NULL, $screen_name = NULL)
328 if ($this->_oauth_token == null) {
329 throw new \Exception('To get the authorize URL, the OAuth token must be set.');
331 $url = self::$_endpoint_oauth . 'oauth/authorize?oauth_token=' . $this->_url($this->_oauth_token);
333 $url .= "&force_login=1";
336 $url .= "&screen_name=" . $screen_name;
342 * Gets the OAuth bearer token
344 * @return string The OAuth bearer token
347 public function oauth2_token()
349 if (! function_exists('curl_init')) {
350 throw new \Exception('To make API requests, the PHP curl extension must be available.');
352 if (self::$_oauth_consumer_key == null) {
353 throw new \Exception('To obtain a bearer token, the consumer key must be set.');
356 $post_fields = array(
357 'grant_type' => 'client_credentials'
359 $url = self::$_endpoint_oauth . 'oauth2/token';
360 $ch = curl_init($url);
361 curl_setopt($ch, CURLOPT_POST, 1);
362 curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
363 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
364 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
365 curl_setopt($ch, CURLOPT_HEADER, 1);
366 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
367 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
368 curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');
370 curl_setopt($ch, CURLOPT_USERPWD, self::$_oauth_consumer_key . ':' . self::$_oauth_consumer_secret);
371 curl_setopt($ch, CURLOPT_HTTPHEADER, array(
374 $reply = curl_exec($ch);
376 // certificate validation results
377 $validation_result = curl_errno($ch);
381 CURLE_SSL_CERTPROBLEM,
383 CURLE_SSL_CACERT_BADFILE,
384 CURLE_SSL_CRL_BADFILE,
385 CURLE_SSL_ISSUER_ERROR
389 throw new \Exception('Error ' . $validation_result . ' while validating the Twitter API certificate.');
392 $httpstatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
393 $reply = $this->_parseApiReply('oauth2/token', $reply);
394 switch ($this->_return_format) {
395 case CODEBIRD_RETURNFORMAT_ARRAY:
396 $reply['httpstatus'] = $httpstatus;
397 if ($httpstatus == 200) {
398 self::setBearerToken($reply['access_token']);
401 case CODEBIRD_RETURNFORMAT_JSON:
402 if ($httpstatus == 200) {
403 $parsed = json_decode($reply);
404 self::setBearerToken($parsed->access_token);
407 case CODEBIRD_RETURNFORMAT_OBJECT:
408 $reply->httpstatus = $httpstatus;
409 if ($httpstatus == 200) {
410 self::setBearerToken($reply->access_token);
422 * URL-encodes the given data
426 * @return mixed The encoded data
428 private function _url($data)
430 if (is_array($data)) {
431 return array_map(array(
435 } elseif (is_scalar($data)) {
436 return str_replace(array(
450 ), rawurlencode($data));
457 * Gets the base64-encoded SHA1 hash for the given data
459 * @param string $data The data to calculate the hash from
461 * @return string The hash
463 private function _sha1($data)
465 if (self::$_oauth_consumer_secret == null) {
466 throw new \Exception('To generate a hash, the consumer secret must be set.');
468 if (!function_exists('hash_hmac')) {
469 throw new \Exception('To generate a hash, the PHP hash extension must be available.');
471 return base64_encode(hash_hmac('sha1', $data, self::$_oauth_consumer_secret . '&'
472 . ($this->_oauth_token_secret != null ? $this->_oauth_token_secret : ''), true));
476 * Generates a (hopefully) unique random string
478 * @param int optional $length The length of the string to generate
480 * @return string The random string
482 protected function _nonce($length = 8)
485 throw new \Exception('Invalid nonce length.');
487 return substr(md5(microtime(true)), 0, $length);
491 * Generates an OAuth signature
493 * @param string $httpmethod Usually either 'GET' or 'POST' or 'DELETE'
494 * @param string $method The API method to call
495 * @param array optional $params The API call parameters, associative
497 * @return string Authorization HTTP header
499 protected function _sign($httpmethod, $method, $params = array())
501 if (self::$_oauth_consumer_key == null) {
502 throw new \Exception('To generate a signature, the consumer key must be set.');
504 $sign_params = array(
505 'consumer_key' => self::$_oauth_consumer_key,
507 'timestamp' => time(),
508 'nonce' => $this->_nonce(),
509 'signature_method' => 'HMAC-SHA1'
511 $sign_base_params = array();
512 foreach ($sign_params as $key => $value) {
513 $sign_base_params['oauth_' . $key] = $this->_url($value);
515 if ($this->_oauth_token != null) {
516 $sign_base_params['oauth_token'] = $this->_url($this->_oauth_token);
518 $oauth_params = $sign_base_params;
519 foreach ($params as $key => $value) {
520 $sign_base_params[$key] = $this->_url($value);
522 ksort($sign_base_params);
523 $sign_base_string = '';
524 foreach ($sign_base_params as $key => $value) {
525 $sign_base_string .= $key . '=' . $value . '&';
527 $sign_base_string = substr($sign_base_string, 0, -1);
528 $signature = $this->_sha1($httpmethod . '&' . $this->_url($method) . '&' . $this->_url($sign_base_string));
530 $params = array_merge($oauth_params, array(
531 'oauth_signature' => $signature
534 $authorization = 'Authorization: OAuth ';
535 foreach ($params as $key => $value) {
536 $authorization .= $key . '="' . $this->_url($value) . '", ';
538 return substr($authorization, 0, -2);
542 * Detects HTTP method to use for API call
544 * @param string $method The API method to call
545 * @param array $params The parameters to send along
547 * @return string The HTTP method that should be used
549 protected function _detectMethod($method, $params)
551 // multi-HTTP method endpoints
553 case 'account/settings':
554 $method = count($params) > 0 ? $method . '__post' : $method;
558 $httpmethods = array();
559 $httpmethods['GET'] = array(
561 'statuses/mentions_timeline',
562 'statuses/user_timeline',
563 'statuses/home_timeline',
564 'statuses/retweets_of_me',
567 'statuses/retweets/:id',
576 'direct_messages/sent',
577 'direct_messages/show',
579 // Friends & Followers
580 'friendships/no_retweets/ids',
583 'friendships/lookup',
584 'friendships/incoming',
585 'friendships/outgoing',
592 'account/verify_credentials',
598 'users/contributees',
599 'users/contributors',
600 'users/profile_banner',
603 'users/suggestions/:slug',
605 'users/suggestions/:slug/members',
615 'lists/subscribers/show',
616 'lists/members/show',
619 'lists/subscriptions',
622 'saved_searches/list',
623 'saved_searches/show/:id',
627 'geo/reverse_geocode',
629 'geo/similar_places',
637 'oauth/authenticate',
641 'help/configuration',
645 'application/rate_limit_status'
647 $httpmethods['POST'] = array(
649 'statuses/destroy/:id',
651 'statuses/retweet/:id',
652 'statuses/update_with_media',
655 'direct_messages/destroy',
656 'direct_messages/new',
658 // Friends & Followers
659 'friendships/create',
660 'friendships/destroy',
661 'friendships/update',
664 'account/settings__post',
665 'account/update_delivery_device',
666 'account/update_profile',
667 'account/update_profile_background_image',
668 'account/update_profile_colors',
669 'account/update_profile_image',
672 'account/update_profile_banner',
673 'account/remove_profile_banner',
680 'lists/members/destroy',
681 'lists/subscribers/create',
682 'lists/subscribers/destroy',
683 'lists/members/create_all',
684 'lists/members/create',
688 'lists/members/destroy_all',
691 'saved_searches/create',
692 'saved_searches/destroy/:id',
701 'oauth/access_token',
702 'oauth/request_token',
704 'oauth2/invalidate_token'
706 foreach ($httpmethods as $httpmethod => $methods) {
707 if (in_array($method, $methods)) {
711 throw new \Exception('Can\'t find HTTP method to use for "' . $method . '".');
715 * Detects if API call should use multipart/form-data
717 * @param string $method The API method to call
719 * @return bool Whether the method should be sent as multipart
721 protected function _detectMultipart($method)
725 'statuses/update_with_media',
728 'account/update_profile_background_image',
729 'account/update_profile_image',
730 'account/update_profile_banner'
732 return in_array($method, $multiparts);
736 * Detect filenames in upload parameters,
737 * build multipart request from upload params
739 * @param string $method The API method to call
740 * @param array $params The parameters to send along
744 protected function _buildMultipart($method, $params)
746 // well, files will only work in multipart methods
747 if (! $this->_detectMultipart($method)) {
751 // only check specific parameters
752 $possible_files = array(
754 'statuses/update_with_media' => 'media[]',
756 'account/update_profile_background_image' => 'image',
757 'account/update_profile_image' => 'image',
758 'account/update_profile_banner' => 'banner'
760 // method might have files?
761 if (! in_array($method, array_keys($possible_files))) {
765 $possible_files = explode(' ', $possible_files[$method]);
767 $multipart_border = '--------------------' . $this->_nonce();
768 $multipart_request = '';
770 foreach ($params as $key => $value) {
772 if (is_array($value)) {
773 throw new \Exception('Using URL-encoded parameters is not supported for uploading media.');
776 $multipart_request .=
777 '--' . $multipart_border . "\r\n"
778 . 'Content-Disposition: form-data; name="' . $key . '"';
780 // check for filenames
781 if (in_array($key, $possible_files)) {
782 if (// is it a file, a readable one?
784 && @is_readable($value)
786 // is it a valid image?
787 && $data = @getimagesize($value)
789 if (// is it a supported image format?
790 in_array($data[2], $this->_supported_media_files)
792 // try to read the file
795 $data = ob_get_contents();
797 if (strlen($data) == 0) {
805 $multipart_request .=
806 "\r\nContent-Transfer-Encoding: base64";
807 $value = base64_encode($value);
811 $multipart_request .=
812 "\r\n\r\n" . $value . "\r\n";
814 $multipart_request .= '--' . $multipart_border . '--';
816 return $multipart_request;
821 * Builds the complete API endpoint url
823 * @param string $method The API method to call
824 * @param string $method_template The API method template to call
826 * @return string The URL to send the request to
828 protected function _getEndpoint($method, $method_template)
830 if (substr($method, 0, 5) == 'oauth') {
831 $url = self::$_endpoint_oauth . $method;
833 $url = self::$_endpoint . $method . '.json';
839 * Calls the API using cURL
841 * @param string $httpmethod The HTTP method to use for making the request
842 * @param string $method The API method to call
843 * @param string $method_template The templated API method to call
844 * @param array optional $params The parameters to send along
845 * @param bool optional $multipart Whether to use multipart/form-data
846 * @param bool optional $app_only_auth Whether to use app-only bearer authentication
848 * @return mixed The API reply, encoded in the set return_format
851 protected function _callApi($httpmethod, $method, $method_template, $params = array(), $multipart = false, $app_only_auth = false)
853 if (! function_exists('curl_init')) {
854 throw new \Exception('To make API requests, the PHP curl extension must be available.');
856 $url = $this->_getEndpoint($method, $method_template);
858 if ($httpmethod == 'GET') {
859 $url_with_params = $url;
860 if (count($params) > 0) {
861 $url_with_params .= '?' . http_build_query($params);
863 $authorization = $this->_sign($httpmethod, $url, $params);
864 $ch = curl_init($url_with_params);
867 $authorization = $this->_sign($httpmethod, $url, array());
868 $params = $this->_buildMultipart($method_template, $params);
870 $authorization = $this->_sign($httpmethod, $url, $params);
871 $params = http_build_query($params);
873 $ch = curl_init($url);
874 curl_setopt($ch, CURLOPT_POST, 1);
875 curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
877 if ($app_only_auth) {
878 if (self::$_oauth_consumer_key == null) {
879 throw new \Exception('To make an app-only auth API request, the consumer key must be set.');
881 // automatically fetch bearer token, if necessary
882 if (self::$_oauth_bearer_token == null) {
883 $this->oauth2_token();
885 $authorization = 'Authorization: Bearer ' . self::$_oauth_bearer_token;
887 $request_headers = array();
888 if (isset($authorization)) {
889 $request_headers[] = $authorization;
890 $request_headers[] = 'Expect:';
893 $first_newline = strpos($params, "\r\n");
894 $multipart_boundary = substr($params, 2, $first_newline - 2);
895 $request_headers[] = 'Content-Length: ' . strlen($params);
896 $request_headers[] = 'Content-Type: multipart/form-data; boundary='
897 . $multipart_boundary;
900 curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
901 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
902 curl_setopt($ch, CURLOPT_HEADER, 1);
903 curl_setopt($ch, CURLOPT_HTTPHEADER, $request_headers);
904 curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
905 curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
906 curl_setopt($ch, CURLOPT_CAINFO, __DIR__ . '/cacert.pem');
908 $reply = curl_exec($ch);
910 // certificate validation results
911 $validation_result = curl_errno($ch);
915 CURLE_SSL_CERTPROBLEM,
917 CURLE_SSL_CACERT_BADFILE,
918 CURLE_SSL_CRL_BADFILE,
919 CURLE_SSL_ISSUER_ERROR
923 throw new \Exception('Error ' . $validation_result . ' while validating the Twitter API certificate.');
926 $httpstatus = curl_getinfo($ch, CURLINFO_HTTP_CODE);
927 $reply = $this->_parseApiReply($method_template, $reply);
928 if ($this->_return_format == CODEBIRD_RETURNFORMAT_OBJECT) {
929 $reply->httpstatus = $httpstatus;
930 } elseif ($this->_return_format == CODEBIRD_RETURNFORMAT_ARRAY) {
931 $reply['httpstatus'] = $httpstatus;
937 * Parses the API reply to encode it in the set return_format
939 * @param string $method The method that has been called
940 * @param string $reply The actual reply, JSON-encoded or URL-encoded
942 * @return array|object The parsed reply
944 protected function _parseApiReply($method, $reply)
946 // split headers and body
948 $reply = explode("\r\n\r\n", $reply, 4);
950 // check if using proxy
951 if (substr($reply[0], 0, 35) === 'HTTP/1.1 200 Connection Established') {
953 } elseif (count($reply) > 2) {
954 $headers = array_shift($reply);
957 implode("\r\n", $reply)
961 $headers_array = explode("\r\n", $reply[0]);
962 foreach ($headers_array as $header) {
963 $header_array = explode(': ', $header, 2);
964 $key = $header_array[0];
966 if (count($header_array) > 1) {
967 $value = $header_array[1];
969 $headers[$key] = $value;
971 if (count($reply) > 1) {
977 $need_array = $this->_return_format == CODEBIRD_RETURNFORMAT_ARRAY;
978 if ($reply == '[]') {
979 switch ($this->_return_format) {
980 case CODEBIRD_RETURNFORMAT_ARRAY:
982 case CODEBIRD_RETURNFORMAT_JSON:
984 case CODEBIRD_RETURNFORMAT_OBJECT:
985 return new \stdClass;
989 if (! $parsed = json_decode($reply, $need_array)) {
991 if (stripos($reply, '<' . '?xml version="1.0" encoding="UTF-8"?' . '>') === 0) {
992 // we received XML...
993 // since this only happens for errors,
994 // don't perform a full decoding
995 preg_match('/<request>(.*)<\/request>/', $reply, $request);
996 preg_match('/<error>(.*)<\/error>/', $reply, $error);
997 $parsed['request'] = htmlspecialchars_decode($request[1]);
998 $parsed['error'] = htmlspecialchars_decode($error[1]);
1000 // assume query format
1001 $reply = explode('&', $reply);
1002 foreach ($reply as $element) {
1003 if (stristr($element, '=')) {
1004 list($key, $value) = explode('=', $element);
1005 $parsed[$key] = $value;
1007 $parsed['message'] = $element;
1012 $reply = json_encode($parsed);
1014 switch ($this->_return_format) {
1015 case CODEBIRD_RETURNFORMAT_ARRAY:
1017 case CODEBIRD_RETURNFORMAT_JSON:
1019 case CODEBIRD_RETURNFORMAT_OBJECT:
1020 return (object) $parsed;