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