3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) {
24 define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
26 function add_twitter_user($twitter_id, $screen_name)
28 // Clear out any bad old foreign_users with the new user's legit URL
29 // This can happen when users move around or fakester accounts get
30 // repoed, and things like that.
31 $luser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
34 $result = $luser->delete();
35 if ($result != false) {
38 "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
43 $fuser = new Foreign_user();
45 $fuser->nickname = $screen_name;
46 $fuser->uri = 'http://twitter.com/' . $screen_name;
47 $fuser->id = $twitter_id;
48 $fuser->service = TWITTER_SERVICE;
49 $fuser->created = common_sql_now();
50 $result = $fuser->insert();
53 common_log(LOG_WARNING,
54 "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
55 common_log_db_error($fuser, 'INSERT', __FILE__);
58 "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
64 // Creates or Updates a Twitter user
65 function save_twitter_user($twitter_id, $screen_name)
67 // Check to see whether the Twitter user is already in the system,
68 // and update its screen name and uri if so.
69 $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
72 // Delete old record if Twitter user changed screen name
74 if ($fuser->nickname != $screen_name) {
75 $oldname = $fuser->nickname;
77 common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
78 'for Twitter user %1$d - %2$s, was %3$s.',
84 // Kill any old, invalid records for this screen name
85 $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
92 'Twitter bridge - deteted old record for Twitter ' .
93 'screen name "%s" belonging to Twitter ID %d.',
101 return add_twitter_user($twitter_id, $screen_name);
104 function is_twitter_bound($notice, $flink) {
106 // Don't send activity activities (at least for now)
107 if ($notice->object_type == ActivityObject::ACTIVITY) {
111 $allowedVerbs = array(ActivityVerb::POST, ActivityVerb::SHARE);
113 // Don't send things that aren't posts or repeats (at least for now)
114 if (!in_array($notice->verb, $allowedVerbs)) {
118 // Check to see if notice should go to Twitter
119 if (!empty($flink) && (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND)) {
121 // If it's not a Twitter-style reply, or if the user WANTS to send replies,
122 // or if it's in reply to a twitter notice
123 if ( (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY) ||
124 ((is_twitter_notice($notice->reply_to) || is_twitter_notice($notice->repeat_of))
125 && (($flink->noticesync & FOREIGN_NOTICE_RECV) == FOREIGN_NOTICE_RECV)) ||
126 (empty($notice->reply_to) && !preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content)) ){
134 function is_twitter_notice($id)
136 $n2s = Notice_to_status::getKV('notice_id', $id);
138 return (!empty($n2s));
142 * Pull the formatted status ID number from a Twitter status object
143 * returned via JSON from Twitter API.
145 * Encapsulates checking for the id_str attribute, which is required
146 * to read 64-bit "Snowflake" ID numbers on a 32-bit system -- the
147 * integer id attribute gets corrupted into a double-precision float,
148 * losing a few digits of precision.
150 * Warning: avoid performing arithmetic or direct comparisons with
151 * this number, as it may get coerced back to a double on 32-bit.
153 * @param object $status
154 * @param string $field base field name if not 'id'
155 * @return mixed id number as int or string
157 function twitter_id($status, $field='id')
159 $field_str = "{$field}_str";
160 if (isset($status->$field_str)) {
161 // String version of the id -- required on 32-bit systems
162 // since the 64-bit numbers get corrupted as ints.
163 return $status->$field_str;
165 return $status->$field;
170 * Check if we need to broadcast a notice over the Twitter bridge, and
171 * do so if necessary. Will determine whether to do a straight post or
174 * This function is meant to be called directly from TwitterQueueHandler.
176 * @param Notice $notice
177 * @return boolean true if complete or successful, false if we should retry
179 function broadcast_twitter($notice)
181 $flink = Foreign_link::getByUserID($notice->profile_id,
184 // Don't bother with basic auth, since it's no longer allowed
185 if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
186 if (is_twitter_bound($notice, $flink)) {
187 if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
188 $retweet = retweet_notice($flink, Notice::getKV('id', $notice->repeat_of));
189 if (is_object($retweet)) {
190 Notice_to_status::saveNew($notice->id, twitter_id($retweet));
193 // Our error processing will have decided if we need to requeue
194 // this or can discard safely.
198 return broadcast_oauth($notice, $flink);
207 * Send a retweet to Twitter for a notice that has been previously bridged
210 * Warning: the return value is not guaranteed to be an object; some error
211 * conditions will return a 'true' which should be passed on to a calling
214 * No local information about the resulting retweet is saved: it's up to
215 * caller to save new mappings etc if appropriate.
217 * @param Foreign_link $flink
218 * @param Notice $notice
219 * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
221 function retweet_notice($flink, $notice)
223 $token = TwitterOAuthClient::unpackToken($flink->credentials);
224 $client = new TwitterOAuthClient($token->key, $token->secret);
226 $id = twitter_status_id($notice);
229 common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
234 $status = $client->statusesRetweet($id);
236 } catch (OAuthClientException $e) {
237 return process_error($e, $flink, $notice);
241 function twitter_status_id($notice)
243 $n2s = Notice_to_status::getKV('notice_id', $notice->id);
247 return $n2s->status_id;
252 * Pull any extra information from a notice that we should transfer over
253 * to Twitter beyond the notice text itself.
255 * @param Notice $notice
256 * @return array of key-value pairs for Twitter update submission
259 function twitter_update_params($notice)
262 if ($notice->lat || $notice->lon) {
263 $params['lat'] = $notice->lat;
264 $params['long'] = $notice->lon;
266 if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
267 $reply = Notice::getKV('id', $notice->reply_to);
268 $params['in_reply_to_status_id'] = twitter_status_id($reply);
273 function broadcast_oauth($notice, $flink) {
274 $user = $flink->getUser();
275 $statustxt = format_status($notice);
276 $params = twitter_update_params($notice);
278 $token = TwitterOAuthClient::unpackToken($flink->credentials);
279 $client = new TwitterOAuthClient($token->key, $token->secret);
283 $status = $client->statusesUpdate($statustxt, $params);
284 if (!empty($status)) {
285 Notice_to_status::saveNew($notice->id, twitter_id($status));
287 } catch (OAuthClientException $e) {
288 return process_error($e, $flink, $notice);
291 if (empty($status)) {
292 // This could represent a failure posting,
293 // or the Twitter API might just be behaving flakey.
294 $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
295 'trying to post notice %d for User %s (user id %d).',
300 common_log(LOG_WARNING, $errmsg);
305 // Notice crossed the great divide
306 $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
307 'OAuth for User %s (user id %d).',
312 common_log(LOG_INFO, $msg);
317 function process_error($e, $flink, $notice)
319 $user = $flink->getUser();
320 $code = $e->getCode();
322 $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
323 'User %s (user id: %d): %s.',
330 common_log(LOG_WARNING, $logmsg);
332 // http://dev.twitter.com/pages/responses_errors
335 // Probably invalid data (bad Unicode chars or coords) that
336 // cannot be resolved by just sending again.
338 // It could also be rate limiting, but retrying immediately
339 // won't help much with that, so we'll discard for now.
340 // If a facility for retrying things later comes up in future,
341 // we can detect the rate-limiting headers and use that.
343 // Discard the message permanently.
347 // Probably a revoked or otherwise bad access token - nuke!
348 remove_twitter_link($flink);
352 // User has exceeder her rate limit -- toss the notice
356 // Resource not found. Shouldn't happen much on posting,
359 // Consider it a matter for tossing the notice.
364 // For every other case, it's probably some flakiness so try
365 // sending the notice again later (requeue).
372 function format_status($notice)
374 // Start with the plaintext source of this notice...
375 $statustxt = $notice->content;
377 // Convert !groups to #hashes
378 // XXX: Make this an optional setting?
379 $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
381 // Twitter still has a 140-char hardcoded max.
382 if (mb_strlen($statustxt) > 140) {
383 $noticeUrl = common_shorten_url($notice->getUrl());
384 $urlLen = mb_strlen($noticeUrl);
385 $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
391 function remove_twitter_link($flink)
393 $user = $flink->getUser();
395 common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
396 "user $user->nickname (user id: $user->id).");
398 $result = $flink->safeDelete();
400 if (empty($result)) {
401 common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
402 "Foreign_link for $user->nickname (user id: $user->id)!");
403 common_log_db_error($flink, 'DELETE', __FILE__);
406 // Notify the user that her Twitter bridge is down
408 if (isset($user->email)) {
409 $result = mail_twitter_bridge_removed($user);
412 $msg = 'Unable to send email to notify ' .
413 "$user->nickname (user id: $user->id) " .
414 'that their Twitter bridge link was ' .
417 common_log(LOG_WARNING, $msg);
423 * Send a mail message to notify a user that her Twitter bridge link
424 * has stopped working, and therefore has been removed. This can
425 * happen when the user changes her Twitter password, or otherwise
428 * @param User $user user whose Twitter bridge link has been removed
430 * @return boolean success flag
432 function mail_twitter_bridge_removed($user)
434 $profile = $user->getProfile();
436 common_switch_locale($user->language);
438 // TRANS: Mail subject after forwarding notices to Twitter has stopped working.
439 $subject = sprintf(_m('Your Twitter bridge has been disabled'));
441 $site_name = common_config('site', 'name');
443 // TRANS: Mail body after forwarding notices to Twitter has stopped working.
444 // TRANS: %1$ is the name of the user the mail is sent to, %2$s is a URL to the
445 // TRANS: Twitter settings, %3$s is the StatusNet sitename.
446 $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
447 'link to Twitter has been disabled. We no longer seem to have ' .
448 'permission to update your Twitter status. Did you maybe revoke ' .
449 '%3$s\'s access?' . "\n\n" .
450 'You can re-enable your Twitter bridge by visiting your ' .
451 "Twitter settings page:\n\n\t%2\$s\n\n" .
453 $profile->getBestName(),
454 common_local_url('twittersettings'),
455 common_config('site', 'name'));
457 common_switch_locale();
458 return mail_to_user($user, $subject, $body);