]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
Merge commit 'refs/merge-requests/157' of git://gitorious.org/statusnet/mainline...
[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         // Delete old record if Twitter user changed screen name
75
76         if ($fuser->nickname != $screen_name) {
77             $oldname = $fuser->nickname;
78             $fuser->delete();
79             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
80                                          'for Twitter user %1$d - %2$s, was %3$s.',
81                                          $fuser->id,
82                                          $screen_name,
83                                          $oldname));
84         }
85     } else {
86         // Kill any old, invalid records for this screen name
87         $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
88
89         if (!empty($fuser)) {
90             $fuser->delete();
91             common_log(
92                 LOG_INFO,
93                 sprintf(
94                     'Twitter bridge - deteted old record for Twitter ' .
95                     'screen name "%s" belonging to Twitter ID %d.',
96                     $screen_name,
97                     $fuser->id
98                 )
99             );
100         }
101     }
102
103     return add_twitter_user($twitter_id, $screen_name);
104 }
105
106 function is_twitter_bound($notice, $flink) {
107     // Check to see if notice should go to Twitter
108     if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
109
110         // If it's not a Twitter-style reply, or if the user WANTS to send replies,
111         // or if it's in reply to a twitter notice
112         if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
113             ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) ||
114             is_twitter_notice($notice->reply_to)) {
115             return true;
116         }
117     }
118
119     return false;
120 }
121
122 function is_twitter_notice($id)
123 {
124     $n2s = Notice_to_status::staticGet('notice_id', $id);
125
126     return (!empty($n2s));
127 }
128
129 /**
130  * Pull the formatted status ID number from a Twitter status object
131  * returned via JSON from Twitter API.
132  *
133  * Encapsulates checking for the id_str attribute, which is required
134  * to read 64-bit "Snowflake" ID numbers on a 32-bit system -- the
135  * integer id attribute gets corrupted into a double-precision float,
136  * losing a few digits of precision.
137  *
138  * Warning: avoid performing arithmetic or direct comparisons with
139  * this number, as it may get coerced back to a double on 32-bit.
140  *
141  * @param object $status
142  * @param string $field base field name if not 'id'
143  * @return mixed id number as int or string
144  */
145 function twitter_id($status, $field='id')
146 {
147     $field_str = "{$field}_str";
148     if (isset($status->$field_str)) {
149         // String version of the id -- required on 32-bit systems
150         // since the 64-bit numbers get corrupted as ints.
151         return $status->$field_str;
152     } else {
153         return $status->$field;
154     }
155 }
156
157 /**
158  * Check if we need to broadcast a notice over the Twitter bridge, and
159  * do so if necessary. Will determine whether to do a straight post or
160  * a repeat/retweet
161  *
162  * This function is meant to be called directly from TwitterQueueHandler.
163  *
164  * @param Notice $notice
165  * @return boolean true if complete or successful, false if we should retry
166  */
167 function broadcast_twitter($notice)
168 {
169     $flink = Foreign_link::getByUserID($notice->profile_id,
170                                        TWITTER_SERVICE);
171
172     // Don't bother with basic auth, since it's no longer allowed
173     if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
174         if (is_twitter_bound($notice, $flink)) {
175             if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
176                 $retweet = retweet_notice($flink, Notice::staticGet('id', $notice->repeat_of));
177                 if (is_object($retweet)) {
178                     Notice_to_status::saveNew($notice->id, twitter_id($retweet));
179                     return true;
180                 } else {
181                     // Our error processing will have decided if we need to requeue
182                     // this or can discard safely.
183                     return $retweet;
184                 }
185             } else {
186                 return broadcast_oauth($notice, $flink);
187             }
188         }
189     }
190
191     return true;
192 }
193
194 /**
195  * Send a retweet to Twitter for a notice that has been previously bridged
196  * in or out.
197  *
198  * Warning: the return value is not guaranteed to be an object; some error
199  * conditions will return a 'true' which should be passed on to a calling
200  * queue handler.
201  *
202  * No local information about the resulting retweet is saved: it's up to
203  * caller to save new mappings etc if appropriate.
204  *
205  * @param Foreign_link $flink
206  * @param Notice $notice
207  * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
208  */
209 function retweet_notice($flink, $notice)
210 {
211     $token = TwitterOAuthClient::unpackToken($flink->credentials);
212     $client = new TwitterOAuthClient($token->key, $token->secret);
213
214     $id = twitter_status_id($notice);
215
216     if (empty($id)) {
217         common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
218         return null;
219     }
220
221     try {
222         $status = $client->statusesRetweet($id);
223         return $status;
224     } catch (OAuthClientException $e) {
225         return process_error($e, $flink, $notice);
226     }
227 }
228
229 function twitter_status_id($notice)
230 {
231     $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
232     if (empty($n2s)) {
233         return null;
234     } else {
235         return $n2s->status_id;
236     }
237 }
238
239 /**
240  * Pull any extra information from a notice that we should transfer over
241  * to Twitter beyond the notice text itself.
242  *
243  * @param Notice $notice
244  * @return array of key-value pairs for Twitter update submission
245  * @access private
246  */
247 function twitter_update_params($notice)
248 {
249     $params = array();
250     if ($notice->lat || $notice->lon) {
251         $params['lat'] = $notice->lat;
252         $params['long'] = $notice->lon;
253     }
254     if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
255         $reply = Notice::staticGet('id', $notice->reply_to);
256         $params['in_reply_to_status_id'] = twitter_status_id($reply);
257     }
258     return $params;
259 }
260
261 function broadcast_oauth($notice, $flink) {
262     $user = $flink->getUser();
263     $statustxt = format_status($notice);
264     $params = twitter_update_params($notice);
265
266     $token = TwitterOAuthClient::unpackToken($flink->credentials);
267     $client = new TwitterOAuthClient($token->key, $token->secret);
268     $status = null;
269
270     try {
271         $status = $client->statusesUpdate($statustxt, $params);
272         if (!empty($status)) {
273             Notice_to_status::saveNew($notice->id, twitter_id($status));
274         }
275     } catch (OAuthClientException $e) {
276         return process_error($e, $flink, $notice);
277     }
278
279     if (empty($status)) {
280         // This could represent a failure posting,
281         // or the Twitter API might just be behaving flakey.
282         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
283                           'trying to post notice %d for User %s (user id %d).',
284                           $notice->id,
285                           $user->nickname,
286                           $user->id);
287
288         common_log(LOG_WARNING, $errmsg);
289
290         return false;
291     }
292
293     // Notice crossed the great divide
294     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
295                    'OAuth for User %s (user id %d).',
296                    $notice->id,
297                    $user->nickname,
298                    $user->id);
299
300     common_log(LOG_INFO, $msg);
301
302     return true;
303 }
304
305 function process_error($e, $flink, $notice)
306 {
307     $user = $flink->getUser();
308     $code = $e->getCode();
309
310     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
311                       'User %s (user id: %d): %s.',
312                       $code,
313                       $notice->id,
314                       $user->nickname,
315                       $user->id,
316                       $e->getMessage());
317
318     common_log(LOG_WARNING, $logmsg);
319
320     // http://dev.twitter.com/pages/responses_errors
321     switch($code) {
322      case 400:
323          // Probably invalid data (bad Unicode chars or coords) that
324          // cannot be resolved by just sending again.
325          //
326          // It could also be rate limiting, but retrying immediately
327          // won't help much with that, so we'll discard for now.
328          // If a facility for retrying things later comes up in future,
329          // we can detect the rate-limiting headers and use that.
330          //
331          // Discard the message permanently.
332          return true;
333          break;
334      case 401:
335         // Probably a revoked or otherwise bad access token - nuke!
336         remove_twitter_link($flink);
337         return true;
338         break;
339      case 403:
340         // User has exceeder her rate limit -- toss the notice
341         return true;
342         break;
343      case 404:
344          // Resource not found. Shouldn't happen much on posting,
345          // but just in case!
346          //
347          // Consider it a matter for tossing the notice.
348          return true;
349          break;
350      default:
351
352         // For every other case, it's probably some flakiness so try
353         // sending the notice again later (requeue).
354
355         return false;
356         break;
357     }
358 }
359
360 function format_status($notice)
361 {
362     // Start with the plaintext source of this notice...
363     $statustxt = $notice->content;
364
365     // Convert !groups to #hashes
366     // XXX: Make this an optional setting?
367     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
368
369     // Twitter still has a 140-char hardcoded max.
370     if (mb_strlen($statustxt) > 140) {
371         $noticeUrl = common_shorten_url($notice->uri);
372         $urlLen = mb_strlen($noticeUrl);
373         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
374     }
375
376     return $statustxt;
377 }
378
379 function remove_twitter_link($flink)
380 {
381     $user = $flink->getUser();
382
383     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
384                "user $user->nickname (user id: $user->id).");
385
386     $result = $flink->safeDelete();
387
388     if (empty($result)) {
389         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
390                    "Foreign_link for $user->nickname (user id: $user->id)!");
391         common_log_db_error($flink, 'DELETE', __FILE__);
392     }
393
394     // Notify the user that her Twitter bridge is down
395
396     if (isset($user->email)) {
397         $result = mail_twitter_bridge_removed($user);
398
399         if (!$result) {
400             $msg = 'Unable to send email to notify ' .
401               "$user->nickname (user id: $user->id) " .
402               'that their Twitter bridge link was ' .
403               'removed!';
404
405             common_log(LOG_WARNING, $msg);
406         }
407     }
408 }
409
410 /**
411  * Send a mail message to notify a user that her Twitter bridge link
412  * has stopped working, and therefore has been removed.  This can
413  * happen when the user changes her Twitter password, or otherwise
414  * revokes access.
415  *
416  * @param User $user   user whose Twitter bridge link has been removed
417  *
418  * @return boolean success flag
419  */
420 function mail_twitter_bridge_removed($user)
421 {
422     $profile = $user->getProfile();
423
424     common_switch_locale($user->language);
425
426     // TRANS: Mail subject after forwarding notices to Twitter has stopped working.
427     $subject = sprintf(_m('Your Twitter bridge has been disabled'));
428
429     $site_name = common_config('site', 'name');
430
431     // TRANS: Mail body after forwarding notices to Twitter has stopped working.
432     // TRANS: %1$ is the name of the user the mail is sent to, %2$s is a URL to the
433     // TRANS: Twitter settings, %3$s is the StatusNet sitename.
434     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
435         'link to Twitter has been disabled. We no longer seem to have ' .
436     'permission to update your Twitter status. Did you maybe revoke ' .
437     '%3$s\'s access?' . "\n\n" .
438     'You can re-enable your Twitter bridge by visiting your ' .
439     "Twitter settings page:\n\n\t%2\$s\n\n" .
440         "Regards,\n%3\$s"),
441         $profile->getBestName(),
442         common_local_url('twittersettings'),
443         common_config('site', 'name'));
444
445     common_switch_locale();
446     return mail_to_user($user, $subject, $body);
447 }