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);
193 $notice->blowOnInsert();
199 * Make an URI for a status.
201 * @param object $status status object
205 function makeStatusURI($username, $id)
207 return 'http://twitter.com/'
215 * Look up a Profile by profileurl field. Profile::staticGet() was
216 * not working consistently.
218 * @param string $nickname local nickname of the Twitter user
219 * @param string $profileurl the profile url
221 * @return mixed value the first Profile with that url, or null
223 function getProfileByUrl($nickname, $profileurl)
225 $profile = new Profile();
226 $profile->nickname = $nickname;
227 $profile->profileurl = $profileurl;
230 if ($profile->find()) {
239 * Check to see if this Twitter status has already been imported
241 * @param Profile $profile Twitter user's local profile
242 * @param string $statusUri URI of the status on Twitter
244 * @return mixed value a matching Notice or null
246 function checkDupe($profile, $statusUri)
248 $notice = new Notice();
249 $notice->uri = $statusUri;
250 $notice->profile_id = $profile->id;
253 if ($notice->find()) {
261 function ensureProfile($user)
263 // check to see if there's already a profile for this user
264 $profileurl = 'http://twitter.com/' . $user->screen_name;
265 $profile = $this->getProfileByUrl($user->screen_name, $profileurl);
267 if (!empty($profile)) {
268 common_debug($this->name() .
269 " - Profile for $profile->nickname found.");
271 // Check to see if the user's Avatar has changed
273 $this->checkAvatar($user, $profile);
277 common_debug($this->name() . ' - Adding profile and remote profile ' .
278 "for Twitter user: $profileurl.");
280 $profile = new Profile();
281 $profile->query("BEGIN");
283 $profile->nickname = $user->screen_name;
284 $profile->fullname = $user->name;
285 $profile->homepage = $user->url;
286 $profile->bio = $user->description;
287 $profile->location = $user->location;
288 $profile->profileurl = $profileurl;
289 $profile->created = common_sql_now();
292 $id = $profile->insert();
293 } catch(Exception $e) {
294 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert profile - ' . $e->getMessage());
298 common_log_db_error($profile, 'INSERT', __FILE__);
299 $profile->query("ROLLBACK");
303 // check for remote profile
305 $remote_pro = Remote_profile::staticGet('uri', $profileurl);
307 if (empty($remote_pro)) {
308 $remote_pro = new Remote_profile();
310 $remote_pro->id = $id;
311 $remote_pro->uri = $profileurl;
312 $remote_pro->created = common_sql_now();
315 $rid = $remote_pro->insert();
316 } catch (Exception $e) {
317 common_log(LOG_WARNING, $this->name() . ' Couldn\'t save remote profile - ' . $e->getMessage());
321 common_log_db_error($profile, 'INSERT', __FILE__);
322 $profile->query("ROLLBACK");
327 $profile->query("COMMIT");
329 $this->saveAvatars($user, $id);
335 function checkAvatar($twitter_user, $profile)
339 $path_parts = pathinfo($twitter_user->profile_image_url);
341 $newname = 'Twitter_' . $twitter_user->id . '_' .
342 $path_parts['basename'];
344 $oldname = $profile->getAvatar(48)->filename;
346 if ($newname != $oldname) {
347 common_debug($this->name() . ' - Avatar for Twitter user ' .
348 "$profile->nickname has changed.");
349 common_debug($this->name() . " - old: $oldname new: $newname");
351 $this->updateAvatars($twitter_user, $profile);
354 if ($this->missingAvatarFile($profile)) {
355 common_debug($this->name() . ' - Twitter user ' .
357 ' is missing one or more local avatars.');
358 common_debug($this->name() ." - old: $oldname new: $newname");
360 $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) {
386 foreach (array(24, 48, 73) as $size) {
387 $filename = $profile->getAvatar($size)->filename;
388 $avatarpath = Avatar::path($filename);
389 if (file_exists($avatarpath) == FALSE) {
396 function getMediatype($ext)
400 switch (strtolower($ext)) {
402 $mediatype = 'image/jpg';
405 $mediatype = 'image/gif';
408 $mediatype = 'image/png';
414 function saveAvatars($user, $id)
418 $path_parts = pathinfo($user->profile_image_url);
419 $ext = $path_parts['extension'];
420 $end = strlen('_normal' . $ext);
421 $img_root = substr($path_parts['basename'], 0, -($end+1));
422 $mediatype = $this->getMediatype($ext);
424 foreach (array('mini', 'normal', 'bigger') as $size) {
425 $url = $path_parts['dirname'] . '/' .
426 $img_root . '_' . $size . ".$ext";
427 $filename = 'Twitter_' . $user->id . '_' .
428 $img_root . "_$size.$ext";
430 if ($this->fetchAvatar($url, $filename)) {
431 $this->newAvatar($id, $size, $mediatype, $filename);
433 common_log(LOG_WARNING, $id() .
434 " - Problem fetching Avatar: $url");
439 function updateAvatar($profile_id, $size, $mediatype, $filename) {
441 common_debug($this->name() . " - Updating avatar: $size");
443 $profile = Profile::staticGet($profile_id);
445 if (empty($profile)) {
446 common_debug($this->name() . " - Couldn't get profile: $profile_id!");
450 $sizes = array('mini' => 24, 'normal' => 48, 'bigger' => 73);
451 $avatar = $profile->getAvatar($sizes[$size]);
453 // Delete the avatar, if present
458 $this->newAvatar($profile->id, $size, $mediatype, $filename);
461 function newAvatar($profile_id, $size, $mediatype, $filename)
465 $avatar = new Avatar();
466 $avatar->profile_id = $profile_id;
471 $avatar->height = 24;
475 $avatar->height = 48;
478 // Note: Twitter's big avatars are a different size than
479 // StatusNet's (StatusNet's = 96)
481 $avatar->height = 73;
484 $avatar->original = 0; // we don't have the original
485 $avatar->mediatype = $mediatype;
486 $avatar->filename = $filename;
487 $avatar->url = Avatar::url($filename);
489 $avatar->created = common_sql_now();
492 $id = $avatar->insert();
493 } catch (Exception $e) {
494 common_log(LOG_WARNING, $this->name() . ' Couldn\'t insert avatar - ' . $e->getMessage());
498 common_log_db_error($avatar, 'INSERT', __FILE__);
502 common_debug($this->name() .
503 " - Saved new $size avatar for $profile_id.");
509 * Fetch a remote avatar image and save to local storage.
511 * @param string $url avatar source URL
512 * @param string $filename bare local filename for download
513 * @return bool true on success, false on failure
515 function fetchAvatar($url, $filename)
517 common_debug($this->name() . " - Fetching Twitter avatar: $url");
519 $request = HTTPClient::start();
520 $response = $request->get($url);
521 if ($response->isOk()) {
522 $avatarfile = Avatar::path($filename);
523 $ok = file_put_contents($avatarfile, $response->getBody());
525 common_log(LOG_WARNING, $this->name() .
526 " - Couldn't open file $filename");
540 function linkify($status)
542 $text = $status->text;
544 if (empty($status->entities)) {
545 common_log(LOG_WARNING, "No entities data for {$status->id}; trying to fake up links ourselves.");
546 $text = common_replace_urls_callback($text, 'common_linkify');
547 $text = preg_replace('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/e', "'\\1#'.TwitterStatusFetcher::tagLink('\\2')", $text);
548 $text = preg_replace('/(^|\s+)@([a-z0-9A-Z_]{1,64})/e', "'\\1@'.TwitterStatusFetcher::atLink('\\2')", $text);
552 // Move all the entities into order so we can
553 // replace them in reverse order and thus
554 // not mess up their indices
556 $toReplace = array();
558 if (!empty($status->entities->urls)) {
559 foreach ($status->entities->urls as $url) {
560 $toReplace[$url->indices[0]] = array(self::URL, $url);
564 if (!empty($status->entities->hashtags)) {
565 foreach ($status->entities->hashtags as $hashtag) {
566 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
570 if (!empty($status->entities->user_mentions)) {
571 foreach ($status->entities->user_mentions as $mention) {
572 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
576 // sort in reverse order by key
580 foreach ($toReplace as $part) {
581 list($type, $object) = $part;
584 $linkText = $this->makeUrlLink($object);
587 $linkText = $this->makeHashtagLink($object);
590 $linkText = $this->makeMentionLink($object);
595 $text = mb_substr($text, 0, $object->indices[0]) . $linkText . mb_substr($text, $object->indices[1]);
600 function makeUrlLink($object)
602 return "<a href='{$object->url}' class='extlink'>{$object->url}</a>";
605 function makeHashtagLink($object)
607 return "#" . self::tagLink($object->text);
610 function makeMentionLink($object)
612 return "@".self::atLink($object->screen_name, $object->name);
615 static function tagLink($tag)
617 return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$tag}</a>";
620 static function atLink($screenName, $fullName=null)
622 if (!empty($fullName)) {
623 return "<a href='http://twitter.com/{$screenName}' title='{$fullName}'>{$screenName}</a>";
625 return "<a href='http://twitter.com/{$screenName}'>{$screenName}</a>";
629 function saveStatusMentions($notice, $status)
633 if (empty($status->entities) || empty($status->entities->user_mentions)) {
637 foreach ($status->entities->user_mentions as $mention) {
638 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
639 if (!empty($flink)) {
640 $user = User::staticGet('id', $flink->user_id);
642 $reply = new Reply();
643 $reply->notice_id = $notice->id;
644 $reply->profile_id = $user->id;
645 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
646 $id = $reply->insert();