/
TwitterOAuth.php
617 lines (564 loc) · 17.7 KB
/
TwitterOAuth.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
<?php
/**
* The most popular PHP library for use with the Twitter OAuth REST API.
*
* @license MIT
*/
namespace Abraham\TwitterOAuth;
use Abraham\TwitterOAuth\Util\JsonDecoder;
/**
* TwitterOAuth class for interacting with the Twitter API.
*
* @author Abraham Williams <abraham@abrah.am>
*/
class TwitterOAuth extends Config
{
const API_VERSION = '1.1';
const API_HOST = 'https://api.twitter.com';
const UPLOAD_HOST = 'https://upload.twitter.com';
/** @var Response details about the result of the last request */
private $response;
/** @var string|null Application bearer token */
private $bearer;
/** @var Consumer Twitter application details */
private $consumer;
/** @var Token|null User access token details */
private $token;
/** @var HmacSha1 OAuth 1 signature type used by Twitter */
private $signatureMethod;
/** @var int Number of attempts we made for the request */
private $attempts = 0;
/**
* Constructor
*
* @param string $consumerKey The Application Consumer Key
* @param string $consumerSecret The Application Consumer Secret
* @param string|null $oauthToken The Client Token (optional)
* @param string|null $oauthTokenSecret The Client Token Secret (optional)
*/
public function __construct($consumerKey, $consumerSecret, $oauthToken = null, $oauthTokenSecret = null)
{
$this->resetLastResponse();
$this->signatureMethod = new HmacSha1();
$this->consumer = new Consumer($consumerKey, $consumerSecret);
if (!empty($oauthToken) && !empty($oauthTokenSecret)) {
$this->setOauthToken($oauthToken, $oauthTokenSecret);
}
if (empty($oauthToken) && !empty($oauthTokenSecret)) {
$this->setBearer($oauthTokenSecret);
}
}
/**
* @param string $oauthToken
* @param string $oauthTokenSecret
*/
public function setOauthToken($oauthToken, $oauthTokenSecret)
{
$this->token = new Token($oauthToken, $oauthTokenSecret);
$this->bearer = null;
}
/**
* @param string $oauthTokenSecret
*/
public function setBearer($oauthTokenSecret)
{
$this->bearer = $oauthTokenSecret;
$this->token = null;
}
/**
* @return string|null
*/
public function getLastApiPath()
{
return $this->response->getApiPath();
}
/**
* @return int
*/
public function getLastHttpCode()
{
return $this->response->getHttpCode();
}
/**
* @return array
*/
public function getLastXHeaders()
{
return $this->response->getXHeaders();
}
/**
* @return array|object|null
*/
public function getLastBody()
{
return $this->response->getBody();
}
/**
* Resets the last response cache.
*/
public function resetLastResponse()
{
$this->response = new Response();
}
/**
* Resets the attempts number.
*/
private function resetAttemptsNumber()
{
$this->attempts = 0;
}
/**
* Delays the retries when they're activated.
*/
private function sleepIfNeeded()
{
if ($this->maxRetries && $this->attempts) {
sleep($this->retriesDelay);
}
}
/**
* Make URLs for user browser navigation.
*
* @param string $path
* @param array $parameters
*
* @return string
*/
public function url($path, array $parameters)
{
$this->resetLastResponse();
$this->response->setApiPath($path);
$query = http_build_query($parameters);
return sprintf('%s/%s?%s', self::API_HOST, $path, $query);
}
/**
* Make /oauth/* requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array
* @throws TwitterOAuthException
*/
public function oauth($path, array $parameters = [])
{
$response = [];
$this->resetLastResponse();
$this->response->setApiPath($path);
$url = sprintf('%s/%s', self::API_HOST, $path);
$result = $this->oAuthRequest($url, 'POST', $parameters);
if ($this->getLastHttpCode() != 200) {
throw new TwitterOAuthException($result);
}
parse_str($result, $response);
$this->response->setBody($response);
return $response;
}
/**
* Make /oauth2/* requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function oauth2($path, array $parameters = [])
{
$method = 'POST';
$this->resetLastResponse();
$this->response->setApiPath($path);
$url = sprintf('%s/%s', self::API_HOST, $path);
$request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters);
$authorization = 'Authorization: Basic ' . $this->encodeAppAuthorization($this->consumer);
$result = $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters);
$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
$this->response->setBody($response);
return $response;
}
/**
* Make GET requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function get($path, array $parameters = [])
{
return $this->http('GET', self::API_HOST, $path, $parameters, false);
}
/**
* Make POST requests to the API.
*
* @param string $path
* @param array $parameters
* @param bool $json
*
* @return array|object
*/
public function post($path, array $parameters = [], $json = false)
{
return $this->http('POST', self::API_HOST, $path, $parameters, $json);
}
/**
* Make DELETE requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function delete($path, array $parameters = [])
{
return $this->http('DELETE', self::API_HOST, $path, $parameters, false);
}
/**
* Make PUT requests to the API.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
public function put($path, array $parameters = [])
{
return $this->http('PUT', self::API_HOST, $path, $parameters, false);
}
/**
* Upload media to upload.twitter.com.
*
* @param string $path
* @param array $parameters
* @param boolean $chunked
*
* @return array|object
*/
public function upload($path, array $parameters = [], $chunked = false)
{
if ($chunked) {
return $this->uploadMediaChunked($path, $parameters);
} else {
return $this->uploadMediaNotChunked($path, $parameters);
}
}
/**
* Progression of media upload
*
* @param string $media_id
*
* @return array|object
*/
public function mediaStatus($media_id)
{
return $this->http('GET', self::UPLOAD_HOST, 'media/upload', [
'command' => 'STATUS',
'media_id' => $media_id
], false);
}
/**
* Private method to upload media (not chunked) to upload.twitter.com.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
private function uploadMediaNotChunked($path, array $parameters)
{
if (! is_readable($parameters['media']) ||
($file = file_get_contents($parameters['media'])) === false) {
throw new \InvalidArgumentException('You must supply a readable file');
}
$parameters['media'] = base64_encode($file);
return $this->http('POST', self::UPLOAD_HOST, $path, $parameters, false);
}
/**
* Private method to upload media (chunked) to upload.twitter.com.
*
* @param string $path
* @param array $parameters
*
* @return array|object
*/
private function uploadMediaChunked($path, array $parameters)
{
$init = $this->http('POST', self::UPLOAD_HOST, $path, $this->mediaInitParameters($parameters), false);
// Append
$segmentIndex = 0;
$media = fopen($parameters['media'], 'rb');
while (!feof($media)) {
$this->http('POST', self::UPLOAD_HOST, 'media/upload', [
'command' => 'APPEND',
'media_id' => $init->media_id_string,
'segment_index' => $segmentIndex++,
'media_data' => base64_encode(fread($media, $this->chunkSize))
], false);
}
fclose($media);
// Finalize
$finalize = $this->http('POST', self::UPLOAD_HOST, 'media/upload', [
'command' => 'FINALIZE',
'media_id' => $init->media_id_string
], false);
return $finalize;
}
/**
* Private method to get params for upload media chunked init.
* Twitter docs: https://dev.twitter.com/rest/reference/post/media/upload-init.html
*
* @param array $parameters
*
* @return array
*/
private function mediaInitParameters(array $parameters)
{
$allowed_keys = ['media_type', 'additional_owners', 'media_category', 'shared'];
$base = [
'command' => 'INIT',
'total_bytes' => filesize($parameters['media'])
];
$allowed_parameters = array_intersect_key($parameters, array_flip($allowed_keys));
return array_merge($base, $allowed_parameters);
}
/**
* Cleanup any parameters that are known not to work.
*
* @param array $parameters
*
* @return array
*/
private function cleanUpParameters(array $parameters)
{
foreach ($parameters as $key => $value) {
// PHP coerces `true` to `"1"` which some Twitter APIs don't like.
if (is_bool($value)) {
$parameters[$key] = var_export($value, true);
}
}
return $parameters;
}
/**
* @param string $method
* @param string $host
* @param string $path
* @param array $parameters
* @param bool $json
*
* @return array|object
*/
private function http($method, $host, $path, array $parameters, $json)
{
$this->resetLastResponse();
$this->resetAttemptsNumber();
$url = sprintf('%s/%s/%s.json', $host, self::API_VERSION, $path);
$this->response->setApiPath($path);
if (!$json) {
$parameters = $this->cleanUpParameters($parameters);
}
return $this->makeRequests($url, $method, $parameters, $json);
}
/**
*
* Make requests and retry them (if enabled) in case of Twitter's problems.
*
* @param string $method
* @param string $url
* @param string $method
* @param array $parameters
* @param bool $json
*
* @return array|object
*/
private function makeRequests($url, $method, array $parameters, $json)
{
do {
$this->sleepIfNeeded();
$result = $this->oAuthRequest($url, $method, $parameters, $json);
$response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
$this->response->setBody($response);
$this->attempts++;
// Retry up to our $maxRetries number if we get errors greater than 500 (over capacity etc)
} while ($this->requestsAvailable());
return $response;
}
/**
* Checks if we have to retry request if API is down.
*
* @return bool
*/
private function requestsAvailable()
{
return ($this->maxRetries && ($this->attempts <= $this->maxRetries) && $this->getLastHttpCode() >= 500);
}
/**
* Format and sign an OAuth / API request
*
* @param string $url
* @param string $method
* @param array $parameters
* @param bool $json
*
* @return string
* @throws TwitterOAuthException
*/
private function oAuthRequest($url, $method, array $parameters, $json = false)
{
$request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters, $json);
if (array_key_exists('oauth_callback', $parameters)) {
// Twitter doesn't like oauth_callback as a parameter.
unset($parameters['oauth_callback']);
}
if ($this->bearer === null) {
$request->signRequest($this->signatureMethod, $this->consumer, $this->token);
$authorization = $request->toHeader();
if (array_key_exists('oauth_verifier', $parameters)) {
// Twitter doesn't always work with oauth in the body and in the header
// and it's already included in the $authorization header
unset($parameters['oauth_verifier']);
}
} else {
$authorization = 'Authorization: Bearer ' . $this->bearer;
}
return $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters, $json);
}
/**
* Set Curl options.
*
* @return array
*/
private function curlOptions()
{
$options = [
// CURLOPT_VERBOSE => true,
CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout,
CURLOPT_HEADER => true,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_SSL_VERIFYHOST => 2,
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_TIMEOUT => $this->timeout,
CURLOPT_USERAGENT => $this->userAgent,
];
if ($this->useCAFile()) {
$options[CURLOPT_CAINFO] = __DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem';
}
if ($this->gzipEncoding) {
$options[CURLOPT_ENCODING] = 'gzip';
}
if (!empty($this->proxy)) {
$options[CURLOPT_PROXY] = $this->proxy['CURLOPT_PROXY'];
$options[CURLOPT_PROXYUSERPWD] = $this->proxy['CURLOPT_PROXYUSERPWD'];
$options[CURLOPT_PROXYPORT] = $this->proxy['CURLOPT_PROXYPORT'];
$options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC;
$options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
}
return $options;
}
/**
* Make an HTTP request
*
* @param string $url
* @param string $method
* @param string $authorization
* @param array $postfields
* @param bool $json
*
* @return string
* @throws TwitterOAuthException
*/
private function request($url, $method, $authorization, array $postfields, $json = false)
{
$options = $this->curlOptions();
$options[CURLOPT_URL] = $url;
$options[CURLOPT_HTTPHEADER] = ['Accept: application/json', $authorization, 'Expect:'];
switch ($method) {
case 'GET':
break;
case 'POST':
$options[CURLOPT_POST] = true;
if ($json) {
$options[CURLOPT_HTTPHEADER][] = 'Content-type: application/json';
$options[CURLOPT_POSTFIELDS] = json_encode($postfields);
} else {
$options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields);
}
break;
case 'DELETE':
$options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
break;
case 'PUT':
$options[CURLOPT_CUSTOMREQUEST] = 'PUT';
break;
}
if (in_array($method, ['GET', 'PUT', 'DELETE']) && !empty($postfields)) {
$options[CURLOPT_URL] .= '?' . Util::buildHttpQuery($postfields);
}
$curlHandle = curl_init();
curl_setopt_array($curlHandle, $options);
$response = curl_exec($curlHandle);
// Throw exceptions on cURL errors.
if (curl_errno($curlHandle) > 0) {
$error = curl_error($curlHandle);
$errorNo = curl_errno($curlHandle);
curl_close($curlHandle);
throw new TwitterOAuthException($error, $errorNo);
}
$this->response->setHttpCode(curl_getinfo($curlHandle, CURLINFO_HTTP_CODE));
$parts = explode("\r\n\r\n", $response);
$responseBody = array_pop($parts);
$responseHeader = array_pop($parts);
$this->response->setHeaders($this->parseHeaders($responseHeader));
curl_close($curlHandle);
return $responseBody;
}
/**
* Get the header info to store.
*
* @param string $header
*
* @return array
*/
private function parseHeaders($header)
{
$headers = [];
foreach (explode("\r\n", $header) as $line) {
if (strpos($line, ':') !== false) {
list ($key, $value) = explode(': ', $line);
$key = str_replace('-', '_', strtolower($key));
$headers[$key] = trim($value);
}
}
return $headers;
}
/**
* Encode application authorization header with base64.
*
* @param Consumer $consumer
*
* @return string
*/
private function encodeAppAuthorization(Consumer $consumer)
{
$key = rawurlencode($consumer->key);
$secret = rawurlencode($consumer->secret);
return base64_encode($key . ':' . $secret);
}
/**
* Is the code running from a Phar module.
*
* @return boolean
*/
private function pharRunning()
{
return class_exists('Phar') && \Phar::running(false) !== '';
}
/**
* Use included CA file instead of OS provided list.
*
* @return boolean
*/
private function useCAFile()
{
/* Use CACert file when not in a PHAR file. */
return !$this->pharRunning();
}
}