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;
67 var $access = self::READ_ONLY; // read (default) or read-write
72 * @param array $args Web and URL arguments
74 * @return boolean false if user doesn't exist
77 function prepare($args)
79 StatusNet::setApi(true); // reduce exception reports to aid in debugging
80 parent::prepare($args);
82 $this->format = $this->arg('format');
83 $this->page = (int)$this->arg('page', 1);
84 $this->count = (int)$this->arg('count', 20);
85 $this->max_id = (int)$this->arg('max_id', 0);
86 $this->since_id = (int)$this->arg('since_id', 0);
88 if ($this->arg('since')) {
89 header('X-StatusNet-Warning: since parameter is disabled; use since_id');
98 * @param array $args Arguments from $_REQUEST
103 function handle($args)
105 parent::handle($args);
109 * Overrides XMLOutputter::element to write booleans as strings (true|false).
110 * See that method's documentation for more info.
112 * @param string $tag Element type or tagname
113 * @param array $attrs Array of element attributes, as
115 * @param string $content string content of the element
119 function element($tag, $attrs=null, $content=null)
121 if (is_bool($content)) {
122 $content = ($content ? 'true' : 'false');
125 return parent::element($tag, $attrs, $content);
128 function twitterUserArray($profile, $get_notice=false)
130 $twitter_user = array();
132 $twitter_user['id'] = intval($profile->id);
133 $twitter_user['name'] = $profile->getBestName();
134 $twitter_user['screen_name'] = $profile->nickname;
135 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
136 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
138 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
139 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
140 Avatar::defaultImage(AVATAR_STREAM_SIZE);
142 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
143 $twitter_user['protected'] = false; # not supported by StatusNet yet
144 $twitter_user['followers_count'] = $profile->subscriberCount();
147 $user = $profile->getUser();
149 // Note: some profiles don't have an associated user
151 $defaultDesign = Design::siteDesign();
154 $design = $user->getDesign();
157 if (empty($design)) {
158 $design = $defaultDesign;
161 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
162 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
163 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
164 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
165 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
166 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
167 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
168 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
169 $twitter_user['profile_sidebar_border_color'] = '';
171 $twitter_user['friends_count'] = $profile->subscriptionCount();
173 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
175 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
179 if (!empty($user) && $user->timezone) {
180 $timezone = $user->timezone;
184 $t->setTimezone(new DateTimeZone($timezone));
186 $twitter_user['utc_offset'] = $t->format('Z');
187 $twitter_user['time_zone'] = $timezone;
189 $twitter_user['profile_background_image_url']
190 = empty($design->backgroundimage)
191 ? '' : ($design->disposition & BACKGROUND_ON)
192 ? Design::url($design->backgroundimage) : '';
194 $twitter_user['profile_background_tile']
195 = empty($design->disposition)
196 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
198 $twitter_user['statuses_count'] = $profile->noticeCount();
200 // Is the requesting user following this user?
201 $twitter_user['following'] = false;
202 $twitter_user['notifications'] = false;
204 if (isset($this->auth_user)) {
206 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
209 $sub = Subscription::pkeyGet(array('subscriber' =>
210 $this->auth_user->id,
211 'subscribed' => $profile->id));
214 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
219 $notice = $profile->getCurrentNotice();
222 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
226 // StatusNet-specific
228 $twitter_user['statusnet_profile_url'] = $profile->profileurl;
230 return $twitter_user;
233 function twitterStatusArray($notice, $include_user=true)
235 $base = $this->twitterSimpleStatusArray($notice, $include_user);
237 if (!empty($notice->repeat_of)) {
238 $original = Notice::staticGet('id', $notice->repeat_of);
239 if (!empty($original)) {
240 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
241 $base['retweeted_status'] = $original_array;
248 function twitterSimpleStatusArray($notice, $include_user=true)
250 $profile = $notice->getProfile();
252 $twitter_status = array();
253 $twitter_status['text'] = $notice->content;
254 $twitter_status['truncated'] = false; # Not possible on StatusNet
255 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
256 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
257 intval($notice->reply_to) : null;
258 $twitter_status['source'] = $this->sourceLink($notice->source);
259 $twitter_status['id'] = intval($notice->id);
261 $replier_profile = null;
263 if ($notice->reply_to) {
264 $reply = Notice::staticGet(intval($notice->reply_to));
266 $replier_profile = $reply->getProfile();
270 $twitter_status['in_reply_to_user_id'] =
271 ($replier_profile) ? intval($replier_profile->id) : null;
272 $twitter_status['in_reply_to_screen_name'] =
273 ($replier_profile) ? $replier_profile->nickname : null;
275 if (isset($notice->lat) && isset($notice->lon)) {
276 // This is the format that GeoJSON expects stuff to be in
277 $twitter_status['geo'] = array('type' => 'Point',
278 'coordinates' => array((float) $notice->lat,
279 (float) $notice->lon));
281 $twitter_status['geo'] = null;
284 if (isset($this->auth_user)) {
285 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
287 $twitter_status['favorited'] = false;
291 $attachments = $notice->attachments();
293 if (!empty($attachments)) {
295 $twitter_status['attachments'] = array();
297 foreach ($attachments as $attachment) {
298 $enclosure_o=$attachment->getEnclosure();
300 $enclosure = array();
301 $enclosure['url'] = $enclosure_o->url;
302 $enclosure['mimetype'] = $enclosure_o->mimetype;
303 $enclosure['size'] = $enclosure_o->size;
304 $twitter_status['attachments'][] = $enclosure;
309 if ($include_user && $profile) {
310 # Don't get notice (recursive!)
311 $twitter_user = $this->twitterUserArray($profile, false);
312 $twitter_status['user'] = $twitter_user;
315 // StatusNet-specific
317 $twitter_status['statusnet_html'] = $notice->rendered;
319 return $twitter_status;
322 function twitterGroupArray($group)
324 $twitter_group=array();
325 $twitter_group['id']=$group->id;
326 $twitter_group['url']=$group->permalink();
327 $twitter_group['nickname']=$group->nickname;
328 $twitter_group['fullname']=$group->fullname;
329 $twitter_group['original_logo']=$group->original_logo;
330 $twitter_group['homepage_logo']=$group->homepage_logo;
331 $twitter_group['stream_logo']=$group->stream_logo;
332 $twitter_group['mini_logo']=$group->mini_logo;
333 $twitter_group['homepage']=$group->homepage;
334 $twitter_group['description']=$group->description;
335 $twitter_group['location']=$group->location;
336 $twitter_group['created']=$this->dateTwitter($group->created);
337 $twitter_group['modified']=$this->dateTwitter($group->modified);
338 return $twitter_group;
341 function twitterRssGroupArray($group)
344 $entry['content']=$group->description;
345 $entry['title']=$group->nickname;
346 $entry['link']=$group->permalink();
347 $entry['published']=common_date_iso8601($group->created);
348 $entry['updated']==common_date_iso8601($group->modified);
349 $taguribase = common_config('integration', 'groupuri');
350 $entry['id'] = "group:$groupuribase:$entry[link]";
352 $entry['description'] = $entry['content'];
353 $entry['pubDate'] = common_date_rfc2822($group->created);
354 $entry['guid'] = $entry['link'];
359 function twitterRssEntryArray($notice)
361 $profile = $notice->getProfile();
364 // We trim() to avoid extraneous whitespace in the output
366 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
367 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
368 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
369 $entry['published'] = common_date_iso8601($notice->created);
371 $taguribase = TagURI::base();
372 $entry['id'] = "tag:$taguribase:$entry[link]";
374 $entry['updated'] = $entry['published'];
375 $entry['author'] = $profile->getBestName();
378 $attachments = $notice->attachments();
379 $enclosures = array();
381 foreach ($attachments as $attachment) {
382 $enclosure_o=$attachment->getEnclosure();
384 $enclosure = array();
385 $enclosure['url'] = $enclosure_o->url;
386 $enclosure['mimetype'] = $enclosure_o->mimetype;
387 $enclosure['size'] = $enclosure_o->size;
388 $enclosures[] = $enclosure;
392 if (!empty($enclosures)) {
393 $entry['enclosures'] = $enclosures;
397 $tag = new Notice_tag();
398 $tag->notice_id = $notice->id;
400 $entry['tags']=array();
401 while ($tag->fetch()) {
402 $entry['tags'][]=$tag->tag;
408 $entry['description'] = $entry['content'];
409 $entry['pubDate'] = common_date_rfc2822($notice->created);
410 $entry['guid'] = $entry['link'];
412 if (isset($notice->lat) && isset($notice->lon)) {
413 // This is the format that GeoJSON expects stuff to be in.
414 // showGeoRSS() below uses it for XML output, so we reuse it
415 $entry['geo'] = array('type' => 'Point',
416 'coordinates' => array((float) $notice->lat,
417 (float) $notice->lon));
419 $entry['geo'] = null;
425 function twitterRelationshipArray($source, $target)
427 $relationship = array();
429 $relationship['source'] =
430 $this->relationshipDetailsArray($source, $target);
431 $relationship['target'] =
432 $this->relationshipDetailsArray($target, $source);
434 return array('relationship' => $relationship);
437 function relationshipDetailsArray($source, $target)
441 $details['screen_name'] = $source->nickname;
442 $details['followed_by'] = $target->isSubscribed($source);
443 $details['following'] = $source->isSubscribed($target);
445 $notifications = false;
447 if ($source->isSubscribed($target)) {
449 $sub = Subscription::pkeyGet(array('subscriber' =>
450 $source->id, 'subscribed' => $target->id));
453 $notifications = ($sub->jabber || $sub->sms);
457 $details['notifications_enabled'] = $notifications;
458 $details['blocking'] = $source->hasBlocked($target);
459 $details['id'] = $source->id;
464 function showTwitterXmlRelationship($relationship)
466 $this->elementStart('relationship');
468 foreach($relationship as $element => $value) {
469 if ($element == 'source' || $element == 'target') {
470 $this->elementStart($element);
471 $this->showXmlRelationshipDetails($value);
472 $this->elementEnd($element);
476 $this->elementEnd('relationship');
479 function showXmlRelationshipDetails($details)
481 foreach($details as $element => $value) {
482 $this->element($element, null, $value);
486 function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
490 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
492 $this->elementStart($tag, $attrs);
493 foreach($twitter_status as $element => $value) {
496 $this->showTwitterXmlUser($twitter_status['user']);
499 $this->element($element, null, common_xml_safe_str($value));
502 $this->showXmlAttachments($twitter_status['attachments']);
505 $this->showGeoXML($value);
507 case 'retweeted_status':
508 $this->showTwitterXmlStatus($value, 'retweeted_status');
511 if (strncmp($element, 'statusnet_', 10) == 0) {
512 $this->element('statusnet:'.substr($element, 10), null, $value);
514 $this->element($element, null, $value);
518 $this->elementEnd($tag);
521 function showTwitterXmlGroup($twitter_group)
523 $this->elementStart('group');
524 foreach($twitter_group as $element => $value) {
525 $this->element($element, null, $value);
527 $this->elementEnd('group');
530 function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
534 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
536 $this->elementStart($role, $attrs);
537 foreach($twitter_user as $element => $value) {
538 if ($element == 'status') {
539 $this->showTwitterXmlStatus($twitter_user['status']);
540 } else if (strncmp($element, 'statusnet_', 10) == 0) {
541 $this->element('statusnet:'.substr($element, 10), null, $value);
543 $this->element($element, null, $value);
546 $this->elementEnd($role);
549 function showXmlAttachments($attachments) {
550 if (!empty($attachments)) {
551 $this->elementStart('attachments', array('type' => 'array'));
552 foreach ($attachments as $attachment) {
554 $attrs['url'] = $attachment['url'];
555 $attrs['mimetype'] = $attachment['mimetype'];
556 $attrs['size'] = $attachment['size'];
557 $this->element('enclosure', $attrs, '');
559 $this->elementEnd('attachments');
563 function showGeoXML($geo)
567 $this->element('geo');
569 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
570 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
571 $this->elementEnd('geo');
575 function showGeoRSS($geo)
581 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
586 function showTwitterRssItem($entry)
588 $this->elementStart('item');
589 $this->element('title', null, $entry['title']);
590 $this->element('description', null, $entry['description']);
591 $this->element('pubDate', null, $entry['pubDate']);
592 $this->element('guid', null, $entry['guid']);
593 $this->element('link', null, $entry['link']);
595 # RSS only supports 1 enclosure per item
596 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
597 $enclosure = $entry['enclosures'][0];
598 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
601 if(array_key_exists('tags', $entry)){
602 foreach($entry['tags'] as $tag){
603 $this->element('category', null,$tag);
607 $this->showGeoRSS($entry['geo']);
608 $this->elementEnd('item');
611 function showJsonObjects($objects)
613 print(json_encode($objects));
616 function showSingleXmlStatus($notice)
618 $this->initDocument('xml');
619 $twitter_status = $this->twitterStatusArray($notice);
620 $this->showTwitterXmlStatus($twitter_status, 'status', true);
621 $this->endDocument('xml');
624 function show_single_json_status($notice)
626 $this->initDocument('json');
627 $status = $this->twitterStatusArray($notice);
628 $this->showJsonObjects($status);
629 $this->endDocument('json');
632 function showXmlTimeline($notice)
635 $this->initDocument('xml');
636 $this->elementStart('statuses', array('type' => 'array',
637 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
639 if (is_array($notice)) {
640 foreach ($notice as $n) {
641 $twitter_status = $this->twitterStatusArray($n);
642 $this->showTwitterXmlStatus($twitter_status);
645 while ($notice->fetch()) {
646 $twitter_status = $this->twitterStatusArray($notice);
647 $this->showTwitterXmlStatus($twitter_status);
651 $this->elementEnd('statuses');
652 $this->endDocument('xml');
655 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
658 $this->initDocument('rss');
660 $this->element('title', null, $title);
661 $this->element('link', null, $link);
663 if (!is_null($self)) {
667 'type' => 'application/rss+xml',
674 if (!is_null($suplink)) {
675 // For FriendFeed's SUP protocol
676 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
677 'rel' => 'http://api.friendfeed.com/2008/03#sup',
679 'type' => 'application/json'));
682 if (!is_null($logo)) {
683 $this->elementStart('image');
684 $this->element('link', null, $link);
685 $this->element('title', null, $title);
686 $this->element('url', null, $logo);
687 $this->elementEnd('image');
690 $this->element('description', null, $subtitle);
691 $this->element('language', null, 'en-us');
692 $this->element('ttl', null, '40');
694 if (is_array($notice)) {
695 foreach ($notice as $n) {
696 $entry = $this->twitterRssEntryArray($n);
697 $this->showTwitterRssItem($entry);
700 while ($notice->fetch()) {
701 $entry = $this->twitterRssEntryArray($notice);
702 $this->showTwitterRssItem($entry);
706 $this->endTwitterRss();
709 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
712 $this->initDocument('atom');
714 $this->element('title', null, $title);
715 $this->element('id', null, $id);
716 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
718 if (!is_null($logo)) {
719 $this->element('logo',null,$logo);
722 if (!is_null($suplink)) {
723 # For FriendFeed's SUP protocol
724 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
726 'type' => 'application/json'));
729 if (!is_null($selfuri)) {
730 $this->element('link', array('href' => $selfuri,
731 'rel' => 'self', 'type' => 'application/atom+xml'), null);
734 $this->element('updated', null, common_date_iso8601('now'));
735 $this->element('subtitle', null, $subtitle);
737 if (is_array($notice)) {
738 foreach ($notice as $n) {
739 $this->raw($n->asAtomEntry());
742 while ($notice->fetch()) {
743 $this->raw($notice->asAtomEntry());
747 $this->endDocument('atom');
751 function showRssGroups($group, $title, $link, $subtitle)
754 $this->initDocument('rss');
756 $this->element('title', null, $title);
757 $this->element('link', null, $link);
758 $this->element('description', null, $subtitle);
759 $this->element('language', null, 'en-us');
760 $this->element('ttl', null, '40');
762 if (is_array($group)) {
763 foreach ($group as $g) {
764 $twitter_group = $this->twitterRssGroupArray($g);
765 $this->showTwitterRssItem($twitter_group);
768 while ($group->fetch()) {
769 $twitter_group = $this->twitterRssGroupArray($group);
770 $this->showTwitterRssItem($twitter_group);
774 $this->endTwitterRss();
777 function showTwitterAtomEntry($entry)
779 $this->elementStart('entry');
780 $this->element('title', null, common_xml_safe_str($entry['title']));
783 array('type' => 'html'),
784 common_xml_safe_str($entry['content'])
786 $this->element('id', null, $entry['id']);
787 $this->element('published', null, $entry['published']);
788 $this->element('updated', null, $entry['updated']);
789 $this->element('link', array('type' => 'text/html',
790 'href' => $entry['link'],
791 'rel' => 'alternate'));
792 $this->element('link', array('type' => $entry['avatar-type'],
793 'href' => $entry['avatar'],
795 $this->elementStart('author');
797 $this->element('name', null, $entry['author-name']);
798 $this->element('uri', null, $entry['author-uri']);
800 $this->elementEnd('author');
801 $this->elementEnd('entry');
804 function showXmlDirectMessage($dm, $namespaces=false)
808 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
810 $this->elementStart('direct_message', $attrs);
811 foreach($dm as $element => $value) {
815 $this->showTwitterXmlUser($value, $element);
818 $this->element($element, null, common_xml_safe_str($value));
821 $this->element($element, null, $value);
825 $this->elementEnd('direct_message');
828 function directMessageArray($message)
832 $from_profile = $message->getFrom();
833 $to_profile = $message->getTo();
835 $dmsg['id'] = $message->id;
836 $dmsg['sender_id'] = $message->from_profile;
837 $dmsg['text'] = trim($message->content);
838 $dmsg['recipient_id'] = $message->to_profile;
839 $dmsg['created_at'] = $this->dateTwitter($message->created);
840 $dmsg['sender_screen_name'] = $from_profile->nickname;
841 $dmsg['recipient_screen_name'] = $to_profile->nickname;
842 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
843 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
848 function rssDirectMessageArray($message)
852 $from = $message->getFrom();
854 $entry['title'] = sprintf('Message from %1$s to %2$s',
855 $from->nickname, $message->getTo()->nickname);
857 $entry['content'] = common_xml_safe_str($message->rendered);
858 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
859 $entry['published'] = common_date_iso8601($message->created);
861 $taguribase = TagURI::base();
863 $entry['id'] = "tag:$taguribase:$entry[link]";
864 $entry['updated'] = $entry['published'];
866 $entry['author-name'] = $from->getBestName();
867 $entry['author-uri'] = $from->homepage;
869 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
871 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
872 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
876 $entry['description'] = $entry['content'];
877 $entry['pubDate'] = common_date_rfc2822($message->created);
878 $entry['guid'] = $entry['link'];
883 function showSingleXmlDirectMessage($message)
885 $this->initDocument('xml');
886 $dmsg = $this->directMessageArray($message);
887 $this->showXmlDirectMessage($dmsg, true);
888 $this->endDocument('xml');
891 function showSingleJsonDirectMessage($message)
893 $this->initDocument('json');
894 $dmsg = $this->directMessageArray($message);
895 $this->showJsonObjects($dmsg);
896 $this->endDocument('json');
899 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
902 $this->initDocument('atom');
904 $this->element('title', null, common_xml_safe_str($title));
905 $this->element('id', null, $id);
906 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
908 if (!is_null($selfuri)) {
909 $this->element('link', array('href' => $selfuri,
910 'rel' => 'self', 'type' => 'application/atom+xml'), null);
913 $this->element('updated', null, common_date_iso8601('now'));
914 $this->element('subtitle', null, common_xml_safe_str($subtitle));
916 if (is_array($group)) {
917 foreach ($group as $g) {
918 $this->raw($g->asAtomEntry());
921 while ($group->fetch()) {
922 $this->raw($group->asAtomEntry());
926 $this->endDocument('atom');
930 function showJsonTimeline($notice)
933 $this->initDocument('json');
937 if (is_array($notice)) {
938 foreach ($notice as $n) {
939 $twitter_status = $this->twitterStatusArray($n);
940 array_push($statuses, $twitter_status);
943 while ($notice->fetch()) {
944 $twitter_status = $this->twitterStatusArray($notice);
945 array_push($statuses, $twitter_status);
949 $this->showJsonObjects($statuses);
951 $this->endDocument('json');
954 function showJsonGroups($group)
957 $this->initDocument('json');
961 if (is_array($group)) {
962 foreach ($group as $g) {
963 $twitter_group = $this->twitterGroupArray($g);
964 array_push($groups, $twitter_group);
967 while ($group->fetch()) {
968 $twitter_group = $this->twitterGroupArray($group);
969 array_push($groups, $twitter_group);
973 $this->showJsonObjects($groups);
975 $this->endDocument('json');
978 function showXmlGroups($group)
981 $this->initDocument('xml');
982 $this->elementStart('groups', array('type' => 'array'));
984 if (is_array($group)) {
985 foreach ($group as $g) {
986 $twitter_group = $this->twitterGroupArray($g);
987 $this->showTwitterXmlGroup($twitter_group);
990 while ($group->fetch()) {
991 $twitter_group = $this->twitterGroupArray($group);
992 $this->showTwitterXmlGroup($twitter_group);
996 $this->elementEnd('groups');
997 $this->endDocument('xml');
1000 function showTwitterXmlUsers($user)
1003 $this->initDocument('xml');
1004 $this->elementStart('users', array('type' => 'array',
1005 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1007 if (is_array($user)) {
1008 foreach ($user as $u) {
1009 $twitter_user = $this->twitterUserArray($u);
1010 $this->showTwitterXmlUser($twitter_user);
1013 while ($user->fetch()) {
1014 $twitter_user = $this->twitterUserArray($user);
1015 $this->showTwitterXmlUser($twitter_user);
1019 $this->elementEnd('users');
1020 $this->endDocument('xml');
1023 function showJsonUsers($user)
1026 $this->initDocument('json');
1030 if (is_array($user)) {
1031 foreach ($user as $u) {
1032 $twitter_user = $this->twitterUserArray($u);
1033 array_push($users, $twitter_user);
1036 while ($user->fetch()) {
1037 $twitter_user = $this->twitterUserArray($user);
1038 array_push($users, $twitter_user);
1042 $this->showJsonObjects($users);
1044 $this->endDocument('json');
1047 function showSingleJsonGroup($group)
1049 $this->initDocument('json');
1050 $twitter_group = $this->twitterGroupArray($group);
1051 $this->showJsonObjects($twitter_group);
1052 $this->endDocument('json');
1055 function showSingleXmlGroup($group)
1057 $this->initDocument('xml');
1058 $twitter_group = $this->twitterGroupArray($group);
1059 $this->showTwitterXmlGroup($twitter_group);
1060 $this->endDocument('xml');
1063 function dateTwitter($dt)
1065 $dateStr = date('d F Y H:i:s', strtotime($dt));
1066 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1067 $d->setTimezone(new DateTimeZone(common_timezone()));
1068 return $d->format('D M d H:i:s O Y');
1071 function initDocument($type='xml')
1075 header('Content-Type: application/xml; charset=utf-8');
1079 header('Content-Type: application/json; charset=utf-8');
1081 // Check for JSONP callback
1082 $callback = $this->arg('callback');
1084 print $callback . '(';
1088 header("Content-Type: application/rss+xml; charset=utf-8");
1089 $this->initTwitterRss();
1092 header('Content-Type: application/atom+xml; charset=utf-8');
1093 $this->initTwitterAtom();
1096 $this->clientError(_('Not a supported data format.'));
1103 function endDocument($type='xml')
1111 // Check for JSONP callback
1112 $callback = $this->arg('callback');
1118 $this->endTwitterRss();
1121 $this->endTwitterRss();
1124 $this->clientError(_('Not a supported data format.'));
1130 function clientError($msg, $code = 400, $format = 'xml')
1132 $action = $this->trimmed('action');
1134 common_debug("User error '$code' on '$action': $msg", __FILE__);
1136 if (!array_key_exists($code, ClientErrorAction::$status)) {
1140 $status_string = ClientErrorAction::$status[$code];
1142 header('HTTP/1.1 '.$code.' '.$status_string);
1144 if ($format == 'xml') {
1145 $this->initDocument('xml');
1146 $this->elementStart('hash');
1147 $this->element('error', null, $msg);
1148 $this->element('request', null, $_SERVER['REQUEST_URI']);
1149 $this->elementEnd('hash');
1150 $this->endDocument('xml');
1151 } elseif ($format == 'json'){
1152 $this->initDocument('json');
1153 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1154 print(json_encode($error_array));
1155 $this->endDocument('json');
1158 // If user didn't request a useful format, throw a regular client error
1159 throw new ClientException($msg, $code);
1163 function serverError($msg, $code = 500, $content_type = 'xml')
1165 $action = $this->trimmed('action');
1167 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1169 if (!array_key_exists($code, ServerErrorAction::$status)) {
1173 $status_string = ServerErrorAction::$status[$code];
1175 header('HTTP/1.1 '.$code.' '.$status_string);
1177 if ($content_type == 'xml') {
1178 $this->initDocument('xml');
1179 $this->elementStart('hash');
1180 $this->element('error', null, $msg);
1181 $this->element('request', null, $_SERVER['REQUEST_URI']);
1182 $this->elementEnd('hash');
1183 $this->endDocument('xml');
1185 $this->initDocument('json');
1186 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1187 print(json_encode($error_array));
1188 $this->endDocument('json');
1192 function initTwitterRss()
1195 $this->elementStart(
1199 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1200 'xmlns:georss' => 'http://www.georss.org/georss'
1203 $this->elementStart('channel');
1204 Event::handle('StartApiRss', array($this));
1207 function endTwitterRss()
1209 $this->elementEnd('channel');
1210 $this->elementEnd('rss');
1214 function initTwitterAtom()
1217 // FIXME: don't hardcode the language here!
1218 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1219 'xml:lang' => 'en-US',
1220 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1223 function endTwitterAtom()
1225 $this->elementEnd('feed');
1229 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1231 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1232 switch ($content_type) {
1234 $this->showTwitterXmlUser($profile_array);
1237 $this->showJsonObjects($profile_array);
1240 $this->clientError(_('Not a supported data format.'));
1246 function getTargetUser($id)
1250 // Twitter supports these other ways of passing the user ID
1251 if (is_numeric($this->arg('id'))) {
1252 return User::staticGet($this->arg('id'));
1253 } else if ($this->arg('id')) {
1254 $nickname = common_canonical_nickname($this->arg('id'));
1255 return User::staticGet('nickname', $nickname);
1256 } else if ($this->arg('user_id')) {
1257 // This is to ensure that a non-numeric user_id still
1258 // overrides screen_name even if it doesn't get used
1259 if (is_numeric($this->arg('user_id'))) {
1260 return User::staticGet('id', $this->arg('user_id'));
1262 } else if ($this->arg('screen_name')) {
1263 $nickname = common_canonical_nickname($this->arg('screen_name'));
1264 return User::staticGet('nickname', $nickname);
1266 // Fall back to trying the currently authenticated user
1267 return $this->auth_user;
1270 } else if (is_numeric($id)) {
1271 return User::staticGet($id);
1273 $nickname = common_canonical_nickname($id);
1274 return User::staticGet('nickname', $nickname);
1278 function getTargetGroup($id)
1281 if (is_numeric($this->arg('id'))) {
1282 return User_group::staticGet($this->arg('id'));
1283 } else if ($this->arg('id')) {
1284 $nickname = common_canonical_nickname($this->arg('id'));
1285 $local = Local_group::staticGet('nickname', $nickname);
1286 if (empty($local)) {
1289 return User_group::staticGet('id', $local->id);
1291 } else if ($this->arg('group_id')) {
1292 // This is to ensure that a non-numeric user_id still
1293 // overrides screen_name even if it doesn't get used
1294 if (is_numeric($this->arg('group_id'))) {
1295 return User_group::staticGet('id', $this->arg('group_id'));
1297 } else if ($this->arg('group_name')) {
1298 $nickname = common_canonical_nickname($this->arg('group_name'));
1299 $local = Local_group::staticGet('nickname', $nickname);
1300 if (empty($local)) {
1303 return User_group::staticGet('id', $local->group_id);
1307 } else if (is_numeric($id)) {
1308 return User_group::staticGet($id);
1310 $nickname = common_canonical_nickname($id);
1311 $local = Local_group::staticGet('nickname', $nickname);
1312 if (empty($local)) {
1315 return User_group::staticGet('id', $local->group_id);
1320 function sourceLink($source)
1322 $source_name = _($source);
1335 $ns = Notice_source::staticGet($source);
1341 $app = Oauth_application::staticGet('name', $source);
1344 $url = $app->source_url;
1348 if (!empty($name) && !empty($url)) {
1349 $source_name = '<a href="' . $url . '">' . $name . '</a>';
1354 return $source_name;
1358 * Returns query argument or default value if not found. Certain
1359 * parameters used throughout the API are lightly scrubbed and
1360 * bounds checked. This overrides Action::arg().
1362 * @param string $key requested argument
1363 * @param string $def default value to return if $key is not provided
1367 function arg($key, $def=null)
1370 // XXX: Do even more input validation/scrubbing?
1372 if (array_key_exists($key, $this->args)) {
1375 $page = (int)$this->args['page'];
1376 return ($page < 1) ? 1 : $page;
1378 $count = (int)$this->args['count'];
1381 } elseif ($count > 200) {
1387 $since_id = (int)$this->args['since_id'];
1388 return ($since_id < 1) ? 0 : $since_id;
1390 $max_id = (int)$this->args['max_id'];
1391 return ($max_id < 1) ? 0 : $max_id;
1393 return parent::arg($key, $def);
1401 * Calculate the complete URI that called up this action. Used for
1402 * Atom rel="self" links. Warning: this is funky.
1404 * @return string URL a URL suitable for rel="self" Atom links
1406 function getSelfUri()
1408 $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1410 $id = $this->arg('id');
1411 $aargs = array('format' => $this->format);
1416 $tag = $this->arg('tag');
1418 $aargs['tag'] = $tag;
1421 parse_str($_SERVER['QUERY_STRING'], $params);
1423 if (!empty($params)) {
1424 unset($params['p']);
1425 $pstring = http_build_query($params);
1428 $uri = common_local_url($action, $aargs);
1430 if (!empty($pstring)) {
1431 $uri .= '?' . $pstring;