-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathtwitter.php
2841 lines (2357 loc) · 105 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
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Twitter class
*
* This source file can be used to communicate with Twitter (http://twitter.com)
*
* The class is documented in the file itself. If you find any bugs help me out and report them. Reporting can be done by sending an email to php-twitter-bugs[at]verkoyen[dot]eu.
* If you report a bug, make sure you give me enough information (include your code).
*
* Known Issues
* - oAuthAuthenticate isn't working correctly
*
* Changelog since 2.0.2
* - tested geo*
* - implemented accountUpdateProfileImage
* - implemented accountUpdateProfileBackgroundImage
* - fixed issue with GET and POST (thx to Luiz Felipe)
* - added a way to detect open_basedir (thx to Lee Kindness)
*
* Changelog since 2.0.1
* - Fixed some documentation
* - Added a new method: usersProfileImage
* - Fixed trendsLocation
* - Added new GEO-methods: geoSearch, geoSimilarPlaces, geoPlaceCreate (not tested because geo-services were disabled.)
* - Added legalToS
* - Added legalPrivacy
* - Fixed helpTest
*
* Changelog since 2.0.0
* - no more fatal if twitter is over capacity
* - fix for calculating the header-string (thx to Dextro)
* - fix for userListsIdStatuses (thx to Josh)
*
* License
* Copyright (c) 2010, Tijs Verkoyen. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
* 3. The name of the author may not be used to endorse or promote products derived from this software without specific prior written permission.
*
* This software is provided by the author "as is" and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the author be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
*
* @author Tijs Verkoyen <[email protected]>
* @version 2.0.3
*
* @copyright Copyright (c) 2010, Tijs Verkoyen. All rights reserved.
* @license BSD License
*/
class Twitter
{
// internal constant to enable/disable debugging
const DEBUG = false;
// url for the twitter-api
const API_URL = 'https://api.twitter.com/1';
const SEARCH_API_URL = 'https://search.twitter.com';
const SECURE_API_URL = 'https://api.twitter.com';
// port for the twitter-api
const API_PORT = 443;
const SEARCH_API_PORT = 443;
const SECURE_API_PORT = 443;
// current version
const VERSION = '2.0.3';
/**
* A cURL instance
*
* @var resource
*/
private $curl;
/**
* The consumer key
*
* @var string
*/
private $consumerKey;
/**
* The consumer secret
*
* @var string
*/
private $consumerSecret;
/**
* The oAuth-token
*
* @var string
*/
private $oAuthToken = '';
/**
* The oAuth-token-secret
*
* @var string
*/
private $oAuthTokenSecret = '';
/**
* The timeout
*
* @var int
*/
private $timeOut = 60;
/**
* The user agent
*
* @var string
*/
private $userAgent;
// class methods
/**
* Default constructor
*
* @return void
* @param string $consumerKey The consumer key to use.
* @param string $consumerSecret The consumer secret to use.
*/
public function __construct($consumerKey, $consumerSecret)
{
$this->setConsumerKey($consumerKey);
$this->setConsumerSecret($consumerSecret);
}
/**
* Default destructor
*
* @return void
*/
public function __destruct()
{
if($this->curl != null) curl_close($this->curl);
}
/**
* Format the parameters as a querystring
*
* @return string
* @param array $parameters
*/
private function buildQuery(array $parameters)
{
// no parameters?
if(empty($parameters)) return '';
// encode the keys
$keys = self::urlencode_rfc3986(array_keys($parameters));
// encode the values
$values = self::urlencode_rfc3986(array_values($parameters));
// reset the parameters
$parameters = array_combine($keys, $values);
// sort parameters by key
uksort($parameters, 'strcmp');
// loop parameters
foreach($parameters as $key => $value)
{
// sort by value
if(is_array($value)) $parameters[$key] = natsort($value);
}
// process parameters
foreach($parameters as $key => $value) $chunks[] = $key .'='. str_replace('%25', '%', $value);
// return
return implode('&', $chunks);
}
/**
* All OAuth 1.0 requests use the same basic algorithm for creating a signature base string and a signature.
* The signature base string is composed of the HTTP method being used, followed by an ampersand ("&") and then the URL-encoded base URL being accessed,
* complete with path (but not query parameters), followed by an ampersand ("&").
* Then, you take all query parameters and POST body parameters (when the POST body is of the URL-encoded type, otherwise the POST body is ignored),
* including the OAuth parameters necessary for negotiation with the request at hand, and sort them in lexicographical order by first parameter name and
* then parameter value (for duplicate parameters), all the while ensuring that both the key and the value for each parameter are URL encoded in isolation.
* Instead of using the equals ("=") sign to mark the key/value relationship, you use the URL-encoded form of "%3D". Each parameter is then joined by the
* URL-escaped ampersand sign, "%26".
*
* @return string
* @param string $url
* @param string $method
* @param array $parameters
*/
private function calculateBaseString($url, $method, array $parameters)
{
// redefine
$url = (string) $url;
$parameters = (array) $parameters;
// init var
$pairs = array();
$chunks = array();
// sort parameters by key
uksort($parameters, 'strcmp');
// loop parameters
foreach($parameters as $key => $value)
{
// sort by value
if(is_array($value)) $parameters[$key] = natsort($value);
}
// process queries
foreach($parameters as $key => $value)
{
$chunks[] = self::urlencode_rfc3986($key) .'%3D'. self::urlencode_rfc3986($value);
}
// buils base
$base = $method .'&';
$base .= urlencode($url) .'&';
$base .= implode('%26', $chunks);
// return
return $base;
}
/**
* Build the Authorization header
* @later: fix me
*
* @return string
* @param array $parameters
* @param string $url
*/
private function calculateHeader(array $parameters, $url)
{
// redefine
$url = (string) $url;
// divide into parts
$parts = parse_url($url);
// init var
$chunks = array();
// process queries
foreach($parameters as $key => $value) $chunks[] = str_replace('%25', '%', self::urlencode_rfc3986($key) .'="'. self::urlencode_rfc3986($value) .'"');
// build return
$return = 'Authorization: OAuth realm="' . $parts['scheme'] . '://' . $parts['host'] . $parts['path'] . '", ';
$return .= implode(',', $chunks);
// prepend name and OAuth part
return $return;
}
/**
* Make an call to the oAuth
* @todo refactor me
*
* @return array
* @param string $method
* @param array[optional] $parameters
*/
private function doOAuthCall($method, array $parameters = null)
{
// redefine
$method = (string) $method;
// append default parameters
$parameters['oauth_consumer_key'] = $this->getConsumerKey();
$parameters['oauth_nonce'] = md5(microtime() . rand());
$parameters['oauth_timestamp'] = time();
$parameters['oauth_signature_method'] = 'HMAC-SHA1';
$parameters['oauth_version'] = '1.0';
// calculate the base string
$base = $this->calculateBaseString(self::SECURE_API_URL .'/oauth/'. $method, 'POST', $parameters);
// add sign into the parameters
$parameters['oauth_signature'] = $this->hmacsha1($this->getConsumerSecret() .'&' . $this->getOAuthTokenSecret(), $base);
// calculate header
$header = $this->calculateHeader($parameters, self::SECURE_API_URL .'/oauth/'. $method);
// set options
$options[CURLOPT_URL] = self::SECURE_API_URL .'/oauth/'. $method;
$options[CURLOPT_PORT] = self::SECURE_API_PORT;
$options[CURLOPT_USERAGENT] = $this->getUserAgent();
if(ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) $options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_SSL_VERIFYHOST] = false;
$options[CURLOPT_HTTPHEADER] = array('Expect:');
$options[CURLOPT_POST] = true;
$options[CURLOPT_POSTFIELDS] = $this->buildQuery($parameters);
// init
$this->curl = curl_init();
// set options
curl_setopt_array($this->curl, $options);
// execute
$response = curl_exec($this->curl);
$headers = curl_getinfo($this->curl);
// fetch errors
$errorNumber = curl_errno($this->curl);
$errorMessage = curl_error($this->curl);
// error?
if($errorNumber != '') throw new TwitterException($errorMessage, $errorNumber);
// init var
$return = array();
// parse the string
parse_str($response, $return);
// return
return $return;
}
/**
* Make the call
*
* @return string
* @param string $url The url to call.
* @param array[optiona] $parameters Optional parameters.
* @param bool[optional] $authenticate Should we authenticate.
* @param bool[optional] $method The method to use. Possible values are GET, POST.
* @param string[optional] $filePath The path to the file to upload.
* @param bool[optional] $expectJSON Do we expect JSON.
* @param bool[optional] $returnHeaders Should the headers be returned?
*/
private function doCall($url, array $parameters = null, $authenticate = false, $method = 'GET', $filePath = null, $expectJSON = true, $returnHeaders = false)
{
// allowed methods
$allowedMethods = array('GET', 'POST');
// redefine
$url = (string) $url;
$parameters = (array) $parameters;
$authenticate = (bool) $authenticate;
$method = (string) $method;
$expectJSON = (bool) $expectJSON;
// validate method
if(!in_array($method, $allowedMethods)) throw new TwitterException('Unknown method ('. $method .'). Allowed methods are: '. implode(', ', $allowedMethods));
// append default parameters
$oauth['oauth_consumer_key'] = $this->getConsumerKey();
$oauth['oauth_nonce'] = md5(microtime() . rand());
$oauth['oauth_timestamp'] = time();
$oauth['oauth_token'] = $this->getOAuthToken();
$oauth['oauth_signature_method'] = 'HMAC-SHA1';
$oauth['oauth_version'] = '1.0';
// set data
$data = $oauth;
if(!empty($parameters)) $data = array_merge($data, $parameters);
// based on the method, we should handle the parameters in a different way
if($method == 'POST')
{
// file provided?
if($filePath != null)
{
// build a boundary
$boundary = md5(time());
// process file
$fileInfo = pathinfo($filePath);
// set mimeType
$mimeType = 'application/octet-stream';
if($fileInfo['extension'] == 'jpg' || $fileInfo['extension'] == 'jpeg') $mimeType = 'image/jpeg';
elseif($fileInfo['extension'] == 'gif') $mimeType = 'image/gif';
elseif($fileInfo['extension'] == 'png') $mimeType = 'image/png';
// init var
$content = '--'. $boundary ."\r\n";
// set file
$content .= 'Content-Disposition: form-data; name=image; filename="'. $fileInfo['basename'] .'"' ."\r\n";
$content .= 'Content-Type: '. $mimeType ."\r\n";
$content .= "\r\n";
$content .= file_get_contents($filePath);
$content .="\r\n";
$content .="--". $boundary .'--';
// build headers
$headers[] = 'Content-Type: multipart/form-data; boundary='. $boundary;
$headers[] = 'Content-Length: '. strlen($content);
// set content
$options[CURLOPT_POSTFIELDS] = $content;
}
// no file
else $options[CURLOPT_POSTFIELDS] = $this->buildQuery($parameters);
// enable post
$options[CURLOPT_POST] = true;
}
else
{
// add the parameters into the querystring
if(!empty($parameters)) $url .= '?'. $this->buildQuery($parameters);
$options[CURLOPT_POST] = false;
}
// calculate the base string
$base = $this->calculateBaseString(self::API_URL .'/'. $url, $method, $data);
// add sign into the parameters
$oauth['oauth_signature'] = $this->hmacsha1($this->getConsumerSecret() .'&' . $this->getOAuthTokenSecret(), $base);
$headers[] = $this->calculateHeader($oauth, self::API_URL .'/'. $url);
$headers[] = 'Expect:';
// set options
$options[CURLOPT_URL] = self::API_URL .'/'. $url;
$options[CURLOPT_PORT] = self::API_PORT;
$options[CURLOPT_USERAGENT] = $this->getUserAgent();
if(ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) $options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_SSL_VERIFYHOST] = false;
$options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
$options[CURLOPT_HTTPHEADER] = $headers;
// init
if($this->curl == null) $this->curl = curl_init();
// set options
curl_setopt_array($this->curl, $options);
// execute
$response = curl_exec($this->curl);
$headers = curl_getinfo($this->curl);
// fetch errors
$errorNumber = curl_errno($this->curl);
$errorMessage = curl_error($this->curl);
// return the headers
if($returnHeaders) return $headers;
// we don't expext JSON, return the response
if(!$expectJSON) return $response;
// replace ids with their string values, added because of some PHP-version can't handle these large values
$response = preg_replace('/id":(\d+)/', 'id":"\1"', $response);
// we expect JSON, so decode it
$json = @json_decode($response, true);
// validate JSON
if($json === null)
{
// should we provide debug information
if(self::DEBUG)
{
// make it output proper
echo '<pre>';
// dump the header-information
var_dump($headers);
// dump the error
var_dump($errorMessage);
// dump the raw response
var_dump($response);
// end proper format
echo '</pre>';
}
// throw exception
throw new TwitterException('Invalid response.');
}
// any errors
if(isset($json['errors']))
{
// should we provide debug information
if(self::DEBUG)
{
// make it output proper
echo '<pre>';
// dump the header-information
var_dump($headers);
// dump the error
var_dump($errorMessage);
// dump the raw response
var_dump($response);
// end proper format
echo '</pre>';
}
// throw exception
if(isset($json['errors'][0]['message'])) throw new TwitterException($json['errors'][0]['message']);
else throw new TwitterException('Invalid response.');
}
// any error
if(isset($json['error']))
{
// should we provide debug information
if(self::DEBUG)
{
// make it output proper
echo '<pre>';
// dump the header-information
var_dump($headers);
// dump the raw response
var_dump($response);
// end proper format
echo '</pre>';
}
// throw exception
throw new TwitterException($json['error']);
}
// return
return $json;
}
/**
* Make the call
*
* @return string
* @param string $url The url to call.
* @param array[optiona] $parameters Optional parameters.
*/
private function doSearchCall($url, array $parameters = null)
{
// redefine
$url = (string) $url;
$parameters = (array) $parameters;
// add the parameters into the querystring
if(!empty($parameters)) $url .= '?'. $this->buildQuery($parameters);
// set options
$options[CURLOPT_URL] = self::SEARCH_API_URL .'/'. $url;
$options[CURLOPT_PORT] = self::SEARCH_API_PORT;
$options[CURLOPT_USERAGENT] = $this->getUserAgent();
if(ini_get('open_basedir') == '' && ini_get('safe_mode' == 'Off')) $options[CURLOPT_FOLLOWLOCATION] = true;
$options[CURLOPT_RETURNTRANSFER] = true;
$options[CURLOPT_TIMEOUT] = (int) $this->getTimeOut();
$options[CURLOPT_SSL_VERIFYPEER] = false;
$options[CURLOPT_SSL_VERIFYHOST] = false;
$options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
// init
if($this->curl == null) $this->curl = curl_init();
// set options
curl_setopt_array($this->curl, $options);
// execute
$response = curl_exec($this->curl);
$headers = curl_getinfo($this->curl);
// fetch errors
$errorNumber = curl_errno($this->curl);
$errorMessage = curl_error($this->curl);
// replace ids with their string values, added because of some PHP-version can't handle these large values
$response = preg_replace('/id":(\d+)/', 'id":"\1"', $response);
// we expect JSON, so decode it
$json = @json_decode($response, true);
// validate JSON
if($json === null)
{
// should we provide debug information
if(self::DEBUG)
{
// make it output proper
echo '<pre>';
// dump the header-information
var_dump($headers);
// dump the error
var_dump($errorMessage);
// dump the raw response
var_dump($response);
// end proper format
echo '</pre>';
}
// throw exception
throw new TwitterException('Invalid response.');
}
// any errors
if(isset($json['errors']))
{
// should we provide debug information
if(self::DEBUG)
{
// make it output proper
echo '<pre>';
// dump the header-information
var_dump($headers);
// dump the error
var_dump($errorMessage);
// dump the raw response
var_dump($response);
// end proper format
echo '</pre>';
}
// throw exception
if(isset($json['errors'][0]['message'])) throw new TwitterException($json['errors'][0]['message']);
else throw new TwitterException('Invalid response.');
}
// any error
if(isset($json['error']))
{
// should we provide debug information
if(self::DEBUG)
{
// make it output proper
echo '<pre>';
// dump the header-information
var_dump($headers);
// dump the raw response
var_dump($response);
// end proper format
echo '</pre>';
}
// throw exception
throw new TwitterException($json['error']);
}
// return
return $json;
}
/**
* Get the consumer key
*
* @return string
*/
private function getConsumerKey()
{
return $this->consumerKey;
}
/**
* Get the consumer secret
*
* @return string
*/
private function getConsumerSecret()
{
return $this->consumerSecret;
}
/**
* Get the oAuth-token
*
* @return string
*/
private function getOAuthToken()
{
return $this->oAuthToken;
}
/**
* Get the oAuth-token-secret
*
* @return string
*/
private function getOAuthTokenSecret()
{
return $this->oAuthTokenSecret;
}
/**
* Get the timeout
*
* @return int
*/
public function getTimeOut()
{
return (int) $this->timeOut;
}
/**
* Get the useragent that will be used. Our version will be prepended to yours.
* It will look like: "PHP Twitter/<version> <your-user-agent>"
*
* @return string
*/
public function getUserAgent()
{
return (string) 'PHP Twitter/'. self::VERSION .' '. $this->userAgent;
}
/**
* Set the consumer key
*
* @return void
* @param string $key The consumer key to use.
*/
private function setConsumerKey($key)
{
$this->consumerKey = (string) $key;
}
/**
* Set the consumer secret
*
* @return void
* @param string $secret The consumer secret to use.
*/
private function setConsumerSecret($secret)
{
$this->consumerSecret = (string) $secret;
}
/**
* Set the oAuth-token
*
* @return void
* @param string $token The token to use.
*/
public function setOAuthToken($token)
{
$this->oAuthToken = (string) $token;
}
/**
* Set the oAuth-secret
*
* @return void
* @param string $secret The secret to use.
*/
public function setOAuthTokenSecret($secret)
{
$this->oAuthTokenSecret = (string) $secret;
}
/**
* Set the timeout
*
* @return void
* @param int $seconds The timeout in seconds
*/
public function setTimeOut($seconds)
{
$this->timeOut = (int) $seconds;
}
/**
* Get the useragent that will be used. Our version will be prepended to yours.
* It will look like: "PHP Twitter/<version> <your-user-agent>"
*
* @return void
* @param string $userAgent Your user-agent, it should look like <app-name>/<app-version>
*/
public function setUserAgent($userAgent)
{
$this->userAgent = (string) $userAgent;
}
/**
* Build the signature for the data
*
* @return string
* @param string $key The key to use for signing.
* @param string $data The data that has to be signed.
*/
private function hmacsha1($key, $data)
{
return base64_encode(hash_hmac('SHA1', $data, $key, true));
}
/**
* URL-encode method for internatl use
*
* @return string
* @param mixed $value The value to encode.
*/
private static function urlencode_rfc3986($value)
{
if(is_array($value)) return array_map(array('Twitter', 'urlencode_rfc3986'), $value);
else
{
$search = array('+', ' ', '%7E', '%');
$replace = array('%20', '%20', '~', '%25');
return str_replace($search, $replace, urlencode($value));
}
}
// Timeline resources
/**
* Returns the 20 most recent statuses from non-protected users who have set a custom user icon.
* The public timeline is cached for 60 seconds and requesting it more often than that is unproductive and a waste of resources.
*
* @return array
* @param bool[optional] $skipUser When true each tweet returned in a timeline will not contain an entire user object. Instead, the user node will contain only an id element to indicate the numerical ID of the Twitter user that set the status.
*/
public function statusesPublicTimeline($skipUser = false)
{
// redefine
$skipUser = (bool) $skipUser;
// build parameters
$parameters = array();
if($skipUser) $parameters['skip_user'] = 'true';
// make the call
return (array) $this->doCall('statuses/public_timeline.json', $parameters);
}
/**
* Returns the 20 most recent statuses posted by the authenticating user and that user's friends. This is the equivalent of /timeline/home on the Web.
*
* @return array
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param int[optional] $count Specifies the number of records to retrieve. May not be greater than 200.
* @param int[optional] $page Specifies the page of results to retrieve.
* @param bool[optional] $skipUser When true each tweet returned in a timeline will not contain an entire user object. Instead, the user node will contain only an id element to indicate the numerical ID of the Twitter user that set the status.
*/
public function statusesHomeTimeline($sinceId = null, $maxId = null, $count = null, $page = null, $skipUser = false)
{
// redefine
$skipUser = (bool) $skipUser;
// build parameters
$parameters = array();
if($sinceId != null) $parameters['since_id'] = (string) $sinceId;
if($maxId != null) $parameters['max_id'] = (string) $maxId;
if($count != null) $parameters['count'] = (int) $count;
if($page != null) $parameters['page'] = (int) $page;
if($skipUser) $parameters['skip_user'] = 'true';
// make the call
return (array) $this->doCall('statuses/home_timeline.json', $parameters, true);
}
/**
* Returns the 20 most recent statuses, including retweets, posted by the authenticating user and that user's friends.
* This is the equivalent of /timeline/home on the Web.
*
* Usage note: This home_timeline call is identical to statuses/friends_timeline, except that home_timeline also contains retweets, while statuses/friends_timeline does not for backwards compatibility reasons.
* In a future version of the API, statuses/friends_timeline will be deprected and replaced by home_timeline.
*
* @return array
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param int[optional] $count Specifies the number of records to retrieve. May not be greater than 200.
* @param int[optional] $page Specifies the page of results to retrieve.
* @param bool[optional] $skipUser When true each tweet returned in a timeline will not contain an entire user object. Instead, the user node will contain only an id element to indicate the numerical ID of the Twitter user that set the status.
*/
public function statusesFriendsTimeline($sinceId = null, $maxId = null, $count = null, $page = null, $skipUser = false)
{
// redefine
$skipUser = (bool) $skipUser;
// build parameters
$parameters = array();
if($sinceId != null) $parameters['since_id'] = (string) $sinceId;
if($maxId != null) $parameters['max_id'] = (string) $maxId;
if($count != null) $parameters['count'] = (int) $count;
if($page != null) $parameters['page'] = (int) $page;
if($skipUser) $parameters['skip_user'] = 'true';
// make the call
return (array) $this->doCall('statuses/friends_timeline.json', $parameters, true);
}
/**
* Returns the 20 most recent statuses posted from the authenticating user. It's also possible to request another user's timeline via the id parameter.
* This is the equivalent of the Web / page for your own user, or the profile page for a third party.
*
* For backwards compatibility reasons, retweets are stripped out of the user_timeline when calling in XML or JSON (they appear with 'RT' in RSS and Atom).
* If you'd like them included, you can merge them in from statuses retweeted_by_me.
*
* @return array
* @param string[optional] $id Specifies the ID or screen name of the user for whom to return results for.
* @param string[optional] $userId Specfies the ID of the user for whom to return results for. Helpful for disambiguating when a valid user ID is also a valid screen name.
* @param string[optional] $screenName Specfies the screen name of the user for whom to return results for. Helpful for disambiguating when a valid screen name is also a user ID.
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param int[optional] $count Specifies the number of records to retrieve. May not be greater than 200.
* @param int[optional] $page Specifies the page of results to retrieve.
* @param bool[optional] $skipUser When true each tweet returned in a timeline will not contain an entire user object. Instead, the user node will contain only an id element to indicate the numerical ID of the Twitter user that set the status.
*/
public function statusesUserTimeline($id = null, $userId = null, $screenName = null, $sinceId = null, $maxId = null, $count = null, $page = null, $skipUser = false)
{
// redefine
$skipUser = (bool) $skipUser;
// build parameters
$parameters = array();
if($id != null) $parameters['id'] = (string) $id;
if($userId != null) $parameters['user_id'] = (string) $userId;
if($screenName != null) $parameters['screen_name'] = (string) $screenName;
if($sinceId != null) $parameters['since_id'] = (string) $sinceId;
if($maxId != null) $parameters['max_id'] = (string) $maxId;
if($count != null) $parameters['count'] = (int) $count;
if($page != null) $parameters['page'] = (int) $page;
if($skipUser) $parameters['skip_user'] = 'true';
// make the call
return (array) $this->doCall('statuses/user_timeline.json', $parameters, true);
}
/**
* Returns the 20 most recent mentions (status containing @username) for the authenticating user.
*
* @return array
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param int[optional] $count Specifies the number of records to retrieve. May not be greater than 200.
* @param int[optional] $page Specifies the page of results to retrieve.
*/
public function statusesMentions($sinceId = null, $maxId = null, $count = null, $page = null)
{
// validate
if($count != null && $count > 200) throw new TwitterException('Count may not be greater than 200.');
// build parameters
$parameters = array();