3 * StatusNet, the distributed open-source microblogging tool
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Dan Moore <dan@moore.cx>
26 * @author Evan Prodromou <evan@status.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Toby Inkster <mail@tobyinkster.co.uk>
29 * @author Zach Copley <zach@status.net>
30 * @copyright 2009 StatusNet, Inc.
31 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
32 * @link http://status.net/
35 if (!defined('STATUSNET')) {
40 * Contains most of the Twitter-compatible API output functions.
44 * @author Craig Andrews <candrews@integralblue.com>
45 * @author Dan Moore <dan@moore.cx>
46 * @author Evan Prodromou <evan@status.net>
47 * @author Jeffery To <jeffery.to@gmail.com>
48 * @author Toby Inkster <mail@tobyinkster.co.uk>
49 * @author Zach Copley <zach@status.net>
50 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51 * @link http://status.net/
54 class ApiAction extends Action
61 var $auth_user = null;
68 var $access = self::READ_ONLY; // read (default) or read-write
73 * @param array $args Web and URL arguments
75 * @return boolean false if user doesn't exist
78 function prepare($args)
80 StatusNet::setApi(true); // reduce exception reports to aid in debugging
81 parent::prepare($args);
83 $this->format = $this->arg('format');
84 $this->page = (int)$this->arg('page', 1);
85 $this->count = (int)$this->arg('count', 20);
86 $this->max_id = (int)$this->arg('max_id', 0);
87 $this->since_id = (int)$this->arg('since_id', 0);
88 $this->since = $this->arg('since');
96 * @param array $args Arguments from $_REQUEST
101 function handle($args)
103 parent::handle($args);
107 * Overrides XMLOutputter::element to write booleans as strings (true|false).
108 * See that method's documentation for more info.
110 * @param string $tag Element type or tagname
111 * @param array $attrs Array of element attributes, as
113 * @param string $content string content of the element
117 function element($tag, $attrs=null, $content=null)
119 if (is_bool($content)) {
120 $content = ($content ? 'true' : 'false');
123 return parent::element($tag, $attrs, $content);
126 function twitterUserArray($profile, $get_notice=false)
128 $twitter_user = array();
130 $twitter_user['id'] = intval($profile->id);
131 $twitter_user['name'] = $profile->getBestName();
132 $twitter_user['screen_name'] = $profile->nickname;
133 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
134 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
136 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
137 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
138 Avatar::defaultImage(AVATAR_STREAM_SIZE);
140 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
141 $twitter_user['protected'] = false; # not supported by StatusNet yet
142 $twitter_user['followers_count'] = $profile->subscriberCount();
145 $user = $profile->getUser();
147 // Note: some profiles don't have an associated user
149 $defaultDesign = Design::siteDesign();
152 $design = $user->getDesign();
155 if (empty($design)) {
156 $design = $defaultDesign;
159 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
160 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
161 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
162 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
163 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
164 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
165 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
166 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
167 $twitter_user['profile_sidebar_border_color'] = '';
169 $twitter_user['friends_count'] = $profile->subscriptionCount();
171 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
173 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
177 if (!empty($user) && $user->timezone) {
178 $timezone = $user->timezone;
182 $t->setTimezone(new DateTimeZone($timezone));
184 $twitter_user['utc_offset'] = $t->format('Z');
185 $twitter_user['time_zone'] = $timezone;
187 $twitter_user['profile_background_image_url']
188 = empty($design->backgroundimage)
189 ? '' : ($design->disposition & BACKGROUND_ON)
190 ? Design::url($design->backgroundimage) : '';
192 $twitter_user['profile_background_tile']
193 = empty($design->disposition)
194 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
196 $twitter_user['statuses_count'] = $profile->noticeCount();
198 // Is the requesting user following this user?
199 $twitter_user['following'] = false;
200 $twitter_user['notifications'] = false;
202 if (isset($this->auth_user)) {
204 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
207 $sub = Subscription::pkeyGet(array('subscriber' =>
208 $this->auth_user->id,
209 'subscribed' => $profile->id));
212 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
217 $notice = $profile->getCurrentNotice();
220 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
224 return $twitter_user;
227 function twitterStatusArray($notice, $include_user=true)
229 $base = $this->twitterSimpleStatusArray($notice, $include_user);
231 if (!empty($notice->repeat_of)) {
232 $original = Notice::staticGet('id', $notice->repeat_of);
233 if (!empty($original)) {
234 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
235 $base['retweeted_status'] = $original_array;
242 function twitterSimpleStatusArray($notice, $include_user=true)
244 $profile = $notice->getProfile();
246 $twitter_status = array();
247 $twitter_status['text'] = $notice->content;
248 $twitter_status['truncated'] = false; # Not possible on StatusNet
249 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
250 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
251 intval($notice->reply_to) : null;
252 $twitter_status['source'] = $this->sourceLink($notice->source);
253 $twitter_status['id'] = intval($notice->id);
255 $replier_profile = null;
257 if ($notice->reply_to) {
258 $reply = Notice::staticGet(intval($notice->reply_to));
260 $replier_profile = $reply->getProfile();
264 $twitter_status['in_reply_to_user_id'] =
265 ($replier_profile) ? intval($replier_profile->id) : null;
266 $twitter_status['in_reply_to_screen_name'] =
267 ($replier_profile) ? $replier_profile->nickname : null;
269 if (isset($notice->lat) && isset($notice->lon)) {
270 // This is the format that GeoJSON expects stuff to be in
271 $twitter_status['geo'] = array('type' => 'Point',
272 'coordinates' => array((float) $notice->lat,
273 (float) $notice->lon));
275 $twitter_status['geo'] = null;
278 if (isset($this->auth_user)) {
279 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
281 $twitter_status['favorited'] = false;
285 $attachments = $notice->attachments();
287 if (!empty($attachments)) {
289 $twitter_status['attachments'] = array();
291 foreach ($attachments as $attachment) {
292 if ($attachment->isEnclosure()) {
293 $enclosure = array();
294 $enclosure['url'] = $attachment->url;
295 $enclosure['mimetype'] = $attachment->mimetype;
296 $enclosure['size'] = $attachment->size;
297 $twitter_status['attachments'][] = $enclosure;
302 if ($include_user && $profile) {
303 # Don't get notice (recursive!)
304 $twitter_user = $this->twitterUserArray($profile, false);
305 $twitter_status['user'] = $twitter_user;
308 return $twitter_status;
311 function twitterGroupArray($group)
313 $twitter_group=array();
314 $twitter_group['id']=$group->id;
315 $twitter_group['url']=$group->permalink();
316 $twitter_group['nickname']=$group->nickname;
317 $twitter_group['fullname']=$group->fullname;
318 $twitter_group['homepage_url']=$group->homepage_url;
319 $twitter_group['original_logo']=$group->original_logo;
320 $twitter_group['homepage_logo']=$group->homepage_logo;
321 $twitter_group['stream_logo']=$group->stream_logo;
322 $twitter_group['mini_logo']=$group->mini_logo;
323 $twitter_group['homepage']=$group->homepage;
324 $twitter_group['description']=$group->description;
325 $twitter_group['location']=$group->location;
326 $twitter_group['created']=$this->dateTwitter($group->created);
327 $twitter_group['modified']=$this->dateTwitter($group->modified);
328 return $twitter_group;
331 function twitterRssGroupArray($group)
334 $entry['content']=$group->description;
335 $entry['title']=$group->nickname;
336 $entry['link']=$group->permalink();
337 $entry['published']=common_date_iso8601($group->created);
338 $entry['updated']==common_date_iso8601($group->modified);
339 $taguribase = common_config('integration', 'groupuri');
340 $entry['id'] = "group:$groupuribase:$entry[link]";
342 $entry['description'] = $entry['content'];
343 $entry['pubDate'] = common_date_rfc2822($group->created);
344 $entry['guid'] = $entry['link'];
349 function twitterRssEntryArray($notice)
351 $profile = $notice->getProfile();
354 // We trim() to avoid extraneous whitespace in the output
356 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
357 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
358 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
359 $entry['published'] = common_date_iso8601($notice->created);
361 $taguribase = TagURI::base();
362 $entry['id'] = "tag:$taguribase:$entry[link]";
364 $entry['updated'] = $entry['published'];
365 $entry['author'] = $profile->getBestName();
368 $attachments = $notice->attachments();
369 $enclosures = array();
371 foreach ($attachments as $attachment) {
372 $enclosure_o=$attachment->getEnclosure();
374 $enclosure = array();
375 $enclosure['url'] = $enclosure_o->url;
376 $enclosure['mimetype'] = $enclosure_o->mimetype;
377 $enclosure['size'] = $enclosure_o->size;
378 $enclosures[] = $enclosure;
382 if (!empty($enclosures)) {
383 $entry['enclosures'] = $enclosures;
387 $tag = new Notice_tag();
388 $tag->notice_id = $notice->id;
390 $entry['tags']=array();
391 while ($tag->fetch()) {
392 $entry['tags'][]=$tag->tag;
398 $entry['description'] = $entry['content'];
399 $entry['pubDate'] = common_date_rfc2822($notice->created);
400 $entry['guid'] = $entry['link'];
402 if (isset($notice->lat) && isset($notice->lon)) {
403 // This is the format that GeoJSON expects stuff to be in.
404 // showGeoRSS() below uses it for XML output, so we reuse it
405 $entry['geo'] = array('type' => 'Point',
406 'coordinates' => array((float) $notice->lat,
407 (float) $notice->lon));
409 $entry['geo'] = null;
415 function twitterRelationshipArray($source, $target)
417 $relationship = array();
419 $relationship['source'] =
420 $this->relationshipDetailsArray($source, $target);
421 $relationship['target'] =
422 $this->relationshipDetailsArray($target, $source);
424 return array('relationship' => $relationship);
427 function relationshipDetailsArray($source, $target)
431 $details['screen_name'] = $source->nickname;
432 $details['followed_by'] = $target->isSubscribed($source);
433 $details['following'] = $source->isSubscribed($target);
435 $notifications = false;
437 if ($source->isSubscribed($target)) {
439 $sub = Subscription::pkeyGet(array('subscriber' =>
440 $source->id, 'subscribed' => $target->id));
443 $notifications = ($sub->jabber || $sub->sms);
447 $details['notifications_enabled'] = $notifications;
448 $details['blocking'] = $source->hasBlocked($target);
449 $details['id'] = $source->id;
454 function showTwitterXmlRelationship($relationship)
456 $this->elementStart('relationship');
458 foreach($relationship as $element => $value) {
459 if ($element == 'source' || $element == 'target') {
460 $this->elementStart($element);
461 $this->showXmlRelationshipDetails($value);
462 $this->elementEnd($element);
466 $this->elementEnd('relationship');
469 function showXmlRelationshipDetails($details)
471 foreach($details as $element => $value) {
472 $this->element($element, null, $value);
476 function showTwitterXmlStatus($twitter_status, $tag='status')
478 $this->elementStart($tag);
479 foreach($twitter_status as $element => $value) {
482 $this->showTwitterXmlUser($twitter_status['user']);
485 $this->element($element, null, common_xml_safe_str($value));
488 $this->showXmlAttachments($twitter_status['attachments']);
491 $this->showGeoRSS($value);
493 case 'retweeted_status':
494 $this->showTwitterXmlStatus($value, 'retweeted_status');
497 $this->element($element, null, $value);
500 $this->elementEnd($tag);
503 function showTwitterXmlGroup($twitter_group)
505 $this->elementStart('group');
506 foreach($twitter_group as $element => $value) {
507 $this->element($element, null, $value);
509 $this->elementEnd('group');
512 function showTwitterXmlUser($twitter_user, $role='user')
514 $this->elementStart($role);
515 foreach($twitter_user as $element => $value) {
516 if ($element == 'status') {
517 $this->showTwitterXmlStatus($twitter_user['status']);
519 $this->element($element, null, $value);
522 $this->elementEnd($role);
525 function showXmlAttachments($attachments) {
526 if (!empty($attachments)) {
527 $this->elementStart('attachments', array('type' => 'array'));
528 foreach ($attachments as $attachment) {
530 $attrs['url'] = $attachment['url'];
531 $attrs['mimetype'] = $attachment['mimetype'];
532 $attrs['size'] = $attachment['size'];
533 $this->element('enclosure', $attrs, '');
535 $this->elementEnd('attachments');
539 function showGeoRSS($geo)
543 $this->element('geo');
545 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
546 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
547 $this->elementEnd('geo');
551 function showTwitterRssItem($entry)
553 $this->elementStart('item');
554 $this->element('title', null, $entry['title']);
555 $this->element('description', null, $entry['description']);
556 $this->element('pubDate', null, $entry['pubDate']);
557 $this->element('guid', null, $entry['guid']);
558 $this->element('link', null, $entry['link']);
560 # RSS only supports 1 enclosure per item
561 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
562 $enclosure = $entry['enclosures'][0];
563 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
566 if(array_key_exists('tags', $entry)){
567 foreach($entry['tags'] as $tag){
568 $this->element('category', null,$tag);
572 $this->showGeoRSS($entry['geo']);
573 $this->elementEnd('item');
576 function showJsonObjects($objects)
578 print(json_encode($objects));
581 function showSingleXmlStatus($notice)
583 $this->initDocument('xml');
584 $twitter_status = $this->twitterStatusArray($notice);
585 $this->showTwitterXmlStatus($twitter_status);
586 $this->endDocument('xml');
589 function show_single_json_status($notice)
591 $this->initDocument('json');
592 $status = $this->twitterStatusArray($notice);
593 $this->showJsonObjects($status);
594 $this->endDocument('json');
597 function showXmlTimeline($notice)
600 $this->initDocument('xml');
601 $this->elementStart('statuses', array('type' => 'array'));
603 if (is_array($notice)) {
604 foreach ($notice as $n) {
605 $twitter_status = $this->twitterStatusArray($n);
606 $this->showTwitterXmlStatus($twitter_status);
609 while ($notice->fetch()) {
610 $twitter_status = $this->twitterStatusArray($notice);
611 $this->showTwitterXmlStatus($twitter_status);
615 $this->elementEnd('statuses');
616 $this->endDocument('xml');
619 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
622 $this->initDocument('rss');
624 $this->element('title', null, $title);
625 $this->element('link', null, $link);
626 if (!is_null($suplink)) {
627 // For FriendFeed's SUP protocol
628 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
629 'rel' => 'http://api.friendfeed.com/2008/03#sup',
631 'type' => 'application/json'));
634 if (!is_null($logo)) {
635 $this->elementStart('image');
636 $this->element('link', null, $link);
637 $this->element('title', null, $title);
638 $this->element('url', null, $logo);
639 $this->elementEnd('image');
642 $this->element('description', null, $subtitle);
643 $this->element('language', null, 'en-us');
644 $this->element('ttl', null, '40');
646 if (is_array($notice)) {
647 foreach ($notice as $n) {
648 $entry = $this->twitterRssEntryArray($n);
649 $this->showTwitterRssItem($entry);
652 while ($notice->fetch()) {
653 $entry = $this->twitterRssEntryArray($notice);
654 $this->showTwitterRssItem($entry);
658 $this->endTwitterRss();
661 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
664 $this->initDocument('atom');
666 $this->element('title', null, $title);
667 $this->element('id', null, $id);
668 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
670 if (!is_null($logo)) {
671 $this->element('logo',null,$logo);
674 if (!is_null($suplink)) {
675 # For FriendFeed's SUP protocol
676 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
678 'type' => 'application/json'));
681 if (!is_null($selfuri)) {
682 $this->element('link', array('href' => $selfuri,
683 'rel' => 'self', 'type' => 'application/atom+xml'), null);
686 $this->element('updated', null, common_date_iso8601('now'));
687 $this->element('subtitle', null, $subtitle);
689 if (is_array($notice)) {
690 foreach ($notice as $n) {
691 $this->raw($n->asAtomEntry());
694 while ($notice->fetch()) {
695 $this->raw($notice->asAtomEntry());
699 $this->endDocument('atom');
703 function showRssGroups($group, $title, $link, $subtitle)
706 $this->initDocument('rss');
708 $this->element('title', null, $title);
709 $this->element('link', null, $link);
710 $this->element('description', null, $subtitle);
711 $this->element('language', null, 'en-us');
712 $this->element('ttl', null, '40');
714 if (is_array($group)) {
715 foreach ($group as $g) {
716 $twitter_group = $this->twitterRssGroupArray($g);
717 $this->showTwitterRssItem($twitter_group);
720 while ($group->fetch()) {
721 $twitter_group = $this->twitterRssGroupArray($group);
722 $this->showTwitterRssItem($twitter_group);
726 $this->endTwitterRss();
729 function showTwitterAtomEntry($entry)
731 $this->elementStart('entry');
732 $this->element('title', null, $entry['title']);
733 $this->element('content', array('type' => 'html'), $entry['content']);
734 $this->element('id', null, $entry['id']);
735 $this->element('published', null, $entry['published']);
736 $this->element('updated', null, $entry['updated']);
737 $this->element('link', array('type' => 'text/html',
738 'href' => $entry['link'],
739 'rel' => 'alternate'));
740 $this->element('link', array('type' => $entry['avatar-type'],
741 'href' => $entry['avatar'],
743 $this->elementStart('author');
745 $this->element('name', null, $entry['author-name']);
746 $this->element('uri', null, $entry['author-uri']);
748 $this->elementEnd('author');
749 $this->elementEnd('entry');
752 function showXmlDirectMessage($dm)
754 $this->elementStart('direct_message');
755 foreach($dm as $element => $value) {
759 $this->showTwitterXmlUser($value, $element);
762 $this->element($element, null, common_xml_safe_str($value));
765 $this->element($element, null, $value);
769 $this->elementEnd('direct_message');
772 function directMessageArray($message)
776 $from_profile = $message->getFrom();
777 $to_profile = $message->getTo();
779 $dmsg['id'] = $message->id;
780 $dmsg['sender_id'] = $message->from_profile;
781 $dmsg['text'] = trim($message->content);
782 $dmsg['recipient_id'] = $message->to_profile;
783 $dmsg['created_at'] = $this->dateTwitter($message->created);
784 $dmsg['sender_screen_name'] = $from_profile->nickname;
785 $dmsg['recipient_screen_name'] = $to_profile->nickname;
786 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
787 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
792 function rssDirectMessageArray($message)
796 $from = $message->getFrom();
798 $entry['title'] = sprintf('Message from %1$s to %2$s',
799 $from->nickname, $message->getTo()->nickname);
801 $entry['content'] = common_xml_safe_str($message->rendered);
802 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
803 $entry['published'] = common_date_iso8601($message->created);
805 $taguribase = TagURI::base();
807 $entry['id'] = "tag:$taguribase:$entry[link]";
808 $entry['updated'] = $entry['published'];
810 $entry['author-name'] = $from->getBestName();
811 $entry['author-uri'] = $from->homepage;
813 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
815 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
816 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
820 $entry['description'] = $entry['content'];
821 $entry['pubDate'] = common_date_rfc2822($message->created);
822 $entry['guid'] = $entry['link'];
827 function showSingleXmlDirectMessage($message)
829 $this->initDocument('xml');
830 $dmsg = $this->directMessageArray($message);
831 $this->showXmlDirectMessage($dmsg);
832 $this->endDocument('xml');
835 function showSingleJsonDirectMessage($message)
837 $this->initDocument('json');
838 $dmsg = $this->directMessageArray($message);
839 $this->showJsonObjects($dmsg);
840 $this->endDocument('json');
843 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
846 $this->initDocument('atom');
848 $this->element('title', null, $title);
849 $this->element('id', null, $id);
850 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
852 if (!is_null($selfuri)) {
853 $this->element('link', array('href' => $selfuri,
854 'rel' => 'self', 'type' => 'application/atom+xml'), null);
857 $this->element('updated', null, common_date_iso8601('now'));
858 $this->element('subtitle', null, $subtitle);
860 if (is_array($group)) {
861 foreach ($group as $g) {
862 $this->raw($g->asAtomEntry());
865 while ($group->fetch()) {
866 $this->raw($group->asAtomEntry());
870 $this->endDocument('atom');
874 function showJsonTimeline($notice)
877 $this->initDocument('json');
881 if (is_array($notice)) {
882 foreach ($notice as $n) {
883 $twitter_status = $this->twitterStatusArray($n);
884 array_push($statuses, $twitter_status);
887 while ($notice->fetch()) {
888 $twitter_status = $this->twitterStatusArray($notice);
889 array_push($statuses, $twitter_status);
893 $this->showJsonObjects($statuses);
895 $this->endDocument('json');
898 function showJsonGroups($group)
901 $this->initDocument('json');
905 if (is_array($group)) {
906 foreach ($group as $g) {
907 $twitter_group = $this->twitterGroupArray($g);
908 array_push($groups, $twitter_group);
911 while ($group->fetch()) {
912 $twitter_group = $this->twitterGroupArray($group);
913 array_push($groups, $twitter_group);
917 $this->showJsonObjects($groups);
919 $this->endDocument('json');
922 function showXmlGroups($group)
925 $this->initDocument('xml');
926 $this->elementStart('groups', array('type' => 'array'));
928 if (is_array($group)) {
929 foreach ($group as $g) {
930 $twitter_group = $this->twitterGroupArray($g);
931 $this->showTwitterXmlGroup($twitter_group);
934 while ($group->fetch()) {
935 $twitter_group = $this->twitterGroupArray($group);
936 $this->showTwitterXmlGroup($twitter_group);
940 $this->elementEnd('groups');
941 $this->endDocument('xml');
944 function showTwitterXmlUsers($user)
947 $this->initDocument('xml');
948 $this->elementStart('users', array('type' => 'array'));
950 if (is_array($user)) {
951 foreach ($user as $u) {
952 $twitter_user = $this->twitterUserArray($u);
953 $this->showTwitterXmlUser($twitter_user);
956 while ($user->fetch()) {
957 $twitter_user = $this->twitterUserArray($user);
958 $this->showTwitterXmlUser($twitter_user);
962 $this->elementEnd('users');
963 $this->endDocument('xml');
966 function showJsonUsers($user)
969 $this->initDocument('json');
973 if (is_array($user)) {
974 foreach ($user as $u) {
975 $twitter_user = $this->twitterUserArray($u);
976 array_push($users, $twitter_user);
979 while ($user->fetch()) {
980 $twitter_user = $this->twitterUserArray($user);
981 array_push($users, $twitter_user);
985 $this->showJsonObjects($users);
987 $this->endDocument('json');
990 function showSingleJsonGroup($group)
992 $this->initDocument('json');
993 $twitter_group = $this->twitterGroupArray($group);
994 $this->showJsonObjects($twitter_group);
995 $this->endDocument('json');
998 function showSingleXmlGroup($group)
1000 $this->initDocument('xml');
1001 $twitter_group = $this->twitterGroupArray($group);
1002 $this->showTwitterXmlGroup($twitter_group);
1003 $this->endDocument('xml');
1006 function dateTwitter($dt)
1008 $dateStr = date('d F Y H:i:s', strtotime($dt));
1009 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1010 $d->setTimezone(new DateTimeZone(common_timezone()));
1011 return $d->format('D M d H:i:s O Y');
1014 function initDocument($type='xml')
1018 header('Content-Type: application/xml; charset=utf-8');
1022 header('Content-Type: application/json; charset=utf-8');
1024 // Check for JSONP callback
1025 $callback = $this->arg('callback');
1027 print $callback . '(';
1031 header("Content-Type: application/rss+xml; charset=utf-8");
1032 $this->initTwitterRss();
1035 header('Content-Type: application/atom+xml; charset=utf-8');
1036 $this->initTwitterAtom();
1039 $this->clientError(_('Not a supported data format.'));
1046 function endDocument($type='xml')
1054 // Check for JSONP callback
1055 $callback = $this->arg('callback');
1061 $this->endTwitterRss();
1064 $this->endTwitterRss();
1067 $this->clientError(_('Not a supported data format.'));
1073 function clientError($msg, $code = 400, $format = 'xml')
1075 $action = $this->trimmed('action');
1077 common_debug("User error '$code' on '$action': $msg", __FILE__);
1079 if (!array_key_exists($code, ClientErrorAction::$status)) {
1083 $status_string = ClientErrorAction::$status[$code];
1085 header('HTTP/1.1 '.$code.' '.$status_string);
1087 if ($format == 'xml') {
1088 $this->initDocument('xml');
1089 $this->elementStart('hash');
1090 $this->element('error', null, $msg);
1091 $this->element('request', null, $_SERVER['REQUEST_URI']);
1092 $this->elementEnd('hash');
1093 $this->endDocument('xml');
1094 } elseif ($format == 'json'){
1095 $this->initDocument('json');
1096 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1097 print(json_encode($error_array));
1098 $this->endDocument('json');
1101 // If user didn't request a useful format, throw a regular client error
1102 throw new ClientException($msg, $code);
1106 function serverError($msg, $code = 500, $content_type = 'xml')
1108 $action = $this->trimmed('action');
1110 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1112 if (!array_key_exists($code, ServerErrorAction::$status)) {
1116 $status_string = ServerErrorAction::$status[$code];
1118 header('HTTP/1.1 '.$code.' '.$status_string);
1120 if ($content_type == 'xml') {
1121 $this->initDocument('xml');
1122 $this->elementStart('hash');
1123 $this->element('error', null, $msg);
1124 $this->element('request', null, $_SERVER['REQUEST_URI']);
1125 $this->elementEnd('hash');
1126 $this->endDocument('xml');
1128 $this->initDocument('json');
1129 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1130 print(json_encode($error_array));
1131 $this->endDocument('json');
1135 function initTwitterRss()
1138 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1139 $this->elementStart('channel');
1140 Event::handle('StartApiRss', array($this));
1143 function endTwitterRss()
1145 $this->elementEnd('channel');
1146 $this->elementEnd('rss');
1150 function initTwitterAtom()
1153 // FIXME: don't hardcode the language here!
1154 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1155 'xml:lang' => 'en-US',
1156 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1159 function endTwitterAtom()
1161 $this->elementEnd('feed');
1165 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1167 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1168 switch ($content_type) {
1170 $this->showTwitterXmlUser($profile_array);
1173 $this->showJsonObjects($profile_array);
1176 $this->clientError(_('Not a supported data format.'));
1182 function getTargetUser($id)
1186 // Twitter supports these other ways of passing the user ID
1187 if (is_numeric($this->arg('id'))) {
1188 return User::staticGet($this->arg('id'));
1189 } else if ($this->arg('id')) {
1190 $nickname = common_canonical_nickname($this->arg('id'));
1191 return User::staticGet('nickname', $nickname);
1192 } else if ($this->arg('user_id')) {
1193 // This is to ensure that a non-numeric user_id still
1194 // overrides screen_name even if it doesn't get used
1195 if (is_numeric($this->arg('user_id'))) {
1196 return User::staticGet('id', $this->arg('user_id'));
1198 } else if ($this->arg('screen_name')) {
1199 $nickname = common_canonical_nickname($this->arg('screen_name'));
1200 return User::staticGet('nickname', $nickname);
1202 // Fall back to trying the currently authenticated user
1203 return $this->auth_user;
1206 } else if (is_numeric($id)) {
1207 return User::staticGet($id);
1209 $nickname = common_canonical_nickname($id);
1210 return User::staticGet('nickname', $nickname);
1214 function getTargetGroup($id)
1217 if (is_numeric($this->arg('id'))) {
1218 return User_group::staticGet($this->arg('id'));
1219 } else if ($this->arg('id')) {
1220 $nickname = common_canonical_nickname($this->arg('id'));
1221 $local = Local_group::staticGet('nickname', $nickname);
1222 if (empty($local)) {
1225 return User_group::staticGet('id', $local->id);
1227 } else if ($this->arg('group_id')) {
1228 // This is to ensure that a non-numeric user_id still
1229 // overrides screen_name even if it doesn't get used
1230 if (is_numeric($this->arg('group_id'))) {
1231 return User_group::staticGet('id', $this->arg('group_id'));
1233 } else if ($this->arg('group_name')) {
1234 $nickname = common_canonical_nickname($this->arg('group_name'));
1235 $local = Local_group::staticGet('nickname', $nickname);
1236 if (empty($local)) {
1239 return User_group::staticGet('id', $local->id);
1243 } else if (is_numeric($id)) {
1244 return User_group::staticGet($id);
1246 $nickname = common_canonical_nickname($id);
1247 $local = Local_group::staticGet('nickname', $nickname);
1248 if (empty($local)) {
1251 return User_group::staticGet('id', $local->id);
1256 function sourceLink($source)
1258 $source_name = _($source);
1271 $ns = Notice_source::staticGet($source);
1277 $app = Oauth_application::staticGet('name', $source);
1280 $url = $app->source_url;
1284 if (!empty($name) && !empty($url)) {
1285 $source_name = '<a href="' . $url . '">' . $name . '</a>';
1290 return $source_name;
1294 * Returns query argument or default value if not found. Certain
1295 * parameters used throughout the API are lightly scrubbed and
1296 * bounds checked. This overrides Action::arg().
1298 * @param string $key requested argument
1299 * @param string $def default value to return if $key is not provided
1303 function arg($key, $def=null)
1306 // XXX: Do even more input validation/scrubbing?
1308 if (array_key_exists($key, $this->args)) {
1311 $page = (int)$this->args['page'];
1312 return ($page < 1) ? 1 : $page;
1314 $count = (int)$this->args['count'];
1317 } elseif ($count > 200) {
1323 $since_id = (int)$this->args['since_id'];
1324 return ($since_id < 1) ? 0 : $since_id;
1326 $max_id = (int)$this->args['max_id'];
1327 return ($max_id < 1) ? 0 : $max_id;
1329 return strtotime($this->args['since']);
1331 return parent::arg($key, $def);
1338 function getSelfUri($action, $aargs)
1340 parse_str($_SERVER['QUERY_STRING'], $params);
1342 if (!empty($params)) {
1343 unset($params['p']);
1344 $pstring = http_build_query($params);
1347 $uri = common_local_url($action, $aargs);
1349 if (!empty($pstring)) {
1350 $uri .= '?' . $pstring;