GitHub Access Token became invalid

It seems like the GitHub access token used for retrieving details about this repository from GitHub became invalid. This might prevent certain types of inspections from being run (in particular, everything related to pull requests).
Please ask an admin of your repository to re-new the access token on this website.
Completed
Pull Request — master (#631)
by
unknown
04:50
created

TwitterOAuth::getUpload()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
eloc 2
nc 1
nop 2
1
<?php
2
/**
3
 * The most popular PHP library for use with the Twitter OAuth REST API.
4
 *
5
 * @license MIT
6
 */
7
namespace Abraham\TwitterOAuth;
8
9
use Abraham\TwitterOAuth\Util\JsonDecoder;
10
11
/**
12
 * TwitterOAuth class for interacting with the Twitter API.
13
 *
14
 * @author Abraham Williams <[email protected]>
15
 */
16
class TwitterOAuth extends Config
17
{
18
    const API_VERSION = '1.1';
19
    const API_HOST = 'https://api.twitter.com';
20
    const UPLOAD_HOST = 'https://upload.twitter.com';
21
22
    /** @var Response details about the result of the last request */
23
    private $response;
24
    /** @var string|null Application bearer token */
25
    private $bearer;
26
    /** @var Consumer Twitter application details */
27
    private $consumer;
28
    /** @var Token|null User access token details */
29
    private $token;
30
    /** @var HmacSha1 OAuth 1 signature type used by Twitter */
31
    private $signatureMethod;
32
    /** @var int Number of attempts we made for the request */
33
    private $attempts = 0;
34
35
    /**
36
     * Constructor
37
     *
38
     * @param string      $consumerKey      The Application Consumer Key
39
     * @param string      $consumerSecret   The Application Consumer Secret
40
     * @param string|null $oauthToken       The Client Token (optional)
41
     * @param string|null $oauthTokenSecret The Client Token Secret (optional)
42
     */
43
    public function __construct($consumerKey, $consumerSecret, $oauthToken = null, $oauthTokenSecret = null)
44
    {
45
        $this->resetLastResponse();
46
        $this->signatureMethod = new HmacSha1();
47
        $this->consumer = new Consumer($consumerKey, $consumerSecret);
48
        if (!empty($oauthToken) && !empty($oauthTokenSecret)) {
49
            $this->setOauthToken($oauthToken, $oauthTokenSecret);
50
        }
51
        if (empty($oauthToken) && !empty($oauthTokenSecret)) {
52
            $this->setBearer($oauthTokenSecret);
53
        }
54
    }
55
56
    /**
57
     * @param string $oauthToken
58
     * @param string $oauthTokenSecret
59
     */
60
    public function setOauthToken($oauthToken, $oauthTokenSecret)
61
    {
62
        $this->token = new Token($oauthToken, $oauthTokenSecret);
63
        $this->bearer = null;
64
    }
65
66
    /**
67
     * @param string $oauthTokenSecret
68
     */
69
    public function setBearer($oauthTokenSecret)
70
    {
71
        $this->bearer = $oauthTokenSecret;
72
        $this->token = null;
73
    }
74
75
    /**
76
     * @return string|null
77
     */
78
    public function getLastApiPath()
79
    {
80
        return $this->response->getApiPath();
81
    }
82
83
    /**
84
     * @return int
85
     */
86
    public function getLastHttpCode()
87
    {
88
        return $this->response->getHttpCode();
89
    }
90
91
    /**
92
     * @return array
93
     */
94
    public function getLastXHeaders()
95
    {
96
        return $this->response->getXHeaders();
97
    }
98
99
    /**
100
     * @return array|object|null
101
     */
102
    public function getLastBody()
103
    {
104
        return $this->response->getBody();
105
    }
106
107
    /**
108
     * Resets the last response cache.
109
     */
110
    public function resetLastResponse()
111
    {
112
        $this->response = new Response();
113
    }
114
115
    /**
116
     * Resets the attempts number.
117
     */
118
    private function resetAttemptsNumber()
119
    {
120
        $this->attempts = 0;
121
    }
122
123
    /**
124
     * Delays the retries when they're activated.
125
     */
126
    private function sleepIfNeeded()
127
    {
128
        if ($this->maxRetries && $this->attempts) {
129
            sleep($this->retriesDelay);
130
        }
131
    }
132
133
134
    /**
135
     * Make URLs for user browser navigation.
136
     *
137
     * @param string $path
138
     * @param array  $parameters
139
     *
140
     * @return string
141
     */
142
    public function url($path, array $parameters)
143
    {
144
        $this->resetLastResponse();
145
        $this->response->setApiPath($path);
146
        $query = http_build_query($parameters);
147
        return sprintf('%s/%s?%s', self::API_HOST, $path, $query);
148
    }
149
150
    /**
151
     * Make /oauth/* requests to the API.
152
     *
153
     * @param string $path
154
     * @param array  $parameters
155
     *
156
     * @return array
157
     * @throws TwitterOAuthException
158
     */
159
    public function oauth($path, array $parameters = [])
160
    {
161
        $response = [];
162
        $this->resetLastResponse();
163
        $this->response->setApiPath($path);
164
        $url = sprintf('%s/%s', self::API_HOST, $path);
165
        $result = $this->oAuthRequest($url, 'POST', $parameters);
166
167
        if ($this->getLastHttpCode() != 200) {
168
            throw new TwitterOAuthException($result);
169
        }
170
171
        parse_str($result, $response);
172
        $this->response->setBody($response);
0 ignored issues
show
Bug introduced by
It seems like $response can also be of type null; however, Abraham\TwitterOAuth\Response::setBody() does only seem to accept array|object, maybe add an additional type check?

If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:

/**
 * @return array|string
 */
function returnsDifferentValues($x) {
    if ($x) {
        return 'foo';
    }

    return array();
}

$x = returnsDifferentValues($y);
if (is_array($x)) {
    // $x is an array.
}

If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.

Loading history...
173
174
        return $response;
175
    }
176
177
    /**
178
     * Make /oauth2/* requests to the API.
179
     *
180
     * @param string $path
181
     * @param array  $parameters
182
     *
183
     * @return array|object
184
     */
185
    public function oauth2($path, array $parameters = [])
186
    {
187
        $method = 'POST';
188
        $this->resetLastResponse();
189
        $this->response->setApiPath($path);
190
        $url = sprintf('%s/%s', self::API_HOST, $path);
191
        $request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters);
192
        $authorization = 'Authorization: Basic ' . $this->encodeAppAuthorization($this->consumer);
193
        $result = $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters);
194
        $response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
195
        $this->response->setBody($response);
196
        return $response;
197
    }
198
199
    /**
200
     * Make GET requests to the API.
201
     *
202
     * @param string $path
203
     * @param array  $parameters
204
     *
205
     * @return array|object
206
     */
207
    public function get($path, array $parameters = [])
208
    {
209
        return $this->http('GET', self::API_HOST, $path, $parameters);
210
    }
211
212
    /**
213
     * Make POST requests to the API.
214
     *
215
     * @param string $path
216
     * @param array  $parameters
217
     *
218
     * @return array|object
219
     */
220
    public function post($path, array $parameters = [])
221
    {
222
        return $this->http('POST', self::API_HOST, $path, $parameters);
223
    }
224
225
    /**
226
     * Make DELETE requests to the API.
227
     *
228
     * @param string $path
229
     * @param array  $parameters
230
     *
231
     * @return array|object
232
     */
233
    public function delete($path, array $parameters = [])
234
    {
235
        return $this->http('DELETE', self::API_HOST, $path, $parameters);
236
    }
237
238
    /**
239
     * Make PUT requests to the API.
240
     *
241
     * @param string $path
242
     * @param array  $parameters
243
     *
244
     * @return array|object
245
     */
246
    public function put($path, array $parameters = [])
247
    {
248
        return $this->http('PUT', self::API_HOST, $path, $parameters);
249
    }
250
251
    /**
252
     * Upload media to upload.twitter.com.
253
     *
254
     * @param string $path
255
     * @param array  $parameters
256
     * @param boolean  $chunked
257
     *
258
     * @return array|object
259
     */
260
    public function upload($path, array $parameters = [], $chunked = false)
261
    {
262
        if ($chunked) {
263
            return $this->uploadMediaChunked($path, $parameters);
264
        } else {
265
            return $this->uploadMediaNotChunked($path, $parameters);
266
        }
267
    }
268
269
    /**
270
     * Make GET requests to the Upload API
271
     *
272
     * @param string $path
273
     * @param array $parameters
274
     *
275
     * @return array|object
276
     */
277
    public function getUpload($path, array $parameters = [])
278
    {
279
        return $this->http('GET', self::UPLOAD_HOST, $path, $parameters);
280
    }
281
282
    /**
283
     * Private method to upload media (not chunked) to upload.twitter.com.
284
     *
285
     * @param string $path
286
     * @param array  $parameters
287
     *
288
     * @return array|object
289
     */
290
    private function uploadMediaNotChunked($path, array $parameters)
291
    {
292
        $file = file_get_contents($parameters['media']);
293
        $base = base64_encode($file);
294
        $parameters['media'] = $base;
295
        return $this->http('POST', self::UPLOAD_HOST, $path, $parameters);
296
    }
297
298
    /**
299
     * Private method to upload media (chunked) to upload.twitter.com.
300
     *
301
     * @param string $path
302
     * @param array  $parameters
303
     *
304
     * @return array|object
305
     */
306
    private function uploadMediaChunked($path, array $parameters)
307
    {
308
        $init = $this->http('POST', self::UPLOAD_HOST, $path, $this->mediaInitParameters($parameters));
309
        // Append
310
        $segmentIndex = 0;
311
        $media = fopen($parameters['media'], 'rb');
312
        while (!feof($media)) {
313
            $this->http('POST', self::UPLOAD_HOST, 'media/upload', [
314
                'command' => 'APPEND',
315
                'media_id' => $init->media_id_string,
316
                'segment_index' => $segmentIndex++,
317
                'media_data' => base64_encode(fread($media, $this->chunkSize))
318
            ]);
319
        }
320
        fclose($media);
321
        // Finalize
322
        $finalize = $this->http('POST', self::UPLOAD_HOST, 'media/upload', [
323
            'command' => 'FINALIZE',
324
            'media_id' => $init->media_id_string
325
        ]);
326
        return $finalize;
327
    }
328
329
    /**
330
     * Private method to get params for upload media chunked init.
331
     * Twitter docs: https://dev.twitter.com/rest/reference/post/media/upload-init.html
332
     *
333
     * @param array  $parameters
334
     *
335
     * @return array
336
     */
337
    private function mediaInitParameters(array $parameters)
338
    {
339
        $return = [
340
            'command' => 'INIT',
341
            'media_type' => $parameters['media_type'],
342
            'total_bytes' => filesize($parameters['media'])
343
        ];
344
        if (isset($parameters['additional_owners'])) {
345
            $return['additional_owners'] = $parameters['additional_owners'];
346
        }
347
        if (isset($parameters['media_category'])) {
348
            $return['media_category'] = $parameters['media_category'];
349
        }
350
        return $return;
351
    }
352
353
    /**
354
     * @param string $method
355
     * @param string $host
356
     * @param string $path
357
     * @param array  $parameters
358
     *
359
     * @return array|object
360
     */
361
    private function http($method, $host, $path, array $parameters)
362
    {
363
        $this->resetLastResponse();
364
        $this->resetAttemptsNumber();
365
        $url = sprintf('%s/%s/%s.json', $host, self::API_VERSION, $path);
366
        $this->response->setApiPath($path);
367
        return $this->makeRequests($url, $method, $parameters);
368
    }
369
370
    /**
371
     *
372
     * Make requests and retry them (if enabled) in case of Twitter's problems.
373
     *
374
     * @param string $method
375
     * @param string $url
376
     * @param string $method
377
     * @param array  $parameters
378
     *
379
     * @return array|object
380
     */
381
    private function makeRequests($url, $method, array $parameters)
382
    {
383
        do {
384
            $this->sleepIfNeeded();
385
            $result = $this->oAuthRequest($url, $method, $parameters);
386
            $response = JsonDecoder::decode($result, $this->decodeJsonAsArray);
387
            $this->response->setBody($response);
388
            $this->attempts++;
389
            // Retry up to our $maxRetries number if we get errors greater than 500 (over capacity etc)
390
        } while ($this->requestsAvailable());
391
392
        return $response;
393
    }
394
395
    /**
396
     * Checks if we have to retry request if API is down.
397
     *
398
     * @return bool
399
     */
400
    private function requestsAvailable()
401
    {
402
        return ($this->maxRetries && ($this->attempts <= $this->maxRetries) && $this->getLastHttpCode() >= 500);
403
    }
404
405
    /**
406
     * Format and sign an OAuth / API request
407
     *
408
     * @param string $url
409
     * @param string $method
410
     * @param array  $parameters
411
     *
412
     * @return string
413
     * @throws TwitterOAuthException
414
     */
415
    private function oAuthRequest($url, $method, array $parameters)
416
    {
417
        $request = Request::fromConsumerAndToken($this->consumer, $this->token, $method, $url, $parameters);
418
        if (array_key_exists('oauth_callback', $parameters)) {
419
            // Twitter doesn't like oauth_callback as a parameter.
420
            unset($parameters['oauth_callback']);
421
        }
422
        if ($this->bearer === null) {
423
            $request->signRequest($this->signatureMethod, $this->consumer, $this->token);
424
            $authorization = $request->toHeader();
425
            if (array_key_exists('oauth_verifier', $parameters)) {
426
                // Twitter doesn't always work with oauth in the body and in the header
427
                // and it's already included in the $authorization header
428
                unset($parameters['oauth_verifier']);
429
            }
430
        } else {
431
            $authorization = 'Authorization: Bearer ' . $this->bearer;
432
        }
433
        return $this->request($request->getNormalizedHttpUrl(), $method, $authorization, $parameters);
434
    }
435
436
    /**
437
     * Set Curl options.
438
     *
439
     * @return array
440
     */
441
    private function curlOptions()
442
    {
443
        $options = [
444
            // CURLOPT_VERBOSE => true,
445
            CURLOPT_CONNECTTIMEOUT => $this->connectionTimeout,
446
            CURLOPT_HEADER => true,
447
            CURLOPT_RETURNTRANSFER => true,
448
            CURLOPT_SSL_VERIFYHOST => 2,
449
            CURLOPT_SSL_VERIFYPEER => true,
450
            CURLOPT_TIMEOUT => $this->timeout,
451
            CURLOPT_USERAGENT => $this->userAgent,
452
        ];
453
454
        if ($this->useCAFile()) {
455
            $options[CURLOPT_CAINFO] = __DIR__ . DIRECTORY_SEPARATOR . 'cacert.pem';
456
        }
457
458
        if ($this->gzipEncoding) {
459
            $options[CURLOPT_ENCODING] = 'gzip';
460
        }
461
462
        if (!empty($this->proxy)) {
463
            $options[CURLOPT_PROXY] = $this->proxy['CURLOPT_PROXY'];
464
            $options[CURLOPT_PROXYUSERPWD] = $this->proxy['CURLOPT_PROXYUSERPWD'];
465
            $options[CURLOPT_PROXYPORT] = $this->proxy['CURLOPT_PROXYPORT'];
466
            $options[CURLOPT_PROXYAUTH] = CURLAUTH_BASIC;
467
            $options[CURLOPT_PROXYTYPE] = CURLPROXY_HTTP;
468
        }
469
470
        return $options;
471
    }
472
473
    /**
474
     * Make an HTTP request
475
     *
476
     * @param string $url
477
     * @param string $method
478
     * @param string $authorization
479
     * @param array $postfields
480
     *
481
     * @return string
482
     * @throws TwitterOAuthException
483
     */
484
    private function request($url, $method, $authorization, array $postfields)
485
    {
486
        $options = $this->curlOptions();
487
        $options[CURLOPT_URL] = $url;
488
        $options[CURLOPT_HTTPHEADER] = ['Accept: application/json', $authorization, 'Expect:'];
489
490
        switch ($method) {
491
            case 'GET':
492
                break;
493
            case 'POST':
494
                $options[CURLOPT_POST] = true;
495
                $options[CURLOPT_POSTFIELDS] = Util::buildHttpQuery($postfields);
496
                break;
497
            case 'DELETE':
498
                $options[CURLOPT_CUSTOMREQUEST] = 'DELETE';
499
                break;
500
            case 'PUT':
501
                $options[CURLOPT_CUSTOMREQUEST] = 'PUT';
502
                break;
503
        }
504
505
        if (in_array($method, ['GET', 'PUT', 'DELETE']) && !empty($postfields)) {
506
            $options[CURLOPT_URL] .= '?' . Util::buildHttpQuery($postfields);
507
        }
508
509
510
        $curlHandle = curl_init();
511
        curl_setopt_array($curlHandle, $options);
512
        $response = curl_exec($curlHandle);
513
514
        // Throw exceptions on cURL errors.
515
        if (curl_errno($curlHandle) > 0) {
516
            throw new TwitterOAuthException(curl_error($curlHandle), curl_errno($curlHandle));
517
        }
518
519
        $this->response->setHttpCode(curl_getinfo($curlHandle, CURLINFO_HTTP_CODE));
520
        $parts = explode("\r\n\r\n", $response);
521
        $responseBody = array_pop($parts);
522
        $responseHeader = array_pop($parts);
523
        $this->response->setHeaders($this->parseHeaders($responseHeader));
524
525
        curl_close($curlHandle);
526
527
        return $responseBody;
528
    }
529
530
    /**
531
     * Get the header info to store.
532
     *
533
     * @param string $header
534
     *
535
     * @return array
536
     */
537
    private function parseHeaders($header)
538
    {
539
        $headers = [];
540
        foreach (explode("\r\n", $header) as $line) {
541
            if (strpos($line, ':') !== false) {
542
                list ($key, $value) = explode(': ', $line);
543
                $key = str_replace('-', '_', strtolower($key));
544
                $headers[$key] = trim($value);
545
            }
546
        }
547
        return $headers;
548
    }
549
550
    /**
551
     * Encode application authorization header with base64.
552
     *
553
     * @param Consumer $consumer
554
     *
555
     * @return string
556
     */
557
    private function encodeAppAuthorization(Consumer $consumer)
558
    {
559
        $key = rawurlencode($consumer->key);
560
        $secret = rawurlencode($consumer->secret);
561
        return base64_encode($key . ':' . $secret);
562
    }
563
564
    /**
565
     * Is the code running from a Phar module.
566
     *
567
     * @return boolean
568
     */
569
    private function pharRunning()
570
    {
571
        return class_exists('Phar') && \Phar::running(false) !== '';
572
    }
573
574
    /**
575
     * Use included CA file instead of OS provided list.
576
     *
577
     * @return boolean
578
     */
579
    private function useCAFile()
580
    {
581
        /* Use CACert file when not in a PHAR file. */
582
        return !$this->pharRunning();
583
    }
584
}
585