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