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