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
61 var $auth_user = null;
68 var $access = self::READ_ONLY; // read (default) or read-write
70 static $reserved_sources = array('web', 'omb', 'ostatus', 'mail', 'xmpp', 'api');
75 * @param array $args Web and URL arguments
77 * @return boolean false if user doesn't exist
80 function prepare($args)
82 StatusNet::setApi(true); // reduce exception reports to aid in debugging
83 parent::prepare($args);
85 $this->format = $this->arg('format');
86 $this->page = (int)$this->arg('page', 1);
87 $this->count = (int)$this->arg('count', 20);
88 $this->max_id = (int)$this->arg('max_id', 0);
89 $this->since_id = (int)$this->arg('since_id', 0);
91 if ($this->arg('since')) {
92 header('X-StatusNet-Warning: since parameter is disabled; use since_id');
95 $this->source = $this->trimmed('source');
97 if (empty($this->source) || in_array($this->source, self::$reserved_sources)) {
98 $this->source = 'api';
107 * @param array $args Arguments from $_REQUEST
112 function handle($args)
114 parent::handle($args);
118 * Overrides XMLOutputter::element to write booleans as strings (true|false).
119 * See that method's documentation for more info.
121 * @param string $tag Element type or tagname
122 * @param array $attrs Array of element attributes, as
124 * @param string $content string content of the element
128 function element($tag, $attrs=null, $content=null)
130 if (is_bool($content)) {
131 $content = ($content ? 'true' : 'false');
134 return parent::element($tag, $attrs, $content);
137 function twitterUserArray($profile, $get_notice=false)
139 $twitter_user = array();
141 $twitter_user['id'] = intval($profile->id);
142 $twitter_user['name'] = $profile->getBestName();
143 $twitter_user['screen_name'] = $profile->nickname;
144 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
145 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
147 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
148 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
149 Avatar::defaultImage(AVATAR_STREAM_SIZE);
151 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
152 $twitter_user['protected'] = false; # not supported by StatusNet yet
153 $twitter_user['followers_count'] = $profile->subscriberCount();
156 $user = $profile->getUser();
158 // Note: some profiles don't have an associated user
160 $defaultDesign = Design::siteDesign();
163 $design = $user->getDesign();
166 if (empty($design)) {
167 $design = $defaultDesign;
170 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
171 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
172 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
173 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
174 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
175 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
176 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
177 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
178 $twitter_user['profile_sidebar_border_color'] = '';
180 $twitter_user['friends_count'] = $profile->subscriptionCount();
182 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
184 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
188 if (!empty($user) && $user->timezone) {
189 $timezone = $user->timezone;
193 $t->setTimezone(new DateTimeZone($timezone));
195 $twitter_user['utc_offset'] = $t->format('Z');
196 $twitter_user['time_zone'] = $timezone;
198 $twitter_user['profile_background_image_url']
199 = empty($design->backgroundimage)
200 ? '' : ($design->disposition & BACKGROUND_ON)
201 ? Design::url($design->backgroundimage) : '';
203 $twitter_user['profile_background_tile']
204 = empty($design->disposition)
205 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
207 $twitter_user['statuses_count'] = $profile->noticeCount();
209 // Is the requesting user following this user?
210 $twitter_user['following'] = false;
211 $twitter_user['notifications'] = false;
213 if (isset($this->auth_user)) {
215 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
218 $sub = Subscription::pkeyGet(array('subscriber' =>
219 $this->auth_user->id,
220 'subscribed' => $profile->id));
223 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
228 $notice = $profile->getCurrentNotice();
231 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
235 return $twitter_user;
238 function twitterStatusArray($notice, $include_user=true)
240 $base = $this->twitterSimpleStatusArray($notice, $include_user);
242 if (!empty($notice->repeat_of)) {
243 $original = Notice::staticGet('id', $notice->repeat_of);
244 if (!empty($original)) {
245 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
246 $base['retweeted_status'] = $original_array;
253 function twitterSimpleStatusArray($notice, $include_user=true)
255 $profile = $notice->getProfile();
257 $twitter_status = array();
258 $twitter_status['text'] = $notice->content;
259 $twitter_status['truncated'] = false; # Not possible on StatusNet
260 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
261 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
262 intval($notice->reply_to) : null;
266 $ns = $notice->getSource();
268 if (!empty($ns->name) && !empty($ns->url)) {
269 $source = '<a href="'
270 . htmlspecialchars($ns->url)
271 . '" rel="nofollow">'
272 . htmlspecialchars($ns->name)
279 $twitter_status['source'] = $source;
280 $twitter_status['id'] = intval($notice->id);
282 $replier_profile = null;
284 if ($notice->reply_to) {
285 $reply = Notice::staticGet(intval($notice->reply_to));
287 $replier_profile = $reply->getProfile();
291 $twitter_status['in_reply_to_user_id'] =
292 ($replier_profile) ? intval($replier_profile->id) : null;
293 $twitter_status['in_reply_to_screen_name'] =
294 ($replier_profile) ? $replier_profile->nickname : null;
296 if (isset($notice->lat) && isset($notice->lon)) {
297 // This is the format that GeoJSON expects stuff to be in
298 $twitter_status['geo'] = array('type' => 'Point',
299 'coordinates' => array((float) $notice->lat,
300 (float) $notice->lon));
302 $twitter_status['geo'] = null;
305 if (isset($this->auth_user)) {
306 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
308 $twitter_status['favorited'] = false;
312 $attachments = $notice->attachments();
314 if (!empty($attachments)) {
316 $twitter_status['attachments'] = array();
318 foreach ($attachments as $attachment) {
319 $enclosure_o=$attachment->getEnclosure();
321 $enclosure = array();
322 $enclosure['url'] = $enclosure_o->url;
323 $enclosure['mimetype'] = $enclosure_o->mimetype;
324 $enclosure['size'] = $enclosure_o->size;
325 $twitter_status['attachments'][] = $enclosure;
330 if ($include_user && $profile) {
331 # Don't get notice (recursive!)
332 $twitter_user = $this->twitterUserArray($profile, false);
333 $twitter_status['user'] = $twitter_user;
336 return $twitter_status;
339 function twitterGroupArray($group)
341 $twitter_group=array();
342 $twitter_group['id']=$group->id;
343 $twitter_group['url']=$group->permalink();
344 $twitter_group['nickname']=$group->nickname;
345 $twitter_group['fullname']=$group->fullname;
346 $twitter_group['original_logo']=$group->original_logo;
347 $twitter_group['homepage_logo']=$group->homepage_logo;
348 $twitter_group['stream_logo']=$group->stream_logo;
349 $twitter_group['mini_logo']=$group->mini_logo;
350 $twitter_group['homepage']=$group->homepage;
351 $twitter_group['description']=$group->description;
352 $twitter_group['location']=$group->location;
353 $twitter_group['created']=$this->dateTwitter($group->created);
354 $twitter_group['modified']=$this->dateTwitter($group->modified);
355 return $twitter_group;
358 function twitterRssGroupArray($group)
361 $entry['content']=$group->description;
362 $entry['title']=$group->nickname;
363 $entry['link']=$group->permalink();
364 $entry['published']=common_date_iso8601($group->created);
365 $entry['updated']==common_date_iso8601($group->modified);
366 $taguribase = common_config('integration', 'groupuri');
367 $entry['id'] = "group:$groupuribase:$entry[link]";
369 $entry['description'] = $entry['content'];
370 $entry['pubDate'] = common_date_rfc2822($group->created);
371 $entry['guid'] = $entry['link'];
376 function twitterRssEntryArray($notice)
378 $profile = $notice->getProfile();
381 // We trim() to avoid extraneous whitespace in the output
383 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
384 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
385 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
386 $entry['published'] = common_date_iso8601($notice->created);
388 $taguribase = TagURI::base();
389 $entry['id'] = "tag:$taguribase:$entry[link]";
391 $entry['updated'] = $entry['published'];
392 $entry['author'] = $profile->getBestName();
395 $attachments = $notice->attachments();
396 $enclosures = array();
398 foreach ($attachments as $attachment) {
399 $enclosure_o=$attachment->getEnclosure();
401 $enclosure = array();
402 $enclosure['url'] = $enclosure_o->url;
403 $enclosure['mimetype'] = $enclosure_o->mimetype;
404 $enclosure['size'] = $enclosure_o->size;
405 $enclosures[] = $enclosure;
409 if (!empty($enclosures)) {
410 $entry['enclosures'] = $enclosures;
414 $tag = new Notice_tag();
415 $tag->notice_id = $notice->id;
417 $entry['tags']=array();
418 while ($tag->fetch()) {
419 $entry['tags'][]=$tag->tag;
425 $entry['description'] = $entry['content'];
426 $entry['pubDate'] = common_date_rfc2822($notice->created);
427 $entry['guid'] = $entry['link'];
429 if (isset($notice->lat) && isset($notice->lon)) {
430 // This is the format that GeoJSON expects stuff to be in.
431 // showGeoRSS() below uses it for XML output, so we reuse it
432 $entry['geo'] = array('type' => 'Point',
433 'coordinates' => array((float) $notice->lat,
434 (float) $notice->lon));
436 $entry['geo'] = null;
442 function twitterRelationshipArray($source, $target)
444 $relationship = array();
446 $relationship['source'] =
447 $this->relationshipDetailsArray($source, $target);
448 $relationship['target'] =
449 $this->relationshipDetailsArray($target, $source);
451 return array('relationship' => $relationship);
454 function relationshipDetailsArray($source, $target)
458 $details['screen_name'] = $source->nickname;
459 $details['followed_by'] = $target->isSubscribed($source);
460 $details['following'] = $source->isSubscribed($target);
462 $notifications = false;
464 if ($source->isSubscribed($target)) {
466 $sub = Subscription::pkeyGet(array('subscriber' =>
467 $source->id, 'subscribed' => $target->id));
470 $notifications = ($sub->jabber || $sub->sms);
474 $details['notifications_enabled'] = $notifications;
475 $details['blocking'] = $source->hasBlocked($target);
476 $details['id'] = $source->id;
481 function showTwitterXmlRelationship($relationship)
483 $this->elementStart('relationship');
485 foreach($relationship as $element => $value) {
486 if ($element == 'source' || $element == 'target') {
487 $this->elementStart($element);
488 $this->showXmlRelationshipDetails($value);
489 $this->elementEnd($element);
493 $this->elementEnd('relationship');
496 function showXmlRelationshipDetails($details)
498 foreach($details as $element => $value) {
499 $this->element($element, null, $value);
503 function showTwitterXmlStatus($twitter_status, $tag='status')
505 $this->elementStart($tag);
506 foreach($twitter_status as $element => $value) {
509 $this->showTwitterXmlUser($twitter_status['user']);
512 $this->element($element, null, common_xml_safe_str($value));
515 $this->showXmlAttachments($twitter_status['attachments']);
518 $this->showGeoXML($value);
520 case 'retweeted_status':
521 $this->showTwitterXmlStatus($value, 'retweeted_status');
524 $this->element($element, null, $value);
527 $this->elementEnd($tag);
530 function showTwitterXmlGroup($twitter_group)
532 $this->elementStart('group');
533 foreach($twitter_group as $element => $value) {
534 $this->element($element, null, $value);
536 $this->elementEnd('group');
539 function showTwitterXmlUser($twitter_user, $role='user')
541 $this->elementStart($role);
542 foreach($twitter_user as $element => $value) {
543 if ($element == 'status') {
544 $this->showTwitterXmlStatus($twitter_user['status']);
546 $this->element($element, null, $value);
549 $this->elementEnd($role);
552 function showXmlAttachments($attachments) {
553 if (!empty($attachments)) {
554 $this->elementStart('attachments', array('type' => 'array'));
555 foreach ($attachments as $attachment) {
557 $attrs['url'] = $attachment['url'];
558 $attrs['mimetype'] = $attachment['mimetype'];
559 $attrs['size'] = $attachment['size'];
560 $this->element('enclosure', $attrs, '');
562 $this->elementEnd('attachments');
566 function showGeoXML($geo)
570 $this->element('geo');
572 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
573 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
574 $this->elementEnd('geo');
578 function showGeoRSS($geo)
584 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
589 function showTwitterRssItem($entry)
591 $this->elementStart('item');
592 $this->element('title', null, $entry['title']);
593 $this->element('description', null, $entry['description']);
594 $this->element('pubDate', null, $entry['pubDate']);
595 $this->element('guid', null, $entry['guid']);
596 $this->element('link', null, $entry['link']);
598 # RSS only supports 1 enclosure per item
599 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
600 $enclosure = $entry['enclosures'][0];
601 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
604 if(array_key_exists('tags', $entry)){
605 foreach($entry['tags'] as $tag){
606 $this->element('category', null,$tag);
610 $this->showGeoRSS($entry['geo']);
611 $this->elementEnd('item');
614 function showJsonObjects($objects)
616 print(json_encode($objects));
619 function showSingleXmlStatus($notice)
621 $this->initDocument('xml');
622 $twitter_status = $this->twitterStatusArray($notice);
623 $this->showTwitterXmlStatus($twitter_status);
624 $this->endDocument('xml');
627 function show_single_json_status($notice)
629 $this->initDocument('json');
630 $status = $this->twitterStatusArray($notice);
631 $this->showJsonObjects($status);
632 $this->endDocument('json');
635 function showXmlTimeline($notice)
638 $this->initDocument('xml');
639 $this->elementStart('statuses', array('type' => 'array'));
641 if (is_array($notice)) {
642 foreach ($notice as $n) {
643 $twitter_status = $this->twitterStatusArray($n);
644 $this->showTwitterXmlStatus($twitter_status);
647 while ($notice->fetch()) {
648 $twitter_status = $this->twitterStatusArray($notice);
649 $this->showTwitterXmlStatus($twitter_status);
653 $this->elementEnd('statuses');
654 $this->endDocument('xml');
657 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
660 $this->initDocument('rss');
662 $this->element('title', null, $title);
663 $this->element('link', null, $link);
665 if (!is_null($self)) {
669 'type' => 'application/rss+xml',
676 if (!is_null($suplink)) {
677 // For FriendFeed's SUP protocol
678 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
679 'rel' => 'http://api.friendfeed.com/2008/03#sup',
681 'type' => 'application/json'));
684 if (!is_null($logo)) {
685 $this->elementStart('image');
686 $this->element('link', null, $link);
687 $this->element('title', null, $title);
688 $this->element('url', null, $logo);
689 $this->elementEnd('image');
692 $this->element('description', null, $subtitle);
693 $this->element('language', null, 'en-us');
694 $this->element('ttl', null, '40');
696 if (is_array($notice)) {
697 foreach ($notice as $n) {
698 $entry = $this->twitterRssEntryArray($n);
699 $this->showTwitterRssItem($entry);
702 while ($notice->fetch()) {
703 $entry = $this->twitterRssEntryArray($notice);
704 $this->showTwitterRssItem($entry);
708 $this->endTwitterRss();
711 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
714 $this->initDocument('atom');
716 $this->element('title', null, $title);
717 $this->element('id', null, $id);
718 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
720 if (!is_null($logo)) {
721 $this->element('logo',null,$logo);
724 if (!is_null($suplink)) {
725 # For FriendFeed's SUP protocol
726 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
728 'type' => 'application/json'));
731 if (!is_null($selfuri)) {
732 $this->element('link', array('href' => $selfuri,
733 'rel' => 'self', 'type' => 'application/atom+xml'), null);
736 $this->element('updated', null, common_date_iso8601('now'));
737 $this->element('subtitle', null, $subtitle);
739 if (is_array($notice)) {
740 foreach ($notice as $n) {
741 $this->raw($n->asAtomEntry());
744 while ($notice->fetch()) {
745 $this->raw($notice->asAtomEntry());
749 $this->endDocument('atom');
753 function showRssGroups($group, $title, $link, $subtitle)
756 $this->initDocument('rss');
758 $this->element('title', null, $title);
759 $this->element('link', null, $link);
760 $this->element('description', null, $subtitle);
761 $this->element('language', null, 'en-us');
762 $this->element('ttl', null, '40');
764 if (is_array($group)) {
765 foreach ($group as $g) {
766 $twitter_group = $this->twitterRssGroupArray($g);
767 $this->showTwitterRssItem($twitter_group);
770 while ($group->fetch()) {
771 $twitter_group = $this->twitterRssGroupArray($group);
772 $this->showTwitterRssItem($twitter_group);
776 $this->endTwitterRss();
779 function showTwitterAtomEntry($entry)
781 $this->elementStart('entry');
782 $this->element('title', null, common_xml_safe_str($entry['title']));
785 array('type' => 'html'),
786 common_xml_safe_str($entry['content'])
788 $this->element('id', null, $entry['id']);
789 $this->element('published', null, $entry['published']);
790 $this->element('updated', null, $entry['updated']);
791 $this->element('link', array('type' => 'text/html',
792 'href' => $entry['link'],
793 'rel' => 'alternate'));
794 $this->element('link', array('type' => $entry['avatar-type'],
795 'href' => $entry['avatar'],
797 $this->elementStart('author');
799 $this->element('name', null, $entry['author-name']);
800 $this->element('uri', null, $entry['author-uri']);
802 $this->elementEnd('author');
803 $this->elementEnd('entry');
806 function showXmlDirectMessage($dm)
808 $this->elementStart('direct_message');
809 foreach($dm as $element => $value) {
813 $this->showTwitterXmlUser($value, $element);
816 $this->element($element, null, common_xml_safe_str($value));
819 $this->element($element, null, $value);
823 $this->elementEnd('direct_message');
826 function directMessageArray($message)
830 $from_profile = $message->getFrom();
831 $to_profile = $message->getTo();
833 $dmsg['id'] = $message->id;
834 $dmsg['sender_id'] = $message->from_profile;
835 $dmsg['text'] = trim($message->content);
836 $dmsg['recipient_id'] = $message->to_profile;
837 $dmsg['created_at'] = $this->dateTwitter($message->created);
838 $dmsg['sender_screen_name'] = $from_profile->nickname;
839 $dmsg['recipient_screen_name'] = $to_profile->nickname;
840 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
841 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
846 function rssDirectMessageArray($message)
850 $from = $message->getFrom();
852 $entry['title'] = sprintf('Message from %1$s to %2$s',
853 $from->nickname, $message->getTo()->nickname);
855 $entry['content'] = common_xml_safe_str($message->rendered);
856 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
857 $entry['published'] = common_date_iso8601($message->created);
859 $taguribase = TagURI::base();
861 $entry['id'] = "tag:$taguribase:$entry[link]";
862 $entry['updated'] = $entry['published'];
864 $entry['author-name'] = $from->getBestName();
865 $entry['author-uri'] = $from->homepage;
867 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
869 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
870 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
874 $entry['description'] = $entry['content'];
875 $entry['pubDate'] = common_date_rfc2822($message->created);
876 $entry['guid'] = $entry['link'];
881 function showSingleXmlDirectMessage($message)
883 $this->initDocument('xml');
884 $dmsg = $this->directMessageArray($message);
885 $this->showXmlDirectMessage($dmsg);
886 $this->endDocument('xml');
889 function showSingleJsonDirectMessage($message)
891 $this->initDocument('json');
892 $dmsg = $this->directMessageArray($message);
893 $this->showJsonObjects($dmsg);
894 $this->endDocument('json');
897 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
900 $this->initDocument('atom');
902 $this->element('title', null, common_xml_safe_str($title));
903 $this->element('id', null, $id);
904 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
906 if (!is_null($selfuri)) {
907 $this->element('link', array('href' => $selfuri,
908 'rel' => 'self', 'type' => 'application/atom+xml'), null);
911 $this->element('updated', null, common_date_iso8601('now'));
912 $this->element('subtitle', null, common_xml_safe_str($subtitle));
914 if (is_array($group)) {
915 foreach ($group as $g) {
916 $this->raw($g->asAtomEntry());
919 while ($group->fetch()) {
920 $this->raw($group->asAtomEntry());
924 $this->endDocument('atom');
928 function showJsonTimeline($notice)
931 $this->initDocument('json');
935 if (is_array($notice)) {
936 foreach ($notice as $n) {
937 $twitter_status = $this->twitterStatusArray($n);
938 array_push($statuses, $twitter_status);
941 while ($notice->fetch()) {
942 $twitter_status = $this->twitterStatusArray($notice);
943 array_push($statuses, $twitter_status);
947 $this->showJsonObjects($statuses);
949 $this->endDocument('json');
952 function showJsonGroups($group)
955 $this->initDocument('json');
959 if (is_array($group)) {
960 foreach ($group as $g) {
961 $twitter_group = $this->twitterGroupArray($g);
962 array_push($groups, $twitter_group);
965 while ($group->fetch()) {
966 $twitter_group = $this->twitterGroupArray($group);
967 array_push($groups, $twitter_group);
971 $this->showJsonObjects($groups);
973 $this->endDocument('json');
976 function showXmlGroups($group)
979 $this->initDocument('xml');
980 $this->elementStart('groups', array('type' => 'array'));
982 if (is_array($group)) {
983 foreach ($group as $g) {
984 $twitter_group = $this->twitterGroupArray($g);
985 $this->showTwitterXmlGroup($twitter_group);
988 while ($group->fetch()) {
989 $twitter_group = $this->twitterGroupArray($group);
990 $this->showTwitterXmlGroup($twitter_group);
994 $this->elementEnd('groups');
995 $this->endDocument('xml');
998 function showTwitterXmlUsers($user)
1001 $this->initDocument('xml');
1002 $this->elementStart('users', array('type' => 'array'));
1004 if (is_array($user)) {
1005 foreach ($user as $u) {
1006 $twitter_user = $this->twitterUserArray($u);
1007 $this->showTwitterXmlUser($twitter_user);
1010 while ($user->fetch()) {
1011 $twitter_user = $this->twitterUserArray($user);
1012 $this->showTwitterXmlUser($twitter_user);
1016 $this->elementEnd('users');
1017 $this->endDocument('xml');
1020 function showJsonUsers($user)
1023 $this->initDocument('json');
1027 if (is_array($user)) {
1028 foreach ($user as $u) {
1029 $twitter_user = $this->twitterUserArray($u);
1030 array_push($users, $twitter_user);
1033 while ($user->fetch()) {
1034 $twitter_user = $this->twitterUserArray($user);
1035 array_push($users, $twitter_user);
1039 $this->showJsonObjects($users);
1041 $this->endDocument('json');
1044 function showSingleJsonGroup($group)
1046 $this->initDocument('json');
1047 $twitter_group = $this->twitterGroupArray($group);
1048 $this->showJsonObjects($twitter_group);
1049 $this->endDocument('json');
1052 function showSingleXmlGroup($group)
1054 $this->initDocument('xml');
1055 $twitter_group = $this->twitterGroupArray($group);
1056 $this->showTwitterXmlGroup($twitter_group);
1057 $this->endDocument('xml');
1060 function dateTwitter($dt)
1062 $dateStr = date('d F Y H:i:s', strtotime($dt));
1063 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1064 $d->setTimezone(new DateTimeZone(common_timezone()));
1065 return $d->format('D M d H:i:s O Y');
1068 function initDocument($type='xml')
1072 header('Content-Type: application/xml; charset=utf-8');
1076 header('Content-Type: application/json; charset=utf-8');
1078 // Check for JSONP callback
1079 $callback = $this->arg('callback');
1081 print $callback . '(';
1085 header("Content-Type: application/rss+xml; charset=utf-8");
1086 $this->initTwitterRss();
1089 header('Content-Type: application/atom+xml; charset=utf-8');
1090 $this->initTwitterAtom();
1093 $this->clientError(_('Not a supported data format.'));
1100 function endDocument($type='xml')
1108 // Check for JSONP callback
1109 $callback = $this->arg('callback');
1115 $this->endTwitterRss();
1118 $this->endTwitterRss();
1121 $this->clientError(_('Not a supported data format.'));
1127 function clientError($msg, $code = 400, $format = 'xml')
1129 $action = $this->trimmed('action');
1131 common_debug("User error '$code' on '$action': $msg", __FILE__);
1133 if (!array_key_exists($code, ClientErrorAction::$status)) {
1137 $status_string = ClientErrorAction::$status[$code];
1139 header('HTTP/1.1 '.$code.' '.$status_string);
1141 if ($format == 'xml') {
1142 $this->initDocument('xml');
1143 $this->elementStart('hash');
1144 $this->element('error', null, $msg);
1145 $this->element('request', null, $_SERVER['REQUEST_URI']);
1146 $this->elementEnd('hash');
1147 $this->endDocument('xml');
1148 } elseif ($format == 'json'){
1149 $this->initDocument('json');
1150 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1151 print(json_encode($error_array));
1152 $this->endDocument('json');
1155 // If user didn't request a useful format, throw a regular client error
1156 throw new ClientException($msg, $code);
1160 function serverError($msg, $code = 500, $content_type = 'xml')
1162 $action = $this->trimmed('action');
1164 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1166 if (!array_key_exists($code, ServerErrorAction::$status)) {
1170 $status_string = ServerErrorAction::$status[$code];
1172 header('HTTP/1.1 '.$code.' '.$status_string);
1174 if ($content_type == 'xml') {
1175 $this->initDocument('xml');
1176 $this->elementStart('hash');
1177 $this->element('error', null, $msg);
1178 $this->element('request', null, $_SERVER['REQUEST_URI']);
1179 $this->elementEnd('hash');
1180 $this->endDocument('xml');
1182 $this->initDocument('json');
1183 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1184 print(json_encode($error_array));
1185 $this->endDocument('json');
1189 function initTwitterRss()
1192 $this->elementStart(
1196 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1197 'xmlns:georss' => 'http://www.georss.org/georss'
1200 $this->elementStart('channel');
1201 Event::handle('StartApiRss', array($this));
1204 function endTwitterRss()
1206 $this->elementEnd('channel');
1207 $this->elementEnd('rss');
1211 function initTwitterAtom()
1214 // FIXME: don't hardcode the language here!
1215 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1216 'xml:lang' => 'en-US',
1217 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1220 function endTwitterAtom()
1222 $this->elementEnd('feed');
1226 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1228 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1229 switch ($content_type) {
1231 $this->showTwitterXmlUser($profile_array);
1234 $this->showJsonObjects($profile_array);
1237 $this->clientError(_('Not a supported data format.'));
1243 function getTargetUser($id)
1247 // Twitter supports these other ways of passing the user ID
1248 if (is_numeric($this->arg('id'))) {
1249 return User::staticGet($this->arg('id'));
1250 } else if ($this->arg('id')) {
1251 $nickname = common_canonical_nickname($this->arg('id'));
1252 return User::staticGet('nickname', $nickname);
1253 } else if ($this->arg('user_id')) {
1254 // This is to ensure that a non-numeric user_id still
1255 // overrides screen_name even if it doesn't get used
1256 if (is_numeric($this->arg('user_id'))) {
1257 return User::staticGet('id', $this->arg('user_id'));
1259 } else if ($this->arg('screen_name')) {
1260 $nickname = common_canonical_nickname($this->arg('screen_name'));
1261 return User::staticGet('nickname', $nickname);
1263 // Fall back to trying the currently authenticated user
1264 return $this->auth_user;
1267 } else if (is_numeric($id)) {
1268 return User::staticGet($id);
1270 $nickname = common_canonical_nickname($id);
1271 return User::staticGet('nickname', $nickname);
1275 function getTargetGroup($id)
1278 if (is_numeric($this->arg('id'))) {
1279 return User_group::staticGet($this->arg('id'));
1280 } else if ($this->arg('id')) {
1281 $nickname = common_canonical_nickname($this->arg('id'));
1282 $local = Local_group::staticGet('nickname', $nickname);
1283 if (empty($local)) {
1286 return User_group::staticGet('id', $local->id);
1288 } else if ($this->arg('group_id')) {
1289 // This is to ensure that a non-numeric user_id still
1290 // overrides screen_name even if it doesn't get used
1291 if (is_numeric($this->arg('group_id'))) {
1292 return User_group::staticGet('id', $this->arg('group_id'));
1294 } else if ($this->arg('group_name')) {
1295 $nickname = common_canonical_nickname($this->arg('group_name'));
1296 $local = Local_group::staticGet('nickname', $nickname);
1297 if (empty($local)) {
1300 return User_group::staticGet('id', $local->group_id);
1304 } else if (is_numeric($id)) {
1305 return User_group::staticGet($id);
1307 $nickname = common_canonical_nickname($id);
1308 $local = Local_group::staticGet('nickname', $nickname);
1309 if (empty($local)) {
1312 return User_group::staticGet('id', $local->group_id);
1318 * Returns query argument or default value if not found. Certain
1319 * parameters used throughout the API are lightly scrubbed and
1320 * bounds checked. This overrides Action::arg().
1322 * @param string $key requested argument
1323 * @param string $def default value to return if $key is not provided
1327 function arg($key, $def=null)
1330 // XXX: Do even more input validation/scrubbing?
1332 if (array_key_exists($key, $this->args)) {
1335 $page = (int)$this->args['page'];
1336 return ($page < 1) ? 1 : $page;
1338 $count = (int)$this->args['count'];
1341 } elseif ($count > 200) {
1347 $since_id = (int)$this->args['since_id'];
1348 return ($since_id < 1) ? 0 : $since_id;
1350 $max_id = (int)$this->args['max_id'];
1351 return ($max_id < 1) ? 0 : $max_id;
1353 return parent::arg($key, $def);
1361 * Calculate the complete URI that called up this action. Used for
1362 * Atom rel="self" links. Warning: this is funky.
1364 * @return string URL a URL suitable for rel="self" Atom links
1366 function getSelfUri()
1368 $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1370 $id = $this->arg('id');
1371 $aargs = array('format' => $this->format);
1376 $tag = $this->arg('tag');
1378 $aargs['tag'] = $tag;
1381 parse_str($_SERVER['QUERY_STRING'], $params);
1383 if (!empty($params)) {
1384 unset($params['p']);
1385 $pstring = http_build_query($params);
1388 $uri = common_local_url($action, $aargs);
1390 if (!empty($pstring)) {
1391 $uri .= '?' . $pstring;