We are no longer offering accounts on this server. Consider https://gitlab.freedesktop.org/ as a place to host projects.

twitter.php 15.8 KB
Newer Older
1 2
<?php
/*
3
 * StatusNet - the distributed open-source microblogging tool
4
 * Copyright (C) 2008-2011 StatusNet, Inc.
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

20
if (!defined('STATUSNET') && !defined('LACONICA')) {
21
    exit(1);
22 23
}

24
define('TWITTER_SERVICE', 1); // Twitter is foreign_service ID 1
25

26 27
function add_twitter_user($twitter_id, $screen_name)
{
28 29 30
    // Clear out any bad old foreign_users with the new user's legit URL
    // This can happen when users move around or fakester accounts get
    // repoed, and things like that.
31 32 33
    try {
        $fuser = Foreign_user::getForeignUser($twitter_id, TWITTER_SERVICE);
        $result = $fuser->delete();
34 35 36 37 38 39
        if ($result != false) {
            common_log(
                LOG_INFO,
                "Twitter bridge - removed old Twitter user: $screen_name ($twitter_id)."
            );
        }
40 41
    } catch (NoResultException $e) {
        // 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 51
    $fuser->created = common_sql_now();
    $result = $fuser->insert();
52

53 54
    if ($result === false) {
        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 58
        common_log(LOG_INFO,
                   "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 66
function save_twitter_user($twitter_id, $screen_name)
{
67 68
    // Check to see whether the Twitter user is already in the system,
    // and update its screen name and uri if so.
69 70
    try {
        $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 75 76 77 78 79 80
            $oldname = $fuser->nickname;
            $fuser->delete();
            common_log(LOG_INFO, sprintf('Twitter bridge - Updated nickname (and URI) ' .
                                         'for Twitter user %1$d - %2$s, was %3$s.',
                                         $fuser->id,
                                         $screen_name,
                                         $oldname));
81
        }
82 83
    } catch (NoResultException $e) {
        // No old users exist for this id
84

85
        // Kill any old, invalid records for this screen name
86 87 88
        // XXX: Is this really only supposed to be run if the above getForeignUser fails?
        try {
            $fuser = Foreign_user::getByNickname($screen_name, TWITTER_SERVICE);
89 90 91 92 93 94 95 96 97 98
            $fuser->delete();
            common_log(
                LOG_INFO,
                sprintf(
                    'Twitter bridge - deteted old record for Twitter ' .
                    'screen name "%s" belonging to Twitter ID %d.',
                    $screen_name,
                    $fuser->id
                )
            );
99 100
        } catch (NoResultException $e) {
            // 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 110 111 112 113

    // Don't send activity activities (at least for now)
    if ($notice->object_type == ActivityObject::ACTIVITY) {
        return false;
    }

114 115 116 117
    $allowedVerbs = array(ActivityVerb::POST, ActivityVerb::SHARE);

    // Don't send things that aren't posts or repeats (at least for now)
    if (!in_array($notice->verb, $allowedVerbs)) {
118 119 120
        return false;
    }

121
    // Check to see if notice should go to Twitter
122
    if (!empty($flink) && (($flink->noticesync & FOREIGN_NOTICE_SEND) == FOREIGN_NOTICE_SEND)) {
123

124 125
        // If it's not a Twitter-style reply, or if the user WANTS to send replies,
        // 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
             (empty($notice->reply_to) && !preg_match('/^@[a-zA-Z0-9_]{1,15}\b/u', $notice->content)) ){
129
            return true;
130 131
        }
    }
132

133 134 135
    return false;
}

136 137
function is_twitter_notice($id)
{
138
    $n2s = Notice_to_status::getKV('notice_id', $id);
139

140
    return (!empty($n2s));
141 142
}

143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170
/**
 * Pull the formatted status ID number from a Twitter status object
 * returned via JSON from Twitter API.
 *
 * Encapsulates checking for the id_str attribute, which is required
 * to read 64-bit "Snowflake" ID numbers on a 32-bit system -- the
 * integer id attribute gets corrupted into a double-precision float,
 * losing a few digits of precision.
 *
 * Warning: avoid performing arithmetic or direct comparisons with
 * this number, as it may get coerced back to a double on 32-bit.
 *
 * @param object $status
 * @param string $field base field name if not 'id'
 * @return mixed id number as int or string
 */
function twitter_id($status, $field='id')
{
    $field_str = "{$field}_str";
    if (isset($status->$field_str)) {
        // String version of the id -- required on 32-bit systems
        // since the 64-bit numbers get corrupted as ints.
        return $status->$field_str;
    } else {
        return $status->$field;
    }
}

171 172 173 174 175 176 177 178 179 180
/**
 * Check if we need to broadcast a notice over the Twitter bridge, and
 * do so if necessary. Will determine whether to do a straight post or
 * a repeat/retweet
 *
 * This function is meant to be called directly from TwitterQueueHandler.
 *
 * @param Notice $notice
 * @return boolean true if complete or successful, false if we should retry
 */
181 182
function broadcast_twitter($notice)
{
183 184 185 186 187 188
    try {
        $flink = Foreign_link::getByUserID($notice->profile_id, TWITTER_SERVICE);
    } catch (NoResultException $e) {
        // Alright so don't broadcast it then! (since there's no foreign link)
        return true;
    }
189

190
    // Don't bother with basic auth, since it's no longer allowed
191
    if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
192 193
        if (is_twitter_bound($notice, $flink)) {
            if (!empty($notice->repeat_of) && is_twitter_notice($notice->repeat_of)) {
194
                $retweet = retweet_notice($flink, Notice::getKV('id', $notice->repeat_of));
195 196 197 198 199 200 201 202
                if (is_object($retweet)) {
                    Notice_to_status::saveNew($notice->id, twitter_id($retweet));
                    return true;
                } else {
                    // Our error processing will have decided if we need to requeue
                    // this or can discard safely.
                    return $retweet;
                }
203
            } else {
204
                return broadcast_oauth($notice, $flink);
205
            }
206 207
        }
    }
208

209
    return true;
210
}
211

212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
/**
 * Send a retweet to Twitter for a notice that has been previously bridged
 * in or out.
 *
 * Warning: the return value is not guaranteed to be an object; some error
 * conditions will return a 'true' which should be passed on to a calling
 * queue handler.
 *
 * No local information about the resulting retweet is saved: it's up to
 * caller to save new mappings etc if appropriate.
 *
 * @param Foreign_link $flink
 * @param Notice $notice
 * @return mixed object with resulting Twitter status data on success, or true/false/null on error conditions.
 */
227 228 229 230 231 232 233
function retweet_notice($flink, $notice)
{
    $token = TwitterOAuthClient::unpackToken($flink->credentials);
    $client = new TwitterOAuthClient($token->key, $token->secret);

    $id = twitter_status_id($notice);

234 235 236 237 238
    if (empty($id)) {
        common_log(LOG_WARNING, "Trying to retweet notice {$notice->id} with no known status id.");
        return null;
    }

239 240
    try {
        $status = $client->statusesRetweet($id);
241
        return $status;
242 243 244 245 246 247 248
    } catch (OAuthClientException $e) {
        return process_error($e, $flink, $notice);
    }
}

function twitter_status_id($notice)
{
249
    $n2s = Notice_to_status::getKV('notice_id', $notice->id);
250 251 252 253
    if (empty($n2s)) {
        return null;
    } else {
        return $n2s->status_id;
254 255 256
    }
}

257 258 259 260 261 262 263 264 265 266 267 268 269 270 271
/**
 * Pull any extra information from a notice that we should transfer over
 * to Twitter beyond the notice text itself.
 *
 * @param Notice $notice
 * @return array of key-value pairs for Twitter update submission
 * @access private
 */
function twitter_update_params($notice)
{
    $params = array();
    if ($notice->lat || $notice->lon) {
        $params['lat'] = $notice->lat;
        $params['long'] = $notice->lon;
    }
272
    if (!empty($notice->reply_to) && is_twitter_notice($notice->reply_to)) {
273
        $reply = Notice::getKV('id', $notice->reply_to);
274 275
        $params['in_reply_to_status_id'] = twitter_status_id($reply);
    }
276 277 278
    return $params;
}

279 280 281 282 283 284 285
function broadcast_oauth($notice, Foreign_link $flink) {
    try {
        $user = $flink->getUser();
    } catch (ServerException $e) {
        common_log(LOG_WARNING, 'Discarding broadcast_oauth for notice '.$notice->id.' because of exception: '.$e->getMessage());
        return true;
    }
286
    $statustxt = format_status($notice);
287 288
    $params = twitter_update_params($notice);

289 290 291
    $token = TwitterOAuthClient::unpackToken($flink->credentials);
    $client = new TwitterOAuthClient($token->key, $token->secret);
    $status = null;
292

293
    try {
294
        $status = $client->statusesUpdate($statustxt, $params);
295
        if (!empty($status)) {
296
            Notice_to_status::saveNew($notice->id, twitter_id($status));
297
        }
Zach Copley's avatar
Zach Copley committed
298
    } catch (OAuthClientException $e) {
299
        return process_error($e, $flink, $notice);
300
    }
301

302 303 304
    if (empty($status)) {
        // This could represent a failure posting,
        // or the Twitter API might just be behaving flakey.
Zach Copley's avatar
Zach Copley committed
305
        $errmsg = sprintf('Twitter bridge - No data returned by Twitter API when ' .
306 307 308 309 310
                          'trying to post notice %d for User %s (user id %d).',
                          $notice->id,
                          $user->nickname,
                          $user->id);

311
        common_log(LOG_WARNING, $errmsg);
312

313 314
        return false;
    }
315

316
    // Notice crossed the great divide
317 318 319 320 321 322
    $msg = sprintf('Twitter bridge - posted notice %d to Twitter using ' .
                   'OAuth for User %s (user id %d).',
                   $notice->id,
                   $user->nickname,
                   $user->id);

323
    common_log(LOG_INFO, $msg);
324

325 326
    return true;
}
327

328
function process_error($e, $flink, $notice)
Zach Copley's avatar
Zach Copley committed
329
{
330 331 332 333 334 335 336 337 338 339
    $user = $flink->getUser();
    $code = $e->getCode();

    $logmsg = sprintf('Twitter bridge - %d posting notice %d for ' .
                      'User %s (user id: %d): %s.',
                      $code,
                      $notice->id,
                      $user->nickname,
                      $user->id,
                      $e->getMessage());
340

Zach Copley's avatar
Zach Copley committed
341
    common_log(LOG_WARNING, $logmsg);
342

343
    // http://dev.twitter.com/pages/responses_errors
344
    switch($code) {
345 346 347 348 349 350 351 352 353 354 355 356
     case 400:
         // Probably invalid data (bad Unicode chars or coords) that
         // cannot be resolved by just sending again.
         //
         // It could also be rate limiting, but retrying immediately
         // won't help much with that, so we'll discard for now.
         // If a facility for retrying things later comes up in future,
         // we can detect the rate-limiting headers and use that.
         //
         // Discard the message permanently.
         return true;
         break;
357
     case 401:
358 359 360
        // Probably a revoked or otherwise bad access token - nuke!
        remove_twitter_link($flink);
        return true;
361 362 363 364 365
        break;
     case 403:
        // User has exceeder her rate limit -- toss the notice
        return true;
        break;
366 367 368 369 370 371 372
     case 404:
         // Resource not found. Shouldn't happen much on posting,
         // but just in case!
         //
         // Consider it a matter for tossing the notice.
         return true;
         break;
373
     default:
374 375 376 377 378

        // For every other case, it's probably some flakiness so try
        // sending the notice again later (requeue).

        return false;
379
        break;
380
    }
381 382
}

383 384
function format_status($notice)
{
385 386
    // Start with the plaintext source of this notice...
    $statustxt = $notice->content;
387 388

    // Convert !groups to #hashes
389
    // XXX: Make this an optional setting?
390 391
    $statustxt = preg_replace('/(^|\s)!([A-Za-z0-9]{1,64})/', "\\1#\\2", $statustxt);

392 393 394 395 396
    // detect links, each link uses 23 characters on twitter
    $numberOfLinks = preg_match_all('`((http|https|ftp)://[^\s<]+[^\s<\.)])`i', $statustxt);
    $statusWithoutLinks = preg_replace('`((http|https|ftp)://[^\s<]+[^\s<\.)])`i', '', $statustxt);
    $statusLength = mb_strlen($statusWithoutLinks)  + $numberOfLinks * 23;

397
    // Twitter still has a 140-char hardcoded max.
398
    if ($statusLength > 140) {
mattl's avatar
mattl committed
399
        $noticeUrl = common_shorten_url($notice->getUrl());
400 401
        // each link uses 23 chars on twitter + 3 for the ' … ' => 26
        $statustxt = mb_substr($statustxt, 0, 140 - 26) . ' … ' . $noticeUrl;
402 403
    }

404
    return $statustxt;
405 406 407 408 409 410 411
}

function remove_twitter_link($flink)
{
    $user = $flink->getUser();

    common_log(LOG_INFO, 'Removing Twitter bridge Foreign link for ' .
412
               "user $user->nickname (user id: $user->id).");
413

414
    $result = $flink->safeDelete();
415 416 417

    if (empty($result)) {
        common_log(LOG_ERR, 'Could not remove Twitter bridge ' .
418
                   "Foreign_link for $user->nickname (user id: $user->id)!");
419 420 421 422 423
        common_log_db_error($flink, 'DELETE', __FILE__);
    }

    // Notify the user that her Twitter bridge is down

424
    if (isset($user->email)) {
425
        $result = mail_twitter_bridge_removed($user);
426

427 428 429 430 431
        if (!$result) {
            $msg = 'Unable to send email to notify ' .
              "$user->nickname (user id: $user->id) " .
              'that their Twitter bridge link was ' .
              'removed!';
432

433 434
            common_log(LOG_WARNING, $msg);
        }
435
    }
436
}
437 438 439 440 441 442 443 444 445 446 447 448 449 450 451

/**
 * Send a mail message to notify a user that her Twitter bridge link
 * has stopped working, and therefore has been removed.  This can
 * happen when the user changes her Twitter password, or otherwise
 * revokes access.
 *
 * @param User $user   user whose Twitter bridge link has been removed
 *
 * @return boolean success flag
 */
function mail_twitter_bridge_removed($user)
{
    $profile = $user->getProfile();

452 453
    common_switch_locale($user->language);

Siebrand Mazeland's avatar
Siebrand Mazeland committed
454 455
    // TRANS: Mail subject after forwarding notices to Twitter has stopped working.
    $subject = sprintf(_m('Your Twitter bridge has been disabled'));
456 457 458

    $site_name = common_config('site', 'name');

Siebrand Mazeland's avatar
Siebrand Mazeland committed
459 460 461
    // TRANS: Mail body after forwarding notices to Twitter has stopped working.
    // TRANS: %1$ is the name of the user the mail is sent to, %2$s is a URL to the
    // TRANS: Twitter settings, %3$s is the StatusNet sitename.
462
    $body = sprintf(_m('Hi, %1$s. We\'re sorry to inform you that your ' .
463
        'link to Twitter has been disabled. We no longer seem to have ' .
Siebrand Mazeland's avatar
Siebrand Mazeland committed
464 465
    'permission to update your Twitter status. Did you maybe revoke ' .
    '%3$s\'s access?' . "\n\n" .
466 467
    'You can re-enable your Twitter bridge by visiting your ' .
    "Twitter settings page:\n\n\t%2\$s\n\n" .
468
        "Regards,\n%3\$s"),
469 470 471 472
        $profile->getBestName(),
        common_local_url('twittersettings'),
        common_config('site', 'name'));

473
    common_switch_locale();
474 475
    return mail_to_user($user, $subject, $body);
}