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 dirname(__DIR__) . '/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 $avatarsizename = 'reasonably_small'; // a Twitter size name for 128x128 px
53 public $avatarsize = 128; // they're square...
55 public function importStatus($status)
57 // Hacktastic: filter out stuff coming from this StatusNet
58 $source = mb_strtolower(common_config('integration', 'source'));
60 if (preg_match("/$source/", mb_strtolower($status->source))) {
61 common_debug(__METHOD__ . ' - Skipping import of status ' .
62 twitter_id($status) . " with source {$source}");
66 // Don't save it if the user is protected
67 // FIXME: save it but treat it as private
68 if ($status->user->protected) {
72 $notice = $this->saveStatus($status);
79 return get_class($this);
82 function saveStatus($status)
84 $profile = $this->ensureProfile($status->user);
86 if (empty($profile)) {
87 common_log(LOG_ERR, __METHOD__ . ' - Problem saving notice. No associated Profile.');
91 $statusId = twitter_id($status);
92 $statusUri = $this->makeStatusURI($status->user->screen_name, $statusId);
94 // check to see if we've already imported the status
95 $n2s = Notice_to_status::getKV('status_id', $statusId);
100 __METHOD__ . " - Ignoring duplicate import: {$statusId}"
102 return Notice::getKV('id', $n2s->notice_id);
105 $dupe = Notice::getKV('uri', $statusUri);
106 if($dupe instanceof Notice) {
107 // Add it to our record
108 Notice_to_status::saveNew($dupe->id, $statusId);
111 __METHOD__ . " - Ignoring duplicate import: {$statusId}"
116 // If it's a retweet, save it as a repeat!
117 if (!empty($status->retweeted_status)) {
118 common_log(LOG_INFO, "Status {$statusId} is a retweet of " . twitter_id($status->retweeted_status) . ".");
119 $original = $this->saveStatus($status->retweeted_status);
120 if (empty($original)) {
123 $author = $original->getProfile();
124 // TRANS: Message used to repeat a notice. RT is the abbreviation of 'retweet'.
125 // TRANS: %1$s is the repeated user's name, %2$s is the repeated notice.
126 $content = sprintf(_m('RT @%1$s %2$s'),
130 if (Notice::contentTooLong($content)) {
131 $contentlimit = Notice::maxContent();
132 $content = mb_substr($content, 0, $contentlimit - 4) . ' ...';
135 $repeat = Notice::saveNew($profile->id,
138 array('repeat_of' => $original->id,
140 'is_local' => Notice::GATEWAY));
141 common_log(LOG_INFO, "Saved {$repeat->id} as a repeat of {$original->id}");
142 Notice_to_status::saveNew($repeat->id, $statusId);
147 $notice = new Notice();
149 $notice->profile_id = $profile->id;
150 $notice->uri = $statusUri;
151 $notice->url = $statusUri;
152 $notice->verb = ActivityVerb::POST;
153 $notice->created = strftime(
155 strtotime($status->created_at)
158 $notice->source = 'twitter';
160 $notice->reply_to = null;
162 $replyTo = twitter_id($status, 'in_reply_to_status_id');
163 if (!empty($replyTo)) {
164 common_log(LOG_INFO, "Status {$statusId} is a reply to status {$replyTo}");
165 $n2s = Notice_to_status::getKV('status_id', $replyTo);
167 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
169 $reply = Notice::getKV('id', $n2s->notice_id);
171 common_log(LOG_INFO, "Couldn't find local notice for status {$replyTo}");
173 common_log(LOG_INFO, "Found local notice {$reply->id} for status {$replyTo}");
174 $notice->reply_to = $reply->id;
175 $notice->conversation = $reply->conversation;
180 $notice->is_local = Notice::GATEWAY;
182 $notice->content = html_entity_decode($this->linkify($status, FALSE), ENT_QUOTES, 'UTF-8');
183 $notice->rendered = $this->linkify($status, TRUE);
185 if (Event::handle('StartNoticeSave', array(&$notice))) {
187 $id = $notice->insert();
190 common_log_db_error($notice, 'INSERT', __FILE__);
191 common_log(LOG_ERR, __METHOD__ . ' - Problem saving notice.');
194 if (empty($notice->conversation)) {
195 $orig = clone($notice);
196 $conv = Conversation::create($notice);
197 common_log(LOG_INFO, "No known conversation for status {$statusId} so a new one ({$conv->id}) was created.");
198 $notice->conversation = $conv->id;
199 $notice->update($orig);
202 Event::handle('EndNoticeSave', array($notice));
205 Notice_to_status::saveNew($notice->id, $statusId);
207 $this->saveStatusMentions($notice, $status);
208 $this->saveStatusAttachments($notice, $status);
210 $notice->blowOnInsert();
216 * Make an URI for a status.
218 * @param object $status status object
222 function makeStatusURI($username, $id)
224 return 'http://twitter.com/#!/'
232 * Look up a Profile by profileurl field. Profile::getKV() was
233 * not working consistently.
235 * @param string $nickname local nickname of the Twitter user
236 * @param string $profileurl the profile url
238 * @return mixed value the first Profile with that url, or null
240 protected function getProfileByUrl($nickname, $profileurl)
242 $profile = new Profile();
243 $profile->nickname = $nickname;
244 $profile->profileurl = $profileurl;
247 if (!$profile->find(true)) {
248 throw new NoResultException($profile);
253 protected function ensureProfile($twuser)
255 // check to see if there's already a profile for this user
256 $profileurl = 'http://twitter.com/' . $twuser->screen_name;
258 $profile = $this->getProfileByUrl($twuser->screen_name, $profileurl);
259 $this->updateAvatar($twuser, $profile);
261 } catch (NoResultException $e) {
262 common_debug(__METHOD__ . ' - Adding profile and remote profile ' .
263 "for Twitter user: $profileurl.");
266 $profile = new Profile();
267 $profile->query("BEGIN");
268 $profile->nickname = $twuser->screen_name;
269 $profile->fullname = $twuser->name;
270 $profile->homepage = $twuser->url;
271 $profile->bio = $twuser->description;
272 $profile->location = $twuser->location;
273 $profile->profileurl = $profileurl;
274 $profile->created = common_sql_now();
277 $id = $profile->insert(); // insert _should_ throw exception on failure
279 throw new Exception('Failed insert');
281 } catch(Exception $e) {
282 common_log(LOG_WARNING, __METHOD__ . " Couldn't insert profile: " . $e->getMessage());
283 common_log_db_error($profile, 'INSERT', __FILE__);
284 $profile->query("ROLLBACK");
288 $profile->query("COMMIT");
289 $this->updateAvatar($twuser, $profile);
294 * Checks whether we have to update the profile's avatar
296 * @return true when updated, false on failure, null when no action taken
298 protected function updateAvatar($twuser, Profile $profile)
300 $path_parts = pathinfo($twuser->profile_image_url);
301 $ext = isset($path_parts['extension'])
302 ? '.'.$path_parts['extension']
303 : ''; // some lack extension
304 $img_root = basename($path_parts['basename'], '_normal'.$ext); // cut off extension
305 $filename = "Twitter_{$twuser->id}_{$img_root}_{$this->avatarsizename}{$ext}";
308 $avatar = Avatar::getUploaded($profile);
309 if ($avatar->filename === $filename) {
312 common_debug(__METHOD__ . " - Updating profile avatar (profile_id={$profile->id}) " .
313 "from {$avatar->filename} to {$filename}");
314 // else we continue with creating a new avatar
315 } catch (NoAvatarException $e) {
316 // Avatar was not found. We can catch NoAvatarException or FileNotFoundException
317 // but generally we just want to continue creating a new avatar.
318 common_debug(__METHOD__ . " - No avatar found for (profile_id={$profile->id})");
321 $url = "{$path_parts['dirname']}/{$img_root}_{$this->avatarsizename}{$ext}";
322 $mediatype = $this->getMediatype(mb_substr($ext, 1));
325 $this->newAvatar($profile, $url, $filename, $mediatype);
326 } catch (Exception $e) {
327 if (file_exists(Avatar::path($filename))) {
328 unlink(Avatar::path($filename));
336 protected function getMediatype($ext)
340 switch (strtolower($ext)) {
343 $mediatype = 'image/jpeg';
346 $mediatype = 'image/gif';
349 $mediatype = 'image/png';
355 protected function newAvatar(Profile $profile, $url, $filename, $mediatype)
357 // Clear out old avatars, won't do anything if there are none
358 Avatar::deleteFromProfile($profile);
360 // throws exception if unable to fetch
361 $this->fetchRemoteUrl($url, Avatar::path($filename));
363 $avatar = new Avatar();
364 $avatar->profile_id = $profile->id;
365 $avatar->original = 1; // this is an original/"uploaded" avatar
366 $avatar->mediatype = $mediatype;
367 $avatar->filename = $filename;
368 $avatar->url = Avatar::url($filename);
369 $avatar->width = $this->avatarsize;
370 $avatar->height = $this->avatarsize;
372 $avatar->created = common_sql_now();
374 $id = $avatar->insert();
377 common_log(LOG_WARNING, __METHOD__ . " Couldn't insert avatar - " . $e->getMessage());
378 common_log_db_error($avatar, 'INSERT', __FILE__);
379 throw new ServerException('Could not insert avatar');
382 common_debug(__METHOD__ . " - Saved new avatar for {$profile->id}.");
388 * Fetch a remote avatar image and save to local storage.
390 * @param string $url avatar source URL
391 * @param string $filename bare local filename for download
392 * @return bool true on success, false on failure
394 protected function fetchRemoteUrl($url, $filename)
396 common_debug(__METHOD__ . " - Fetching Twitter avatar: {$url} to {$filename}");
397 $request = HTTPClient::start();
398 $request->setConfig('connect_timeout', 3); // I had problems with throttling
399 $request->setConfig('timeout', 6); // and locking the process sucks.
400 $response = $request->get($url);
401 if ($response->isOk()) {
402 if (!file_put_contents($filename, $response->getBody())) {
403 throw new ServerException('Failed saving fetched file');
406 throw new Exception('Unexpected HTTP status code');
415 function linkify($status, $html = FALSE)
417 $text = $status->text;
419 if (empty($status->entities)) {
420 $statusId = twitter_id($status);
421 common_log(LOG_WARNING, "No entities data for {$statusId}; trying to fake up links ourselves.");
422 $text = common_replace_urls_callback($text, 'common_linkify');
423 $text = preg_replace_callback('/(^|\"\;|\'|\(|\[|\{|\s+)#([\pL\pN_\-\.]{1,64})/',
424 function ($m) { return $m[1].'#'.TwitterStatusFetcher::tagLink($m[2]); }, $text);
425 $text = preg_replace_callback('/(^|\s+)@([a-z0-9A-Z_]{1,64})/',
426 function ($m) { return $m[1].'@'.TwitterStatusFetcher::atLink($m[2]); }, $text);
430 // Move all the entities into order so we can
431 // replace them and escape surrounding plaintext
434 $toReplace = array();
436 if (!empty($status->entities->urls)) {
437 foreach ($status->entities->urls as $url) {
438 $toReplace[$url->indices[0]] = array(self::URL, $url);
442 if (!empty($status->entities->hashtags)) {
443 foreach ($status->entities->hashtags as $hashtag) {
444 $toReplace[$hashtag->indices[0]] = array(self::HASHTAG, $hashtag);
448 if (!empty($status->entities->user_mentions)) {
449 foreach ($status->entities->user_mentions as $mention) {
450 $toReplace[$mention->indices[0]] = array(self::MENTION, $mention);
454 // sort in forward order by key
461 foreach ($toReplace as $part) {
462 list($type, $object) = $part;
463 $start = $object->indices[0];
464 $end = $object->indices[1];
465 if ($cursor < $start) {
466 // Copy in the preceding plaintext
467 $result .= $this->twitEscape(mb_substr($text, $cursor, $start - $cursor));
470 $orig = $this->twitEscape(mb_substr($text, $start, $end - $start));
473 $linkText = $this->makeUrlLink($object, $orig, $html);
477 $linkText = $this->makeHashtagLink($object, $orig);
484 $linkText = $this->makeMentionLink($object, $orig);
493 $result .= $linkText;
496 $last = $this->twitEscape(mb_substr($text, $cursor));
502 function twitEscape($str)
504 // Twitter seems to preemptive turn < and > into < and >
505 // but doesn't for &, so while you may have some magic protection
506 // against XSS by not bothing to escape manually, you still get
507 // invalid XHTML. Thanks!
509 // Looks like their web interface pretty much sends anything
510 // through intact, so.... to do equivalent, decode all entities
511 // and then re-encode the special ones.
512 return htmlspecialchars(html_entity_decode($str, ENT_COMPAT, 'UTF-8'));
515 function makeUrlLink($object, $orig, $html)
518 return '<a href="'.htmlspecialchars($object->expanded_url).'" class="extlink">'.htmlspecialchars($object->display_url).'</a>';
520 return htmlspecialchars($object->expanded_url);
524 function makeHashtagLink($object, $orig)
526 return "#" . self::tagLink($object->text, substr($orig, 1));
529 function makeMentionLink($object, $orig)
531 return "@".self::atLink($object->screen_name, $object->name, substr($orig, 1));
534 static function tagLink($tag, $orig)
536 return "<a href='https://twitter.com/search?q=%23{$tag}' class='hashtag'>{$orig}</a>";
539 static function atLink($screenName, $fullName, $orig)
541 if (!empty($fullName)) {
542 return "<a href='http://twitter.com/#!/{$screenName}' title='{$fullName}'>{$orig}</a>";
544 return "<a href='http://twitter.com/#!/{$screenName}'>{$orig}</a>";
548 function saveStatusMentions($notice, $status)
552 if (empty($status->entities) || empty($status->entities->user_mentions)) {
556 foreach ($status->entities->user_mentions as $mention) {
558 $flink = Foreign_link::getByForeignID($mention->id, TWITTER_SERVICE);
559 $user = $flink->getUser();
560 $reply = new Reply();
561 $reply->notice_id = $notice->id;
562 $reply->profile_id = $user->id;
563 $reply->modified = $notice->created;
564 common_log(LOG_INFO, __METHOD__ . ": saving reply: notice {$notice->id} to profile {$user->id}");
565 $id = $reply->insert();
566 } catch (NoResultException $e) {
567 common_log(LOG_WARNING, 'No local user found for Foreign_link with local User id: '.$flink->user_id);
573 * Record URL links from the notice. Needed to get thumbnail records
574 * for referenced photo and video posts, etc.
576 * @param Notice $notice
577 * @param object $status
579 function saveStatusAttachments(Notice $notice, $status)
581 if (common_config('attachments', 'process_links')) {
582 if (!empty($status->entities) && !empty($status->entities->urls)) {
583 foreach ($status->entities->urls as $url) {
585 File::processNew($url->url, $notice);
586 } catch (ServerException $e) {
587 // Could not process attached URL