]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/TwitterBridge/daemons/twitterstatusfetcher.php
Merge remote branch 'gitorious/0.9.x' into 0.9.x
[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                              $status->id . ' 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             Twitter_synch_status::setLastId($flink->foreign_id, 'home_timeline', $timeline[0]->id);
222             common_debug("Set lastId value '{$timeline[0]->id}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
223         }
224
225         // Okay, record the time we synced with Twitter for posterity
226         $flink->last_noticesync = common_sql_now();
227         $flink->update();
228     }
229
230     function saveStatus($status)
231     {
232         $profile = $this->ensureProfile($status->user);
233
234         if (empty($profile)) {
235             common_log(LOG_ERR, $this->name() .
236                 ' - 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             common_log(
247                 LOG_INFO,
248                 $this->name() .
249                 " - Ignoring duplicate import: {$status->id}"
250             );
251             return Notice::staticGet('id', $n2s->notice_id);
252         }
253
254         // If it's a retweet, save it as a repeat!
255         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             if (empty($original)) {
259                 return null;
260             } else {
261                 $author = $original->getProfile();
262                 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
263                 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
264                 $content = sprintf(_m('RT @%1$s %2$s'),
265                                    $author->nickname,
266                                    $original->content);
267
268                 if (Notice::contentTooLong($content)) {
269                     $contentlimit = Notice::maxContent();
270                     $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
271                 }
272
273                 $repeat = Notice::saveNew($profile->id,
274                                           $content,
275                                           'twitter',
276                                           array('repeat_of' => $original->id,
277                                                 'uri' => $statusUri,
278                                                 '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                 return $repeat;
282             }
283         }
284
285         $notice = new Notice();
286
287         $notice->profile_id = $profile->id;
288         $notice->uri        = $statusUri;
289         $notice->url        = $statusUri;
290         $notice->created    = strftime(
291             '%Y-%m-%d %H:%M:%S',
292             strtotime($status->created_at)
293         );
294
295         $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             $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
302             if (empty($n2s)) {
303                 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
304             } else {
305                 $reply = Notice::staticGet('id', $n2s->notice_id);
306                 if (empty($reply)) {
307                     common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
308                 } else {
309                     common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
310                     $notice->reply_to     = $reply->id;
311                     $notice->conversation = $reply->conversation;
312                 }
313             }
314         }
315
316         if (empty($notice->conversation)) {
317             $conv = Conversation::create();
318             $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);
325         $notice->rendered = $this->linkify($status);
326
327         if (Event::handle('StartNoticeSave', array(&$notice))) {
328
329             $id = $notice->insert();
330
331             if (!$id) {
332                 common_log_db_error($notice, 'INSERT', __FILE__);
333                 common_log(LOG_ERR, $this->name() .
334                     ' - Problem saving notice.');
335             }
336
337             Event::handle('EndNoticeSave', array($notice));
338         }
339
340         Notice_to_status::saveNew($notice->id, $status->id);
341
342         $this->saveStatusMentions($notice, $status);
343
344         $notice->blowOnInsert();
345
346         return $notice;
347     }
348
349     /**
350      * Make an URI for a status.
351      *
352      * @param object $status status object
353      *
354      * @return string URI
355      */
356     function makeStatusURI($username, $id)
357     {
358         return 'http://twitter.com/'
359           . $username
360           . '/status/'
361           . $id;
362     }
363
364     /**
365      * Look up a Profile by profileurl field.  Profile::staticGet() was
366      * not working consistently.
367      *
368      * @param string $nickname   local nickname of the Twitter user
369      * @param string $profileurl the profile url
370      *
371      * @return mixed value the first Profile with that url, or null
372      */
373     function getProfileByUrl($nickname, $profileurl)
374     {
375         $profile = new Profile();
376         $profile->nickname = $nickname;
377         $profile->profileurl = $profileurl;
378         $profile->limit(1);
379
380         if ($profile->find()) {
381             $profile->fetch();
382             return $profile;
383         }
384
385         return null;
386     }
387
388     /**
389      * Check to see if this Twitter status has already been imported
390      *
391      * @param Profile $profile   Twitter user's local profile
392      * @param string  $statusUri URI of the status on Twitter
393      *
394      * @return mixed value a matching Notice or null
395      */
396     function checkDupe($profile, $statusUri)
397     {
398         $notice = new Notice();
399         $notice->uri = $statusUri;
400         $notice->profile_id = $profile->id;
401         $notice->limit(1);
402
403         if ($notice->find()) {
404             $notice->fetch();
405             return $notice;
406         }
407
408         return null;
409     }
410
411     function ensureProfile($user)
412     {
413         // check to see if there's already a profile for this user
414         $profileurl = 'http://twitter.com/' . $user->screen_name;
415         $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
416
417         if (!empty($profile)) {
418             common_debug($this->name() .
419                          " - 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             common_debug($this->name() . ' - Adding profile and remote profile ' .
428                          "for Twitter user: $profileurl.");
429
430             $profile = new Profile();
431             $profile->query("BEGIN");
432
433             $profile->nickname = $user->screen_name;
434             $profile->fullname = $user->name;
435             $profile->homepage = $user->url;
436             $profile->bio = $user->description;
437             $profile->location = $user->location;
438             $profile->profileurl = $profileurl;
439             $profile->created = common_sql_now();
440
441             try {
442                 $id = $profile->insert();
443             } catch(Exception $e) {
444                 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
445             }
446
447             if (empty($id)) {
448                 common_log_db_error($profile, 'INSERT', __FILE__);
449                 $profile->query("ROLLBACK");
450                 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                 $remote_pro->id = $id;
461                 $remote_pro->uri = $profileurl;
462                 $remote_pro->created = common_sql_now();
463
464                 try {
465                     $rid = $remote_pro->insert();
466                 } catch (Exception $e) {
467                     common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
468                 }
469
470                 if (empty($rid)) {
471                     common_log_db_error($profile, 'INSERT', __FILE__);
472                     $profile->query("ROLLBACK");
473                     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         $path_parts = pathinfo($twitter_user->profile_image_url);
490
491         $newname = 'Twitter_' . $twitter_user->id . '_' .
492             $path_parts['basename'];
493
494         $oldname = $profile->getAvatar(48)->filename;
495
496         if ($newname != $oldname) {
497             common_debug($this->name() . ' - Avatar for Twitter user ' .
498                          "$profile->nickname has changed.");
499             common_debug($this->name() . " - old: $oldname new: $newname");
500
501             $this->updateAvatars($twitter_user, $profile);
502         }
503
504         if ($this->missingAvatarFile($profile)) {
505             common_debug($this->name() . ' - Twitter user ' .
506                          $profile->nickname .
507                          ' is missing one or more local avatars.');
508             common_debug($this->name() ." - old: $oldname new: $newname");
509
510             $this->updateAvatars($twitter_user, $profile);
511         }
512     }
513
514     function updateAvatars($twitter_user, $profile) {
515
516         global $config;
517
518         $path_parts = pathinfo($twitter_user->profile_image_url);
519
520         $img_root = substr($path_parts['basename'], 0, -11);
521         $ext = $path_parts['extension'];
522         $mediatype = $this->getMediatype($ext);
523
524         foreach (array('mini', 'normal', 'bigger') as $size) {
525             $url = $path_parts['dirname'] . '/' .
526                 $img_root . '_' . $size . ".$ext";
527             $filename = 'Twitter_' . $twitter_user->id . '_' .
528                 $img_root . "_$size.$ext";
529
530             $this->updateAvatar($profile->id, $size, $mediatype, $filename);
531             $this->fetchAvatar($url, $filename);
532         }
533     }
534
535     function missingAvatarFile($profile) {
536         foreach (array(24, 48, 73) as $size) {
537             $filename = $profile->getAvatar($size)->filename;
538             $avatarpath = Avatar::path($filename);
539             if (file_exists($avatarpath) == FALSE) {
540                 return true;
541             }
542         }
543         return false;
544     }
545
546     function getMediatype($ext)
547     {
548         $mediatype = null;
549
550         switch (strtolower($ext)) {
551         case 'jpg':
552             $mediatype = 'image/jpg';
553             break;
554         case 'gif':
555             $mediatype = 'image/gif';
556             break;
557         default:
558             $mediatype = 'image/png';
559         }
560
561         return $mediatype;
562     }
563
564     function saveAvatars($user, $id)
565     {
566         global $config;
567
568         $path_parts = pathinfo($user->profile_image_url);
569         $ext = $path_parts['extension'];
570         $end = strlen('_normal' . $ext);
571         $img_root = substr($path_parts['basename'], 0, -($end+1));
572         $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                 $img_root . "_$size.$ext";
579
580             if ($this->fetchAvatar($url, $filename)) {
581                 $this->newAvatar($id, $size, $mediatype, $filename);
582             } 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         $profile = Profile::staticGet($profile_id);
594
595         if (empty($profile)) {
596             common_debug($this->name() . " - Couldn't get profile: $profile_id!");
597             return;
598         }
599
600         $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
601         $avatar = $profile->getAvatar($sizes[$size]);
602
603         // Delete the avatar, if present
604         if ($avatar) {
605             $avatar->delete();
606         }
607
608         $this->newAvatar($profile->id, $size, $mediatype, $filename);
609     }
610
611     function newAvatar($profile_id, $size, $mediatype, $filename)
612     {
613         global $config;
614
615         $avatar = new Avatar();
616         $avatar->profile_id = $profile_id;
617
618         switch($size) {
619         case 'mini':
620             $avatar->width  = 24;
621             $avatar->height = 24;
622             break;
623         case 'normal':
624             $avatar->width  = 48;
625             $avatar->height = 48;
626             break;
627         default:
628             // Note: Twitter's big avatars are a different size than
629             // StatusNet's (StatusNet's = 96)
630             $avatar->width  = 73;
631             $avatar->height = 73;
632         }
633
634         $avatar->original = 0; // we don't have the original
635         $avatar->mediatype = $mediatype;
636         $avatar->filename = $filename;
637         $avatar->url = Avatar::url($filename);
638
639         $avatar->created = common_sql_now();
640
641         try {
642             $id = $avatar->insert();
643         } catch (Exception $e) {
644             common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
645         }
646
647         if (empty($id)) {
648             common_log_db_error($avatar, 'INSERT', __FILE__);
649             return null;
650         }
651
652         common_debug($this->name() .
653                      " - Saved new $size avatar for $profile_id.");
654
655         return $id;
656     }
657
658     /**
659      * Fetch a remote avatar image and save to local storage.
660      *
661      * @param string $url avatar source URL
662      * @param string $filename bare local filename for download
663      * @return bool true on success, false on failure
664      */
665     function fetchAvatar($url, $filename)
666     {
667         common_debug($this->name() . " - Fetching Twitter avatar: $url");
668
669         $request = HTTPClient::start();
670         $response = $request->get($url);
671         if ($response->isOk()) {
672             $avatarfile = Avatar::path($filename);
673             $ok = file_put_contents($avatarfile, $response->getBody());
674             if (!$ok) {
675                 common_log(LOG_WARNING, $this->name() .
676                            " - Couldn't open file $filename");
677                 return false;
678             }
679         } else {
680             return false;
681         }
682
683         return true;
684     }
685
686     const URL = 1;
687     const HASHTAG = 2;
688     const MENTION = 3;
689
690     function linkify($status)
691     {
692         $text = $status->text;
693
694         if (empty($status->entities)) {
695             common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
696             $text = common_replace_urls_callback($text, 'common_linkify');
697             $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             return $text;
700         }
701
702         // Move all the entities into order so we can
703         // replace them in reverse order and thus
704         // not mess up their indices
705
706         $toReplace = array();
707
708         if (!empty($status->entities->urls)) {
709             foreach ($status->entities->urls as $url) {
710                 $toReplace[$url->indices[0]] = array(self::URL, $url);
711             }
712         }
713
714         if (!empty($status->entities->hashtags)) {
715             foreach ($status->entities->hashtags as $hashtag) {
716                 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
717             }
718         }
719
720         if (!empty($status->entities->user_mentions)) {
721             foreach ($status->entities->user_mentions as $mention) {
722                 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
723             }
724         }
725
726         // sort in reverse order by key
727
728         krsort($toReplace);
729
730         foreach ($toReplace as $part) {
731             list($type, $object) = $part;
732             switch($type) {
733             case self::URL:
734                 $linkText = $this->makeUrlLink($object);
735                 break;
736             case self::HASHTAG:
737                 $linkText = $this->makeHashtagLink($object);
738                 break;
739             case self::MENTION:
740                 $linkText = $this->makeMentionLink($object);
741                 break;
742             default:
743                 continue;
744             }
745             $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
746         }
747         return $text;
748     }
749
750     function makeUrlLink($object)
751     {
752         return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
753     }
754
755     function makeHashtagLink($object)
756     {
757         return "#" . self::tagLink($object->text);
758     }
759
760     function makeMentionLink($object)
761     {
762         return "@".self::atLink($object->screen_name, $object->name);
763     }
764
765     static function tagLink($tag)
766     {
767         return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
768     }
769
770     static function atLink($screenName, $fullName=null)
771     {
772         if (!empty($fullName)) {
773             return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
774         } else {
775             return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
776         }
777     }
778
779     function saveStatusMentions($notice, $status)
780     {
781         $mentions = array();
782
783         if (empty($status->entities) || empty($status->entities->user_mentions)) {
784             return;
785         }
786
787         foreach ($status->entities->user_mentions as $mention) {
788             $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
789             if (!empty($flink)) {
790                 $user = User::staticGet('id', $flink->user_id);
791                 if (!empty($user)) {
792                     $reply = new Reply();
793                     $reply->notice_id  = $notice->id;
794                     $reply->profile_id = $user->id;
795                     common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
796                     $id = $reply->insert();
797                 }
798             }
799         }
800     }
801 }
802
803 $id    = null;
804 $debug = null;
805
806 if (have_option('i')) {
807     $id = get_option_value('i');
808 } else if (have_option('--id')) {
809     $id = get_option_value('--id');
810 } else if (count($args) > 0) {
811     $id = $args[0];
812 } else {
813     $id = null;
814 }
815
816 if (have_option('d') || have_option('debug')) {
817     $debug = true;
818 }
819
820 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);
821 $fetcher->runOnce();