3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2010 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 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
28 function add_twitter_user($twitter_id, $screen_name)
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);
36 $result = $luser->delete();
37 if ($result != false) {
40 "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
45 $fuser = new Foreign_user();
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();
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__);
60 "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
66 // Creates or Updates a Twitter user
67 function save_twitter_user($twitter_id, $screen_name)
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);
75 // Delete old record if Twitter user changed screen name
77 if ($fuser->nickname != $screen_name) {
78 $oldname = $fuser->nickname;
80 common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
81 'for Twitter user %1$d - %2$s, was %3$s.',
88 // Kill any old, invalid records for this screen name
89 $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
96 'Twitter bridge - deteted old record for Twitter ' .
97 'screen name "%s" belonging to Twitter ID %d.',
105 return add_twitter_user($twitter_id, $screen_name);
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)) {
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)) {
124 function is_twitter_notice($id)
126 $n2s = Notice_to_status::staticGet('notice_id', $id);
128 return (!empty($n2s));
131 function broadcast_twitter($notice)
133 $flink = Foreign_link::getByUserID($notice->profile_id,
136 // Don't bother with basic auth, since it's no longer allowed
137 if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
138 if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
139 $retweet = retweet_notice($flink, Notice::staticGet('id', $notice->repeat_of));
140 if (!empty($retweet)) {
141 Notice_to_status::saveNew($notice->id, $retweet->id);
143 } else if (is_twitter_bound($notice, $flink)) {
144 return broadcast_oauth($notice, $flink);
151 function retweet_notice($flink, $notice)
153 $token = TwitterOAuthClient::unpackToken($flink->credentials);
154 $client = new TwitterOAuthClient($token->key, $token->secret);
156 $id = twitter_status_id($notice);
159 common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
164 $status = $client->statusesRetweet($id);
166 } catch (OAuthClientException $e) {
167 return process_error($e, $flink, $notice);
171 function twitter_status_id($notice)
173 $n2s = Notice_to_status::staticGet('notice_id', $notice->id);
177 return $n2s->status_id;
182 * Pull any extra information from a notice that we should transfer over
183 * to Twitter beyond the notice text itself.
185 * @param Notice $notice
186 * @return array of key-value pairs for Twitter update submission
189 function twitter_update_params($notice)
192 if ($notice->lat || $notice->lon) {
193 $params['lat'] = $notice->lat;
194 $params['long'] = $notice->lon;
196 if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
197 $reply = Notice::staticGet('id', $notice->reply_to);
198 $params['in_reply_to_status_id'] = twitter_status_id($reply);
203 function broadcast_oauth($notice, $flink) {
204 $user = $flink->getUser();
205 $statustxt = format_status($notice);
206 $params = twitter_update_params($notice);
208 $token = TwitterOAuthClient::unpackToken($flink->credentials);
209 $client = new TwitterOAuthClient($token->key, $token->secret);
213 $status = $client->statusesUpdate($statustxt, $params);
214 if (!empty($status)) {
215 Notice_to_status::saveNew($notice->id, $status->id);
217 } catch (OAuthClientException $e) {
218 return process_error($e, $flink, $notice);
221 if (empty($status)) {
223 // This could represent a failure posting,
224 // or the Twitter API might just be behaving flakey.
225 $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
226 'trying to post notice %d for User %s (user id %d).',
231 common_log(LOG_WARNING, $errmsg);
236 // Notice crossed the great divide
237 $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
238 'OAuth for User %s (user id %d).',
243 common_log(LOG_INFO, $msg);
248 function process_error($e, $flink, $notice)
250 $user = $flink->getUser();
251 $code = $e->getCode();
253 $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
254 'User %s (user id: %d): %s.',
261 common_log(LOG_WARNING, $logmsg);
265 // Probably a revoked or otherwise bad access token - nuke!
266 remove_twitter_link($flink);
270 // User has exceeder her rate limit -- toss the notice
275 // For every other case, it's probably some flakiness so try
276 // sending the notice again later (requeue).
283 function format_status($notice)
285 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
286 $statustxt = preg_replace('/^@/', ' @', $notice->content);
288 // Convert !groups to #hashes
290 // XXX: Make this an optional setting?
292 $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
294 if (mb_strlen($statustxt) > 140) {
295 $noticeUrl = common_shorten_url($notice->uri);
296 $urlLen = mb_strlen($noticeUrl);
297 $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
303 function remove_twitter_link($flink)
305 $user = $flink->getUser();
307 common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
308 "user $user->nickname (user id: $user->id).");
310 $result = $flink->safeDelete();
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__);
318 // Notify the user that her Twitter bridge is down
320 if (isset($user->email)) {
321 $result = mail_twitter_bridge_removed($user);
324 $msg = 'Unable to send email to notify ' .
325 "$user->nickname (user id: $user->id) " .
326 'that their Twitter bridge link was ' .
329 common_log(LOG_WARNING, $msg);
335 * Send a mail message to notify a user that her Twitter bridge link
336 * has stopped working, and therefore has been removed. This can
337 * happen when the user changes her Twitter password, or otherwise
340 * @param User $user user whose Twitter bridge link has been removed
342 * @return boolean success flag
344 function mail_twitter_bridge_removed($user)
346 $profile = $user->getProfile();
348 common_switch_locale($user->language);
350 $subject = sprintf(_m('Your Twitter bridge has been disabled.'));
352 $site_name = common_config('site', 'name');
354 $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
355 'link to Twitter has been disabled. We no longer seem to have ' .
356 'permission to update your Twitter status. Did you maybe revoke ' .
357 '%3$s\'s access?' . "\n\n" .
358 'You can re-enable your Twitter bridge by visiting your ' .
359 "Twitter settings page:\n\n\t%2\$s\n\n" .
361 $profile->getBestName(),
362 common_local_url('twittersettings'),
363 common_config('site', 'name'));
365 common_switch_locale();
366 return mail_to_user($user, $subject, $body);