]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
When Twitter bridge encounters a 403 (rate limit) err, drop the notice
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) {
21     exit(1);
22 }
23
24 define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
25
26 require_once INSTALLDIR . '/plugins/TwitterBridge/twitterbasicauthclient.php';
27 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
28
29 function updateTwitter_user($twitter_id, $screen_name)
30 {
31     $uri = 'http://twitter.com/' . $screen_name;
32     $fuser = new Foreign_user();
33
34     $fuser->query('BEGIN');
35
36     // Dropping down to SQL because regular DB_DataObject udpate stuff doesn't seem
37     // to work so good with tables that have multiple column primary keys
38
39     // Any time we update the uri for a forein user we have to make sure there
40     // are no dupe entries first -- unique constraint on the uri column
41
42     $qry = 'UPDATE foreign_user set uri = \'\' WHERE uri = ';
43     $qry .= '\'' . $uri . '\'' . ' AND service = ' . TWITTER_SERVICE;
44
45     $fuser->query($qry);
46
47     // Update the user
48
49     $qry = 'UPDATE foreign_user SET nickname = ';
50     $qry .= '\'' . $screen_name . '\'' . ', uri = \'' . $uri . '\' ';
51     $qry .= 'WHERE id = ' . $twitter_id . ' AND service = ' . TWITTER_SERVICE;
52
53     $fuser->query('COMMIT');
54
55     $fuser->free();
56     unset($fuser);
57
58     return true;
59 }
60
61 function add_twitter_user($twitter_id, $screen_name)
62 {
63
64     $new_uri = 'http://twitter.com/' . $screen_name;
65
66     // Clear out any bad old foreign_users with the new user's legit URL
67     // This can happen when users move around or fakester accounts get
68     // repoed, and things like that.
69
70     $luser = new Foreign_user();
71     $luser->uri = $new_uri;
72     $luser->service = TWITTER_SERVICE;
73     $result = $luser->delete();
74
75     if (empty($result)) {
76         common_log(LOG_WARNING,
77             "Twitter bridge - removed invalid Twitter user squatting on uri: $new_uri");
78     }
79
80     $luser->free();
81     unset($luser);
82
83     // Otherwise, create a new Twitter user
84
85     $fuser = new Foreign_user();
86
87     $fuser->nickname = $screen_name;
88     $fuser->uri = 'http://twitter.com/' . $screen_name;
89     $fuser->id = $twitter_id;
90     $fuser->service = TWITTER_SERVICE;
91     $fuser->created = common_sql_now();
92     $result = $fuser->insert();
93
94     if (empty($result)) {
95         common_log(LOG_WARNING,
96             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
97         common_log_db_error($fuser, 'INSERT', __FILE__);
98     } else {
99         common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
100     }
101
102     return $result;
103 }
104
105 // Creates or Updates a Twitter user
106 function save_twitter_user($twitter_id, $screen_name)
107 {
108
109     // Check to see whether the Twitter user is already in the system,
110     // and update its screen name and uri if so.
111
112     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
113
114     if (!empty($fuser)) {
115
116         $result = true;
117
118         // Only update if Twitter screen name has changed
119
120         if ($fuser->nickname != $screen_name) {
121             $result = updateTwitter_user($twitter_id, $screen_name);
122
123             common_debug('Twitter bridge - Updated nickname (and URI) for Twitter user ' .
124                 "$fuser->id to $screen_name, was $fuser->nickname");
125         }
126
127         return $result;
128
129     } else {
130         return add_twitter_user($twitter_id, $screen_name);
131     }
132
133     $fuser->free();
134     unset($fuser);
135
136     return true;
137 }
138
139 function is_twitter_bound($notice, $flink) {
140
141     // Check to see if notice should go to Twitter
142     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
143
144         // If it's not a Twitter-style reply, or if the user WANTS to send replies.
145         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
146             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
147             return true;
148         }
149     }
150
151     return false;
152 }
153
154 function broadcast_twitter($notice)
155 {
156     $flink = Foreign_link::getByUserID($notice->profile_id,
157                                        TWITTER_SERVICE);
158
159     if (is_twitter_bound($notice, $flink)) {
160         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
161             return broadcast_oauth($notice, $flink);
162         } else {
163             return broadcast_basicauth($notice, $flink);
164         }
165     }
166
167     return true;
168 }
169
170 function broadcast_oauth($notice, $flink) {
171     $user = $flink->getUser();
172     $statustxt = format_status($notice);
173     $token = TwitterOAuthClient::unpackToken($flink->credentials);
174     $client = new TwitterOAuthClient($token->key, $token->secret);
175     $status = null;
176
177     try {
178         $status = $client->statusesUpdate($statustxt);
179     } catch (OAuthClientException $e) {
180         return process_error($e, $flink, $notice);
181     }
182
183     if (empty($status)) {
184
185         // This could represent a failure posting,
186         // or the Twitter API might just be behaving flakey.
187
188         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
189                           'trying to post notice %d for User %s (user id %d).',
190                           $notice->id,
191                           $user->nickname,
192                           $user->id);
193
194         common_log(LOG_WARNING, $errmsg);
195
196         return false;
197     }
198
199     // Notice crossed the great divide
200
201     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
202                    'OAuth for User %s (user id %d).',
203                    $notice->id,
204                    $user->nickname,
205                    $user->id);
206
207     common_log(LOG_INFO, $msg);
208
209     return true;
210 }
211
212 function broadcast_basicauth($notice, $flink)
213 {
214     $user = $flink->getUser();
215
216     $statustxt = format_status($notice);
217
218     $client = new TwitterBasicAuthClient($flink);
219     $status = null;
220
221     try {
222         $status = $client->statusesUpdate($statustxt);
223     } catch (BasicAuthException $e) {
224         return process_error($e, $flink, $notice);
225     }
226
227     if (empty($status)) {
228
229         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
230                           'trying to post notice %d for %s (user id %d).',
231                           $notice->id,
232                           $user->nickname,
233                           $user->id);
234
235         common_log(LOG_WARNING, $errmsg);
236
237         $errmsg = sprintf('No data returned by Twitter API when ' .
238                           'trying to post notice %d for %s (user id %d).',
239                           $notice->id,
240                           $user->nickname,
241                           $user->id);
242         common_log(LOG_WARNING, $errmsg);
243         return false;
244     }
245
246     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
247                    'HTTP basic auth for User %s (user id %d).',
248                    $notice->id,
249                    $user->nickname,
250                    $user->id);
251
252     common_log(LOG_INFO, $msg);
253
254     return true;
255 }
256
257 function process_error($e, $flink, $notice)
258 {
259     $user = $flink->getUser();
260     $code = $e->getCode();
261
262     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
263                       'User %s (user id: %d): %s.',
264                       $code,
265                       $notice->id,
266                       $user->nickname,
267                       $user->id,
268                       $e->getMessage());
269
270     common_log(LOG_WARNING, $logmsg);
271
272     switch($code) {
273      case 401:
274         // Probably a revoked or otherwise bad access token - nuke!
275         remove_twitter_link($flink);
276         return true;
277         break;
278      case 403:
279         // User has exceeder her rate limit -- toss the notice
280         return true;
281         break;
282      default:
283
284         // For every other case, it's probably some flakiness so try
285         // sending the notice again later (requeue).
286
287         return false;
288         break;
289     }
290 }
291
292 function format_status($notice)
293 {
294     // XXX: Hack to get around PHP cURL's use of @ being a a meta character
295     $statustxt = preg_replace('/^@/', ' @', $notice->content);
296
297     // Convert !groups to #hashes
298     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
299
300     return $statustxt;
301 }
302
303 function remove_twitter_link($flink)
304 {
305     $user = $flink->getUser();
306
307     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
308                "user $user->nickname (user id: $user->id).");
309
310     $result = $flink->delete();
311
312     if (empty($result)) {
313         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
314                    "Foreign_link for $user->nickname (user id: $user->id)!");
315         common_log_db_error($flink, 'DELETE', __FILE__);
316     }
317
318     // Notify the user that her Twitter bridge is down
319
320     if (isset($user->email)) {
321
322         $result = mail_twitter_bridge_removed($user);
323
324         if (!$result) {
325
326             $msg = 'Unable to send email to notify ' .
327               "$user->nickname (user id: $user->id) " .
328               'that their Twitter bridge link was ' .
329               'removed!';
330
331             common_log(LOG_WARNING, $msg);
332         }
333     }
334
335 }
336
337 /**
338  * Send a mail message to notify a user that her Twitter bridge link
339  * has stopped working, and therefore has been removed.  This can
340  * happen when the user changes her Twitter password, or otherwise
341  * revokes access.
342  *
343  * @param User $user   user whose Twitter bridge link has been removed
344  *
345  * @return boolean success flag
346  */
347
348 function mail_twitter_bridge_removed($user)
349 {
350     common_init_locale($user->language);
351
352     $profile = $user->getProfile();
353
354     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
355
356     $site_name = common_config('site', 'name');
357
358     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
359         'link to Twitter has been disabled. We no longer seem to have ' .
360     'permission to update your Twitter status. (Did you revoke ' .
361     '%3$s\'s access?)' . "\n\n" .
362     'You can re-enable your Twitter bridge by visiting your ' .
363     "Twitter settings page:\n\n\t%2\$s\n\n" .
364         "Regards,\n%3\$s\n"),
365         $profile->getBestName(),
366         common_local_url('twittersettings'),
367         common_config('site', 'name'));
368
369     common_init_locale();
370     return mail_to_user($user, $subject, $body);
371 }
372