]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
TwitterBridge fix: merge down remaining 64-bit Snowflake ID fixes for twitterstatusfe...
[quix0rs-gnu-social.git] / plugins / TwitterBridge / daemons / twitterstatusfetcher.php
1 #!/usr/bin/env php
2 <?php
3 /**
4  * StatusNet - the distributed open-source microblogging tool
5  * Copyright (C) 2008-2010, StatusNet, Inc.
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or
10  * (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
19  */
20
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
22
23 // Tune number of processes and how often to poll Twitter
24 // XXX: Should these things be in config.php?
25 define('MAXCHILDREN', 2);
26 define('POLL_INTERVAL', 60); // in seconds
27
28 $shortoptions = 'di::';
29 $longoptions = array('id::', 'debug');
30
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
33
34   -i --id              Identity (default 'generic')
35   -d --debug           Debug (lots of log output)
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  * Fetches statuses from Twitter and inserts them as notices
49  *
50  * NOTE: an Avatar path MUST be set in config.php for this
51  * script to work, e.g.:
52  *     $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
53  *
54  * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
55  * this script is run, so the default avatar path is always set wrong in
56  * default.php. Therefore it must be set explicitly in config.php. --Z
57  *
58  * @category Twitter
59  * @package  StatusNet
60  * @author   Zach Copley <zach@status.net>
61  * @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      *  Constructor
69      *
70      * @param string  $id           the name/id of this daemon
71      * @param int     $interval     sleep this long before doing everything again
72      * @param int     $max_children maximum number of child processes at a time
73      * @param boolean $debug        debug output flag
74      *
75      * @return void
76      *
77      **/
78     function __construct($id = null, $interval = 60,
79                          $max_children = 2, $debug = null)
80     {
81         parent::__construct($id, $interval, $max_children, $debug);
82     }
83
84     /**
85      * Name of this daemon
86      *
87      * @return string Name of the daemon.
88      */
89     function name()
90     {
91         return ('twitterstatusfetcher.'.$this->_id);
92     }
93
94     /**
95      * Find all the Twitter foreign links for users who have requested
96      * 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             if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
115                 FOREIGN_NOTICE_RECV) {
116                 $flinks[] = clone($flink);
117                 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
118             } else {
119                 common_log(LOG_INFO, "nothing to sync");
120             }
121         }
122
123         $flink->free();
124         unset($flink);
125
126         $conn->disconnect();
127         unset($_DB_DATAOBJECT['CONNECTIONS']);
128
129         return $flinks;
130     }
131
132     function childTask($flink) {
133         // Each child ps needs its own DB connection
134
135         // Note: DataObject::getDatabaseConnection() creates
136         // a new connection if there isn't one already
137         $conn = &$flink->getDatabaseConnection();
138
139         $this->getTimeline($flink);
140
141         $flink->last_friendsync = common_sql_now();
142         $flink->update();
143
144         $conn->disconnect();
145
146         // XXX: Couldn't find a less brutal way to blow
147         // away a cached connection
148         global $_DB_DATAOBJECT;
149         unset($_DB_DATAOBJECT['CONNECTIONS']);
150     }
151
152     function getTimeline($flink)
153     {
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         common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
161                      $flink->foreign_id);
162
163         $client = null;
164
165         if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
166             $token = TwitterOAuthClient::unpackToken($flink->credentials);
167             $client = new TwitterOAuthClient($token->key, $token->secret);
168             common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
169         } 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         common_debug("Got lastId value '{$lastId}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
178
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                        $flink->user_id . ' - code: ' .
185                        $e->getCode() . 'msg: ' . $e->getMessage());
186         }
187
188         if (empty($timeline)) {
189             common_log(LOG_WARNING, $this->name() .  " - Empty timeline.");
190             return;
191         }
192
193         common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
194
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                 common_debug($this->name() . ' - Skipping import of status ' .
203                              twitter_id($status) . ' with source ' . $source);
204                 continue;
205             }
206
207             // Don't save it if the user is protected
208             // FIXME: save it but treat it as private
209             if ($status->user->protected) {
210                 continue;
211             }
212
213             $notice = $this->saveStatus($status);
214
215             if (!empty($notice)) {
216                 Inbox::insertNotice($flink->user_id, $notice->id);
217             }
218         }
219
220         if (!empty($timeline)) {
221             $lastId = twitter_id($timeline[0]);
222             Twitter_synch_status::setLastId($flink->foreign_id, 'home_timeline', $lastId);
223             common_debug("Set lastId value '$lastId' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
224         }
225
226         // Okay, record the time we synced with Twitter for posterity
227         $flink->last_noticesync = common_sql_now();
228         $flink->update();
229     }
230
231     function saveStatus($status)
232     {
233         $profile = $this->ensureProfile($status->user);
234
235         if (empty($profile)) {
236             common_log(LOG_ERR, $this->name() .
237                 ' - Problem saving notice. No associated Profile.');
238             return null;
239         }
240
241         $statusId = twitter_id($status);
242         $statusUri = $this->makeStatusURI($status->user->screen_name, $statusId);
243
244         // check to see if we've already imported the status
245         $n2s = Notice_to_status::staticGet('status_id', $statusId);
246
247         if (!empty($n2s)) {
248             common_log(
249                 LOG_INFO,
250                 $this->name() .
251                 " - Ignoring duplicate import: {$statusId}"
252             );
253             return Notice::staticGet('id', $n2s->notice_id);
254         }
255
256         // If it's a retweet, save it as a repeat!
257         if (!empty($status->retweeted_status)) {
258             common_log(LOG_INFO, "Status {$statusId} is a retweet of " . twitter_id($status->retweeted_status) . ".");
259             $original = $this->saveStatus($status->retweeted_status);
260             if (empty($original)) {
261                 return null;
262             } else {
263                 $author = $original->getProfile();
264                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
265                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
266                 $content = sprintf(_m('RT @%1$s %2$s'),
267                                    $author->nickname,
268                                    $original->content);
269
270                 if (Notice::contentTooLong($content)) {
271                     $contentlimit = Notice::maxContent();
272                     $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
273                 }
274
275                 $repeat = Notice::saveNew($profile->id,
276                                           $content,
277                                           'twitter',
278                                           array('repeat_of' => $original->id,
279                                                 'uri' => $statusUri,
280                                                 'is_local' => Notice::GATEWAY));
281                 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
282                 Notice_to_status::saveNew($repeat->id, $statusId);
283                 return $repeat;
284             }
285         }
286
287         $notice = new Notice();
288
289         $notice->profile_id = $profile->id;
290         $notice->uri        = $statusUri;
291         $notice->url        = $statusUri;
292         $notice->created    = strftime(
293             '%Y-%m-%d %H:%M:%S',
294             strtotime($status->created_at)
295         );
296
297         $notice->source     = 'twitter';
298
299         $notice->reply_to   = null;
300
301         $replyTo = twitter_id($status, 'in_reply_to_status_id');
302         if (!empty($replyTo)) {
303             common_log(LOG_INFO, "Status {$statusId} is a reply to status {$replyTo}");
304             $n2s = Notice_to_status::staticGet('status_id', $replyTo);
305             if (empty($n2s)) {
306                 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
307             } else {
308                 $reply = Notice::staticGet('id', $n2s->notice_id);
309                 if (empty($reply)) {
310                     common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
311                 } else {
312                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$replyTo}");
313                     $notice->reply_to     = $reply->id;
314                     $notice->conversation = $reply->conversation;
315                 }
316             }
317         }
318
319         if (empty($notice->conversation)) {
320             $conv = Conversation::create();
321             $notice->conversation = $conv->id;
322             common_log(LOG_INFO, "No known conversation for status {$statusId} so making a new one {$conv->id}.");
323         }
324
325         $notice->is_local   = Notice::GATEWAY;
326
327         $notice->content  = html_entity_decode($status->text, ENT_QUOTES, 'UTF-8');
328         $notice->rendered = $this->linkify($status);
329
330         if (Event::handle('StartNoticeSave', array(&$notice))) {
331
332             $id = $notice->insert();
333
334             if (!$id) {
335                 common_log_db_error($notice, 'INSERT', __FILE__);
336                 common_log(LOG_ERR, $this->name() .
337                     ' - Problem saving notice.');
338             }
339
340             Event::handle('EndNoticeSave', array($notice));
341         }
342
343         Notice_to_status::saveNew($notice->id, $statusId);
344
345         $this->saveStatusMentions($notice, $status);
346
347         $notice->blowOnInsert();
348
349         return $notice;
350     }
351
352     /**
353      * Make an URI for a status.
354      *
355      * @param object $status status object
356      *
357      * @return string URI
358      */
359     function makeStatusURI($username, $id)
360     {
361         return 'http://twitter.com/'
362           . $username
363           . '/status/'
364           . $id;
365     }
366
367     /**
368      * Look up a Profile by profileurl field.  Profile::staticGet() was
369      * not working consistently.
370      *
371      * @param string $nickname   local nickname of the Twitter user
372      * @param string $profileurl the profile url
373      *
374      * @return mixed value the first Profile with that url, or null
375      */
376     function getProfileByUrl($nickname, $profileurl)
377     {
378         $profile = new Profile();
379         $profile->nickname = $nickname;
380         $profile->profileurl = $profileurl;
381         $profile->limit(1);
382
383         if ($profile->find()) {
384             $profile->fetch();
385             return $profile;
386         }
387
388         return null;
389     }
390
391     /**
392      * Check to see if this Twitter status has already been imported
393      *
394      * @param Profile $profile   Twitter user's local profile
395      * @param string  $statusUri URI of the status on Twitter
396      *
397      * @return mixed value a matching Notice or null
398      */
399     function checkDupe($profile, $statusUri)
400     {
401         $notice = new Notice();
402         $notice->uri = $statusUri;
403         $notice->profile_id = $profile->id;
404         $notice->limit(1);
405
406         if ($notice->find()) {
407             $notice->fetch();
408             return $notice;
409         }
410
411         return null;
412     }
413
414     function ensureProfile($user)
415     {
416         // check to see if there's already a profile for this user
417         $profileurl = 'http://twitter.com/' . $user->screen_name;
418         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
419
420         if (!empty($profile)) {
421             common_debug($this->name() .
422                          " - Profile for $profile->nickname found.");
423
424             // Check to see if the user's Avatar has changed
425
426             $this->checkAvatar($user, $profile);
427             return $profile;
428
429         } else {
430             common_debug($this->name() . ' - Adding profile and remote profile ' .
431                          "for Twitter user: $profileurl.");
432
433             $profile = new Profile();
434             $profile->query("BEGIN");
435
436             $profile->nickname = $user->screen_name;
437             $profile->fullname = $user->name;
438             $profile->homepage = $user->url;
439             $profile->bio = $user->description;
440             $profile->location = $user->location;
441             $profile->profileurl = $profileurl;
442             $profile->created = common_sql_now();
443
444             try {
445                 $id = $profile->insert();
446             } catch(Exception $e) {
447                 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
448             }
449
450             if (empty($id)) {
451                 common_log_db_error($profile, 'INSERT', __FILE__);
452                 $profile->query("ROLLBACK");
453                 return false;
454             }
455
456             // check for remote profile
457
458             $remote_pro = Remote_profile::staticGet('uri', $profileurl);
459
460             if (empty($remote_pro)) {
461                 $remote_pro = new Remote_profile();
462
463                 $remote_pro->id = $id;
464                 $remote_pro->uri = $profileurl;
465                 $remote_pro->created = common_sql_now();
466
467                 try {
468                     $rid = $remote_pro->insert();
469                 } catch (Exception $e) {
470                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
471                 }
472
473                 if (empty($rid)) {
474                     common_log_db_error($profile, 'INSERT', __FILE__);
475                     $profile->query("ROLLBACK");
476                     return false;
477                 }
478             }
479
480             $profile->query("COMMIT");
481
482             $this->saveAvatars($user, $id);
483
484             return $profile;
485         }
486     }
487
488     function checkAvatar($twitter_user, $profile)
489     {
490         global $config;
491
492         $path_parts = pathinfo($twitter_user->profile_image_url);
493
494         $newname = 'Twitter_' . $twitter_user->id . '_' .
495             $path_parts['basename'];
496
497         $oldname = $profile->getAvatar(48)->filename;
498
499         if ($newname != $oldname) {
500             common_debug($this->name() . ' - Avatar for Twitter user ' .
501                          "$profile->nickname has changed.");
502             common_debug($this->name() . " - old: $oldname new: $newname");
503
504             $this->updateAvatars($twitter_user, $profile);
505         }
506
507         if ($this->missingAvatarFile($profile)) {
508             common_debug($this->name() . ' - Twitter user ' .
509                          $profile->nickname .
510                          ' is missing one or more local avatars.');
511             common_debug($this->name() ." - old: $oldname new: $newname");
512
513             $this->updateAvatars($twitter_user, $profile);
514         }
515     }
516
517     function updateAvatars($twitter_user, $profile) {
518
519         global $config;
520
521         $path_parts = pathinfo($twitter_user->profile_image_url);
522
523         $img_root = substr($path_parts['basename'], 0, -11);
524         $ext = $path_parts['extension'];
525         $mediatype = $this->getMediatype($ext);
526
527         foreach (array('mini', 'normal', 'bigger') as $size) {
528             $url = $path_parts['dirname'] . '/' .
529                 $img_root . '_' . $size . ".$ext";
530             $filename = 'Twitter_' . $twitter_user->id . '_' .
531                 $img_root . "_$size.$ext";
532
533             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
534             $this->fetchAvatar($url, $filename);
535         }
536     }
537
538     function missingAvatarFile($profile) {
539         foreach (array(24, 48, 73) as $size) {
540             $filename = $profile->getAvatar($size)->filename;
541             $avatarpath = Avatar::path($filename);
542             if (file_exists($avatarpath) == FALSE) {
543                 return true;
544             }
545         }
546         return false;
547     }
548
549     function getMediatype($ext)
550     {
551         $mediatype = null;
552
553         switch (strtolower($ext)) {
554         case 'jpg':
555             $mediatype = 'image/jpg';
556             break;
557         case 'gif':
558             $mediatype = 'image/gif';
559             break;
560         default:
561             $mediatype = 'image/png';
562         }
563
564         return $mediatype;
565     }
566
567     function saveAvatars($user, $id)
568     {
569         global $config;
570
571         $path_parts = pathinfo($user->profile_image_url);
572         $ext = $path_parts['extension'];
573         $end = strlen('_normal' . $ext);
574         $img_root = substr($path_parts['basename'], 0, -($end+1));
575         $mediatype = $this->getMediatype($ext);
576
577         foreach (array('mini', 'normal', 'bigger') as $size) {
578             $url = $path_parts['dirname'] . '/' .
579                 $img_root . '_' . $size . ".$ext";
580             $filename = 'Twitter_' . $user->id . '_' .
581                 $img_root . "_$size.$ext";
582
583             if ($this->fetchAvatar($url, $filename)) {
584                 $this->newAvatar($id, $size, $mediatype, $filename);
585             } else {
586                 common_log(LOG_WARNING, $id() .
587                            " - Problem fetching Avatar: $url");
588             }
589         }
590     }
591
592     function updateAvatar($profile_id, $size, $mediatype, $filename) {
593
594         common_debug($this->name() . " - Updating avatar: $size");
595
596         $profile = Profile::staticGet($profile_id);
597
598         if (empty($profile)) {
599             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
600             return;
601         }
602
603         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
604         $avatar = $profile->getAvatar($sizes[$size]);
605
606         // Delete the avatar, if present
607         if ($avatar) {
608             $avatar->delete();
609         }
610
611         $this->newAvatar($profile->id, $size, $mediatype, $filename);
612     }
613
614     function newAvatar($profile_id, $size, $mediatype, $filename)
615     {
616         global $config;
617
618         $avatar = new Avatar();
619         $avatar->profile_id = $profile_id;
620
621         switch($size) {
622         case 'mini':
623             $avatar->width  = 24;
624             $avatar->height = 24;
625             break;
626         case 'normal':
627             $avatar->width  = 48;
628             $avatar->height = 48;
629             break;
630         default:
631             // Note: Twitter's big avatars are a different size than
632             // StatusNet's (StatusNet's = 96)
633             $avatar->width  = 73;
634             $avatar->height = 73;
635         }
636
637         $avatar->original = 0; // we don't have the original
638         $avatar->mediatype = $mediatype;
639         $avatar->filename = $filename;
640         $avatar->url = Avatar::url($filename);
641
642         $avatar->created = common_sql_now();
643
644         try {
645             $id = $avatar->insert();
646         } catch (Exception $e) {
647             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
648         }
649
650         if (empty($id)) {
651             common_log_db_error($avatar, 'INSERT', __FILE__);
652             return null;
653         }
654
655         common_debug($this->name() .
656                      " - Saved new $size avatar for $profile_id.");
657
658         return $id;
659     }
660
661     /**
662      * Fetch a remote avatar image and save to local storage.
663      *
664      * @param string $url avatar source URL
665      * @param string $filename bare local filename for download
666      * @return bool true on success, false on failure
667      */
668     function fetchAvatar($url, $filename)
669     {
670         common_debug($this->name() . " - Fetching Twitter avatar: $url");
671
672         $request = HTTPClient::start();
673         $response = $request->get($url);
674         if ($response->isOk()) {
675             $avatarfile = Avatar::path($filename);
676             $ok = file_put_contents($avatarfile, $response->getBody());
677             if (!$ok) {
678                 common_log(LOG_WARNING, $this->name() .
679                            " - Couldn't open file $filename");
680                 return false;
681             }
682         } else {
683             return false;
684         }
685
686         return true;
687     }
688
689     const URL = 1;
690     const HASHTAG = 2;
691     const MENTION = 3;
692
693     function linkify($status)
694     {
695         $text = $status->text;
696
697         if (empty($status->entities)) {
698             common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
699             $text = common_replace_urls_callback($text, 'common_linkify');
700             $text = preg_replace('/(^|\&quot\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
701             $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
702             return $text;
703         }
704
705         // Move all the entities into order so we can
706         // replace them in reverse order and thus
707         // not mess up their indices
708
709         $toReplace = array();
710
711         if (!empty($status->entities->urls)) {
712             foreach ($status->entities->urls as $url) {
713                 $toReplace[$url->indices[0]] = array(self::URL, $url);
714             }
715         }
716
717         if (!empty($status->entities->hashtags)) {
718             foreach ($status->entities->hashtags as $hashtag) {
719                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
720             }
721         }
722
723         if (!empty($status->entities->user_mentions)) {
724             foreach ($status->entities->user_mentions as $mention) {
725                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
726             }
727         }
728
729         // sort in reverse order by key
730
731         krsort($toReplace);
732
733         foreach ($toReplace as $part) {
734             list($type, $object) = $part;
735             switch($type) {
736             case self::URL:
737                 $linkText = $this->makeUrlLink($object);
738                 break;
739             case self::HASHTAG:
740                 $linkText = $this->makeHashtagLink($object);
741                 break;
742             case self::MENTION:
743                 $linkText = $this->makeMentionLink($object);
744                 break;
745             default:
746                 continue;
747             }
748             $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
749         }
750         return $text;
751     }
752
753     function makeUrlLink($object)
754     {
755         return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
756     }
757
758     function makeHashtagLink($object)
759     {
760         return "#" . self::tagLink($object->text);
761     }
762
763     function makeMentionLink($object)
764     {
765         return "@".self::atLink($object->screen_name, $object->name);
766     }
767
768     static function tagLink($tag)
769     {
770         return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
771     }
772
773     static function atLink($screenName, $fullName=null)
774     {
775         if (!empty($fullName)) {
776             return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
777         } else {
778             return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
779         }
780     }
781
782     function saveStatusMentions($notice, $status)
783     {
784         $mentions = array();
785
786         if (empty($status->entities) || empty($status->entities->user_mentions)) {
787             return;
788         }
789
790         foreach ($status->entities->user_mentions as $mention) {
791             $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
792             if (!empty($flink)) {
793                 $user = User::staticGet('id', $flink->user_id);
794                 if (!empty($user)) {
795                     $reply = new Reply();
796                     $reply->notice_id  = $notice->id;
797                     $reply->profile_id = $user->id;
798                     common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
799                     $id = $reply->insert();
800                 }
801             }
802         }
803     }
804 }
805
806 $id    = null;
807 $debug = null;
808
809 if (have_option('i')) {
810     $id = get_option_value('i');
811 } else if (have_option('--id')) {
812     $id = get_option_value('--id');
813 } else if (count($args) > 0) {
814     $id = $args[0];
815 } else {
816     $id = null;
817 }
818
819 if (have_option('d') || have_option('debug')) {
820     $debug = true;
821 }
822
823 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
824 $fetcher->runOnce();