4 * Laconica - a distributed open-source microblogging tool
5 * Copyright (C) 2008, 2009, Control Yourself, 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 = 'i::';
29 $longoptions = array('id::');
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
34 -i --id Identity (default 'generic')
38 require_once INSTALLDIR.'/scripts/commandline.inc';
40 require_once INSTALLDIR . '/lib/common.php';
41 require_once INSTALLDIR . '/lib/daemon.php';
44 * Fetcher for statuses from Twitter
46 * Fetches statuses from Twitter and inserts them as notices in local
51 * @author Zach Copley <zach@controlyourself.ca>
52 * @author Evan Prodromou <evan@controlyourself.ca>
53 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
54 * @link http://laconi.ca/
57 // NOTE: an Avatar path MUST be set in config.php for this
58 // script to work: e.g.: $config['avatar']['path'] = '/laconica/avatar';
60 class TwitterStatusFetcher extends Daemon
62 private $_children = array();
67 * @return string Name of the daemon.
72 return ('twitterstatusfetcher.'.$this->_id);
85 $flinks = $this->refreshFlinks();
87 foreach ($flinks as $f) {
89 // We have to disconnect from the DB before forking so
90 // each sub-process will open its own connection and
91 // avoid stomping on the others
93 $conn = &$f->getDatabaseConnection();
99 die ("Couldn't fork!");
105 if (defined('SCRIPT_DEBUG')) {
106 common_debug("Parent: forked new status ".
107 " fetcher process " . $pid);
110 $this->_children[] = $pid;
115 $this->getTimeline($f);
119 // Remove child from ps list as it finishes
120 while (($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
122 if (defined('SCRIPT_DEBUG')) {
123 common_debug("Child $c finished.");
126 $this->removePs($this->_children, $c);
129 // Wait! We have too many damn kids.
130 if (sizeof($this->_children) > MAXCHILDREN) {
132 if (defined('SCRIPT_DEBUG')) {
133 common_debug('Too many children. Waiting...');
136 if (($c = pcntl_wait($status, WUNTRACED)) > 0) {
138 if (defined('SCRIPT_DEBUG')) {
139 common_debug("Finished waiting for $c");
142 $this->removePs($this->_children, $c);
147 // Remove all children from the process list before restarting
148 while (($c = pcntl_wait($status, WUNTRACED)) > 0) {
150 if (defined('SCRIPT_DEBUG')) {
151 common_debug("Child $c finished.");
154 $this->removePs($this->_children, $c);
157 // Rest for a bit before we fetch more statuses
159 if (defined('SCRIPT_DEBUG')) {
160 common_debug('Waiting ' . POLL_INTERVAL .
161 ' secs before hitting Twitter again.');
164 if (POLL_INTERVAL > 0) {
165 sleep(POLL_INTERVAL);
172 * Refresh the foreign links for this user
177 function refreshFlinks()
179 $flink = new Foreign_link();
181 $flink->service = 1; // Twitter
183 $flink->orderBy('last_noticesync');
185 $cnt = $flink->find();
187 if (defined('SCRIPT_DEBUG')) {
188 common_debug('Updating Twitter friends subscriptions' .
194 while ($flink->fetch()) {
196 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
197 FOREIGN_NOTICE_RECV) {
198 $flinks[] = clone($flink);
211 * @param array &$plist unknown.
212 * @param string $ps unknown.
218 function removePs(&$plist, $ps)
220 for ($i = 0; $i < sizeof($plist); $i++) {
221 if ($plist[$i] == $ps) {
223 $plist = array_values($plist);
229 function getTimeline($flink)
232 common_log(LOG_WARNING,
233 "Can't retrieve Foreign_link for foreign ID $fid");
237 $fuser = $flink->getForeignUser();
240 common_log(LOG_WARNING, "Unmatched user for ID " .
245 if (defined('SCRIPT_DEBUG')) {
246 common_debug('Trying to get timeline for Twitter user ' .
247 "$fuser->nickname ($flink->foreign_id).");
250 // XXX: Biggest remaining issue - How do we know at which status
251 // to start importing? How many statuses? Right now I'm going
252 // with the default last 20.
254 $url = 'http://twitter.com/statuses/friends_timeline.json';
256 $timeline_json = get_twitter_data($url, $fuser->nickname,
257 $flink->credentials);
259 $timeline = json_decode($timeline_json);
261 if (empty($timeline)) {
262 common_log(LOG_WARNING, "Empty timeline.");
266 // Reverse to preserve order
267 foreach (array_reverse($timeline) as $status) {
269 // Hacktastic: filter out stuff coming from this Laconica
270 $source = mb_strtolower(common_config('integration', 'source'));
272 if (preg_match("/$source/", mb_strtolower($status->source))) {
273 if (defined('SCRIPT_DEBUG')) {
274 common_debug('Skipping import of status ' . $status->id .
275 ' with source ' . $source);
280 $this->saveStatus($status, $flink);
283 // Okay, record the time we synced with Twitter for posterity
284 $flink->last_noticesync = common_sql_now();
288 function saveStatus($status, $flink)
290 $id = $this->ensureProfile($status->user);
291 $profile = Profile::staticGet($id);
295 'Problem saving notice. No associated Profile.');
299 // XXX: change of screen name?
301 $uri = 'http://twitter.com/' . $status->user->screen_name .
302 '/status/' . $status->id;
304 $notice = Notice::staticGet('uri', $uri);
306 // check to see if we've already imported the status
310 $notice = new Notice();
312 $notice->profile_id = $id;
314 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
315 strtotime($status->created_at));
316 $notice->content = common_shorten_links($status->text); // XXX
317 $notice->rendered = common_render_content($notice->content, $notice);
318 $notice->source = 'twitter';
319 $notice->reply_to = null; // XXX lookup reply
320 $notice->is_local = NOTICE_GATEWAY;
322 if (Event::handle('StartNoticeSave', array(&$notice))) {
323 $id = $notice->insert();
324 Event::handle('EndNoticeSave', array($notice));
328 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
329 'user_id' => $flink->user_id))) {
331 $inbox = new Notice_inbox();
333 $inbox->user_id = $flink->user_id;
334 $inbox->notice_id = $notice->id;
335 $inbox->created = $notice->created;
336 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
342 function ensureProfile($user)
344 // check to see if there's already a profile for this user
345 $profileurl = 'http://twitter.com/' . $user->screen_name;
346 $profile = Profile::staticGet('profileurl', $profileurl);
349 if (defined('SCRIPT_DEBUG')) {
350 common_debug("Profile for $profile->nickname found.");
353 // Check to see if the user's Avatar has changed
354 $this->checkAvatar($user, $profile);
359 if (defined('SCRIPT_DEBUG')) {
360 common_debug('Adding profile and remote profile ' .
361 "for Twitter user: $profileurl");
364 $profile = new Profile();
365 $profile->query("BEGIN");
367 $profile->nickname = $user->screen_name;
368 $profile->fullname = $user->name;
369 $profile->homepage = $user->url;
370 $profile->bio = $user->description;
371 $profile->location = $user->location;
372 $profile->profileurl = $profileurl;
373 $profile->created = common_sql_now();
375 $id = $profile->insert();
378 common_log_db_error($profile, 'INSERT', __FILE__);
379 $profile->query("ROLLBACK");
383 // check for remote profile
384 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
388 $remote_pro = new Remote_profile();
390 $remote_pro->id = $id;
391 $remote_pro->uri = $profileurl;
392 $remote_pro->created = common_sql_now();
394 $rid = $remote_pro->insert();
397 common_log_db_error($profile, 'INSERT', __FILE__);
398 $profile->query("ROLLBACK");
403 $profile->query("COMMIT");
405 $this->saveAvatars($user, $id);
411 function checkAvatar($twitter_user, $profile)
415 $path_parts = pathinfo($twitter_user->profile_image_url);
417 $newname = 'Twitter_' . $twitter_user->id . '_' .
418 $path_parts['basename'];
420 $oldname = $profile->getAvatar(48)->filename;
422 if ($newname != $oldname) {
424 if (defined('SCRIPT_DEBUG')) {
425 common_debug('Avatar for Twitter user ' .
426 "$profile->nickname has changed.");
427 common_debug("old: $oldname new: $newname");
430 $this->updateAvatars($twitter_user, $profile);
433 if ($this->missingAvatarFile($profile)) {
435 if (defined('SCRIPT_DEBUG')) {
436 common_debug('Twitter user ' . $profile->nickname .
437 ' is missing one or more local avatars.');
438 common_debug("old: $oldname new: $newname");
441 $this->updateAvatars($twitter_user, $profile);
446 function updateAvatars($twitter_user, $profile) {
450 $path_parts = pathinfo($twitter_user->profile_image_url);
452 $img_root = substr($path_parts['basename'], 0, -11);
453 $ext = $path_parts['extension'];
454 $mediatype = $this->getMediatype($ext);
456 foreach (array('mini', 'normal', 'bigger') as $size) {
457 $url = $path_parts['dirname'] . '/' .
458 $img_root . '_' . $size . ".$ext";
459 $filename = 'Twitter_' . $twitter_user->id . '_' .
460 $img_root . "_$size.$ext";
462 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
463 $this->fetchAvatar($url, $filename);
467 function missingAvatarFile($profile) {
469 foreach (array(24, 48, 73) as $size) {
471 $filename = $profile->getAvatar($size)->filename;
472 $avatarpath = Avatar::path($filename);
474 if (file_exists($avatarpath) == FALSE) {
482 function getMediatype($ext)
486 switch (strtolower($ext)) {
488 $mediatype = 'image/jpg';
491 $mediatype = 'image/gif';
494 $mediatype = 'image/png';
500 function saveAvatars($user, $id)
504 $path_parts = pathinfo($user->profile_image_url);
505 $ext = $path_parts['extension'];
506 $end = strlen('_normal' . $ext);
507 $img_root = substr($path_parts['basename'], 0, -($end+1));
508 $mediatype = $this->getMediatype($ext);
510 foreach (array('mini', 'normal', 'bigger') as $size) {
511 $url = $path_parts['dirname'] . '/' .
512 $img_root . '_' . $size . ".$ext";
513 $filename = 'Twitter_' . $user->id . '_' .
514 $img_root . "_$size.$ext";
516 if ($this->fetchAvatar($url, $filename)) {
517 $this->newAvatar($id, $size, $mediatype, $filename);
519 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
524 function updateAvatar($profile_id, $size, $mediatype, $filename) {
526 if (defined('SCRIPT_DEBUG')) {
527 common_debug("Updating avatar: $size");
530 $profile = Profile::staticGet($profile_id);
532 if (empty($profile)) {
533 if (defined('SCRIPT_DEBUG')) {
534 common_debug("Couldn't get profile: $profile_id!");
539 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
540 $avatar = $profile->getAvatar($sizes[$size]);
542 // Delete the avatar, if present
547 $this->newAvatar($profile->id, $size, $mediatype, $filename);
550 function newAvatar($profile_id, $size, $mediatype, $filename)
554 $avatar = new Avatar();
555 $avatar->profile_id = $profile_id;
560 $avatar->height = 24;
564 $avatar->height = 48;
568 // Note: Twitter's big avatars are a different size than
569 // Laconica's (Laconica's = 96)
572 $avatar->height = 73;
575 $avatar->original = 0; // we don't have the original
576 $avatar->mediatype = $mediatype;
577 $avatar->filename = $filename;
578 $avatar->url = Avatar::url($filename);
580 if (defined('SCRIPT_DEBUG')) {
581 common_debug("new filename: $avatar->url");
584 $avatar->created = common_sql_now();
586 $id = $avatar->insert();
589 common_log_db_error($avatar, 'INSERT', __FILE__);
593 if (defined('SCRIPT_DEBUG')) {
594 common_debug("Saved new $size avatar for $profile_id.");
600 function fetchAvatar($url, $filename)
602 $avatar_dir = INSTALLDIR . '/avatar/';
604 $avatarfile = $avatar_dir . $filename;
606 $out = fopen($avatarfile, 'wb');
608 common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
612 if (defined('SCRIPT_DEBUG')) {
613 common_debug("Fetching avatar: $url");
617 curl_setopt($ch, CURLOPT_URL, $url);
618 curl_setopt($ch, CURLOPT_FILE, $out);
619 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
620 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
621 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
622 $result = curl_exec($ch);
633 if (have_option('i')) {
634 $id = get_option_value('i');
635 } else if (have_option('--id')) {
636 $id = get_option_value('--id');
637 } else if (count($args) > 0) {
643 $fetcher = new TwitterStatusFetcher($id);