4 * StatusNet - the distributed open-source microblogging tool
5 * Copyright (C) 2008, 2009, StatusNet, 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__) . '/..'));
22 define('STATUSNET', true);
23 define('LACONICA', true); // compatibility
25 // Tune number of processes and how often to poll Twitter
26 // XXX: Should these things be in config.php?
27 define('MAXCHILDREN', 2);
28 define('POLL_INTERVAL', 60); // in seconds
30 $shortoptions = 'di::';
31 $longoptions = array('id::', 'debug');
33 $helptext = <<<END_OF_TRIM_HELP
34 Batch script for retrieving Twitter messages from foreign service.
36 -i --id Identity (default 'generic')
37 -d --debug Debug (lots of log output)
41 require_once INSTALLDIR .'/scripts/commandline.inc';
42 require_once INSTALLDIR . '/lib/daemon.php';
45 * Fetcher for statuses from Twitter
47 * Fetches statuses from Twitter and inserts them as notices in local
52 * @author Zach Copley <zach@status.net>
53 * @author Evan Prodromou <evan@status.net>
54 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
55 * @link http://status.net/
58 // NOTE: an Avatar path MUST be set in config.php for this
59 // script to work: e.g.: $config['avatar']['path'] = '/statusnet/avatar';
61 class TwitterStatusFetcher extends ParallelizingDaemon
66 * @param string $id the name/id of this daemon
67 * @param int $interval sleep this long before doing everything again
68 * @param int $max_children maximum number of child processes at a time
69 * @param boolean $debug debug output flag
74 function __construct($id = null, $interval = 60,
75 $max_children = 2, $debug = null)
77 parent::__construct($id, $interval, $max_children, $debug);
83 * @return string Name of the daemon.
88 return ('twitterstatusfetcher.'.$this->_id);
92 * Find all the Twitter foreign links for users who have requested
93 * importing of their friends' timelines
95 * @return array flinks an array of Foreign_link objects
100 global $_DB_DATAOBJECT;
102 $flink = new Foreign_link();
103 $conn = &$flink->getDatabaseConnection();
105 $flink->service = TWITTER_SERVICE;
106 $flink->orderBy('last_noticesync');
111 while ($flink->fetch()) {
113 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
114 FOREIGN_NOTICE_RECV) {
115 $flinks[] = clone($flink);
123 unset($_DB_DATAOBJECT['CONNECTIONS']);
128 function childTask($flink) {
130 // Each child ps needs its own DB connection
132 // Note: DataObject::getDatabaseConnection() creates
133 // a new connection if there isn't one already
135 $conn = &$flink->getDatabaseConnection();
137 $this->getTimeline($flink);
139 $flink->last_friendsync = common_sql_now();
144 // XXX: Couldn't find a less brutal way to blow
145 // away a cached connection
147 global $_DB_DATAOBJECT;
148 unset($_DB_DATAOBJECT['CONNECTIONS']);
151 function getTimeline($flink)
154 common_log(LOG_WARNING, $this->name() .
155 " - Can't retrieve Foreign_link for foreign ID $fid");
159 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
162 // XXX: Biggest remaining issue - How do we know at which status
163 // to start importing? How many statuses? Right now I'm going
164 // with the default last 20.
168 if (TwitterOAuthClient::isPackedToken($flink->credentials)) {
169 $token = TwitterOAuthClient::unpackToken($flink->credentials);
170 $client = new TwitterOAuthClient($token->key, $token->secret);
171 common_debug($this->name() . ' - Grabbing friends timeline with OAuth.');
173 $client = new TwitterBasicAuthClient($flink);
174 common_debug($this->name() . ' - Grabbing friends timeline with basic auth.');
180 $timeline = $client->statusesFriendsTimeline();
181 } catch (Exception $e) {
182 common_log(LOG_WARNING, $this->name() .
183 ' - Twitter client unable to get friends timeline for user ' .
184 $flink->user_id . ' - code: ' .
185 $e->getCode() . 'msg: ' . $e->getMessage());
188 if (empty($timeline)) {
189 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
193 // Reverse to preserve order
195 foreach (array_reverse($timeline) as $status) {
197 // Hacktastic: filter out stuff coming from this StatusNet
199 $source = mb_strtolower(common_config('integration', 'source'));
201 if (preg_match("/$source/", mb_strtolower($status->source))) {
202 common_debug($this->name() . ' - Skipping import of status ' .
203 $status->id . ' with source ' . $source);
207 $this->saveStatus($status, $flink);
210 // Okay, record the time we synced with Twitter for posterity
212 $flink->last_noticesync = common_sql_now();
216 function saveStatus($status, $flink)
218 $id = $this->ensureProfile($status->user);
220 $profile = Profile::staticGet($id);
222 if (empty($profile)) {
223 common_log(LOG_ERR, $this->name() .
224 ' - Problem saving notice. No associated Profile.');
228 // XXX: change of screen name?
230 $uri = 'http://twitter.com/' . $status->user->screen_name .
231 '/status/' . $status->id;
233 $notice = Notice::staticGet('uri', $uri);
235 // check to see if we've already imported the status
237 if (empty($notice)) {
239 $notice = new Notice();
241 $notice->profile_id = $id;
243 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
244 strtotime($status->created_at));
245 $notice->content = common_shorten_links($status->text); // XXX
246 $notice->rendered = common_render_content($notice->content, $notice);
247 $notice->source = 'twitter';
248 $notice->reply_to = null; // XXX: lookup reply
249 $notice->is_local = Notice::GATEWAY;
251 if (Event::handle('StartNoticeSave', array(&$notice))) {
252 $id = $notice->insert();
253 Event::handle('EndNoticeSave', array($notice));
257 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
258 'user_id' => $flink->user_id))) {
260 $inbox = new Notice_inbox();
262 $inbox->user_id = $flink->user_id;
263 $inbox->notice_id = $notice->id;
264 $inbox->created = $notice->created;
265 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
271 function ensureProfile($user)
273 // check to see if there's already a profile for this user
275 $profileurl = 'http://twitter.com/' . $user->screen_name;
276 $profile = Profile::staticGet('profileurl', $profileurl);
278 if (!empty($profile)) {
279 common_debug($this->name() .
280 " - Profile for $profile->nickname found.");
282 // Check to see if the user's Avatar has changed
284 $this->checkAvatar($user, $profile);
288 common_debug($this->name() . ' - Adding profile and remote profile ' .
289 "for Twitter user: $profileurl.");
291 $profile = new Profile();
292 $profile->query("BEGIN");
294 $profile->nickname = $user->screen_name;
295 $profile->fullname = $user->name;
296 $profile->homepage = $user->url;
297 $profile->bio = $user->description;
298 $profile->location = $user->location;
299 $profile->profileurl = $profileurl;
300 $profile->created = common_sql_now();
302 $id = $profile->insert();
305 common_log_db_error($profile, 'INSERT', __FILE__);
306 $profile->query("ROLLBACK");
310 // check for remote profile
312 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
314 if (empty($remote_pro)) {
316 $remote_pro = new Remote_profile();
318 $remote_pro->id = $id;
319 $remote_pro->uri = $profileurl;
320 $remote_pro->created = common_sql_now();
322 $rid = $remote_pro->insert();
325 common_log_db_error($profile, 'INSERT', __FILE__);
326 $profile->query("ROLLBACK");
331 $profile->query("COMMIT");
333 $this->saveAvatars($user, $id);
339 function checkAvatar($twitter_user, $profile)
343 $path_parts = pathinfo($twitter_user->profile_image_url);
345 $newname = 'Twitter_' . $twitter_user->id . '_' .
346 $path_parts['basename'];
348 $oldname = $profile->getAvatar(48)->filename;
350 if ($newname != $oldname) {
351 common_debug($this->name() . ' - Avatar for Twitter user ' .
352 "$profile->nickname has changed.");
353 common_debug($this->name() . " - old: $oldname new: $newname");
355 $this->updateAvatars($twitter_user, $profile);
358 if ($this->missingAvatarFile($profile)) {
359 common_debug($this->name() . ' - Twitter user ' .
361 ' is missing one or more local avatars.');
362 common_debug($this->name() ." - old: $oldname new: $newname");
364 $this->updateAvatars($twitter_user, $profile);
369 function updateAvatars($twitter_user, $profile) {
373 $path_parts = pathinfo($twitter_user->profile_image_url);
375 $img_root = substr($path_parts['basename'], 0, -11);
376 $ext = $path_parts['extension'];
377 $mediatype = $this->getMediatype($ext);
379 foreach (array('mini', 'normal', 'bigger') as $size) {
380 $url = $path_parts['dirname'] . '/' .
381 $img_root . '_' . $size . ".$ext";
382 $filename = 'Twitter_' . $twitter_user->id . '_' .
383 $img_root . "_$size.$ext";
385 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
386 $this->fetchAvatar($url, $filename);
390 function missingAvatarFile($profile) {
392 foreach (array(24, 48, 73) as $size) {
394 $filename = $profile->getAvatar($size)->filename;
395 $avatarpath = Avatar::path($filename);
397 if (file_exists($avatarpath) == FALSE) {
405 function getMediatype($ext)
409 switch (strtolower($ext)) {
411 $mediatype = 'image/jpg';
414 $mediatype = 'image/gif';
417 $mediatype = 'image/png';
423 function saveAvatars($user, $id)
427 $path_parts = pathinfo($user->profile_image_url);
428 $ext = $path_parts['extension'];
429 $end = strlen('_normal' . $ext);
430 $img_root = substr($path_parts['basename'], 0, -($end+1));
431 $mediatype = $this->getMediatype($ext);
433 foreach (array('mini', 'normal', 'bigger') as $size) {
434 $url = $path_parts['dirname'] . '/' .
435 $img_root . '_' . $size . ".$ext";
436 $filename = 'Twitter_' . $user->id . '_' .
437 $img_root . "_$size.$ext";
439 if ($this->fetchAvatar($url, $filename)) {
440 $this->newAvatar($id, $size, $mediatype, $filename);
442 common_log(LOG_WARNING, $this->id() .
443 " - Problem fetching Avatar: $url");
448 function updateAvatar($profile_id, $size, $mediatype, $filename) {
450 common_debug($this->name() . " - Updating avatar: $size");
452 $profile = Profile::staticGet($profile_id);
454 if (empty($profile)) {
455 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
459 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
460 $avatar = $profile->getAvatar($sizes[$size]);
462 // Delete the avatar, if present
468 $this->newAvatar($profile->id, $size, $mediatype, $filename);
471 function newAvatar($profile_id, $size, $mediatype, $filename)
475 $avatar = new Avatar();
476 $avatar->profile_id = $profile_id;
481 $avatar->height = 24;
485 $avatar->height = 48;
489 // Note: Twitter's big avatars are a different size than
490 // StatusNet's (StatusNet's = 96)
493 $avatar->height = 73;
496 $avatar->original = 0; // we don't have the original
497 $avatar->mediatype = $mediatype;
498 $avatar->filename = $filename;
499 $avatar->url = Avatar::url($filename);
501 common_debug($this->name() . " - New filename: $avatar->url");
503 $avatar->created = common_sql_now();
505 $id = $avatar->insert();
508 common_log_db_error($avatar, 'INSERT', __FILE__);
512 common_debug($this->name() .
513 " - Saved new $size avatar for $profile_id.");
518 function fetchAvatar($url, $filename)
520 $avatar_dir = INSTALLDIR . '/avatar/';
522 $avatarfile = $avatar_dir . $filename;
524 $out = fopen($avatarfile, 'wb');
526 common_log(LOG_WARNING, $this->name() .
527 " - Couldn't open file $filename");
531 common_debug($this->name() . " - Fetching Twitter avatar: $url");
534 curl_setopt($ch, CURLOPT_URL, $url);
535 curl_setopt($ch, CURLOPT_FILE, $out);
536 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
537 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
538 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
539 $result = curl_exec($ch);
551 if (have_option('i')) {
552 $id = get_option_value('i');
553 } else if (have_option('--id')) {
554 $id = get_option_value('--id');
555 } else if (count($args) > 0) {
561 if (have_option('d') || have_option('debug')) {
565 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);