]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Fix for failure edge case in TwitterBridge outgoing repeat/retweets.
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2010 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/twitteroauthclient.php';
27
28 function add_twitter_user($twitter_id, $screen_name)
29 {
30     // Clear out any bad old foreign_users with the new user's legit URL
31     // This can happen when users move around or fakester accounts get
32     // repoed, and things like that.
33     $luser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
34
35     if (!empty($luser)) {
36         $result = $luser->delete();
37         if ($result != false) {
38             common_log(
39                 LOG_INFO,
40                 "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
41             );
42         }
43     }
44
45     $fuser = new Foreign_user();
46
47     $fuser->nickname = $screen_name;
48     $fuser->uri = 'http://twitter.com/' . $screen_name;
49     $fuser->id = $twitter_id;
50     $fuser->service = TWITTER_SERVICE;
51     $fuser->created = common_sql_now();
52     $result = $fuser->insert();
53
54     if (empty($result)) {
55         common_log(LOG_WARNING,
56             "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
57         common_log_db_error($fuser, 'INSERT', __FILE__);
58     } else {
59         common_log(LOG_INFO,
60                    "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
61     }
62
63     return $result;
64 }
65
66 // Creates or Updates a Twitter user
67 function save_twitter_user($twitter_id, $screen_name)
68 {
69     // Check to see whether the Twitter user is already in the system,
70     // and update its screen name and uri if so.
71     $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
72
73     if (!empty($fuser)) {
74
75         // Delete old record if Twitter user changed screen name
76
77         if ($fuser->nickname != $screen_name) {
78             $oldname = $fuser->nickname;
79             $fuser->delete();
80             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
81                                          'for Twitter user %1$d - %2$s, was %3$s.',
82                                          $fuser->id,
83                                          $screen_name,
84                                          $oldname));
85         }
86
87     } else {
88         // Kill any old, invalid records for this screen name
89         $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
90
91         if (!empty($fuser)) {
92             $fuser->delete();
93             common_log(
94                 LOG_INFO,
95                 sprintf(
96                     'Twitter bridge - deteted old record for Twitter ' .
97                     'screen name "%s" belonging to Twitter ID %d.',
98                     $screen_name,
99                     $fuser->id
100                 )
101             );
102         }
103     }
104
105     return add_twitter_user($twitter_id, $screen_name);
106 }
107
108 function is_twitter_bound($notice, $flink) {
109     // Check to see if notice should go to Twitter
110     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
111
112         // If it's not a Twitter-style reply, or if the user WANTS to send replies,
113         // or if it's in reply to a twitter notice
114         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
115             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) ||
116             is_twitter_notice($notice->reply_to)) {
117             return true;
118         }
119     }
120
121     return false;
122 }
123
124 function is_twitter_notice($id)
125 {
126     $n2s = Notice_to_status::staticGet('notice_id', $id);
127
128     return (!empty($n2s));
129 }
130
131 /**
132  * Check if we need to broadcast a notice over the Twitter bridge, and
133  * do so if necessary. Will determine whether to do a straight post or
134  * a repeat/retweet
135  *
136  * This function is meant to be called directly from TwitterQueueHandler.
137  *
138  * @param Notice $notice
139  * @return boolean true if complete or successful, false if we should retry
140  */
141 function broadcast_twitter($notice)
142 {
143     $flink = Foreign_link::getByUserID($notice->profile_id,
144                                        TWITTER_SERVICE);
145
146     // Don't bother with basic auth, since it's no longer allowed
147     if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
148         if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
149             $retweet = retweet_notice($flink, Notice::staticGet('id', $notice->repeat_of));
150             if (is_object($retweet)) {
151                 Notice_to_status::saveNew($notice->id, $retweet->id);
152                 return true;
153             } else {
154                 // Our error processing will have decided if we need to requeue
155                 // this or can discard safely.
156                 return $retweet;
157             }
158         } else if (is_twitter_bound($notice, $flink)) {
159             return broadcast_oauth($notice, $flink);
160         }
161     }
162
163     return true;
164 }
165
166 /**
167  * Send a retweet to Twitter for a notice that has been previously bridged
168  * in or out.
169  *
170  * Warning: the return value is not guaranteed to be an object; some error
171  * conditions will return a 'true' which should be passed on to a calling
172  * queue handler.
173  *
174  * No local information about the resulting retweet is saved: it's up to
175  * caller to save new mappings etc if appropriate.
176  *
177  * @param Foreign_link $flink
178  * @param Notice $notice
179  * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
180  */
181 function retweet_notice($flink, $notice)
182 {
183     $token = TwitterOAuthClient::unpackToken($flink->credentials);
184     $client = new TwitterOAuthClient($token->key, $token->secret);
185
186     $id = twitter_status_id($notice);
187
188     if (empty($id)) {
189         common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
190         return null;
191     }
192
193     try {
194         $status = $client->statusesRetweet($id);
195         return $status;
196     } catch (OAuthClientException $e) {
197         return process_error($e, $flink, $notice);
198     }
199 }
200
201 function twitter_status_id($notice)
202 {
203     $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
204     if (empty($n2s)) {
205         return null;
206     } else {
207         return $n2s->status_id;
208     }
209 }
210
211 /**
212  * Pull any extra information from a notice that we should transfer over
213  * to Twitter beyond the notice text itself.
214  *
215  * @param Notice $notice
216  * @return array of key-value pairs for Twitter update submission
217  * @access private
218  */
219 function twitter_update_params($notice)
220 {
221     $params = array();
222     if ($notice->lat || $notice->lon) {
223         $params['lat'] = $notice->lat;
224         $params['long'] = $notice->lon;
225     }
226     if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
227         $reply = Notice::staticGet('id', $notice->reply_to);
228         $params['in_reply_to_status_id'] = twitter_status_id($reply);
229     }
230     return $params;
231 }
232
233 function broadcast_oauth($notice, $flink) {
234     $user = $flink->getUser();
235     $statustxt = format_status($notice);
236     $params = twitter_update_params($notice);
237
238     $token = TwitterOAuthClient::unpackToken($flink->credentials);
239     $client = new TwitterOAuthClient($token->key, $token->secret);
240     $status = null;
241
242     try {
243         $status = $client->statusesUpdate($statustxt, $params);
244         if (!empty($status)) {
245             Notice_to_status::saveNew($notice->id, $status->id);
246         }
247     } catch (OAuthClientException $e) {
248         return process_error($e, $flink, $notice);
249     }
250
251     if (empty($status)) {
252
253         // This could represent a failure posting,
254         // or the Twitter API might just be behaving flakey.
255         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
256                           'trying to post notice %d for User %s (user id %d).',
257                           $notice->id,
258                           $user->nickname,
259                           $user->id);
260
261         common_log(LOG_WARNING, $errmsg);
262
263         return false;
264     }
265
266     // Notice crossed the great divide
267     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
268                    'OAuth for User %s (user id %d).',
269                    $notice->id,
270                    $user->nickname,
271                    $user->id);
272
273     common_log(LOG_INFO, $msg);
274
275     return true;
276 }
277
278 function process_error($e, $flink, $notice)
279 {
280     $user = $flink->getUser();
281     $code = $e->getCode();
282
283     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
284                       'User %s (user id: %d): %s.',
285                       $code,
286                       $notice->id,
287                       $user->nickname,
288                       $user->id,
289                       $e->getMessage());
290
291     common_log(LOG_WARNING, $logmsg);
292
293     switch($code) {
294      case 401:
295         // Probably a revoked or otherwise bad access token - nuke!
296         remove_twitter_link($flink);
297         return true;
298         break;
299      case 403:
300         // User has exceeder her rate limit -- toss the notice
301         return true;
302         break;
303      default:
304
305         // For every other case, it's probably some flakiness so try
306         // sending the notice again later (requeue).
307
308         return false;
309         break;
310     }
311 }
312
313 function format_status($notice)
314 {
315     // Start with the plaintext source of this notice...
316     $statustxt = $notice->content;
317
318     // Convert !groups to #hashes
319     // XXX: Make this an optional setting?
320     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
321
322     // Twitter still has a 140-char hardcoded max.
323     if (mb_strlen($statustxt) > 140) {
324         $noticeUrl = common_shorten_url($notice->uri);
325         $urlLen = mb_strlen($noticeUrl);
326         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
327     }
328
329     return $statustxt;
330 }
331
332 function remove_twitter_link($flink)
333 {
334     $user = $flink->getUser();
335
336     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
337                "user $user->nickname (user id: $user->id).");
338
339     $result = $flink->safeDelete();
340
341     if (empty($result)) {
342         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
343                    "Foreign_link for $user->nickname (user id: $user->id)!");
344         common_log_db_error($flink, 'DELETE', __FILE__);
345     }
346
347     // Notify the user that her Twitter bridge is down
348
349     if (isset($user->email)) {
350         $result = mail_twitter_bridge_removed($user);
351
352         if (!$result) {
353             $msg = 'Unable to send email to notify ' .
354               "$user->nickname (user id: $user->id) " .
355               'that their Twitter bridge link was ' .
356               'removed!';
357
358             common_log(LOG_WARNING, $msg);
359         }
360     }
361 }
362
363 /**
364  * Send a mail message to notify a user that her Twitter bridge link
365  * has stopped working, and therefore has been removed.  This can
366  * happen when the user changes her Twitter password, or otherwise
367  * revokes access.
368  *
369  * @param User $user   user whose Twitter bridge link has been removed
370  *
371  * @return boolean success flag
372  */
373 function mail_twitter_bridge_removed($user)
374 {
375     $profile = $user->getProfile();
376
377     common_switch_locale($user->language);
378
379     $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
380
381     $site_name = common_config('site', 'name');
382
383     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
384         'link to Twitter has been disabled. We no longer seem to have ' .
385     'permission to update your Twitter status. Did you maybe revoke ' .
386     '%3$s\'s access?' . "\n\n" .
387     'You can re-enable your Twitter bridge by visiting your ' .
388     "Twitter settings page:\n\n\t%2\$s\n\n" .
389         "Regards,\n%3\$s"),
390         $profile->getBestName(),
391         common_local_url('twittersettings'),
392         common_config('site', 'name'));
393
394     common_switch_locale();
395     return mail_to_user($user, $subject, $body);
396 }