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::getKV('status_id', $statusId);
99 " - Ignoring duplicate import: {$statusId}"
101 return Notice::getKV('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::getKV('status_id', $replyTo);
154 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
156 $reply = Notice::getKV('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($this->linkify($status, FALSE), ENT_QUOTES, 'UTF-8');
176 $notice->rendered = $this->linkify($status, TRUE);
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::getKV() 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::getKV('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 $newname = 'Twitter_' . $twitter_user->id . '_' . basename($twitter_user->profile_image_url);
345 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
346 $oldname = $avatar->filename;
348 } catch (Exception $e) {
353 if ($newname != $oldname) {
354 common_debug($this->name() . ' - Avatar for Twitter user ' .
355 "$profile->nickname has changed.");
356 common_debug($this->name() . " - old: $oldname new: $newname");
358 $this->updateAvatars($twitter_user, $profile);
361 if (Avatar::hasUploaded($profile)) {
362 common_debug($this->name() . ' - Twitter user ' .
364 ' is missing one or more local avatars.');
365 common_debug($this->name() ." - old: $oldname new: $newname");
367 $this->updateAvatars($twitter_user, $profile);
371 function updateAvatars($twitter_user, $profile) {
375 $path_parts = pathinfo($twitter_user->profile_image_url);
377 $ext = (isset($path_parts['extension']) ? '.'.$path_parts['extension'] : ''); // some lack extension
378 $img_root = basename($path_parts['basename'], '_normal'.$ext); // cut off extension
379 $mediatype = $this->getMediatype(substr($ext, 1));
381 foreach (array('mini', 'normal', 'bigger') as $size) {
382 $url = $path_parts['dirname'] . '/' .
383 $img_root . '_' . $size . $ext;
384 $filename = 'Twitter_' . $twitter_user->id . '_' .
385 $img_root . '_' . $size . $ext;
387 $this->updateAvatar($profile->id, $size, $mediatype, $filename);
388 $this->fetchAvatar($url, $filename);
392 function getMediatype($ext)
396 switch (strtolower($ext)) {
399 $mediatype = 'image/jpeg';
402 $mediatype = 'image/gif';
405 $mediatype = 'image/png';
411 function saveAvatars($user, $id)
415 $path_parts = pathinfo($user->profile_image_url);
416 $ext = (isset($path_parts['extension']) ? '.'.$path_parts['extension'] : '');
417 $img_root = basename($path_parts['basename'], '_normal'.$ext);
418 $mediatype = $this->getMediatype(substr($ext, 1));
420 foreach (array('mini', 'normal', 'bigger') as $size) {
421 $url = $path_parts['dirname'] . '/' .
422 $img_root . '_' . $size . $ext;
423 $filename = 'Twitter_' . $user->id . '_' .
424 $img_root . '_' . $size . $ext;
426 if ($this->fetchAvatar($url, $filename)) {
427 $this->newAvatar($id, $size, $mediatype, $filename);
429 common_log(LOG_WARNING, $id() .
430 " - Problem fetching Avatar: $url");
435 function updateAvatar($profile_id, $size, $mediatype, $filename) {
437 common_debug($this->name() . " - Updating avatar: $size");
439 $profile = Profile::getKV($profile_id);
441 if (empty($profile)) {
442 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
446 Avatar::deleteFromProfile($profile);
448 $this->newAvatar($profile->id, $size, $mediatype, $filename);
451 function newAvatar($profile_id, $size, $mediatype, $filename)
455 $avatar = new Avatar();
456 $avatar->profile_id = $profile_id;
461 $avatar->height = 24;
465 $avatar->height = 48;
468 // Note: Twitter's big avatars are a different size than
469 // StatusNet's (StatusNet's = 96)
471 $avatar->height = 73;
474 $avatar->original = 0; // we don't have the original
475 $avatar->mediatype = $mediatype;
476 $avatar->filename = $filename;
477 $avatar->url = Avatar::url($filename);
479 $avatar->created = common_sql_now();
482 $id = $avatar->insert();
483 } catch (Exception $e) {
484 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
488 common_log_db_error($avatar, 'INSERT', __FILE__);
492 common_debug($this->name() .
493 " - Saved new $size avatar for $profile_id.");
499 * Fetch a remote avatar image and save to local storage.
501 * @param string $url avatar source URL
502 * @param string $filename bare local filename for download
503 * @return bool true on success, false on failure
505 function fetchAvatar($url, $filename)
507 common_debug($this->name() . " - Fetching Twitter avatar: $url");
509 $request = HTTPClient::start();
510 $response = $request->get($url);
511 if ($response->isOk()) {
512 $avatarfile = Avatar::path($filename);
513 $ok = file_put_contents($avatarfile, $response->getBody());
515 common_log(LOG_WARNING, $this->name() .
516 " - Couldn't open file $filename");
530 function linkify($status, $html = FALSE)
532 $text = $status->text;
534 if (empty($status->entities)) {
535 $statusId = twitter_id($status);
536 common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
537 $text = common_replace_urls_callback($text, 'common_linkify');
538 $text = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
539 $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
543 // Move all the entities into order so we can
544 // replace them and escape surrounding plaintext
547 $toReplace = array();
549 if (!empty($status->entities->urls)) {
550 foreach ($status->entities->urls as $url) {
551 $toReplace[$url->indices[0]] = array(self::URL, $url);
555 if (!empty($status->entities->hashtags)) {
556 foreach ($status->entities->hashtags as $hashtag) {
557 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
561 if (!empty($status->entities->user_mentions)) {
562 foreach ($status->entities->user_mentions as $mention) {
563 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
567 // sort in forward order by key
574 foreach ($toReplace as $part) {
575 list($type, $object) = $part;
576 $start = $object->indices[0];
577 $end = $object->indices[1];
578 if ($cursor < $start) {
579 // Copy in the preceding plaintext
580 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
583 $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
586 $linkText = $this->makeUrlLink($object, $orig, $html);
590 $linkText = $this->makeHashtagLink($object, $orig);
597 $linkText = $this->makeMentionLink($object, $orig);
606 $result .= $linkText;
609 $last = $this->twitEscape(mb_substr($text, $cursor));
615 function twitEscape($str)
617 // Twitter seems to preemptive turn < and > into < and >
618 // but doesn't for &, so while you may have some magic protection
619 // against XSS by not bothing to escape manually, you still get
620 // invalid XHTML. Thanks!
622 // Looks like their web interface pretty much sends anything
623 // through intact, so.... to do equivalent, decode all entities
624 // and then re-encode the special ones.
625 return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
628 function makeUrlLink($object, $orig, $html)
631 return '<a href="'.htmlspecialchars($object->expanded_url).'" class="extlink">'.htmlspecialchars($object->display_url).'</a>';
633 return htmlspecialchars($object->expanded_url);
637 function makeHashtagLink($object, $orig)
639 return "#" . self::tagLink($object->text, substr($orig, 1));
642 function makeMentionLink($object, $orig)
644 return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
647 static function tagLink($tag, $orig)
649 return "<a href='https://search.twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
652 static function atLink($screenName, $fullName, $orig)
654 if (!empty($fullName)) {
655 return "<a href='http://twitter.com/#!/{$screenName}' title='{$fullName}'>{$orig}</a>";
657 return "<a href='http://twitter.com/#!/{$screenName}'>{$orig}</a>";
661 function saveStatusMentions($notice, $status)
665 if (empty($status->entities) || empty($status->entities->user_mentions)) {
669 foreach ($status->entities->user_mentions as $mention) {
670 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
671 if (!empty($flink)) {
672 $user = User::getKV('id', $flink->user_id);
674 $reply = new Reply();
675 $reply->notice_id = $notice->id;
676 $reply->profile_id = $user->id;
677 $reply->modified = $notice->created;
678 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
679 $id = $reply->insert();
686 * Record URL links from the notice. Needed to get thumbnail records
687 * for referenced photo and video posts, etc.
689 * @param Notice $notice
690 * @param object $status
692 function saveStatusAttachments($notice, $status)
694 if (common_config('attachments', 'process_links')) {
695 if (!empty($status->entities) && !empty($status->entities->urls)) {
696 foreach ($status->entities->urls as $url) {
697 File::processNew($url->url, $notice->id);