forked from dg/twitter-php
-
Notifications
You must be signed in to change notification settings - Fork 1
/
twitter.class.php
311 lines (247 loc) · 7.6 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
<?php
require_once(dirname(__FILE__) . '/lib/twitteroauth.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://apiwiki.twitter.com/Twitter-API-Documentation
* @version 1.3
*/
class Twitter
{
/**#@+ Timeline {@link Twitter::load()} */
const ME = 1;
const ME_AND_FRIENDS = 2;
const REPLIES = 3;
const ALL = 4;
/**#@-*/
/**#@+ Output format {@link Twitter::load()} */
const XML = 0;
const JSON = 16;
const RSS = 32;
const ATOM = 48;
/**#@-*/
/**#@+ Authorization states {@link Twitter::__construct()} */
const AUTH_ACCESS = 200;
const AUTH_REDIRECT = 301;
/**#@-*/
/** @var int */
public static $cacheExpire = 1800; // 30 min
/** @var string */
public static $cacheDir;
/** @var TwitterOAuth */
private $oauth;
/**
* Creates object using application and request/access keys.
* @param string app key
* @param string app secret
* @param string access key
* @param string access secret
* @throws TwitterException when CURL extension is not loaded
* @throws TwitterAuthException to signalize individual authorization steps
*/
public function __construct($appKey, $appSecret, $accessKey = NULL, $accessSecret = NULL)
{
if (!$accessKey || !$accessSecret) {
$sess = &$_SESSION['__TWT'];
if (!$sess['request_key'] || !$sess['request_secret']) {
$oauth = new TwitterOAuth($appKey, $appSecret);
$token = $oauth->getRequestToken();
$sess['request_key'] = $token['oauth_token'];
$sess['request_secret'] = $token['oauth_token_secret'];
$url = $oauth->getAuthorizeURL($sess['request_key']);
throw new TwitterAuthException($url, self::AUTH_REDIRECT);
} else {
$oauth = new TwitterOAuth($appKey, $appSecret, $sess['request_key'], $sess['request_secret']);
unset($_SESSION['__TWT']);
$info = $oauth->getAccessToken();
$accessKey = $info['oauth_token'];
$accessSecret = $info['oauth_token_secret'];
throw new TwitterAuthException(NULL, self::AUTH_ACCESS, $accessKey, $accessSecret);
}
} else {
$this->oauth = new TwitterOAuth($appKey, $appSecret, $accessKey, $accessSecret);
}
}
/**
* Checks authorization.
* @return boolean
*/
public function isAuthorized()
{
return ($this->oauth instanceof TwitterOAuth);
}
/**
* 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);
}
$xml = $this->httpRequest(
'https://api.twitter.com/1/statuses/update.xml',
array('status' => $message)
);
return $xml->id ? (string) $xml->id : FALSE;
}
/**
* Returns the most recent statuses.
* @param int timeline (ME | ME_AND_FRIENDS | REPLIES | ALL) and optional format (XML | JSON | RSS | ATOM)
* @param int number of statuses to retrieve
* @param int page of results to retrieve
* @param bool include retweets?
* @return mixed
* @throws TwitterException
*/
public function load($flags = self::ME, $count = 20, $page = 1, $retweets = FALSE)
{
static $timelines = array(self::ME => 'user_timeline', self::ME_AND_FRIENDS => 'friends_timeline', self::REPLIES => 'mentions', self::ALL => 'public_timeline');
static $formats = array(self::XML => 'xml', self::JSON => 'json', self::RSS => 'rss', self::ATOM => 'atom');
if (!is_int($flags)) { // back compatibility
$flags = $flags ? self::ME_AND_FRIENDS : self::ME;
} elseif (!isset($timelines[$flags & 0x0F], $formats[$flags & 0x30])) {
throw new InvalidArgumentException;
}
return $this->cachedHttpRequest("http://api.twitter.com/1/statuses/" . $timelines[$flags & 0x0F] . '.' . $formats[$flags & 0x30] . "?count=$count&page=$page&include_rts=$retweets");
}
/**
* Destroys status.
* @param int id of status to be destroyed
* @return mixed
* @throws TwitterException
*/
public function destroy($id)
{
$xml = $this->httpRequest("http://api.twitter.com/1/statuses/destroy/:$id.xml", array('id' => $id));
return $xml->id ? (string) $xml->id : FALSE;
}
/**
* Returns tweets that match a specified query.
* @param string query
* @param int format (JSON | ATOM)
* @return mixed
* @throws TwitterException
*/
public function search($query, $flags = self::JSON)
{
static $formats = array(self::JSON => 'json', self::ATOM => 'atom');
if (!isset($formats[$flags & 0x30])) {
throw new InvalidArgumentException;
}
return $this->httpRequest(
'http://search.twitter.com/search.' . $formats[$flags & 0x30],
array('q' => $query)
)->results;
}
/**
* Process HTTP request.
* @param string URL
* @param array POST data
* @return mixed
* @throws TwitterException
*/
private function httpRequest($url, $postData = NULL)
{
if (!($this->oauth instanceof TwitterOAuth)) {
throw new TwitterException('Not authorized.');
}
$result = $this->oauth->oAuthRequest($url, ($postData ? 'POST' : 'GET'), $postData);
if (strpos($url, 'json')) {
$payload = @json_decode($result); // intentionally @
} else {
$payload = @simplexml_load_string($result); // intentionally @
}
if (empty($payload)) {
throw new TwitterException('Invalid server response');
}
return $payload;
}
/**
* Cached HTTP request.
* @param string URL
* @return mixed
*/
private function cachedHttpRequest($url)
{
if (!self::$cacheDir) {
return $this->httpRequest($url);
}
$cacheFile = self::$cacheDir . '/twitter.' . md5($url);
$cache = @file_get_contents($cacheFile); // intentionally @
$cache = strncmp($cache, '<', 1) ? @json_decode($cache) : @simplexml_load_string($cache); // intentionally @
if ($cache && @filemtime($cacheFile) + self::$cacheExpire > time()) { // intentionally @
return $cache;
}
try {
$payload = $this->httpRequest($url);
file_put_contents($cacheFile, $payload instanceof SimpleXMLElement ? $payload->asXml() : json_encode($payload));
return $payload;
} catch (TwitterException $e) {
if ($cache) {
return $cache;
}
throw $e;
}
}
/**
* Shortens URL using http://is.gd API.
* @param array
* @return string
* @throws TwitterException
*/
private function shortenUrl($m)
{
if (!extension_loaded('curl')) {
throw new TwitterException('PHP extension CURL is not loaded.');
}
$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;
}
}
/**
* An exception generated by Twitter.
*/
class TwitterException extends Exception
{
}
/**
* An exception generated by authorization process.
*/
class TwitterAuthException extends TwitterException
{
private $uri;
private $accessKey;
private $accessSecret;
public function __construct($uri, $code, $accessKey = NULL, $accessSecret = NULL)
{
parent::__construct(NULL, $code);
$this->uri = $uri;
$this->accessKey = $accessKey;
$this->accessSecret = $accessSecret;
}
public function getUri()
{
return $this->uri;
}
public function getAccessKey()
{
return $this->accessKey;
}
public function getAccessToken()
{
return $this->accessSecret;
}
}