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 $this->element($element, null, $value);
514 $this->elementEnd($tag);
517 function showTwitterXmlGroup($twitter_group)
519 $this->elementStart('group');
520 foreach($twitter_group as $element => $value) {
521 $this->element($element, null, $value);
523 $this->elementEnd('group');
526 function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
530 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
532 $this->elementStart($role, $attrs);
533 foreach($twitter_user as $element => $value) {
534 if ($element == 'status') {
535 $this->showTwitterXmlStatus($twitter_user['status']);
537 $this->element($element, null, $value);
540 $this->elementEnd($role);
543 function showXmlAttachments($attachments) {
544 if (!empty($attachments)) {
545 $this->elementStart('attachments', array('type' => 'array'));
546 foreach ($attachments as $attachment) {
548 $attrs['url'] = $attachment['url'];
549 $attrs['mimetype'] = $attachment['mimetype'];
550 $attrs['size'] = $attachment['size'];
551 $this->element('enclosure', $attrs, '');
553 $this->elementEnd('attachments');
557 function showGeoXML($geo)
561 $this->element('geo');
563 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
564 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
565 $this->elementEnd('geo');
569 function showGeoRSS($geo)
575 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
580 function showTwitterRssItem($entry)
582 $this->elementStart('item');
583 $this->element('title', null, $entry['title']);
584 $this->element('description', null, $entry['description']);
585 $this->element('pubDate', null, $entry['pubDate']);
586 $this->element('guid', null, $entry['guid']);
587 $this->element('link', null, $entry['link']);
589 # RSS only supports 1 enclosure per item
590 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
591 $enclosure = $entry['enclosures'][0];
592 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
595 if(array_key_exists('tags', $entry)){
596 foreach($entry['tags'] as $tag){
597 $this->element('category', null,$tag);
601 $this->showGeoRSS($entry['geo']);
602 $this->elementEnd('item');
605 function showJsonObjects($objects)
607 print(json_encode($objects));
610 function showSingleXmlStatus($notice)
612 $this->initDocument('xml');
613 $twitter_status = $this->twitterStatusArray($notice);
614 $this->showTwitterXmlStatus($twitter_status, 'status', true);
615 $this->endDocument('xml');
618 function show_single_json_status($notice)
620 $this->initDocument('json');
621 $status = $this->twitterStatusArray($notice);
622 $this->showJsonObjects($status);
623 $this->endDocument('json');
626 function showXmlTimeline($notice)
629 $this->initDocument('xml');
630 $this->elementStart('statuses', array('type' => 'array',
631 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
633 if (is_array($notice)) {
634 foreach ($notice as $n) {
635 $twitter_status = $this->twitterStatusArray($n);
636 $this->showTwitterXmlStatus($twitter_status);
639 while ($notice->fetch()) {
640 $twitter_status = $this->twitterStatusArray($notice);
641 $this->showTwitterXmlStatus($twitter_status);
645 $this->elementEnd('statuses');
646 $this->endDocument('xml');
649 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
652 $this->initDocument('rss');
654 $this->element('title', null, $title);
655 $this->element('link', null, $link);
657 if (!is_null($self)) {
661 'type' => 'application/rss+xml',
668 if (!is_null($suplink)) {
669 // For FriendFeed's SUP protocol
670 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
671 'rel' => 'http://api.friendfeed.com/2008/03#sup',
673 'type' => 'application/json'));
676 if (!is_null($logo)) {
677 $this->elementStart('image');
678 $this->element('link', null, $link);
679 $this->element('title', null, $title);
680 $this->element('url', null, $logo);
681 $this->elementEnd('image');
684 $this->element('description', null, $subtitle);
685 $this->element('language', null, 'en-us');
686 $this->element('ttl', null, '40');
688 if (is_array($notice)) {
689 foreach ($notice as $n) {
690 $entry = $this->twitterRssEntryArray($n);
691 $this->showTwitterRssItem($entry);
694 while ($notice->fetch()) {
695 $entry = $this->twitterRssEntryArray($notice);
696 $this->showTwitterRssItem($entry);
700 $this->endTwitterRss();
703 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
706 $this->initDocument('atom');
708 $this->element('title', null, $title);
709 $this->element('id', null, $id);
710 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
712 if (!is_null($logo)) {
713 $this->element('logo',null,$logo);
716 if (!is_null($suplink)) {
717 # For FriendFeed's SUP protocol
718 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
720 'type' => 'application/json'));
723 if (!is_null($selfuri)) {
724 $this->element('link', array('href' => $selfuri,
725 'rel' => 'self', 'type' => 'application/atom+xml'), null);
728 $this->element('updated', null, common_date_iso8601('now'));
729 $this->element('subtitle', null, $subtitle);
731 if (is_array($notice)) {
732 foreach ($notice as $n) {
733 $this->raw($n->asAtomEntry());
736 while ($notice->fetch()) {
737 $this->raw($notice->asAtomEntry());
741 $this->endDocument('atom');
745 function showRssGroups($group, $title, $link, $subtitle)
748 $this->initDocument('rss');
750 $this->element('title', null, $title);
751 $this->element('link', null, $link);
752 $this->element('description', null, $subtitle);
753 $this->element('language', null, 'en-us');
754 $this->element('ttl', null, '40');
756 if (is_array($group)) {
757 foreach ($group as $g) {
758 $twitter_group = $this->twitterRssGroupArray($g);
759 $this->showTwitterRssItem($twitter_group);
762 while ($group->fetch()) {
763 $twitter_group = $this->twitterRssGroupArray($group);
764 $this->showTwitterRssItem($twitter_group);
768 $this->endTwitterRss();
771 function showTwitterAtomEntry($entry)
773 $this->elementStart('entry');
774 $this->element('title', null, common_xml_safe_str($entry['title']));
777 array('type' => 'html'),
778 common_xml_safe_str($entry['content'])
780 $this->element('id', null, $entry['id']);
781 $this->element('published', null, $entry['published']);
782 $this->element('updated', null, $entry['updated']);
783 $this->element('link', array('type' => 'text/html',
784 'href' => $entry['link'],
785 'rel' => 'alternate'));
786 $this->element('link', array('type' => $entry['avatar-type'],
787 'href' => $entry['avatar'],
789 $this->elementStart('author');
791 $this->element('name', null, $entry['author-name']);
792 $this->element('uri', null, $entry['author-uri']);
794 $this->elementEnd('author');
795 $this->elementEnd('entry');
798 function showXmlDirectMessage($dm, $namespaces=false)
802 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
804 $this->elementStart('direct_message', $attrs);
805 foreach($dm as $element => $value) {
809 $this->showTwitterXmlUser($value, $element);
812 $this->element($element, null, common_xml_safe_str($value));
815 $this->element($element, null, $value);
819 $this->elementEnd('direct_message');
822 function directMessageArray($message)
826 $from_profile = $message->getFrom();
827 $to_profile = $message->getTo();
829 $dmsg['id'] = $message->id;
830 $dmsg['sender_id'] = $message->from_profile;
831 $dmsg['text'] = trim($message->content);
832 $dmsg['recipient_id'] = $message->to_profile;
833 $dmsg['created_at'] = $this->dateTwitter($message->created);
834 $dmsg['sender_screen_name'] = $from_profile->nickname;
835 $dmsg['recipient_screen_name'] = $to_profile->nickname;
836 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
837 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
842 function rssDirectMessageArray($message)
846 $from = $message->getFrom();
848 $entry['title'] = sprintf('Message from %1$s to %2$s',
849 $from->nickname, $message->getTo()->nickname);
851 $entry['content'] = common_xml_safe_str($message->rendered);
852 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
853 $entry['published'] = common_date_iso8601($message->created);
855 $taguribase = TagURI::base();
857 $entry['id'] = "tag:$taguribase:$entry[link]";
858 $entry['updated'] = $entry['published'];
860 $entry['author-name'] = $from->getBestName();
861 $entry['author-uri'] = $from->homepage;
863 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
865 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
866 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
870 $entry['description'] = $entry['content'];
871 $entry['pubDate'] = common_date_rfc2822($message->created);
872 $entry['guid'] = $entry['link'];
877 function showSingleXmlDirectMessage($message)
879 $this->initDocument('xml');
880 $dmsg = $this->directMessageArray($message);
881 $this->showXmlDirectMessage($dmsg, true);
882 $this->endDocument('xml');
885 function showSingleJsonDirectMessage($message)
887 $this->initDocument('json');
888 $dmsg = $this->directMessageArray($message);
889 $this->showJsonObjects($dmsg);
890 $this->endDocument('json');
893 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
896 $this->initDocument('atom');
898 $this->element('title', null, common_xml_safe_str($title));
899 $this->element('id', null, $id);
900 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
902 if (!is_null($selfuri)) {
903 $this->element('link', array('href' => $selfuri,
904 'rel' => 'self', 'type' => 'application/atom+xml'), null);
907 $this->element('updated', null, common_date_iso8601('now'));
908 $this->element('subtitle', null, common_xml_safe_str($subtitle));
910 if (is_array($group)) {
911 foreach ($group as $g) {
912 $this->raw($g->asAtomEntry());
915 while ($group->fetch()) {
916 $this->raw($group->asAtomEntry());
920 $this->endDocument('atom');
924 function showJsonTimeline($notice)
927 $this->initDocument('json');
931 if (is_array($notice)) {
932 foreach ($notice as $n) {
933 $twitter_status = $this->twitterStatusArray($n);
934 array_push($statuses, $twitter_status);
937 while ($notice->fetch()) {
938 $twitter_status = $this->twitterStatusArray($notice);
939 array_push($statuses, $twitter_status);
943 $this->showJsonObjects($statuses);
945 $this->endDocument('json');
948 function showJsonGroups($group)
951 $this->initDocument('json');
955 if (is_array($group)) {
956 foreach ($group as $g) {
957 $twitter_group = $this->twitterGroupArray($g);
958 array_push($groups, $twitter_group);
961 while ($group->fetch()) {
962 $twitter_group = $this->twitterGroupArray($group);
963 array_push($groups, $twitter_group);
967 $this->showJsonObjects($groups);
969 $this->endDocument('json');
972 function showXmlGroups($group)
975 $this->initDocument('xml');
976 $this->elementStart('groups', array('type' => 'array'));
978 if (is_array($group)) {
979 foreach ($group as $g) {
980 $twitter_group = $this->twitterGroupArray($g);
981 $this->showTwitterXmlGroup($twitter_group);
984 while ($group->fetch()) {
985 $twitter_group = $this->twitterGroupArray($group);
986 $this->showTwitterXmlGroup($twitter_group);
990 $this->elementEnd('groups');
991 $this->endDocument('xml');
994 function showTwitterXmlUsers($user)
997 $this->initDocument('xml');
998 $this->elementStart('users', array('type' => 'array',
999 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1001 if (is_array($user)) {
1002 foreach ($user as $u) {
1003 $twitter_user = $this->twitterUserArray($u);
1004 $this->showTwitterXmlUser($twitter_user);
1007 while ($user->fetch()) {
1008 $twitter_user = $this->twitterUserArray($user);
1009 $this->showTwitterXmlUser($twitter_user);
1013 $this->elementEnd('users');
1014 $this->endDocument('xml');
1017 function showJsonUsers($user)
1020 $this->initDocument('json');
1024 if (is_array($user)) {
1025 foreach ($user as $u) {
1026 $twitter_user = $this->twitterUserArray($u);
1027 array_push($users, $twitter_user);
1030 while ($user->fetch()) {
1031 $twitter_user = $this->twitterUserArray($user);
1032 array_push($users, $twitter_user);
1036 $this->showJsonObjects($users);
1038 $this->endDocument('json');
1041 function showSingleJsonGroup($group)
1043 $this->initDocument('json');
1044 $twitter_group = $this->twitterGroupArray($group);
1045 $this->showJsonObjects($twitter_group);
1046 $this->endDocument('json');
1049 function showSingleXmlGroup($group)
1051 $this->initDocument('xml');
1052 $twitter_group = $this->twitterGroupArray($group);
1053 $this->showTwitterXmlGroup($twitter_group);
1054 $this->endDocument('xml');
1057 function dateTwitter($dt)
1059 $dateStr = date('d F Y H:i:s', strtotime($dt));
1060 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1061 $d->setTimezone(new DateTimeZone(common_timezone()));
1062 return $d->format('D M d H:i:s O Y');
1065 function initDocument($type='xml')
1069 header('Content-Type: application/xml; charset=utf-8');
1073 header('Content-Type: application/json; charset=utf-8');
1075 // Check for JSONP callback
1076 $callback = $this->arg('callback');
1078 print $callback . '(';
1082 header("Content-Type: application/rss+xml; charset=utf-8");
1083 $this->initTwitterRss();
1086 header('Content-Type: application/atom+xml; charset=utf-8');
1087 $this->initTwitterAtom();
1090 $this->clientError(_('Not a supported data format.'));
1097 function endDocument($type='xml')
1105 // Check for JSONP callback
1106 $callback = $this->arg('callback');
1112 $this->endTwitterRss();
1115 $this->endTwitterRss();
1118 $this->clientError(_('Not a supported data format.'));
1124 function clientError($msg, $code = 400, $format = 'xml')
1126 $action = $this->trimmed('action');
1128 common_debug("User error '$code' on '$action': $msg", __FILE__);
1130 if (!array_key_exists($code, ClientErrorAction::$status)) {
1134 $status_string = ClientErrorAction::$status[$code];
1136 header('HTTP/1.1 '.$code.' '.$status_string);
1138 if ($format == 'xml') {
1139 $this->initDocument('xml');
1140 $this->elementStart('hash');
1141 $this->element('error', null, $msg);
1142 $this->element('request', null, $_SERVER['REQUEST_URI']);
1143 $this->elementEnd('hash');
1144 $this->endDocument('xml');
1145 } elseif ($format == 'json'){
1146 $this->initDocument('json');
1147 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1148 print(json_encode($error_array));
1149 $this->endDocument('json');
1152 // If user didn't request a useful format, throw a regular client error
1153 throw new ClientException($msg, $code);
1157 function serverError($msg, $code = 500, $content_type = 'xml')
1159 $action = $this->trimmed('action');
1161 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1163 if (!array_key_exists($code, ServerErrorAction::$status)) {
1167 $status_string = ServerErrorAction::$status[$code];
1169 header('HTTP/1.1 '.$code.' '.$status_string);
1171 if ($content_type == 'xml') {
1172 $this->initDocument('xml');
1173 $this->elementStart('hash');
1174 $this->element('error', null, $msg);
1175 $this->element('request', null, $_SERVER['REQUEST_URI']);
1176 $this->elementEnd('hash');
1177 $this->endDocument('xml');
1179 $this->initDocument('json');
1180 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1181 print(json_encode($error_array));
1182 $this->endDocument('json');
1186 function initTwitterRss()
1189 $this->elementStart(
1193 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1194 'xmlns:georss' => 'http://www.georss.org/georss'
1197 $this->elementStart('channel');
1198 Event::handle('StartApiRss', array($this));
1201 function endTwitterRss()
1203 $this->elementEnd('channel');
1204 $this->elementEnd('rss');
1208 function initTwitterAtom()
1211 // FIXME: don't hardcode the language here!
1212 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1213 'xml:lang' => 'en-US',
1214 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1217 function endTwitterAtom()
1219 $this->elementEnd('feed');
1223 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1225 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1226 switch ($content_type) {
1228 $this->showTwitterXmlUser($profile_array);
1231 $this->showJsonObjects($profile_array);
1234 $this->clientError(_('Not a supported data format.'));
1240 function getTargetUser($id)
1244 // Twitter supports these other ways of passing the user ID
1245 if (is_numeric($this->arg('id'))) {
1246 return User::staticGet($this->arg('id'));
1247 } else if ($this->arg('id')) {
1248 $nickname = common_canonical_nickname($this->arg('id'));
1249 return User::staticGet('nickname', $nickname);
1250 } else if ($this->arg('user_id')) {
1251 // This is to ensure that a non-numeric user_id still
1252 // overrides screen_name even if it doesn't get used
1253 if (is_numeric($this->arg('user_id'))) {
1254 return User::staticGet('id', $this->arg('user_id'));
1256 } else if ($this->arg('screen_name')) {
1257 $nickname = common_canonical_nickname($this->arg('screen_name'));
1258 return User::staticGet('nickname', $nickname);
1260 // Fall back to trying the currently authenticated user
1261 return $this->auth_user;
1264 } else if (is_numeric($id)) {
1265 return User::staticGet($id);
1267 $nickname = common_canonical_nickname($id);
1268 return User::staticGet('nickname', $nickname);
1272 function getTargetGroup($id)
1275 if (is_numeric($this->arg('id'))) {
1276 return User_group::staticGet($this->arg('id'));
1277 } else if ($this->arg('id')) {
1278 $nickname = common_canonical_nickname($this->arg('id'));
1279 $local = Local_group::staticGet('nickname', $nickname);
1280 if (empty($local)) {
1283 return User_group::staticGet('id', $local->id);
1285 } else if ($this->arg('group_id')) {
1286 // This is to ensure that a non-numeric user_id still
1287 // overrides screen_name even if it doesn't get used
1288 if (is_numeric($this->arg('group_id'))) {
1289 return User_group::staticGet('id', $this->arg('group_id'));
1291 } else if ($this->arg('group_name')) {
1292 $nickname = common_canonical_nickname($this->arg('group_name'));
1293 $local = Local_group::staticGet('nickname', $nickname);
1294 if (empty($local)) {
1297 return User_group::staticGet('id', $local->group_id);
1301 } else if (is_numeric($id)) {
1302 return User_group::staticGet($id);
1304 $nickname = common_canonical_nickname($id);
1305 $local = Local_group::staticGet('nickname', $nickname);
1306 if (empty($local)) {
1309 return User_group::staticGet('id', $local->group_id);
1314 function sourceLink($source)
1316 $source_name = _($source);
1329 $ns = Notice_source::staticGet($source);
1335 $app = Oauth_application::staticGet('name', $source);
1338 $url = $app->source_url;
1342 if (!empty($name) && !empty($url)) {
1343 $source_name = '<a href="' . $url . '">' . $name . '</a>';
1348 return $source_name;
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;