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