forked from dg/twitter-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtwitter.class.php
359 lines (290 loc) · 9 KB
/
twitter.class.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
<?php
require_once dirname(__FILE__) . '/OAuth.php';
/**
* Twitter for PHP - library for sending messages to Twitter and receiving status updates.
*
* @author David Grudl
* @copyright Copyright (c) 2008 David Grudl
* @license New BSD License
* @link http://phpfashion.com/
* @see http://dev.twitter.com/doc
* @version 2.0
*/
class Twitter
{
/**#@+ Timeline {@link Twitter::load()} */
const ME = 1;
const ME_AND_FRIENDS = 2;
const REPLIES = 3;
const ALL = 4;
const RETWEETS = 128; // include retweets?
/**#@-*/
/**#@+ Output format {@link Twitter::load()} */
const XML = 0;
const JSON = 16;
const RSS = 32;
const ATOM = 48;
/**#@-*/
/** @var int */
public static $cacheExpire = 1800; // 30 min
/** @var string */
public static $cacheDir;
/** @var OAuthSignatureMethod */
private $signatureMethod;
/** @var OAuthConsumer */
private $consumer;
/** @var OAuthConsumer */
private $token;
/**
* Creates object using consumer and access keys.
* @param string consumer key
* @param string app secret
* @param string optional access token
* @param string optinal access token secret
* @throws TwitterException when CURL extension is not loaded
*/
public function __construct($consumerKey = NULL, $consumerSecret = NULL, $accessToken = NULL, $accessTokenSecret = NULL)
{
if (!extension_loaded('curl')) {
throw new TwitterException('PHP extension CURL is not loaded.');
}
$this->signatureMethod = new OAuthSignatureMethod_HMAC_SHA1();
$this->consumer = new OAuthConsumer($consumerKey, $consumerSecret);
$this->token = new OAuthConsumer($accessToken, $accessTokenSecret);
}
/**
* Tests if user credentials are valid.
* @return boolean
* @throws TwitterException
*/
public function authenticate()
{
try {
$res = $this->request('account/verify_credentials', NULL, 'GET');
return !empty($res->id);
} catch (TwitterException $e) {
if ($e->getCode() === 401) {
return FALSE;
}
throw $e;
}
}
/**
* Sends message to the Twitter.
* @param string message encoded in UTF-8
* @return mixed ID on success or FALSE on failure
* @throws TwitterException
*/
public function send($message)
{
if (iconv_strlen($message, 'UTF-8') > 140) {
$message = preg_replace_callback('#https?://\S+[^:);,.!?\s]#', array($this, 'shortenUrl'), $message);
}
$res = $this->request('statuses/update', array('status' => $message));
return $res->id ? (string) $res->id : FALSE;
}
/**
* Returns the most recent statuses.
* @param int timeline (ME | ME_AND_FRIENDS | REPLIES | ALL) and optional (RETWEETS) or format (XML | JSON | RSS | ATOM)
* @param int number of statuses to retrieve
* @param int page of results to retrieve
* @return mixed
* @throws TwitterException
*/
public function load($flags = self::ME, $count = 20, $page = 1)
{
static $timelines = array(self::ME => 'user_timeline', self::ME_AND_FRIENDS => 'friends_timeline', self::REPLIES => 'mentions', self::ALL => 'public_timeline');
if (!is_int($flags)) { // back compatibility
$flags = $flags ? self::ME_AND_FRIENDS : self::ME;
} elseif (!isset($timelines[$flags & 0x0F])) {
throw new InvalidArgumentException;
}
return $this->cachedRequest('statuses/' . $timelines[$flags & 0x0F] . '.' . self::getFormat($flags), array(
'count' => $count,
'page' => $page,
'include_rts' => $flags & self::RETWEETS ? 1 : 0,
));
}
/**
* Returns information of a given user.
* @param string name
* @param int format (XML | JSON)
* @return mixed
* @throws TwitterException
*/
public function loadUserInfo($user, $flags = self::XML)
{
return $this->cachedRequest('users/show.' . self::getFormat($flags), array('screen_name' => $user));
}
/**
* Destroys status.
* @param int id of status to be destroyed
* @return mixed
* @throws TwitterException
*/
public function destroy($id)
{
$res = $this->request("statuses/destroy/$id");
return $res->id ? (string) $res->id : FALSE;
}
/**
* Returns tweets that match a specified query.
* @param string|array query
* @param int format (JSON | ATOM)
* @return mixed
* @throws TwitterException
*/
public function search($query, $flags = self::JSON)
{
return $this->request(
'http://search.twitter.com/search.' . self::getFormat($flags),
is_array($query) ? $query : array('q' => $query),
'GET'
)->results;
}
/**
* Process HTTP request.
* @param string URL or twitter command
* @param array data
* @param string HTTP method
* @return mixed
* @throws TwitterException
*/
public function request($request, $data = NULL, $method = 'POST')
{
if (!strpos($request, '://')) {
if (!strpos($request, '.')) {
$request .= '.json';
}
$request = 'http://api.twitter.com/1/' . $request;
}
$request = OAuthRequest::from_consumer_and_token($this->consumer, $this->token, $method, $request, $data);
$request->sign_request($this->signatureMethod, $this->consumer, $this->token);
$curl = curl_init();
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_HTTPHEADER, array('Expect:'));
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE); // no echo, just return result
curl_setopt($curl, CURLOPT_USERAGENT, 'Twitter for PHP');
if ($method === 'POST') {
curl_setopt($curl, CURLOPT_POST, TRUE);
curl_setopt($curl, CURLOPT_POSTFIELDS, $request->to_postdata());
curl_setopt($curl, CURLOPT_URL, $request->get_normalized_http_url());
} else {
curl_setopt($curl, CURLOPT_URL, $request->to_url());
}
$result = curl_exec($curl);
if (curl_errno($curl)) {
throw new TwitterException('Server error: ' . curl_error($curl));
}
$type = curl_getinfo($curl, CURLINFO_CONTENT_TYPE);
if (strpos($type, 'xml')) {
$payload = @simplexml_load_string($result); // intentionally @
} elseif (strpos($type, 'json')) {
$payload = @json_decode($result); // intentionally @
}
if (empty($payload)) {
throw new TwitterException('Invalid server response');
}
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ($code >= 400) {
throw new TwitterException(isset($payload->error) ? $payload->error : "Server error #$code", $code);
}
return $payload;
}
/**
* Cached HTTP request.
* @param string URL or twitter command
* @param array
* @param int
* @return mixed
*/
public function cachedRequest($request, $data = NULL, $cacheExpire = NULL)
{
if (!self::$cacheDir) {
return $this->request($request, $data, 'GET');
}
if ($cacheExpire === NULL) {
$cacheExpire = self::$cacheExpire;
}
$cacheFile = self::$cacheDir . '/twitter.' . md5($request . json_encode($data) . serialize(array($this->consumer, $this->token)));
$cache = @file_get_contents($cacheFile); // intentionally @
$cache = strncmp($cache, '<', 1) ? @json_decode($cache) : @simplexml_load_string($cache); // intentionally @
if ($cache && @filemtime($cacheFile) + $cacheExpire > time()) { // intentionally @
return $cache;
}
try {
$payload = $this->request($request, $data, 'GET');
file_put_contents($cacheFile, $payload instanceof SimpleXMLElement ? $payload->asXml() : json_encode($payload));
return $payload;
} catch (TwitterException $e) {
if ($cache) {
return $cache;
}
throw $e;
}
}
/**
* Makes twitter links, @usernames and #hashtags clickable.
* @param string
* @return string
*/
public static function clickable($s)
{
return preg_replace_callback(
'~(?<!\w)(https?://\S+\w|www\.\S+\w|@\w+|#\w+)|[<>&]~u',
array(__CLASS__, 'clickableCallback'),
html_entity_decode($s, ENT_QUOTES, 'UTF-8')
);
}
private static function clickableCallback($m)
{
$m = htmlspecialchars($m[0]);
if ($m[0] === '#') {
$m = substr($m, 1);
return "<a href='http://twitter.com/search?q=%23$m'>#$m</a>";
} elseif ($m[0] === '@') {
$m = substr($m, 1);
return "@<a href='http://twitter.com/$m'>$m</a>";
} elseif ($m[0] === 'w') {
return "<a href='http://$m'>$m</a>";
} elseif ($m[0] === 'h') {
return "<a href='$m'>$m</a>";
} else {
return $m;
}
}
/**
* Shortens URL using http://is.gd API.
* @param array
* @return string
*/
private function shortenUrl($m)
{
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, 'http://is.gd/api.php?longurl=' . urlencode($m[0]));
curl_setopt($curl, CURLOPT_HEADER, FALSE);
curl_setopt($curl, CURLOPT_TIMEOUT, 20);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$result = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
return curl_errno($curl) || $code >= 400 ? $m[0] : $result;
}
private static function getFormat($flag)
{
static $formats = array(self::XML => 'xml', self::JSON => 'json', self::RSS => 'rss', self::ATOM => 'atom');
$flag = $flag & 0x30;
if (isset($formats[$flag])) {
return $formats[$flag];
} else {
throw new InvalidArgumentException('Invalid format');
}
}
}
/**
* An exception generated by Twitter.
*/
class TwitterException extends Exception
{
}