3 * Laconica - a distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, Control Yourself, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 if (!defined('LACONICA')) {
24 class TwitterapiAction extends Action
32 * @param array $args Web and URL arguments
34 * @return boolean false if user doesn't exist
37 function prepare($args)
39 parent::prepare($args);
46 * @param array $args Arguments from $_REQUEST
51 function handle($args)
53 parent::handle($args);
57 * Overrides XMLOutputter::element to write booleans as strings (true|false).
58 * See that method's documentation for more info.
60 * @param string $tag Element type or tagname
61 * @param array $attrs Array of element attributes, as
63 * @param string $content string content of the element
67 function element($tag, $attrs=null, $content=null)
69 if (is_bool($content)) {
70 $content = ($content ? 'true' : 'false');
73 return parent::element($tag, $attrs, $content);
76 function twitter_user_array($profile, $get_notice=false)
78 $twitter_user = array();
80 $twitter_user['id'] = intval($profile->id);
81 $twitter_user['name'] = $profile->getBestName();
82 $twitter_user['screen_name'] = $profile->nickname;
83 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
84 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
86 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
87 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
88 Avatar::defaultImage(AVATAR_STREAM_SIZE);
90 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
91 $twitter_user['protected'] = false; # not supported by Laconica yet
92 $twitter_user['followers_count'] = $this->count_subscriptions($profile);
94 // To be supported soon...
95 $twitter_user['profile_background_color'] = '';
96 $twitter_user['profile_text_color'] = '';
97 $twitter_user['profile_link_color'] = '';
98 $twitter_user['profile_sidebar_fill_color'] = '';
99 $twitter_user['profile_sidebar_border_color'] = '';
101 $subbed = DB_DataObject::factory('subscription');
102 $subbed->subscriber = $profile->id;
103 $subbed_count = (int) $subbed->count() - 1;
104 $twitter_user['friends_count'] = (is_int($subbed_count)) ? $subbed_count : 0;
106 $twitter_user['created_at'] = $this->date_twitter($profile->created);
108 $faves = DB_DataObject::factory('fave');
109 $faves->user_id = $user->id;
110 $faves_count = (int) $faves->count();
111 $twitter_user['favourites_count'] = $faves_count; // British spelling!
113 // Need to pull up the user for some of this
114 $user = User::staticGet($profile->id);
118 if ($user->timezone) {
119 $timezone = $user->timezone;
123 $t->setTimezone(new DateTimeZone($timezone));
125 $twitter_user['utc_offset'] = $t->format('Z');
126 $twitter_user['time_zone'] = $timezone;
128 // To be supported some day, perhaps
129 $twitter_user['profile_background_image_url'] = '';
130 $twitter_user['profile_background_tile'] = false;
132 $notices = DB_DataObject::factory('notice');
133 $notices->profile_id = $profile->id;
134 $notice_count = (int) $notices->count();
136 $twitter_user['statuses_count'] = (is_int($notice_count)) ? $notice_count : 0;
138 // Is the requesting user following this user?
139 $twitter_user['following'] = false;
140 $twitter_user['notifications'] = false;
142 if (isset($apidata['user'])) {
144 $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
147 $sub = Subscription::pkeyGet(array('subscriber' =>
148 $apidata['user']->id, 'subscribed' => $profile->id));
151 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
156 $notice = $profile->getCurrentNotice();
159 $twitter_user['status'] = $this->twitter_status_array($notice, false);
163 return $twitter_user;
166 function twitter_status_array($notice, $include_user=true)
168 $profile = $notice->getProfile();
170 $twitter_status = array();
171 $twitter_status['text'] = $notice->content;
172 $twitter_status['truncated'] = false; # Not possible on Laconica
173 $twitter_status['created_at'] = $this->date_twitter($notice->created);
174 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
175 intval($notice->reply_to) : null;
176 $twitter_status['source'] = $this->source_link($notice->source);
177 $twitter_status['id'] = intval($notice->id);
179 $replier_profile = null;
181 if ($notice->reply_to) {
182 $reply = Notice::staticGet(intval($notice->reply_to));
184 $replier_profile = $reply->getProfile();
188 $twitter_status['in_reply_to_user_id'] =
189 ($replier_profile) ? intval($replier_profile->id) : null;
190 $twitter_status['in_reply_to_screen_name'] =
191 ($replier_profile) ? $replier_profile->nickname : null;
193 if (isset($this->auth_user)) {
194 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
196 $twitter_status['favorited'] = false;
200 # Don't get notice (recursive!)
201 $twitter_user = $this->twitter_user_array($profile, false);
202 $twitter_status['user'] = $twitter_user;
205 return $twitter_status;
208 function twitter_rss_entry_array($notice)
211 $profile = $notice->getProfile();
214 # We trim() to avoid extraneous whitespace in the output
216 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
217 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
218 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
219 $entry['published'] = common_date_iso8601($notice->created);
221 $taguribase = common_config('integration', 'taguri');
222 $entry['id'] = "tag:$taguribase:$entry[link]";
224 $entry['updated'] = $entry['published'];
225 $entry['author'] = $profile->getBestName();
228 $entry['description'] = $entry['content'];
229 $entry['pubDate'] = common_date_rfc2822($notice->created);
230 $entry['guid'] = $entry['link'];
235 function twitter_rss_dmsg_array($message)
240 $entry['title'] = sprintf('Message from %s to %s',
241 $message->getFrom()->nickname, $message->getTo()->nickname);
243 $entry['content'] = common_xml_safe_str(trim($message->content));
244 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
245 $entry['published'] = common_date_iso8601($message->created);
247 $taguribase = common_config('integration', 'taguri');
249 $entry['id'] = "tag:$taguribase,:$entry[link]";
250 $entry['updated'] = $entry['published'];
251 $entry['author'] = $message->getFrom()->getBestName();
254 $entry['description'] = $entry['content'];
255 $entry['pubDate'] = common_date_rfc2822($message->created);
256 $entry['guid'] = $entry['link'];
261 function twitter_dmsg_array($message)
263 $twitter_dm = array();
265 $from_profile = $message->getFrom();
266 $to_profile = $message->getTo();
268 $twitter_dm['id'] = $message->id;
269 $twitter_dm['sender_id'] = $message->from_profile;
270 $twitter_dm['text'] = trim($message->content);
271 $twitter_dm['recipient_id'] = $message->to_profile;
272 $twitter_dm['created_at'] = $this->date_twitter($message->created);
273 $twitter_dm['sender_screen_name'] = $from_profile->nickname;
274 $twitter_dm['recipient_screen_name'] = $to_profile->nickname;
275 $twitter_dm['sender'] = $this->twitter_user_array($from_profile, false);
276 $twitter_dm['recipient'] = $this->twitter_user_array($to_profile, false);
281 function show_twitter_xml_status($twitter_status)
283 $this->elementStart('status');
284 foreach($twitter_status as $element => $value) {
287 $this->show_twitter_xml_user($twitter_status['user']);
290 $this->element($element, null, common_xml_safe_str($value));
293 $this->element($element, null, $value);
296 $this->elementEnd('status');
299 function show_twitter_xml_user($twitter_user, $role='user')
301 $this->elementStart($role);
302 foreach($twitter_user as $element => $value) {
303 if ($element == 'status') {
304 $this->show_twitter_xml_status($twitter_user['status']);
306 $this->element($element, null, $value);
309 $this->elementEnd($role);
312 function show_twitter_rss_item($entry)
314 $this->elementStart('item');
315 $this->element('title', null, $entry['title']);
316 $this->element('description', null, $entry['description']);
317 $this->element('pubDate', null, $entry['pubDate']);
318 $this->element('guid', null, $entry['guid']);
319 $this->element('link', null, $entry['link']);
320 $this->elementEnd('item');
323 function show_json_objects($objects)
325 print(json_encode($objects));
328 function show_single_xml_status($notice)
330 $this->init_document('xml');
331 $twitter_status = $this->twitter_status_array($notice);
332 $this->show_twitter_xml_status($twitter_status);
333 $this->end_document('xml');
336 function show_single_json_status($notice)
338 $this->init_document('json');
339 $status = $this->twitter_status_array($notice);
340 $this->show_json_objects($status);
341 $this->end_document('json');
344 function show_single_xml_dmsg($message)
346 $this->init_document('xml');
347 $dmsg = $this->twitter_dmsg_array($message);
348 $this->show_twitter_xml_dmsg($dmsg);
349 $this->end_document('xml');
352 function show_single_json_dmsg($message)
354 $this->init_document('json');
355 $dmsg = $this->twitter_dmsg_array($message);
356 $this->show_json_objects($dmsg);
357 $this->end_document('json');
360 function show_twitter_xml_dmsg($twitter_dm)
362 $this->elementStart('direct_message');
363 foreach($twitter_dm as $element => $value) {
367 $this->show_twitter_xml_user($value, $element);
370 $this->element($element, null, common_xml_safe_str($value));
373 $this->element($element, null, $value);
376 $this->elementEnd('direct_message');
379 function show_xml_timeline($notice)
382 $this->init_document('xml');
383 $this->elementStart('statuses', array('type' => 'array'));
385 if (is_array($notice)) {
386 foreach ($notice as $n) {
387 $twitter_status = $this->twitter_status_array($n);
388 $this->show_twitter_xml_status($twitter_status);
391 while ($notice->fetch()) {
392 $twitter_status = $this->twitter_status_array($notice);
393 $this->show_twitter_xml_status($twitter_status);
397 $this->elementEnd('statuses');
398 $this->end_document('xml');
401 function show_rss_timeline($notice, $title, $link, $subtitle, $suplink=null)
404 $this->init_document('rss');
406 $this->elementStart('channel');
407 $this->element('title', null, $title);
408 $this->element('link', null, $link);
409 if (!is_null($suplink)) {
410 # For FriendFeed's SUP protocol
411 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
412 'rel' => 'http://api.friendfeed.com/2008/03#sup',
414 'type' => 'application/json'));
416 $this->element('description', null, $subtitle);
417 $this->element('language', null, 'en-us');
418 $this->element('ttl', null, '40');
420 if (is_array($notice)) {
421 foreach ($notice as $n) {
422 $entry = $this->twitter_rss_entry_array($n);
423 $this->show_twitter_rss_item($entry);
426 while ($notice->fetch()) {
427 $entry = $this->twitter_rss_entry_array($notice);
428 $this->show_twitter_rss_item($entry);
432 $this->elementEnd('channel');
433 $this->end_twitter_rss();
436 function show_atom_timeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
439 $this->init_document('atom');
441 $this->element('title', null, $title);
442 $this->element('id', null, $id);
443 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
445 if (!is_null($suplink)) {
446 # For FriendFeed's SUP protocol
447 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
449 'type' => 'application/json'));
452 if (!is_null($selfuri)) {
453 $this->element('link', array('href' => $selfuri,
454 'rel' => 'self', 'type' => 'application/atom+xml'), null);
457 $this->element('updated', null, common_date_iso8601('now'));
458 $this->element('subtitle', null, $subtitle);
460 if (is_array($notice)) {
461 foreach ($notice as $n) {
462 $this->raw($n->asAtomEntry());
465 while ($notice->fetch()) {
466 $this->raw($notice->asAtomEntry());
470 $this->end_document('atom');
474 function show_json_timeline($notice)
477 $this->init_document('json');
481 if (is_array($notice)) {
482 foreach ($notice as $n) {
483 $twitter_status = $this->twitter_status_array($n);
484 array_push($statuses, $twitter_status);
487 while ($notice->fetch()) {
488 $twitter_status = $this->twitter_status_array($notice);
489 array_push($statuses, $twitter_status);
493 $this->show_json_objects($statuses);
495 $this->end_document('json');
498 // Anyone know what date format this is?
499 // Twitter's dates look like this: "Mon Jul 14 23:52:38 +0000 2008" -- Zach
500 function date_twitter($dt)
503 return date("D M d H:i:s O Y", $t);
506 // XXX: Candidate for a general utility method somewhere?
507 function count_subscriptions($profile)
511 $sub = new Subscription();
512 $sub->subscribed = $profile->id;
514 $count = $sub->find();
523 function init_document($type='xml')
527 header('Content-Type: application/xml; charset=utf-8');
531 header('Content-Type: application/json; charset=utf-8');
533 // Check for JSONP callback
534 $callback = $this->arg('callback');
536 print $callback . '(';
540 header("Content-Type: application/rss+xml; charset=utf-8");
541 $this->init_twitter_rss();
544 header('Content-Type: application/atom+xml; charset=utf-8');
545 $this->init_twitter_atom();
548 $this->clientError(_('Not a supported data format.'));
555 function end_document($type='xml')
563 // Check for JSONP callback
564 $callback = $this->arg('callback');
570 $this->end_twitter_rss();
573 $this->end_twitter_rss();
576 $this->clientError(_('Not a supported data format.'));
582 function clientError($msg, $code = 400, $content_type = 'json')
585 static $status = array(400 => 'Bad Request',
586 401 => 'Unauthorized',
587 402 => 'Payment Required',
590 405 => 'Method Not Allowed',
591 406 => 'Not Acceptable',
592 407 => 'Proxy Authentication Required',
593 408 => 'Request Timeout',
596 411 => 'Length Required',
597 412 => 'Precondition Failed',
598 413 => 'Request Entity Too Large',
599 414 => 'Request-URI Too Long',
600 415 => 'Unsupported Media Type',
601 416 => 'Requested Range Not Satisfiable',
602 417 => 'Expectation Failed');
604 $action = $this->trimmed('action');
606 common_debug("User error '$code' on '$action': $msg", __FILE__);
608 if (!array_key_exists($code, $status)) {
612 $status_string = $status[$code];
613 header('HTTP/1.1 '.$code.' '.$status_string);
615 if ($content_type == 'xml') {
616 $this->init_document('xml');
617 $this->elementStart('hash');
618 $this->element('error', null, $msg);
619 $this->element('request', null, $_SERVER['REQUEST_URI']);
620 $this->elementEnd('hash');
621 $this->end_document('xml');
623 $this->init_document('json');
624 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
625 print(json_encode($error_array));
626 $this->end_document('json');
631 function init_twitter_rss()
634 $this->elementStart('rss', array('version' => '2.0'));
637 function end_twitter_rss()
639 $this->elementEnd('rss');
643 function init_twitter_atom()
646 // FIXME: don't hardcode the language here!
647 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
648 'xml:lang' => 'en-US',
649 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
652 function end_twitter_atom()
654 $this->elementEnd('feed');
658 function show_profile($profile, $content_type='xml', $notice=null)
660 $profile_array = $this->twitter_user_array($profile, true);
661 switch ($content_type) {
663 $this->show_twitter_xml_user($profile_array);
666 $this->show_json_objects($profile_array);
669 $this->clientError(_('Not a supported data format.'));
675 function get_user($id, $apidata=null)
679 // Twitter supports these other ways of passing the user ID
680 if (is_numeric($this->arg('id'))) {
681 return User::staticGet($this->arg('id'));
682 } else if ($this->arg('id')) {
683 $nickname = common_canonical_nickname($this->arg('id'));
684 return User::staticGet('nickname', $nickname);
685 } else if ($this->arg('user_id')) {
686 // This is to ensure that a non-numeric user_id still
687 // overrides screen_name even if it doesn't get used
688 if (is_numeric($this->arg('user_id'))) {
689 return User::staticGet('id', $this->arg('user_id'));
691 } else if ($this->arg('screen_name')) {
692 $nickname = common_canonical_nickname($this->arg('screen_name'));
693 return User::staticGet('nickname', $nickname);
695 // Fall back to trying the currently authenticated user
696 return $apidata['user'];
699 } else if (is_numeric($id)) {
700 return User::staticGet($id);
702 $nickname = common_canonical_nickname($id);
703 return User::staticGet('nickname', $nickname);
707 function get_profile($id)
709 if (is_numeric($id)) {
710 return Profile::staticGet($id);
712 $user = User::staticGet('nickname', $id);
714 return $user->getProfile();
721 function source_link($source)
723 $source_name = _($source);
732 $ns = Notice_source::staticGet($source);
734 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
742 * Returns query argument or default value if not found. Certain
743 * parameters used throughout the API are lightly scrubbed and
744 * bounds checked. This overrides Action::arg().
746 * @param string $key requested argument
747 * @param string $def default value to return if $key is not provided
751 function arg($key, $def=null)
754 // XXX: Do even more input validation/scrubbing?
756 if (array_key_exists($key, $this->args)) {
759 $page = (int)$this->args['page'];
760 return ($page < 1) ? 1 : $page;
762 $count = (int)$this->args['count'];
765 } elseif ($count > 200) {
771 $since_id = (int)$this->args['since_id'];
772 return ($since_id < 1) ? 0 : $since_id;
774 $max_id = (int)$this->args['max_id'];
775 return ($max_id < 1) ? 0 : $max_id;
777 return strtotime($this->args['since']);
779 return parent::arg($key, $def);