3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, Control Yourself, 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('LACONICA')) { exit(1); }
22 define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
24 function get_twitter_data($uri, $screen_name, $password)
28 CURLOPT_USERPWD => sprintf("%s:%s", $screen_name, $password),
29 CURLOPT_RETURNTRANSFER => true,
30 CURLOPT_FAILONERROR => true,
31 CURLOPT_HEADER => false,
32 CURLOPT_FOLLOWLOCATION => true,
33 CURLOPT_USERAGENT => "Laconica",
34 CURLOPT_CONNECTTIMEOUT => 120,
35 CURLOPT_TIMEOUT => 120,
36 # Twitter is strict about accepting invalid "Expect" headers
37 CURLOPT_HTTPHEADER => array('Expect:')
40 $ch = curl_init($uri);
41 curl_setopt_array($ch, $options);
42 $data = curl_exec($ch);
43 $errmsg = curl_error($ch);
46 common_debug("Twitter bridge - cURL error: $errmsg - trying to load: $uri with user $screen_name.",
49 if (defined('SCRIPT_DEBUG')) {
50 print "cURL error: $errmsg - trying to load: $uri with user $screen_name.\n";
59 function twitter_json_data($uri, $screen_name, $password)
61 $json_data = get_twitter_data($uri, $screen_name, $password);
67 $data = json_decode($json_data);
76 function twitter_user_info($screen_name, $password)
78 $uri = "http://twitter.com/users/show/$screen_name.json";
79 return twitter_json_data($uri, $screen_name, $password);
82 function twitter_friends_ids($screen_name, $password)
84 $uri = "http://twitter.com/friends/ids/$screen_name.json";
85 return twitter_json_data($uri, $screen_name, $password);
88 function update_twitter_user($twitter_id, $screen_name)
90 $uri = 'http://twitter.com/' . $screen_name;
92 $fuser = new Foreign_user();
94 $fuser->query('BEGIN');
96 // Dropping down to SQL because regular db_object udpate stuff doesn't seem
97 // to work so good with tables that have multiple column primary keys
99 // Any time we update the uri for a forein user we have to make sure there
100 // are no dupe entries first -- unique constraint on the uri column
102 $qry = 'UPDATE foreign_user set uri = \'\' WHERE uri = ';
103 $qry .= '\'' . $uri . '\'' . ' AND service = ' . TWITTER_SERVICE;
105 $result = $fuser->query($qry);
108 common_debug("Removed uri ($uri) from another foreign_user who was squatting on it.");
109 if (defined('SCRIPT_DEBUG')) {
110 print("Removed uri ($uri) from another Twitter user who was squatting on it.\n");
115 $qry = 'UPDATE foreign_user SET nickname = ';
116 $qry .= '\'' . $screen_name . '\'' . ', uri = \'' . $uri . '\' ';
117 $qry .= 'WHERE id = ' . $twitter_id . ' AND service = ' . TWITTER_SERVICE;
119 $result = $fuser->query($qry);
122 common_log(LOG_WARNING,
123 "Couldn't update foreign_user data for Twitter user: $screen_name");
124 common_log_db_error($fuser, 'UPDATE', __FILE__);
125 if (defined('SCRIPT_DEBUG')) {
126 print "UPDATE failed: for Twitter user: $twitter_id - $screen_name. - ";
127 print common_log_objstring($fuser) . "\n";
128 $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
129 print "DB_DataObject Error: " . $error->getMessage() . "\n";
134 $fuser->query('COMMIT');
142 function add_twitter_user($twitter_id, $screen_name)
145 $new_uri = 'http://twitter.com/' . $screen_name;
147 // Clear out any bad old foreign_users with the new user's legit URL
148 // This can happen when users move around or fakester accounts get
149 // repoed, and things like that.
150 $luser = new Foreign_user();
151 $luser->uri = $new_uri;
152 $luser->service = TWITTER_SERVICE;
153 $result = $luser->delete();
156 common_log(LOG_WARNING,
157 "Twitter bridge - removed invalid Twitter user squatting on uri: $new_uri");
158 if (defined('SCRIPT_DEBUG')) {
159 print "Removed invalid Twitter user squatting on uri: $new_uri\n";
166 // Otherwise, create a new Twitter user
167 $fuser = new Foreign_user();
169 $fuser->nickname = $screen_name;
170 $fuser->uri = 'http://twitter.com/' . $screen_name;
171 $fuser->id = $twitter_id;
172 $fuser->service = TWITTER_SERVICE;
173 $fuser->created = common_sql_now();
174 $result = $fuser->insert();
177 common_log(LOG_WARNING,
178 "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
179 common_log_db_error($fuser, 'INSERT', __FILE__);
180 if (defined('SCRIPT_DEBUG')) {
181 print "INSERT failed: could not add new Twitter user: $twitter_id - $screen_name. - ";
182 print common_log_objstring($fuser) . "\n";
183 $error = &PEAR::getStaticProperty('DB_DataObject','lastError');
184 print "DB_DataObject Error: " . $error->getMessage() . "\n";
187 common_debug("Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
188 if (defined('SCRIPT_DEBUG')) {
189 print "Added new Twitter user: $screen_name ($twitter_id).\n";
196 // Creates or Updates a Twitter user
197 function save_twitter_user($twitter_id, $screen_name)
200 // Check to see whether the Twitter user is already in the system,
201 // and update its screen name and uri if so.
202 $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
208 // Only update if Twitter screen name has changed
209 if ($fuser->nickname != $screen_name) {
210 $result = update_twitter_user($twitter_id, $screen_name);
212 common_debug('Twitter bridge - Updated nickname (and URI) for Twitter user ' .
213 "$fuser->id to $screen_name, was $fuser->nickname");
215 if (defined('SCRIPT_DEBUG')) {
216 print 'Updated nickname (and URI) for Twitter user ' .
217 "$fuser->id to $screen_name, was $fuser->nickname\n";
224 return add_twitter_user($twitter_id, $screen_name);
233 function retreive_twitter_friends($twitter_id, $screen_name, $password)
237 $uri = "http://twitter.com/statuses/friends/$twitter_id.json?page=";
238 $friends_ids = twitter_friends_ids($screen_name, $password);
244 if (defined('SCRIPT_DEBUG')) {
245 print "Twitter 'social graph' ids method says $screen_name has " .
246 count($friends_ids) . " friends.\n";
249 // Calculate how many pages to get...
250 $pages = ceil(count($friends_ids) / 100);
253 common_log(LOG_WARNING,
254 "Twitter bridge - $screen_name seems to have no friends.");
255 if (defined('SCRIPT_DEBUG')) {
256 print "$screen_name seems to have no friends.\n";
260 for ($i = 1; $i <= $pages; $i++) {
262 $data = get_twitter_data($uri . $i, $screen_name, $password);
265 common_log(LOG_WARNING,
266 "Twitter bridge - Couldn't retrieve page $i of $screen_name's friends.");
267 if (defined('SCRIPT_DEBUG')) {
268 print "Couldn't retrieve page $i of $screen_name's friends.\n";
273 $more_friends = json_decode($data);
275 if (!$more_friends) {
277 common_log(LOG_WARNING,
278 "Twitter bridge - No data for page $i of $screen_name's friends.");
279 if (defined('SCRIPT_DEBUG')) {
280 print "No data for page $i of $screen_name's friends.\n";
285 $friends = array_merge($friends, $more_friends);
291 function save_twitter_friends($user, $twitter_id, $screen_name, $password)
294 $friends = retreive_twitter_friends($twitter_id, $screen_name, $password);
296 if (empty($friends)) {
297 common_debug("Twitter bridge - Couldn't get friends data from Twitter for $screen_name.");
298 if (defined('SCRIPT_DEBUG')) {
299 print "Couldn't get friends data from Twitter for $screen_name.\n";
304 foreach ($friends as $friend) {
306 $friend_name = $friend->screen_name;
307 $friend_id = (int) $friend->id;
309 // Update or create the Foreign_user record
310 if (!save_twitter_user($friend_id, $friend_name)) {
311 common_log(LOG_WARNING,
312 "Twitter bridge - couldn't save $screen_name's friend, $friend_name.");
313 if (defined('SCRIPT_DEBUG')) {
314 print "Couldn't save $screen_name's friend, $friend_name.\n";
319 // Check to see if there's a related local user
320 $flink = Foreign_link::getByForeignID($friend_id, 1);
324 // Get associated user and subscribe her
325 $friend_user = User::staticGet('id', $flink->user_id);
326 if (!empty($friend_user)) {
327 $result = subs_subscribe_to($user, $friend_user);
329 if ($result === true) {
330 common_debug("Twitter bridge - subscribed $friend_user->nickname to $user->nickname.");
331 if (defined('SCRIPT_DEBUG')) {
332 print("Subscribed $friend_user->nickname to $user->nickname.\n");
335 if (defined('SCRIPT_DEBUG')) {
336 print "$result ($friend_user->nickname to $user->nickname)\n";
346 function is_twitter_bound($notice, $flink) {
348 // Check to see if notice should go to Twitter
349 if (!empty($flink) && ($flink->noticesync & FOREIGN_NOTICE_SEND)) {
351 // If it's not a Twitter-style reply, or if the user WANTS to send replies.
352 if (!preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
353 ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
361 function broadcast_twitter($notice)
363 $flink = Foreign_link::getByUserID($notice->profile_id,
366 if (is_twitter_bound($notice, $flink)) {
368 $user = $flink->getUser();
370 // XXX: Hack to get around PHP cURL's use of @ being a a meta character
371 $statustxt = preg_replace('/^@/', ' @', $notice->content);
373 $client = new TwitterOAuthClient($flink->token, $flink->credentials);
378 $status = $client->statuses_update($statustxt);
379 } catch (OAuthClientCurlException $e) {
381 if ($e->getMessage() == 'The requested URL returned error: 401') {
383 $errmsg = sprintf('User %1$s (user id: %2$s) has an invalid ' .
384 'Twitter OAuth access token.',
385 $user->nickname, $user->id);
386 common_log(LOG_WARNING, $errmsg);
388 // Bad auth token! We need to delete the foreign_link
389 // to Twitter and inform the user.
391 remove_twitter_link($flink);
396 // Some other error happened, so we should probably
397 // try to send again later.
399 $errmsg = sprintf('cURL error trying to send notice to Twitter ' .
400 'for user %1$s (user id: %2$s) - ' .
401 'code: %3$s message: $4$s.',
402 $user->nickname, $user->id,
403 $e->getCode(), $e->getMessage());
404 common_log(LOG_WARNING, $errmsg);
410 if (empty($status)) {
412 // This could represent a failure posting,
413 // or the Twitter API might just be behaving flakey.
415 $errmsg = sprint('No data returned by Twitter API when ' .
416 'trying to send update for %1$s (user id %2$s).',
417 $user->nickname, $user->id);
418 common_log(LOG_WARNING, $errmsg);
423 // Notice crossed the great divide
425 $msg = sprintf('Twitter bridge posted notice %s to Twitter.',
427 common_log(LOG_INFO, $msg);
434 function remove_twitter_link($flink)
436 $user = $flink->getUser();
438 common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
439 "user $user->nickname (user id: $user->id).");
441 $result = $flink->delete();
443 if (empty($result)) {
444 common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
445 "Foreign_link for $user->nickname (user id: $user->id)!");
446 common_log_db_error($flink, 'DELETE', __FILE__);
449 // Notify the user that her Twitter bridge is down
451 if (isset($user->email)) {
453 $result = mail_twitter_bridge_removed($user);
457 $msg = 'Unable to send email to notify ' .
458 "$user->nickname (user id: $user->id) " .
459 'that their Twitter bridge link was ' .
462 common_log(LOG_WARNING, $msg);