forked from tijsverkoyen/TwitterOAuth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Twitter.php
executable file
·3234 lines (2913 loc) · 138 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
namespace TijsVerkoyen\Twitter;
/**
* Twitter class
*
* @author Tijs Verkoyen <php-twitter@verkoyen.eu>
* @version 2.3.0
* @copyright Copyright (c), 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.1';
const SECURE_API_URL = 'https://api.twitter.com';
// port for the twitter-api
const API_PORT = 443;
const SECURE_API_PORT = 443;
// current version
const VERSION = '2.3.0';
/**
* 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
*
* @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
*/
public function __destruct()
{
if($this->curl != null) curl_close($this->curl);
}
/**
* Format the parameters as a querystring
*
* @param array $parameters The parameters.
* @return string
*/
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".
*
* @param string $url The URL.
* @param string $method The method to use.
* @param array $parameters The parameters.
* @return string
*/
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) {
// only add if not already in the url
if (substr_count($url, $key . '=' . $value) == 0) {
$chunks[] = self::urlencode_rfc3986($key) . '%3D' .
self::urlencode_rfc3986($value);
}
}
// buils base
$base = $method . '&';
$base .= urlencode($url);
$base .= (substr_count($url, '?')) ? '%26' : '&';
$base .= implode('%26', $chunks);
$base = str_replace('%3F', '&', $base);
// return
return $base;
}
/**
* Build the Authorization header
* @later: fix me
*
* @param array $parameters The parameters.
* @param string $url The URL.
* @return string
*/
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
*
* @param string $method The method.
* @param array[optional] $parameters The parameters.
* @return array
*/
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 Exception($errorMessage, $errorNumber);
}
// init var
$return = array();
// parse the string
parse_str($response, $return);
// return
return $return;
}
/**
* Make the call
*
* @param string $url The url to call.
* @param array[optional] $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?
* @return string
*/
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 Exception(
'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);
// calculate the base string
$base = $this->calculateBaseString(
self::API_URL . '/' . $url, $method, $data
);
// 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;
}
// 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 Exception('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 Exception($json['errors'][0]['message']);
} elseif (isset($json['errors']) && is_string($json['errors'])) {
throw new Exception($json['errors']);
} else throw new Exception('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 Exception($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
*
* @param string $key The consumer key to use.
*/
private function setConsumerKey($key)
{
$this->consumerKey = (string) $key;
}
/**
* Set the consumer secret
*
* @param string $secret The consumer secret to use.
*/
private function setConsumerSecret($secret)
{
$this->consumerSecret = (string) $secret;
}
/**
* Set the oAuth-token
*
* @param string $token The token to use.
*/
public function setOAuthToken($token)
{
$this->oAuthToken = (string) $token;
}
/**
* Set the oAuth-secret
*
* @param string $secret The secret to use.
*/
public function setOAuthTokenSecret($secret)
{
$this->oAuthTokenSecret = (string) $secret;
}
/**
* Set the timeout
*
* @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>"
*
* @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
*
* @param string $key The key to use for signing.
* @param string $data The data that has to be signed.
* @return string
*/
private function hmacsha1($key, $data)
{
return base64_encode(hash_hmac('SHA1', $data, $key, true));
}
/**
* URL-encode method for internal use
*
* @param mixed $value The value to encode.
* @return string
*/
private static function urlencode_rfc3986($value)
{
if (is_array($value)) {
return array_map(array(__CLASS__, '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 mentions (tweets containing a users's @screen_name) for the authenticating user.
* The timeline returned is the equivalent of the one seen when you view your mentions on twitter.com.
* This method can only return up to 800 tweets.
*
* @param int[optional] $count Specifies the number of tweets to try and retrieve, up to a maximum of 200. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if include_rts is not supplied.
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @param bool[optional] $contributorDetails This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included.
* @param bool[optional] $includeEntities The entities node will be disincluded when set to false.
* @return array
*/
public function statusesMentionsTimeline(
$count = null, $sinceId = null, $maxId = null,
$trimUser = null, $contributorDetails = null, $includeEntities = null
)
{
// build parameters
$parameters = null;
$parameters['include_rts'] = 'true';
if ($count != null) {
$parameters['count'] = (int) $count;
}
if ($sinceId != null) {
$parameters['since_id'] = (string) $sinceId;
}
if ($maxId != null) {
$parameters['max_id'] = (string) $maxId;
}
if ($trimUser != null) {
$parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
}
if ($contributorDetails != null) {
$parameters['contributor_details'] = ($contributorDetails) ? 'true' : 'false';
}
if ($includeEntities != null) {
$parameters['include_entities'] = ($includeEntities) ? 'true' : 'false';
}
// make the call
return (array) $this->doCall(
'statuses/mentions_timeline.json',
$parameters, true
);
}
/**
* Returns a collection of the most recent Tweets posted by the user indicated by the screen_name or user_id parameters.
* User timelines belonging to protected users may only be requested when the authenticated user either "owns" the timeline or is an approved follower of the owner.
* The timeline returned is the equivalent of the one seen when you view a user's profile on twitter.com.
* This method can only return up to 3,200 of a user's most recent Tweets. Native retweets of other statuses by the user is included in this total, regardless of whether include_rts is set to false when requesting this resource.
*
* @param string[optional] $userId 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 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. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available.
* @param int[optional] $count Specifies the number of tweets to try and retrieve, up to a maximum of 200 per distinct request. The value of count is best thought of as a limit to the number of tweets to return because suspended or deleted content is removed after the count has been applied. We include retweets in the count, even if include_rts is not supplied.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @param bool[optional] $excludeReplies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets — this is because the count parameter retrieves that many tweets before filtering out retweets and replies.
* @param bool[optional] $contributorDetails This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included.
* @param bool[optional] $includeRts When set to false, the timeline will strip any native retweets (though they will still count toward both the maximal length of the timeline and the slice selected by the count parameter). Note: If you're using the trim_user parameter in conjunction with include_rts, the retweets will still contain a full user object.
* @return array
*/
public function statusesUserTimeline(
$userId = null, $screenName = null, $sinceId = null, $count = null,
$maxId = null, $trimUser = null, $excludeReplies = null,
$contributorDetails = null, $includeRts = null
)
{
// build parameters
$parameters = null;
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 ($count != null) {
$parameters['count'] = (int) $count;
}
if ($maxId != null) {
$parameters['max_id'] = (string) $maxId;
}
if ($trimUser != null) {
$parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
}
if ($excludeReplies != null) {
$parameters['exclude_replies'] = ($excludeReplies) ? 'true' : 'false';
}
if ($contributorDetails != null) {
$parameters['contributor_details'] = ($contributorDetails) ? 'true' : 'false';
}
if ($includeRts != null) {
$parameters['include_rts'] = ($includeRts) ? 'true' : 'false';
}
// make the call
return (array) $this->doCall(
'statuses/user_timeline.json',
$parameters
);
}
/**
* Returns the 20 most recent statuses, including retweets if they exist, posted by the authenticating user and the user's they follow. This is the same timeline seen by a user when they login to twitter.com.
* This method is identical to statusesFriendsTimeline, except that this method always includes retweets.
*
* @param int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 200. Defaults to 20.
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @param bool[optional] $excludeReplies This parameter will prevent replies from appearing in the returned timeline. Using exclude_replies with the count parameter will mean you will receive up-to count tweets — this is because the count parameter retrieves that many tweets before filtering out retweets and replies.
* @param bool[optional] $contributorDetails This parameter enhances the contributors element of the status response to include the screen_name of the contributor. By default only the user_id of the contributor is included.
* @param bool[optional] $includeEntities The entities node will be disincluded when set to false.
* @return array
*/
public function statusesHomeTimeline(
$count = null, $sinceId = null, $maxId = null, $trimUser = null,
$excludeReplies = null, $contributorDetails = null,
$includeEntities = null
)
{
// build parameters
$parameters = null;
if ($count != null) {
$parameters['count'] = (int) $count;
}
if ($sinceId != null) {
$parameters['since_id'] = (string) $sinceId;
}
if ($maxId != null) {
$parameters['max_id'] = (string) $maxId;
}
if ($trimUser != null) {
$parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
}
if ($excludeReplies != null) {
$parameters['exclude_replies'] = ($excludeReplies) ? 'true' : 'false';
}
if ($contributorDetails != null) {
$parameters['contributor_details'] = ($contributorDetails) ? 'true' : 'false';
}
if ($includeEntities != null) {
$parameters['include_entities'] = ($includeEntities) ? 'true' : 'false';
}
// make the call
return (array) $this->doCall(
'statuses/home_timeline.json',
$parameters, true
);
}
/**
* Returns the most recent tweets authored by the authenticating user that have recently been retweeted by others. This timeline is a subset of the user's GET statuses/user_timeline.
*
* @param int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 100. If omitted, 20 will be assumed.
* @param string[optional] $sinceId Returns results with an ID greater than (that is, more recent than) the specified ID. There are limits to the number of Tweets which can be accessed through the API. If the limit of Tweets has occured since the since_id, the since_id will be forced to the oldest ID available.
* @param string[optional] $maxId Returns results with an ID less than (that is, older than) or equal to the specified ID.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @param bool[optional] $includeEntities The tweet entities node will be disincluded when set to false.
* @param bool[optional] $includeUserEntities The user entities node will be disincluded when set to false.
* @return array
*/
public function statusesRetweetsOfMe(
$count = null, $sinceId = null, $maxId = null,
$trimUser = null, $includeEntities = null, $includeUserEntities = null
)
{
// build parameters
$parameters = null;
if ($count != null) {
$parameters['count'] = (int) $count;
}
if ($sinceId != null) {
$parameters['since_id'] = (string) $sinceId;
}
if ($maxId != null) {
$parameters['max_id'] = (string) $maxId;
}
if ($trimUser != null) {
$parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
}
if ($includeEntities != null) {
$parameters['include_entities'] = ($includeEntities) ? 'true' : 'false';
}
if ($includeUserEntities != null) {
$parameters['include_user_entities'] = ($includeUserEntities) ? 'true' : 'false';
}
// make the call
return (array) $this->doCall(
'statuses/retweets_of_me.json',
$parameters, true
);
}
// Tweets resources
/**
* Returns up to 100 of the first retweets of a given tweet.
*
* @param string $id The numerical ID of the desired status.
* @param int[optional] $count Specifies the number of records to retrieve. Must be less than or equal to 100.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @return array
*/
public function statusesRetweets($id, $count = null, $trimUser = null)
{
// build parameters
$parameters = null;
if ($count != null) {
$parameters['count'] = (int) $count;
}
if ($trimUser != null) {
$parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
}
// make the call
return (array) $this->doCall(
'statuses/retweets/' . (string) $id . '.json',
$parameters
);
}
/**
* Returns a single Tweet, specified by the id parameter. The Tweet's author will also be embedded within the tweet.
*
* @param string $id The numerical ID of the desired Tweet.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @param bool[optional] $includeMyRetweet When set to true, any Tweets returned that have been retweeted by the authenticating user will include an additional current_user_retweet node, containing the ID of the source status for the retweet.
* @param bool[optional] $includeEntities The entities node will be disincluded when set to false.
* @return array
*/
public function statusesShow(
$id, $trimUser = null, $includeMyRetweet = null, $includeEntities = null
)
{
// build parameters
$parameters['id'] = (string) $id;
if ($trimUser != null) {
$parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
}
if ($includeMyRetweet != null) {
$parameters['include_my_retweet'] = ($includeMyRetweet) ? 'true' : 'false';
}
if ($includeEntities != null) {
$parameters['include_entities'] = ($includeEntities) ? 'true' : 'false';
}
// make the call
return (array) $this->doCall(
'statuses/show.json',
$parameters, true
);
}
/**
* Destroys the status specified by the required ID parameter. The authenticating user must be the author of the specified status. Returns the destroyed status if successful.
*
* @param string $id The numerical ID of the desired status.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @return array
*/
public function statusesDestroy($id, $trimUser = null)
{
// build parameters
$parameters = null;
if($trimUser != null) $parameters['trim_user'] = ($trimUser) ? 'true' : 'false';
// make the call
return (array) $this->doCall(
'statuses/destroy/' . (string) $id . '.json',
$parameters, true, 'POST'
);
}
/**
* Updates the authenticating user's status. A status update with text identical to the authenticating user's text identical to the authenticating user's current status will be ignored to prevent duplicates.
*
* @param string $status The text of your status update, typically up to 140 characters. URL encode as necessary. t.co link wrapping may effect character counts. There are some special commands in this field to be aware of. For instance, preceding a message with "D " or "M " and following it with a screen name can create a direct message to that user if the relationship allows for it.
* @param string[optional] $inReplyToStatusId The ID of an existing status that the update is in reply to. Note: This parameter will be ignored unless the author of the tweet this parameter references is mentioned within the status text. Therefore, you must include @username, where username is the author of the referenced tweet, within the update.
* @param float[optional] $lat The latitude of the location this tweet refers to. This parameter will be ignored unless it is inside the range -90.0 to +90.0 (North is positive) inclusive. It will also be ignored if there isn't a corresponding long parameter.
* @param float[optional] $long The longitude of the location this tweet refers to. The valid ranges for longitude is -180.0 to +180.0 (East is positive) inclusive. This parameter will be ignored if outside that range, if it is not a number, if geo_enabled is disabled, or if there not a corresponding lat parameter.
* @param string[optional] $placeId A place in the world. These IDs can be retrieved from GET geo/reverse_geocode.
* @param bool[optional] $displayCoordinates Whether or not to put a pin on the exact coordinates a tweet has been sent from.
* @param bool[optional] $trimUser When set to true, each tweet returned in a timeline will include a user object including only the status authors numerical ID. Omit this parameter to receive the complete user object.
* @return array
*/
public function statusesUpdate(
$status, $inReplyToStatusId = null, $lat = null, $long = null,
$placeId = null, $displayCoordinates = null, $trimUser = null
)
{
// build parameters
$parameters['status'] = (string) $status;
if ($inReplyToStatusId != null) {
$parameters['in_reply_to_status_id'] = (string) $inReplyToStatusId;
}
if ($lat != null) {
$parameters['lat'] = (float) $lat;
}
if ($long != null) {
$parameters['long'] = (float) $long;