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="' . $ns->url . '">' . $ns->name . '</a>';
275 $twitter_status['source'] = $source;
276 $twitter_status['id'] = intval($notice->id);
278 $replier_profile = null;
280 if ($notice->reply_to) {
281 $reply = Notice::staticGet(intval($notice->reply_to));
283 $replier_profile = $reply->getProfile();
287 $twitter_status['in_reply_to_user_id'] =
288 ($replier_profile) ? intval($replier_profile->id) : null;
289 $twitter_status['in_reply_to_screen_name'] =
290 ($replier_profile) ? $replier_profile->nickname : null;
292 if (isset($notice->lat) && isset($notice->lon)) {
293 // This is the format that GeoJSON expects stuff to be in
294 $twitter_status['geo'] = array('type' => 'Point',
295 'coordinates' => array((float) $notice->lat,
296 (float) $notice->lon));
298 $twitter_status['geo'] = null;
301 if (isset($this->auth_user)) {
302 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
304 $twitter_status['favorited'] = false;
308 $attachments = $notice->attachments();
310 if (!empty($attachments)) {
312 $twitter_status['attachments'] = array();
314 foreach ($attachments as $attachment) {
315 $enclosure_o=$attachment->getEnclosure();
317 $enclosure = array();
318 $enclosure['url'] = $enclosure_o->url;
319 $enclosure['mimetype'] = $enclosure_o->mimetype;
320 $enclosure['size'] = $enclosure_o->size;
321 $twitter_status['attachments'][] = $enclosure;
326 if ($include_user && $profile) {
327 # Don't get notice (recursive!)
328 $twitter_user = $this->twitterUserArray($profile, false);
329 $twitter_status['user'] = $twitter_user;
332 return $twitter_status;
335 function twitterGroupArray($group)
337 $twitter_group=array();
338 $twitter_group['id']=$group->id;
339 $twitter_group['url']=$group->permalink();
340 $twitter_group['nickname']=$group->nickname;
341 $twitter_group['fullname']=$group->fullname;
342 $twitter_group['original_logo']=$group->original_logo;
343 $twitter_group['homepage_logo']=$group->homepage_logo;
344 $twitter_group['stream_logo']=$group->stream_logo;
345 $twitter_group['mini_logo']=$group->mini_logo;
346 $twitter_group['homepage']=$group->homepage;
347 $twitter_group['description']=$group->description;
348 $twitter_group['location']=$group->location;
349 $twitter_group['created']=$this->dateTwitter($group->created);
350 $twitter_group['modified']=$this->dateTwitter($group->modified);
351 return $twitter_group;
354 function twitterRssGroupArray($group)
357 $entry['content']=$group->description;
358 $entry['title']=$group->nickname;
359 $entry['link']=$group->permalink();
360 $entry['published']=common_date_iso8601($group->created);
361 $entry['updated']==common_date_iso8601($group->modified);
362 $taguribase = common_config('integration', 'groupuri');
363 $entry['id'] = "group:$groupuribase:$entry[link]";
365 $entry['description'] = $entry['content'];
366 $entry['pubDate'] = common_date_rfc2822($group->created);
367 $entry['guid'] = $entry['link'];
372 function twitterRssEntryArray($notice)
374 $profile = $notice->getProfile();
377 // We trim() to avoid extraneous whitespace in the output
379 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
380 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
381 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
382 $entry['published'] = common_date_iso8601($notice->created);
384 $taguribase = TagURI::base();
385 $entry['id'] = "tag:$taguribase:$entry[link]";
387 $entry['updated'] = $entry['published'];
388 $entry['author'] = $profile->getBestName();
391 $attachments = $notice->attachments();
392 $enclosures = array();
394 foreach ($attachments as $attachment) {
395 $enclosure_o=$attachment->getEnclosure();
397 $enclosure = array();
398 $enclosure['url'] = $enclosure_o->url;
399 $enclosure['mimetype'] = $enclosure_o->mimetype;
400 $enclosure['size'] = $enclosure_o->size;
401 $enclosures[] = $enclosure;
405 if (!empty($enclosures)) {
406 $entry['enclosures'] = $enclosures;
410 $tag = new Notice_tag();
411 $tag->notice_id = $notice->id;
413 $entry['tags']=array();
414 while ($tag->fetch()) {
415 $entry['tags'][]=$tag->tag;
421 $entry['description'] = $entry['content'];
422 $entry['pubDate'] = common_date_rfc2822($notice->created);
423 $entry['guid'] = $entry['link'];
425 if (isset($notice->lat) && isset($notice->lon)) {
426 // This is the format that GeoJSON expects stuff to be in.
427 // showGeoRSS() below uses it for XML output, so we reuse it
428 $entry['geo'] = array('type' => 'Point',
429 'coordinates' => array((float) $notice->lat,
430 (float) $notice->lon));
432 $entry['geo'] = null;
438 function twitterRelationshipArray($source, $target)
440 $relationship = array();
442 $relationship['source'] =
443 $this->relationshipDetailsArray($source, $target);
444 $relationship['target'] =
445 $this->relationshipDetailsArray($target, $source);
447 return array('relationship' => $relationship);
450 function relationshipDetailsArray($source, $target)
454 $details['screen_name'] = $source->nickname;
455 $details['followed_by'] = $target->isSubscribed($source);
456 $details['following'] = $source->isSubscribed($target);
458 $notifications = false;
460 if ($source->isSubscribed($target)) {
462 $sub = Subscription::pkeyGet(array('subscriber' =>
463 $source->id, 'subscribed' => $target->id));
466 $notifications = ($sub->jabber || $sub->sms);
470 $details['notifications_enabled'] = $notifications;
471 $details['blocking'] = $source->hasBlocked($target);
472 $details['id'] = $source->id;
477 function showTwitterXmlRelationship($relationship)
479 $this->elementStart('relationship');
481 foreach($relationship as $element => $value) {
482 if ($element == 'source' || $element == 'target') {
483 $this->elementStart($element);
484 $this->showXmlRelationshipDetails($value);
485 $this->elementEnd($element);
489 $this->elementEnd('relationship');
492 function showXmlRelationshipDetails($details)
494 foreach($details as $element => $value) {
495 $this->element($element, null, $value);
499 function showTwitterXmlStatus($twitter_status, $tag='status')
501 $this->elementStart($tag);
502 foreach($twitter_status as $element => $value) {
505 $this->showTwitterXmlUser($twitter_status['user']);
508 $this->element($element, null, common_xml_safe_str($value));
511 $this->showXmlAttachments($twitter_status['attachments']);
514 $this->showGeoXML($value);
516 case 'retweeted_status':
517 $this->showTwitterXmlStatus($value, 'retweeted_status');
520 $this->element($element, null, $value);
523 $this->elementEnd($tag);
526 function showTwitterXmlGroup($twitter_group)
528 $this->elementStart('group');
529 foreach($twitter_group as $element => $value) {
530 $this->element($element, null, $value);
532 $this->elementEnd('group');
535 function showTwitterXmlUser($twitter_user, $role='user')
537 $this->elementStart($role);
538 foreach($twitter_user as $element => $value) {
539 if ($element == 'status') {
540 $this->showTwitterXmlStatus($twitter_user['status']);
542 $this->element($element, null, $value);
545 $this->elementEnd($role);
548 function showXmlAttachments($attachments) {
549 if (!empty($attachments)) {
550 $this->elementStart('attachments', array('type' => 'array'));
551 foreach ($attachments as $attachment) {
553 $attrs['url'] = $attachment['url'];
554 $attrs['mimetype'] = $attachment['mimetype'];
555 $attrs['size'] = $attachment['size'];
556 $this->element('enclosure', $attrs, '');
558 $this->elementEnd('attachments');
562 function showGeoXML($geo)
566 $this->element('geo');
568 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
569 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
570 $this->elementEnd('geo');
574 function showGeoRSS($geo)
580 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
585 function showTwitterRssItem($entry)
587 $this->elementStart('item');
588 $this->element('title', null, $entry['title']);
589 $this->element('description', null, $entry['description']);
590 $this->element('pubDate', null, $entry['pubDate']);
591 $this->element('guid', null, $entry['guid']);
592 $this->element('link', null, $entry['link']);
594 # RSS only supports 1 enclosure per item
595 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
596 $enclosure = $entry['enclosures'][0];
597 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
600 if(array_key_exists('tags', $entry)){
601 foreach($entry['tags'] as $tag){
602 $this->element('category', null,$tag);
606 $this->showGeoRSS($entry['geo']);
607 $this->elementEnd('item');
610 function showJsonObjects($objects)
612 print(json_encode($objects));
615 function showSingleXmlStatus($notice)
617 $this->initDocument('xml');
618 $twitter_status = $this->twitterStatusArray($notice);
619 $this->showTwitterXmlStatus($twitter_status);
620 $this->endDocument('xml');
623 function show_single_json_status($notice)
625 $this->initDocument('json');
626 $status = $this->twitterStatusArray($notice);
627 $this->showJsonObjects($status);
628 $this->endDocument('json');
631 function showXmlTimeline($notice)
634 $this->initDocument('xml');
635 $this->elementStart('statuses', array('type' => 'array'));
637 if (is_array($notice)) {
638 foreach ($notice as $n) {
639 $twitter_status = $this->twitterStatusArray($n);
640 $this->showTwitterXmlStatus($twitter_status);
643 while ($notice->fetch()) {
644 $twitter_status = $this->twitterStatusArray($notice);
645 $this->showTwitterXmlStatus($twitter_status);
649 $this->elementEnd('statuses');
650 $this->endDocument('xml');
653 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
656 $this->initDocument('rss');
658 $this->element('title', null, $title);
659 $this->element('link', null, $link);
661 if (!is_null($self)) {
665 'type' => 'application/rss+xml',
672 if (!is_null($suplink)) {
673 // For FriendFeed's SUP protocol
674 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
675 'rel' => 'http://api.friendfeed.com/2008/03#sup',
677 'type' => 'application/json'));
680 if (!is_null($logo)) {
681 $this->elementStart('image');
682 $this->element('link', null, $link);
683 $this->element('title', null, $title);
684 $this->element('url', null, $logo);
685 $this->elementEnd('image');
688 $this->element('description', null, $subtitle);
689 $this->element('language', null, 'en-us');
690 $this->element('ttl', null, '40');
692 if (is_array($notice)) {
693 foreach ($notice as $n) {
694 $entry = $this->twitterRssEntryArray($n);
695 $this->showTwitterRssItem($entry);
698 while ($notice->fetch()) {
699 $entry = $this->twitterRssEntryArray($notice);
700 $this->showTwitterRssItem($entry);
704 $this->endTwitterRss();
707 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
710 $this->initDocument('atom');
712 $this->element('title', null, $title);
713 $this->element('id', null, $id);
714 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
716 if (!is_null($logo)) {
717 $this->element('logo',null,$logo);
720 if (!is_null($suplink)) {
721 # For FriendFeed's SUP protocol
722 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
724 'type' => 'application/json'));
727 if (!is_null($selfuri)) {
728 $this->element('link', array('href' => $selfuri,
729 'rel' => 'self', 'type' => 'application/atom+xml'), null);
732 $this->element('updated', null, common_date_iso8601('now'));
733 $this->element('subtitle', null, $subtitle);
735 if (is_array($notice)) {
736 foreach ($notice as $n) {
737 $this->raw($n->asAtomEntry());
740 while ($notice->fetch()) {
741 $this->raw($notice->asAtomEntry());
745 $this->endDocument('atom');
749 function showRssGroups($group, $title, $link, $subtitle)
752 $this->initDocument('rss');
754 $this->element('title', null, $title);
755 $this->element('link', null, $link);
756 $this->element('description', null, $subtitle);
757 $this->element('language', null, 'en-us');
758 $this->element('ttl', null, '40');
760 if (is_array($group)) {
761 foreach ($group as $g) {
762 $twitter_group = $this->twitterRssGroupArray($g);
763 $this->showTwitterRssItem($twitter_group);
766 while ($group->fetch()) {
767 $twitter_group = $this->twitterRssGroupArray($group);
768 $this->showTwitterRssItem($twitter_group);
772 $this->endTwitterRss();
775 function showTwitterAtomEntry($entry)
777 $this->elementStart('entry');
778 $this->element('title', null, common_xml_safe_str($entry['title']));
781 array('type' => 'html'),
782 common_xml_safe_str($entry['content'])
784 $this->element('id', null, $entry['id']);
785 $this->element('published', null, $entry['published']);
786 $this->element('updated', null, $entry['updated']);
787 $this->element('link', array('type' => 'text/html',
788 'href' => $entry['link'],
789 'rel' => 'alternate'));
790 $this->element('link', array('type' => $entry['avatar-type'],
791 'href' => $entry['avatar'],
793 $this->elementStart('author');
795 $this->element('name', null, $entry['author-name']);
796 $this->element('uri', null, $entry['author-uri']);
798 $this->elementEnd('author');
799 $this->elementEnd('entry');
802 function showXmlDirectMessage($dm)
804 $this->elementStart('direct_message');
805 foreach($dm as $element => $value) {
809 $this->showTwitterXmlUser($value, $element);
812 $this->element($element, null, common_xml_safe_str($value));
815 $this->element($element, null, $value);
819 $this->elementEnd('direct_message');
822 function directMessageArray($message)
826 $from_profile = $message->getFrom();
827 $to_profile = $message->getTo();
829 $dmsg['id'] = $message->id;
830 $dmsg['sender_id'] = $message->from_profile;
831 $dmsg['text'] = trim($message->content);
832 $dmsg['recipient_id'] = $message->to_profile;
833 $dmsg['created_at'] = $this->dateTwitter($message->created);
834 $dmsg['sender_screen_name'] = $from_profile->nickname;
835 $dmsg['recipient_screen_name'] = $to_profile->nickname;
836 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
837 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
842 function rssDirectMessageArray($message)
846 $from = $message->getFrom();
848 $entry['title'] = sprintf('Message from %1$s to %2$s',
849 $from->nickname, $message->getTo()->nickname);
851 $entry['content'] = common_xml_safe_str($message->rendered);
852 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
853 $entry['published'] = common_date_iso8601($message->created);
855 $taguribase = TagURI::base();
857 $entry['id'] = "tag:$taguribase:$entry[link]";
858 $entry['updated'] = $entry['published'];
860 $entry['author-name'] = $from->getBestName();
861 $entry['author-uri'] = $from->homepage;
863 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
865 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
866 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
870 $entry['description'] = $entry['content'];
871 $entry['pubDate'] = common_date_rfc2822($message->created);
872 $entry['guid'] = $entry['link'];
877 function showSingleXmlDirectMessage($message)
879 $this->initDocument('xml');
880 $dmsg = $this->directMessageArray($message);
881 $this->showXmlDirectMessage($dmsg);
882 $this->endDocument('xml');
885 function showSingleJsonDirectMessage($message)
887 $this->initDocument('json');
888 $dmsg = $this->directMessageArray($message);
889 $this->showJsonObjects($dmsg);
890 $this->endDocument('json');
893 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
896 $this->initDocument('atom');
898 $this->element('title', null, common_xml_safe_str($title));
899 $this->element('id', null, $id);
900 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
902 if (!is_null($selfuri)) {
903 $this->element('link', array('href' => $selfuri,
904 'rel' => 'self', 'type' => 'application/atom+xml'), null);
907 $this->element('updated', null, common_date_iso8601('now'));
908 $this->element('subtitle', null, common_xml_safe_str($subtitle));
910 if (is_array($group)) {
911 foreach ($group as $g) {
912 $this->raw($g->asAtomEntry());
915 while ($group->fetch()) {
916 $this->raw($group->asAtomEntry());
920 $this->endDocument('atom');
924 function showJsonTimeline($notice)
927 $this->initDocument('json');
931 if (is_array($notice)) {
932 foreach ($notice as $n) {
933 $twitter_status = $this->twitterStatusArray($n);
934 array_push($statuses, $twitter_status);
937 while ($notice->fetch()) {
938 $twitter_status = $this->twitterStatusArray($notice);
939 array_push($statuses, $twitter_status);
943 $this->showJsonObjects($statuses);
945 $this->endDocument('json');
948 function showJsonGroups($group)
951 $this->initDocument('json');
955 if (is_array($group)) {
956 foreach ($group as $g) {
957 $twitter_group = $this->twitterGroupArray($g);
958 array_push($groups, $twitter_group);
961 while ($group->fetch()) {
962 $twitter_group = $this->twitterGroupArray($group);
963 array_push($groups, $twitter_group);
967 $this->showJsonObjects($groups);
969 $this->endDocument('json');
972 function showXmlGroups($group)
975 $this->initDocument('xml');
976 $this->elementStart('groups', array('type' => 'array'));
978 if (is_array($group)) {
979 foreach ($group as $g) {
980 $twitter_group = $this->twitterGroupArray($g);
981 $this->showTwitterXmlGroup($twitter_group);
984 while ($group->fetch()) {
985 $twitter_group = $this->twitterGroupArray($group);
986 $this->showTwitterXmlGroup($twitter_group);
990 $this->elementEnd('groups');
991 $this->endDocument('xml');
994 function showTwitterXmlUsers($user)
997 $this->initDocument('xml');
998 $this->elementStart('users', array('type' => 'array'));
1000 if (is_array($user)) {
1001 foreach ($user as $u) {
1002 $twitter_user = $this->twitterUserArray($u);
1003 $this->showTwitterXmlUser($twitter_user);
1006 while ($user->fetch()) {
1007 $twitter_user = $this->twitterUserArray($user);
1008 $this->showTwitterXmlUser($twitter_user);
1012 $this->elementEnd('users');
1013 $this->endDocument('xml');
1016 function showJsonUsers($user)
1019 $this->initDocument('json');
1023 if (is_array($user)) {
1024 foreach ($user as $u) {
1025 $twitter_user = $this->twitterUserArray($u);
1026 array_push($users, $twitter_user);
1029 while ($user->fetch()) {
1030 $twitter_user = $this->twitterUserArray($user);
1031 array_push($users, $twitter_user);
1035 $this->showJsonObjects($users);
1037 $this->endDocument('json');
1040 function showSingleJsonGroup($group)
1042 $this->initDocument('json');
1043 $twitter_group = $this->twitterGroupArray($group);
1044 $this->showJsonObjects($twitter_group);
1045 $this->endDocument('json');
1048 function showSingleXmlGroup($group)
1050 $this->initDocument('xml');
1051 $twitter_group = $this->twitterGroupArray($group);
1052 $this->showTwitterXmlGroup($twitter_group);
1053 $this->endDocument('xml');
1056 function dateTwitter($dt)
1058 $dateStr = date('d F Y H:i:s', strtotime($dt));
1059 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1060 $d->setTimezone(new DateTimeZone(common_timezone()));
1061 return $d->format('D M d H:i:s O Y');
1064 function initDocument($type='xml')
1068 header('Content-Type: application/xml; charset=utf-8');
1072 header('Content-Type: application/json; charset=utf-8');
1074 // Check for JSONP callback
1075 $callback = $this->arg('callback');
1077 print $callback . '(';
1081 header("Content-Type: application/rss+xml; charset=utf-8");
1082 $this->initTwitterRss();
1085 header('Content-Type: application/atom+xml; charset=utf-8');
1086 $this->initTwitterAtom();
1089 $this->clientError(_('Not a supported data format.'));
1096 function endDocument($type='xml')
1104 // Check for JSONP callback
1105 $callback = $this->arg('callback');
1111 $this->endTwitterRss();
1114 $this->endTwitterRss();
1117 $this->clientError(_('Not a supported data format.'));
1123 function clientError($msg, $code = 400, $format = 'xml')
1125 $action = $this->trimmed('action');
1127 common_debug("User error '$code' on '$action': $msg", __FILE__);
1129 if (!array_key_exists($code, ClientErrorAction::$status)) {
1133 $status_string = ClientErrorAction::$status[$code];
1135 header('HTTP/1.1 '.$code.' '.$status_string);
1137 if ($format == 'xml') {
1138 $this->initDocument('xml');
1139 $this->elementStart('hash');
1140 $this->element('error', null, $msg);
1141 $this->element('request', null, $_SERVER['REQUEST_URI']);
1142 $this->elementEnd('hash');
1143 $this->endDocument('xml');
1144 } elseif ($format == 'json'){
1145 $this->initDocument('json');
1146 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1147 print(json_encode($error_array));
1148 $this->endDocument('json');
1151 // If user didn't request a useful format, throw a regular client error
1152 throw new ClientException($msg, $code);
1156 function serverError($msg, $code = 500, $content_type = 'xml')
1158 $action = $this->trimmed('action');
1160 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1162 if (!array_key_exists($code, ServerErrorAction::$status)) {
1166 $status_string = ServerErrorAction::$status[$code];
1168 header('HTTP/1.1 '.$code.' '.$status_string);
1170 if ($content_type == 'xml') {
1171 $this->initDocument('xml');
1172 $this->elementStart('hash');
1173 $this->element('error', null, $msg);
1174 $this->element('request', null, $_SERVER['REQUEST_URI']);
1175 $this->elementEnd('hash');
1176 $this->endDocument('xml');
1178 $this->initDocument('json');
1179 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1180 print(json_encode($error_array));
1181 $this->endDocument('json');
1185 function initTwitterRss()
1188 $this->elementStart(
1192 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1193 'xmlns:georss' => 'http://www.georss.org/georss'
1196 $this->elementStart('channel');
1197 Event::handle('StartApiRss', array($this));
1200 function endTwitterRss()
1202 $this->elementEnd('channel');
1203 $this->elementEnd('rss');
1207 function initTwitterAtom()
1210 // FIXME: don't hardcode the language here!
1211 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1212 'xml:lang' => 'en-US',
1213 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1216 function endTwitterAtom()
1218 $this->elementEnd('feed');
1222 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1224 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1225 switch ($content_type) {
1227 $this->showTwitterXmlUser($profile_array);
1230 $this->showJsonObjects($profile_array);
1233 $this->clientError(_('Not a supported data format.'));
1239 function getTargetUser($id)
1243 // Twitter supports these other ways of passing the user ID
1244 if (is_numeric($this->arg('id'))) {
1245 return User::staticGet($this->arg('id'));
1246 } else if ($this->arg('id')) {
1247 $nickname = common_canonical_nickname($this->arg('id'));
1248 return User::staticGet('nickname', $nickname);
1249 } else if ($this->arg('user_id')) {
1250 // This is to ensure that a non-numeric user_id still
1251 // overrides screen_name even if it doesn't get used
1252 if (is_numeric($this->arg('user_id'))) {
1253 return User::staticGet('id', $this->arg('user_id'));
1255 } else if ($this->arg('screen_name')) {
1256 $nickname = common_canonical_nickname($this->arg('screen_name'));
1257 return User::staticGet('nickname', $nickname);
1259 // Fall back to trying the currently authenticated user
1260 return $this->auth_user;
1263 } else if (is_numeric($id)) {
1264 return User::staticGet($id);
1266 $nickname = common_canonical_nickname($id);
1267 return User::staticGet('nickname', $nickname);
1271 function getTargetGroup($id)
1274 if (is_numeric($this->arg('id'))) {
1275 return User_group::staticGet($this->arg('id'));
1276 } else if ($this->arg('id')) {
1277 $nickname = common_canonical_nickname($this->arg('id'));
1278 $local = Local_group::staticGet('nickname', $nickname);
1279 if (empty($local)) {
1282 return User_group::staticGet('id', $local->id);
1284 } else if ($this->arg('group_id')) {
1285 // This is to ensure that a non-numeric user_id still
1286 // overrides screen_name even if it doesn't get used
1287 if (is_numeric($this->arg('group_id'))) {
1288 return User_group::staticGet('id', $this->arg('group_id'));
1290 } else if ($this->arg('group_name')) {
1291 $nickname = common_canonical_nickname($this->arg('group_name'));
1292 $local = Local_group::staticGet('nickname', $nickname);
1293 if (empty($local)) {
1296 return User_group::staticGet('id', $local->group_id);
1300 } else if (is_numeric($id)) {
1301 return User_group::staticGet($id);
1303 $nickname = common_canonical_nickname($id);
1304 $local = Local_group::staticGet('nickname', $nickname);
1305 if (empty($local)) {
1308 return User_group::staticGet('id', $local->group_id);
1314 * Returns query argument or default value if not found. Certain
1315 * parameters used throughout the API are lightly scrubbed and
1316 * bounds checked. This overrides Action::arg().
1318 * @param string $key requested argument
1319 * @param string $def default value to return if $key is not provided
1323 function arg($key, $def=null)
1326 // XXX: Do even more input validation/scrubbing?
1328 if (array_key_exists($key, $this->args)) {
1331 $page = (int)$this->args['page'];
1332 return ($page < 1) ? 1 : $page;
1334 $count = (int)$this->args['count'];
1337 } elseif ($count > 200) {
1343 $since_id = (int)$this->args['since_id'];
1344 return ($since_id < 1) ? 0 : $since_id;
1346 $max_id = (int)$this->args['max_id'];
1347 return ($max_id < 1) ? 0 : $max_id;
1349 return parent::arg($key, $def);
1357 * Calculate the complete URI that called up this action. Used for
1358 * Atom rel="self" links. Warning: this is funky.
1360 * @return string URL a URL suitable for rel="self" Atom links
1362 function getSelfUri()
1364 $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1366 $id = $this->arg('id');
1367 $aargs = array('format' => $this->format);
1372 $tag = $this->arg('tag');
1374 $aargs['tag'] = $tag;
1377 parse_str($_SERVER['QUERY_STRING'], $params);
1379 if (!empty($params)) {
1380 unset($params['p']);
1381 $pstring = http_build_query($params);
1384 $uri = common_local_url($action, $aargs);
1386 if (!empty($pstring)) {
1387 $uri .= '?' . $pstring;