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 if (empty($original)) {
230 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
231 $original_array['retweeted_status'] = $base;
232 return $original_array;
237 function twitterSimpleStatusArray($notice, $include_user=true)
239 $profile = $notice->getProfile();
241 $twitter_status = array();
242 $twitter_status['text'] = $notice->content;
243 $twitter_status['truncated'] = false; # Not possible on StatusNet
244 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
245 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
246 intval($notice->reply_to) : null;
247 $twitter_status['source'] = $this->sourceLink($notice->source);
248 $twitter_status['id'] = intval($notice->id);
250 $replier_profile = null;
252 if ($notice->reply_to) {
253 $reply = Notice::staticGet(intval($notice->reply_to));
255 $replier_profile = $reply->getProfile();
259 $twitter_status['in_reply_to_user_id'] =
260 ($replier_profile) ? intval($replier_profile->id) : null;
261 $twitter_status['in_reply_to_screen_name'] =
262 ($replier_profile) ? $replier_profile->nickname : null;
264 if (isset($notice->lat) && isset($notice->lon)) {
265 // This is the format that GeoJSON expects stuff to be in
266 $twitter_status['geo'] = array('type' => 'Point',
267 'coordinates' => array((float) $notice->lat,
268 (float) $notice->lon));
270 $twitter_status['geo'] = null;
273 if (isset($this->auth_user)) {
274 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
276 $twitter_status['favorited'] = false;
280 $attachments = $notice->attachments();
282 if (!empty($attachments)) {
284 $twitter_status['attachments'] = array();
286 foreach ($attachments as $attachment) {
287 if ($attachment->isEnclosure()) {
288 $enclosure = array();
289 $enclosure['url'] = $attachment->url;
290 $enclosure['mimetype'] = $attachment->mimetype;
291 $enclosure['size'] = $attachment->size;
292 $twitter_status['attachments'][] = $enclosure;
298 # Don't get notice (recursive!)
299 $twitter_user = $this->twitterUserArray($profile, false);
300 $twitter_status['user'] = $twitter_user;
303 return $twitter_status;
306 function twitterGroupArray($group)
308 $twitter_group=array();
309 $twitter_group['id']=$group->id;
310 $twitter_group['url']=$group->permalink();
311 $twitter_group['nickname']=$group->nickname;
312 $twitter_group['fullname']=$group->fullname;
313 $twitter_group['homepage_url']=$group->homepage_url;
314 $twitter_group['original_logo']=$group->original_logo;
315 $twitter_group['homepage_logo']=$group->homepage_logo;
316 $twitter_group['stream_logo']=$group->stream_logo;
317 $twitter_group['mini_logo']=$group->mini_logo;
318 $twitter_group['homepage']=$group->homepage;
319 $twitter_group['description']=$group->description;
320 $twitter_group['location']=$group->location;
321 $twitter_group['created']=$this->dateTwitter($group->created);
322 $twitter_group['modified']=$this->dateTwitter($group->modified);
323 return $twitter_group;
326 function twitterRssGroupArray($group)
329 $entry['content']=$group->description;
330 $entry['title']=$group->nickname;
331 $entry['link']=$group->permalink();
332 $entry['published']=common_date_iso8601($group->created);
333 $entry['updated']==common_date_iso8601($group->modified);
334 $taguribase = common_config('integration', 'groupuri');
335 $entry['id'] = "group:$groupuribase:$entry[link]";
337 $entry['description'] = $entry['content'];
338 $entry['pubDate'] = common_date_rfc2822($group->created);
339 $entry['guid'] = $entry['link'];
344 function twitterRssEntryArray($notice)
346 $profile = $notice->getProfile();
349 // We trim() to avoid extraneous whitespace in the output
351 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
352 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
353 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
354 $entry['published'] = common_date_iso8601($notice->created);
356 $taguribase = common_config('integration', 'taguri');
357 $entry['id'] = "tag:$taguribase:$entry[link]";
359 $entry['updated'] = $entry['published'];
360 $entry['author'] = $profile->getBestName();
363 $attachments = $notice->attachments();
364 $enclosures = array();
366 foreach ($attachments as $attachment) {
367 $enclosure_o=$attachment->getEnclosure();
369 $enclosure = array();
370 $enclosure['url'] = $enclosure_o->url;
371 $enclosure['mimetype'] = $enclosure_o->mimetype;
372 $enclosure['size'] = $enclosure_o->size;
373 $enclosures[] = $enclosure;
377 if (!empty($enclosures)) {
378 $entry['enclosures'] = $enclosures;
382 $tag = new Notice_tag();
383 $tag->notice_id = $notice->id;
385 $entry['tags']=array();
386 while ($tag->fetch()) {
387 $entry['tags'][]=$tag->tag;
393 $entry['description'] = $entry['content'];
394 $entry['pubDate'] = common_date_rfc2822($notice->created);
395 $entry['guid'] = $entry['link'];
397 if (isset($notice->lat) && isset($notice->lon)) {
398 // This is the format that GeoJSON expects stuff to be in.
399 // showGeoRSS() below uses it for XML output, so we reuse it
400 $entry['geo'] = array('type' => 'Point',
401 'coordinates' => array((float) $notice->lat,
402 (float) $notice->lon));
404 $entry['geo'] = null;
410 function twitterRelationshipArray($source, $target)
412 $relationship = array();
414 $relationship['source'] =
415 $this->relationshipDetailsArray($source, $target);
416 $relationship['target'] =
417 $this->relationshipDetailsArray($target, $source);
419 return array('relationship' => $relationship);
422 function relationshipDetailsArray($source, $target)
426 $details['screen_name'] = $source->nickname;
427 $details['followed_by'] = $target->isSubscribed($source);
428 $details['following'] = $source->isSubscribed($target);
430 $notifications = false;
432 if ($source->isSubscribed($target)) {
434 $sub = Subscription::pkeyGet(array('subscriber' =>
435 $source->id, 'subscribed' => $target->id));
438 $notifications = ($sub->jabber || $sub->sms);
442 $details['notifications_enabled'] = $notifications;
443 $details['blocking'] = $source->hasBlocked($target);
444 $details['id'] = $source->id;
449 function showTwitterXmlRelationship($relationship)
451 $this->elementStart('relationship');
453 foreach($relationship as $element => $value) {
454 if ($element == 'source' || $element == 'target') {
455 $this->elementStart($element);
456 $this->showXmlRelationshipDetails($value);
457 $this->elementEnd($element);
461 $this->elementEnd('relationship');
464 function showXmlRelationshipDetails($details)
466 foreach($details as $element => $value) {
467 $this->element($element, null, $value);
471 function showTwitterXmlStatus($twitter_status, $tag='status')
473 $this->elementStart($tag);
474 foreach($twitter_status as $element => $value) {
477 $this->showTwitterXmlUser($twitter_status['user']);
480 $this->element($element, null, common_xml_safe_str($value));
483 $this->showXmlAttachments($twitter_status['attachments']);
486 $this->showGeoRSS($value);
488 case 'retweeted_status':
489 $this->showTwitterXmlStatus($value, 'retweeted_status');
492 $this->element($element, null, $value);
495 $this->elementEnd($tag);
498 function showTwitterXmlGroup($twitter_group)
500 $this->elementStart('group');
501 foreach($twitter_group as $element => $value) {
502 $this->element($element, null, $value);
504 $this->elementEnd('group');
507 function showTwitterXmlUser($twitter_user, $role='user')
509 $this->elementStart($role);
510 foreach($twitter_user as $element => $value) {
511 if ($element == 'status') {
512 $this->showTwitterXmlStatus($twitter_user['status']);
514 $this->element($element, null, $value);
517 $this->elementEnd($role);
520 function showXmlAttachments($attachments) {
521 if (!empty($attachments)) {
522 $this->elementStart('attachments', array('type' => 'array'));
523 foreach ($attachments as $attachment) {
525 $attrs['url'] = $attachment['url'];
526 $attrs['mimetype'] = $attachment['mimetype'];
527 $attrs['size'] = $attachment['size'];
528 $this->element('enclosure', $attrs, '');
530 $this->elementEnd('attachments');
534 function showGeoRSS($geo)
538 $this->element('geo');
540 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
541 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
542 $this->elementEnd('geo');
546 function showTwitterRssItem($entry)
548 $this->elementStart('item');
549 $this->element('title', null, $entry['title']);
550 $this->element('description', null, $entry['description']);
551 $this->element('pubDate', null, $entry['pubDate']);
552 $this->element('guid', null, $entry['guid']);
553 $this->element('link', null, $entry['link']);
555 # RSS only supports 1 enclosure per item
556 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
557 $enclosure = $entry['enclosures'][0];
558 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
561 if(array_key_exists('tags', $entry)){
562 foreach($entry['tags'] as $tag){
563 $this->element('category', null,$tag);
567 $this->showGeoRSS($entry['geo']);
568 $this->elementEnd('item');
571 function showJsonObjects($objects)
573 print(json_encode($objects));
576 function showSingleXmlStatus($notice)
578 $this->initDocument('xml');
579 $twitter_status = $this->twitterStatusArray($notice);
580 $this->showTwitterXmlStatus($twitter_status);
581 $this->endDocument('xml');
584 function show_single_json_status($notice)
586 $this->initDocument('json');
587 $status = $this->twitterStatusArray($notice);
588 $this->showJsonObjects($status);
589 $this->endDocument('json');
592 function showXmlTimeline($notice)
595 $this->initDocument('xml');
596 $this->elementStart('statuses', array('type' => 'array'));
598 if (is_array($notice)) {
599 foreach ($notice as $n) {
600 $twitter_status = $this->twitterStatusArray($n);
601 $this->showTwitterXmlStatus($twitter_status);
604 while ($notice->fetch()) {
605 $twitter_status = $this->twitterStatusArray($notice);
606 $this->showTwitterXmlStatus($twitter_status);
610 $this->elementEnd('statuses');
611 $this->endDocument('xml');
614 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
617 $this->initDocument('rss');
619 $this->element('title', null, $title);
620 $this->element('link', null, $link);
621 if (!is_null($suplink)) {
622 // For FriendFeed's SUP protocol
623 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
624 'rel' => 'http://api.friendfeed.com/2008/03#sup',
626 'type' => 'application/json'));
629 if (!is_null($logo)) {
630 $this->elementStart('image');
631 $this->element('link', null, $link);
632 $this->element('title', null, $title);
633 $this->element('url', null, $logo);
634 $this->elementEnd('image');
637 $this->element('description', null, $subtitle);
638 $this->element('language', null, 'en-us');
639 $this->element('ttl', null, '40');
641 if (is_array($notice)) {
642 foreach ($notice as $n) {
643 $entry = $this->twitterRssEntryArray($n);
644 $this->showTwitterRssItem($entry);
647 while ($notice->fetch()) {
648 $entry = $this->twitterRssEntryArray($notice);
649 $this->showTwitterRssItem($entry);
653 $this->endTwitterRss();
656 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
659 $this->initDocument('atom');
661 $this->element('title', null, $title);
662 $this->element('id', null, $id);
663 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
665 if (!is_null($logo)) {
666 $this->element('logo',null,$logo);
669 if (!is_null($suplink)) {
670 # For FriendFeed's SUP protocol
671 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
673 'type' => 'application/json'));
676 if (!is_null($selfuri)) {
677 $this->element('link', array('href' => $selfuri,
678 'rel' => 'self', 'type' => 'application/atom+xml'), null);
681 $this->element('updated', null, common_date_iso8601('now'));
682 $this->element('subtitle', null, $subtitle);
684 if (is_array($notice)) {
685 foreach ($notice as $n) {
686 $this->raw($n->asAtomEntry());
689 while ($notice->fetch()) {
690 $this->raw($notice->asAtomEntry());
694 $this->endDocument('atom');
698 function showRssGroups($group, $title, $link, $subtitle)
701 $this->initDocument('rss');
703 $this->element('title', null, $title);
704 $this->element('link', null, $link);
705 $this->element('description', null, $subtitle);
706 $this->element('language', null, 'en-us');
707 $this->element('ttl', null, '40');
709 if (is_array($group)) {
710 foreach ($group as $g) {
711 $twitter_group = $this->twitterRssGroupArray($g);
712 $this->showTwitterRssItem($twitter_group);
715 while ($group->fetch()) {
716 $twitter_group = $this->twitterRssGroupArray($group);
717 $this->showTwitterRssItem($twitter_group);
721 $this->endTwitterRss();
724 function showTwitterAtomEntry($entry)
726 $this->elementStart('entry');
727 $this->element('title', null, $entry['title']);
728 $this->element('content', array('type' => 'html'), $entry['content']);
729 $this->element('id', null, $entry['id']);
730 $this->element('published', null, $entry['published']);
731 $this->element('updated', null, $entry['updated']);
732 $this->element('link', array('type' => 'text/html',
733 'href' => $entry['link'],
734 'rel' => 'alternate'));
735 $this->element('link', array('type' => $entry['avatar-type'],
736 'href' => $entry['avatar'],
738 $this->elementStart('author');
740 $this->element('name', null, $entry['author-name']);
741 $this->element('uri', null, $entry['author-uri']);
743 $this->elementEnd('author');
744 $this->elementEnd('entry');
747 function showXmlDirectMessage($dm)
749 $this->elementStart('direct_message');
750 foreach($dm as $element => $value) {
754 $this->showTwitterXmlUser($value, $element);
757 $this->element($element, null, common_xml_safe_str($value));
760 $this->element($element, null, $value);
764 $this->elementEnd('direct_message');
767 function directMessageArray($message)
771 $from_profile = $message->getFrom();
772 $to_profile = $message->getTo();
774 $dmsg['id'] = $message->id;
775 $dmsg['sender_id'] = $message->from_profile;
776 $dmsg['text'] = trim($message->content);
777 $dmsg['recipient_id'] = $message->to_profile;
778 $dmsg['created_at'] = $this->dateTwitter($message->created);
779 $dmsg['sender_screen_name'] = $from_profile->nickname;
780 $dmsg['recipient_screen_name'] = $to_profile->nickname;
781 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
782 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
787 function rssDirectMessageArray($message)
791 $from = $message->getFrom();
793 $entry['title'] = sprintf('Message from %s to %s',
794 $from->nickname, $message->getTo()->nickname);
796 $entry['content'] = common_xml_safe_str($message->rendered);
797 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
798 $entry['published'] = common_date_iso8601($message->created);
800 $taguribase = common_config('integration', 'taguri');
802 $entry['id'] = "tag:$taguribase:$entry[link]";
803 $entry['updated'] = $entry['published'];
805 $entry['author-name'] = $from->getBestName();
806 $entry['author-uri'] = $from->homepage;
808 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
810 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
811 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
815 $entry['description'] = $entry['content'];
816 $entry['pubDate'] = common_date_rfc2822($message->created);
817 $entry['guid'] = $entry['link'];
822 function showSingleXmlDirectMessage($message)
824 $this->initDocument('xml');
825 $dmsg = $this->directMessageArray($message);
826 $this->showXmlDirectMessage($dmsg);
827 $this->endDocument('xml');
830 function showSingleJsonDirectMessage($message)
832 $this->initDocument('json');
833 $dmsg = $this->directMessageArray($message);
834 $this->showJsonObjects($dmsg);
835 $this->endDocument('json');
838 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
841 $this->initDocument('atom');
843 $this->element('title', null, $title);
844 $this->element('id', null, $id);
845 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
847 if (!is_null($selfuri)) {
848 $this->element('link', array('href' => $selfuri,
849 'rel' => 'self', 'type' => 'application/atom+xml'), null);
852 $this->element('updated', null, common_date_iso8601('now'));
853 $this->element('subtitle', null, $subtitle);
855 if (is_array($group)) {
856 foreach ($group as $g) {
857 $this->raw($g->asAtomEntry());
860 while ($group->fetch()) {
861 $this->raw($group->asAtomEntry());
865 $this->endDocument('atom');
869 function showJsonTimeline($notice)
872 $this->initDocument('json');
876 if (is_array($notice)) {
877 foreach ($notice as $n) {
878 $twitter_status = $this->twitterStatusArray($n);
879 array_push($statuses, $twitter_status);
882 while ($notice->fetch()) {
883 $twitter_status = $this->twitterStatusArray($notice);
884 array_push($statuses, $twitter_status);
888 $this->showJsonObjects($statuses);
890 $this->endDocument('json');
893 function showJsonGroups($group)
896 $this->initDocument('json');
900 if (is_array($group)) {
901 foreach ($group as $g) {
902 $twitter_group = $this->twitterGroupArray($g);
903 array_push($groups, $twitter_group);
906 while ($group->fetch()) {
907 $twitter_group = $this->twitterGroupArray($group);
908 array_push($groups, $twitter_group);
912 $this->showJsonObjects($groups);
914 $this->endDocument('json');
917 function showXmlGroups($group)
920 $this->initDocument('xml');
921 $this->elementStart('groups', array('type' => 'array'));
923 if (is_array($group)) {
924 foreach ($group as $g) {
925 $twitter_group = $this->twitterGroupArray($g);
926 $this->showTwitterXmlGroup($twitter_group);
929 while ($group->fetch()) {
930 $twitter_group = $this->twitterGroupArray($group);
931 $this->showTwitterXmlGroup($twitter_group);
935 $this->elementEnd('groups');
936 $this->endDocument('xml');
939 function showTwitterXmlUsers($user)
942 $this->initDocument('xml');
943 $this->elementStart('users', array('type' => 'array'));
945 if (is_array($user)) {
946 foreach ($user as $u) {
947 $twitter_user = $this->twitterUserArray($u);
948 $this->showTwitterXmlUser($twitter_user);
951 while ($user->fetch()) {
952 $twitter_user = $this->twitterUserArray($user);
953 $this->showTwitterXmlUser($twitter_user);
957 $this->elementEnd('users');
958 $this->endDocument('xml');
961 function showJsonUsers($user)
964 $this->initDocument('json');
968 if (is_array($user)) {
969 foreach ($user as $u) {
970 $twitter_user = $this->twitterUserArray($u);
971 array_push($users, $twitter_user);
974 while ($user->fetch()) {
975 $twitter_user = $this->twitterUserArray($user);
976 array_push($users, $twitter_user);
980 $this->showJsonObjects($users);
982 $this->endDocument('json');
985 function showSingleJsonGroup($group)
987 $this->initDocument('json');
988 $twitter_group = $this->twitterGroupArray($group);
989 $this->showJsonObjects($twitter_group);
990 $this->endDocument('json');
993 function showSingleXmlGroup($group)
995 $this->initDocument('xml');
996 $twitter_group = $this->twitterGroupArray($group);
997 $this->showTwitterXmlGroup($twitter_group);
998 $this->endDocument('xml');
1001 function dateTwitter($dt)
1003 $dateStr = date('d F Y H:i:s', strtotime($dt));
1004 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1005 $d->setTimezone(new DateTimeZone(common_timezone()));
1006 return $d->format('D M d H:i:s O Y');
1009 function initDocument($type='xml')
1013 header('Content-Type: application/xml; charset=utf-8');
1017 header('Content-Type: application/json; charset=utf-8');
1019 // Check for JSONP callback
1020 $callback = $this->arg('callback');
1022 print $callback . '(';
1026 header("Content-Type: application/rss+xml; charset=utf-8");
1027 $this->initTwitterRss();
1030 header('Content-Type: application/atom+xml; charset=utf-8');
1031 $this->initTwitterAtom();
1034 $this->clientError(_('Not a supported data format.'));
1041 function endDocument($type='xml')
1049 // Check for JSONP callback
1050 $callback = $this->arg('callback');
1056 $this->endTwitterRss();
1059 $this->endTwitterRss();
1062 $this->clientError(_('Not a supported data format.'));
1068 function clientError($msg, $code = 400, $format = 'xml')
1070 $action = $this->trimmed('action');
1072 common_debug("User error '$code' on '$action': $msg", __FILE__);
1074 if (!array_key_exists($code, ClientErrorAction::$status)) {
1078 $status_string = ClientErrorAction::$status[$code];
1080 header('HTTP/1.1 '.$code.' '.$status_string);
1082 if ($format == 'xml') {
1083 $this->initDocument('xml');
1084 $this->elementStart('hash');
1085 $this->element('error', null, $msg);
1086 $this->element('request', null, $_SERVER['REQUEST_URI']);
1087 $this->elementEnd('hash');
1088 $this->endDocument('xml');
1089 } elseif ($format == 'json'){
1090 $this->initDocument('json');
1091 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1092 print(json_encode($error_array));
1093 $this->endDocument('json');
1096 // If user didn't request a useful format, throw a regular client error
1097 throw new ClientException($msg, $code);
1101 function serverError($msg, $code = 500, $content_type = 'json')
1103 $action = $this->trimmed('action');
1105 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1107 if (!array_key_exists($code, ServerErrorAction::$status)) {
1111 $status_string = ServerErrorAction::$status[$code];
1113 header('HTTP/1.1 '.$code.' '.$status_string);
1115 if ($content_type == 'xml') {
1116 $this->initDocument('xml');
1117 $this->elementStart('hash');
1118 $this->element('error', null, $msg);
1119 $this->element('request', null, $_SERVER['REQUEST_URI']);
1120 $this->elementEnd('hash');
1121 $this->endDocument('xml');
1123 $this->initDocument('json');
1124 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1125 print(json_encode($error_array));
1126 $this->endDocument('json');
1130 function initTwitterRss()
1133 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1134 $this->elementStart('channel');
1135 Event::handle('StartApiRss', array($this));
1138 function endTwitterRss()
1140 $this->elementEnd('channel');
1141 $this->elementEnd('rss');
1145 function initTwitterAtom()
1148 // FIXME: don't hardcode the language here!
1149 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1150 'xml:lang' => 'en-US',
1151 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1152 Event::handle('StartApiAtom', array($this));
1155 function endTwitterAtom()
1157 $this->elementEnd('feed');
1161 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1163 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1164 switch ($content_type) {
1166 $this->showTwitterXmlUser($profile_array);
1169 $this->showJsonObjects($profile_array);
1172 $this->clientError(_('Not a supported data format.'));
1178 function getTargetUser($id)
1182 // Twitter supports these other ways of passing the user ID
1183 if (is_numeric($this->arg('id'))) {
1184 return User::staticGet($this->arg('id'));
1185 } else if ($this->arg('id')) {
1186 $nickname = common_canonical_nickname($this->arg('id'));
1187 return User::staticGet('nickname', $nickname);
1188 } else if ($this->arg('user_id')) {
1189 // This is to ensure that a non-numeric user_id still
1190 // overrides screen_name even if it doesn't get used
1191 if (is_numeric($this->arg('user_id'))) {
1192 return User::staticGet('id', $this->arg('user_id'));
1194 } else if ($this->arg('screen_name')) {
1195 $nickname = common_canonical_nickname($this->arg('screen_name'));
1196 return User::staticGet('nickname', $nickname);
1198 // Fall back to trying the currently authenticated user
1199 return $this->auth_user;
1202 } else if (is_numeric($id)) {
1203 return User::staticGet($id);
1205 $nickname = common_canonical_nickname($id);
1206 return User::staticGet('nickname', $nickname);
1210 function getTargetGroup($id)
1213 if (is_numeric($this->arg('id'))) {
1214 return User_group::staticGet($this->arg('id'));
1215 } else if ($this->arg('id')) {
1216 $nickname = common_canonical_nickname($this->arg('id'));
1217 return User_group::staticGet('nickname', $nickname);
1218 } else if ($this->arg('group_id')) {
1219 // This is to ensure that a non-numeric user_id still
1220 // overrides screen_name even if it doesn't get used
1221 if (is_numeric($this->arg('group_id'))) {
1222 return User_group::staticGet('id', $this->arg('group_id'));
1224 } else if ($this->arg('group_name')) {
1225 $nickname = common_canonical_nickname($this->arg('group_name'));
1226 return User_group::staticGet('nickname', $nickname);
1229 } else if (is_numeric($id)) {
1230 return User_group::staticGet($id);
1232 $nickname = common_canonical_nickname($id);
1233 return User_group::staticGet('nickname', $nickname);
1237 function sourceLink($source)
1239 $source_name = _($source);
1248 $ns = Notice_source::staticGet($source);
1250 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1254 return $source_name;
1258 * Returns query argument or default value if not found. Certain
1259 * parameters used throughout the API are lightly scrubbed and
1260 * bounds checked. This overrides Action::arg().
1262 * @param string $key requested argument
1263 * @param string $def default value to return if $key is not provided
1267 function arg($key, $def=null)
1270 // XXX: Do even more input validation/scrubbing?
1272 if (array_key_exists($key, $this->args)) {
1275 $page = (int)$this->args['page'];
1276 return ($page < 1) ? 1 : $page;
1278 $count = (int)$this->args['count'];
1281 } elseif ($count > 200) {
1287 $since_id = (int)$this->args['since_id'];
1288 return ($since_id < 1) ? 0 : $since_id;
1290 $max_id = (int)$this->args['max_id'];
1291 return ($max_id < 1) ? 0 : $max_id;
1293 return strtotime($this->args['since']);
1295 return parent::arg($key, $def);