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/twitterbasicauthclient.php';
44 require_once INSTALLDIR . '/plugins/TwitterBridge/twitteroauthclient.php';
47 * Fetch statuses from Twitter
49 * Fetches statuses from Twitter and inserts them as notices
51 * NOTE: an Avatar path MUST be set in config.php for this
52 * script to work, e.g.:
53 * $config['avatar']['path'] = $config['site']['path'] . '/avatar/';
55 * @todo @fixme @gar Fix the above. For some reason $_path is always empty when
56 * this script is run, so the default avatar path is always set wrong in
57 * default.php. Therefore it must be set explicitly in config.php. --Z
61 * @author Zach Copley <zach@status.net>
62 * @author Evan Prodromou <evan@status.net>
63 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
64 * @link http://status.net/
67 class TwitterStatusFetcher extends ParallelizingDaemon
72 * @param string $id the name/id of this daemon
73 * @param int $interval sleep this long before doing everything again
74 * @param int $max_children maximum number of child processes at a time
75 * @param boolean $debug debug output flag
80 function __construct($id = null, $interval = 60,
81 $max_children = 2, $debug = null)
83 parent::__construct($id, $interval, $max_children, $debug);
89 * @return string Name of the daemon.
94 return ('twitterstatusfetcher.'.$this->_id);
98 * Find all the Twitter foreign links for users who have requested
99 * importing of their friends' timelines
101 * @return array flinks an array of Foreign_link objects
104 function getObjects()
106 global $_DB_DATAOBJECT;
108 $flink = new Foreign_link();
109 $conn = &$flink->getDatabaseConnection();
111 $flink->service = TWITTER_SERVICE;
112 $flink->orderBy('last_noticesync');
117 while ($flink->fetch()) {
119 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
120 FOREIGN_NOTICE_RECV) {
121 $flinks[] = clone($flink);
122 common_log(LOG_INFO, "sync: foreign id $flink->foreign_id");
124 common_log(LOG_INFO, "nothing to sync");
132 unset($_DB_DATAOBJECT['CONNECTIONS']);
137 function childTask($flink) {
139 // Each child ps needs its own DB connection
141 // Note: DataObject::getDatabaseConnection() creates
142 // a new connection if there isn't one already
144 $conn = &$flink->getDatabaseConnection();
146 $this->getTimeline($flink);
148 $flink->last_friendsync = common_sql_now();
153 // XXX: Couldn't find a less brutal way to blow
154 // away a cached connection
156 global $_DB_DATAOBJECT;
157 unset($_DB_DATAOBJECT['CONNECTIONS']);
160 function getTimeline($flink)
163 common_log(LOG_WARNING, $this->name() .
164 " - Can't retrieve Foreign_link for foreign ID $fid");
168 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
171 // XXX: Biggest remaining issue - How do we know at which status
172 // to start importing? How many statuses? Right now I'm going
173 // with the default last 20.
177 if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
178 $token = TwitterOAuthClient::unpackToken($flink->credentials);
179 $client = new TwitterOAuthClient($token->key, $token->secret);
180 common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
182 $client = new TwitterBasicAuthClient($flink);
183 common_debug($this->name() . ' - Grabbing friends timeline with basic auth.');
189 $timeline = $client->statusesFriendsTimeline();
190 } catch (Exception $e) {
191 common_log(LOG_WARNING, $this->name() .
192 ' - Twitter client unable to get friends timeline for user ' .
193 $flink->user_id . ' - code: ' .
194 $e->getCode() . 'msg: ' . $e->getMessage());
197 if (empty($timeline)) {
198 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
202 common_debug(LOG_INFO, $this->name() . ' - Retrieved ' . sizeof($timeline) . ' statuses from Twitter.');
204 // Reverse to preserve order
206 foreach (array_reverse($timeline) as $status) {
208 // Hacktastic: filter out stuff coming from this StatusNet
210 $source = mb_strtolower(common_config('integration', 'source'));
212 if (preg_match("/$source/", mb_strtolower($status->source))) {
213 common_debug($this->name() . ' - Skipping import of status ' .
214 $status->id . ' with source ' . $source);
218 // Don't save it if the user is protected
219 // FIXME: save it but treat it as private
221 if ($status->user->protected) {
225 $notice = $this->saveStatus($status);
227 if (!empty($notice)) {
228 Inbox::insertNotice($flink->user_id, $notice->id);
232 // Okay, record the time we synced with Twitter for posterity
234 $flink->last_noticesync = common_sql_now();
238 function saveStatus($status)
240 $profile = $this->ensureProfile($status->user);
242 if (empty($profile)) {
243 common_log(LOG_ERR, $this->name() .
244 ' - Problem saving notice. No associated Profile.');
248 $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
250 // check to see if we've already imported the status
252 $dupe = $this->checkDupe($profile, $statusUri);
258 " - Ignoring duplicate import: $statusUri"
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 $repeat = $original->repeat($profile->id, 'twitter');
269 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
273 $notice = new Notice();
275 $notice->profile_id = $profile->id;
276 $notice->uri = $statusUri;
277 $notice->url = $statusUri;
278 $notice->created = strftime(
280 strtotime($status->created_at)
283 $notice->source = 'twitter';
285 $notice->reply_to = null;
287 if (!empty($status->in_reply_to_status_id)) {
288 common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
289 $replyUri = $this->makeStatusURI($status->in_reply_to_screen_name, $status->in_reply_to_status_id);
290 $reply = Notice::staticGet('uri', $replyUri);
292 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
294 common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
295 $notice->reply_to = $reply->id;
296 $notice->conversation = $reply->conversation;
300 if (empty($notice->conversation)) {
301 $conv = Conversation::create();
302 $notice->conversation = $conv->id;
303 common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
306 $notice->is_local = Notice::GATEWAY;
308 $notice->content = common_shorten_links($status->text);
309 $notice->rendered = common_render_content(
314 if (Event::handle('StartNoticeSave', array(&$notice))) {
316 $id = $notice->insert();
319 common_log_db_error($notice, 'INSERT', __FILE__);
320 common_log(LOG_ERR, $this->name() .
321 ' - Problem saving notice.');
324 Event::handle('EndNoticeSave', array($notice));
327 $notice->blowOnInsert();
333 * Make an URI for a status.
335 * @param object $status status object
340 function makeStatusURI($username, $id)
342 return 'http://twitter.com/'
349 * Look up a Profile by profileurl field. Profile::staticGet() was
350 * not working consistently.
352 * @param string $nickname local nickname of the Twitter user
353 * @param string $profileurl the profile url
355 * @return mixed value the first Profile with that url, or null
358 function getProfileByUrl($nickname, $profileurl)
360 $profile = new Profile();
361 $profile->nickname = $nickname;
362 $profile->profileurl = $profileurl;
365 if ($profile->find()) {
374 * Check to see if this Twitter status has already been imported
376 * @param Profile $profile Twitter user's local profile
377 * @param string $statusUri URI of the status on Twitter
379 * @return mixed value a matching Notice or null
382 function checkDupe($profile, $statusUri)
384 $notice = new Notice();
385 $notice->uri = $statusUri;
386 $notice->profile_id = $profile->id;
389 if ($notice->find()) {
397 function ensureProfile($user)
399 // check to see if there's already a profile for this user
401 $profileurl = 'http://twitter.com/' . $user->screen_name;
402 $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
404 if (!empty($profile)) {
405 common_debug($this->name() .
406 " - Profile for $profile->nickname found.");
408 // Check to see if the user's Avatar has changed
410 $this->checkAvatar($user, $profile);
415 common_debug($this->name() . ' - Adding profile and remote profile ' .
416 "for Twitter user: $profileurl.");
418 $profile = new Profile();
419 $profile->query("BEGIN");
421 $profile->nickname = $user->screen_name;
422 $profile->fullname = $user->name;
423 $profile->homepage = $user->url;
424 $profile->bio = $user->description;
425 $profile->location = $user->location;
426 $profile->profileurl = $profileurl;
427 $profile->created = common_sql_now();
430 $id = $profile->insert();
431 } catch(Exception $e) {
432 common_log(LOG_WARNING, $this->name . ' Couldn\'t insert profile - ' . $e->getMessage());
436 common_log_db_error($profile, 'INSERT', __FILE__);
437 $profile->query("ROLLBACK");
441 // check for remote profile
443 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
445 if (empty($remote_pro)) {
447 $remote_pro = new Remote_profile();
449 $remote_pro->id = $id;
450 $remote_pro->uri = $profileurl;
451 $remote_pro->created = common_sql_now();
454 $rid = $remote_pro->insert();
455 } catch (Exception $e) {
456 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
460 common_log_db_error($profile, 'INSERT', __FILE__);
461 $profile->query("ROLLBACK");
466 $profile->query("COMMIT");
468 $this->saveAvatars($user, $id);
474 function checkAvatar($twitter_user, $profile)
478 $path_parts = pathinfo($twitter_user->profile_image_url);
480 $newname = 'Twitter_' . $twitter_user->id . '_' .
481 $path_parts['basename'];
483 $oldname = $profile->getAvatar(48)->filename;
485 if ($newname != $oldname) {
486 common_debug($this->name() . ' - Avatar for Twitter user ' .
487 "$profile->nickname has changed.");
488 common_debug($this->name() . " - old: $oldname new: $newname");
490 $this->updateAvatars($twitter_user, $profile);
493 if ($this->missingAvatarFile($profile)) {
494 common_debug($this->name() . ' - Twitter user ' .
496 ' is missing one or more local avatars.');
497 common_debug($this->name() ." - old: $oldname new: $newname");
499 $this->updateAvatars($twitter_user, $profile);
503 function updateAvatars($twitter_user, $profile) {
507 $path_parts = pathinfo($twitter_user->profile_image_url);
509 $img_root = substr($path_parts['basename'], 0, -11);
510 $ext = $path_parts['extension'];
511 $mediatype = $this->getMediatype($ext);
513 foreach (array('mini', 'normal', 'bigger') as $size) {
514 $url = $path_parts['dirname'] . '/' .
515 $img_root . '_' . $size . ".$ext";
516 $filename = 'Twitter_' . $twitter_user->id . '_' .
517 $img_root . "_$size.$ext";
519 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
520 $this->fetchAvatar($url, $filename);
524 function missingAvatarFile($profile) {
525 foreach (array(24, 48, 73) as $size) {
526 $filename = $profile->getAvatar($size)->filename;
527 $avatarpath = Avatar::path($filename);
528 if (file_exists($avatarpath) == FALSE) {
535 function getMediatype($ext)
539 switch (strtolower($ext)) {
541 $mediatype = 'image/jpg';
544 $mediatype = 'image/gif';
547 $mediatype = 'image/png';
553 function saveAvatars($user, $id)
557 $path_parts = pathinfo($user->profile_image_url);
558 $ext = $path_parts['extension'];
559 $end = strlen('_normal' . $ext);
560 $img_root = substr($path_parts['basename'], 0, -($end+1));
561 $mediatype = $this->getMediatype($ext);
563 foreach (array('mini', 'normal', 'bigger') as $size) {
564 $url = $path_parts['dirname'] . '/' .
565 $img_root . '_' . $size . ".$ext";
566 $filename = 'Twitter_' . $user->id . '_' .
567 $img_root . "_$size.$ext";
569 if ($this->fetchAvatar($url, $filename)) {
570 $this->newAvatar($id, $size, $mediatype, $filename);
572 common_log(LOG_WARNING, $id() .
573 " - Problem fetching Avatar: $url");
578 function updateAvatar($profile_id, $size, $mediatype, $filename) {
580 common_debug($this->name() . " - Updating avatar: $size");
582 $profile = Profile::staticGet($profile_id);
584 if (empty($profile)) {
585 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
589 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
590 $avatar = $profile->getAvatar($sizes[$size]);
592 // Delete the avatar, if present
598 $this->newAvatar($profile->id, $size, $mediatype, $filename);
601 function newAvatar($profile_id, $size, $mediatype, $filename)
605 $avatar = new Avatar();
606 $avatar->profile_id = $profile_id;
611 $avatar->height = 24;
615 $avatar->height = 48;
619 // Note: Twitter's big avatars are a different size than
620 // StatusNet's (StatusNet's = 96)
623 $avatar->height = 73;
626 $avatar->original = 0; // we don't have the original
627 $avatar->mediatype = $mediatype;
628 $avatar->filename = $filename;
629 $avatar->url = Avatar::url($filename);
631 $avatar->created = common_sql_now();
634 $id = $avatar->insert();
635 } catch (Exception $e) {
636 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
640 common_log_db_error($avatar, 'INSERT', __FILE__);
644 common_debug($this->name() .
645 " - Saved new $size avatar for $profile_id.");
651 * Fetch a remote avatar image and save to local storage.
653 * @param string $url avatar source URL
654 * @param string $filename bare local filename for download
655 * @return bool true on success, false on failure
657 function fetchAvatar($url, $filename)
659 common_debug($this->name() . " - Fetching Twitter avatar: $url");
661 $request = HTTPClient::start();
662 $response = $request->get($url);
663 if ($response->isOk()) {
664 $avatarfile = Avatar::path($filename);
665 $ok = file_put_contents($avatarfile, $response->getBody());
667 common_log(LOG_WARNING, $this->name() .
668 " - Couldn't open file $filename");
682 if (have_option('i')) {
683 $id = get_option_value('i');
684 } else if (have_option('--id')) {
685 $id = get_option_value('--id');
686 } else if (count($args) > 0) {
692 if (have_option('d') || have_option('debug')) {
696 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);