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 = 'di::';
29 $longoptions = array('id::', 'debug');
31 $helptext = <<<END_OF_TRIM_HELP
32 Batch script for retrieving Twitter messages from foreign service.
34 -i --id Identity (default 'generic')
35 -d --debug Debug (lots of log output)
39 require_once INSTALLDIR . '/scripts/commandline.inc';
40 require_once INSTALLDIR . '/lib/daemon.php';
41 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.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 ParallelizingDaemon
65 * @param string $id the name/id of this daemon
66 * @param int $interval sleep this long before doing everything again
67 * @param int $max_children maximum number of child processes at a time
68 * @param boolean $debug debug output flag
73 function __construct($id = null, $interval = 60,
74 $max_children = 2, $debug = null)
76 parent::__construct($id, $interval, $max_children, $debug);
82 * @return string Name of the daemon.
87 return ('twitterstatusfetcher.'.$this->_id);
91 * Find all the Twitter foreign links for users who have requested
92 * importing of their friends' timelines
94 * @return array flinks an array of Foreign_link objects
99 global $_DB_DATAOBJECT;
101 $flink = new Foreign_link();
102 $conn = &$flink->getDatabaseConnection();
104 $flink->service = TWITTER_SERVICE;
105 $flink->orderBy('last_noticesync');
110 while ($flink->fetch()) {
112 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
113 FOREIGN_NOTICE_RECV) {
114 $flinks[] = clone($flink);
122 unset($_DB_DATAOBJECT['CONNECTIONS']);
127 function childTask($flink) {
129 // Each child ps needs its own DB connection
131 // Note: DataObject::getDatabaseConnection() creates
132 // a new connection if there isn't one already
134 $conn = &$flink->getDatabaseConnection();
136 $this->getTimeline($flink);
138 $flink->last_friendsync = common_sql_now();
143 // XXX: Couldn't find a less brutal way to blow
144 // away a cached connection
146 global $_DB_DATAOBJECT;
147 unset($_DB_DATAOBJECT['CONNECTIONS']);
150 function getTimeline($flink)
153 common_log(LOG_WARNING, $this->name() .
154 " - Can't retrieve Foreign_link for foreign ID $fid");
158 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
161 // XXX: Biggest remaining issue - How do we know at which status
162 // to start importing? How many statuses? Right now I'm going
163 // with the default last 20.
165 $token = TwitterOAuthClient::unpackToken($flink->credentials);
167 $client = new TwitterOAuthClient($token->key, $token->secret);
172 $timeline = $client->statusesFriendsTimeline();
173 } catch (OAuthClientCurlException $e) {
174 common_log(LOG_WARNING, $this->name() .
175 ' - OAuth client unable to get friends timeline for user ' .
176 $flink->user_id . ' - code: ' .
177 $e->getCode() . 'msg: ' . $e->getMessage());
180 if (empty($timeline)) {
181 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
185 // Reverse to preserve order
187 foreach (array_reverse($timeline) as $status) {
189 // Hacktastic: filter out stuff coming from this Laconica
191 $source = mb_strtolower(common_config('integration', 'source'));
193 if (preg_match("/$source/", mb_strtolower($status->source))) {
194 common_debug($this->name() . ' - Skipping import of status ' .
195 $status->id . ' with source ' . $source);
199 $this->saveStatus($status, $flink);
202 // Okay, record the time we synced with Twitter for posterity
204 $flink->last_noticesync = common_sql_now();
208 function saveStatus($status, $flink)
210 $id = $this->ensureProfile($status->user);
212 $profile = Profile::staticGet($id);
214 if (empty($profile)) {
215 common_log(LOG_ERR, $this->name() .
216 ' - Problem saving notice. No associated Profile.');
220 // XXX: change of screen name?
222 $uri = 'http://twitter.com/' . $status->user->screen_name .
223 '/status/' . $status->id;
225 $notice = Notice::staticGet('uri', $uri);
227 // check to see if we've already imported the status
229 if (empty($notice)) {
231 $notice = new Notice();
233 $notice->profile_id = $id;
235 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
236 strtotime($status->created_at));
237 $notice->content = common_shorten_links($status->text); // XXX
238 $notice->rendered = common_render_content($notice->content, $notice);
239 $notice->source = 'twitter';
240 $notice->reply_to = null; // XXX: lookup reply
241 $notice->is_local = Notice::GATEWAY;
243 if (Event::handle('StartNoticeSave', array(&$notice))) {
244 $id = $notice->insert();
245 Event::handle('EndNoticeSave', array($notice));
249 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
250 'user_id' => $flink->user_id))) {
252 $inbox = new Notice_inbox();
254 $inbox->user_id = $flink->user_id;
255 $inbox->notice_id = $notice->id;
256 $inbox->created = $notice->created;
257 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
263 function ensureProfile($user)
265 // check to see if there's already a profile for this user
267 $profileurl = 'http://twitter.com/' . $user->screen_name;
268 $profile = Profile::staticGet('profileurl', $profileurl);
270 if (!empty($profile)) {
271 common_debug($this->name() .
272 " - Profile for $profile->nickname found.");
274 // Check to see if the user's Avatar has changed
276 $this->checkAvatar($user, $profile);
280 common_debug($this->name() . ' - Adding profile and remote profile ' .
281 "for Twitter user: $profileurl.");
283 $profile = new Profile();
284 $profile->query("BEGIN");
286 $profile->nickname = $user->screen_name;
287 $profile->fullname = $user->name;
288 $profile->homepage = $user->url;
289 $profile->bio = $user->description;
290 $profile->location = $user->location;
291 $profile->profileurl = $profileurl;
292 $profile->created = common_sql_now();
294 $id = $profile->insert();
297 common_log_db_error($profile, 'INSERT', __FILE__);
298 $profile->query("ROLLBACK");
302 // check for remote profile
304 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
306 if (empty($remote_pro)) {
308 $remote_pro = new Remote_profile();
310 $remote_pro->id = $id;
311 $remote_pro->uri = $profileurl;
312 $remote_pro->created = common_sql_now();
314 $rid = $remote_pro->insert();
317 common_log_db_error($profile, 'INSERT', __FILE__);
318 $profile->query("ROLLBACK");
323 $profile->query("COMMIT");
325 $this->saveAvatars($user, $id);
331 function checkAvatar($twitter_user, $profile)
335 $path_parts = pathinfo($twitter_user->profile_image_url);
337 $newname = 'Twitter_' . $twitter_user->id . '_' .
338 $path_parts['basename'];
340 $oldname = $profile->getAvatar(48)->filename;
342 if ($newname != $oldname) {
343 common_debug($this->name() . ' - Avatar for Twitter user ' .
344 "$profile->nickname has changed.");
345 common_debug($this->name() . " - old: $oldname new: $newname");
347 $this->updateAvatars($twitter_user, $profile);
350 if ($this->missingAvatarFile($profile)) {
351 common_debug($this->name() . ' - Twitter user ' .
353 ' is missing one or more local avatars.');
354 common_debug($this->name() ." - old: $oldname new: $newname");
356 $this->updateAvatars($twitter_user, $profile);
361 function updateAvatars($twitter_user, $profile) {
365 $path_parts = pathinfo($twitter_user->profile_image_url);
367 $img_root = substr($path_parts['basename'], 0, -11);
368 $ext = $path_parts['extension'];
369 $mediatype = $this->getMediatype($ext);
371 foreach (array('mini', 'normal', 'bigger') as $size) {
372 $url = $path_parts['dirname'] . '/' .
373 $img_root . '_' . $size . ".$ext";
374 $filename = 'Twitter_' . $twitter_user->id . '_' .
375 $img_root . "_$size.$ext";
377 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
378 $this->fetchAvatar($url, $filename);
382 function missingAvatarFile($profile) {
384 foreach (array(24, 48, 73) as $size) {
386 $filename = $profile->getAvatar($size)->filename;
387 $avatarpath = Avatar::path($filename);
389 if (file_exists($avatarpath) == FALSE) {
397 function getMediatype($ext)
401 switch (strtolower($ext)) {
403 $mediatype = 'image/jpg';
406 $mediatype = 'image/gif';
409 $mediatype = 'image/png';
415 function saveAvatars($user, $id)
419 $path_parts = pathinfo($user->profile_image_url);
420 $ext = $path_parts['extension'];
421 $end = strlen('_normal' . $ext);
422 $img_root = substr($path_parts['basename'], 0, -($end+1));
423 $mediatype = $this->getMediatype($ext);
425 foreach (array('mini', 'normal', 'bigger') as $size) {
426 $url = $path_parts['dirname'] . '/' .
427 $img_root . '_' . $size . ".$ext";
428 $filename = 'Twitter_' . $user->id . '_' .
429 $img_root . "_$size.$ext";
431 if ($this->fetchAvatar($url, $filename)) {
432 $this->newAvatar($id, $size, $mediatype, $filename);
434 common_log(LOG_WARNING, $this->id() .
435 " - Problem fetching Avatar: $url");
440 function updateAvatar($profile_id, $size, $mediatype, $filename) {
442 common_debug($this->name() . " - Updating avatar: $size");
444 $profile = Profile::staticGet($profile_id);
446 if (empty($profile)) {
447 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
451 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
452 $avatar = $profile->getAvatar($sizes[$size]);
454 // Delete the avatar, if present
460 $this->newAvatar($profile->id, $size, $mediatype, $filename);
463 function newAvatar($profile_id, $size, $mediatype, $filename)
467 $avatar = new Avatar();
468 $avatar->profile_id = $profile_id;
473 $avatar->height = 24;
477 $avatar->height = 48;
481 // Note: Twitter's big avatars are a different size than
482 // Laconica's (Laconica's = 96)
485 $avatar->height = 73;
488 $avatar->original = 0; // we don't have the original
489 $avatar->mediatype = $mediatype;
490 $avatar->filename = $filename;
491 $avatar->url = Avatar::url($filename);
493 common_debug($this->name() . " - New filename: $avatar->url");
495 $avatar->created = common_sql_now();
497 $id = $avatar->insert();
500 common_log_db_error($avatar, 'INSERT', __FILE__);
504 common_debug($this->name() .
505 " - Saved new $size avatar for $profile_id.");
510 function fetchAvatar($url, $filename)
512 $avatar_dir = INSTALLDIR . '/avatar/';
514 $avatarfile = $avatar_dir . $filename;
516 $out = fopen($avatarfile, 'wb');
518 common_log(LOG_WARNING, $this->name() .
519 " - Couldn't open file $filename");
523 common_debug($this->name() . " - Fetching Twitter avatar: $url");
526 curl_setopt($ch, CURLOPT_URL, $url);
527 curl_setopt($ch, CURLOPT_FILE, $out);
528 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
529 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
530 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
531 $result = curl_exec($ch);
543 if (have_option('i')) {
544 $id = get_option_value('i');
545 } else if (have_option('--id')) {
546 $id = get_option_value('--id');
547 } else if (count($args) > 0) {
553 if (have_option('d') || have_option('debug')) {
557 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);