4 * Laconica - a distributed open-source microblogging tool
5 * Copyright (C) 2008, Controlez-Vous, 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 // Abort if called from a web server
22 if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
23 print "This script must be run from the command line\n";
27 define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
28 define('LACONICA', true);
30 // Tune number of processes and how often to poll Twitter
31 // XXX: Should these things be in config.php?
32 define('MAXCHILDREN', 2);
33 define('POLL_INTERVAL', 60); // in seconds
35 // Uncomment this to get useful logging
36 define('SCRIPT_DEBUG', true);
38 require_once INSTALLDIR . '/lib/common.php';
39 require_once INSTALLDIR . '/lib/daemon.php';
42 * Fetcher for statuses from Twitter
44 * Fetches statuses from Twitter and inserts them as notices in local
49 * @author Zach Copley <zach@controlyourself.ca>
50 * @author Evan Prodromou <evan@controlyourself.ca>
51 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
52 * @link http://laconi.ca/
55 // NOTE: an Avatar path MUST be set in config.php for this
56 // script to work: e.g.: $config['avatar']['path'] = '/laconica/avatar';
58 class TwitterStatusFetcher extends Daemon
60 private $_children = array();
65 * @return string Name of the daemon.
70 return ('twitterstatusfetcher.generic');
83 $flinks = $this->refreshFlinks();
85 foreach ($flinks as $f) {
87 // We have to disconnect from the DB before forking so
88 // each sub-process will open its own connection and
89 // avoid stomping on the others
91 $conn = &$f->getDatabaseConnection();
97 die ("Couldn't fork!");
103 if (defined('SCRIPT_DEBUG')) {
104 common_debug("Parent: forked new status ".
105 " fetcher process " . $pid);
108 $this->_children[] = $pid;
113 $this->getTimeline($f);
117 // Remove child from ps list as it finishes
118 while (($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
120 if (defined('SCRIPT_DEBUG')) {
121 common_debug("Child $c finished.");
124 $this->removePs($this->_children, $c);
127 // Wait! We have too many damn kids.
128 if (sizeof($this->_children) > MAXCHILDREN) {
130 if (defined('SCRIPT_DEBUG')) {
131 common_debug('Too many children. Waiting...');
134 if (($c = pcntl_wait($status, WUNTRACED)) > 0) {
136 if (defined('SCRIPT_DEBUG')) {
137 common_debug("Finished waiting for $c");
140 $this->removePs($this->_children, $c);
145 // Remove all children from the process list before restarting
146 while (($c = pcntl_wait($status, WUNTRACED)) > 0) {
148 if (defined('SCRIPT_DEBUG')) {
149 common_debug("Child $c finished.");
152 $this->removePs($this->_children, $c);
155 // Rest for a bit before we fetch more statuses
157 if (defined('SCRIPT_DEBUG')) {
158 common_debug('Waiting ' . POLL_INTERVAL .
159 ' secs before hitting Twitter again.');
162 if (POLL_INTERVAL > 0) {
163 sleep(POLL_INTERVAL);
170 * Refresh the foreign links for this user
175 function refreshFlinks()
177 $flink = new Foreign_link();
179 $flink->service = 1; // Twitter
181 $flink->orderBy('last_noticesync');
183 $cnt = $flink->find();
185 if (defined('SCRIPT_DEBUG')) {
186 common_debug('Updating Twitter friends subscriptions' .
192 while ($flink->fetch()) {
194 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
195 FOREIGN_NOTICE_RECV) {
196 $flinks[] = clone($flink);
209 * @param array &$plist unknown.
210 * @param string $ps unknown.
216 function removePs(&$plist, $ps)
218 for ($i = 0; $i < sizeof($plist); $i++) {
219 if ($plist[$i] == $ps) {
221 $plist = array_values($plist);
227 function getTimeline($flink)
230 common_log(LOG_WARNING,
231 "Can't retrieve Foreign_link for foreign ID $fid");
235 $fuser = $flink->getForeignUser();
238 common_log(LOG_WARNING, "Unmatched user for ID " .
243 if (defined('SCRIPT_DEBUG')) {
244 common_debug('Trying to get timeline for Twitter user ' .
245 "$fuser->nickname ($flink->foreign_id).");
248 // XXX: Biggest remaining issue - How do we know at which status
249 // to start importing? How many statuses? Right now I'm going
250 // with the default last 20.
252 $url = 'http://twitter.com/statuses/friends_timeline.json';
254 $timeline_json = get_twitter_data($url, $fuser->nickname,
255 $flink->credentials);
257 $timeline = json_decode($timeline_json);
259 if (empty($timeline)) {
260 common_log(LOG_WARNING, "Empty timeline.");
264 // Reverse to preserve order
265 foreach (array_reverse($timeline) as $status) {
267 // Hacktastic: filter out stuff coming from this Laconica
268 $source = mb_strtolower(common_config('integration', 'source'));
270 if (preg_match("/$source/", mb_strtolower($status->source))) {
271 if (defined('SCRIPT_DEBUG')) {
272 common_debug('Skipping import of status ' . $status->id .
273 ' with source ' . $source);
278 $this->saveStatus($status, $flink);
281 // Okay, record the time we synced with Twitter for posterity
282 $flink->last_noticesync = common_sql_now();
286 function saveStatus($status, $flink)
288 $id = $this->ensureProfile($status->user);
289 $profile = Profile::staticGet($id);
293 'Problem saving notice. No associated Profile.');
297 // XXX: change of screen name?
299 $uri = 'http://twitter.com/' . $status->user->screen_name .
300 '/status/' . $status->id;
302 $notice = Notice::staticGet('uri', $uri);
304 // check to see if we've already imported the status
308 $notice = new Notice();
310 $notice->profile_id = $id;
312 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
313 strtotime($status->created_at));
314 $notice->content = common_shorten_links($status->text); // XXX
315 $notice->rendered = common_render_content($notice->content, $notice);
316 $notice->source = 'twitter';
317 $notice->reply_to = null; // XXX lookup reply
318 $notice->is_local = NOTICE_GATEWAY;
320 if (Event::handle('StartNoticeSave', array(&$notice))) {
321 $id = $notice->insert();
322 Event::handle('EndNoticeSave', array($notice));
326 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
327 'user_id' => $flink->user_id))) {
329 $inbox = new Notice_inbox();
331 $inbox->user_id = $flink->user_id;
332 $inbox->notice_id = $notice->id;
333 $inbox->created = $notice->created;
334 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
340 function ensureProfile($user)
342 // check to see if there's already a profile for this user
343 $profileurl = 'http://twitter.com/' . $user->screen_name;
344 $profile = Profile::staticGet('profileurl', $profileurl);
347 if (defined('SCRIPT_DEBUG')) {
348 common_debug("Profile for $profile->nickname found.");
351 // Check to see if the user's Avatar has changed
352 $this->checkAvatar($user, $profile);
357 if (defined('SCRIPT_DEBUG')) {
358 common_debug('Adding profile and remote profile ' .
359 "for Twitter user: $profileurl");
362 $profile = new Profile();
363 $profile->query("BEGIN");
365 $profile->nickname = $user->screen_name;
366 $profile->fullname = $user->name;
367 $profile->homepage = $user->url;
368 $profile->bio = $user->description;
369 $profile->location = $user->location;
370 $profile->profileurl = $profileurl;
371 $profile->created = common_sql_now();
373 $id = $profile->insert();
376 common_log_db_error($profile, 'INSERT', __FILE__);
377 $profile->query("ROLLBACK");
381 // check for remote profile
382 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
386 $remote_pro = new Remote_profile();
388 $remote_pro->id = $id;
389 $remote_pro->uri = $profileurl;
390 $remote_pro->created = common_sql_now();
392 $rid = $remote_pro->insert();
395 common_log_db_error($profile, 'INSERT', __FILE__);
396 $profile->query("ROLLBACK");
401 $profile->query("COMMIT");
403 $this->saveAvatars($user, $id);
409 function checkAvatar($twitter_user, $profile)
413 $path_parts = pathinfo($twitter_user->profile_image_url);
415 $newname = 'Twitter_' . $twitter_user->id . '_' .
416 $path_parts['basename'];
418 $oldname = $profile->getAvatar(48)->filename;
420 if ($newname != $oldname) {
422 if (defined('SCRIPT_DEBUG')) {
423 common_debug('Avatar for Twitter user ' .
424 "$profile->nickname has changed.");
425 common_debug("old: $oldname new: $newname");
428 $this->updateAvatars($twitter_user, $profile);
431 if ($this->missingAvatarFile($profile)) {
433 if (defined('SCRIPT_DEBUG')) {
434 common_debug('Twitter user ' . $profile->nickname .
435 ' is missing one or more local avatars.');
436 common_debug("old: $oldname new: $newname");
439 $this->updateAvatars($twitter_user, $profile);
444 function updateAvatars($twitter_user, $profile) {
448 $path_parts = pathinfo($twitter_user->profile_image_url);
450 $img_root = substr($path_parts['basename'], 0, -11);
451 $ext = $path_parts['extension'];
452 $mediatype = $this->getMediatype($ext);
454 foreach (array('mini', 'normal', 'bigger') as $size) {
455 $url = $path_parts['dirname'] . '/' .
456 $img_root . '_' . $size . ".$ext";
457 $filename = 'Twitter_' . $twitter_user->id . '_' .
458 $img_root . "_$size.$ext";
460 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
461 $this->fetchAvatar($url, $filename);
465 function missingAvatarFile($profile) {
467 foreach (array(24, 48, 73) as $size) {
469 $filename = $profile->getAvatar($size)->filename;
470 $avatarpath = Avatar::path($filename);
472 if (file_exists($avatarpath) == FALSE) {
480 function getMediatype($ext)
484 switch (strtolower($ext)) {
486 $mediatype = 'image/jpg';
489 $mediatype = 'image/gif';
492 $mediatype = 'image/png';
498 function saveAvatars($user, $id)
502 $path_parts = pathinfo($user->profile_image_url);
503 $ext = $path_parts['extension'];
504 $end = strlen('_normal' . $ext);
505 $img_root = substr($path_parts['basename'], 0, -($end+1));
506 $mediatype = $this->getMediatype($ext);
508 foreach (array('mini', 'normal', 'bigger') as $size) {
509 $url = $path_parts['dirname'] . '/' .
510 $img_root . '_' . $size . ".$ext";
511 $filename = 'Twitter_' . $user->id . '_' .
512 $img_root . "_$size.$ext";
514 if ($this->fetchAvatar($url, $filename)) {
515 $this->newAvatar($id, $size, $mediatype, $filename);
517 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
522 function updateAvatar($profile_id, $size, $mediatype, $filename) {
524 if (defined('SCRIPT_DEBUG')) {
525 common_debug("Updating avatar: $size");
528 $profile = Profile::staticGet($profile_id);
530 if (empty($profile)) {
531 if (defined('SCRIPT_DEBUG')) {
532 common_debug("Couldn't get profile: $profile_id!");
537 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
538 $avatar = $profile->getAvatar($sizes[$size]);
540 // Delete the avatar, if present
545 $this->newAvatar($profile->id, $size, $mediatype, $filename);
548 function newAvatar($profile_id, $size, $mediatype, $filename)
552 $avatar = new Avatar();
553 $avatar->profile_id = $profile_id;
558 $avatar->height = 24;
562 $avatar->height = 48;
566 // Note: Twitter's big avatars are a different size than
567 // Laconica's (Laconica's = 96)
570 $avatar->height = 73;
573 $avatar->original = 0; // we don't have the original
574 $avatar->mediatype = $mediatype;
575 $avatar->filename = $filename;
576 $avatar->url = Avatar::url($filename);
578 if (defined('SCRIPT_DEBUG')) {
579 common_debug("new filename: $avatar->url");
582 $avatar->created = common_sql_now();
584 $id = $avatar->insert();
587 common_log_db_error($avatar, 'INSERT', __FILE__);
591 if (defined('SCRIPT_DEBUG')) {
592 common_debug("Saved new $size avatar for $profile_id.");
598 function fetchAvatar($url, $filename)
600 $avatar_dir = INSTALLDIR . '/avatar/';
602 $avatarfile = $avatar_dir . $filename;
604 $out = fopen($avatarfile, 'wb');
606 common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
610 if (defined('SCRIPT_DEBUG')) {
611 common_debug("Fetching avatar: $url");
615 curl_setopt($ch, CURLOPT_URL, $url);
616 curl_setopt($ch, CURLOPT_FILE, $out);
617 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
618 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
619 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
620 $result = curl_exec($ch);
629 ini_set("max_execution_time", "0");
630 ini_set("max_input_time", "0");
632 mb_internal_encoding('UTF-8');
635 $fetcher = new TwitterStatusFetcher();