4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2008-2010, StatusNet, Inc.
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.
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.
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/>.
21 define('INSTALLDIR', realpath(dirname(__FILE__) . '/../../..'));
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
28 $shortoptions = 'di::';
29 $longoptions = array('id::', 'debug');
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
34 -i --id Identity (default 'generic')
35 -d --debug Debug (lots of log output)
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';
46 * Fetch statuses from Twitter
48 * Fetches statuses from Twitter and inserts them as notices
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/';
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
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/
66 class TwitterStatusFetcher extends ParallelizingDaemon
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
79 function __construct($id = null, $interval = 60,
80 $max_children = 2, $debug = null)
82 parent::__construct($id, $interval, $max_children, $debug);
88 * @return string Name of the daemon.
93 return ('twitterstatusfetcher.'.$this->_id);
97 * Find all the Twitter foreign links for users who have requested
98 * importing of their friends' timelines
100 * @return array flinks an array of Foreign_link objects
103 function getObjects()
105 global $_DB_DATAOBJECT;
106 $flink = new Foreign_link();
107 $conn = &$flink->getDatabaseConnection();
109 $flink->service = TWITTER_SERVICE;
110 $flink->orderBy('last_noticesync');
115 while ($flink->fetch()) {
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");
122 common_log(LOG_INFO, "nothing to sync");
130 unset($_DB_DATAOBJECT['CONNECTIONS']);
135 function childTask($flink) {
137 // Each child ps needs its own DB connection
139 // Note: DataObject::getDatabaseConnection() creates
140 // a new connection if there isn't one already
142 $conn = &$flink->getDatabaseConnection();
144 $this->getTimeline($flink);
146 $flink->last_friendsync = common_sql_now();
151 // XXX: Couldn't find a less brutal way to blow
152 // away a cached connection
154 global $_DB_DATAOBJECT;
155 unset($_DB_DATAOBJECT['CONNECTIONS']);
158 function getTimeline($flink)
161 common_log(LOG_WARNING, $this->name() .
162 " - Can't retrieve Foreign_link for foreign ID $fid");
166 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
171 if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
172 $token = TwitterOAuthClient::unpackToken($flink->credentials);
173 $client = new TwitterOAuthClient($token->key, $token->secret);
174 common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
176 common_debug("Skipping friends timeline for $flink->foreign_id since not OAuth.");
181 $lastId = Twitter_synch_status::getLastId($flink->foreign_id, 'home_timeline');
183 common_debug("Got lastId value '{$lastId}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
186 $timeline = $client->statusesHomeTimeline($lastId);
187 } catch (Exception $e) {
188 common_log(LOG_WARNING, $this->name() .
189 ' - Twitter client unable to get friends timeline for user ' .
190 $flink->user_id . ' - code: ' .
191 $e->getCode() . 'msg: ' . $e->getMessage());
194 if (empty($timeline)) {
195 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
199 common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
201 // Reverse to preserve order
203 foreach (array_reverse($timeline) as $status) {
205 // Hacktastic: filter out stuff coming from this StatusNet
207 $source = mb_strtolower(common_config('integration', 'source'));
209 if (preg_match("/$source/", mb_strtolower($status->source))) {
210 common_debug($this->name() . ' - Skipping import of status ' .
211 $status->id . ' with source ' . $source);
215 // Don't save it if the user is protected
216 // FIXME: save it but treat it as private
218 if ($status->user->protected) {
222 $notice = $this->saveStatus($status);
224 if (!empty($notice)) {
225 Inbox::insertNotice($flink->user_id, $notice->id);
229 if (!empty($timeline)) {
230 Twitter_synch_status::setLastId($flink->foreign_id, 'home_timeline', $timeline[0]->id);
231 common_debug("Set lastId value '{$timeline[0]->id}' for foreign id '{$flink->foreign_id}' and timeline 'home_timeline'");
234 // Okay, record the time we synced with Twitter for posterity
236 $flink->last_noticesync = common_sql_now();
240 function saveStatus($status)
242 $profile = $this->ensureProfile($status->user);
244 if (empty($profile)) {
245 common_log(LOG_ERR, $this->name() .
246 ' - Problem saving notice. No associated Profile.');
250 $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
252 // check to see if we've already imported the status
254 $n2s = Notice_to_status::staticGet('status_id', $status->id);
260 " - Ignoring duplicate import: {$status->id}"
262 return Notice::staticGet('id', $n2s->notice_id);
265 // If it's a retweet, save it as a repeat!
267 if (!empty($status->retweeted_status)) {
268 common_log(LOG_INFO, "Status {$status->id} is a retweet of {$status->retweeted_status->id}.");
269 $original = $this->saveStatus($status->retweeted_status);
270 if (empty($original)) {
273 $author = $original->getProfile();
274 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
275 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
276 $content = sprintf(_('RT @%1$s %2$s'),
280 if (Notice::contentTooLong($content)) {
281 $contentlimit = Notice::maxContent();
282 $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
285 $repeat = Notice::saveNew($profile->id,
288 array('repeat_of' => $original->id,
290 'is_local' => Notice::GATEWAY));
291 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
292 Notice_to_status::saveNew($repeat->id, $status->id);
297 $notice = new Notice();
299 $notice->profile_id = $profile->id;
300 $notice->uri = $statusUri;
301 $notice->url = $statusUri;
302 $notice->created = strftime(
304 strtotime($status->created_at)
307 $notice->source = 'twitter';
309 $notice->reply_to = null;
311 if (!empty($status->in_reply_to_status_id)) {
312 common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
313 $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
315 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
317 $reply = Notice::staticGet('id', $n2s->notice_id);
319 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
321 common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
322 $notice->reply_to = $reply->id;
323 $notice->conversation = $reply->conversation;
328 if (empty($notice->conversation)) {
329 $conv = Conversation::create();
330 $notice->conversation = $conv->id;
331 common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
334 $notice->is_local = Notice::GATEWAY;
336 $notice->content = html_entity_decode($status->text);
337 $notice->rendered = $this->linkify($status);
339 if (Event::handle('StartNoticeSave', array(&$notice))) {
341 $id = $notice->insert();
344 common_log_db_error($notice, 'INSERT', __FILE__);
345 common_log(LOG_ERR, $this->name() .
346 ' - Problem saving notice.');
349 Event::handle('EndNoticeSave', array($notice));
352 Notice_to_status::saveNew($notice->id, $status->id);
354 $this->saveStatusMentions($notice, $status);
356 $notice->blowOnInsert();
362 * Make an URI for a status.
364 * @param object $status status object
369 function makeStatusURI($username, $id)
371 return 'http://twitter.com/'
378 * Look up a Profile by profileurl field. Profile::staticGet() was
379 * not working consistently.
381 * @param string $nickname local nickname of the Twitter user
382 * @param string $profileurl the profile url
384 * @return mixed value the first Profile with that url, or null
387 function getProfileByUrl($nickname, $profileurl)
389 $profile = new Profile();
390 $profile->nickname = $nickname;
391 $profile->profileurl = $profileurl;
394 if ($profile->find()) {
403 * Check to see if this Twitter status has already been imported
405 * @param Profile $profile Twitter user's local profile
406 * @param string $statusUri URI of the status on Twitter
408 * @return mixed value a matching Notice or null
411 function checkDupe($profile, $statusUri)
413 $notice = new Notice();
414 $notice->uri = $statusUri;
415 $notice->profile_id = $profile->id;
418 if ($notice->find()) {
426 function ensureProfile($user)
428 // check to see if there's already a profile for this user
430 $profileurl = 'http://twitter.com/' . $user->screen_name;
431 $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
433 if (!empty($profile)) {
434 common_debug($this->name() .
435 " - Profile for $profile->nickname found.");
437 // Check to see if the user's Avatar has changed
439 $this->checkAvatar($user, $profile);
444 common_debug($this->name() . ' - Adding profile and remote profile ' .
445 "for Twitter user: $profileurl.");
447 $profile = new Profile();
448 $profile->query("BEGIN");
450 $profile->nickname = $user->screen_name;
451 $profile->fullname = $user->name;
452 $profile->homepage = $user->url;
453 $profile->bio = $user->description;
454 $profile->location = $user->location;
455 $profile->profileurl = $profileurl;
456 $profile->created = common_sql_now();
459 $id = $profile->insert();
460 } catch(Exception $e) {
461 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
465 common_log_db_error($profile, 'INSERT', __FILE__);
466 $profile->query("ROLLBACK");
470 // check for remote profile
472 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
474 if (empty($remote_pro)) {
476 $remote_pro = new Remote_profile();
478 $remote_pro->id = $id;
479 $remote_pro->uri = $profileurl;
480 $remote_pro->created = common_sql_now();
483 $rid = $remote_pro->insert();
484 } catch (Exception $e) {
485 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
489 common_log_db_error($profile, 'INSERT', __FILE__);
490 $profile->query("ROLLBACK");
495 $profile->query("COMMIT");
497 $this->saveAvatars($user, $id);
503 function checkAvatar($twitter_user, $profile)
507 $path_parts = pathinfo($twitter_user->profile_image_url);
509 $newname = 'Twitter_' . $twitter_user->id . '_' .
510 $path_parts['basename'];
512 $oldname = $profile->getAvatar(48)->filename;
514 if ($newname != $oldname) {
515 common_debug($this->name() . ' - Avatar for Twitter user ' .
516 "$profile->nickname has changed.");
517 common_debug($this->name() . " - old: $oldname new: $newname");
519 $this->updateAvatars($twitter_user, $profile);
522 if ($this->missingAvatarFile($profile)) {
523 common_debug($this->name() . ' - Twitter user ' .
525 ' is missing one or more local avatars.');
526 common_debug($this->name() ." - old: $oldname new: $newname");
528 $this->updateAvatars($twitter_user, $profile);
532 function updateAvatars($twitter_user, $profile) {
536 $path_parts = pathinfo($twitter_user->profile_image_url);
538 $img_root = substr($path_parts['basename'], 0, -11);
539 $ext = $path_parts['extension'];
540 $mediatype = $this->getMediatype($ext);
542 foreach (array('mini', 'normal', 'bigger') as $size) {
543 $url = $path_parts['dirname'] . '/' .
544 $img_root . '_' . $size . ".$ext";
545 $filename = 'Twitter_' . $twitter_user->id . '_' .
546 $img_root . "_$size.$ext";
548 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
549 $this->fetchAvatar($url, $filename);
553 function missingAvatarFile($profile) {
554 foreach (array(24, 48, 73) as $size) {
555 $filename = $profile->getAvatar($size)->filename;
556 $avatarpath = Avatar::path($filename);
557 if (file_exists($avatarpath) == FALSE) {
564 function getMediatype($ext)
568 switch (strtolower($ext)) {
570 $mediatype = 'image/jpg';
573 $mediatype = 'image/gif';
576 $mediatype = 'image/png';
582 function saveAvatars($user, $id)
586 $path_parts = pathinfo($user->profile_image_url);
587 $ext = $path_parts['extension'];
588 $end = strlen('_normal' . $ext);
589 $img_root = substr($path_parts['basename'], 0, -($end+1));
590 $mediatype = $this->getMediatype($ext);
592 foreach (array('mini', 'normal', 'bigger') as $size) {
593 $url = $path_parts['dirname'] . '/' .
594 $img_root . '_' . $size . ".$ext";
595 $filename = 'Twitter_' . $user->id . '_' .
596 $img_root . "_$size.$ext";
598 if ($this->fetchAvatar($url, $filename)) {
599 $this->newAvatar($id, $size, $mediatype, $filename);
601 common_log(LOG_WARNING, $id() .
602 " - Problem fetching Avatar: $url");
607 function updateAvatar($profile_id, $size, $mediatype, $filename) {
609 common_debug($this->name() . " - Updating avatar: $size");
611 $profile = Profile::staticGet($profile_id);
613 if (empty($profile)) {
614 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
618 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
619 $avatar = $profile->getAvatar($sizes[$size]);
621 // Delete the avatar, if present
627 $this->newAvatar($profile->id, $size, $mediatype, $filename);
630 function newAvatar($profile_id, $size, $mediatype, $filename)
634 $avatar = new Avatar();
635 $avatar->profile_id = $profile_id;
640 $avatar->height = 24;
644 $avatar->height = 48;
648 // Note: Twitter's big avatars are a different size than
649 // StatusNet's (StatusNet's = 96)
652 $avatar->height = 73;
655 $avatar->original = 0; // we don't have the original
656 $avatar->mediatype = $mediatype;
657 $avatar->filename = $filename;
658 $avatar->url = Avatar::url($filename);
660 $avatar->created = common_sql_now();
663 $id = $avatar->insert();
664 } catch (Exception $e) {
665 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
669 common_log_db_error($avatar, 'INSERT', __FILE__);
673 common_debug($this->name() .
674 " - Saved new $size avatar for $profile_id.");
680 * Fetch a remote avatar image and save to local storage.
682 * @param string $url avatar source URL
683 * @param string $filename bare local filename for download
684 * @return bool true on success, false on failure
686 function fetchAvatar($url, $filename)
688 common_debug($this->name() . " - Fetching Twitter avatar: $url");
690 $request = HTTPClient::start();
691 $response = $request->get($url);
692 if ($response->isOk()) {
693 $avatarfile = Avatar::path($filename);
694 $ok = file_put_contents($avatarfile, $response->getBody());
696 common_log(LOG_WARNING, $this->name() .
697 " - Couldn't open file $filename");
711 function linkify($status)
713 $text = $status->text;
715 if (empty($status->entities)) {
716 common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
717 $text = common_replace_urls_callback($text, 'common_linkify');
718 $text = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
719 $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
723 // Move all the entities into order so we can
724 // replace them in reverse order and thus
725 // not mess up their indices
727 $toReplace = array();
729 if (!empty($status->entities->urls)) {
730 foreach ($status->entities->urls as $url) {
731 $toReplace[$url->indices[0]] = array(self::URL, $url);
735 if (!empty($status->entities->hashtags)) {
736 foreach ($status->entities->hashtags as $hashtag) {
737 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
741 if (!empty($status->entities->user_mentions)) {
742 foreach ($status->entities->user_mentions as $mention) {
743 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
747 // sort in reverse order by key
751 foreach ($toReplace as $part) {
752 list($type, $object) = $part;
755 $linkText = $this->makeUrlLink($object);
758 $linkText = $this->makeHashtagLink($object);
761 $linkText = $this->makeMentionLink($object);
766 $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
771 function makeUrlLink($object)
773 return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
776 function makeHashtagLink($object)
778 return "#" . self::tagLink($object->text);
781 function makeMentionLink($object)
783 return "@".self::atLink($object->screen_name, $object->name);
786 static function tagLink($tag)
788 return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
791 static function atLink($screenName, $fullName=null)
793 if (!empty($fullName)) {
794 return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
796 return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
800 function saveStatusMentions($notice, $status)
804 if (empty($status->entities) || empty($status->entities->user_mentions)) {
808 foreach ($status->entities->user_mentions as $mention) {
809 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
810 if (!empty($flink)) {
811 $user = User::staticGet('id', $flink->user_id);
813 $reply = new Reply();
814 $reply->notice_id = $notice->id;
815 $reply->profile_id = $user->id;
816 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
817 $id = $reply->insert();
827 if (have_option('i')) {
828 $id = get_option_value('i');
829 } else if (have_option('--id')) {
830 $id = get_option_value('--id');
831 } else if (count($args) > 0) {
837 if (have_option('d') || have_option('debug')) {
841 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);