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
58 var $auth_user = null;
68 * @param array $args Web and URL arguments
70 * @return boolean false if user doesn't exist
73 function prepare($args)
75 parent::prepare($args);
77 $this->format = $this->arg('format');
78 $this->page = (int)$this->arg('page', 1);
79 $this->count = (int)$this->arg('count', 20);
80 $this->max_id = (int)$this->arg('max_id', 0);
81 $this->since_id = (int)$this->arg('since_id', 0);
82 $this->since = $this->arg('since');
90 * @param array $args Arguments from $_REQUEST
95 function handle($args)
97 parent::handle($args);
101 * Overrides XMLOutputter::element to write booleans as strings (true|false).
102 * See that method's documentation for more info.
104 * @param string $tag Element type or tagname
105 * @param array $attrs Array of element attributes, as
107 * @param string $content string content of the element
111 function element($tag, $attrs=null, $content=null)
113 if (is_bool($content)) {
114 $content = ($content ? 'true' : 'false');
117 return parent::element($tag, $attrs, $content);
120 function twitterUserArray($profile, $get_notice=false)
122 $twitter_user = array();
124 $twitter_user['id'] = intval($profile->id);
125 $twitter_user['name'] = $profile->getBestName();
126 $twitter_user['screen_name'] = $profile->nickname;
127 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
128 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
130 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
131 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
132 Avatar::defaultImage(AVATAR_STREAM_SIZE);
134 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
135 $twitter_user['protected'] = false; # not supported by StatusNet yet
136 $twitter_user['followers_count'] = $profile->subscriberCount();
139 $user = $profile->getUser();
141 // Note: some profiles don't have an associated user
144 $design = $user->getDesign();
147 if (empty($design)) {
148 $design = Design::siteDesign();
151 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
152 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
153 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
154 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
155 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
156 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
157 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
158 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
159 $twitter_user['profile_sidebar_border_color'] = '';
161 $twitter_user['friends_count'] = $profile->subscriptionCount();
163 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
165 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
169 if ($user->timezone) {
170 $timezone = $user->timezone;
174 $t->setTimezone(new DateTimeZone($timezone));
176 $twitter_user['utc_offset'] = $t->format('Z');
177 $twitter_user['time_zone'] = $timezone;
179 $twitter_user['profile_background_image_url']
180 = empty($design->backgroundimage)
181 ? '' : ($design->disposition & BACKGROUND_ON)
182 ? Design::url($design->backgroundimage) : '';
184 $twitter_user['profile_background_tile']
185 = empty($design->disposition)
186 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
188 $twitter_user['statuses_count'] = $profile->noticeCount();
190 // Is the requesting user following this user?
191 $twitter_user['following'] = false;
192 $twitter_user['notifications'] = false;
194 if (isset($this->auth_user)) {
196 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
199 $sub = Subscription::pkeyGet(array('subscriber' =>
200 $this->auth_user->id,
201 'subscribed' => $profile->id));
204 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
209 $notice = $profile->getCurrentNotice();
212 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
216 return $twitter_user;
219 function twitterStatusArray($notice, $include_user=true)
221 $base = $this->twitterSimpleStatusArray($notice, $include_user);
223 if (empty($notice->repeat_of)) {
226 $original = Notice::staticGet('id', $notice->repeat_of);
227 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
228 $original_array['retweeted_status'] = $base;
229 return $original_array;
233 function twitterSimpleStatusArray($notice, $include_user=true)
235 $profile = $notice->getProfile();
237 $twitter_status = array();
238 $twitter_status['text'] = $notice->content;
239 $twitter_status['truncated'] = false; # Not possible on StatusNet
240 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
241 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
242 intval($notice->reply_to) : null;
243 $twitter_status['source'] = $this->sourceLink($notice->source);
244 $twitter_status['id'] = intval($notice->id);
246 $replier_profile = null;
248 if ($notice->reply_to) {
249 $reply = Notice::staticGet(intval($notice->reply_to));
251 $replier_profile = $reply->getProfile();
255 $twitter_status['in_reply_to_user_id'] =
256 ($replier_profile) ? intval($replier_profile->id) : null;
257 $twitter_status['in_reply_to_screen_name'] =
258 ($replier_profile) ? $replier_profile->nickname : null;
260 if (isset($notice->lat) && isset($notice->lon)) {
261 // This is the format that GeoJSON expects stuff to be in
262 $twitter_status['geo'] = array('type' => 'Point',
263 'coordinates' => array((float) $notice->lat,
264 (float) $notice->lon));
266 $twitter_status['geo'] = null;
269 if (isset($this->auth_user)) {
270 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
272 $twitter_status['favorited'] = false;
276 $attachments = $notice->attachments();
278 if (!empty($attachments)) {
280 $twitter_status['attachments'] = array();
282 foreach ($attachments as $attachment) {
283 if ($attachment->isEnclosure()) {
284 $enclosure = array();
285 $enclosure['url'] = $attachment->url;
286 $enclosure['mimetype'] = $attachment->mimetype;
287 $enclosure['size'] = $attachment->size;
288 $twitter_status['attachments'][] = $enclosure;
294 # Don't get notice (recursive!)
295 $twitter_user = $this->twitterUserArray($profile, false);
296 $twitter_status['user'] = $twitter_user;
299 return $twitter_status;
302 function twitterGroupArray($group)
304 $twitter_group=array();
305 $twitter_group['id']=$group->id;
306 $twitter_group['url']=$group->permalink();
307 $twitter_group['nickname']=$group->nickname;
308 $twitter_group['fullname']=$group->fullname;
309 $twitter_group['homepage_url']=$group->homepage_url;
310 $twitter_group['original_logo']=$group->original_logo;
311 $twitter_group['homepage_logo']=$group->homepage_logo;
312 $twitter_group['stream_logo']=$group->stream_logo;
313 $twitter_group['mini_logo']=$group->mini_logo;
314 $twitter_group['homepage']=$group->homepage;
315 $twitter_group['description']=$group->description;
316 $twitter_group['location']=$group->location;
317 $twitter_group['created']=$this->dateTwitter($group->created);
318 $twitter_group['modified']=$this->dateTwitter($group->modified);
319 return $twitter_group;
322 function twitterRssGroupArray($group)
325 $entry['content']=$group->description;
326 $entry['title']=$group->nickname;
327 $entry['link']=$group->permalink();
328 $entry['published']=common_date_iso8601($group->created);
329 $entry['updated']==common_date_iso8601($group->modified);
330 $taguribase = common_config('integration', 'groupuri');
331 $entry['id'] = "group:$groupuribase:$entry[link]";
333 $entry['description'] = $entry['content'];
334 $entry['pubDate'] = common_date_rfc2822($group->created);
335 $entry['guid'] = $entry['link'];
340 function twitterRssEntryArray($notice)
342 $profile = $notice->getProfile();
345 // We trim() to avoid extraneous whitespace in the output
347 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
348 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
349 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
350 $entry['published'] = common_date_iso8601($notice->created);
352 $taguribase = common_config('integration', 'taguri');
353 $entry['id'] = "tag:$taguribase:$entry[link]";
355 $entry['updated'] = $entry['published'];
356 $entry['author'] = $profile->getBestName();
359 $attachments = $notice->attachments();
360 $enclosures = array();
362 foreach ($attachments as $attachment) {
363 $enclosure_o=$attachment->getEnclosure();
365 $enclosure = array();
366 $enclosure['url'] = $enclosure_o->url;
367 $enclosure['mimetype'] = $enclosure_o->mimetype;
368 $enclosure['size'] = $enclosure_o->size;
369 $enclosures[] = $enclosure;
373 if (!empty($enclosures)) {
374 $entry['enclosures'] = $enclosures;
378 $tag = new Notice_tag();
379 $tag->notice_id = $notice->id;
381 $entry['tags']=array();
382 while ($tag->fetch()) {
383 $entry['tags'][]=$tag->tag;
389 $entry['description'] = $entry['content'];
390 $entry['pubDate'] = common_date_rfc2822($notice->created);
391 $entry['guid'] = $entry['link'];
393 if (isset($notice->lat) && isset($notice->lon)) {
394 // This is the format that GeoJSON expects stuff to be in.
395 // showGeoRSS() below uses it for XML output, so we reuse it
396 $entry['geo'] = array('type' => 'Point',
397 'coordinates' => array((float) $notice->lat,
398 (float) $notice->lon));
400 $entry['geo'] = null;
406 function twitterRelationshipArray($source, $target)
408 $relationship = array();
410 $relationship['source'] =
411 $this->relationshipDetailsArray($source, $target);
412 $relationship['target'] =
413 $this->relationshipDetailsArray($target, $source);
415 return array('relationship' => $relationship);
418 function relationshipDetailsArray($source, $target)
422 $details['screen_name'] = $source->nickname;
423 $details['followed_by'] = $target->isSubscribed($source);
424 $details['following'] = $source->isSubscribed($target);
426 $notifications = false;
428 if ($source->isSubscribed($target)) {
430 $sub = Subscription::pkeyGet(array('subscriber' =>
431 $source->id, 'subscribed' => $target->id));
434 $notifications = ($sub->jabber || $sub->sms);
438 $details['notifications_enabled'] = $notifications;
439 $details['blocking'] = $source->hasBlocked($target);
440 $details['id'] = $source->id;
445 function showTwitterXmlRelationship($relationship)
447 $this->elementStart('relationship');
449 foreach($relationship as $element => $value) {
450 if ($element == 'source' || $element == 'target') {
451 $this->elementStart($element);
452 $this->showXmlRelationshipDetails($value);
453 $this->elementEnd($element);
457 $this->elementEnd('relationship');
460 function showXmlRelationshipDetails($details)
462 foreach($details as $element => $value) {
463 $this->element($element, null, $value);
467 function showTwitterXmlStatus($twitter_status, $tag='status')
469 $this->elementStart($tag);
470 foreach($twitter_status as $element => $value) {
473 $this->showTwitterXmlUser($twitter_status['user']);
476 $this->element($element, null, common_xml_safe_str($value));
479 $this->showXmlAttachments($twitter_status['attachments']);
482 $this->showGeoRSS($value);
484 case 'retweeted_status':
485 $this->showTwitterXmlStatus($value, 'retweeted_status');
488 $this->element($element, null, $value);
491 $this->elementEnd($tag);
494 function showTwitterXmlGroup($twitter_group)
496 $this->elementStart('group');
497 foreach($twitter_group as $element => $value) {
498 $this->element($element, null, $value);
500 $this->elementEnd('group');
503 function showTwitterXmlUser($twitter_user, $role='user')
505 $this->elementStart($role);
506 foreach($twitter_user as $element => $value) {
507 if ($element == 'status') {
508 $this->showTwitterXmlStatus($twitter_user['status']);
510 $this->element($element, null, $value);
513 $this->elementEnd($role);
516 function showXmlAttachments($attachments) {
517 if (!empty($attachments)) {
518 $this->elementStart('attachments', array('type' => 'array'));
519 foreach ($attachments as $attachment) {
521 $attrs['url'] = $attachment['url'];
522 $attrs['mimetype'] = $attachment['mimetype'];
523 $attrs['size'] = $attachment['size'];
524 $this->element('enclosure', $attrs, '');
526 $this->elementEnd('attachments');
530 function showGeoRSS($geo)
534 $this->element('geo');
536 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
537 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
538 $this->elementEnd('geo');
542 function showTwitterRssItem($entry)
544 $this->elementStart('item');
545 $this->element('title', null, $entry['title']);
546 $this->element('description', null, $entry['description']);
547 $this->element('pubDate', null, $entry['pubDate']);
548 $this->element('guid', null, $entry['guid']);
549 $this->element('link', null, $entry['link']);
551 # RSS only supports 1 enclosure per item
552 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
553 $enclosure = $entry['enclosures'][0];
554 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
557 if(array_key_exists('tags', $entry)){
558 foreach($entry['tags'] as $tag){
559 $this->element('category', null,$tag);
563 $this->showGeoRSS($entry['geo']);
564 $this->elementEnd('item');
567 function showJsonObjects($objects)
569 print(json_encode($objects));
572 function showSingleXmlStatus($notice)
574 $this->initDocument('xml');
575 $twitter_status = $this->twitterStatusArray($notice);
576 $this->showTwitterXmlStatus($twitter_status);
577 $this->endDocument('xml');
580 function show_single_json_status($notice)
582 $this->initDocument('json');
583 $status = $this->twitterStatusArray($notice);
584 $this->showJsonObjects($status);
585 $this->endDocument('json');
588 function showXmlTimeline($notice)
591 $this->initDocument('xml');
592 $this->elementStart('statuses', array('type' => 'array'));
594 if (is_array($notice)) {
595 foreach ($notice as $n) {
596 $twitter_status = $this->twitterStatusArray($n);
597 $this->showTwitterXmlStatus($twitter_status);
600 while ($notice->fetch()) {
601 $twitter_status = $this->twitterStatusArray($notice);
602 $this->showTwitterXmlStatus($twitter_status);
606 $this->elementEnd('statuses');
607 $this->endDocument('xml');
610 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
613 $this->initDocument('rss');
615 $this->element('title', null, $title);
616 $this->element('link', null, $link);
617 if (!is_null($suplink)) {
618 // For FriendFeed's SUP protocol
619 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
620 'rel' => 'http://api.friendfeed.com/2008/03#sup',
622 'type' => 'application/json'));
625 if (!is_null($logo)) {
626 $this->elementStart('image');
627 $this->element('link', null, $link);
628 $this->element('title', null, $title);
629 $this->element('url', null, $logo);
630 $this->elementEnd('image');
633 $this->element('description', null, $subtitle);
634 $this->element('language', null, 'en-us');
635 $this->element('ttl', null, '40');
637 if (is_array($notice)) {
638 foreach ($notice as $n) {
639 $entry = $this->twitterRssEntryArray($n);
640 $this->showTwitterRssItem($entry);
643 while ($notice->fetch()) {
644 $entry = $this->twitterRssEntryArray($notice);
645 $this->showTwitterRssItem($entry);
649 $this->endTwitterRss();
652 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
655 $this->initDocument('atom');
657 $this->element('title', null, $title);
658 $this->element('id', null, $id);
659 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
661 if (!is_null($logo)) {
662 $this->element('logo',null,$logo);
665 if (!is_null($suplink)) {
666 # For FriendFeed's SUP protocol
667 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
669 'type' => 'application/json'));
672 if (!is_null($selfuri)) {
673 $this->element('link', array('href' => $selfuri,
674 'rel' => 'self', 'type' => 'application/atom+xml'), null);
677 $this->element('updated', null, common_date_iso8601('now'));
678 $this->element('subtitle', null, $subtitle);
680 if (is_array($notice)) {
681 foreach ($notice as $n) {
682 $this->raw($n->asAtomEntry());
685 while ($notice->fetch()) {
686 $this->raw($notice->asAtomEntry());
690 $this->endDocument('atom');
694 function showRssGroups($group, $title, $link, $subtitle)
697 $this->initDocument('rss');
699 $this->element('title', null, $title);
700 $this->element('link', null, $link);
701 $this->element('description', null, $subtitle);
702 $this->element('language', null, 'en-us');
703 $this->element('ttl', null, '40');
705 if (is_array($group)) {
706 foreach ($group as $g) {
707 $twitter_group = $this->twitterRssGroupArray($g);
708 $this->showTwitterRssItem($twitter_group);
711 while ($group->fetch()) {
712 $twitter_group = $this->twitterRssGroupArray($group);
713 $this->showTwitterRssItem($twitter_group);
717 $this->endTwitterRss();
720 function showTwitterAtomEntry($entry)
722 $this->elementStart('entry');
723 $this->element('title', null, $entry['title']);
724 $this->element('content', array('type' => 'html'), $entry['content']);
725 $this->element('id', null, $entry['id']);
726 $this->element('published', null, $entry['published']);
727 $this->element('updated', null, $entry['updated']);
728 $this->element('link', array('type' => 'text/html',
729 'href' => $entry['link'],
730 'rel' => 'alternate'));
731 $this->element('link', array('type' => $entry['avatar-type'],
732 'href' => $entry['avatar'],
734 $this->elementStart('author');
736 $this->element('name', null, $entry['author-name']);
737 $this->element('uri', null, $entry['author-uri']);
739 $this->elementEnd('author');
740 $this->elementEnd('entry');
743 function showXmlDirectMessage($dm)
745 $this->elementStart('direct_message');
746 foreach($dm as $element => $value) {
750 $this->showTwitterXmlUser($value, $element);
753 $this->element($element, null, common_xml_safe_str($value));
756 $this->element($element, null, $value);
760 $this->elementEnd('direct_message');
763 function directMessageArray($message)
767 $from_profile = $message->getFrom();
768 $to_profile = $message->getTo();
770 $dmsg['id'] = $message->id;
771 $dmsg['sender_id'] = $message->from_profile;
772 $dmsg['text'] = trim($message->content);
773 $dmsg['recipient_id'] = $message->to_profile;
774 $dmsg['created_at'] = $this->dateTwitter($message->created);
775 $dmsg['sender_screen_name'] = $from_profile->nickname;
776 $dmsg['recipient_screen_name'] = $to_profile->nickname;
777 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
778 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
783 function rssDirectMessageArray($message)
787 $from = $message->getFrom();
789 $entry['title'] = sprintf('Message from %s to %s',
790 $from->nickname, $message->getTo()->nickname);
792 $entry['content'] = common_xml_safe_str($message->rendered);
793 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
794 $entry['published'] = common_date_iso8601($message->created);
796 $taguribase = common_config('integration', 'taguri');
798 $entry['id'] = "tag:$taguribase:$entry[link]";
799 $entry['updated'] = $entry['published'];
801 $entry['author-name'] = $from->getBestName();
802 $entry['author-uri'] = $from->homepage;
804 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
806 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
807 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
811 $entry['description'] = $entry['content'];
812 $entry['pubDate'] = common_date_rfc2822($message->created);
813 $entry['guid'] = $entry['link'];
818 function showSingleXmlDirectMessage($message)
820 $this->initDocument('xml');
821 $dmsg = $this->directMessageArray($message);
822 $this->showXmlDirectMessage($dmsg);
823 $this->endDocument('xml');
826 function showSingleJsonDirectMessage($message)
828 $this->initDocument('json');
829 $dmsg = $this->directMessageArray($message);
830 $this->showJsonObjects($dmsg);
831 $this->endDocument('json');
834 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
837 $this->initDocument('atom');
839 $this->element('title', null, $title);
840 $this->element('id', null, $id);
841 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
843 if (!is_null($selfuri)) {
844 $this->element('link', array('href' => $selfuri,
845 'rel' => 'self', 'type' => 'application/atom+xml'), null);
848 $this->element('updated', null, common_date_iso8601('now'));
849 $this->element('subtitle', null, $subtitle);
851 if (is_array($group)) {
852 foreach ($group as $g) {
853 $this->raw($g->asAtomEntry());
856 while ($group->fetch()) {
857 $this->raw($group->asAtomEntry());
861 $this->endDocument('atom');
865 function showJsonTimeline($notice)
868 $this->initDocument('json');
872 if (is_array($notice)) {
873 foreach ($notice as $n) {
874 $twitter_status = $this->twitterStatusArray($n);
875 array_push($statuses, $twitter_status);
878 while ($notice->fetch()) {
879 $twitter_status = $this->twitterStatusArray($notice);
880 array_push($statuses, $twitter_status);
884 $this->showJsonObjects($statuses);
886 $this->endDocument('json');
889 function showJsonGroups($group)
892 $this->initDocument('json');
896 if (is_array($group)) {
897 foreach ($group as $g) {
898 $twitter_group = $this->twitterGroupArray($g);
899 array_push($groups, $twitter_group);
902 while ($group->fetch()) {
903 $twitter_group = $this->twitterGroupArray($group);
904 array_push($groups, $twitter_group);
908 $this->showJsonObjects($groups);
910 $this->endDocument('json');
913 function showXmlGroups($group)
916 $this->initDocument('xml');
917 $this->elementStart('groups', array('type' => 'array'));
919 if (is_array($group)) {
920 foreach ($group as $g) {
921 $twitter_group = $this->twitterGroupArray($g);
922 $this->showTwitterXmlGroup($twitter_group);
925 while ($group->fetch()) {
926 $twitter_group = $this->twitterGroupArray($group);
927 $this->showTwitterXmlGroup($twitter_group);
931 $this->elementEnd('groups');
932 $this->endDocument('xml');
935 function showTwitterXmlUsers($user)
938 $this->initDocument('xml');
939 $this->elementStart('users', array('type' => 'array'));
941 if (is_array($user)) {
942 foreach ($user as $u) {
943 $twitter_user = $this->twitterUserArray($u);
944 $this->showTwitterXmlUser($twitter_user);
947 while ($user->fetch()) {
948 $twitter_user = $this->twitterUserArray($user);
949 $this->showTwitterXmlUser($twitter_user);
953 $this->elementEnd('users');
954 $this->endDocument('xml');
957 function showJsonUsers($user)
960 $this->initDocument('json');
964 if (is_array($user)) {
965 foreach ($user as $u) {
966 $twitter_user = $this->twitterUserArray($u);
967 array_push($users, $twitter_user);
970 while ($user->fetch()) {
971 $twitter_user = $this->twitterUserArray($user);
972 array_push($users, $twitter_user);
976 $this->showJsonObjects($users);
978 $this->endDocument('json');
981 function showSingleJsonGroup($group)
983 $this->initDocument('json');
984 $twitter_group = $this->twitterGroupArray($group);
985 $this->showJsonObjects($twitter_group);
986 $this->endDocument('json');
989 function showSingleXmlGroup($group)
991 $this->initDocument('xml');
992 $twitter_group = $this->twitterGroupArray($group);
993 $this->showTwitterXmlGroup($twitter_group);
994 $this->endDocument('xml');
997 function dateTwitter($dt)
999 $dateStr = date('d F Y H:i:s', strtotime($dt));
1000 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1001 $d->setTimezone(new DateTimeZone(common_timezone()));
1002 return $d->format('D M d H:i:s O Y');
1005 function initDocument($type='xml')
1009 header('Content-Type: application/xml; charset=utf-8');
1013 header('Content-Type: application/json; charset=utf-8');
1015 // Check for JSONP callback
1016 $callback = $this->arg('callback');
1018 print $callback . '(';
1022 header("Content-Type: application/rss+xml; charset=utf-8");
1023 $this->initTwitterRss();
1026 header('Content-Type: application/atom+xml; charset=utf-8');
1027 $this->initTwitterAtom();
1030 $this->clientError(_('Not a supported data format.'));
1037 function endDocument($type='xml')
1045 // Check for JSONP callback
1046 $callback = $this->arg('callback');
1052 $this->endTwitterRss();
1055 $this->endTwitterRss();
1058 $this->clientError(_('Not a supported data format.'));
1064 function clientError($msg, $code = 400, $format = 'xml')
1066 $action = $this->trimmed('action');
1068 common_debug("User error '$code' on '$action': $msg", __FILE__);
1070 if (!array_key_exists($code, ClientErrorAction::$status)) {
1074 $status_string = ClientErrorAction::$status[$code];
1076 header('HTTP/1.1 '.$code.' '.$status_string);
1078 if ($format == 'xml') {
1079 $this->initDocument('xml');
1080 $this->elementStart('hash');
1081 $this->element('error', null, $msg);
1082 $this->element('request', null, $_SERVER['REQUEST_URI']);
1083 $this->elementEnd('hash');
1084 $this->endDocument('xml');
1085 } elseif ($format == 'json'){
1086 $this->initDocument('json');
1087 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1088 print(json_encode($error_array));
1089 $this->endDocument('json');
1092 // If user didn't request a useful format, throw a regular client error
1093 throw new ClientException($msg, $code);
1097 function serverError($msg, $code = 500, $content_type = 'json')
1099 $action = $this->trimmed('action');
1101 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1103 if (!array_key_exists($code, ServerErrorAction::$status)) {
1107 $status_string = ServerErrorAction::$status[$code];
1109 header('HTTP/1.1 '.$code.' '.$status_string);
1111 if ($content_type == 'xml') {
1112 $this->initDocument('xml');
1113 $this->elementStart('hash');
1114 $this->element('error', null, $msg);
1115 $this->element('request', null, $_SERVER['REQUEST_URI']);
1116 $this->elementEnd('hash');
1117 $this->endDocument('xml');
1119 $this->initDocument('json');
1120 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1121 print(json_encode($error_array));
1122 $this->endDocument('json');
1126 function initTwitterRss()
1129 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1130 $this->elementStart('channel');
1131 Event::handle('StartApiRss', array($this));
1134 function endTwitterRss()
1136 $this->elementEnd('channel');
1137 $this->elementEnd('rss');
1141 function initTwitterAtom()
1144 // FIXME: don't hardcode the language here!
1145 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1146 'xml:lang' => 'en-US',
1147 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1148 Event::handle('StartApiAtom', array($this));
1151 function endTwitterAtom()
1153 $this->elementEnd('feed');
1157 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1159 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1160 switch ($content_type) {
1162 $this->showTwitterXmlUser($profile_array);
1165 $this->showJsonObjects($profile_array);
1168 $this->clientError(_('Not a supported data format.'));
1174 function getTargetUser($id)
1178 // Twitter supports these other ways of passing the user ID
1179 if (is_numeric($this->arg('id'))) {
1180 return User::staticGet($this->arg('id'));
1181 } else if ($this->arg('id')) {
1182 $nickname = common_canonical_nickname($this->arg('id'));
1183 return User::staticGet('nickname', $nickname);
1184 } else if ($this->arg('user_id')) {
1185 // This is to ensure that a non-numeric user_id still
1186 // overrides screen_name even if it doesn't get used
1187 if (is_numeric($this->arg('user_id'))) {
1188 return User::staticGet('id', $this->arg('user_id'));
1190 } else if ($this->arg('screen_name')) {
1191 $nickname = common_canonical_nickname($this->arg('screen_name'));
1192 return User::staticGet('nickname', $nickname);
1194 // Fall back to trying the currently authenticated user
1195 return $this->auth_user;
1198 } else if (is_numeric($id)) {
1199 return User::staticGet($id);
1201 $nickname = common_canonical_nickname($id);
1202 return User::staticGet('nickname', $nickname);
1206 function getTargetGroup($id)
1209 if (is_numeric($this->arg('id'))) {
1210 return User_group::staticGet($this->arg('id'));
1211 } else if ($this->arg('id')) {
1212 $nickname = common_canonical_nickname($this->arg('id'));
1213 return User_group::staticGet('nickname', $nickname);
1214 } else if ($this->arg('group_id')) {
1215 // This is to ensure that a non-numeric user_id still
1216 // overrides screen_name even if it doesn't get used
1217 if (is_numeric($this->arg('group_id'))) {
1218 return User_group::staticGet('id', $this->arg('group_id'));
1220 } else if ($this->arg('group_name')) {
1221 $nickname = common_canonical_nickname($this->arg('group_name'));
1222 return User_group::staticGet('nickname', $nickname);
1225 } else if (is_numeric($id)) {
1226 return User_group::staticGet($id);
1228 $nickname = common_canonical_nickname($id);
1229 return User_group::staticGet('nickname', $nickname);
1233 function sourceLink($source)
1235 $source_name = _($source);
1244 $ns = Notice_source::staticGet($source);
1246 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1250 return $source_name;
1254 * Returns query argument or default value if not found. Certain
1255 * parameters used throughout the API are lightly scrubbed and
1256 * bounds checked. This overrides Action::arg().
1258 * @param string $key requested argument
1259 * @param string $def default value to return if $key is not provided
1263 function arg($key, $def=null)
1266 // XXX: Do even more input validation/scrubbing?
1268 if (array_key_exists($key, $this->args)) {
1271 $page = (int)$this->args['page'];
1272 return ($page < 1) ? 1 : $page;
1274 $count = (int)$this->args['count'];
1277 } elseif ($count > 200) {
1283 $since_id = (int)$this->args['since_id'];
1284 return ($since_id < 1) ? 0 : $since_id;
1286 $max_id = (int)$this->args['max_id'];
1287 return ($max_id < 1) ? 0 : $max_id;
1289 return strtotime($this->args['since']);
1291 return parent::arg($key, $def);