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();
350 $twitter_group['id']=$group->id;
351 $twitter_group['url']=$group->permalink();
352 $twitter_group['nickname']=$group->nickname;
353 $twitter_group['fullname']=$group->fullname;
354 $twitter_group['original_logo']=$group->original_logo;
355 $twitter_group['homepage_logo']=$group->homepage_logo;
356 $twitter_group['stream_logo']=$group->stream_logo;
357 $twitter_group['mini_logo']=$group->mini_logo;
358 $twitter_group['homepage']=$group->homepage;
359 $twitter_group['description']=$group->description;
360 $twitter_group['location']=$group->location;
361 $twitter_group['created']=$this->dateTwitter($group->created);
362 $twitter_group['modified']=$this->dateTwitter($group->modified);
363 return $twitter_group;
366 function twitterRssGroupArray($group)
369 $entry['content']=$group->description;
370 $entry['title']=$group->nickname;
371 $entry['link']=$group->permalink();
372 $entry['published']=common_date_iso8601($group->created);
373 $entry['updated']==common_date_iso8601($group->modified);
374 $taguribase = common_config('integration', 'groupuri');
375 $entry['id'] = "group:$groupuribase:$entry[link]";
377 $entry['description'] = $entry['content'];
378 $entry['pubDate'] = common_date_rfc2822($group->created);
379 $entry['guid'] = $entry['link'];
384 function twitterRssEntryArray($notice)
386 $profile = $notice->getProfile();
389 // We trim() to avoid extraneous whitespace in the output
391 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
392 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
393 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
394 $entry['published'] = common_date_iso8601($notice->created);
396 $taguribase = TagURI::base();
397 $entry['id'] = "tag:$taguribase:$entry[link]";
399 $entry['updated'] = $entry['published'];
400 $entry['author'] = $profile->getBestName();
403 $attachments = $notice->attachments();
404 $enclosures = array();
406 foreach ($attachments as $attachment) {
407 $enclosure_o=$attachment->getEnclosure();
409 $enclosure = array();
410 $enclosure['url'] = $enclosure_o->url;
411 $enclosure['mimetype'] = $enclosure_o->mimetype;
412 $enclosure['size'] = $enclosure_o->size;
413 $enclosures[] = $enclosure;
417 if (!empty($enclosures)) {
418 $entry['enclosures'] = $enclosures;
422 $tag = new Notice_tag();
423 $tag->notice_id = $notice->id;
425 $entry['tags']=array();
426 while ($tag->fetch()) {
427 $entry['tags'][]=$tag->tag;
433 $entry['description'] = $entry['content'];
434 $entry['pubDate'] = common_date_rfc2822($notice->created);
435 $entry['guid'] = $entry['link'];
437 if (isset($notice->lat) && isset($notice->lon)) {
438 // This is the format that GeoJSON expects stuff to be in.
439 // showGeoRSS() below uses it for XML output, so we reuse it
440 $entry['geo'] = array('type' => 'Point',
441 'coordinates' => array((float) $notice->lat,
442 (float) $notice->lon));
444 $entry['geo'] = null;
450 function twitterRelationshipArray($source, $target)
452 $relationship = array();
454 $relationship['source'] =
455 $this->relationshipDetailsArray($source, $target);
456 $relationship['target'] =
457 $this->relationshipDetailsArray($target, $source);
459 return array('relationship' => $relationship);
462 function relationshipDetailsArray($source, $target)
466 $details['screen_name'] = $source->nickname;
467 $details['followed_by'] = $target->isSubscribed($source);
468 $details['following'] = $source->isSubscribed($target);
470 $notifications = false;
472 if ($source->isSubscribed($target)) {
474 $sub = Subscription::pkeyGet(array('subscriber' =>
475 $source->id, 'subscribed' => $target->id));
478 $notifications = ($sub->jabber || $sub->sms);
482 $details['notifications_enabled'] = $notifications;
483 $details['blocking'] = $source->hasBlocked($target);
484 $details['id'] = $source->id;
489 function showTwitterXmlRelationship($relationship)
491 $this->elementStart('relationship');
493 foreach($relationship as $element => $value) {
494 if ($element == 'source' || $element == 'target') {
495 $this->elementStart($element);
496 $this->showXmlRelationshipDetails($value);
497 $this->elementEnd($element);
501 $this->elementEnd('relationship');
504 function showXmlRelationshipDetails($details)
506 foreach($details as $element => $value) {
507 $this->element($element, null, $value);
511 function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
515 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
517 $this->elementStart($tag, $attrs);
518 foreach($twitter_status as $element => $value) {
521 $this->showTwitterXmlUser($twitter_status['user']);
524 $this->element($element, null, common_xml_safe_str($value));
527 $this->showXmlAttachments($twitter_status['attachments']);
530 $this->showGeoXML($value);
532 case 'retweeted_status':
533 $this->showTwitterXmlStatus($value, 'retweeted_status');
536 $this->element($element, null, $value);
539 $this->elementEnd($tag);
542 function showTwitterXmlGroup($twitter_group)
544 $this->elementStart('group');
545 foreach($twitter_group as $element => $value) {
546 $this->element($element, null, $value);
548 $this->elementEnd('group');
551 function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
555 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
557 $this->elementStart($role, $attrs);
558 foreach($twitter_user as $element => $value) {
559 if ($element == 'status') {
560 $this->showTwitterXmlStatus($twitter_user['status']);
562 $this->element($element, null, $value);
565 $this->elementEnd($role);
568 function showXmlAttachments($attachments) {
569 if (!empty($attachments)) {
570 $this->elementStart('attachments', array('type' => 'array'));
571 foreach ($attachments as $attachment) {
573 $attrs['url'] = $attachment['url'];
574 $attrs['mimetype'] = $attachment['mimetype'];
575 $attrs['size'] = $attachment['size'];
576 $this->element('enclosure', $attrs, '');
578 $this->elementEnd('attachments');
582 function showGeoXML($geo)
586 $this->element('geo');
588 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
589 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
590 $this->elementEnd('geo');
594 function showGeoRSS($geo)
600 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
605 function showTwitterRssItem($entry)
607 $this->elementStart('item');
608 $this->element('title', null, $entry['title']);
609 $this->element('description', null, $entry['description']);
610 $this->element('pubDate', null, $entry['pubDate']);
611 $this->element('guid', null, $entry['guid']);
612 $this->element('link', null, $entry['link']);
614 # RSS only supports 1 enclosure per item
615 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
616 $enclosure = $entry['enclosures'][0];
617 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
620 if(array_key_exists('tags', $entry)){
621 foreach($entry['tags'] as $tag){
622 $this->element('category', null,$tag);
626 $this->showGeoRSS($entry['geo']);
627 $this->elementEnd('item');
630 function showJsonObjects($objects)
632 print(json_encode($objects));
635 function showSingleXmlStatus($notice)
637 $this->initDocument('xml');
638 $twitter_status = $this->twitterStatusArray($notice);
639 $this->showTwitterXmlStatus($twitter_status, 'status', true);
640 $this->endDocument('xml');
643 function show_single_json_status($notice)
645 $this->initDocument('json');
646 $status = $this->twitterStatusArray($notice);
647 $this->showJsonObjects($status);
648 $this->endDocument('json');
651 function showXmlTimeline($notice)
654 $this->initDocument('xml');
655 $this->elementStart('statuses', array('type' => 'array',
656 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
658 if (is_array($notice)) {
659 foreach ($notice as $n) {
660 $twitter_status = $this->twitterStatusArray($n);
661 $this->showTwitterXmlStatus($twitter_status);
664 while ($notice->fetch()) {
665 $twitter_status = $this->twitterStatusArray($notice);
666 $this->showTwitterXmlStatus($twitter_status);
670 $this->elementEnd('statuses');
671 $this->endDocument('xml');
674 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
677 $this->initDocument('rss');
679 $this->element('title', null, $title);
680 $this->element('link', null, $link);
682 if (!is_null($self)) {
686 'type' => 'application/rss+xml',
693 if (!is_null($suplink)) {
694 // For FriendFeed's SUP protocol
695 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
696 'rel' => 'http://api.friendfeed.com/2008/03#sup',
698 'type' => 'application/json'));
701 if (!is_null($logo)) {
702 $this->elementStart('image');
703 $this->element('link', null, $link);
704 $this->element('title', null, $title);
705 $this->element('url', null, $logo);
706 $this->elementEnd('image');
709 $this->element('description', null, $subtitle);
710 $this->element('language', null, 'en-us');
711 $this->element('ttl', null, '40');
713 if (is_array($notice)) {
714 foreach ($notice as $n) {
715 $entry = $this->twitterRssEntryArray($n);
716 $this->showTwitterRssItem($entry);
719 while ($notice->fetch()) {
720 $entry = $this->twitterRssEntryArray($notice);
721 $this->showTwitterRssItem($entry);
725 $this->endTwitterRss();
728 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
731 $this->initDocument('atom');
733 $this->element('title', null, $title);
734 $this->element('id', null, $id);
735 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
737 if (!is_null($logo)) {
738 $this->element('logo',null,$logo);
741 if (!is_null($suplink)) {
742 # For FriendFeed's SUP protocol
743 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
745 'type' => 'application/json'));
748 if (!is_null($selfuri)) {
749 $this->element('link', array('href' => $selfuri,
750 'rel' => 'self', 'type' => 'application/atom+xml'), null);
753 $this->element('updated', null, common_date_iso8601('now'));
754 $this->element('subtitle', null, $subtitle);
756 if (is_array($notice)) {
757 foreach ($notice as $n) {
758 $this->raw($n->asAtomEntry());
761 while ($notice->fetch()) {
762 $this->raw($notice->asAtomEntry());
766 $this->endDocument('atom');
770 function showRssGroups($group, $title, $link, $subtitle)
773 $this->initDocument('rss');
775 $this->element('title', null, $title);
776 $this->element('link', null, $link);
777 $this->element('description', null, $subtitle);
778 $this->element('language', null, 'en-us');
779 $this->element('ttl', null, '40');
781 if (is_array($group)) {
782 foreach ($group as $g) {
783 $twitter_group = $this->twitterRssGroupArray($g);
784 $this->showTwitterRssItem($twitter_group);
787 while ($group->fetch()) {
788 $twitter_group = $this->twitterRssGroupArray($group);
789 $this->showTwitterRssItem($twitter_group);
793 $this->endTwitterRss();
796 function showTwitterAtomEntry($entry)
798 $this->elementStart('entry');
799 $this->element('title', null, common_xml_safe_str($entry['title']));
802 array('type' => 'html'),
803 common_xml_safe_str($entry['content'])
805 $this->element('id', null, $entry['id']);
806 $this->element('published', null, $entry['published']);
807 $this->element('updated', null, $entry['updated']);
808 $this->element('link', array('type' => 'text/html',
809 'href' => $entry['link'],
810 'rel' => 'alternate'));
811 $this->element('link', array('type' => $entry['avatar-type'],
812 'href' => $entry['avatar'],
814 $this->elementStart('author');
816 $this->element('name', null, $entry['author-name']);
817 $this->element('uri', null, $entry['author-uri']);
819 $this->elementEnd('author');
820 $this->elementEnd('entry');
823 function showXmlDirectMessage($dm, $namespaces=false)
827 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
829 $this->elementStart('direct_message', $attrs);
830 foreach($dm as $element => $value) {
834 $this->showTwitterXmlUser($value, $element);
837 $this->element($element, null, common_xml_safe_str($value));
840 $this->element($element, null, $value);
844 $this->elementEnd('direct_message');
847 function directMessageArray($message)
851 $from_profile = $message->getFrom();
852 $to_profile = $message->getTo();
854 $dmsg['id'] = $message->id;
855 $dmsg['sender_id'] = $message->from_profile;
856 $dmsg['text'] = trim($message->content);
857 $dmsg['recipient_id'] = $message->to_profile;
858 $dmsg['created_at'] = $this->dateTwitter($message->created);
859 $dmsg['sender_screen_name'] = $from_profile->nickname;
860 $dmsg['recipient_screen_name'] = $to_profile->nickname;
861 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
862 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
867 function rssDirectMessageArray($message)
871 $from = $message->getFrom();
873 $entry['title'] = sprintf('Message from %1$s to %2$s',
874 $from->nickname, $message->getTo()->nickname);
876 $entry['content'] = common_xml_safe_str($message->rendered);
877 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
878 $entry['published'] = common_date_iso8601($message->created);
880 $taguribase = TagURI::base();
882 $entry['id'] = "tag:$taguribase:$entry[link]";
883 $entry['updated'] = $entry['published'];
885 $entry['author-name'] = $from->getBestName();
886 $entry['author-uri'] = $from->homepage;
888 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
890 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
891 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
895 $entry['description'] = $entry['content'];
896 $entry['pubDate'] = common_date_rfc2822($message->created);
897 $entry['guid'] = $entry['link'];
902 function showSingleXmlDirectMessage($message)
904 $this->initDocument('xml');
905 $dmsg = $this->directMessageArray($message);
906 $this->showXmlDirectMessage($dmsg, true);
907 $this->endDocument('xml');
910 function showSingleJsonDirectMessage($message)
912 $this->initDocument('json');
913 $dmsg = $this->directMessageArray($message);
914 $this->showJsonObjects($dmsg);
915 $this->endDocument('json');
918 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
921 $this->initDocument('atom');
923 $this->element('title', null, common_xml_safe_str($title));
924 $this->element('id', null, $id);
925 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
927 if (!is_null($selfuri)) {
928 $this->element('link', array('href' => $selfuri,
929 'rel' => 'self', 'type' => 'application/atom+xml'), null);
932 $this->element('updated', null, common_date_iso8601('now'));
933 $this->element('subtitle', null, common_xml_safe_str($subtitle));
935 if (is_array($group)) {
936 foreach ($group as $g) {
937 $this->raw($g->asAtomEntry());
940 while ($group->fetch()) {
941 $this->raw($group->asAtomEntry());
945 $this->endDocument('atom');
949 function showJsonTimeline($notice)
952 $this->initDocument('json');
956 if (is_array($notice)) {
957 foreach ($notice as $n) {
958 $twitter_status = $this->twitterStatusArray($n);
959 array_push($statuses, $twitter_status);
962 while ($notice->fetch()) {
963 $twitter_status = $this->twitterStatusArray($notice);
964 array_push($statuses, $twitter_status);
968 $this->showJsonObjects($statuses);
970 $this->endDocument('json');
973 function showJsonGroups($group)
976 $this->initDocument('json');
980 if (is_array($group)) {
981 foreach ($group as $g) {
982 $twitter_group = $this->twitterGroupArray($g);
983 array_push($groups, $twitter_group);
986 while ($group->fetch()) {
987 $twitter_group = $this->twitterGroupArray($group);
988 array_push($groups, $twitter_group);
992 $this->showJsonObjects($groups);
994 $this->endDocument('json');
997 function showXmlGroups($group)
1000 $this->initDocument('xml');
1001 $this->elementStart('groups', array('type' => 'array'));
1003 if (is_array($group)) {
1004 foreach ($group as $g) {
1005 $twitter_group = $this->twitterGroupArray($g);
1006 $this->showTwitterXmlGroup($twitter_group);
1009 while ($group->fetch()) {
1010 $twitter_group = $this->twitterGroupArray($group);
1011 $this->showTwitterXmlGroup($twitter_group);
1015 $this->elementEnd('groups');
1016 $this->endDocument('xml');
1019 function showTwitterXmlUsers($user)
1022 $this->initDocument('xml');
1023 $this->elementStart('users', array('type' => 'array',
1024 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1026 if (is_array($user)) {
1027 foreach ($user as $u) {
1028 $twitter_user = $this->twitterUserArray($u);
1029 $this->showTwitterXmlUser($twitter_user);
1032 while ($user->fetch()) {
1033 $twitter_user = $this->twitterUserArray($user);
1034 $this->showTwitterXmlUser($twitter_user);
1038 $this->elementEnd('users');
1039 $this->endDocument('xml');
1042 function showJsonUsers($user)
1045 $this->initDocument('json');
1049 if (is_array($user)) {
1050 foreach ($user as $u) {
1051 $twitter_user = $this->twitterUserArray($u);
1052 array_push($users, $twitter_user);
1055 while ($user->fetch()) {
1056 $twitter_user = $this->twitterUserArray($user);
1057 array_push($users, $twitter_user);
1061 $this->showJsonObjects($users);
1063 $this->endDocument('json');
1066 function showSingleJsonGroup($group)
1068 $this->initDocument('json');
1069 $twitter_group = $this->twitterGroupArray($group);
1070 $this->showJsonObjects($twitter_group);
1071 $this->endDocument('json');
1074 function showSingleXmlGroup($group)
1076 $this->initDocument('xml');
1077 $twitter_group = $this->twitterGroupArray($group);
1078 $this->showTwitterXmlGroup($twitter_group);
1079 $this->endDocument('xml');
1082 function dateTwitter($dt)
1084 $dateStr = date('d F Y H:i:s', strtotime($dt));
1085 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1086 $d->setTimezone(new DateTimeZone(common_timezone()));
1087 return $d->format('D M d H:i:s O Y');
1090 function initDocument($type='xml')
1094 header('Content-Type: application/xml; charset=utf-8');
1098 header('Content-Type: application/json; charset=utf-8');
1100 // Check for JSONP callback
1101 $callback = $this->arg('callback');
1103 print $callback . '(';
1107 header("Content-Type: application/rss+xml; charset=utf-8");
1108 $this->initTwitterRss();
1111 header('Content-Type: application/atom+xml; charset=utf-8');
1112 $this->initTwitterAtom();
1115 $this->clientError(_('Not a supported data format.'));
1122 function endDocument($type='xml')
1130 // Check for JSONP callback
1131 $callback = $this->arg('callback');
1137 $this->endTwitterRss();
1140 $this->endTwitterRss();
1143 $this->clientError(_('Not a supported data format.'));
1149 function clientError($msg, $code = 400, $format = 'xml')
1151 $action = $this->trimmed('action');
1153 common_debug("User error '$code' on '$action': $msg", __FILE__);
1155 if (!array_key_exists($code, ClientErrorAction::$status)) {
1159 $status_string = ClientErrorAction::$status[$code];
1161 header('HTTP/1.1 '.$code.' '.$status_string);
1163 if ($format == 'xml') {
1164 $this->initDocument('xml');
1165 $this->elementStart('hash');
1166 $this->element('error', null, $msg);
1167 $this->element('request', null, $_SERVER['REQUEST_URI']);
1168 $this->elementEnd('hash');
1169 $this->endDocument('xml');
1170 } elseif ($format == 'json'){
1171 $this->initDocument('json');
1172 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1173 print(json_encode($error_array));
1174 $this->endDocument('json');
1177 // If user didn't request a useful format, throw a regular client error
1178 throw new ClientException($msg, $code);
1182 function serverError($msg, $code = 500, $content_type = 'xml')
1184 $action = $this->trimmed('action');
1186 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1188 if (!array_key_exists($code, ServerErrorAction::$status)) {
1192 $status_string = ServerErrorAction::$status[$code];
1194 header('HTTP/1.1 '.$code.' '.$status_string);
1196 if ($content_type == 'xml') {
1197 $this->initDocument('xml');
1198 $this->elementStart('hash');
1199 $this->element('error', null, $msg);
1200 $this->element('request', null, $_SERVER['REQUEST_URI']);
1201 $this->elementEnd('hash');
1202 $this->endDocument('xml');
1204 $this->initDocument('json');
1205 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1206 print(json_encode($error_array));
1207 $this->endDocument('json');
1211 function initTwitterRss()
1214 $this->elementStart(
1218 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1219 'xmlns:georss' => 'http://www.georss.org/georss'
1222 $this->elementStart('channel');
1223 Event::handle('StartApiRss', array($this));
1226 function endTwitterRss()
1228 $this->elementEnd('channel');
1229 $this->elementEnd('rss');
1233 function initTwitterAtom()
1236 // FIXME: don't hardcode the language here!
1237 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1238 'xml:lang' => 'en-US',
1239 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1242 function endTwitterAtom()
1244 $this->elementEnd('feed');
1248 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1250 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1251 switch ($content_type) {
1253 $this->showTwitterXmlUser($profile_array);
1256 $this->showJsonObjects($profile_array);
1259 $this->clientError(_('Not a supported data format.'));
1265 function getTargetUser($id)
1269 // Twitter supports these other ways of passing the user ID
1270 if (is_numeric($this->arg('id'))) {
1271 return User::staticGet($this->arg('id'));
1272 } else if ($this->arg('id')) {
1273 $nickname = common_canonical_nickname($this->arg('id'));
1274 return User::staticGet('nickname', $nickname);
1275 } else if ($this->arg('user_id')) {
1276 // This is to ensure that a non-numeric user_id still
1277 // overrides screen_name even if it doesn't get used
1278 if (is_numeric($this->arg('user_id'))) {
1279 return User::staticGet('id', $this->arg('user_id'));
1281 } else if ($this->arg('screen_name')) {
1282 $nickname = common_canonical_nickname($this->arg('screen_name'));
1283 return User::staticGet('nickname', $nickname);
1285 // Fall back to trying the currently authenticated user
1286 return $this->auth_user;
1289 } else if (is_numeric($id)) {
1290 return User::staticGet($id);
1292 $nickname = common_canonical_nickname($id);
1293 return User::staticGet('nickname', $nickname);
1297 function getTargetGroup($id)
1300 if (is_numeric($this->arg('id'))) {
1301 return User_group::staticGet($this->arg('id'));
1302 } else if ($this->arg('id')) {
1303 $nickname = common_canonical_nickname($this->arg('id'));
1304 $local = Local_group::staticGet('nickname', $nickname);
1305 if (empty($local)) {
1308 return User_group::staticGet('id', $local->id);
1310 } else if ($this->arg('group_id')) {
1311 // This is to ensure that a non-numeric user_id still
1312 // overrides screen_name even if it doesn't get used
1313 if (is_numeric($this->arg('group_id'))) {
1314 return User_group::staticGet('id', $this->arg('group_id'));
1316 } else if ($this->arg('group_name')) {
1317 $nickname = common_canonical_nickname($this->arg('group_name'));
1318 $local = Local_group::staticGet('nickname', $nickname);
1319 if (empty($local)) {
1322 return User_group::staticGet('id', $local->group_id);
1326 } else if (is_numeric($id)) {
1327 return User_group::staticGet($id);
1329 $nickname = common_canonical_nickname($id);
1330 $local = Local_group::staticGet('nickname', $nickname);
1331 if (empty($local)) {
1334 return User_group::staticGet('id', $local->group_id);
1340 * Returns query argument or default value if not found. Certain
1341 * parameters used throughout the API are lightly scrubbed and
1342 * bounds checked. This overrides Action::arg().
1344 * @param string $key requested argument
1345 * @param string $def default value to return if $key is not provided
1349 function arg($key, $def=null)
1352 // XXX: Do even more input validation/scrubbing?
1354 if (array_key_exists($key, $this->args)) {
1357 $page = (int)$this->args['page'];
1358 return ($page < 1) ? 1 : $page;
1360 $count = (int)$this->args['count'];
1363 } elseif ($count > 200) {
1369 $since_id = (int)$this->args['since_id'];
1370 return ($since_id < 1) ? 0 : $since_id;
1372 $max_id = (int)$this->args['max_id'];
1373 return ($max_id < 1) ? 0 : $max_id;
1375 return parent::arg($key, $def);
1383 * Calculate the complete URI that called up this action. Used for
1384 * Atom rel="self" links. Warning: this is funky.
1386 * @return string URL a URL suitable for rel="self" Atom links
1388 function getSelfUri()
1390 $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1392 $id = $this->arg('id');
1393 $aargs = array('format' => $this->format);
1398 $tag = $this->arg('tag');
1400 $aargs['tag'] = $tag;
1403 parse_str($_SERVER['QUERY_STRING'], $params);
1405 if (!empty($params)) {
1406 unset($params['p']);
1407 $pstring = http_build_query($params);
1410 $uri = common_local_url($action, $aargs);
1412 if (!empty($pstring)) {
1413 $uri .= '?' . $pstring;