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 // Preset the server at the command line
40 $server = ($argc > 2) ? $argv[2] : null;
41 $path = ($argc > 3) ? $argv[3] : null;
43 require_once INSTALLDIR . '/lib/common.php';
44 require_once INSTALLDIR . '/lib/daemon.php';
47 * Fetcher for statuses from Twitter
49 * Fetches statuses from Twitter and inserts them as notices in local
54 * @author Zach Copley <zach@controlyourself.ca>
55 * @author Evan Prodromou <evan@controlyourself.ca>
56 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
57 * @link http://laconi.ca/
60 // NOTE: an Avatar path MUST be set in config.php for this
61 // script to work: e.g.: $config['avatar']['path'] = '/laconica/avatar';
63 class TwitterStatusFetcher extends Daemon
65 private $_children = array();
70 * @return string Name of the daemon.
75 return ('twitterstatusfetcher.generic');
88 $flinks = $this->refreshFlinks();
90 foreach ($flinks as $f) {
92 // We have to disconnect from the DB before forking so
93 // each sub-process will open its own connection and
94 // avoid stomping on the others
96 $conn = &$f->getDatabaseConnection();
102 die ("Couldn't fork!");
108 if (defined('SCRIPT_DEBUG')) {
109 common_debug("Parent: forked new status ".
110 " fetcher process " . $pid);
113 $this->_children[] = $pid;
118 $this->getTimeline($f);
122 // Remove child from ps list as it finishes
123 while (($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
125 if (defined('SCRIPT_DEBUG')) {
126 common_debug("Child $c finished.");
129 $this->removePs($this->_children, $c);
132 // Wait! We have too many damn kids.
133 if (sizeof($this->_children) > MAXCHILDREN) {
135 if (defined('SCRIPT_DEBUG')) {
136 common_debug('Too many children. Waiting...');
139 if (($c = pcntl_wait($status, WUNTRACED)) > 0) {
141 if (defined('SCRIPT_DEBUG')) {
142 common_debug("Finished waiting for $c");
145 $this->removePs($this->_children, $c);
150 // Remove all children from the process list before restarting
151 while (($c = pcntl_wait($status, WUNTRACED)) > 0) {
153 if (defined('SCRIPT_DEBUG')) {
154 common_debug("Child $c finished.");
157 $this->removePs($this->_children, $c);
160 // Rest for a bit before we fetch more statuses
162 if (defined('SCRIPT_DEBUG')) {
163 common_debug('Waiting ' . POLL_INTERVAL .
164 ' secs before hitting Twitter again.');
167 if (POLL_INTERVAL > 0) {
168 sleep(POLL_INTERVAL);
175 * Refresh the foreign links for this user
180 function refreshFlinks()
182 $flink = new Foreign_link();
184 $flink->service = 1; // Twitter
186 $flink->orderBy('last_noticesync');
188 $cnt = $flink->find();
190 if (defined('SCRIPT_DEBUG')) {
191 common_debug('Updating Twitter friends subscriptions' .
197 while ($flink->fetch()) {
199 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
200 FOREIGN_NOTICE_RECV) {
201 $flinks[] = clone($flink);
214 * @param array &$plist unknown.
215 * @param string $ps unknown.
221 function removePs(&$plist, $ps)
223 for ($i = 0; $i < sizeof($plist); $i++) {
224 if ($plist[$i] == $ps) {
226 $plist = array_values($plist);
232 function getTimeline($flink)
235 common_log(LOG_WARNING,
236 "Can't retrieve Foreign_link for foreign ID $fid");
240 $fuser = $flink->getForeignUser();
243 common_log(LOG_WARNING, "Unmatched user for ID " .
248 if (defined('SCRIPT_DEBUG')) {
249 common_debug('Trying to get timeline for Twitter user ' .
250 "$fuser->nickname ($flink->foreign_id).");
253 // XXX: Biggest remaining issue - How do we know at which status
254 // to start importing? How many statuses? Right now I'm going
255 // with the default last 20.
257 $url = 'http://twitter.com/statuses/friends_timeline.json';
259 $timeline_json = get_twitter_data($url, $fuser->nickname,
260 $flink->credentials);
262 $timeline = json_decode($timeline_json);
264 if (empty($timeline)) {
265 common_log(LOG_WARNING, "Empty timeline.");
269 // Reverse to preserve order
270 foreach (array_reverse($timeline) as $status) {
272 // Hacktastic: filter out stuff coming from this Laconica
273 $source = mb_strtolower(common_config('integration', 'source'));
275 if (preg_match("/$source/", mb_strtolower($status->source))) {
276 if (defined('SCRIPT_DEBUG')) {
277 common_debug('Skipping import of status ' . $status->id .
278 ' with source ' . $source);
283 $this->saveStatus($status, $flink);
286 // Okay, record the time we synced with Twitter for posterity
287 $flink->last_noticesync = common_sql_now();
291 function saveStatus($status, $flink)
293 $id = $this->ensureProfile($status->user);
294 $profile = Profile::staticGet($id);
298 'Problem saving notice. No associated Profile.');
302 // XXX: change of screen name?
304 $uri = 'http://twitter.com/' . $status->user->screen_name .
305 '/status/' . $status->id;
307 $notice = Notice::staticGet('uri', $uri);
309 // check to see if we've already imported the status
313 $notice = new Notice();
315 $notice->profile_id = $id;
317 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
318 strtotime($status->created_at));
319 $notice->content = common_shorten_links($status->text); // XXX
320 $notice->rendered = common_render_content($notice->content, $notice);
321 $notice->source = 'twitter';
322 $notice->reply_to = null; // XXX lookup reply
323 $notice->is_local = NOTICE_GATEWAY;
325 if (Event::handle('StartNoticeSave', array(&$notice))) {
326 $id = $notice->insert();
327 Event::handle('EndNoticeSave', array($notice));
331 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
332 'user_id' => $flink->user_id))) {
334 $inbox = new Notice_inbox();
336 $inbox->user_id = $flink->user_id;
337 $inbox->notice_id = $notice->id;
338 $inbox->created = $notice->created;
339 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
345 function ensureProfile($user)
347 // check to see if there's already a profile for this user
348 $profileurl = 'http://twitter.com/' . $user->screen_name;
349 $profile = Profile::staticGet('profileurl', $profileurl);
352 if (defined('SCRIPT_DEBUG')) {
353 common_debug("Profile for $profile->nickname found.");
356 // Check to see if the user's Avatar has changed
357 $this->checkAvatar($user, $profile);
362 if (defined('SCRIPT_DEBUG')) {
363 common_debug('Adding profile and remote profile ' .
364 "for Twitter user: $profileurl");
367 $profile = new Profile();
368 $profile->query("BEGIN");
370 $profile->nickname = $user->screen_name;
371 $profile->fullname = $user->name;
372 $profile->homepage = $user->url;
373 $profile->bio = $user->description;
374 $profile->location = $user->location;
375 $profile->profileurl = $profileurl;
376 $profile->created = common_sql_now();
378 $id = $profile->insert();
381 common_log_db_error($profile, 'INSERT', __FILE__);
382 $profile->query("ROLLBACK");
386 // check for remote profile
387 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
391 $remote_pro = new Remote_profile();
393 $remote_pro->id = $id;
394 $remote_pro->uri = $profileurl;
395 $remote_pro->created = common_sql_now();
397 $rid = $remote_pro->insert();
400 common_log_db_error($profile, 'INSERT', __FILE__);
401 $profile->query("ROLLBACK");
406 $profile->query("COMMIT");
408 $this->saveAvatars($user, $id);
414 function checkAvatar($twitter_user, $profile)
418 $path_parts = pathinfo($twitter_user->profile_image_url);
420 $newname = 'Twitter_' . $twitter_user->id . '_' .
421 $path_parts['basename'];
423 $oldname = $profile->getAvatar(48)->filename;
425 if ($newname != $oldname) {
427 if (defined('SCRIPT_DEBUG')) {
428 common_debug('Avatar for Twitter user ' .
429 "$profile->nickname has changed.");
430 common_debug("old: $oldname new: $newname");
433 $this->updateAvatars($twitter_user, $profile);
436 if ($this->missingAvatarFile($profile)) {
438 if (defined('SCRIPT_DEBUG')) {
439 common_debug('Twitter user ' . $profile->nickname .
440 ' is missing one or more local avatars.');
441 common_debug("old: $oldname new: $newname");
444 $this->updateAvatars($twitter_user, $profile);
449 function updateAvatars($twitter_user, $profile) {
453 $path_parts = pathinfo($twitter_user->profile_image_url);
455 $img_root = substr($path_parts['basename'], 0, -11);
456 $ext = $path_parts['extension'];
457 $mediatype = $this->getMediatype($ext);
459 foreach (array('mini', 'normal', 'bigger') as $size) {
460 $url = $path_parts['dirname'] . '/' .
461 $img_root . '_' . $size . ".$ext";
462 $filename = 'Twitter_' . $twitter_user->id . '_' .
463 $img_root . "_$size.$ext";
465 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
466 $this->fetchAvatar($url, $filename);
470 function missingAvatarFile($profile) {
472 foreach (array(24, 48, 73) as $size) {
474 $filename = $profile->getAvatar($size)->filename;
475 $avatarpath = Avatar::path($filename);
477 if (file_exists($avatarpath) == FALSE) {
485 function getMediatype($ext)
489 switch (strtolower($ext)) {
491 $mediatype = 'image/jpg';
494 $mediatype = 'image/gif';
497 $mediatype = 'image/png';
503 function saveAvatars($user, $id)
507 $path_parts = pathinfo($user->profile_image_url);
508 $ext = $path_parts['extension'];
509 $end = strlen('_normal' . $ext);
510 $img_root = substr($path_parts['basename'], 0, -($end+1));
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_' . $user->id . '_' .
517 $img_root . "_$size.$ext";
519 if ($this->fetchAvatar($url, $filename)) {
520 $this->newAvatar($id, $size, $mediatype, $filename);
522 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
527 function updateAvatar($profile_id, $size, $mediatype, $filename) {
529 if (defined('SCRIPT_DEBUG')) {
530 common_debug("Updating avatar: $size");
533 $profile = Profile::staticGet($profile_id);
535 if (empty($profile)) {
536 if (defined('SCRIPT_DEBUG')) {
537 common_debug("Couldn't get profile: $profile_id!");
542 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
543 $avatar = $profile->getAvatar($sizes[$size]);
545 // Delete the avatar, if present
550 $this->newAvatar($profile->id, $size, $mediatype, $filename);
553 function newAvatar($profile_id, $size, $mediatype, $filename)
557 $avatar = new Avatar();
558 $avatar->profile_id = $profile_id;
563 $avatar->height = 24;
567 $avatar->height = 48;
571 // Note: Twitter's big avatars are a different size than
572 // Laconica's (Laconica's = 96)
575 $avatar->height = 73;
578 $avatar->original = 0; // we don't have the original
579 $avatar->mediatype = $mediatype;
580 $avatar->filename = $filename;
581 $avatar->url = Avatar::url($filename);
583 if (defined('SCRIPT_DEBUG')) {
584 common_debug("new filename: $avatar->url");
587 $avatar->created = common_sql_now();
589 $id = $avatar->insert();
592 common_log_db_error($avatar, 'INSERT', __FILE__);
596 if (defined('SCRIPT_DEBUG')) {
597 common_debug("Saved new $size avatar for $profile_id.");
603 function fetchAvatar($url, $filename)
605 $avatar_dir = INSTALLDIR . '/avatar/';
607 $avatarfile = $avatar_dir . $filename;
609 $out = fopen($avatarfile, 'wb');
611 common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
615 if (defined('SCRIPT_DEBUG')) {
616 common_debug("Fetching avatar: $url");
620 curl_setopt($ch, CURLOPT_URL, $url);
621 curl_setopt($ch, CURLOPT_FILE, $out);
622 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
623 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
624 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
625 $result = curl_exec($ch);
634 ini_set("max_execution_time", "0");
635 ini_set("max_input_time", "0");
637 mb_internal_encoding('UTF-8');
640 $fetcher = new TwitterStatusFetcher();