Move library\OAuth1.php to class structure Friendica\Security\OAuth1
[friendica-addons.git/.git] / statusnet / library / twitteroauth.php
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  * Version 0.2.0 kept for compatibility purpose with StatusNetOAuth
9  */
10
11 use Friendica\Security\OAuth1\OAuthConsumer;
12 use Friendica\Security\OAuth1\OAuthRequest;
13 use Friendica\Security\OAuth1\OAuthSignatureMethod_HMAC_SHA1;
14 use Friendica\Security\OAuth1\OAuthToken;
15 use Friendica\Security\OAuth1\OAuthUtil;
16
17 /**
18  * Twitter OAuth class
19  */
20 class TwitterOAuth
21 {
22         /* Set up the API root URL. */
23         public $host = "https://api.twitter.com/1.1/";
24         /* Set timeout default. */
25         public $timeout = 30;
26         /* Set connect timeout. */
27         public $connecttimeout = 30;
28         /* Verify SSL Cert. */
29         public $ssl_verifypeer = FALSE;
30         /* Response format. */
31         public $format = 'json';
32         /* Decode returned json data. */
33         public $decode_json = TRUE;
34         /* Set the useragent. */
35         public $useragent = 'TwitterOAuth v0.2.0-beta2';
36
37         /* Contains the last HTTP status code returned. */
38         public $http_code;
39         /* Contains the last API call. */
40         public $url;
41         /**
42          * Contains the last HTTP headers returned.
43          * @var array
44          */
45         public $http_header;
46         /**
47          * Contains the last HTTP request info
48          * @var string
49          */
50         public $http_info;
51
52         /** @var OAuthToken */
53         private $token;
54         /** @var OAuthConsumer */
55         private $consumer;
56         /** @var OAuthSignatureMethod_HMAC_SHA1 */
57         private $sha1_method;
58
59         /**
60          * Set API URLS
61          */
62         function accessTokenURL()
63         {
64                 return 'https://api.twitter.com/oauth/access_token';
65         }
66
67         function authenticateURL()
68         {
69                 return 'https://twitter.com/oauth/authenticate';
70         }
71
72         function authorizeURL()
73         {
74                 return 'https://twitter.com/oauth/authorize';
75         }
76
77         function requestTokenURL()
78         {
79                 return 'https://api.twitter.com/oauth/request_token';
80         }
81
82         function __construct($consumer_key, $consumer_secret, $oauth_token = null, $oauth_token_secret = null)
83         {
84                 $this->sha1_method = new OAuthSignatureMethod_HMAC_SHA1();
85                 $this->consumer = new OAuthConsumer($consumer_key, $consumer_secret);
86                 if (!empty($oauth_token) && !empty($oauth_token_secret)) {
87                         $this->token = new OAuthToken($oauth_token, $oauth_token_secret);
88                 } else {
89                         $this->token = null;
90                 }
91         }
92
93         /**
94          * Get a request_token
95          *
96          * @param callback $oauth_callback
97          * @return array
98          */
99         function getRequestToken($oauth_callback = null)
100         {
101                 $parameters = [];
102                 if (!empty($oauth_callback)) {
103                         $parameters['oauth_callback'] = $oauth_callback;
104                 }
105
106                 $request = $this->oAuthRequest($this->requestTokenURL(), 'GET', $parameters);
107                 $token = OAuthUtil::parse_parameters($request);
108                 $this->token = new OAuthToken($token['oauth_token'], $token['oauth_token_secret']);
109                 return $token;
110         }
111
112         /**
113          * Get the authorize URL
114          *
115          * @param array $token
116          * @param bool $sign_in_with_tumblr
117          * @return string
118          */
119         function getAuthorizeURL($token, $sign_in_with_twitter = TRUE)
120         {
121                 if (is_array($token)) {
122                         $token = $token['oauth_token'];
123                 }
124
125                 if (empty($sign_in_with_twitter)) {
126                         return $this->authorizeURL() . "?oauth_token={$token}";
127                 } else {
128                         return $this->authenticateURL() . "?oauth_token={$token}";
129                 }
130         }
131
132         /**
133          * Exchange request token and secret for an access token and
134          * secret, to sign API calls.
135          *
136          * @param bool $oauth_verifier
137          * @return array ("oauth_token" => "the-access-token",
138          *                "oauth_token_secret" => "the-access-secret",
139          *                "user_id" => "9436992",
140          *                "screen_name" => "abraham")
141          */
142         function getAccessToken($oauth_verifier = FALSE)
143         {
144                 $parameters = [];
145                 if (!empty($oauth_verifier)) {
146                         $parameters['oauth_verifier'] = $oauth_verifier;
147                 }
148
149                 $request = $this->oAuthRequest($this->accessTokenURL(), 'GET', $parameters);
150                 $token = OAuthUtil::parse_parameters($request);
151                 $this->token = new OAuthToken($token['oauth_token'], $token['oauth_token_secret']);
152
153                 return $token;
154         }
155
156         /**
157          * One time exchange of username and password for access token and secret.
158          *
159          * @param string $username
160          * @param string $password
161          * @return array ("oauth_token" => "the-access-token",
162          *                "oauth_token_secret" => "the-access-secret",
163          *                "user_id" => "9436992",
164          *                "screen_name" => "abraham",
165          *                "x_auth_expires" => "0")
166          */
167         function getXAuthToken($username, $password)
168         {
169                 $parameters = [];
170                 $parameters['x_auth_username'] = $username;
171                 $parameters['x_auth_password'] = $password;
172                 $parameters['x_auth_mode'] = 'client_auth';
173                 $request = $this->oAuthRequest($this->accessTokenURL(), 'POST', $parameters);
174                 $token = OAuthUtil::parse_parameters($request);
175                 $this->token = new OAuthToken($token['oauth_token'], $token['oauth_token_secret']);
176
177                 return $token;
178         }
179
180         /**
181          * GET wrapper for oAuthRequest.
182          *
183          * @param string $url
184          * @param array $parameters
185          * @return mixed|string
186          */
187         function get($url, $parameters = [])
188         {
189                 $response = $this->oAuthRequest($url, 'GET', $parameters);
190                 if ($this->format === 'json' && $this->decode_json) {
191                         return json_decode($response);
192                 }
193
194                 return $response;
195         }
196
197         /**
198          * POST wrapper for oAuthRequest.
199          *
200          * @param string $url
201          * @param array $parameters
202          * @return mixed|string
203          */
204         function post($url, $parameters = [])
205         {
206                 $response = $this->oAuthRequest($url, 'POST', $parameters);
207                 if ($this->format === 'json' && $this->decode_json) {
208                         return json_decode($response);
209                 }
210
211                 return $response;
212         }
213
214         /**
215          * DELETE wrapper for oAuthReqeust.
216          *
217          * @param string $url
218          * @param array $parameters
219          * @return mixed|string
220          */
221         function delete($url, $parameters = [])
222         {
223                 $response = $this->oAuthRequest($url, 'DELETE', $parameters);
224                 if ($this->format === 'json' && $this->decode_json) {
225                         return json_decode($response);
226                 }
227
228                 return $response;
229         }
230
231         /**
232          * Format and sign an OAuth / API request
233          *
234          * @param string $url
235          * @param string $method
236          * @param array $parameters
237          * @return mixed|string
238          */
239         function oAuthRequest($url, $method, $parameters)
240         {
241                 if (strrpos($url, 'https://') !== 0 && strrpos($url, 'http://') !== 0) {
242                         $url = "{$this->host}{$url}.{$this->format}";
243                 }
244
245                 $request = OAuthRequest::from_consumer_and_token($this->consumer, $method, $url, $parameters, $this->token);
246                 $request->sign_request($this->sha1_method, $this->consumer, $this->token);
247                 switch ($method) {
248                         case 'GET':
249                                 return $this->http($request->to_url(), 'GET');
250                         case 'UPLOAD':
251                                 return $this->http($request->get_normalized_http_url(), 'POST', $request->to_postdata(true));
252                         default:
253                                 return $this->http($request->get_normalized_http_url(), $method, $request->to_postdata());
254                 }
255         }
256
257         /**
258          * Make an HTTP request
259          *
260          * @param string $url
261          * @param string $method
262          * @param mixed  $postfields
263          * @return string API results
264          */
265         function http($url, $method, $postfields = null)
266         {
267                 $this->http_info = [];
268                 $ci = curl_init();
269                 /* Curl settings */
270                 curl_setopt($ci, CURLOPT_USERAGENT, $this->useragent);
271                 curl_setopt($ci, CURLOPT_CONNECTTIMEOUT, $this->connecttimeout);
272                 curl_setopt($ci, CURLOPT_TIMEOUT, $this->timeout);
273                 curl_setopt($ci, CURLOPT_RETURNTRANSFER, TRUE);
274                 curl_setopt($ci, CURLOPT_HTTPHEADER, array('Expect:'));
275                 curl_setopt($ci, CURLOPT_SSL_VERIFYPEER, $this->ssl_verifypeer);
276                 curl_setopt($ci, CURLOPT_HEADERFUNCTION, array($this, 'getHeader'));
277                 curl_setopt($ci, CURLOPT_HEADER, FALSE);
278
279                 switch ($method) {
280                         case 'POST':
281                                 curl_setopt($ci, CURLOPT_POST, TRUE);
282                                 if (!empty($postfields)) {
283                                         curl_setopt($ci, CURLOPT_POSTFIELDS, $postfields);
284                                 }
285                                 break;
286                         case 'DELETE':
287                                 curl_setopt($ci, CURLOPT_CUSTOMREQUEST, 'DELETE');
288                                 if (!empty($postfields)) {
289                                         $url = "{$url}?{$postfields}";
290                                 }
291                 }
292
293                 curl_setopt($ci, CURLOPT_URL, $url);
294                 $response = curl_exec($ci);
295                 $this->http_code = curl_getinfo($ci, CURLINFO_HTTP_CODE);
296                 $this->http_info = array_merge($this->http_info, curl_getinfo($ci));
297                 $this->url = $url;
298                 curl_close($ci);
299
300                 return $response;
301         }
302
303         /**
304          * Get the header info to store.
305          *
306          * @param resource $ch
307          * @param string $header
308          * @return int
309          */
310         function getHeader($ch, $header)
311         {
312                 $i = strpos($header, ':');
313                 if (!empty($i)) {
314                         $key = str_replace('-', '_', strtolower(substr($header, 0, $i)));
315                         $value = trim(substr($header, $i + 2));
316                         $this->http_header[$key] = $value;
317                 }
318
319                 return strlen($header);
320         }
321 }