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');
41 // NOTE: an Avatar path MUST be set in config.php for this
42 // script to work: e.g.: $config['avatar']['path'] = '/laconica/avatar';
44 class TwitterStatusFetcher extends Daemon
47 private $children = array();
51 return ('twitterstatusfetcher.generic');
58 $flinks = $this->refreshFlinks();
60 foreach ($flinks as $f){
62 // We have to disconnect from the DB before forking so
63 // each sub-process will open its own connection and
64 // avoid stomping on the others
66 $conn = &$f->getDatabaseConnection();
72 die ("Couldn't fork!");
78 if (defined('SCRIPT_DEBUG')) {
79 common_debug("Parent: forked new status fetcher process " . $pid);
82 $this->children[] = $pid;
87 $this->getTimeline($f);
91 // Remove child from ps list as it finishes
92 while(($c = pcntl_wait($status, WNOHANG OR WUNTRACED)) > 0) {
94 if (defined('SCRIPT_DEBUG')) {
95 common_debug("Child $c finished.");
98 $this->remove_ps($this->children, $c);
101 // Wait! We have too many damn kids.
102 if (sizeof($this->children) > MAXCHILDREN) {
104 if (defined('SCRIPT_DEBUG')) {
105 common_debug('Too many children. Waiting...');
108 if (($c = pcntl_wait($status, WUNTRACED)) > 0){
110 if (defined('SCRIPT_DEBUG')) {
111 common_debug("Finished waiting for $c");
114 $this->remove_ps($this->children, $c);
119 // Remove all children from the process list before restarting
120 while(($c = pcntl_wait($status, WUNTRACED)) > 0) {
122 if (defined('SCRIPT_DEBUG')) {
123 common_debug("Child $c finished.");
126 $this->remove_ps($this->children, $c);
129 // Rest for a bit before we fetch more statuses
131 if (defined('SCRIPT_DEBUG')) {
132 common_debug('Waiting ' . POLL_INTERVAL .
133 ' secs before hitting Twitter again.');
136 if (POLL_INTERVAL > 0) {
137 sleep(POLL_INTERVAL);
143 function refreshFlinks() {
145 $flink = new Foreign_link();
146 $flink->service = 1; // Twitter
147 $flink->orderBy('last_noticesync');
149 $cnt = $flink->find();
151 if (defined('SCRIPT_DEBUG')) {
152 common_debug('Updating Twitter friends subscriptions' .
158 while ($flink->fetch()) {
160 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
161 FOREIGN_NOTICE_RECV) {
162 $flinks[] = clone($flink);
172 function remove_ps(&$plist, $ps){
173 for ($i = 0; $i < sizeof($plist); $i++) {
174 if ($plist[$i] == $ps) {
176 $plist = array_values($plist);
182 function getTimeline($flink)
186 common_log(LOG_WARNING,
187 "Can't retrieve Foreign_link for foreign ID $fid");
191 $fuser = $flink->getForeignUser();
194 common_log(LOG_WARNING, "Unmatched user for ID " .
199 if (defined('SCRIPT_DEBUG')) {
200 common_debug('Trying to get timeline for Twitter user ' .
201 "$fuser->nickname ($flink->foreign_id).");
204 // XXX: Biggest remaining issue - How do we know at which status
205 // to start importing? How many statuses? Right now I'm going
206 // with the default last 20.
208 $url = 'http://twitter.com/statuses/friends_timeline.json';
210 $timeline_json = get_twitter_data($url, $fuser->nickname,
211 $flink->credentials);
213 $timeline = json_decode($timeline_json);
215 if (empty($timeline)) {
216 common_log(LOG_WARNING, "Empty timeline.");
220 // Reverse to preserve order
221 foreach (array_reverse($timeline) as $status) {
223 // Hacktastic: filter out stuff coming from this Laconica
224 $source = mb_strtolower(common_config('integration', 'source'));
226 if (preg_match("/$source/", mb_strtolower($status->source))) {
227 if (defined('SCRIPT_DEBUG')) {
228 common_debug('Skipping import of status ' . $status->id .
229 ' with source ' . $source);
234 $this->saveStatus($status, $flink);
237 // Okay, record the time we synced with Twitter for posterity
238 $flink->last_noticesync = common_sql_now();
242 function saveStatus($status, $flink)
244 $id = $this->ensureProfile($status->user);
245 $profile = Profile::staticGet($id);
249 'Problem saving notice. No associated Profile.');
253 $uri = 'http://twitter.com/' . $status->user->screen_name .
254 '/status/' . $status->id;
256 $notice = Notice::staticGet('uri', $uri);
258 // check to see if we've already imported the status
261 $created = strftime('%Y-%m-%d %H:%M:%S',
262 strtotime($status->created_at));;
264 $notice = Notice::saveNew($id, $status->text, 'twitter',
265 -2, null, $uri, $created);
267 if (defined('SCRIPT_DEBUG')) {
268 common_debug("Saved status $status->id" .
269 " as notice $notice->id.");
273 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
274 'user_id' => $flink->user_id))) {
276 $inbox = new Notice_inbox();
277 $inbox->user_id = $flink->user_id;
278 $inbox->notice_id = $notice->id;
279 $inbox->created = $notice->created;
285 function ensureProfile($user)
287 // check to see if there's already a profile for this user
288 $profileurl = 'http://twitter.com/' . $user->screen_name;
289 $profile = Profile::staticGet('profileurl', $profileurl);
292 if (defined('SCRIPT_DEBUG')) {
293 common_debug("Profile for $profile->nickname found.");
296 // Check to see if the user's Avatar has changed
297 $this->checkAvatar($user, $profile);
302 if (defined('SCRIPT_DEBUG')) {
303 common_debug('Adding profile and remote profile ' .
304 "for Twitter user: $profileurl");
307 $profile = new Profile();
308 $profile->query("BEGIN");
310 $profile->nickname = $user->screen_name;
311 $profile->fullname = $user->name;
312 $profile->homepage = $user->url;
313 $profile->bio = $user->description;
314 $profile->location = $user->location;
315 $profile->profileurl = $profileurl;
316 $profile->created = common_sql_now();
318 $id = $profile->insert();
321 common_log_db_error($profile, 'INSERT', __FILE__);
322 $profile->query("ROLLBACK");
326 // check for remote profile
327 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
331 $remote_pro = new Remote_profile();
333 $remote_pro->id = $id;
334 $remote_pro->uri = $profileurl;
335 $remote_pro->created = common_sql_now();
337 $rid = $remote_pro->insert();
340 common_log_db_error($profile, 'INSERT', __FILE__);
341 $profile->query("ROLLBACK");
346 $profile->query("COMMIT");
348 $this->saveAvatars($user, $id);
354 function checkAvatar($user, $profile)
358 $path_parts = pathinfo($user->profile_image_url);
359 $newname = 'Twitter_' . $user->id . '_' .
360 $path_parts['basename'];
362 $oldname = $profile->getAvatar(48)->filename;
364 if ($newname != $oldname || $this->missingAvatarFile($profile)) {
366 if (defined('SCRIPT_DEBUG')) {
367 common_debug('Avatar for Twitter user ' .
368 "$profile->nickname has changed, or was missing locally.");
369 common_debug("old: $oldname new: $newname");
372 $img_root = substr($path_parts['basename'], 0, -11);
373 $ext = $path_parts['extension'];
374 $mediatype = $this->getMediatype($ext);
376 foreach (array('mini', 'normal', 'bigger') as $size) {
377 $url = $path_parts['dirname'] . '/' .
378 $img_root . '_' . $size . ".$ext";
379 $filename = 'Twitter_' . $user->id . '_' .
380 $img_root . "_$size.$ext";
382 if ($this->fetchAvatar($url, $filename)) {
383 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
389 function missingAvatarFile($profile) {
391 foreach (array(24, 48, 73) as $size) {
393 $filename = $profile->getAvatar($size)->filename;
394 $avatarpath = Avatar::path($filename);
396 if (file_exists($avatarpath) == FALSE) {
404 function getMediatype($ext)
408 switch (strtolower($ext)) {
410 $mediatype = 'image/jpg';
413 $mediatype = 'image/gif';
416 $mediatype = 'image/png';
422 function saveAvatars($user, $id)
426 $path_parts = pathinfo($user->profile_image_url);
427 $ext = $path_parts['extension'];
428 $end = strlen('_normal' . $ext);
429 $img_root = substr($path_parts['basename'], 0, -($end+1));
430 $mediatype = $this->getMediatype($ext);
432 foreach (array('mini', 'normal', 'bigger') as $size) {
433 $url = $path_parts['dirname'] . '/' .
434 $img_root . '_' . $size . ".$ext";
435 $filename = 'Twitter_' . $user->id . '_' .
436 $img_root . "_$size.$ext";
438 if ($this->fetchAvatar($url, $filename)) {
439 $this->newAvatar($id, $size, $mediatype, $filename);
441 common_log(LOG_WARNING, "Problem fetching Avatar: $url", __FILE__);
446 function updateAvatar($profile_id, $size, $mediatype, $filename) {
448 if (defined('SCRIPT_DEBUG')) {
449 common_debug("Updating avatar: $size");
452 $profile = Profile::staticGet($profile_id);
455 if (defined('SCRIPT_DEBUG')) {
456 common_debug("Couldn't get profile: $profile_id!");
461 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
462 $avatar = $profile->getAvatar($sizes[$size]);
465 if (defined('SCRIPT_DEBUG')) {
466 common_debug("Deleting $size avatar for $profile->nickname.");
471 $this->newAvatar($profile->id, $size, $mediatype, $filename);
474 function newAvatar($profile_id, $size, $mediatype, $filename)
478 $avatar = new Avatar();
479 $avatar->profile_id = $profile_id;
484 $avatar->height = 24;
488 $avatar->height = 48;
492 // Note: Twitter's big avatars are a different size than
493 // Laconica's (Laconica's = 96)
496 $avatar->height = 73;
499 $avatar->original = 0; // we don't have the original
500 $avatar->mediatype = $mediatype;
501 $avatar->filename = $filename;
502 $avatar->url = Avatar::url($filename);
504 if (defined('SCRIPT_DEBUG')) {
505 common_debug("new filename: $avatar->url");
508 $avatar->created = common_sql_now();
510 $id = $avatar->insert();
513 common_log_db_error($avatar, 'INSERT', __FILE__);
517 if (defined('SCRIPT_DEBUG')) {
518 common_debug("Saved new $size avatar for $profile_id.");
524 function fetchAvatar($url, $filename)
526 $avatar_dir = INSTALLDIR . '/avatar/';
528 $avatarfile = $avatar_dir . $filename;
530 $out = fopen($avatarfile, 'wb');
532 common_log(LOG_WARNING, "Couldn't open file $filename", __FILE__);
536 if (defined('SCRIPT_DEBUG')) {
537 common_debug("Fetching avatar: $url");
541 curl_setopt($ch, CURLOPT_URL, $url);
542 curl_setopt($ch, CURLOPT_FILE, $out);
543 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
544 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
545 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
546 $result = curl_exec($ch);
555 ini_set("max_execution_time", "0");
556 ini_set("max_input_time", "0");
558 mb_internal_encoding('UTF-8');
561 $fetcher = new TwitterStatusFetcher();