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 // StatusNet-specific
237 $twitter_user['statusnet:profile_url'] = $profile->profileurl;
239 return $twitter_user;
242 function twitterStatusArray($notice, $include_user=true)
244 $base = $this->twitterSimpleStatusArray($notice, $include_user);
246 if (!empty($notice->repeat_of)) {
247 $original = Notice::staticGet('id', $notice->repeat_of);
248 if (!empty($original)) {
249 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
250 $base['retweeted_status'] = $original_array;
257 function twitterSimpleStatusArray($notice, $include_user=true)
259 $profile = $notice->getProfile();
261 $twitter_status = array();
262 $twitter_status['text'] = $notice->content;
263 $twitter_status['truncated'] = false; # Not possible on StatusNet
264 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
265 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
266 intval($notice->reply_to) : null;
270 $ns = $notice->getSource();
272 if (!empty($ns->name) && !empty($ns->url)) {
273 $source = '<a href="'
274 . htmlspecialchars($ns->url)
275 . '" rel="nofollow">'
276 . htmlspecialchars($ns->name)
283 $twitter_status['source'] = $source;
284 $twitter_status['id'] = intval($notice->id);
286 $replier_profile = null;
288 if ($notice->reply_to) {
289 $reply = Notice::staticGet(intval($notice->reply_to));
291 $replier_profile = $reply->getProfile();
295 $twitter_status['in_reply_to_user_id'] =
296 ($replier_profile) ? intval($replier_profile->id) : null;
297 $twitter_status['in_reply_to_screen_name'] =
298 ($replier_profile) ? $replier_profile->nickname : null;
300 if (isset($notice->lat) && isset($notice->lon)) {
301 // This is the format that GeoJSON expects stuff to be in
302 $twitter_status['geo'] = array('type' => 'Point',
303 'coordinates' => array((float) $notice->lat,
304 (float) $notice->lon));
306 $twitter_status['geo'] = null;
309 if (isset($this->auth_user)) {
310 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
312 $twitter_status['favorited'] = false;
316 $attachments = $notice->attachments();
318 if (!empty($attachments)) {
320 $twitter_status['attachments'] = array();
322 foreach ($attachments as $attachment) {
323 $enclosure_o=$attachment->getEnclosure();
325 $enclosure = array();
326 $enclosure['url'] = $enclosure_o->url;
327 $enclosure['mimetype'] = $enclosure_o->mimetype;
328 $enclosure['size'] = $enclosure_o->size;
329 $twitter_status['attachments'][] = $enclosure;
334 if ($include_user && $profile) {
335 # Don't get notice (recursive!)
336 $twitter_user = $this->twitterUserArray($profile, false);
337 $twitter_status['user'] = $twitter_user;
340 // StatusNet-specific
342 $twitter_status['statusnet:html'] = $notice->rendered;
344 return $twitter_status;
347 function twitterGroupArray($group)
349 $twitter_group = array();
351 $twitter_group['id'] = $group->id;
352 $twitter_group['url'] = $group->permalink();
353 $twitter_group['nickname'] = $group->nickname;
354 $twitter_group['fullname'] = $group->fullname;
356 if (isset($this->auth_user)) {
357 $twitter_group['member'] = $this->auth_user->isMember($group);
358 $twitter_group['blocked'] = Group_block::isBlocked(
360 $this->auth_user->getProfile()
364 $twitter_group['member_count'] = $group->getMemberCount();
365 $twitter_group['original_logo'] = $group->original_logo;
366 $twitter_group['homepage_logo'] = $group->homepage_logo;
367 $twitter_group['stream_logo'] = $group->stream_logo;
368 $twitter_group['mini_logo'] = $group->mini_logo;
369 $twitter_group['homepage'] = $group->homepage;
370 $twitter_group['description'] = $group->description;
371 $twitter_group['location'] = $group->location;
372 $twitter_group['created'] = $this->dateTwitter($group->created);
373 $twitter_group['modified'] = $this->dateTwitter($group->modified);
375 return $twitter_group;
378 function twitterRssGroupArray($group)
381 $entry['content']=$group->description;
382 $entry['title']=$group->nickname;
383 $entry['link']=$group->permalink();
384 $entry['published']=common_date_iso8601($group->created);
385 $entry['updated']==common_date_iso8601($group->modified);
386 $taguribase = common_config('integration', 'groupuri');
387 $entry['id'] = "group:$groupuribase:$entry[link]";
389 $entry['description'] = $entry['content'];
390 $entry['pubDate'] = common_date_rfc2822($group->created);
391 $entry['guid'] = $entry['link'];
396 function twitterRssEntryArray($notice)
398 $profile = $notice->getProfile();
401 // We trim() to avoid extraneous whitespace in the output
403 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
404 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
405 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
406 $entry['published'] = common_date_iso8601($notice->created);
408 $taguribase = TagURI::base();
409 $entry['id'] = "tag:$taguribase:$entry[link]";
411 $entry['updated'] = $entry['published'];
412 $entry['author'] = $profile->getBestName();
415 $attachments = $notice->attachments();
416 $enclosures = array();
418 foreach ($attachments as $attachment) {
419 $enclosure_o=$attachment->getEnclosure();
421 $enclosure = array();
422 $enclosure['url'] = $enclosure_o->url;
423 $enclosure['mimetype'] = $enclosure_o->mimetype;
424 $enclosure['size'] = $enclosure_o->size;
425 $enclosures[] = $enclosure;
429 if (!empty($enclosures)) {
430 $entry['enclosures'] = $enclosures;
434 $tag = new Notice_tag();
435 $tag->notice_id = $notice->id;
437 $entry['tags']=array();
438 while ($tag->fetch()) {
439 $entry['tags'][]=$tag->tag;
445 $entry['description'] = $entry['content'];
446 $entry['pubDate'] = common_date_rfc2822($notice->created);
447 $entry['guid'] = $entry['link'];
449 if (isset($notice->lat) && isset($notice->lon)) {
450 // This is the format that GeoJSON expects stuff to be in.
451 // showGeoRSS() below uses it for XML output, so we reuse it
452 $entry['geo'] = array('type' => 'Point',
453 'coordinates' => array((float) $notice->lat,
454 (float) $notice->lon));
456 $entry['geo'] = null;
462 function twitterRelationshipArray($source, $target)
464 $relationship = array();
466 $relationship['source'] =
467 $this->relationshipDetailsArray($source, $target);
468 $relationship['target'] =
469 $this->relationshipDetailsArray($target, $source);
471 return array('relationship' => $relationship);
474 function relationshipDetailsArray($source, $target)
478 $details['screen_name'] = $source->nickname;
479 $details['followed_by'] = $target->isSubscribed($source);
480 $details['following'] = $source->isSubscribed($target);
482 $notifications = false;
484 if ($source->isSubscribed($target)) {
486 $sub = Subscription::pkeyGet(array('subscriber' =>
487 $source->id, 'subscribed' => $target->id));
490 $notifications = ($sub->jabber || $sub->sms);
494 $details['notifications_enabled'] = $notifications;
495 $details['blocking'] = $source->hasBlocked($target);
496 $details['id'] = $source->id;
501 function showTwitterXmlRelationship($relationship)
503 $this->elementStart('relationship');
505 foreach($relationship as $element => $value) {
506 if ($element == 'source' || $element == 'target') {
507 $this->elementStart($element);
508 $this->showXmlRelationshipDetails($value);
509 $this->elementEnd($element);
513 $this->elementEnd('relationship');
516 function showXmlRelationshipDetails($details)
518 foreach($details as $element => $value) {
519 $this->element($element, null, $value);
523 function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
527 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
529 $this->elementStart($tag, $attrs);
530 foreach($twitter_status as $element => $value) {
533 $this->showTwitterXmlUser($twitter_status['user']);
536 $this->element($element, null, common_xml_safe_str($value));
539 $this->showXmlAttachments($twitter_status['attachments']);
542 $this->showGeoXML($value);
544 case 'retweeted_status':
545 $this->showTwitterXmlStatus($value, 'retweeted_status');
548 $this->element($element, null, $value);
551 $this->elementEnd($tag);
554 function showTwitterXmlGroup($twitter_group)
556 $this->elementStart('group');
557 foreach($twitter_group as $element => $value) {
558 $this->element($element, null, $value);
560 $this->elementEnd('group');
563 function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
567 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
569 $this->elementStart($role, $attrs);
570 foreach($twitter_user as $element => $value) {
571 if ($element == 'status') {
572 $this->showTwitterXmlStatus($twitter_user['status']);
574 $this->element($element, null, $value);
577 $this->elementEnd($role);
580 function showXmlAttachments($attachments) {
581 if (!empty($attachments)) {
582 $this->elementStart('attachments', array('type' => 'array'));
583 foreach ($attachments as $attachment) {
585 $attrs['url'] = $attachment['url'];
586 $attrs['mimetype'] = $attachment['mimetype'];
587 $attrs['size'] = $attachment['size'];
588 $this->element('enclosure', $attrs, '');
590 $this->elementEnd('attachments');
594 function showGeoXML($geo)
598 $this->element('geo');
600 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
601 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
602 $this->elementEnd('geo');
606 function showGeoRSS($geo)
612 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
617 function showTwitterRssItem($entry)
619 $this->elementStart('item');
620 $this->element('title', null, $entry['title']);
621 $this->element('description', null, $entry['description']);
622 $this->element('pubDate', null, $entry['pubDate']);
623 $this->element('guid', null, $entry['guid']);
624 $this->element('link', null, $entry['link']);
626 # RSS only supports 1 enclosure per item
627 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
628 $enclosure = $entry['enclosures'][0];
629 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
632 if(array_key_exists('tags', $entry)){
633 foreach($entry['tags'] as $tag){
634 $this->element('category', null,$tag);
638 $this->showGeoRSS($entry['geo']);
639 $this->elementEnd('item');
642 function showJsonObjects($objects)
644 print(json_encode($objects));
647 function showSingleXmlStatus($notice)
649 $this->initDocument('xml');
650 $twitter_status = $this->twitterStatusArray($notice);
651 $this->showTwitterXmlStatus($twitter_status, 'status', true);
652 $this->endDocument('xml');
655 function show_single_json_status($notice)
657 $this->initDocument('json');
658 $status = $this->twitterStatusArray($notice);
659 $this->showJsonObjects($status);
660 $this->endDocument('json');
663 function showXmlTimeline($notice)
666 $this->initDocument('xml');
667 $this->elementStart('statuses', array('type' => 'array',
668 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
670 if (is_array($notice)) {
671 foreach ($notice as $n) {
672 $twitter_status = $this->twitterStatusArray($n);
673 $this->showTwitterXmlStatus($twitter_status);
676 while ($notice->fetch()) {
677 $twitter_status = $this->twitterStatusArray($notice);
678 $this->showTwitterXmlStatus($twitter_status);
682 $this->elementEnd('statuses');
683 $this->endDocument('xml');
686 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
689 $this->initDocument('rss');
691 $this->element('title', null, $title);
692 $this->element('link', null, $link);
694 if (!is_null($self)) {
698 'type' => 'application/rss+xml',
705 if (!is_null($suplink)) {
706 // For FriendFeed's SUP protocol
707 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
708 'rel' => 'http://api.friendfeed.com/2008/03#sup',
710 'type' => 'application/json'));
713 if (!is_null($logo)) {
714 $this->elementStart('image');
715 $this->element('link', null, $link);
716 $this->element('title', null, $title);
717 $this->element('url', null, $logo);
718 $this->elementEnd('image');
721 $this->element('description', null, $subtitle);
722 $this->element('language', null, 'en-us');
723 $this->element('ttl', null, '40');
725 if (is_array($notice)) {
726 foreach ($notice as $n) {
727 $entry = $this->twitterRssEntryArray($n);
728 $this->showTwitterRssItem($entry);
731 while ($notice->fetch()) {
732 $entry = $this->twitterRssEntryArray($notice);
733 $this->showTwitterRssItem($entry);
737 $this->endTwitterRss();
740 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
743 $this->initDocument('atom');
745 $this->element('title', null, $title);
746 $this->element('id', null, $id);
747 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
749 if (!is_null($logo)) {
750 $this->element('logo',null,$logo);
753 if (!is_null($suplink)) {
754 # For FriendFeed's SUP protocol
755 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
757 'type' => 'application/json'));
760 if (!is_null($selfuri)) {
761 $this->element('link', array('href' => $selfuri,
762 'rel' => 'self', 'type' => 'application/atom+xml'), null);
765 $this->element('updated', null, common_date_iso8601('now'));
766 $this->element('subtitle', null, $subtitle);
768 if (is_array($notice)) {
769 foreach ($notice as $n) {
770 $this->raw($n->asAtomEntry());
773 while ($notice->fetch()) {
774 $this->raw($notice->asAtomEntry());
778 $this->endDocument('atom');
782 function showRssGroups($group, $title, $link, $subtitle)
785 $this->initDocument('rss');
787 $this->element('title', null, $title);
788 $this->element('link', null, $link);
789 $this->element('description', null, $subtitle);
790 $this->element('language', null, 'en-us');
791 $this->element('ttl', null, '40');
793 if (is_array($group)) {
794 foreach ($group as $g) {
795 $twitter_group = $this->twitterRssGroupArray($g);
796 $this->showTwitterRssItem($twitter_group);
799 while ($group->fetch()) {
800 $twitter_group = $this->twitterRssGroupArray($group);
801 $this->showTwitterRssItem($twitter_group);
805 $this->endTwitterRss();
808 function showTwitterAtomEntry($entry)
810 $this->elementStart('entry');
811 $this->element('title', null, common_xml_safe_str($entry['title']));
814 array('type' => 'html'),
815 common_xml_safe_str($entry['content'])
817 $this->element('id', null, $entry['id']);
818 $this->element('published', null, $entry['published']);
819 $this->element('updated', null, $entry['updated']);
820 $this->element('link', array('type' => 'text/html',
821 'href' => $entry['link'],
822 'rel' => 'alternate'));
823 $this->element('link', array('type' => $entry['avatar-type'],
824 'href' => $entry['avatar'],
826 $this->elementStart('author');
828 $this->element('name', null, $entry['author-name']);
829 $this->element('uri', null, $entry['author-uri']);
831 $this->elementEnd('author');
832 $this->elementEnd('entry');
835 function showXmlDirectMessage($dm, $namespaces=false)
839 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
841 $this->elementStart('direct_message', $attrs);
842 foreach($dm as $element => $value) {
846 $this->showTwitterXmlUser($value, $element);
849 $this->element($element, null, common_xml_safe_str($value));
852 $this->element($element, null, $value);
856 $this->elementEnd('direct_message');
859 function directMessageArray($message)
863 $from_profile = $message->getFrom();
864 $to_profile = $message->getTo();
866 $dmsg['id'] = $message->id;
867 $dmsg['sender_id'] = $message->from_profile;
868 $dmsg['text'] = trim($message->content);
869 $dmsg['recipient_id'] = $message->to_profile;
870 $dmsg['created_at'] = $this->dateTwitter($message->created);
871 $dmsg['sender_screen_name'] = $from_profile->nickname;
872 $dmsg['recipient_screen_name'] = $to_profile->nickname;
873 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
874 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
879 function rssDirectMessageArray($message)
883 $from = $message->getFrom();
885 $entry['title'] = sprintf('Message from %1$s to %2$s',
886 $from->nickname, $message->getTo()->nickname);
888 $entry['content'] = common_xml_safe_str($message->rendered);
889 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
890 $entry['published'] = common_date_iso8601($message->created);
892 $taguribase = TagURI::base();
894 $entry['id'] = "tag:$taguribase:$entry[link]";
895 $entry['updated'] = $entry['published'];
897 $entry['author-name'] = $from->getBestName();
898 $entry['author-uri'] = $from->homepage;
900 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
902 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
903 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
907 $entry['description'] = $entry['content'];
908 $entry['pubDate'] = common_date_rfc2822($message->created);
909 $entry['guid'] = $entry['link'];
914 function showSingleXmlDirectMessage($message)
916 $this->initDocument('xml');
917 $dmsg = $this->directMessageArray($message);
918 $this->showXmlDirectMessage($dmsg, true);
919 $this->endDocument('xml');
922 function showSingleJsonDirectMessage($message)
924 $this->initDocument('json');
925 $dmsg = $this->directMessageArray($message);
926 $this->showJsonObjects($dmsg);
927 $this->endDocument('json');
930 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
933 $this->initDocument('atom');
935 $this->element('title', null, common_xml_safe_str($title));
936 $this->element('id', null, $id);
937 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
939 if (!is_null($selfuri)) {
940 $this->element('link', array('href' => $selfuri,
941 'rel' => 'self', 'type' => 'application/atom+xml'), null);
944 $this->element('updated', null, common_date_iso8601('now'));
945 $this->element('subtitle', null, common_xml_safe_str($subtitle));
947 if (is_array($group)) {
948 foreach ($group as $g) {
949 $this->raw($g->asAtomEntry());
952 while ($group->fetch()) {
953 $this->raw($group->asAtomEntry());
957 $this->endDocument('atom');
961 function showJsonTimeline($notice)
964 $this->initDocument('json');
968 if (is_array($notice)) {
969 foreach ($notice as $n) {
970 $twitter_status = $this->twitterStatusArray($n);
971 array_push($statuses, $twitter_status);
974 while ($notice->fetch()) {
975 $twitter_status = $this->twitterStatusArray($notice);
976 array_push($statuses, $twitter_status);
980 $this->showJsonObjects($statuses);
982 $this->endDocument('json');
985 function showJsonGroups($group)
988 $this->initDocument('json');
992 if (is_array($group)) {
993 foreach ($group as $g) {
994 $twitter_group = $this->twitterGroupArray($g);
995 array_push($groups, $twitter_group);
998 while ($group->fetch()) {
999 $twitter_group = $this->twitterGroupArray($group);
1000 array_push($groups, $twitter_group);
1004 $this->showJsonObjects($groups);
1006 $this->endDocument('json');
1009 function showXmlGroups($group)
1012 $this->initDocument('xml');
1013 $this->elementStart('groups', array('type' => 'array'));
1015 if (is_array($group)) {
1016 foreach ($group as $g) {
1017 $twitter_group = $this->twitterGroupArray($g);
1018 $this->showTwitterXmlGroup($twitter_group);
1021 while ($group->fetch()) {
1022 $twitter_group = $this->twitterGroupArray($group);
1023 $this->showTwitterXmlGroup($twitter_group);
1027 $this->elementEnd('groups');
1028 $this->endDocument('xml');
1031 function showTwitterXmlUsers($user)
1034 $this->initDocument('xml');
1035 $this->elementStart('users', array('type' => 'array',
1036 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1038 if (is_array($user)) {
1039 foreach ($user as $u) {
1040 $twitter_user = $this->twitterUserArray($u);
1041 $this->showTwitterXmlUser($twitter_user);
1044 while ($user->fetch()) {
1045 $twitter_user = $this->twitterUserArray($user);
1046 $this->showTwitterXmlUser($twitter_user);
1050 $this->elementEnd('users');
1051 $this->endDocument('xml');
1054 function showJsonUsers($user)
1057 $this->initDocument('json');
1061 if (is_array($user)) {
1062 foreach ($user as $u) {
1063 $twitter_user = $this->twitterUserArray($u);
1064 array_push($users, $twitter_user);
1067 while ($user->fetch()) {
1068 $twitter_user = $this->twitterUserArray($user);
1069 array_push($users, $twitter_user);
1073 $this->showJsonObjects($users);
1075 $this->endDocument('json');
1078 function showSingleJsonGroup($group)
1080 $this->initDocument('json');
1081 $twitter_group = $this->twitterGroupArray($group);
1082 $this->showJsonObjects($twitter_group);
1083 $this->endDocument('json');
1086 function showSingleXmlGroup($group)
1088 $this->initDocument('xml');
1089 $twitter_group = $this->twitterGroupArray($group);
1090 $this->showTwitterXmlGroup($twitter_group);
1091 $this->endDocument('xml');
1094 function dateTwitter($dt)
1096 $dateStr = date('d F Y H:i:s', strtotime($dt));
1097 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1098 $d->setTimezone(new DateTimeZone(common_timezone()));
1099 return $d->format('D M d H:i:s O Y');
1102 function initDocument($type='xml')
1106 header('Content-Type: application/xml; charset=utf-8');
1110 header('Content-Type: application/json; charset=utf-8');
1112 // Check for JSONP callback
1113 $callback = $this->arg('callback');
1115 print $callback . '(';
1119 header("Content-Type: application/rss+xml; charset=utf-8");
1120 $this->initTwitterRss();
1123 header('Content-Type: application/atom+xml; charset=utf-8');
1124 $this->initTwitterAtom();
1127 $this->clientError(_('Not a supported data format.'));
1134 function endDocument($type='xml')
1142 // Check for JSONP callback
1143 $callback = $this->arg('callback');
1149 $this->endTwitterRss();
1152 $this->endTwitterRss();
1155 $this->clientError(_('Not a supported data format.'));
1161 function clientError($msg, $code = 400, $format = 'xml')
1163 $action = $this->trimmed('action');
1165 common_debug("User error '$code' on '$action': $msg", __FILE__);
1167 if (!array_key_exists($code, ClientErrorAction::$status)) {
1171 $status_string = ClientErrorAction::$status[$code];
1173 header('HTTP/1.1 '.$code.' '.$status_string);
1175 if ($format == 'xml') {
1176 $this->initDocument('xml');
1177 $this->elementStart('hash');
1178 $this->element('error', null, $msg);
1179 $this->element('request', null, $_SERVER['REQUEST_URI']);
1180 $this->elementEnd('hash');
1181 $this->endDocument('xml');
1182 } elseif ($format == 'json'){
1183 $this->initDocument('json');
1184 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1185 print(json_encode($error_array));
1186 $this->endDocument('json');
1189 // If user didn't request a useful format, throw a regular client error
1190 throw new ClientException($msg, $code);
1194 function serverError($msg, $code = 500, $content_type = 'xml')
1196 $action = $this->trimmed('action');
1198 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1200 if (!array_key_exists($code, ServerErrorAction::$status)) {
1204 $status_string = ServerErrorAction::$status[$code];
1206 header('HTTP/1.1 '.$code.' '.$status_string);
1208 if ($content_type == 'xml') {
1209 $this->initDocument('xml');
1210 $this->elementStart('hash');
1211 $this->element('error', null, $msg);
1212 $this->element('request', null, $_SERVER['REQUEST_URI']);
1213 $this->elementEnd('hash');
1214 $this->endDocument('xml');
1216 $this->initDocument('json');
1217 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1218 print(json_encode($error_array));
1219 $this->endDocument('json');
1223 function initTwitterRss()
1226 $this->elementStart(
1230 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1231 'xmlns:georss' => 'http://www.georss.org/georss'
1234 $this->elementStart('channel');
1235 Event::handle('StartApiRss', array($this));
1238 function endTwitterRss()
1240 $this->elementEnd('channel');
1241 $this->elementEnd('rss');
1245 function initTwitterAtom()
1248 // FIXME: don't hardcode the language here!
1249 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1250 'xml:lang' => 'en-US',
1251 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1254 function endTwitterAtom()
1256 $this->elementEnd('feed');
1260 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1262 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1263 switch ($content_type) {
1265 $this->showTwitterXmlUser($profile_array);
1268 $this->showJsonObjects($profile_array);
1271 $this->clientError(_('Not a supported data format.'));
1277 function getTargetUser($id)
1281 // Twitter supports these other ways of passing the user ID
1282 if (is_numeric($this->arg('id'))) {
1283 return User::staticGet($this->arg('id'));
1284 } else if ($this->arg('id')) {
1285 $nickname = common_canonical_nickname($this->arg('id'));
1286 return User::staticGet('nickname', $nickname);
1287 } else if ($this->arg('user_id')) {
1288 // This is to ensure that a non-numeric user_id still
1289 // overrides screen_name even if it doesn't get used
1290 if (is_numeric($this->arg('user_id'))) {
1291 return User::staticGet('id', $this->arg('user_id'));
1293 } else if ($this->arg('screen_name')) {
1294 $nickname = common_canonical_nickname($this->arg('screen_name'));
1295 return User::staticGet('nickname', $nickname);
1297 // Fall back to trying the currently authenticated user
1298 return $this->auth_user;
1301 } else if (is_numeric($id)) {
1302 return User::staticGet($id);
1304 $nickname = common_canonical_nickname($id);
1305 return User::staticGet('nickname', $nickname);
1309 function getTargetGroup($id)
1312 if (is_numeric($this->arg('id'))) {
1313 return User_group::staticGet($this->arg('id'));
1314 } else if ($this->arg('id')) {
1315 $nickname = common_canonical_nickname($this->arg('id'));
1316 $local = Local_group::staticGet('nickname', $nickname);
1317 if (empty($local)) {
1320 return User_group::staticGet('id', $local->id);
1322 } else if ($this->arg('group_id')) {
1323 // This is to ensure that a non-numeric user_id still
1324 // overrides screen_name even if it doesn't get used
1325 if (is_numeric($this->arg('group_id'))) {
1326 return User_group::staticGet('id', $this->arg('group_id'));
1328 } else if ($this->arg('group_name')) {
1329 $nickname = common_canonical_nickname($this->arg('group_name'));
1330 $local = Local_group::staticGet('nickname', $nickname);
1331 if (empty($local)) {
1334 return User_group::staticGet('id', $local->group_id);
1338 } else if (is_numeric($id)) {
1339 return User_group::staticGet($id);
1341 $nickname = common_canonical_nickname($id);
1342 $local = Local_group::staticGet('nickname', $nickname);
1343 if (empty($local)) {
1346 return User_group::staticGet('id', $local->group_id);
1352 * Returns query argument or default value if not found. Certain
1353 * parameters used throughout the API are lightly scrubbed and
1354 * bounds checked. This overrides Action::arg().
1356 * @param string $key requested argument
1357 * @param string $def default value to return if $key is not provided
1361 function arg($key, $def=null)
1364 // XXX: Do even more input validation/scrubbing?
1366 if (array_key_exists($key, $this->args)) {
1369 $page = (int)$this->args['page'];
1370 return ($page < 1) ? 1 : $page;
1372 $count = (int)$this->args['count'];
1375 } elseif ($count > 200) {
1381 $since_id = (int)$this->args['since_id'];
1382 return ($since_id < 1) ? 0 : $since_id;
1384 $max_id = (int)$this->args['max_id'];
1385 return ($max_id < 1) ? 0 : $max_id;
1387 return parent::arg($key, $def);
1395 * Calculate the complete URI that called up this action. Used for
1396 * Atom rel="self" links. Warning: this is funky.
1398 * @return string URL a URL suitable for rel="self" Atom links
1400 function getSelfUri()
1402 $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1404 $id = $this->arg('id');
1405 $aargs = array('format' => $this->format);
1410 $tag = $this->arg('tag');
1412 $aargs['tag'] = $tag;
1415 parse_str($_SERVER['QUERY_STRING'], $params);
1417 if (!empty($params)) {
1418 unset($params['p']);
1419 $pstring = http_build_query($params);
1422 $uri = common_local_url($action, $aargs);
1424 if (!empty($pstring)) {
1425 $uri .= '?' . $pstring;