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

twitterstatusfetcher.php 26.2 KB
Newer Older
1 2
#!/usr/bin/env php
<?php
3
/**
4
 * StatusNet - the distributed open-source microblogging tool
5
 * Copyright (C) 2008-2010, StatusNet, Inc.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 *
 * 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/>.
 */

21
define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
22

23
// Tune number of processes and how often to poll Twitter
24 25 26
// XXX: Should these things be in config.php?
define('MAXCHILDREN', 2);
define('POLL_INTERVAL', 60); // in seconds
27

28 29
$shortoptions = 'di::';
$longoptions = array('id::', 'debug');
30

31 32
$helptext = <<<END_OF_TRIM_HELP
Batch script for retrieving Twitter messages from foreign service.
33

34 35
  -i --id              Identity (default 'generic')
  -d --debug           Debug (lots of log output)
Zach Copley's avatar
Zach Copley committed
36

37
END_OF_TRIM_HELP;
38

39
require_once INSTALLDIR . '/scripts/commandline.inc';
40
require_once INSTALLDIR . '/lib/common.php';
41
require_once INSTALLDIR . '/lib/daemon.php';
42
require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
43
require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
44 45

/**
46
 * Fetch statuses from Twitter
47
 *
48 49 50 51 52 53 54 55 56
 * Fetches statuses from Twitter and inserts them as notices
 *
 * NOTE: an Avatar path MUST be set in config.php for this
 * script to work, e.g.:
 *     $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
 *
 * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
 * this script is run, so the default avatar path is always set wrong in
 * default.php. Therefore it must be set explicitly in config.php. --Z
57 58
 *
 * @category Twitter
59
 * @package  StatusNet
60 61
 * @author   Zach Copley <zach@status.net>
 * @author   Evan Prodromou <evan@status.net>
62
 * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
63
 * @link     http://status.net/
64
 */
65
class TwitterStatusFetcher extends ParallelizingDaemon
66
{
67 68 69 70 71 72 73 74 75 76 77 78 79
    /**
     *  Constructor
     *
     * @param string  $id           the name/id of this daemon
     * @param int     $interval     sleep this long before doing everything again
     * @param int     $max_children maximum number of child processes at a time
     * @param boolean $debug        debug output flag
     *
     * @return void
     *
     **/
    function __construct($id = null, $interval = 60,
                         $max_children = 2, $debug = null)
Zach Copley's avatar
Zach Copley committed
80
    {
81
        parent::__construct($id, $interval, $max_children, $debug);
Zach Copley's avatar
Zach Copley committed
82 83
    }

84 85 86 87 88
    /**
     * Name of this daemon
     *
     * @return string Name of the daemon.
     */
89 90
    function name()
    {
91
        return ('twitterstatusfetcher.'.$this->_id);
92
    }
93

94
    /**
95 96
     * Find all the Twitter foreign links for users who have requested
     * importing of their friends' timelines
97
     *
98
     * @return array flinks an array of Foreign_link objects
99
     */
100
    function getObjects()
101
    {
102
        global $_DB_DATAOBJECT;
103
        $flink = new Foreign_link();
104
        $conn = &$flink->getDatabaseConnection();
105

106
        $flink->service = TWITTER_SERVICE;
107
        $flink->orderBy('last_noticesync');
108
        $flink->find();
109

110
        $flinks = array();
111

112
        while ($flink->fetch()) {
113

114 115
            if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
                FOREIGN_NOTICE_RECV) {
116
                $flinks[] = clone($flink);
117 118 119
                common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
            } else {
                common_log(LOG_INFO, "nothing to sync");
120 121
            }
        }
122

123 124
        $flink->free();
        unset($flink);
125

126 127 128
        $conn->disconnect();
        unset($_DB_DATAOBJECT['CONNECTIONS']);

129 130
        return $flinks;
    }
131

132 133 134 135
    function childTask($flink) {
        // Each child ps needs its own DB connection

        // Note: DataObject::getDatabaseConnection() creates
136
        // a new connection if there isn't one already
137 138 139 140 141 142 143 144 145
        $conn = &$flink->getDatabaseConnection();

        $this->getTimeline($flink);

        $flink->last_friendsync = common_sql_now();
        $flink->update();

        $conn->disconnect();

146
        // XXX: Couldn't find a less brutal way to blow
147 148 149
        // away a cached connection
        global $_DB_DATAOBJECT;
        unset($_DB_DATAOBJECT['CONNECTIONS']);
150 151
    }

152 153
    function getTimeline($flink)
    {
154
        if (empty($flink)) {
155
            common_log(LOG_WARNING, $this->name() .
156
                       " - Can't retrieve Foreign_link for foreign ID $fid");
157
            return;
158 159
        }

160 161
        common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
                     $flink->foreign_id);
162

163
        $client = null;
164

165 166 167 168 169
        if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
            $token = TwitterOAuthClient::unpackToken($flink->credentials);
            $client = new TwitterOAuthClient($token->key, $token->secret);
            common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
        } else {
170
            common_debug("Skipping friends timeline for $flink->foreign_id since not OAuth.");
171
        }
172

173
        $timeline = null;
174

175
        $lastId = Twitter_synch_status::getLastId($flink->foreign_id, 'home_timeline');
176

177 178
        common_debug("Got lastId value '{$lastId}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");

179
        try {
180
            $timeline = $client->statusesHomeTimeline($lastId);
181
        } catch (Exception $e) {
182
            common_log(LOG_WARNING, $this->name() .
183
                       ' - Twitter client unable to get friends timeline for user ' .
184 185 186
                       $flink->user_id . ' - code: ' .
                       $e->getCode() . 'msg: ' . $e->getMessage());
        }
187

188
        if (empty($timeline)) {
189
            common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
190
            return;
191 192
        }

193 194
        common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');

195
        // Reverse to preserve order
196

197
        foreach (array_reverse($timeline) as $status) {
198
            // Hacktastic: filter out stuff coming from this StatusNet
199
            $source = mb_strtolower(common_config('integration', 'source'));
200

201
            if (preg_match("/$source/", mb_strtolower($status->source))) {
202 203
                common_debug($this->name() . ' - Skipping import of status ' .
                             $status->id . ' with source ' . $source);
204 205
                continue;
            }
206

207 208 209 210 211 212
            // Don't save it if the user is protected
            // FIXME: save it but treat it as private
            if ($status->user->protected) {
                continue;
            }

213 214 215 216 217
            $notice = $this->saveStatus($status);

            if (!empty($notice)) {
                Inbox::insertNotice($flink->user_id, $notice->id);
            }
218
        }
219

220 221 222 223
        if (!empty($timeline)) {
            Twitter_synch_status::setLastId($flink->foreign_id, 'home_timeline', $timeline[0]->id);
            common_debug("Set lastId value '{$timeline[0]->id}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
        }
224

225 226 227
        // Okay, record the time we synced with Twitter for posterity
        $flink->last_noticesync = common_sql_now();
        $flink->update();
228
    }
229

230
    function saveStatus($status)
231
    {
232
        $profile = $this->ensureProfile($status->user);
233

234
        if (empty($profile)) {
235 236
            common_log(LOG_ERR, $this->name() .
                ' - Problem saving notice. No associated Profile.');
237
            return null;
238 239
        }

240
        $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
241

242
        // check to see if we've already imported the status
243
        $n2s = Notice_to_status::staticGet('status_id', $status->id);
244

245
        if (!empty($n2s)) {
246 247 248
            common_log(
                LOG_INFO,
                $this->name() .
249
                " - Ignoring duplicate import: {$status->id}"
250
            );
251
            return Notice::staticGet('id', $n2s->notice_id);
252 253 254 255
        }

        // If it's a retweet, save it as a repeat!
        if (!empty($status->retweeted_status)) {
256
            common_log(LOG_INFO, "Status {$status->id} is a retweet of {$status->retweeted_status->id}.");
257
            $original = $this->saveStatus($status->retweeted_status);
258 259 260 261 262 263
            if (empty($original)) {
                return null;
            } else {
                $author = $original->getProfile();
                // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
                // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
Siebrand Mazeland's avatar
Siebrand Mazeland committed
264
                $content = sprintf(_m('RT @%1$s %2$s'),
265 266
                                   $author->nickname,
                                   $original->content);
267 268 269 270 271 272

                if (Notice::contentTooLong($content)) {
                    $contentlimit = Notice::maxContent();
                    $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
                }

273 274 275 276
                $repeat = Notice::saveNew($profile->id,
                                          $content,
                                          'twitter',
                                          array('repeat_of' => $original->id,
277 278
                                                'uri' => $statusUri,
                                                'is_local' => Notice::GATEWAY));
279
                common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
280
                Notice_to_status::saveNew($repeat->id, $status->id);
281 282
                return $repeat;
            }
283 284 285 286 287 288 289 290 291 292 293 294 295
        }

        $notice = new Notice();

        $notice->profile_id = $profile->id;
        $notice->uri        = $statusUri;
        $notice->url        = $statusUri;
        $notice->created    = strftime(
            '%Y-%m-%d %H:%M:%S',
            strtotime($status->created_at)
        );

        $notice->source     = 'twitter';
296

297
        $notice->reply_to   = null;
298 299

        if (!empty($status->in_reply_to_status_id)) {
300
            common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
301 302
            $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
            if (empty($n2s)) {
303 304
                common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
            } else {
305 306 307 308 309 310 311 312
                $reply = Notice::staticGet('id', $n2s->notice_id);
                if (empty($reply)) {
                    common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
                } else {
                    common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
                    $notice->reply_to     = $reply->id;
                    $notice->conversation = $reply->conversation;
                }
313 314 315 316 317 318
            }
        }

        if (empty($notice->conversation)) {
            $conv = Conversation::create();
            $notice->conversation = $conv->id;
319
            common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
320 321
        }

322
        $notice->is_local   = Notice::GATEWAY;
323

324
        $notice->content  = html_entity_decode($status->text, ENT_QUOTES, 'UTF-8');
325
        $notice->rendered = $this->linkify($status);
326

327
        if (Event::handle('StartNoticeSave', array(&$notice))) {
328

329
            $id = $notice->insert();
330

331 332 333 334
            if (!$id) {
                common_log_db_error($notice, 'INSERT', __FILE__);
                common_log(LOG_ERR, $this->name() .
                    ' - Problem saving notice.');
335
            }
336

337
            Event::handle('EndNoticeSave', array($notice));
338
        }
339

340
        Notice_to_status::saveNew($notice->id, $status->id);
341 342 343

        $this->saveStatusMentions($notice, $status);

344
        $notice->blowOnInsert();
345 346

        return $notice;
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361
    }

    /**
     * Make an URI for a status.
     *
     * @param object $status status object
     *
     * @return string URI
     */
    function makeStatusURI($username, $id)
    {
        return 'http://twitter.com/'
          . $username
          . '/status/'
          . $id;
362
    }
363

364 365 366 367
    /**
     * Look up a Profile by profileurl field.  Profile::staticGet() was
     * not working consistently.
     *
368 369
     * @param string $nickname   local nickname of the Twitter user
     * @param string $profileurl the profile url
370
     *
371
     * @return mixed value the first Profile with that url, or null
372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387
     */
    function getProfileByUrl($nickname, $profileurl)
    {
        $profile = new Profile();
        $profile->nickname = $nickname;
        $profile->profileurl = $profileurl;
        $profile->limit(1);

        if ($profile->find()) {
            $profile->fetch();
            return $profile;
        }

        return null;
    }

388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410
    /**
     * Check to see if this Twitter status has already been imported
     *
     * @param Profile $profile   Twitter user's local profile
     * @param string  $statusUri URI of the status on Twitter
     *
     * @return mixed value a matching Notice or null
     */
    function checkDupe($profile, $statusUri)
    {
        $notice = new Notice();
        $notice->uri = $statusUri;
        $notice->profile_id = $profile->id;
        $notice->limit(1);

        if ($notice->find()) {
            $notice->fetch();
            return $notice;
        }

        return null;
    }

411 412 413 414
    function ensureProfile($user)
    {
        // check to see if there's already a profile for this user
        $profileurl = 'http://twitter.com/' . $user->screen_name;
415
        $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
416

417
        if (!empty($profile)) {
418 419
            common_debug($this->name() .
                         " - Profile for $profile->nickname found.");
420

421
            // Check to see if the user's Avatar has changed
422

423
            $this->checkAvatar($user, $profile);
424
            return $profile;
425

426
        } else {
427 428
            common_debug($this->name() . ' - Adding profile and remote profile ' .
                         "for Twitter user: $profileurl.");
429

430 431
            $profile = new Profile();
            $profile->query("BEGIN");
432

433 434 435 436 437 438 439
            $profile->nickname = $user->screen_name;
            $profile->fullname = $user->name;
            $profile->homepage = $user->url;
            $profile->bio = $user->description;
            $profile->location = $user->location;
            $profile->profileurl = $profileurl;
            $profile->created = common_sql_now();
440

441 442 443 444 445
            try {
                $id = $profile->insert();
            } catch(Exception $e) {
                common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
            }
446

447 448 449 450
            if (empty($id)) {
                common_log_db_error($profile, 'INSERT', __FILE__);
                $profile->query("ROLLBACK");
                return false;
451
            }
452

453
            // check for remote profile
454

455
            $remote_pro = Remote_profile::staticGet('uri', $profileurl);
456

457
            if (empty($remote_pro)) {
458
                $remote_pro = new Remote_profile();
459

460 461 462
                $remote_pro->id = $id;
                $remote_pro->uri = $profileurl;
                $remote_pro->created = common_sql_now();
463

464 465 466 467 468
                try {
                    $rid = $remote_pro->insert();
                } catch (Exception $e) {
                    common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
                }
469

470 471 472 473
                if (empty($rid)) {
                    common_log_db_error($profile, 'INSERT', __FILE__);
                    $profile->query("ROLLBACK");
                    return false;
474
                }
475 476
            }

477
            $profile->query("COMMIT");
478

479
            $this->saveAvatars($user, $id);
480

481
            return $profile;
482
        }
483 484
    }

485
    function checkAvatar($twitter_user, $profile)
486 487
    {
        global $config;
488

489 490 491
        $path_parts = pathinfo($twitter_user->profile_image_url);

        $newname = 'Twitter_' . $twitter_user->id . '_' .
492
            $path_parts['basename'];
493

494
        $oldname = $profile->getAvatar(48)->filename;
495

496
        if ($newname != $oldname) {
497 498 499
            common_debug($this->name() . ' - Avatar for Twitter user ' .
                         "$profile->nickname has changed.");
            common_debug($this->name() . " - old: $oldname new: $newname");
500

501 502
            $this->updateAvatars($twitter_user, $profile);
        }
503

504
        if ($this->missingAvatarFile($profile)) {
505 506 507 508
            common_debug($this->name() . ' - Twitter user ' .
                         $profile->nickname .
                         ' is missing one or more local avatars.');
            common_debug($this->name() ." - old: $oldname new: $newname");
509 510

            $this->updateAvatars($twitter_user, $profile);
511
        }
512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531
    }

    function updateAvatars($twitter_user, $profile) {

        global $config;

        $path_parts = pathinfo($twitter_user->profile_image_url);

        $img_root = substr($path_parts['basename'], 0, -11);
        $ext = $path_parts['extension'];
        $mediatype = $this->getMediatype($ext);

        foreach (array('mini', 'normal', 'bigger') as $size) {
            $url = $path_parts['dirname'] . '/' .
                $img_root . '_' . $size . ".$ext";
            $filename = 'Twitter_' . $twitter_user->id . '_' .
                $img_root . "_$size.$ext";

            $this->updateAvatar($profile->id, $size, $mediatype, $filename);
            $this->fetchAvatar($url, $filename);
532 533 534
        }
    }

535 536 537 538 539 540 541 542 543
    function missingAvatarFile($profile) {
        foreach (array(24, 48, 73) as $size) {
            $filename = $profile->getAvatar($size)->filename;
            $avatarpath = Avatar::path($filename);
            if (file_exists($avatarpath) == FALSE) {
                return true;
            }
        }
        return false;
544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    }

    function getMediatype($ext)
    {
        $mediatype = null;

        switch (strtolower($ext)) {
        case 'jpg':
            $mediatype = 'image/jpg';
            break;
        case 'gif':
            $mediatype = 'image/gif';
            break;
        default:
            $mediatype = 'image/png';
559 560
        }

561 562 563 564 565 566 567 568
        return $mediatype;
    }

    function saveAvatars($user, $id)
    {
        global $config;

        $path_parts = pathinfo($user->profile_image_url);
569
        $ext = $path_parts['extension'];
570 571 572
        $end = strlen('_normal' . $ext);
        $img_root = substr($path_parts['basename'], 0, -($end+1));
        $mediatype = $this->getMediatype($ext);
573 574

        foreach (array('mini', 'normal', 'bigger') as $size) {
575
            $url = $path_parts['dirname'] . '/' .
576
                $img_root . '_' . $size . ".$ext";
577
            $filename = 'Twitter_' . $user->id . '_' .
578 579
                $img_root . "_$size.$ext";

580 581 582
            if ($this->fetchAvatar($url, $filename)) {
                $this->newAvatar($id, $size, $mediatype, $filename);
            } else {
583
                common_log(LOG_WARNING, $id() .
584
                           " - Problem fetching Avatar: $url");
585 586 587 588
            }
        }
    }

589
    function updateAvatar($profile_id, $size, $mediatype, $filename) {
590

591
        common_debug($this->name() . " - Updating avatar: $size");
592

593 594
        $profile = Profile::staticGet($profile_id);

595
        if (empty($profile)) {
596
            common_debug($this->name() . " - Couldn't get profile: $profile_id!");
597
            return;
598 599
        }

600 601
        $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
        $avatar = $profile->getAvatar($sizes[$size]);
602

603
        // Delete the avatar, if present
604 605 606 607 608
        if ($avatar) {
            $avatar->delete();
        }

        $this->newAvatar($profile->id, $size, $mediatype, $filename);
609
    }
610

611 612 613
    function newAvatar($profile_id, $size, $mediatype, $filename)
    {
        global $config;
614

615 616
        $avatar = new Avatar();
        $avatar->profile_id = $profile_id;
617

618 619 620 621 622 623 624 625 626 627 628
        switch($size) {
        case 'mini':
            $avatar->width  = 24;
            $avatar->height = 24;
            break;
        case 'normal':
            $avatar->width  = 48;
            $avatar->height = 48;
            break;
        default:
            // Note: Twitter's big avatars are a different size than
629
            // StatusNet's (StatusNet's = 96)
630 631 632
            $avatar->width  = 73;
            $avatar->height = 73;
        }
633

634
        $avatar->original = 0; // we don't have the original
635 636 637 638 639
        $avatar->mediatype = $mediatype;
        $avatar->filename = $filename;
        $avatar->url = Avatar::url($filename);

        $avatar->created = common_sql_now();
640

641 642 643 644 645
        try {
            $id = $avatar->insert();
        } catch (Exception $e) {
            common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
        }
646

647
        if (empty($id)) {
648 649 650
            common_log_db_error($avatar, 'INSERT', __FILE__);
            return null;
        }
651

652 653
        common_debug($this->name() .
                     " - Saved new $size avatar for $profile_id.");
654

655
        return $id;
656
    }
657

658 659 660 661 662 663 664
    /**
     * Fetch a remote avatar image and save to local storage.
     *
     * @param string $url avatar source URL
     * @param string $filename bare local filename for download
     * @return bool true on success, false on failure
     */
665 666
    function fetchAvatar($url, $filename)
    {
667
        common_debug($this->name() . " - Fetching Twitter avatar: $url");
668

669 670 671 672 673 674 675
        $request = HTTPClient::start();
        $response = $request->get($url);
        if ($response->isOk()) {
            $avatarfile = Avatar::path($filename);
            $ok = file_put_contents($avatarfile, $response->getBody());
            if (!$ok) {
                common_log(LOG_WARNING, $this->name() .
676
                           " - Couldn't open file $filename");
677 678 679
                return false;
            }
        } else {
680 681
            return false;
        }
682

683
        return true;
684
    }
685 686 687 688 689 690 691 692 693 694

    const URL = 1;
    const HASHTAG = 2;
    const MENTION = 3;

    function linkify($status)
    {
        $text = $status->text;

        if (empty($status->entities)) {
695 696 697
            common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
            $text = common_replace_urls_callback($text, 'common_linkify');
            $text = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
698
            $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744
            return $text;
        }

        // Move all the entities into order so we can
        // replace them in reverse order and thus
        // not mess up their indices

        $toReplace = array();

        if (!empty($status->entities->urls)) {
            foreach ($status->entities->urls as $url) {
                $toReplace[$url->indices[0]] = array(self::URL, $url);
            }
        }

        if (!empty($status->entities->hashtags)) {
            foreach ($status->entities->hashtags as $hashtag) {
                $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
            }
        }

        if (!empty($status->entities->user_mentions)) {
            foreach ($status->entities->user_mentions as $mention) {
                $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
            }
        }

        // sort in reverse order by key

        krsort($toReplace);

        foreach ($toReplace as $part) {
            list($type, $object) = $part;
            switch($type) {
            case self::URL:
                $linkText = $this->makeUrlLink($object);
                break;
            case self::HASHTAG:
                $linkText = $this->makeHashtagLink($object);
                break;
            case self::MENTION:
                $linkText = $this->makeMentionLink($object);
                break;
            default:
                continue;
            }
745
            $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
746 747 748 749 750 751 752 753 754 755 756
        }
        return $text;
    }

    function makeUrlLink($object)
    {
        return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
    }

    function makeHashtagLink($object)
    {
757
        return "#" . self::tagLink($object->text);
758 759 760 761
    }

    function makeMentionLink($object)
    {
762 763 764 765 766 767 768 769 770 771 772 773 774 775 776
        return "@".self::atLink($object->screen_name, $object->name);
    }

    static function tagLink($tag)
    {
        return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
    }

    static function atLink($screenName, $fullName=null)
    {
        if (!empty($fullName)) {
            return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
        } else {
            return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
        }
777
    }
778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800

    function saveStatusMentions($notice, $status)
    {
        $mentions = array();

        if (empty($status->entities) || empty($status->entities->user_mentions)) {
            return;
        }

        foreach ($status->entities->user_mentions as $mention) {
            $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
            if (!empty($flink)) {
                $user = User::staticGet('id', $flink->user_id);
                if (!empty($user)) {
                    $reply = new Reply();
                    $reply->notice_id  = $notice->id;
                    $reply->profile_id = $user->id;
                    common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
                    $id = $reply->insert();
                }
            }
        }
    }
801
}
802

803 804
$id    = null;
$debug = null;
805

806 807 808 809 810 811 812 813 814 815
if (have_option('i')) {
    $id = get_option_value('i');
} else if (have_option('--id')) {
    $id = get_option_value('--id');
} else if (count($args) > 0) {
    $id = $args[0];
} else {
    $id = null;
}

816
if (have_option('d') || have_option('debug')) {
817
    $debug = true;
818
}
Zach Copley's avatar
Zach Copley committed
819

820
$fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
821
$fetcher->runOnce();