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();
64 function __construct($id=null, $daemonize=true)
66 parent::__construct($daemonize);
76 * @return string Name of the daemon.
81 return ('twitterstatusfetcher.'.$this->_id);
94 $flinks = $this->refreshFlinks();
96 foreach ($flinks as $f) {
98 // We have to disconnect from the DB before forking so
99 // each sub-process will open its own connection and
100 // avoid stomping on the others
102 $conn = &$f->getDatabaseConnection();
108 die ("Couldn't fork!");
114 if (defined('SCRIPT_DEBUG')) {
115 common_debug("Parent: forked new status ".
116 " fetcher process " . $pid);
119 $this->_children[] = $pid;
124 $this->getTimeline($f);
128 // Remove child from ps list as it finishes
129 while (($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
131 if (defined('SCRIPT_DEBUG')) {
132 common_debug("Child $c finished.");
135 $this->removePs($this->_children, $c);
138 // Wait! We have too many damn kids.
139 if (sizeof($this->_children) > MAXCHILDREN) {
141 if (defined('SCRIPT_DEBUG')) {
142 common_debug('Too many children. Waiting...');
145 if (($c = pcntl_wait($status, WUNTRACED)) > 0) {
147 if (defined('SCRIPT_DEBUG')) {
148 common_debug("Finished waiting for $c");
151 $this->removePs($this->_children, $c);
156 // Remove all children from the process list before restarting
157 while (($c = pcntl_wait($status, WUNTRACED)) > 0) {
159 if (defined('SCRIPT_DEBUG')) {
160 common_debug("Child $c finished.");
163 $this->removePs($this->_children, $c);
166 // Rest for a bit before we fetch more statuses
168 if (defined('SCRIPT_DEBUG')) {
169 common_debug('Waiting ' . POLL_INTERVAL .
170 ' secs before hitting Twitter again.');
173 if (POLL_INTERVAL > 0) {
174 sleep(POLL_INTERVAL);
181 * Refresh the foreign links for this user
186 function refreshFlinks()
188 $flink = new Foreign_link();
190 $flink->service = 1; // Twitter
192 $flink->orderBy('last_noticesync');
194 $cnt = $flink->find();
196 if (defined('SCRIPT_DEBUG')) {
197 common_debug('Updating Twitter friends subscriptions' .
203 while ($flink->fetch()) {
205 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
206 FOREIGN_NOTICE_RECV) {
207 $flinks[] = clone($flink);
220 * @param array &$plist unknown.
221 * @param string $ps unknown.
227 function removePs(&$plist, $ps)
229 for ($i = 0; $i < sizeof($plist); $i++) {
230 if ($plist[$i] == $ps) {
232 $plist = array_values($plist);
238 function getTimeline($flink)
241 common_log(LOG_WARNING,
242 "Can't retrieve Foreign_link for foreign ID $fid");
246 $fuser = $flink->getForeignUser();
249 common_log(LOG_WARNING, "Unmatched user for ID " .
254 if (defined('SCRIPT_DEBUG')) {
255 common_debug('Trying to get timeline for Twitter user ' .
256 "$fuser->nickname ($flink->foreign_id).");
259 // XXX: Biggest remaining issue - How do we know at which status
260 // to start importing? How many statuses? Right now I'm going
261 // with the default last 20.
263 $url = 'http://twitter.com/statuses/friends_timeline.json';
265 $timeline_json = get_twitter_data($url, $fuser->nickname,
266 $flink->credentials);
268 $timeline = json_decode($timeline_json);
270 if (empty($timeline)) {
271 common_log(LOG_WARNING, "Empty timeline.");
275 // Reverse to preserve order
276 foreach (array_reverse($timeline) as $status) {
278 // Hacktastic: filter out stuff coming from this Laconica
279 $source = mb_strtolower(common_config('integration', 'source'));
281 if (preg_match("/$source/", mb_strtolower($status->source))) {
282 if (defined('SCRIPT_DEBUG')) {
283 common_debug('Skipping import of status ' . $status->id .
284 ' with source ' . $source);
289 $this->saveStatus($status, $flink);
292 // Okay, record the time we synced with Twitter for posterity
293 $flink->last_noticesync = common_sql_now();
297 function saveStatus($status, $flink)
299 $id = $this->ensureProfile($status->user);
300 $profile = Profile::staticGet($id);
304 'Problem saving notice. No associated Profile.');
308 // XXX: change of screen name?
310 $uri = 'http://twitter.com/' . $status->user->screen_name .
311 '/status/' . $status->id;
313 $notice = Notice::staticGet('uri', $uri);
315 // check to see if we've already imported the status
319 $notice = new Notice();
321 $notice->profile_id = $id;
323 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
324 strtotime($status->created_at));
325 $notice->content = common_shorten_links($status->text); // XXX
326 $notice->rendered = common_render_content($notice->content, $notice);
327 $notice->source = 'twitter';
328 $notice->reply_to = null; // XXX lookup reply
329 $notice->is_local = NOTICE_GATEWAY;
331 if (Event::handle('StartNoticeSave', array(&$notice))) {
332 $id = $notice->insert();
333 Event::handle('EndNoticeSave', array($notice));
337 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
338 'user_id' => $flink->user_id))) {
340 $inbox = new Notice_inbox();
342 $inbox->user_id = $flink->user_id;
343 $inbox->notice_id = $notice->id;
344 $inbox->created = $notice->created;
345 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
351 function ensureProfile($user)
353 // check to see if there's already a profile for this user
354 $profileurl = 'http://twitter.com/' . $user->screen_name;
355 $profile = Profile::staticGet('profileurl', $profileurl);
358 if (defined('SCRIPT_DEBUG')) {
359 common_debug("Profile for $profile->nickname found.");
362 // Check to see if the user's Avatar has changed
363 $this->checkAvatar($user, $profile);
368 if (defined('SCRIPT_DEBUG')) {
369 common_debug('Adding profile and remote profile ' .
370 "for Twitter user: $profileurl");
373 $profile = new Profile();
374 $profile->query("BEGIN");
376 $profile->nickname = $user->screen_name;
377 $profile->fullname = $user->name;
378 $profile->homepage = $user->url;
379 $profile->bio = $user->description;
380 $profile->location = $user->location;
381 $profile->profileurl = $profileurl;
382 $profile->created = common_sql_now();
384 $id = $profile->insert();
387 common_log_db_error($profile, 'INSERT', __FILE__);
388 $profile->query("ROLLBACK");
392 // check for remote profile
393 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
397 $remote_pro = new Remote_profile();
399 $remote_pro->id = $id;
400 $remote_pro->uri = $profileurl;
401 $remote_pro->created = common_sql_now();
403 $rid = $remote_pro->insert();
406 common_log_db_error($profile, 'INSERT', __FILE__);
407 $profile->query("ROLLBACK");
412 $profile->query("COMMIT");
414 $this->saveAvatars($user, $id);
420 function checkAvatar($twitter_user, $profile)
424 $path_parts = pathinfo($twitter_user->profile_image_url);
426 $newname = 'Twitter_' . $twitter_user->id . '_' .
427 $path_parts['basename'];
429 $oldname = $profile->getAvatar(48)->filename;
431 if ($newname != $oldname) {
433 if (defined('SCRIPT_DEBUG')) {
434 common_debug('Avatar for Twitter user ' .
435 "$profile->nickname has changed.");
436 common_debug("old: $oldname new: $newname");
439 $this->updateAvatars($twitter_user, $profile);
442 if ($this->missingAvatarFile($profile)) {
444 if (defined('SCRIPT_DEBUG')) {
445 common_debug('Twitter user ' . $profile->nickname .
446 ' is missing one or more local avatars.');
447 common_debug("old: $oldname new: $newname");
450 $this->updateAvatars($twitter_user, $profile);
455 function updateAvatars($twitter_user, $profile) {
459 $path_parts = pathinfo($twitter_user->profile_image_url);
461 $img_root = substr($path_parts['basename'], 0, -11);
462 $ext = $path_parts['extension'];
463 $mediatype = $this->getMediatype($ext);
465 foreach (array('mini', 'normal', 'bigger') as $size) {
466 $url = $path_parts['dirname'] . '/' .
467 $img_root . '_' . $size . ".$ext";
468 $filename = 'Twitter_' . $twitter_user->id . '_' .
469 $img_root . "_$size.$ext";
471 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
472 $this->fetchAvatar($url, $filename);
476 function missingAvatarFile($profile) {
478 foreach (array(24, 48, 73) as $size) {
480 $filename = $profile->getAvatar($size)->filename;
481 $avatarpath = Avatar::path($filename);
483 if (file_exists($avatarpath) == FALSE) {
491 function getMediatype($ext)
495 switch (strtolower($ext)) {
497 $mediatype = 'image/jpg';
500 $mediatype = 'image/gif';
503 $mediatype = 'image/png';
509 function saveAvatars($user, $id)
513 $path_parts = pathinfo($user->profile_image_url);
514 $ext = $path_parts['extension'];
515 $end = strlen('_normal' . $ext);
516 $img_root = substr($path_parts['basename'], 0, -($end+1));
517 $mediatype = $this->getMediatype($ext);
519 foreach (array('mini', 'normal', 'bigger') as $size) {
520 $url = $path_parts['dirname'] . '/' .
521 $img_root . '_' . $size . ".$ext";
522 $filename = 'Twitter_' . $user->id . '_' .
523 $img_root . "_$size.$ext";
525 if ($this->fetchAvatar($url, $filename)) {
526 $this->newAvatar($id, $size, $mediatype, $filename);
528 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
533 function updateAvatar($profile_id, $size, $mediatype, $filename) {
535 if (defined('SCRIPT_DEBUG')) {
536 common_debug("Updating avatar: $size");
539 $profile = Profile::staticGet($profile_id);
541 if (empty($profile)) {
542 if (defined('SCRIPT_DEBUG')) {
543 common_debug("Couldn't get profile: $profile_id!");
548 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
549 $avatar = $profile->getAvatar($sizes[$size]);
551 // Delete the avatar, if present
556 $this->newAvatar($profile->id, $size, $mediatype, $filename);
559 function newAvatar($profile_id, $size, $mediatype, $filename)
563 $avatar = new Avatar();
564 $avatar->profile_id = $profile_id;
569 $avatar->height = 24;
573 $avatar->height = 48;
577 // Note: Twitter's big avatars are a different size than
578 // Laconica's (Laconica's = 96)
581 $avatar->height = 73;
584 $avatar->original = 0; // we don't have the original
585 $avatar->mediatype = $mediatype;
586 $avatar->filename = $filename;
587 $avatar->url = Avatar::url($filename);
589 if (defined('SCRIPT_DEBUG')) {
590 common_debug("new filename: $avatar->url");
593 $avatar->created = common_sql_now();
595 $id = $avatar->insert();
598 common_log_db_error($avatar, 'INSERT', __FILE__);
602 if (defined('SCRIPT_DEBUG')) {
603 common_debug("Saved new $size avatar for $profile_id.");
609 function fetchAvatar($url, $filename)
611 $avatar_dir = INSTALLDIR . '/avatar/';
613 $avatarfile = $avatar_dir . $filename;
615 $out = fopen($avatarfile, 'wb');
617 common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
621 if (defined('SCRIPT_DEBUG')) {
622 common_debug("Fetching avatar: $url");
626 curl_setopt($ch, CURLOPT_URL, $url);
627 curl_setopt($ch, CURLOPT_FILE, $out);
628 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
629 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
630 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
631 $result = curl_exec($ch);
642 if (have_option('i')) {
643 $id = get_option_value('i');
644 } else if (have_option('--id')) {
645 $id = get_option_value('--id');
646 } else if (count($args) > 0) {
652 common_debug("id set to $id");
654 $fetcher = new TwitterStatusFetcher($id);