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 twitter_id($status) . ' 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 $statusId = twitter_id($status);
90 $statusUri = $this->makeStatusURI($status->user->screen_name, $statusId);
92 // check to see if we've already imported the status
93 $n2s = Notice_to_status::staticGet('status_id', $statusId);
99 " - Ignoring duplicate import: {$statusId}"
101 return Notice::staticGet('id', $n2s->notice_id);
104 // If it's a retweet, save it as a repeat!
105 if (!empty($status->retweeted_status)) {
106 common_log(LOG_INFO, "Status {$statusId} is a retweet of " . twitter_id($status->retweeted_status) . ".");
107 $original = $this->saveStatus($status->retweeted_status);
108 if (empty($original)) {
111 $author = $original->getProfile();
112 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
113 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
114 $content = sprintf(_m('RT @%1$s %2$s'),
118 if (Notice::contentTooLong($content)) {
119 $contentlimit = Notice::maxContent();
120 $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
123 $repeat = Notice::saveNew($profile->id,
126 array('repeat_of' => $original->id,
128 'is_local' => Notice::GATEWAY));
129 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
130 Notice_to_status::saveNew($repeat->id, $statusId);
135 $notice = new Notice();
137 $notice->profile_id = $profile->id;
138 $notice->uri = $statusUri;
139 $notice->url = $statusUri;
140 $notice->created = strftime(
142 strtotime($status->created_at)
145 $notice->source = 'twitter';
147 $notice->reply_to = null;
149 $replyTo = twitter_id($status, 'in_reply_to_status_id');
150 if (!empty($replyTo)) {
151 common_log(LOG_INFO, "Status {$statusId} is a reply to status {$replyTo}");
152 $n2s = Notice_to_status::staticGet('status_id', $replyTo);
154 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
156 $reply = Notice::staticGet('id', $n2s->notice_id);
158 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
160 common_log(LOG_INFO, "Found local notice {$reply->id} for status {$replyTo}");
161 $notice->reply_to = $reply->id;
162 $notice->conversation = $reply->conversation;
167 if (empty($notice->conversation)) {
168 $conv = Conversation::create();
169 $notice->conversation = $conv->id;
170 common_log(LOG_INFO, "No known conversation for status {$statusId} so making a new one {$conv->id}.");
173 $notice->is_local = Notice::GATEWAY;
175 $notice->content = html_entity_decode($status->text, ENT_QUOTES, 'UTF-8');
176 $notice->rendered = $this->linkify($status);
178 if (Event::handle('StartNoticeSave', array(&$notice))) {
180 $id = $notice->insert();
183 common_log_db_error($notice, 'INSERT', __FILE__);
184 common_log(LOG_ERR, $this->name() .
185 ' - Problem saving notice.');
188 Event::handle('EndNoticeSave', array($notice));
191 Notice_to_status::saveNew($notice->id, $statusId);
193 $this->saveStatusMentions($notice, $status);
194 $this->saveStatusAttachments($notice, $status);
196 $notice->blowOnInsert();
202 * Make an URI for a status.
204 * @param object $status status object
208 function makeStatusURI($username, $id)
210 return 'http://twitter.com/#!/'
218 * Look up a Profile by profileurl field. Profile::staticGet() was
219 * not working consistently.
221 * @param string $nickname local nickname of the Twitter user
222 * @param string $profileurl the profile url
224 * @return mixed value the first Profile with that url, or null
226 function getProfileByUrl($nickname, $profileurl)
228 $profile = new Profile();
229 $profile->nickname = $nickname;
230 $profile->profileurl = $profileurl;
233 if ($profile->find()) {
242 * Check to see if this Twitter status has already been imported
244 * @param Profile $profile Twitter user's local profile
245 * @param string $statusUri URI of the status on Twitter
247 * @return mixed value a matching Notice or null
249 function checkDupe($profile, $statusUri)
251 $notice = new Notice();
252 $notice->uri = $statusUri;
253 $notice->profile_id = $profile->id;
256 if ($notice->find()) {
264 function ensureProfile($user)
266 // check to see if there's already a profile for this user
267 $profileurl = 'http://twitter.com/' . $user->screen_name;
268 $profile = $this->getProfileByUrl($user->screen_name, $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();
295 $id = $profile->insert();
296 } catch(Exception $e) {
297 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert profile - ' . $e->getMessage());
301 common_log_db_error($profile, 'INSERT', __FILE__);
302 $profile->query("ROLLBACK");
306 // check for remote profile
308 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
310 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();
318 $rid = $remote_pro->insert();
319 } catch (Exception $e) {
320 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
324 common_log_db_error($profile, 'INSERT', __FILE__);
325 $profile->query("ROLLBACK");
330 $profile->query("COMMIT");
332 $this->saveAvatars($user, $id);
338 function checkAvatar($twitter_user, $profile)
342 $path_parts = pathinfo($twitter_user->profile_image_url);
344 $newname = 'Twitter_' . $twitter_user->id . '_' .
345 $path_parts['basename'];
347 $oldname = $profile->getAvatar(48)->filename;
349 if ($newname != $oldname) {
350 common_debug($this->name() . ' - Avatar for Twitter user ' .
351 "$profile->nickname has changed.");
352 common_debug($this->name() . " - old: $oldname new: $newname");
354 $this->updateAvatars($twitter_user, $profile);
357 if ($this->missingAvatarFile($profile)) {
358 common_debug($this->name() . ' - Twitter user ' .
360 ' is missing one or more local avatars.');
361 common_debug($this->name() ." - old: $oldname new: $newname");
363 $this->updateAvatars($twitter_user, $profile);
367 function updateAvatars($twitter_user, $profile) {
371 $path_parts = pathinfo($twitter_user->profile_image_url);
373 $img_root = substr($path_parts['basename'], 0, -11);
374 $ext = $path_parts['extension'];
375 $mediatype = $this->getMediatype($ext);
377 foreach (array('mini', 'normal', 'bigger') as $size) {
378 $url = $path_parts['dirname'] . '/' .
379 $img_root . '_' . $size . ".$ext";
380 $filename = 'Twitter_' . $twitter_user->id . '_' .
381 $img_root . "_$size.$ext";
383 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
384 $this->fetchAvatar($url, $filename);
388 function missingAvatarFile($profile) {
389 foreach (array(24, 48, 73) as $size) {
390 $filename = $profile->getAvatar($size)->filename;
391 $avatarpath = Avatar::path($filename);
392 if (file_exists($avatarpath) == FALSE) {
399 function getMediatype($ext)
403 switch (strtolower($ext)) {
405 $mediatype = 'image/jpg';
408 $mediatype = 'image/gif';
411 $mediatype = 'image/png';
417 function saveAvatars($user, $id)
421 $path_parts = pathinfo($user->profile_image_url);
422 $ext = $path_parts['extension'];
423 $end = strlen('_normal' . $ext);
424 $img_root = substr($path_parts['basename'], 0, -($end+1));
425 $mediatype = $this->getMediatype($ext);
427 foreach (array('mini', 'normal', 'bigger') as $size) {
428 $url = $path_parts['dirname'] . '/' .
429 $img_root . '_' . $size . ".$ext";
430 $filename = 'Twitter_' . $user->id . '_' .
431 $img_root . "_$size.$ext";
433 if ($this->fetchAvatar($url, $filename)) {
434 $this->newAvatar($id, $size, $mediatype, $filename);
436 common_log(LOG_WARNING, $id() .
437 " - Problem fetching Avatar: $url");
442 function updateAvatar($profile_id, $size, $mediatype, $filename) {
444 common_debug($this->name() . " - Updating avatar: $size");
446 $profile = Profile::staticGet($profile_id);
448 if (empty($profile)) {
449 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
453 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
454 $avatar = $profile->getAvatar($sizes[$size]);
456 // Delete the avatar, if present
461 $this->newAvatar($profile->id, $size, $mediatype, $filename);
464 function newAvatar($profile_id, $size, $mediatype, $filename)
468 $avatar = new Avatar();
469 $avatar->profile_id = $profile_id;
474 $avatar->height = 24;
478 $avatar->height = 48;
481 // Note: Twitter's big avatars are a different size than
482 // StatusNet's (StatusNet's = 96)
484 $avatar->height = 73;
487 $avatar->original = 0; // we don't have the original
488 $avatar->mediatype = $mediatype;
489 $avatar->filename = $filename;
490 $avatar->url = Avatar::url($filename);
492 $avatar->created = common_sql_now();
495 $id = $avatar->insert();
496 } catch (Exception $e) {
497 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
501 common_log_db_error($avatar, 'INSERT', __FILE__);
505 common_debug($this->name() .
506 " - Saved new $size avatar for $profile_id.");
512 * Fetch a remote avatar image and save to local storage.
514 * @param string $url avatar source URL
515 * @param string $filename bare local filename for download
516 * @return bool true on success, false on failure
518 function fetchAvatar($url, $filename)
520 common_debug($this->name() . " - Fetching Twitter avatar: $url");
522 $request = HTTPClient::start();
523 $response = $request->get($url);
524 if ($response->isOk()) {
525 $avatarfile = Avatar::path($filename);
526 $ok = file_put_contents($avatarfile, $response->getBody());
528 common_log(LOG_WARNING, $this->name() .
529 " - Couldn't open file $filename");
543 function linkify($status)
545 $text = $status->text;
547 if (empty($status->entities)) {
548 $statusId = twitter_id($status);
549 common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
550 $text = common_replace_urls_callback($text, 'common_linkify');
551 $text = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
552 $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
556 // Move all the entities into order so we can
557 // replace them and escape surrounding plaintext
560 $toReplace = array();
562 if (!empty($status->entities->urls)) {
563 foreach ($status->entities->urls as $url) {
564 $toReplace[$url->indices[0]] = array(self::URL, $url);
568 if (!empty($status->entities->hashtags)) {
569 foreach ($status->entities->hashtags as $hashtag) {
570 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
574 if (!empty($status->entities->user_mentions)) {
575 foreach ($status->entities->user_mentions as $mention) {
576 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
580 // sort in forward order by key
587 foreach ($toReplace as $part) {
588 list($type, $object) = $part;
589 $start = $object->indices[0];
590 $end = $object->indices[1];
591 if ($cursor < $start) {
592 // Copy in the preceding plaintext
593 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
596 $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
599 $linkText = $this->makeUrlLink($object, $orig);
602 $linkText = $this->makeHashtagLink($object, $orig);
605 $linkText = $this->makeMentionLink($object, $orig);
611 $result .= $linkText;
614 $last = $this->twitEscape(mb_substr($text, $cursor));
620 function twitEscape($str)
622 // Twitter seems to preemptive turn < and > into < and >
623 // but doesn't for &, so while you may have some magic protection
624 // against XSS by not bothing to escape manually, you still get
625 // invalid XHTML. Thanks!
627 // Looks like their web interface pretty much sends anything
628 // through intact, so.... to do equivalent, decode all entities
629 // and then re-encode the special ones.
630 return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
633 function makeUrlLink($object, $orig)
635 return "<a href='{$object->url}' class='extlink'>{$orig}</a>";
638 function makeHashtagLink($object, $orig)
640 return "#" . self::tagLink($object->text, substr($orig, 1));
643 function makeMentionLink($object, $orig)
645 return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
648 static function tagLink($tag, $orig)
650 return "<a href='https://search.twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
653 static function atLink($screenName, $fullName, $orig)
655 if (!empty($fullName)) {
656 return "<a href='http://twitter.com/#!/{$screenName}' title='{$fullName}'>{$orig}</a>";
658 return "<a href='http://twitter.com/#!/{$screenName}'>{$orig}</a>";
662 function saveStatusMentions($notice, $status)
666 if (empty($status->entities) || empty($status->entities->user_mentions)) {
670 foreach ($status->entities->user_mentions as $mention) {
671 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
672 if (!empty($flink)) {
673 $user = User::staticGet('id', $flink->user_id);
675 $reply = new Reply();
676 $reply->notice_id = $notice->id;
677 $reply->profile_id = $user->id;
678 $reply->modified = $notice->created;
679 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
680 $id = $reply->insert();
687 * Record URL links from the notice. Needed to get thumbnail records
688 * for referenced photo and video posts, etc.
690 * @param Notice $notice
691 * @param object $status
693 function saveStatusAttachments($notice, $status)
695 if (common_config('attachments', 'process_links')) {
696 if (!empty($status->entities) && !empty($status->entities->urls)) {
697 foreach ($status->entities->urls as $url) {
698 File::processNew($url->url, $notice->id);