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