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;
107 $flink = new Foreign_link();
108 $conn = &$flink->getDatabaseConnection();
110 $flink->service = TWITTER_SERVICE;
111 $flink->orderBy('last_noticesync');
116 while ($flink->fetch()) {
118 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
119 FOREIGN_NOTICE_RECV) {
120 $flinks[] = clone($flink);
121 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
123 common_log(LOG_INFO, "nothing to sync");
131 unset($_DB_DATAOBJECT['CONNECTIONS']);
136 function childTask($flink) {
138 // Each child ps needs its own DB connection
140 // Note: DataObject::getDatabaseConnection() creates
141 // a new connection if there isn't one already
143 $conn = &$flink->getDatabaseConnection();
145 $this->getTimeline($flink);
147 $flink->last_friendsync = common_sql_now();
152 // XXX: Couldn't find a less brutal way to blow
153 // away a cached connection
155 global $_DB_DATAOBJECT;
156 unset($_DB_DATAOBJECT['CONNECTIONS']);
159 function getTimeline($flink)
162 common_log(LOG_WARNING, $this->name() .
163 " - Can't retrieve Foreign_link for foreign ID $fid");
167 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
170 // XXX: Biggest remaining issue - How do we know at which status
171 // to start importing? How many statuses? Right now I'm going
172 // with the default last 20.
176 if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
177 $token = TwitterOAuthClient::unpackToken($flink->credentials);
178 $client = new TwitterOAuthClient($token->key, $token->secret);
179 common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
181 common_debug("Skipping friends timeline for $flink->foreign_id since not OAuth.");
187 $timeline = $client->statusesHomeTimeline();
188 } catch (Exception $e) {
189 common_log(LOG_WARNING, $this->name() .
190 ' - Twitter client unable to get friends timeline for user ' .
191 $flink->user_id . ' - code: ' .
192 $e->getCode() . 'msg: ' . $e->getMessage());
195 if (empty($timeline)) {
196 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
200 common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
202 // Reverse to preserve order
204 foreach (array_reverse($timeline) as $status) {
206 // Hacktastic: filter out stuff coming from this StatusNet
208 $source = mb_strtolower(common_config('integration', 'source'));
210 if (preg_match("/$source/", mb_strtolower($status->source))) {
211 common_debug($this->name() . ' - Skipping import of status ' .
212 $status->id . ' with source ' . $source);
216 // Don't save it if the user is protected
217 // FIXME: save it but treat it as private
219 if ($status->user->protected) {
223 $notice = $this->saveStatus($status);
225 if (!empty($notice)) {
226 Inbox::insertNotice($flink->user_id, $notice->id);
230 // Okay, record the time we synced with Twitter for posterity
232 $flink->last_noticesync = common_sql_now();
236 function saveStatus($status)
238 $profile = $this->ensureProfile($status->user);
240 if (empty($profile)) {
241 common_log(LOG_ERR, $this->name() .
242 ' - Problem saving notice. No associated Profile.');
246 $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
248 // check to see if we've already imported the status
250 $n2s = Notice_to_status::staticGet('status_id', $status->id);
256 " - Ignoring duplicate import: {$status->id}"
258 return Notice::staticGet('id', $n2s->notice_id);
261 common_debug("Saving status {$status->id} with data " . print_r($status, true));
263 // If it's a retweet, save it as a repeat!
265 if (!empty($status->retweeted_status)) {
266 common_log(LOG_INFO, "Status {$status->id} is a retweet of {$status->retweeted_status->id}.");
267 $original = $this->saveStatus($status->retweeted_status);
268 if (empty($original)) {
271 $author = $original->getProfile();
272 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
273 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
274 $content = sprintf(_('RT @%1$s %2$s'),
278 if (Notice::contentTooLong($content)) {
279 $contentlimit = Notice::maxContent();
280 $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
283 $repeat = Notice::saveNew($profile->id,
286 array('repeat_of' => $original->id,
288 'is_local' => Notice::GATEWAY));
289 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
290 Notice_to_status::saveNew($repeat->id, $status->id);
295 $notice = new Notice();
297 $notice->profile_id = $profile->id;
298 $notice->uri = $statusUri;
299 $notice->url = $statusUri;
300 $notice->created = strftime(
302 strtotime($status->created_at)
305 $notice->source = 'twitter';
307 $notice->reply_to = null;
309 if (!empty($status->in_reply_to_status_id)) {
310 common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
311 $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
313 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
315 $reply = Notice::staticGet('id', $n2s->notice_id);
317 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
319 common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
320 $notice->reply_to = $reply->id;
321 $notice->conversation = $reply->conversation;
326 if (empty($notice->conversation)) {
327 $conv = Conversation::create();
328 $notice->conversation = $conv->id;
329 common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
332 $notice->is_local = Notice::GATEWAY;
334 $notice->content = html_entity_decode($status->text);
335 $notice->rendered = $this->linkify($status);
337 if (Event::handle('StartNoticeSave', array(&$notice))) {
339 $id = $notice->insert();
342 common_log_db_error($notice, 'INSERT', __FILE__);
343 common_log(LOG_ERR, $this->name() .
344 ' - Problem saving notice.');
347 Event::handle('EndNoticeSave', array($notice));
350 Notice_to_status::saveNew($notice->id, $status->id);
351 $notice->blowOnInsert();
357 * Make an URI for a status.
359 * @param object $status status object
364 function makeStatusURI($username, $id)
366 return 'http://twitter.com/'
373 * Look up a Profile by profileurl field. Profile::staticGet() was
374 * not working consistently.
376 * @param string $nickname local nickname of the Twitter user
377 * @param string $profileurl the profile url
379 * @return mixed value the first Profile with that url, or null
382 function getProfileByUrl($nickname, $profileurl)
384 $profile = new Profile();
385 $profile->nickname = $nickname;
386 $profile->profileurl = $profileurl;
389 if ($profile->find()) {
398 * Check to see if this Twitter status has already been imported
400 * @param Profile $profile Twitter user's local profile
401 * @param string $statusUri URI of the status on Twitter
403 * @return mixed value a matching Notice or null
406 function checkDupe($profile, $statusUri)
408 $notice = new Notice();
409 $notice->uri = $statusUri;
410 $notice->profile_id = $profile->id;
413 if ($notice->find()) {
421 function ensureProfile($user)
423 // check to see if there's already a profile for this user
425 $profileurl = 'http://twitter.com/' . $user->screen_name;
426 $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
428 if (!empty($profile)) {
429 common_debug($this->name() .
430 " - Profile for $profile->nickname found.");
432 // Check to see if the user's Avatar has changed
434 $this->checkAvatar($user, $profile);
439 common_debug($this->name() . ' - Adding profile and remote profile ' .
440 "for Twitter user: $profileurl.");
442 $profile = new Profile();
443 $profile->query("BEGIN");
445 $profile->nickname = $user->screen_name;
446 $profile->fullname = $user->name;
447 $profile->homepage = $user->url;
448 $profile->bio = $user->description;
449 $profile->location = $user->location;
450 $profile->profileurl = $profileurl;
451 $profile->created = common_sql_now();
454 $id = $profile->insert();
455 } catch(Exception $e) {
456 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
460 common_log_db_error($profile, 'INSERT', __FILE__);
461 $profile->query("ROLLBACK");
465 // check for remote profile
467 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
469 if (empty($remote_pro)) {
471 $remote_pro = new Remote_profile();
473 $remote_pro->id = $id;
474 $remote_pro->uri = $profileurl;
475 $remote_pro->created = common_sql_now();
478 $rid = $remote_pro->insert();
479 } catch (Exception $e) {
480 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
484 common_log_db_error($profile, 'INSERT', __FILE__);
485 $profile->query("ROLLBACK");
490 $profile->query("COMMIT");
492 $this->saveAvatars($user, $id);
498 function checkAvatar($twitter_user, $profile)
502 $path_parts = pathinfo($twitter_user->profile_image_url);
504 $newname = 'Twitter_' . $twitter_user->id . '_' .
505 $path_parts['basename'];
507 $oldname = $profile->getAvatar(48)->filename;
509 if ($newname != $oldname) {
510 common_debug($this->name() . ' - Avatar for Twitter user ' .
511 "$profile->nickname has changed.");
512 common_debug($this->name() . " - old: $oldname new: $newname");
514 $this->updateAvatars($twitter_user, $profile);
517 if ($this->missingAvatarFile($profile)) {
518 common_debug($this->name() . ' - Twitter user ' .
520 ' is missing one or more local avatars.');
521 common_debug($this->name() ." - old: $oldname new: $newname");
523 $this->updateAvatars($twitter_user, $profile);
527 function updateAvatars($twitter_user, $profile) {
531 $path_parts = pathinfo($twitter_user->profile_image_url);
533 $img_root = substr($path_parts['basename'], 0, -11);
534 $ext = $path_parts['extension'];
535 $mediatype = $this->getMediatype($ext);
537 foreach (array('mini', 'normal', 'bigger') as $size) {
538 $url = $path_parts['dirname'] . '/' .
539 $img_root . '_' . $size . ".$ext";
540 $filename = 'Twitter_' . $twitter_user->id . '_' .
541 $img_root . "_$size.$ext";
543 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
544 $this->fetchAvatar($url, $filename);
548 function missingAvatarFile($profile) {
549 foreach (array(24, 48, 73) as $size) {
550 $filename = $profile->getAvatar($size)->filename;
551 $avatarpath = Avatar::path($filename);
552 if (file_exists($avatarpath) == FALSE) {
559 function getMediatype($ext)
563 switch (strtolower($ext)) {
565 $mediatype = 'image/jpg';
568 $mediatype = 'image/gif';
571 $mediatype = 'image/png';
577 function saveAvatars($user, $id)
581 $path_parts = pathinfo($user->profile_image_url);
582 $ext = $path_parts['extension'];
583 $end = strlen('_normal' . $ext);
584 $img_root = substr($path_parts['basename'], 0, -($end+1));
585 $mediatype = $this->getMediatype($ext);
587 foreach (array('mini', 'normal', 'bigger') as $size) {
588 $url = $path_parts['dirname'] . '/' .
589 $img_root . '_' . $size . ".$ext";
590 $filename = 'Twitter_' . $user->id . '_' .
591 $img_root . "_$size.$ext";
593 if ($this->fetchAvatar($url, $filename)) {
594 $this->newAvatar($id, $size, $mediatype, $filename);
596 common_log(LOG_WARNING, $id() .
597 " - Problem fetching Avatar: $url");
602 function updateAvatar($profile_id, $size, $mediatype, $filename) {
604 common_debug($this->name() . " - Updating avatar: $size");
606 $profile = Profile::staticGet($profile_id);
608 if (empty($profile)) {
609 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
613 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
614 $avatar = $profile->getAvatar($sizes[$size]);
616 // Delete the avatar, if present
622 $this->newAvatar($profile->id, $size, $mediatype, $filename);
625 function newAvatar($profile_id, $size, $mediatype, $filename)
629 $avatar = new Avatar();
630 $avatar->profile_id = $profile_id;
635 $avatar->height = 24;
639 $avatar->height = 48;
643 // Note: Twitter's big avatars are a different size than
644 // StatusNet's (StatusNet's = 96)
647 $avatar->height = 73;
650 $avatar->original = 0; // we don't have the original
651 $avatar->mediatype = $mediatype;
652 $avatar->filename = $filename;
653 $avatar->url = Avatar::url($filename);
655 $avatar->created = common_sql_now();
658 $id = $avatar->insert();
659 } catch (Exception $e) {
660 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
664 common_log_db_error($avatar, 'INSERT', __FILE__);
668 common_debug($this->name() .
669 " - Saved new $size avatar for $profile_id.");
675 * Fetch a remote avatar image and save to local storage.
677 * @param string $url avatar source URL
678 * @param string $filename bare local filename for download
679 * @return bool true on success, false on failure
681 function fetchAvatar($url, $filename)
683 common_debug($this->name() . " - Fetching Twitter avatar: $url");
685 $request = HTTPClient::start();
686 $response = $request->get($url);
687 if ($response->isOk()) {
688 $avatarfile = Avatar::path($filename);
689 $ok = file_put_contents($avatarfile, $response->getBody());
691 common_log(LOG_WARNING, $this->name() .
692 " - Couldn't open file $filename");
706 function linkify($status)
708 $text = $status->text;
710 if (empty($status->entities)) {
714 // Move all the entities into order so we can
715 // replace them in reverse order and thus
716 // not mess up their indices
718 $toReplace = array();
720 if (!empty($status->entities->urls)) {
721 foreach ($status->entities->urls as $url) {
722 $toReplace[$url->indices[0]] = array(self::URL, $url);
726 if (!empty($status->entities->hashtags)) {
727 foreach ($status->entities->hashtags as $hashtag) {
728 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
732 if (!empty($status->entities->user_mentions)) {
733 foreach ($status->entities->user_mentions as $mention) {
734 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
738 // sort in reverse order by key
742 foreach ($toReplace as $part) {
743 list($type, $object) = $part;
746 $linkText = $this->makeUrlLink($object);
749 $linkText = $this->makeHashtagLink($object);
752 $linkText = $this->makeMentionLink($object);
757 $text = substr_replace($text,
760 $object->indices[1] - $object->indices[0]);
765 function makeUrlLink($object)
767 return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
770 function makeHashtagLink($object)
772 return "<a href='https://twitter.com/search?q=%23{$object->text}' class='hashtag'>{$object->text}</a>";
775 function makeMentionLink($object)
777 return "<a href='http://twitter.com/{$object->screen_name}' title='{$object->name}'>{$object->screen_name}</a>";
784 if (have_option('i')) {
785 $id = get_option_value('i');
786 } else if (have_option('--id')) {
787 $id = get_option_value('--id');
788 } else if (count($args) > 0) {
794 if (have_option('d') || have_option('debug')) {
798 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);