3 * StatusNet, the distributed open-source microblogging tool
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Dan Moore <dan@moore.cx>
26 * @author Evan Prodromou <evan@status.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Toby Inkster <mail@tobyinkster.co.uk>
29 * @author Zach Copley <zach@status.net>
30 * @copyright 2009 StatusNet, Inc.
31 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
32 * @link http://status.net/
35 if (!defined('STATUSNET')) {
40 * Contains most of the Twitter-compatible API output functions.
44 * @author Craig Andrews <candrews@integralblue.com>
45 * @author Dan Moore <dan@moore.cx>
46 * @author Evan Prodromou <evan@status.net>
47 * @author Jeffery To <jeffery.to@gmail.com>
48 * @author Toby Inkster <mail@tobyinkster.co.uk>
49 * @author Zach Copley <zach@status.net>
50 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51 * @link http://status.net/
54 class ApiAction extends Action
58 var $auth_user = null;
68 * @param array $args Web and URL arguments
70 * @return boolean false if user doesn't exist
73 function prepare($args)
75 parent::prepare($args);
77 $this->format = $this->arg('format');
78 $this->page = (int)$this->arg('page', 1);
79 $this->count = (int)$this->arg('count', 20);
80 $this->max_id = (int)$this->arg('max_id', 0);
81 $this->since_id = (int)$this->arg('since_id', 0);
82 $this->since = $this->arg('since');
90 * @param array $args Arguments from $_REQUEST
95 function handle($args)
97 parent::handle($args);
101 * Overrides XMLOutputter::element to write booleans as strings (true|false).
102 * See that method's documentation for more info.
104 * @param string $tag Element type or tagname
105 * @param array $attrs Array of element attributes, as
107 * @param string $content string content of the element
111 function element($tag, $attrs=null, $content=null)
113 if (is_bool($content)) {
114 $content = ($content ? 'true' : 'false');
117 return parent::element($tag, $attrs, $content);
120 function twitterUserArray($profile, $get_notice=false)
122 $twitter_user = array();
124 $twitter_user['id'] = intval($profile->id);
125 $twitter_user['name'] = $profile->getBestName();
126 $twitter_user['screen_name'] = $profile->nickname;
127 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
128 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
130 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
131 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
132 Avatar::defaultImage(AVATAR_STREAM_SIZE);
134 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
135 $twitter_user['protected'] = false; # not supported by StatusNet yet
136 $twitter_user['followers_count'] = $profile->subscriberCount();
139 $user = $profile->getUser();
141 // Note: some profiles don't have an associated user
144 $design = $user->getDesign();
147 if (empty($design)) {
148 $design = Design::siteDesign();
151 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
152 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
153 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
154 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
155 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
156 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
157 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
158 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
159 $twitter_user['profile_sidebar_border_color'] = '';
161 $twitter_user['friends_count'] = $profile->subscriptionCount();
163 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
165 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
169 if ($user->timezone) {
170 $timezone = $user->timezone;
174 $t->setTimezone(new DateTimeZone($timezone));
176 $twitter_user['utc_offset'] = $t->format('Z');
177 $twitter_user['time_zone'] = $timezone;
179 $twitter_user['profile_background_image_url']
180 = empty($design->backgroundimage)
181 ? '' : ($design->disposition & BACKGROUND_ON)
182 ? Design::url($design->backgroundimage) : '';
184 $twitter_user['profile_background_tile']
185 = empty($design->disposition)
186 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
188 $twitter_user['statuses_count'] = $profile->noticeCount();
190 // Is the requesting user following this user?
191 $twitter_user['following'] = false;
192 $twitter_user['notifications'] = false;
194 if (isset($this->auth_user)) {
196 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
199 $sub = Subscription::pkeyGet(array('subscriber' =>
200 $this->auth_user->id,
201 'subscribed' => $profile->id));
204 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
209 $notice = $profile->getCurrentNotice();
212 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
216 return $twitter_user;
219 function twitterStatusArray($notice, $include_user=true)
221 $base = $this->twitterSimpleStatusArray($notice, $include_user);
223 if (!empty($notice->repeat_of)) {
224 $original = Notice::staticGet('id', $notice->repeat_of);
225 if (!empty($original)) {
226 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
227 $base['retweeted_status'] = $original_array;
234 function twitterSimpleStatusArray($notice, $include_user=true)
236 $profile = $notice->getProfile();
238 $twitter_status = array();
239 $twitter_status['text'] = $notice->content;
240 $twitter_status['truncated'] = false; # Not possible on StatusNet
241 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
242 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
243 intval($notice->reply_to) : null;
244 $twitter_status['source'] = $this->sourceLink($notice->source);
245 $twitter_status['id'] = intval($notice->id);
247 $replier_profile = null;
249 if ($notice->reply_to) {
250 $reply = Notice::staticGet(intval($notice->reply_to));
252 $replier_profile = $reply->getProfile();
256 $twitter_status['in_reply_to_user_id'] =
257 ($replier_profile) ? intval($replier_profile->id) : null;
258 $twitter_status['in_reply_to_screen_name'] =
259 ($replier_profile) ? $replier_profile->nickname : null;
261 if (isset($notice->lat) && isset($notice->lon)) {
262 // This is the format that GeoJSON expects stuff to be in
263 $twitter_status['geo'] = array('type' => 'Point',
264 'coordinates' => array((float) $notice->lat,
265 (float) $notice->lon));
267 $twitter_status['geo'] = null;
270 if (isset($this->auth_user)) {
271 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
273 $twitter_status['favorited'] = false;
277 $attachments = $notice->attachments();
279 if (!empty($attachments)) {
281 $twitter_status['attachments'] = array();
283 foreach ($attachments as $attachment) {
284 if ($attachment->isEnclosure()) {
285 $enclosure = array();
286 $enclosure['url'] = $attachment->url;
287 $enclosure['mimetype'] = $attachment->mimetype;
288 $enclosure['size'] = $attachment->size;
289 $twitter_status['attachments'][] = $enclosure;
295 # Don't get notice (recursive!)
296 $twitter_user = $this->twitterUserArray($profile, false);
297 $twitter_status['user'] = $twitter_user;
300 return $twitter_status;
303 function twitterGroupArray($group)
305 $twitter_group=array();
306 $twitter_group['id']=$group->id;
307 $twitter_group['url']=$group->permalink();
308 $twitter_group['nickname']=$group->nickname;
309 $twitter_group['fullname']=$group->fullname;
310 $twitter_group['homepage_url']=$group->homepage_url;
311 $twitter_group['original_logo']=$group->original_logo;
312 $twitter_group['homepage_logo']=$group->homepage_logo;
313 $twitter_group['stream_logo']=$group->stream_logo;
314 $twitter_group['mini_logo']=$group->mini_logo;
315 $twitter_group['homepage']=$group->homepage;
316 $twitter_group['description']=$group->description;
317 $twitter_group['location']=$group->location;
318 $twitter_group['created']=$this->dateTwitter($group->created);
319 $twitter_group['modified']=$this->dateTwitter($group->modified);
320 return $twitter_group;
323 function twitterRssGroupArray($group)
326 $entry['content']=$group->description;
327 $entry['title']=$group->nickname;
328 $entry['link']=$group->permalink();
329 $entry['published']=common_date_iso8601($group->created);
330 $entry['updated']==common_date_iso8601($group->modified);
331 $taguribase = common_config('integration', 'groupuri');
332 $entry['id'] = "group:$groupuribase:$entry[link]";
334 $entry['description'] = $entry['content'];
335 $entry['pubDate'] = common_date_rfc2822($group->created);
336 $entry['guid'] = $entry['link'];
341 function twitterRssEntryArray($notice)
343 $profile = $notice->getProfile();
346 // We trim() to avoid extraneous whitespace in the output
348 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
349 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
350 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
351 $entry['published'] = common_date_iso8601($notice->created);
353 $taguribase = common_config('integration', 'taguri');
354 $entry['id'] = "tag:$taguribase:$entry[link]";
356 $entry['updated'] = $entry['published'];
357 $entry['author'] = $profile->getBestName();
360 $attachments = $notice->attachments();
361 $enclosures = array();
363 foreach ($attachments as $attachment) {
364 $enclosure_o=$attachment->getEnclosure();
366 $enclosure = array();
367 $enclosure['url'] = $enclosure_o->url;
368 $enclosure['mimetype'] = $enclosure_o->mimetype;
369 $enclosure['size'] = $enclosure_o->size;
370 $enclosures[] = $enclosure;
374 if (!empty($enclosures)) {
375 $entry['enclosures'] = $enclosures;
379 $tag = new Notice_tag();
380 $tag->notice_id = $notice->id;
382 $entry['tags']=array();
383 while ($tag->fetch()) {
384 $entry['tags'][]=$tag->tag;
390 $entry['description'] = $entry['content'];
391 $entry['pubDate'] = common_date_rfc2822($notice->created);
392 $entry['guid'] = $entry['link'];
394 if (isset($notice->lat) && isset($notice->lon)) {
395 // This is the format that GeoJSON expects stuff to be in.
396 // showGeoRSS() below uses it for XML output, so we reuse it
397 $entry['geo'] = array('type' => 'Point',
398 'coordinates' => array((float) $notice->lat,
399 (float) $notice->lon));
401 $entry['geo'] = null;
407 function twitterRelationshipArray($source, $target)
409 $relationship = array();
411 $relationship['source'] =
412 $this->relationshipDetailsArray($source, $target);
413 $relationship['target'] =
414 $this->relationshipDetailsArray($target, $source);
416 return array('relationship' => $relationship);
419 function relationshipDetailsArray($source, $target)
423 $details['screen_name'] = $source->nickname;
424 $details['followed_by'] = $target->isSubscribed($source);
425 $details['following'] = $source->isSubscribed($target);
427 $notifications = false;
429 if ($source->isSubscribed($target)) {
431 $sub = Subscription::pkeyGet(array('subscriber' =>
432 $source->id, 'subscribed' => $target->id));
435 $notifications = ($sub->jabber || $sub->sms);
439 $details['notifications_enabled'] = $notifications;
440 $details['blocking'] = $source->hasBlocked($target);
441 $details['id'] = $source->id;
446 function showTwitterXmlRelationship($relationship)
448 $this->elementStart('relationship');
450 foreach($relationship as $element => $value) {
451 if ($element == 'source' || $element == 'target') {
452 $this->elementStart($element);
453 $this->showXmlRelationshipDetails($value);
454 $this->elementEnd($element);
458 $this->elementEnd('relationship');
461 function showXmlRelationshipDetails($details)
463 foreach($details as $element => $value) {
464 $this->element($element, null, $value);
468 function showTwitterXmlStatus($twitter_status, $tag='status')
470 $this->elementStart($tag);
471 foreach($twitter_status as $element => $value) {
474 $this->showTwitterXmlUser($twitter_status['user']);
477 $this->element($element, null, common_xml_safe_str($value));
480 $this->showXmlAttachments($twitter_status['attachments']);
483 $this->showGeoRSS($value);
485 case 'retweeted_status':
486 $this->showTwitterXmlStatus($value, 'retweeted_status');
489 $this->element($element, null, $value);
492 $this->elementEnd($tag);
495 function showTwitterXmlGroup($twitter_group)
497 $this->elementStart('group');
498 foreach($twitter_group as $element => $value) {
499 $this->element($element, null, $value);
501 $this->elementEnd('group');
504 function showTwitterXmlUser($twitter_user, $role='user')
506 $this->elementStart($role);
507 foreach($twitter_user as $element => $value) {
508 if ($element == 'status') {
509 $this->showTwitterXmlStatus($twitter_user['status']);
511 $this->element($element, null, $value);
514 $this->elementEnd($role);
517 function showXmlAttachments($attachments) {
518 if (!empty($attachments)) {
519 $this->elementStart('attachments', array('type' => 'array'));
520 foreach ($attachments as $attachment) {
522 $attrs['url'] = $attachment['url'];
523 $attrs['mimetype'] = $attachment['mimetype'];
524 $attrs['size'] = $attachment['size'];
525 $this->element('enclosure', $attrs, '');
527 $this->elementEnd('attachments');
531 function showGeoRSS($geo)
535 $this->element('geo');
537 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
538 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
539 $this->elementEnd('geo');
543 function showTwitterRssItem($entry)
545 $this->elementStart('item');
546 $this->element('title', null, $entry['title']);
547 $this->element('description', null, $entry['description']);
548 $this->element('pubDate', null, $entry['pubDate']);
549 $this->element('guid', null, $entry['guid']);
550 $this->element('link', null, $entry['link']);
552 # RSS only supports 1 enclosure per item
553 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
554 $enclosure = $entry['enclosures'][0];
555 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
558 if(array_key_exists('tags', $entry)){
559 foreach($entry['tags'] as $tag){
560 $this->element('category', null,$tag);
564 $this->showGeoRSS($entry['geo']);
565 $this->elementEnd('item');
568 function showJsonObjects($objects)
570 print(json_encode($objects));
573 function showSingleXmlStatus($notice)
575 $this->initDocument('xml');
576 $twitter_status = $this->twitterStatusArray($notice);
577 $this->showTwitterXmlStatus($twitter_status);
578 $this->endDocument('xml');
581 function show_single_json_status($notice)
583 $this->initDocument('json');
584 $status = $this->twitterStatusArray($notice);
585 $this->showJsonObjects($status);
586 $this->endDocument('json');
589 function showXmlTimeline($notice)
592 $this->initDocument('xml');
593 $this->elementStart('statuses', array('type' => 'array'));
595 if (is_array($notice)) {
596 foreach ($notice as $n) {
597 $twitter_status = $this->twitterStatusArray($n);
598 $this->showTwitterXmlStatus($twitter_status);
601 while ($notice->fetch()) {
602 $twitter_status = $this->twitterStatusArray($notice);
603 $this->showTwitterXmlStatus($twitter_status);
607 $this->elementEnd('statuses');
608 $this->endDocument('xml');
611 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
614 $this->initDocument('rss');
616 $this->element('title', null, $title);
617 $this->element('link', null, $link);
618 if (!is_null($suplink)) {
619 // For FriendFeed's SUP protocol
620 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
621 'rel' => 'http://api.friendfeed.com/2008/03#sup',
623 'type' => 'application/json'));
626 if (!is_null($logo)) {
627 $this->elementStart('image');
628 $this->element('link', null, $link);
629 $this->element('title', null, $title);
630 $this->element('url', null, $logo);
631 $this->elementEnd('image');
634 $this->element('description', null, $subtitle);
635 $this->element('language', null, 'en-us');
636 $this->element('ttl', null, '40');
638 if (is_array($notice)) {
639 foreach ($notice as $n) {
640 $entry = $this->twitterRssEntryArray($n);
641 $this->showTwitterRssItem($entry);
644 while ($notice->fetch()) {
645 $entry = $this->twitterRssEntryArray($notice);
646 $this->showTwitterRssItem($entry);
650 $this->endTwitterRss();
653 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
656 $this->initDocument('atom');
658 $this->element('title', null, $title);
659 $this->element('id', null, $id);
660 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
662 if (!is_null($logo)) {
663 $this->element('logo',null,$logo);
666 if (!is_null($suplink)) {
667 # For FriendFeed's SUP protocol
668 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
670 'type' => 'application/json'));
673 if (!is_null($selfuri)) {
674 $this->element('link', array('href' => $selfuri,
675 'rel' => 'self', 'type' => 'application/atom+xml'), null);
678 $this->element('updated', null, common_date_iso8601('now'));
679 $this->element('subtitle', null, $subtitle);
681 if (is_array($notice)) {
682 foreach ($notice as $n) {
683 $this->raw($n->asAtomEntry());
686 while ($notice->fetch()) {
687 $this->raw($notice->asAtomEntry());
691 $this->endDocument('atom');
695 function showRssGroups($group, $title, $link, $subtitle)
698 $this->initDocument('rss');
700 $this->element('title', null, $title);
701 $this->element('link', null, $link);
702 $this->element('description', null, $subtitle);
703 $this->element('language', null, 'en-us');
704 $this->element('ttl', null, '40');
706 if (is_array($group)) {
707 foreach ($group as $g) {
708 $twitter_group = $this->twitterRssGroupArray($g);
709 $this->showTwitterRssItem($twitter_group);
712 while ($group->fetch()) {
713 $twitter_group = $this->twitterRssGroupArray($group);
714 $this->showTwitterRssItem($twitter_group);
718 $this->endTwitterRss();
721 function showTwitterAtomEntry($entry)
723 $this->elementStart('entry');
724 $this->element('title', null, $entry['title']);
725 $this->element('content', array('type' => 'html'), $entry['content']);
726 $this->element('id', null, $entry['id']);
727 $this->element('published', null, $entry['published']);
728 $this->element('updated', null, $entry['updated']);
729 $this->element('link', array('type' => 'text/html',
730 'href' => $entry['link'],
731 'rel' => 'alternate'));
732 $this->element('link', array('type' => $entry['avatar-type'],
733 'href' => $entry['avatar'],
735 $this->elementStart('author');
737 $this->element('name', null, $entry['author-name']);
738 $this->element('uri', null, $entry['author-uri']);
740 $this->elementEnd('author');
741 $this->elementEnd('entry');
744 function showXmlDirectMessage($dm)
746 $this->elementStart('direct_message');
747 foreach($dm as $element => $value) {
751 $this->showTwitterXmlUser($value, $element);
754 $this->element($element, null, common_xml_safe_str($value));
757 $this->element($element, null, $value);
761 $this->elementEnd('direct_message');
764 function directMessageArray($message)
768 $from_profile = $message->getFrom();
769 $to_profile = $message->getTo();
771 $dmsg['id'] = $message->id;
772 $dmsg['sender_id'] = $message->from_profile;
773 $dmsg['text'] = trim($message->content);
774 $dmsg['recipient_id'] = $message->to_profile;
775 $dmsg['created_at'] = $this->dateTwitter($message->created);
776 $dmsg['sender_screen_name'] = $from_profile->nickname;
777 $dmsg['recipient_screen_name'] = $to_profile->nickname;
778 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
779 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
784 function rssDirectMessageArray($message)
788 $from = $message->getFrom();
790 $entry['title'] = sprintf('Message from %s to %s',
791 $from->nickname, $message->getTo()->nickname);
793 $entry['content'] = common_xml_safe_str($message->rendered);
794 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
795 $entry['published'] = common_date_iso8601($message->created);
797 $taguribase = common_config('integration', 'taguri');
799 $entry['id'] = "tag:$taguribase:$entry[link]";
800 $entry['updated'] = $entry['published'];
802 $entry['author-name'] = $from->getBestName();
803 $entry['author-uri'] = $from->homepage;
805 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
807 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
808 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
812 $entry['description'] = $entry['content'];
813 $entry['pubDate'] = common_date_rfc2822($message->created);
814 $entry['guid'] = $entry['link'];
819 function showSingleXmlDirectMessage($message)
821 $this->initDocument('xml');
822 $dmsg = $this->directMessageArray($message);
823 $this->showXmlDirectMessage($dmsg);
824 $this->endDocument('xml');
827 function showSingleJsonDirectMessage($message)
829 $this->initDocument('json');
830 $dmsg = $this->directMessageArray($message);
831 $this->showJsonObjects($dmsg);
832 $this->endDocument('json');
835 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
838 $this->initDocument('atom');
840 $this->element('title', null, $title);
841 $this->element('id', null, $id);
842 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
844 if (!is_null($selfuri)) {
845 $this->element('link', array('href' => $selfuri,
846 'rel' => 'self', 'type' => 'application/atom+xml'), null);
849 $this->element('updated', null, common_date_iso8601('now'));
850 $this->element('subtitle', null, $subtitle);
852 if (is_array($group)) {
853 foreach ($group as $g) {
854 $this->raw($g->asAtomEntry());
857 while ($group->fetch()) {
858 $this->raw($group->asAtomEntry());
862 $this->endDocument('atom');
866 function showJsonTimeline($notice)
869 $this->initDocument('json');
873 if (is_array($notice)) {
874 foreach ($notice as $n) {
875 $twitter_status = $this->twitterStatusArray($n);
876 array_push($statuses, $twitter_status);
879 while ($notice->fetch()) {
880 $twitter_status = $this->twitterStatusArray($notice);
881 array_push($statuses, $twitter_status);
885 $this->showJsonObjects($statuses);
887 $this->endDocument('json');
890 function showJsonGroups($group)
893 $this->initDocument('json');
897 if (is_array($group)) {
898 foreach ($group as $g) {
899 $twitter_group = $this->twitterGroupArray($g);
900 array_push($groups, $twitter_group);
903 while ($group->fetch()) {
904 $twitter_group = $this->twitterGroupArray($group);
905 array_push($groups, $twitter_group);
909 $this->showJsonObjects($groups);
911 $this->endDocument('json');
914 function showXmlGroups($group)
917 $this->initDocument('xml');
918 $this->elementStart('groups', array('type' => 'array'));
920 if (is_array($group)) {
921 foreach ($group as $g) {
922 $twitter_group = $this->twitterGroupArray($g);
923 $this->showTwitterXmlGroup($twitter_group);
926 while ($group->fetch()) {
927 $twitter_group = $this->twitterGroupArray($group);
928 $this->showTwitterXmlGroup($twitter_group);
932 $this->elementEnd('groups');
933 $this->endDocument('xml');
936 function showTwitterXmlUsers($user)
939 $this->initDocument('xml');
940 $this->elementStart('users', array('type' => 'array'));
942 if (is_array($user)) {
943 foreach ($user as $u) {
944 $twitter_user = $this->twitterUserArray($u);
945 $this->showTwitterXmlUser($twitter_user);
948 while ($user->fetch()) {
949 $twitter_user = $this->twitterUserArray($user);
950 $this->showTwitterXmlUser($twitter_user);
954 $this->elementEnd('users');
955 $this->endDocument('xml');
958 function showJsonUsers($user)
961 $this->initDocument('json');
965 if (is_array($user)) {
966 foreach ($user as $u) {
967 $twitter_user = $this->twitterUserArray($u);
968 array_push($users, $twitter_user);
971 while ($user->fetch()) {
972 $twitter_user = $this->twitterUserArray($user);
973 array_push($users, $twitter_user);
977 $this->showJsonObjects($users);
979 $this->endDocument('json');
982 function showSingleJsonGroup($group)
984 $this->initDocument('json');
985 $twitter_group = $this->twitterGroupArray($group);
986 $this->showJsonObjects($twitter_group);
987 $this->endDocument('json');
990 function showSingleXmlGroup($group)
992 $this->initDocument('xml');
993 $twitter_group = $this->twitterGroupArray($group);
994 $this->showTwitterXmlGroup($twitter_group);
995 $this->endDocument('xml');
998 function dateTwitter($dt)
1000 $dateStr = date('d F Y H:i:s', strtotime($dt));
1001 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1002 $d->setTimezone(new DateTimeZone(common_timezone()));
1003 return $d->format('D M d H:i:s O Y');
1006 function initDocument($type='xml')
1010 header('Content-Type: application/xml; charset=utf-8');
1014 header('Content-Type: application/json; charset=utf-8');
1016 // Check for JSONP callback
1017 $callback = $this->arg('callback');
1019 print $callback . '(';
1023 header("Content-Type: application/rss+xml; charset=utf-8");
1024 $this->initTwitterRss();
1027 header('Content-Type: application/atom+xml; charset=utf-8');
1028 $this->initTwitterAtom();
1031 $this->clientError(_('Not a supported data format.'));
1038 function endDocument($type='xml')
1046 // Check for JSONP callback
1047 $callback = $this->arg('callback');
1053 $this->endTwitterRss();
1056 $this->endTwitterRss();
1059 $this->clientError(_('Not a supported data format.'));
1065 function clientError($msg, $code = 400, $format = 'xml')
1067 $action = $this->trimmed('action');
1069 common_debug("User error '$code' on '$action': $msg", __FILE__);
1071 if (!array_key_exists($code, ClientErrorAction::$status)) {
1075 $status_string = ClientErrorAction::$status[$code];
1077 header('HTTP/1.1 '.$code.' '.$status_string);
1079 if ($format == 'xml') {
1080 $this->initDocument('xml');
1081 $this->elementStart('hash');
1082 $this->element('error', null, $msg);
1083 $this->element('request', null, $_SERVER['REQUEST_URI']);
1084 $this->elementEnd('hash');
1085 $this->endDocument('xml');
1086 } elseif ($format == 'json'){
1087 $this->initDocument('json');
1088 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1089 print(json_encode($error_array));
1090 $this->endDocument('json');
1093 // If user didn't request a useful format, throw a regular client error
1094 throw new ClientException($msg, $code);
1098 function serverError($msg, $code = 500, $content_type = 'json')
1100 $action = $this->trimmed('action');
1102 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1104 if (!array_key_exists($code, ServerErrorAction::$status)) {
1108 $status_string = ServerErrorAction::$status[$code];
1110 header('HTTP/1.1 '.$code.' '.$status_string);
1112 if ($content_type == 'xml') {
1113 $this->initDocument('xml');
1114 $this->elementStart('hash');
1115 $this->element('error', null, $msg);
1116 $this->element('request', null, $_SERVER['REQUEST_URI']);
1117 $this->elementEnd('hash');
1118 $this->endDocument('xml');
1120 $this->initDocument('json');
1121 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1122 print(json_encode($error_array));
1123 $this->endDocument('json');
1127 function initTwitterRss()
1130 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1131 $this->elementStart('channel');
1132 Event::handle('StartApiRss', array($this));
1135 function endTwitterRss()
1137 $this->elementEnd('channel');
1138 $this->elementEnd('rss');
1142 function initTwitterAtom()
1145 // FIXME: don't hardcode the language here!
1146 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1147 'xml:lang' => 'en-US',
1148 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1149 Event::handle('StartApiAtom', array($this));
1152 function endTwitterAtom()
1154 $this->elementEnd('feed');
1158 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1160 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1161 switch ($content_type) {
1163 $this->showTwitterXmlUser($profile_array);
1166 $this->showJsonObjects($profile_array);
1169 $this->clientError(_('Not a supported data format.'));
1175 function getTargetUser($id)
1179 // Twitter supports these other ways of passing the user ID
1180 if (is_numeric($this->arg('id'))) {
1181 return User::staticGet($this->arg('id'));
1182 } else if ($this->arg('id')) {
1183 $nickname = common_canonical_nickname($this->arg('id'));
1184 return User::staticGet('nickname', $nickname);
1185 } else if ($this->arg('user_id')) {
1186 // This is to ensure that a non-numeric user_id still
1187 // overrides screen_name even if it doesn't get used
1188 if (is_numeric($this->arg('user_id'))) {
1189 return User::staticGet('id', $this->arg('user_id'));
1191 } else if ($this->arg('screen_name')) {
1192 $nickname = common_canonical_nickname($this->arg('screen_name'));
1193 return User::staticGet('nickname', $nickname);
1195 // Fall back to trying the currently authenticated user
1196 return $this->auth_user;
1199 } else if (is_numeric($id)) {
1200 return User::staticGet($id);
1202 $nickname = common_canonical_nickname($id);
1203 return User::staticGet('nickname', $nickname);
1207 function getTargetGroup($id)
1210 if (is_numeric($this->arg('id'))) {
1211 return User_group::staticGet($this->arg('id'));
1212 } else if ($this->arg('id')) {
1213 $nickname = common_canonical_nickname($this->arg('id'));
1214 return User_group::staticGet('nickname', $nickname);
1215 } else if ($this->arg('group_id')) {
1216 // This is to ensure that a non-numeric user_id still
1217 // overrides screen_name even if it doesn't get used
1218 if (is_numeric($this->arg('group_id'))) {
1219 return User_group::staticGet('id', $this->arg('group_id'));
1221 } else if ($this->arg('group_name')) {
1222 $nickname = common_canonical_nickname($this->arg('group_name'));
1223 return User_group::staticGet('nickname', $nickname);
1226 } else if (is_numeric($id)) {
1227 return User_group::staticGet($id);
1229 $nickname = common_canonical_nickname($id);
1230 return User_group::staticGet('nickname', $nickname);
1234 function sourceLink($source)
1236 $source_name = _($source);
1245 $ns = Notice_source::staticGet($source);
1247 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1251 return $source_name;
1255 * Returns query argument or default value if not found. Certain
1256 * parameters used throughout the API are lightly scrubbed and
1257 * bounds checked. This overrides Action::arg().
1259 * @param string $key requested argument
1260 * @param string $def default value to return if $key is not provided
1264 function arg($key, $def=null)
1267 // XXX: Do even more input validation/scrubbing?
1269 if (array_key_exists($key, $this->args)) {
1272 $page = (int)$this->args['page'];
1273 return ($page < 1) ? 1 : $page;
1275 $count = (int)$this->args['count'];
1278 } elseif ($count > 200) {
1284 $since_id = (int)$this->args['since_id'];
1285 return ($since_id < 1) ? 0 : $since_id;
1287 $max_id = (int)$this->args['max_id'];
1288 return ($max_id < 1) ? 0 : $max_id;
1290 return strtotime($this->args['since']);
1292 return parent::arg($key, $def);