]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/twitter.php
TwitterBridge messing about, Twitter OAuth requires Authorization header now?
[quix0rs-gnu-social.git] / plugins / TwitterBridge / twitter.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008-2011 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 function add_twitter_user($twitter_id, $screen_name)
27 {
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     try {
32         $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
33         $result = $fuser->delete();
34         if ($result != false) {
35             common_log(
36                 LOG_INFO,
37                 "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
38             );
39         }
40     } catch (NoResultException $e) {
41         // no old foreign users exist for this id
42     }
43
44     $fuser = new Foreign_user();
45
46     $fuser->nickname = $screen_name;
47     $fuser->uri = 'http://twitter.com/' . $screen_name;
48     $fuser->id = $twitter_id;
49     $fuser->service = TWITTER_SERVICE;
50     $fuser->created = common_sql_now();
51     $result = $fuser->insert();
52
53     if ($result === false) {
54         common_log(LOG_WARNING, "Twitter bridge - failed to add new Twitter user: $twitter_id - $screen_name.");
55         common_log_db_error($fuser, 'INSERT', __FILE__);
56     } else {
57         common_log(LOG_INFO,
58                    "Twitter bridge - Added new Twitter user: $screen_name ($twitter_id).");
59     }
60
61     return $result;
62 }
63
64 // Creates or Updates a Twitter user
65 function save_twitter_user($twitter_id, $screen_name)
66 {
67     // Check to see whether the Twitter user is already in the system,
68     // and update its screen name and uri if so.
69     try {
70         $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
71
72         // Delete old record if Twitter user changed screen name
73         if ($fuser->nickname != $screen_name) {
74             $oldname = $fuser->nickname;
75             $fuser->delete();
76             common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
77                                          'for Twitter user %1$d - %2$s, was %3$s.',
78                                          $fuser->id,
79                                          $screen_name,
80                                          $oldname));
81         }
82     } catch (NoResultException $e) {
83         // No old users exist for this id
84     
85         // Kill any old, invalid records for this screen name
86         // XXX: Is this really only supposed to be run if the above getForeignUser fails?
87         try {
88             $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
89             $fuser->delete();
90             common_log(
91                 LOG_INFO,
92                 sprintf(
93                     'Twitter bridge - deteted old record for Twitter ' .
94                     'screen name "%s" belonging to Twitter ID %d.',
95                     $screen_name,
96                     $fuser->id
97                 )
98             );
99         } catch (NoResultException $e) {
100             // No old users exist for this screen_name
101         }
102     }
103
104     return add_twitter_user($twitter_id, $screen_name);
105 }
106
107 function is_twitter_bound($notice, $flink) {
108
109     // Don't send activity activities (at least for now)
110     if ($notice->object_type == ActivityObject::ACTIVITY) {
111         return false;
112     }
113
114     $allowedVerbs = array(ActivityVerb::POST, ActivityVerb::SHARE);
115
116     // Don't send things that aren't posts or repeats (at least for now)
117     if (!in_array($notice->verb, $allowedVerbs)) {
118         return false;
119     }
120
121     // Check to see if notice should go to Twitter
122     if (!empty($flink) && (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND)) {
123
124         // If it's not a Twitter-style reply, or if the user WANTS to send replies,
125         // or if it's in reply to a twitter notice
126         if ( (($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) == FOREIGN_NOTICE_SEND_REPLY) ||
127               ((is_twitter_notice($notice->reply_to) || is_twitter_notice($notice->repeat_of))
128               && (($flink->noticesync & FOREIGN_NOTICE_RECV) == FOREIGN_NOTICE_RECV)) ||
129              (empty($notice->reply_to) && !preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content)) ){
130             return true;
131         }
132     }
133
134     return false;
135 }
136
137 function is_twitter_notice($id)
138 {
139     $n2s = Notice_to_status::getKV('notice_id', $id);
140
141     return (!empty($n2s));
142 }
143
144 /**
145  * Pull the formatted status ID number from a Twitter status object
146  * returned via JSON from Twitter API.
147  *
148  * Encapsulates checking for the id_str attribute, which is required
149  * to read 64-bit "Snowflake" ID numbers on a 32-bit system -- the
150  * integer id attribute gets corrupted into a double-precision float,
151  * losing a few digits of precision.
152  *
153  * Warning: avoid performing arithmetic or direct comparisons with
154  * this number, as it may get coerced back to a double on 32-bit.
155  *
156  * @param object $status
157  * @param string $field base field name if not 'id'
158  * @return mixed id number as int or string
159  */
160 function twitter_id($status, $field='id')
161 {
162     $field_str = "{$field}_str";
163     if (isset($status->$field_str)) {
164         // String version of the id -- required on 32-bit systems
165         // since the 64-bit numbers get corrupted as ints.
166         return $status->$field_str;
167     } else {
168         return $status->$field;
169     }
170 }
171
172 /**
173  * Check if we need to broadcast a notice over the Twitter bridge, and
174  * do so if necessary. Will determine whether to do a straight post or
175  * a repeat/retweet
176  *
177  * This function is meant to be called directly from TwitterQueueHandler.
178  *
179  * @param Notice $notice
180  * @return boolean true if complete or successful, false if we should retry
181  */
182 function broadcast_twitter($notice)
183 {
184     $flink = Foreign_link::getByUserID($notice->profile_id,
185                                        TWITTER_SERVICE);
186
187     // Don't bother with basic auth, since it's no longer allowed
188     if (!empty($flink) && TwitterOAuthClient::isPackedToken($flink->credentials)) {
189         if (is_twitter_bound($notice, $flink)) {
190             if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
191                 $retweet = retweet_notice($flink, Notice::getKV('id', $notice->repeat_of));
192                 if (is_object($retweet)) {
193                     Notice_to_status::saveNew($notice->id, twitter_id($retweet));
194                     return true;
195                 } else {
196                     // Our error processing will have decided if we need to requeue
197                     // this or can discard safely.
198                     return $retweet;
199                 }
200             } else {
201                 return broadcast_oauth($notice, $flink);
202             }
203         }
204     }
205
206     return true;
207 }
208
209 /**
210  * Send a retweet to Twitter for a notice that has been previously bridged
211  * in or out.
212  *
213  * Warning: the return value is not guaranteed to be an object; some error
214  * conditions will return a 'true' which should be passed on to a calling
215  * queue handler.
216  *
217  * No local information about the resulting retweet is saved: it's up to
218  * caller to save new mappings etc if appropriate.
219  *
220  * @param Foreign_link $flink
221  * @param Notice $notice
222  * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
223  */
224 function retweet_notice($flink, $notice)
225 {
226     $token = TwitterOAuthClient::unpackToken($flink->credentials);
227     $client = new TwitterOAuthClient($token->key, $token->secret);
228
229     $id = twitter_status_id($notice);
230
231     if (empty($id)) {
232         common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
233         return null;
234     }
235
236     try {
237         $status = $client->statusesRetweet($id);
238         return $status;
239     } catch (OAuthClientException $e) {
240         return process_error($e, $flink, $notice);
241     }
242 }
243
244 function twitter_status_id($notice)
245 {
246     $n2s = Notice_to_status::getKV('notice_id', $notice->id);
247     if (empty($n2s)) {
248         return null;
249     } else {
250         return $n2s->status_id;
251     }
252 }
253
254 /**
255  * Pull any extra information from a notice that we should transfer over
256  * to Twitter beyond the notice text itself.
257  *
258  * @param Notice $notice
259  * @return array of key-value pairs for Twitter update submission
260  * @access private
261  */
262 function twitter_update_params($notice)
263 {
264     $params = array();
265     if ($notice->lat || $notice->lon) {
266         $params['lat'] = $notice->lat;
267         $params['long'] = $notice->lon;
268     }
269     if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
270         $reply = Notice::getKV('id', $notice->reply_to);
271         $params['in_reply_to_status_id'] = twitter_status_id($reply);
272     }
273     return $params;
274 }
275
276 function broadcast_oauth($notice, $flink) {
277     $user = $flink->getUser();
278     $statustxt = format_status($notice);
279     $params = twitter_update_params($notice);
280
281     $token = TwitterOAuthClient::unpackToken($flink->credentials);
282     $client = new TwitterOAuthClient($token->key, $token->secret);
283     $status = null;
284
285     try {
286         $status = $client->statusesUpdate($statustxt, $params);
287         if (!empty($status)) {
288             Notice_to_status::saveNew($notice->id, twitter_id($status));
289         }
290     } catch (OAuthClientException $e) {
291         return process_error($e, $flink, $notice);
292     }
293
294     if (empty($status)) {
295         // This could represent a failure posting,
296         // or the Twitter API might just be behaving flakey.
297         $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
298                           'trying to post notice %d for User %s (user id %d).',
299                           $notice->id,
300                           $user->nickname,
301                           $user->id);
302
303         common_log(LOG_WARNING, $errmsg);
304
305         return false;
306     }
307
308     // Notice crossed the great divide
309     $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
310                    'OAuth for User %s (user id %d).',
311                    $notice->id,
312                    $user->nickname,
313                    $user->id);
314
315     common_log(LOG_INFO, $msg);
316
317     return true;
318 }
319
320 function process_error($e, $flink, $notice)
321 {
322     $user = $flink->getUser();
323     $code = $e->getCode();
324
325     $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
326                       'User %s (user id: %d): %s.',
327                       $code,
328                       $notice->id,
329                       $user->nickname,
330                       $user->id,
331                       $e->getMessage());
332
333     common_log(LOG_WARNING, $logmsg);
334
335     // http://dev.twitter.com/pages/responses_errors
336     switch($code) {
337      case 400:
338          // Probably invalid data (bad Unicode chars or coords) that
339          // cannot be resolved by just sending again.
340          //
341          // It could also be rate limiting, but retrying immediately
342          // won't help much with that, so we'll discard for now.
343          // If a facility for retrying things later comes up in future,
344          // we can detect the rate-limiting headers and use that.
345          //
346          // Discard the message permanently.
347          return true;
348          break;
349      case 401:
350         // Probably a revoked or otherwise bad access token - nuke!
351         remove_twitter_link($flink);
352         return true;
353         break;
354      case 403:
355         // User has exceeder her rate limit -- toss the notice
356         return true;
357         break;
358      case 404:
359          // Resource not found. Shouldn't happen much on posting,
360          // but just in case!
361          //
362          // Consider it a matter for tossing the notice.
363          return true;
364          break;
365      default:
366
367         // For every other case, it's probably some flakiness so try
368         // sending the notice again later (requeue).
369
370         return false;
371         break;
372     }
373 }
374
375 function format_status($notice)
376 {
377     // Start with the plaintext source of this notice...
378     $statustxt = $notice->content;
379
380     // Convert !groups to #hashes
381     // XXX: Make this an optional setting?
382     $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);
383
384     // Twitter still has a 140-char hardcoded max.
385     if (mb_strlen($statustxt) > 140) {
386         $noticeUrl = common_shorten_url($notice->getUrl());
387         $urlLen = mb_strlen($noticeUrl);
388         $statustxt = mb_substr($statustxt, 0, 140 - ($urlLen + 3)) . ' … ' . $noticeUrl;
389     }
390
391     return $statustxt;
392 }
393
394 function remove_twitter_link($flink)
395 {
396     $user = $flink->getUser();
397
398     common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
399                "user $user->nickname (user id: $user->id).");
400
401     $result = $flink->safeDelete();
402
403     if (empty($result)) {
404         common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
405                    "Foreign_link for $user->nickname (user id: $user->id)!");
406         common_log_db_error($flink, 'DELETE', __FILE__);
407     }
408
409     // Notify the user that her Twitter bridge is down
410
411     if (isset($user->email)) {
412         $result = mail_twitter_bridge_removed($user);
413
414         if (!$result) {
415             $msg = 'Unable to send email to notify ' .
416               "$user->nickname (user id: $user->id) " .
417               'that their Twitter bridge link was ' .
418               'removed!';
419
420             common_log(LOG_WARNING, $msg);
421         }
422     }
423 }
424
425 /**
426  * Send a mail message to notify a user that her Twitter bridge link
427  * has stopped working, and therefore has been removed.  This can
428  * happen when the user changes her Twitter password, or otherwise
429  * revokes access.
430  *
431  * @param User $user   user whose Twitter bridge link has been removed
432  *
433  * @return boolean success flag
434  */
435 function mail_twitter_bridge_removed($user)
436 {
437     $profile = $user->getProfile();
438
439     common_switch_locale($user->language);
440
441     // TRANS: Mail subject after forwarding notices to Twitter has stopped working.
442     $subject = sprintf(_m('Your Twitter bridge has been disabled'));
443
444     $site_name = common_config('site', 'name');
445
446     // TRANS: Mail body after forwarding notices to Twitter has stopped working.
447     // TRANS: %1$ is the name of the user the mail is sent to, %2$s is a URL to the
448     // TRANS: Twitter settings, %3$s is the StatusNet sitename.
449     $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
450         'link to Twitter has been disabled. We no longer seem to have ' .
451     'permission to update your Twitter status. Did you maybe revoke ' .
452     '%3$s\'s access?' . "\n\n" .
453     'You can re-enable your Twitter bridge by visiting your ' .
454     "Twitter settings page:\n\n\t%2\$s\n\n" .
455         "Regards,\n%3\$s"),
456         $profile->getBestName(),
457         common_local_url('twittersettings'),
458         common_config('site', 'name'));
459
460     common_switch_locale();
461     return mail_to_user($user, $subject, $body);
462 }