3 * StatusNet, the distributed open-source microblogging tool
7 * LICENCE: 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/>.
22 * @author Zach Copley <zach@status.net>
23 * @author Julien C <chaumond@gmail.com>
24 * @author Brion Vibber <brion@status.net>
25 * @copyright 2009-2010 StatusNet, Inc.
26 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27 * @link http://status.net/
30 if (!defined('STATUSNET')) {
34 require_once INSTALLDIR . '/plugins/TwitterBridge/twitter.php';
37 * Encapsulation of the Twitter status -> notice incoming bridge import.
38 * Is used by both the polling twitterstatusfetcher.php daemon, and the
39 * in-progress streaming import.
43 * @author Zach Copley <zach@status.net>
44 * @author Julien C <chaumond@gmail.com>
45 * @author Brion Vibber <brion@status.net>
46 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
47 * @link http://status.net/
48 * @link http://twitter.com/
52 public function importStatus($status)
54 // Hacktastic: filter out stuff coming from this StatusNet
55 $source = mb_strtolower(common_config('integration', 'source'));
57 if (preg_match("/$source/", mb_strtolower($status->source))) {
58 common_debug($this->name() . ' - Skipping import of status ' .
59 $status->id . ' with source ' . $source);
63 // Don't save it if the user is protected
64 // FIXME: save it but treat it as private
65 if ($status->user->protected) {
69 $notice = $this->saveStatus($status);
76 return get_class($this);
79 function saveStatus($status)
81 $profile = $this->ensureProfile($status->user);
83 if (empty($profile)) {
84 common_log(LOG_ERR, $this->name() .
85 ' - Problem saving notice. No associated Profile.');
89 $statusUri = $this->makeStatusURI($status->user->screen_name, $status->id);
91 // check to see if we've already imported the status
92 $n2s = Notice_to_status::staticGet('status_id', $status->id);
98 " - Ignoring duplicate import: {$status->id}"
100 return Notice::staticGet('id', $n2s->notice_id);
103 // If it's a retweet, save it as a repeat!
104 if (!empty($status->retweeted_status)) {
105 common_log(LOG_INFO, "Status {$status->id} is a retweet of {$status->retweeted_status->id}.");
106 $original = $this->saveStatus($status->retweeted_status);
107 if (empty($original)) {
110 $author = $original->getProfile();
111 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
112 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
113 $content = sprintf(_m('RT @%1$s %2$s'),
117 if (Notice::contentTooLong($content)) {
118 $contentlimit = Notice::maxContent();
119 $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
122 $repeat = Notice::saveNew($profile->id,
125 array('repeat_of' => $original->id,
127 'is_local' => Notice::GATEWAY));
128 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
129 Notice_to_status::saveNew($repeat->id, $status->id);
134 $notice = new Notice();
136 $notice->profile_id = $profile->id;
137 $notice->uri = $statusUri;
138 $notice->url = $statusUri;
139 $notice->created = strftime(
141 strtotime($status->created_at)
144 $notice->source = 'twitter';
146 $notice->reply_to = null;
148 if (!empty($status->in_reply_to_status_id)) {
149 common_log(LOG_INFO, "Status {$status->id} is a reply to status {$status->in_reply_to_status_id}");
150 $n2s = Notice_to_status::staticGet('status_id', $status->in_reply_to_status_id);
152 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
154 $reply = Notice::staticGet('id', $n2s->notice_id);
156 common_log(LOG_INFO, "Couldn't find local notice for status {$status->in_reply_to_status_id}");
158 common_log(LOG_INFO, "Found local notice {$reply->id} for status {$status->in_reply_to_status_id}");
159 $notice->reply_to = $reply->id;
160 $notice->conversation = $reply->conversation;
165 if (empty($notice->conversation)) {
166 $conv = Conversation::create();
167 $notice->conversation = $conv->id;
168 common_log(LOG_INFO, "No known conversation for status {$status->id} so making a new one {$conv->id}.");
171 $notice->is_local = Notice::GATEWAY;
173 $notice->content = html_entity_decode($status->text, ENT_QUOTES, 'UTF-8');
174 $notice->rendered = $this->linkify($status);
176 if (Event::handle('StartNoticeSave', array(&$notice))) {
178 $id = $notice->insert();
181 common_log_db_error($notice, 'INSERT', __FILE__);
182 common_log(LOG_ERR, $this->name() .
183 ' - Problem saving notice.');
186 Event::handle('EndNoticeSave', array($notice));
189 Notice_to_status::saveNew($notice->id, $status->id);
191 $this->saveStatusMentions($notice, $status);
192 $this->saveStatusAttachments($notice, $status);
194 $notice->blowOnInsert();
200 * Make an URI for a status.
202 * @param object $status status object
206 function makeStatusURI($username, $id)
208 return 'http://twitter.com/'
216 * Look up a Profile by profileurl field. Profile::staticGet() was
217 * not working consistently.
219 * @param string $nickname local nickname of the Twitter user
220 * @param string $profileurl the profile url
222 * @return mixed value the first Profile with that url, or null
224 function getProfileByUrl($nickname, $profileurl)
226 $profile = new Profile();
227 $profile->nickname = $nickname;
228 $profile->profileurl = $profileurl;
231 if ($profile->find()) {
240 * Check to see if this Twitter status has already been imported
242 * @param Profile $profile Twitter user's local profile
243 * @param string $statusUri URI of the status on Twitter
245 * @return mixed value a matching Notice or null
247 function checkDupe($profile, $statusUri)
249 $notice = new Notice();
250 $notice->uri = $statusUri;
251 $notice->profile_id = $profile->id;
254 if ($notice->find()) {
262 function ensureProfile($user)
264 // check to see if there's already a profile for this user
265 $profileurl = 'http://twitter.com/' . $user->screen_name;
266 $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
268 if (!empty($profile)) {
269 common_debug($this->name() .
270 " - Profile for $profile->nickname found.");
272 // Check to see if the user's Avatar has changed
274 $this->checkAvatar($user, $profile);
278 common_debug($this->name() . ' - Adding profile and remote profile ' .
279 "for Twitter user: $profileurl.");
281 $profile = new Profile();
282 $profile->query("BEGIN");
284 $profile->nickname = $user->screen_name;
285 $profile->fullname = $user->name;
286 $profile->homepage = $user->url;
287 $profile->bio = $user->description;
288 $profile->location = $user->location;
289 $profile->profileurl = $profileurl;
290 $profile->created = common_sql_now();
293 $id = $profile->insert();
294 } catch(Exception $e) {
295 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert profile - ' . $e->getMessage());
299 common_log_db_error($profile, 'INSERT', __FILE__);
300 $profile->query("ROLLBACK");
304 // check for remote profile
306 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
308 if (empty($remote_pro)) {
309 $remote_pro = new Remote_profile();
311 $remote_pro->id = $id;
312 $remote_pro->uri = $profileurl;
313 $remote_pro->created = common_sql_now();
316 $rid = $remote_pro->insert();
317 } catch (Exception $e) {
318 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
322 common_log_db_error($profile, 'INSERT', __FILE__);
323 $profile->query("ROLLBACK");
328 $profile->query("COMMIT");
330 $this->saveAvatars($user, $id);
336 function checkAvatar($twitter_user, $profile)
340 $path_parts = pathinfo($twitter_user->profile_image_url);
342 $newname = 'Twitter_' . $twitter_user->id . '_' .
343 $path_parts['basename'];
345 $oldname = $profile->getAvatar(48)->filename;
347 if ($newname != $oldname) {
348 common_debug($this->name() . ' - Avatar for Twitter user ' .
349 "$profile->nickname has changed.");
350 common_debug($this->name() . " - old: $oldname new: $newname");
352 $this->updateAvatars($twitter_user, $profile);
355 if ($this->missingAvatarFile($profile)) {
356 common_debug($this->name() . ' - Twitter user ' .
358 ' is missing one or more local avatars.');
359 common_debug($this->name() ." - old: $oldname new: $newname");
361 $this->updateAvatars($twitter_user, $profile);
365 function updateAvatars($twitter_user, $profile) {
369 $path_parts = pathinfo($twitter_user->profile_image_url);
371 $img_root = substr($path_parts['basename'], 0, -11);
372 $ext = $path_parts['extension'];
373 $mediatype = $this->getMediatype($ext);
375 foreach (array('mini', 'normal', 'bigger') as $size) {
376 $url = $path_parts['dirname'] . '/' .
377 $img_root . '_' . $size . ".$ext";
378 $filename = 'Twitter_' . $twitter_user->id . '_' .
379 $img_root . "_$size.$ext";
381 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
382 $this->fetchAvatar($url, $filename);
386 function missingAvatarFile($profile) {
387 foreach (array(24, 48, 73) as $size) {
388 $filename = $profile->getAvatar($size)->filename;
389 $avatarpath = Avatar::path($filename);
390 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, $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
459 $this->newAvatar($profile->id, $size, $mediatype, $filename);
462 function newAvatar($profile_id, $size, $mediatype, $filename)
466 $avatar = new Avatar();
467 $avatar->profile_id = $profile_id;
472 $avatar->height = 24;
476 $avatar->height = 48;
479 // Note: Twitter's big avatars are a different size than
480 // StatusNet's (StatusNet's = 96)
482 $avatar->height = 73;
485 $avatar->original = 0; // we don't have the original
486 $avatar->mediatype = $mediatype;
487 $avatar->filename = $filename;
488 $avatar->url = Avatar::url($filename);
490 $avatar->created = common_sql_now();
493 $id = $avatar->insert();
494 } catch (Exception $e) {
495 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
499 common_log_db_error($avatar, 'INSERT', __FILE__);
503 common_debug($this->name() .
504 " - Saved new $size avatar for $profile_id.");
510 * Fetch a remote avatar image and save to local storage.
512 * @param string $url avatar source URL
513 * @param string $filename bare local filename for download
514 * @return bool true on success, false on failure
516 function fetchAvatar($url, $filename)
518 common_debug($this->name() . " - Fetching Twitter avatar: $url");
520 $request = HTTPClient::start();
521 $response = $request->get($url);
522 if ($response->isOk()) {
523 $avatarfile = Avatar::path($filename);
524 $ok = file_put_contents($avatarfile, $response->getBody());
526 common_log(LOG_WARNING, $this->name() .
527 " - Couldn't open file $filename");
541 function linkify($status)
543 $text = $status->text;
545 if (empty($status->entities)) {
546 common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
547 $text = common_replace_urls_callback($text, 'common_linkify');
548 $text = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
549 $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
553 // Move all the entities into order so we can
554 // replace them in reverse order and thus
555 // not mess up their indices
557 $toReplace = array();
559 if (!empty($status->entities->urls)) {
560 foreach ($status->entities->urls as $url) {
561 $toReplace[$url->indices[0]] = array(self::URL, $url);
565 if (!empty($status->entities->hashtags)) {
566 foreach ($status->entities->hashtags as $hashtag) {
567 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
571 if (!empty($status->entities->user_mentions)) {
572 foreach ($status->entities->user_mentions as $mention) {
573 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
577 // sort in reverse order by key
581 foreach ($toReplace as $part) {
582 list($type, $object) = $part;
585 $linkText = $this->makeUrlLink($object);
588 $linkText = $this->makeHashtagLink($object);
591 $linkText = $this->makeMentionLink($object);
596 $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
601 function makeUrlLink($object)
603 return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
606 function makeHashtagLink($object)
608 return "#" . self::tagLink($object->text);
611 function makeMentionLink($object)
613 return "@".self::atLink($object->screen_name, $object->name);
616 static function tagLink($tag)
618 return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
621 static function atLink($screenName, $fullName=null)
623 if (!empty($fullName)) {
624 return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
626 return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
630 function saveStatusMentions($notice, $status)
634 if (empty($status->entities) || empty($status->entities->user_mentions)) {
638 foreach ($status->entities->user_mentions as $mention) {
639 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
640 if (!empty($flink)) {
641 $user = User::staticGet('id', $flink->user_id);
643 $reply = new Reply();
644 $reply->notice_id = $notice->id;
645 $reply->profile_id = $user->id;
646 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
647 $id = $reply->insert();
654 * Record URL links from the notice. Needed to get thumbnail records
655 * for referenced photo and video posts, etc.
657 * @param Notice $notice
658 * @param object $status
660 function saveStatusAttachments($notice, $status)
662 if (common_config('attachments', 'process_links')) {
663 if (!empty($status->entities) && !empty($status->entities->urls)) {
664 foreach ($status->entities->urls as $url) {
665 File::processNew($url->url, $notice->id);