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 ' .
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.
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.');
180 common_debug("Skipping friends timeline for $flink->foreign_id since not OAuth.");
185 $lastId = Twitter_synch_status::getLastId($flink->user_id, 'home_timeline');
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());
196 if (empty($timeline)) {
197 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
201 common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
205 // Reverse to preserve order
207 foreach (array_reverse($timeline) as $status) {
209 $lastSeenId = $status->id;
211 // Hacktastic: filter out stuff coming from this StatusNet
213 $source = mb_strtolower(common_config('integration', 'source'));
215 if (preg_match("/$source/", mb_strtolower($status->source))) {
216 common_debug($this->name() . ' - Skipping import of status ' .
217 $status->id . ' with source ' . $source);
221 // Don't save it if the user is protected
222 // FIXME: save it but treat it as private
224 if ($status->user->protected) {
228 $notice = $this->saveStatus($status);
230 if (!empty($notice)) {
231 Inbox::insertNotice($flink->user_id, $notice->id);
235 if (!empty($lastSeenId)) {
236 Twitter_synch_status::setLastId($flink->user_id, 'home_timeline', $lastSeenId);
239 // Okay, record the time we synced with Twitter for posterity
241 $flink->last_noticesync = common_sql_now();
245 function saveStatus($status)
247 $profile = $this->ensureProfile($status->user);
249 if (empty($profile)) {
250 common_log(LOG_ERR, $this->name() .
251 ' - Problem saving notice. No associated Profile.');
255 $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
257 // check to see if we've already imported the status
259 $n2s = Notice_to_status::staticGet('status_id', $status->id);
265 " - Ignoring duplicate import: {$status->id}"
267 return Notice::staticGet('id', $n2s->notice_id);
270 // If it's a retweet, save it as a repeat!
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)) {
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'),
285 if (Notice::contentTooLong($content)) {
286 $contentlimit = Notice::maxContent();
287 $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
290 $repeat = Notice::saveNew($profile->id,
293 array('repeat_of' => $original->id,
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);
302 $notice = new Notice();
304 $notice->profile_id = $profile->id;
305 $notice->uri = $statusUri;
306 $notice->url = $statusUri;
307 $notice->created = strftime(
309 strtotime($status->created_at)
312 $notice->source = 'twitter';
314 $notice->reply_to = null;
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);
320 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
322 $reply = Notice::staticGet('id', $n2s->notice_id);
324 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
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;
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}.");
339 $notice->is_local = Notice::GATEWAY;
341 $notice->content = html_entity_decode($status->text);
342 $notice->rendered = $this->linkify($status);
344 if (Event::handle('StartNoticeSave', array(&$notice))) {
346 $id = $notice->insert();
349 common_log_db_error($notice, 'INSERT', __FILE__);
350 common_log(LOG_ERR, $this->name() .
351 ' - Problem saving notice.');
354 Event::handle('EndNoticeSave', array($notice));
357 Notice_to_status::saveNew($notice->id, $status->id);
359 $this->saveStatusMentions($notice, $status);
361 $notice->blowOnInsert();
367 * Make an URI for a status.
369 * @param object $status status object
374 function makeStatusURI($username, $id)
376 return 'http://twitter.com/'
383 * Look up a Profile by profileurl field. Profile::staticGet() was
384 * not working consistently.
386 * @param string $nickname local nickname of the Twitter user
387 * @param string $profileurl the profile url
389 * @return mixed value the first Profile with that url, or null
392 function getProfileByUrl($nickname, $profileurl)
394 $profile = new Profile();
395 $profile->nickname = $nickname;
396 $profile->profileurl = $profileurl;
399 if ($profile->find()) {
408 * Check to see if this Twitter status has already been imported
410 * @param Profile $profile Twitter user's local profile
411 * @param string $statusUri URI of the status on Twitter
413 * @return mixed value a matching Notice or null
416 function checkDupe($profile, $statusUri)
418 $notice = new Notice();
419 $notice->uri = $statusUri;
420 $notice->profile_id = $profile->id;
423 if ($notice->find()) {
431 function ensureProfile($user)
433 // check to see if there's already a profile for this user
435 $profileurl = 'http://twitter.com/' . $user->screen_name;
436 $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
438 if (!empty($profile)) {
439 common_debug($this->name() .
440 " - Profile for $profile->nickname found.");
442 // Check to see if the user's Avatar has changed
444 $this->checkAvatar($user, $profile);
449 common_debug($this->name() . ' - Adding profile and remote profile ' .
450 "for Twitter user: $profileurl.");
452 $profile = new Profile();
453 $profile->query("BEGIN");
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();
464 $id = $profile->insert();
465 } catch(Exception $e) {
466 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
470 common_log_db_error($profile, 'INSERT', __FILE__);
471 $profile->query("ROLLBACK");
475 // check for remote profile
477 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
479 if (empty($remote_pro)) {
481 $remote_pro = new Remote_profile();
483 $remote_pro->id = $id;
484 $remote_pro->uri = $profileurl;
485 $remote_pro->created = common_sql_now();
488 $rid = $remote_pro->insert();
489 } catch (Exception $e) {
490 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
494 common_log_db_error($profile, 'INSERT', __FILE__);
495 $profile->query("ROLLBACK");
500 $profile->query("COMMIT");
502 $this->saveAvatars($user, $id);
508 function checkAvatar($twitter_user, $profile)
512 $path_parts = pathinfo($twitter_user->profile_image_url);
514 $newname = 'Twitter_' . $twitter_user->id . '_' .
515 $path_parts['basename'];
517 $oldname = $profile->getAvatar(48)->filename;
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");
524 $this->updateAvatars($twitter_user, $profile);
527 if ($this->missingAvatarFile($profile)) {
528 common_debug($this->name() . ' - Twitter user ' .
530 ' is missing one or more local avatars.');
531 common_debug($this->name() ." - old: $oldname new: $newname");
533 $this->updateAvatars($twitter_user, $profile);
537 function updateAvatars($twitter_user, $profile) {
541 $path_parts = pathinfo($twitter_user->profile_image_url);
543 $img_root = substr($path_parts['basename'], 0, -11);
544 $ext = $path_parts['extension'];
545 $mediatype = $this->getMediatype($ext);
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";
553 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
554 $this->fetchAvatar($url, $filename);
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) {
569 function getMediatype($ext)
573 switch (strtolower($ext)) {
575 $mediatype = 'image/jpg';
578 $mediatype = 'image/gif';
581 $mediatype = 'image/png';
587 function saveAvatars($user, $id)
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);
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";
603 if ($this->fetchAvatar($url, $filename)) {
604 $this->newAvatar($id, $size, $mediatype, $filename);
606 common_log(LOG_WARNING, $id() .
607 " - Problem fetching Avatar: $url");
612 function updateAvatar($profile_id, $size, $mediatype, $filename) {
614 common_debug($this->name() . " - Updating avatar: $size");
616 $profile = Profile::staticGet($profile_id);
618 if (empty($profile)) {
619 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
623 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
624 $avatar = $profile->getAvatar($sizes[$size]);
626 // Delete the avatar, if present
632 $this->newAvatar($profile->id, $size, $mediatype, $filename);
635 function newAvatar($profile_id, $size, $mediatype, $filename)
639 $avatar = new Avatar();
640 $avatar->profile_id = $profile_id;
645 $avatar->height = 24;
649 $avatar->height = 48;
653 // Note: Twitter's big avatars are a different size than
654 // StatusNet's (StatusNet's = 96)
657 $avatar->height = 73;
660 $avatar->original = 0; // we don't have the original
661 $avatar->mediatype = $mediatype;
662 $avatar->filename = $filename;
663 $avatar->url = Avatar::url($filename);
665 $avatar->created = common_sql_now();
668 $id = $avatar->insert();
669 } catch (Exception $e) {
670 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
674 common_log_db_error($avatar, 'INSERT', __FILE__);
678 common_debug($this->name() .
679 " - Saved new $size avatar for $profile_id.");
685 * Fetch a remote avatar image and save to local storage.
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
691 function fetchAvatar($url, $filename)
693 common_debug($this->name() . " - Fetching Twitter avatar: $url");
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());
701 common_log(LOG_WARNING, $this->name() .
702 " - Couldn't open file $filename");
716 function linkify($status)
718 $text = $status->text;
720 if (empty($status->entities)) {
724 // Move all the entities into order so we can
725 // replace them in reverse order and thus
726 // not mess up their indices
728 $toReplace = array();
730 if (!empty($status->entities->urls)) {
731 foreach ($status->entities->urls as $url) {
732 $toReplace[$url->indices[0]] = array(self::URL, $url);
736 if (!empty($status->entities->hashtags)) {
737 foreach ($status->entities->hashtags as $hashtag) {
738 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
742 if (!empty($status->entities->user_mentions)) {
743 foreach ($status->entities->user_mentions as $mention) {
744 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
748 // sort in reverse order by key
752 foreach ($toReplace as $part) {
753 list($type, $object) = $part;
756 $linkText = $this->makeUrlLink($object);
759 $linkText = $this->makeHashtagLink($object);
762 $linkText = $this->makeMentionLink($object);
767 $text = substr_replace($text,
770 $object->indices[1] - $object->indices[0]);
775 function makeUrlLink($object)
777 return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
780 function makeHashtagLink($object)
782 return "#<a href='https://twitter.com/search?q=%23{$object->text}' class='hashtag'>{$object->text}</a>";
785 function makeMentionLink($object)
787 return "@<a href='http://twitter.com/{$object->screen_name}' title='{$object->name}'>{$object->screen_name}</a>";
790 function saveStatusMentions($notice, $status)
794 if (empty($status->entities) || empty($status->entities->user_mentions)) {
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);
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();
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) {
827 if (have_option('d') || have_option('debug')) {
831 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);