/
Twitter.php
executable file
·779 lines (625 loc) · 20.3 KB
/
Twitter.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
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
<?php
/**
* This class will handle all interactions between itself and Twitter API
* including the OAuth flow.
*
* @package PHPTwitter
**/
class Twitter {
/**
* Consumer tokens
* @var OAuthToken
**/
protected $consumer;
/**
* Request Tokens
* @var OAuthToken
**/
protected $request;
/**
* Access Tokens
* @var OAuthToken
**/
protected $access;
/**
* OAuth Verification key sent back by the API.
* @var string
**/
protected $oAuthVerifier;
/**
* Twitter endpoint
* @var string URL
**/
protected $endPoint = "https://api.twitter.com/";
/**
* Twitter OAuth Version
* @var string
**/
protected $oAuthVersion = "1.0";
/**
* Oauth Signature method
* @var string
**/
protected $oAuthSignatureMethod = "HMAC-SHA1";
/**
* Oauth callback. This will default to the current link if not set.
* @var string URL
**/
protected $oAuthCallback;
/**
* Oauth random generated token. Populated by Twitter::getOAuthNonce
* @var string
**/
protected $oAuthNonce;
/**
* Stores the current oauth timestamp
* @var int
**/
protected $oAuthTimestamp;
/**
* Generated signature for our OAuth request. This is generated by signRequest().
* @var string
**/
protected $oAuthSignature;
/**
* Whether or not we're using a secure connection.
* @var boolean
**/
protected $ssl = true;
/**
* The CA info file path
* @var string - file path
**/
protected $caInfo;
/**
* Sets the firectory of the caInfo file.
* @var string - directory path
**/
protected $caPath;
/**
* Curl options
* @var array
**/
protected $curlOpts = array();
/**
* HTTP Headers
* @var array
**/
protected $headers = array();
/**
* User agent string.
* @var string
**/
protected $userAgent = "PHPTwitter";
/**
* Store the current users id and screen name
* @var array
**/
protected $user = array();
/**
* Parses parameters (usually tokens) from a response body.
*
* @example
* oauth_token=123456789&oauth_token_secret=987654321
* Array(
* oauth_token => 123456789,
* oauth_token_secret => 987654321,
* etc...
* )
*
* @return array
**/
public static function parse_params($string) {
// Parse the body to retreive the request tokens.
$arr = explode("&", $string);
// Set the request tokens into a key => param structure.
$params = array();
foreach($arr as $param) {
list($key, $value) = explode("=", $param);
$params[$key] = $value;
}
return $params;
}
/**
* Initiate our Twitter class
* @param
**/
public function __construct($consumerKey, $consumerSecret, $accessToken = null, $accessSecret = null) {
// Load dependancies
require_once("OAuthToken.php");
require_once("CurlResponse.php");
$this->consumer = new OAuthToken($consumerKey, $consumerSecret);
$this->request = new OAuthToken(null, null);
$this->access = new OAuthToken($accessToken, $accessSecret);
// Set the default locations of the certificates
$this->setCAPath(rtrim(dirname(__FILE__), "/"));
$this->setCAInfo(rtrim($this->getCAPath(), "/") . "/cacert.pem");
}
/**
* Check to see if we have access to the current account.
* @todo verify the access tokens.
* @return boolean
**/
public function hasAccess() {
if($this->access()->token != null && $this->access()->secret != null)
return true;
return false;
}
/**
* OAuth Flow - Step 1...
* Attempt to obtain a request token from the API.
* @return OAuthToken or false on fail
**/
public function getRequestToken() {
// If we've already got a tokens, return them.
if($this->request()->token != null && $this->request()->secret != null)
return $this->request();
// Make the api request.
$result = $this->api("oauth/request_token", "POST");
if($result->statusCode() == 200) {
$params = self::parse_params($result->body());
// Now we've got our params in a usable state, we'll set them and continue with the oauth flow.
if(isset($params['oauth_token'], $params['oauth_token_secret'])) {
$this->setRequest(new OAuthToken($params['oauth_token'], $params['oauth_token_secret']));
return $this->request();
}
}
return false;
}
/**
* Oauth Flow - Step 2...
* Return the login URL to the user so they can grant access to the application.
* @return string URL or false on fail
**/
public function getLoginURL() {
if($this->request()->token != null && $this->request()->secret != null)
return $this->getEndPoint() . "oauth/authorize?oauth_token=" . rawurlencode($this->request()->token);
return false;
}
/**
* OAuth Flow - Step 3...
* We will attempt to complete the oauth flow by obtaining an Access Token
* @return OAuthToken or false on fail
**/
public function getAccessToken() {
// Check for current access token.
if($this->hasAccess())
return $this->access();
// Attempt to retreive the access user from twitter if we have the oauth verifier.
if($this->getOAuthVerifier()) {
$result = $this->api("oauth/access_token", "POST", array(
"oauth_verifier" => $this->getOAuthVerifier()
));
// Parse parameters
$params = self::parse_params($result->body());
if(isset($params['oauth_token'], $params['oauth_token_secret'])) {
$this->setAccess(new OAuthToken($params['oauth_token'], $params['oauth_token_secret']));
return $this->access();
}
}
return false;
}
/**
* Sends an HTTP Request to the API endpoint.
* @param $request - API request
* @param $method - HTTP Method - default: GET
* @param $params array - HTTP Query parameters
* @return CurlResponse
**/
public function api($request, $method = "GET", $params = array()) {
// Sign the current request with the Authorization header.
$this->signRequest($request, $method, $params);
$url = $this->getRequestURL($request, $method, $params);
// Setup curl options
$this->curlOpts += array(
CURLOPT_URL => $this->getRequestURL($request, $method, $params),
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HEADER => false,
CURLOPT_USERAGENT => $this->getUserAgent(),
CURLINFO_HEADER_OUT => true
);
switch($method) {
case 'POST':
$this->curlOpts += array(
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => (is_array($params) && !empty($params)) ? http_build_query($params) : null
);
break;
case 'GET':
default:
$this->curlOpts += array(
CURLOPT_HTTPGET => true
);
}
// Set SSL values
if($this->isSSL() && $this->getCAInfo() && $this->getCAPath()) {
$this->curlOpts += array(
CURLOPT_SSL_VERIFYPEER => true,
CURLOPT_SSL_VERIFYHOST => true,
CURLOPT_CAINFO => $this->getCAInfo(),
CURLOPT_CAPATH => $this->getCAPath()
);
}
// Setup Curl
$ch = curl_init();
// Set curl options
curl_setopt_array($ch, $this->curlOpts);
// add headers
curl_setopt($ch, CURLOPT_HTTPHEADER, $this->getHeaders());
// execute the curl request
$response = new CurlResponse($ch);
// Clean this request, ready for the next one.
$this->curlOpts = array();
return $response;
}
/**
* Returns an array of headers to send to the api endpoint
* @param $request string - API Requets (subURL)
* @params $method string - HTTP method (ie GET, POST etc..)
* @return array
**/
public function signRequest($request, $method, $params) {
if($this->getOAuthSignatureMethod() == "HMAC-SHA1") {
$headers = array();
// We'll build up and calculate the signature, then add it into the Authorization header.
$signingParams = array(
"oauth_nonce" => $this->getOAuthNonce(),
"oauth_signature_method" => $this->getOAuthSignatureMethod(),
"oauth_timestamp" => $this->getOAuthTimestamp(),
"oauth_consumer_key" => $this->consumer()->token,
"oauth_version" => $this->getOAuthVersion()
);
// If we have access, add the oauth_token to the signing params
if($this->hasAccess()) {
$signingParams['oauth_token'] = $this->access()->token;
} else {
$signingParams['oauth_callback'] = $this->getOAuthCallback();
}
// Make a copy of this so we can add base string params without affecting signing params.
$baseStringParams = array_merge($signingParams, $params);
// Build the oauth signature out of our signing parameters.
$signingParams['oauth_signature'] = base64_encode(
hash_hmac(
'sha1',
$baseString = $this->getOAuthBaseString($request, $method, $baseStringParams, $params),
$this->getOAuthSigningKey(),
true
)
);
$this->oAuthSignature = $signingParams['oauth_signature'];
// If we have a request token, add that to our signing params
if($this->request()->token && !$this->hasAccess()) $signingParams['oauth_token'] = $this->request()->token;
ksort($signingParams);
// Now build the Authorization header string.
$headers["Authorization"] = "Authorization: OAuth ";
foreach($signingParams as $k => $v)
$headers["Authorization"] .= rawurlencode($k).'="'.rawurlencode($v).'", ';
$headers["Authorization"] = substr($headers["Authorization"], 0, strlen($headers["Authorization"])-2);
$this->addHeaders($headers);
return $headers;
}
throw new Exception("Only HMAC-SHA1 is a supported signature method");
return array();
}
/**
* This will build up the base string for signing oauth requests.
* @param $request string - API Requets (subURL)
* @param $method string - HTTP method (ie GET, POST etc..)
* @param $signingParams array
* @return string
**/
public function getOAuthBaseString($request, $method, $signingParams, $params) {
ksort($signingParams);
list($requestURL) = explode("?", $this->getRequestURL($request, $method, $params));
$baseString = rawurlencode($method).'&'.rawurlencode($requestURL).'&';
foreach ($signingParams as $k => $v)
$baseString .= rawurlencode(rawurlencode($k).'='.rawurlencode($v).'&');
// Remove the last 3 chars (encoded ampersand (%26)) from our baseString.
$baseString = substr($baseString, 0, strlen($baseString)-3);
return $baseString;
}
/**
* Generate an oauthsigning key from the keys we have so far.
* @return string
**/
public function getOAuthSigningKey() {
$signingKey = rawurlencode($this->consumer()->secret).'&';
// If we have an access token, append its secret to our signing key.
// If not, we will attempt to do the same for the request token secret.
if($this->hasAccess())
$signingKey .= rawurlencode($this->access()->secret);
else if ($this->request()->secret)
$signingKey .= rawurlencode($this->request()->secret);
return $signingKey;
}
/**
* Get the current twitter user.
* This calls account/verify_credentials {@link https://dev.twitter.com/docs/api/1.1/get/account/verify_credentials}
* @return array
**/
public function getUser() {
if(!empty($this->user))
return (array) $this->user;
// We haven't already set the user. See if we have access to retreive the current user.
if($this->hasAccess()) {
$result = $this->api("1.1/account/verify_credentials.json");
if($result->statusCode() == 200)
$this->user = json_decode($result->body(), true);
}
return $this->user;
}
public function setUser($id, $screen_name) {
$this->user = array(
"id" => (string) $id, // This must be a string to deal with 64-bit integers on 32-bit systems
"screen_name" => (string) $screen_name
);
}
/**
* Returns the consumer keys.
* @return OAuthToken
**/
public function consumer() {
return $this->consumer;
}
/**
* Sets the current consumer keys
* @param $consumer OAuthToken
**/
public function setConsumer(OAuthToken $consumer) {
$this->consumer = $consumer;
}
/**
* Returns the current request keys
* @return OAuthToken
**/
public function request() {
return $this->request;
}
/**
* Set request keys
* @param $request OAuthToken
**/
public function setRequest(OauthToken $request) {
$this->request = $request;
}
/**
* Returns the current access keys
* @return OAuthToken
**/
public function access() {
return $this->access;
}
/**
* Sets the current access tokens
* @param $access OAuthToken
**/
public function setAccess(OAuthToken $access) {
$this->access = $access;
}
/**
* Get the current oauth verifier
* @return string
**/
public function getOAuthVerifier() {
// If we've already got a verifier, return it.
if($this->oAuthVerifier)
return $this->oAuthVerifier;
// Attempt to gain the verifier from the current http request.
if(isset($_GET['oauth_verifier']))
return $this->oAuthVerifier = (string) $_GET['oauth_verifier'];
return false;
}
/**
* Set the current oauth verifier
* @param $verifier string
**/
public function setOAuthVerifier($verifier) {
$this->oAuthVerifier = (string) $verifier;
}
/**
* Get the current API endpoint
* @return string URL
**/
public function getEndPoint() {
return (string) $this->endPoint;
}
/**
* Set the current API endpoint
* @param $endPoint string URL
**/
public function setEndPoint($endPoint) {
$this->endPoint = (string) $endPoint;
}
/**
* Builds up the request URL
* @param $request string - API subURL string
* @param $method string - HTTP Method
* @param $params array - query parameters
* @return string URL
**/
public function getRequestURL($request, $method = "GET", $params = array()) {
// Parse the request url.
$url = parse_url(rtrim($this->getEndPoint(), "/") . "/" . ltrim($request, "/"));
$query = isset($url['query']) ? self::parse_params($url['query']) : array();
if($method == "GET") {
$url['query'] = array_merge($query, $params);
} else if ($method == "POST") {
$url['query'] = $query;
}
ksort($url['query']);
if(!empty($url['query']))
$url['query'] = http_build_query($url['query']);
else
$url['query'] = null;
// Build the URL
$requestURL = $url['scheme'] . "://" . $url['host'] . $url['path'];
if(isset($url['query']) && trim($url['query']) != "")
$requestURL .= "?" . $url['query'];
return $requestURL;
}
/**
* Gets and returns the current oauth version
* @return string
**/
public function getOAuthVersion() {
return $this->oAuthVersion;
}
/**
* Set the current oauth version
* @param $version string
**/
public function setOAuthVersion($version) {
$this->oAuthVersion = (string) $version;
}
/**
* Get the current oauth signature method.
* @return string
**/
public function getOAuthSignatureMethod() {
return $this->oAuthSignatureMethod;
}
/**
* Set the current oauth signature method.
* @param $method string
**/
public function setOAuthSignatureMethod($method) {
$this->oAuthSignatureMethod = (string) $method;
}
/**
* Returns the current oauth callback. defaults to current link is not set.
* @return string URL
**/
public function getOAuthCallback() {
if(!$this->oAuthCallback) {
$scheme = (array_key_exists("HTTPS", $_SERVER) && $_SERVER['HTTPS']) ? "https://" : "http://";
$this->oAuthCallback = $scheme . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
return $this->oAuthCallback;
}
/**
* Set the current oauth callback
* @param $url string URL
**/
public function setOAuthCallback($url) {
$this->oAuthCallback = (string) $url;
}
/**
* Generates a random token to be used only once.
* @return string
**/
public function getOAuthNonce() {
// If we've already generated one, just return that one.
if($this->oAuthNonce)
return $this->oAuthNonce;
return $this->oAuthNonce = md5(microtime());
}
/**
* Sets the current oauth nonce.
* @param $strgin string
**/
public function setOAuthNonce($string) {
$this->oAuthNonce = (string) $string;
}
/**
* Returns the current timestamp. This can be faked by using setOAuthTimestamp.
* @return int
**/
public function getOAuthTimestamp() {
if($this->oAuthTimestamp)
return $this->oAuthTimestamp;
return time();
}
/**
* Set the current oauth timestamp.
* @param $timestamp
**/
public function setOAuthTimestamp($timestamp) {
$this->oAuthTimestamp = (int) $timestamp;
}
/**
* Gets a list of headers to send with the api request.
* @return array
**/
public function getHeaders() {
return $this->headers;
}
/**
* Add headers to the array
* @param $headers array
**/
public function addHeaders($headers = array()) {
if(!empty($headers))
foreach($headers as $key => $value)
if(is_string($key) && is_string($value))
$this->headers[$key] = $value;
}
/**
* Remove a single header.
* @param $key string
**/
public function clearHeader($key)
{
if(array_key_exists($key, $this->headers))
unset($this->headers[$key]);
}
/**
* Clear all headers.
**/
public function clearAllHeaders()
{
$this->headers = array();
}
/**
* Find whether or not we're sending our requests ofver a secure connection.
* @return boolean
**/
public function isSSL() {
return (bool) $this->ssl;
}
/**
* Set whether ot not to use ssl.
* @param $bool boolean
**/
public function setSSL($bool) {
$this->ssl = (bool) $bool;
}
/**
* Gets the CA Cert
* @return string filepath
**/
public function getCAInfo() {
return (string) $this->caInfo;
}
/**
* Set the location of the cainfo file.
* @param $file string
**/
public function setCAInfo($file) {
$this->caInfo = (string) $file;
}
/**
* Gets the CA Path
* @return string filepath
**/
public function getCAPath() {
return (string) rtrim($this->caPath);
}
/**
* set the directory of the ca info file
* @return string - directory path
**/
public function setCAPath($path) {
$this->caPath = (string) $path;
}
public function getUserAgent() {
return (string) $this->userAgent;
}
/**
* Set the user agent string.
* @param $string string
**/
public function setUserAgent($string) {
$this->userAgent = (string) $string;
}
}
?>