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';
43 * Fetcher for statuses from Twitter
45 * Fetches statuses from Twitter and inserts them as notices in local
50 * @author Zach Copley <zach@controlyourself.ca>
51 * @author Evan Prodromou <evan@controlyourself.ca>
52 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
53 * @link http://laconi.ca/
56 // NOTE: an Avatar path MUST be set in config.php for this
57 // script to work: e.g.: $config['avatar']['path'] = '/laconica/avatar';
59 class TwitterStatusFetcher extends ParallelizingDaemon
64 * @param string $id the name/id of this daemon
65 * @param int $interval sleep this long before doing everything again
66 * @param int $max_children maximum number of child processes at a time
67 * @param boolean $debug debug output flag
72 function __construct($id = null, $interval = 60,
73 $max_children = 2, $debug = null)
75 parent::__construct($id, $interval, $max_children, $debug);
81 * @return string Name of the daemon.
86 return ('twitterstatusfetcher.'.$this->_id);
90 * Find all the Twitter foreign links for users who have requested
91 * importing of their friends' timelines
93 * @return array flinks an array of Foreign_link objects
98 global $_DB_DATAOBJECT;
101 global $_DB_DATAOBJECT;
103 >>>>>>> 0.8.x:scripts/twitterstatusfetcher.php
104 $flink = new Foreign_link();
105 $conn = &$flink->getDatabaseConnection();
107 $flink->service = TWITTER_SERVICE;
108 $flink->orderBy('last_noticesync');
113 while ($flink->fetch()) {
115 if (($flink->noticesync & FOREIGN_NOTICE_RECV) ==
116 FOREIGN_NOTICE_RECV) {
117 $flinks[] = clone($flink);
125 unset($_DB_DATAOBJECT['CONNECTIONS']);
130 function childTask($flink) {
132 // Each child ps needs its own DB connection
134 // Note: DataObject::getDatabaseConnection() creates
135 // a new connection if there isn't one already
137 $conn = &$flink->getDatabaseConnection();
139 $this->getTimeline($flink);
141 $flink->last_friendsync = common_sql_now();
146 // XXX: Couldn't find a less brutal way to blow
147 // away a cached connection
149 global $_DB_DATAOBJECT;
150 unset($_DB_DATAOBJECT['CONNECTIONS']);
153 function getTimeline($flink)
156 common_log(LOG_WARNING, $this->name() .
157 " - Can't retrieve Foreign_link for foreign ID $fid");
161 common_debug($this->name() . ' - Trying to get timeline for Twitter user ' .
164 // XXX: Biggest remaining issue - How do we know at which status
165 // to start importing? How many statuses? Right now I'm going
166 // with the default last 20.
168 $token = TwitterOAuthClient::unpackToken($flink->credentials);
170 $client = new TwitterOAuthClient($token->key, $token->secret);
175 $timeline = $client->statusesFriendsTimeline();
176 } catch (OAuthClientCurlException $e) {
177 common_log(LOG_WARNING, $this->name() .
178 ' - OAuth client unable to get friends timeline for user ' .
179 $flink->user_id . ' - code: ' .
180 $e->getCode() . 'msg: ' . $e->getMessage());
183 if (empty($timeline)) {
184 common_log(LOG_WARNING, $this->name() . " - Empty timeline.");
188 // Reverse to preserve order
190 foreach (array_reverse($timeline) as $status) {
192 // Hacktastic: filter out stuff coming from this Laconica
194 $source = mb_strtolower(common_config('integration', 'source'));
196 if (preg_match("/$source/", mb_strtolower($status->source))) {
197 common_debug($this->name() . ' - Skipping import of status ' .
198 $status->id . ' with source ' . $source);
202 $this->saveStatus($status, $flink);
205 // Okay, record the time we synced with Twitter for posterity
207 $flink->last_noticesync = common_sql_now();
211 function saveStatus($status, $flink)
213 $id = $this->ensureProfile($status->user);
215 $profile = Profile::staticGet($id);
217 if (empty($profile)) {
218 common_log(LOG_ERR, $this->name() .
219 ' - Problem saving notice. No associated Profile.');
223 // XXX: change of screen name?
225 $uri = 'http://twitter.com/' . $status->user->screen_name .
226 '/status/' . $status->id;
228 $notice = Notice::staticGet('uri', $uri);
230 // check to see if we've already imported the status
232 if (empty($notice)) {
234 $notice = new Notice();
236 $notice->profile_id = $id;
238 $notice->created = strftime('%Y-%m-%d %H:%M:%S',
239 strtotime($status->created_at));
240 $notice->content = common_shorten_links($status->text); // XXX
241 $notice->rendered = common_render_content($notice->content, $notice);
242 $notice->source = 'twitter';
243 $notice->reply_to = null; // XXX: lookup reply
244 $notice->is_local = Notice::GATEWAY;
246 if (Event::handle('StartNoticeSave', array(&$notice))) {
247 $id = $notice->insert();
248 Event::handle('EndNoticeSave', array($notice));
252 if (!Notice_inbox::pkeyGet(array('notice_id' => $notice->id,
253 'user_id' => $flink->user_id))) {
255 $inbox = new Notice_inbox();
257 $inbox->user_id = $flink->user_id;
258 $inbox->notice_id = $notice->id;
259 $inbox->created = $notice->created;
260 $inbox->source = NOTICE_INBOX_SOURCE_GATEWAY; // From a private source
266 function ensureProfile($user)
268 // check to see if there's already a profile for this user
270 $profileurl = 'http://twitter.com/' . $user->screen_name;
271 $profile = Profile::staticGet('profileurl', $profileurl);
273 if (!empty($profile)) {
274 common_debug($this->name() .
275 " - Profile for $profile->nickname found.");
277 // Check to see if the user's Avatar has changed
279 $this->checkAvatar($user, $profile);
283 common_debug($this->name() . ' - Adding profile and remote profile ' .
284 "for Twitter user: $profileurl.");
286 $profile = new Profile();
287 $profile->query("BEGIN");
289 $profile->nickname = $user->screen_name;
290 $profile->fullname = $user->name;
291 $profile->homepage = $user->url;
292 $profile->bio = $user->description;
293 $profile->location = $user->location;
294 $profile->profileurl = $profileurl;
295 $profile->created = common_sql_now();
297 $id = $profile->insert();
300 common_log_db_error($profile, 'INSERT', __FILE__);
301 $profile->query("ROLLBACK");
305 // check for remote profile
307 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
309 if (empty($remote_pro)) {
311 $remote_pro = new Remote_profile();
313 $remote_pro->id = $id;
314 $remote_pro->uri = $profileurl;
315 $remote_pro->created = common_sql_now();
317 $rid = $remote_pro->insert();
320 common_log_db_error($profile, 'INSERT', __FILE__);
321 $profile->query("ROLLBACK");
326 $profile->query("COMMIT");
328 $this->saveAvatars($user, $id);
334 function checkAvatar($twitter_user, $profile)
338 $path_parts = pathinfo($twitter_user->profile_image_url);
340 $newname = 'Twitter_' . $twitter_user->id . '_' .
341 $path_parts['basename'];
343 $oldname = $profile->getAvatar(48)->filename;
345 if ($newname != $oldname) {
346 common_debug($this->name() . ' - Avatar for Twitter user ' .
347 "$profile->nickname has changed.");
348 common_debug($this->name() . " - old: $oldname new: $newname");
350 $this->updateAvatars($twitter_user, $profile);
353 if ($this->missingAvatarFile($profile)) {
354 common_debug($this->name() . ' - Twitter user ' .
356 ' is missing one or more local avatars.');
357 common_debug($this->name() ." - old: $oldname new: $newname");
359 $this->updateAvatars($twitter_user, $profile);
364 function updateAvatars($twitter_user, $profile) {
368 $path_parts = pathinfo($twitter_user->profile_image_url);
370 $img_root = substr($path_parts['basename'], 0, -11);
371 $ext = $path_parts['extension'];
372 $mediatype = $this->getMediatype($ext);
374 foreach (array('mini', 'normal', 'bigger') as $size) {
375 $url = $path_parts['dirname'] . '/' .
376 $img_root . '_' . $size . ".$ext";
377 $filename = 'Twitter_' . $twitter_user->id . '_' .
378 $img_root . "_$size.$ext";
380 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
381 $this->fetchAvatar($url, $filename);
385 function missingAvatarFile($profile) {
387 foreach (array(24, 48, 73) as $size) {
389 $filename = $profile->getAvatar($size)->filename;
390 $avatarpath = Avatar::path($filename);
392 if (file_exists($avatarpath) == FALSE) {
400 function getMediatype($ext)
404 switch (strtolower($ext)) {
406 $mediatype = 'image/jpg';
409 $mediatype = 'image/gif';
412 $mediatype = 'image/png';
418 function saveAvatars($user, $id)
422 $path_parts = pathinfo($user->profile_image_url);
423 $ext = $path_parts['extension'];
424 $end = strlen('_normal' . $ext);
425 $img_root = substr($path_parts['basename'], 0, -($end+1));
426 $mediatype = $this->getMediatype($ext);
428 foreach (array('mini', 'normal', 'bigger') as $size) {
429 $url = $path_parts['dirname'] . '/' .
430 $img_root . '_' . $size . ".$ext";
431 $filename = 'Twitter_' . $user->id . '_' .
432 $img_root . "_$size.$ext";
434 if ($this->fetchAvatar($url, $filename)) {
435 $this->newAvatar($id, $size, $mediatype, $filename);
437 common_log(LOG_WARNING, $this->id() .
438 " - Problem fetching Avatar: $url");
443 function updateAvatar($profile_id, $size, $mediatype, $filename) {
445 common_debug($this->name() . " - Updating avatar: $size");
447 $profile = Profile::staticGet($profile_id);
449 if (empty($profile)) {
450 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
454 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
455 $avatar = $profile->getAvatar($sizes[$size]);
457 // Delete the avatar, if present
463 $this->newAvatar($profile->id, $size, $mediatype, $filename);
466 function newAvatar($profile_id, $size, $mediatype, $filename)
470 $avatar = new Avatar();
471 $avatar->profile_id = $profile_id;
476 $avatar->height = 24;
480 $avatar->height = 48;
484 // Note: Twitter's big avatars are a different size than
485 // Laconica's (Laconica's = 96)
488 $avatar->height = 73;
491 $avatar->original = 0; // we don't have the original
492 $avatar->mediatype = $mediatype;
493 $avatar->filename = $filename;
494 $avatar->url = Avatar::url($filename);
496 common_debug($this->name() . " - New filename: $avatar->url");
498 $avatar->created = common_sql_now();
500 $id = $avatar->insert();
503 common_log_db_error($avatar, 'INSERT', __FILE__);
507 common_debug($this->name() .
508 " - Saved new $size avatar for $profile_id.");
513 function fetchAvatar($url, $filename)
515 $avatar_dir = INSTALLDIR . '/avatar/';
517 $avatarfile = $avatar_dir . $filename;
519 $out = fopen($avatarfile, 'wb');
521 common_log(LOG_WARNING, $this->name() .
522 " - Couldn't open file $filename");
526 common_debug($this->name() . " - Fetching Twitter avatar: $url");
529 curl_setopt($ch, CURLOPT_URL, $url);
530 curl_setopt($ch, CURLOPT_FILE, $out);
531 curl_setopt($ch, CURLOPT_BINARYTRANSFER, true);
532 curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
533 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
534 $result = curl_exec($ch);
546 if (have_option('i')) {
547 $id = get_option_value('i');
548 } else if (have_option('--id')) {
549 $id = get_option_value('--id');
550 } else if (count($args) > 0) {
556 if (have_option('d') || have_option('debug')) {
560 $fetcher = new TwitterStatusFetcher($id, 60, 2, $debug);