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
67 * @param array $args Web and URL arguments
69 * @return boolean false if user doesn't exist
72 function prepare($args)
74 parent::prepare($args);
76 $this->format = $this->arg('format');
77 $this->page = (int)$this->arg('page', 1);
78 $this->count = (int)$this->arg('count', 20);
79 $this->max_id = (int)$this->arg('max_id', 0);
80 $this->since_id = (int)$this->arg('since_id', 0);
81 $this->since = $this->arg('since');
89 * @param array $args Arguments from $_REQUEST
94 function handle($args)
96 parent::handle($args);
100 * Overrides XMLOutputter::element to write booleans as strings (true|false).
101 * See that method's documentation for more info.
103 * @param string $tag Element type or tagname
104 * @param array $attrs Array of element attributes, as
106 * @param string $content string content of the element
110 function element($tag, $attrs=null, $content=null)
112 if (is_bool($content)) {
113 $content = ($content ? 'true' : 'false');
116 return parent::element($tag, $attrs, $content);
119 function twitterUserArray($profile, $get_notice=false)
121 $twitter_user = array();
123 $twitter_user['id'] = intval($profile->id);
124 $twitter_user['name'] = $profile->getBestName();
125 $twitter_user['screen_name'] = $profile->nickname;
126 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
127 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
129 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
130 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
131 Avatar::defaultImage(AVATAR_STREAM_SIZE);
133 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
134 $twitter_user['protected'] = false; # not supported by StatusNet yet
135 $twitter_user['followers_count'] = $profile->subscriberCount();
137 $defaultDesign = Design::siteDesign();
139 $user = $profile->getUser();
141 // Note: some profiles don't have an associated user
144 $design = $user->getDesign();
147 if (empty($design)) {
148 $design = $defaultDesign;
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($apidata['user'])) {
196 $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
199 $sub = Subscription::pkeyGet(array('subscriber' =>
200 $apidata['user']->id, 'subscribed' => $profile->id));
203 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
208 $notice = $profile->getCurrentNotice();
211 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
215 return $twitter_user;
218 function twitterStatusArray($notice, $include_user=true)
220 $profile = $notice->getProfile();
222 $twitter_status = array();
223 $twitter_status['text'] = $notice->content;
224 $twitter_status['truncated'] = false; # Not possible on StatusNet
225 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
226 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
227 intval($notice->reply_to) : null;
228 $twitter_status['source'] = $this->sourceLink($notice->source);
229 $twitter_status['id'] = intval($notice->id);
231 $replier_profile = null;
233 if ($notice->reply_to) {
234 $reply = Notice::staticGet(intval($notice->reply_to));
236 $replier_profile = $reply->getProfile();
240 $twitter_status['in_reply_to_user_id'] =
241 ($replier_profile) ? intval($replier_profile->id) : null;
242 $twitter_status['in_reply_to_screen_name'] =
243 ($replier_profile) ? $replier_profile->nickname : null;
245 if (isset($notice->lat) && isset($notice->lon)) {
246 // This is the format that GeoJSON expects stuff to be in
247 $twitter_status['geo'] = array('type' => 'Point',
248 'coordinates' => array((float) $notice->lat,
249 (float) $notice->lon));
251 $twitter_status['geo'] = null;
254 if (isset($this->auth_user)) {
255 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
257 $twitter_status['favorited'] = false;
261 $attachments = $notice->attachments();
263 if (!empty($attachments)) {
265 $twitter_status['attachments'] = array();
267 foreach ($attachments as $attachment) {
268 if ($attachment->isEnclosure()) {
269 $enclosure = array();
270 $enclosure['url'] = $attachment->url;
271 $enclosure['mimetype'] = $attachment->mimetype;
272 $enclosure['size'] = $attachment->size;
273 $twitter_status['attachments'][] = $enclosure;
279 # Don't get notice (recursive!)
280 $twitter_user = $this->twitterUserArray($profile, false);
281 $twitter_status['user'] = $twitter_user;
284 return $twitter_status;
287 function twitterGroupArray($group)
289 $twitter_group=array();
290 $twitter_group['id']=$group->id;
291 $twitter_group['url']=$group->permalink();
292 $twitter_group['nickname']=$group->nickname;
293 $twitter_group['fullname']=$group->fullname;
294 $twitter_group['homepage_url']=$group->homepage_url;
295 $twitter_group['original_logo']=$group->original_logo;
296 $twitter_group['homepage_logo']=$group->homepage_logo;
297 $twitter_group['stream_logo']=$group->stream_logo;
298 $twitter_group['mini_logo']=$group->mini_logo;
299 $twitter_group['homepage']=$group->homepage;
300 $twitter_group['description']=$group->description;
301 $twitter_group['location']=$group->location;
302 $twitter_group['created']=$this->dateTwitter($group->created);
303 $twitter_group['modified']=$this->dateTwitter($group->modified);
304 return $twitter_group;
307 function twitterRssGroupArray($group)
310 $entry['content']=$group->description;
311 $entry['title']=$group->nickname;
312 $entry['link']=$group->permalink();
313 $entry['published']=common_date_iso8601($group->created);
314 $entry['updated']==common_date_iso8601($group->modified);
315 $taguribase = common_config('integration', 'groupuri');
316 $entry['id'] = "group:$groupuribase:$entry[link]";
318 $entry['description'] = $entry['content'];
319 $entry['pubDate'] = common_date_rfc2822($group->created);
320 $entry['guid'] = $entry['link'];
325 function twitterRssEntryArray($notice)
327 $profile = $notice->getProfile();
330 // We trim() to avoid extraneous whitespace in the output
332 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
333 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
334 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
335 $entry['published'] = common_date_iso8601($notice->created);
337 $taguribase = common_config('integration', 'taguri');
338 $entry['id'] = "tag:$taguribase:$entry[link]";
340 $entry['updated'] = $entry['published'];
341 $entry['author'] = $profile->getBestName();
344 $attachments = $notice->attachments();
345 $enclosures = array();
347 foreach ($attachments as $attachment) {
348 $enclosure_o=$attachment->getEnclosure();
350 $enclosure = array();
351 $enclosure['url'] = $enclosure_o->url;
352 $enclosure['mimetype'] = $enclosure_o->mimetype;
353 $enclosure['size'] = $enclosure_o->size;
354 $enclosures[] = $enclosure;
358 if (!empty($enclosures)) {
359 $entry['enclosures'] = $enclosures;
363 $tag = new Notice_tag();
364 $tag->notice_id = $notice->id;
366 $entry['tags']=array();
367 while ($tag->fetch()) {
368 $entry['tags'][]=$tag->tag;
374 $entry['description'] = $entry['content'];
375 $entry['pubDate'] = common_date_rfc2822($notice->created);
376 $entry['guid'] = $entry['link'];
378 if (isset($notice->lat) && isset($notice->lon)) {
379 // This is the format that GeoJSON expects stuff to be in.
380 // showGeoRSS() below uses it for XML output, so we reuse it
381 $entry['geo'] = array('type' => 'Point',
382 'coordinates' => array((float) $notice->lat,
383 (float) $notice->lon));
385 $entry['geo'] = null;
391 function twitterRelationshipArray($source, $target)
393 $relationship = array();
395 $relationship['source'] =
396 $this->relationshipDetailsArray($source, $target);
397 $relationship['target'] =
398 $this->relationshipDetailsArray($target, $source);
400 return array('relationship' => $relationship);
403 function relationshipDetailsArray($source, $target)
407 $details['screen_name'] = $source->nickname;
408 $details['followed_by'] = $target->isSubscribed($source);
409 $details['following'] = $source->isSubscribed($target);
411 $notifications = false;
413 if ($source->isSubscribed($target)) {
415 $sub = Subscription::pkeyGet(array('subscriber' =>
416 $source->id, 'subscribed' => $target->id));
419 $notifications = ($sub->jabber || $sub->sms);
423 $details['notifications_enabled'] = $notifications;
424 $details['blocking'] = $source->hasBlocked($target);
425 $details['id'] = $source->id;
430 function showTwitterXmlRelationship($relationship)
432 $this->elementStart('relationship');
434 foreach($relationship as $element => $value) {
435 if ($element == 'source' || $element == 'target') {
436 $this->elementStart($element);
437 $this->showXmlRelationshipDetails($value);
438 $this->elementEnd($element);
442 $this->elementEnd('relationship');
445 function showXmlRelationshipDetails($details)
447 foreach($details as $element => $value) {
448 $this->element($element, null, $value);
452 function showTwitterXmlStatus($twitter_status)
454 $this->elementStart('status');
455 foreach($twitter_status as $element => $value) {
458 $this->showTwitterXmlUser($twitter_status['user']);
461 $this->element($element, null, common_xml_safe_str($value));
464 $this->showXmlAttachments($twitter_status['attachments']);
467 $this->showGeoRSS($value);
470 $this->element($element, null, $value);
473 $this->elementEnd('status');
476 function showTwitterXmlGroup($twitter_group)
478 $this->elementStart('group');
479 foreach($twitter_group as $element => $value) {
480 $this->element($element, null, $value);
482 $this->elementEnd('group');
485 function showTwitterXmlUser($twitter_user, $role='user')
487 $this->elementStart($role);
488 foreach($twitter_user as $element => $value) {
489 if ($element == 'status') {
490 $this->showTwitterXmlStatus($twitter_user['status']);
492 $this->element($element, null, $value);
495 $this->elementEnd($role);
498 function showXmlAttachments($attachments) {
499 if (!empty($attachments)) {
500 $this->elementStart('attachments', array('type' => 'array'));
501 foreach ($attachments as $attachment) {
503 $attrs['url'] = $attachment['url'];
504 $attrs['mimetype'] = $attachment['mimetype'];
505 $attrs['size'] = $attachment['size'];
506 $this->element('enclosure', $attrs, '');
508 $this->elementEnd('attachments');
512 function showGeoRSS($geo)
516 $this->element('geo');
518 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
519 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
520 $this->elementEnd('geo');
524 function showTwitterRssItem($entry)
526 $this->elementStart('item');
527 $this->element('title', null, $entry['title']);
528 $this->element('description', null, $entry['description']);
529 $this->element('pubDate', null, $entry['pubDate']);
530 $this->element('guid', null, $entry['guid']);
531 $this->element('link', null, $entry['link']);
533 # RSS only supports 1 enclosure per item
534 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
535 $enclosure = $entry['enclosures'][0];
536 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
539 if(array_key_exists('tags', $entry)){
540 foreach($entry['tags'] as $tag){
541 $this->element('category', null,$tag);
545 $this->showGeoRSS($entry['geo']);
546 $this->elementEnd('item');
549 function showJsonObjects($objects)
551 print(json_encode($objects));
554 function showSingleXmlStatus($notice)
556 $this->initDocument('xml');
557 $twitter_status = $this->twitterStatusArray($notice);
558 $this->showTwitterXmlStatus($twitter_status);
559 $this->endDocument('xml');
562 function show_single_json_status($notice)
564 $this->initDocument('json');
565 $status = $this->twitterStatusArray($notice);
566 $this->showJsonObjects($status);
567 $this->endDocument('json');
570 function showXmlTimeline($notice)
573 $this->initDocument('xml');
574 $this->elementStart('statuses', array('type' => 'array'));
576 if (is_array($notice)) {
577 foreach ($notice as $n) {
578 $twitter_status = $this->twitterStatusArray($n);
579 $this->showTwitterXmlStatus($twitter_status);
582 while ($notice->fetch()) {
583 $twitter_status = $this->twitterStatusArray($notice);
584 $this->showTwitterXmlStatus($twitter_status);
588 $this->elementEnd('statuses');
589 $this->endDocument('xml');
592 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null)
595 $this->initDocument('rss');
597 $this->element('title', null, $title);
598 $this->element('link', null, $link);
599 if (!is_null($suplink)) {
600 // For FriendFeed's SUP protocol
601 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
602 'rel' => 'http://api.friendfeed.com/2008/03#sup',
604 'type' => 'application/json'));
606 $this->element('description', null, $subtitle);
607 $this->element('language', null, 'en-us');
608 $this->element('ttl', null, '40');
610 if (is_array($notice)) {
611 foreach ($notice as $n) {
612 $entry = $this->twitterRssEntryArray($n);
613 $this->showTwitterRssItem($entry);
616 while ($notice->fetch()) {
617 $entry = $this->twitterRssEntryArray($notice);
618 $this->showTwitterRssItem($entry);
622 $this->endTwitterRss();
625 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
628 $this->initDocument('atom');
630 $this->element('title', null, $title);
631 $this->element('id', null, $id);
632 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
634 if (!is_null($suplink)) {
635 # For FriendFeed's SUP protocol
636 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
638 'type' => 'application/json'));
641 if (!is_null($selfuri)) {
642 $this->element('link', array('href' => $selfuri,
643 'rel' => 'self', 'type' => 'application/atom+xml'), null);
646 $this->element('updated', null, common_date_iso8601('now'));
647 $this->element('subtitle', null, $subtitle);
649 if (is_array($notice)) {
650 foreach ($notice as $n) {
651 $this->raw($n->asAtomEntry());
654 while ($notice->fetch()) {
655 $this->raw($notice->asAtomEntry());
659 $this->endDocument('atom');
663 function showRssGroups($group, $title, $link, $subtitle)
666 $this->initDocument('rss');
668 $this->element('title', null, $title);
669 $this->element('link', null, $link);
670 $this->element('description', null, $subtitle);
671 $this->element('language', null, 'en-us');
672 $this->element('ttl', null, '40');
674 if (is_array($group)) {
675 foreach ($group as $g) {
676 $twitter_group = $this->twitterRssGroupArray($g);
677 $this->showTwitterRssItem($twitter_group);
680 while ($group->fetch()) {
681 $twitter_group = $this->twitterRssGroupArray($group);
682 $this->showTwitterRssItem($twitter_group);
686 $this->endTwitterRss();
689 function showTwitterAtomEntry($entry)
691 $this->elementStart('entry');
692 $this->element('title', null, $entry['title']);
693 $this->element('content', array('type' => 'html'), $entry['content']);
694 $this->element('id', null, $entry['id']);
695 $this->element('published', null, $entry['published']);
696 $this->element('updated', null, $entry['updated']);
697 $this->element('link', array('type' => 'text/html',
698 'href' => $entry['link'],
699 'rel' => 'alternate'));
700 $this->element('link', array('type' => $entry['avatar-type'],
701 'href' => $entry['avatar'],
703 $this->elementStart('author');
705 $this->element('name', null, $entry['author-name']);
706 $this->element('uri', null, $entry['author-uri']);
708 $this->elementEnd('author');
709 $this->elementEnd('entry');
712 function showXmlDirectMessage($dm)
714 $this->elementStart('direct_message');
715 foreach($dm as $element => $value) {
719 $this->showTwitterXmlUser($value, $element);
722 $this->element($element, null, common_xml_safe_str($value));
725 $this->element($element, null, $value);
729 $this->elementEnd('direct_message');
732 function directMessageArray($message)
736 $from_profile = $message->getFrom();
737 $to_profile = $message->getTo();
739 $dmsg['id'] = $message->id;
740 $dmsg['sender_id'] = $message->from_profile;
741 $dmsg['text'] = trim($message->content);
742 $dmsg['recipient_id'] = $message->to_profile;
743 $dmsg['created_at'] = $this->dateTwitter($message->created);
744 $dmsg['sender_screen_name'] = $from_profile->nickname;
745 $dmsg['recipient_screen_name'] = $to_profile->nickname;
746 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
747 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
752 function rssDirectMessageArray($message)
756 $from = $message->getFrom();
758 $entry['title'] = sprintf('Message from %s to %s',
759 $from->nickname, $message->getTo()->nickname);
761 $entry['content'] = common_xml_safe_str($message->rendered);
762 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
763 $entry['published'] = common_date_iso8601($message->created);
765 $taguribase = common_config('integration', 'taguri');
767 $entry['id'] = "tag:$taguribase:$entry[link]";
768 $entry['updated'] = $entry['published'];
770 $entry['author-name'] = $from->getBestName();
771 $entry['author-uri'] = $from->homepage;
773 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
775 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
776 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
780 $entry['description'] = $entry['content'];
781 $entry['pubDate'] = common_date_rfc2822($message->created);
782 $entry['guid'] = $entry['link'];
787 function showSingleXmlDirectMessage($message)
789 $this->initDocument('xml');
790 $dmsg = $this->directMessageArray($message);
791 $this->showXmlDirectMessage($dmsg);
792 $this->endDocument('xml');
795 function showSingleJsonDirectMessage($message)
797 $this->initDocument('json');
798 $dmsg = $this->directMessageArray($message);
799 $this->showJsonObjects($dmsg);
800 $this->endDocument('json');
803 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
806 $this->initDocument('atom');
808 $this->element('title', null, $title);
809 $this->element('id', null, $id);
810 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
812 if (!is_null($selfuri)) {
813 $this->element('link', array('href' => $selfuri,
814 'rel' => 'self', 'type' => 'application/atom+xml'), null);
817 $this->element('updated', null, common_date_iso8601('now'));
818 $this->element('subtitle', null, $subtitle);
820 if (is_array($group)) {
821 foreach ($group as $g) {
822 $this->raw($g->asAtomEntry());
825 while ($group->fetch()) {
826 $this->raw($group->asAtomEntry());
830 $this->endDocument('atom');
834 function showJsonTimeline($notice)
837 $this->initDocument('json');
841 if (is_array($notice)) {
842 foreach ($notice as $n) {
843 $twitter_status = $this->twitterStatusArray($n);
844 array_push($statuses, $twitter_status);
847 while ($notice->fetch()) {
848 $twitter_status = $this->twitterStatusArray($notice);
849 array_push($statuses, $twitter_status);
853 $this->showJsonObjects($statuses);
855 $this->endDocument('json');
858 function showJsonGroups($group)
861 $this->initDocument('json');
865 if (is_array($group)) {
866 foreach ($group as $g) {
867 $twitter_group = $this->twitterGroupArray($g);
868 array_push($groups, $twitter_group);
871 while ($group->fetch()) {
872 $twitter_group = $this->twitterGroupArray($group);
873 array_push($groups, $twitter_group);
877 $this->showJsonObjects($groups);
879 $this->endDocument('json');
882 function showXmlGroups($group)
885 $this->initDocument('xml');
886 $this->elementStart('groups', array('type' => 'array'));
888 if (is_array($group)) {
889 foreach ($group as $g) {
890 $twitter_group = $this->twitterGroupArray($g);
891 $this->showTwitterXmlGroup($twitter_group);
894 while ($group->fetch()) {
895 $twitter_group = $this->twitterGroupArray($group);
896 $this->showTwitterXmlGroup($twitter_group);
900 $this->elementEnd('groups');
901 $this->endDocument('xml');
904 function showTwitterXmlUsers($user)
907 $this->initDocument('xml');
908 $this->elementStart('users', array('type' => 'array'));
910 if (is_array($user)) {
911 foreach ($user as $u) {
912 $twitter_user = $this->twitterUserArray($u);
913 $this->showTwitterXmlUser($twitter_user);
916 while ($user->fetch()) {
917 $twitter_user = $this->twitterUserArray($user);
918 $this->showTwitterXmlUser($twitter_user);
922 $this->elementEnd('users');
923 $this->endDocument('xml');
926 function showJsonUsers($user)
929 $this->initDocument('json');
933 if (is_array($user)) {
934 foreach ($user as $u) {
935 $twitter_user = $this->twitterUserArray($u);
936 array_push($users, $twitter_user);
939 while ($user->fetch()) {
940 $twitter_user = $this->twitterUserArray($user);
941 array_push($users, $twitter_user);
945 $this->showJsonObjects($users);
947 $this->endDocument('json');
950 function showSingleJsonGroup($group)
952 $this->initDocument('json');
953 $twitter_group = $this->twitterGroupArray($group);
954 $this->showJsonObjects($twitter_group);
955 $this->endDocument('json');
958 function showSingleXmlGroup($group)
960 $this->initDocument('xml');
961 $twitter_group = $this->twitterGroupArray($group);
962 $this->showTwitterXmlGroup($twitter_group);
963 $this->endDocument('xml');
966 function dateTwitter($dt)
968 $dateStr = date('d F Y H:i:s', strtotime($dt));
969 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
970 $d->setTimezone(new DateTimeZone(common_timezone()));
971 return $d->format('D M d H:i:s O Y');
974 function initDocument($type='xml')
978 header('Content-Type: application/xml; charset=utf-8');
982 header('Content-Type: application/json; charset=utf-8');
984 // Check for JSONP callback
985 $callback = $this->arg('callback');
987 print $callback . '(';
991 header("Content-Type: application/rss+xml; charset=utf-8");
992 $this->initTwitterRss();
995 header('Content-Type: application/atom+xml; charset=utf-8');
996 $this->initTwitterAtom();
999 $this->clientError(_('Not a supported data format.'));
1006 function endDocument($type='xml')
1014 // Check for JSONP callback
1015 $callback = $this->arg('callback');
1021 $this->endTwitterRss();
1024 $this->endTwitterRss();
1027 $this->clientError(_('Not a supported data format.'));
1033 function clientError($msg, $code = 400, $format = 'xml')
1035 $action = $this->trimmed('action');
1037 common_debug("User error '$code' on '$action': $msg", __FILE__);
1039 if (!array_key_exists($code, ClientErrorAction::$status)) {
1043 $status_string = ClientErrorAction::$status[$code];
1045 header('HTTP/1.1 '.$code.' '.$status_string);
1047 if ($format == 'xml') {
1048 $this->initDocument('xml');
1049 $this->elementStart('hash');
1050 $this->element('error', null, $msg);
1051 $this->element('request', null, $_SERVER['REQUEST_URI']);
1052 $this->elementEnd('hash');
1053 $this->endDocument('xml');
1054 } elseif ($format == 'json'){
1055 $this->initDocument('json');
1056 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1057 print(json_encode($error_array));
1058 $this->endDocument('json');
1061 // If user didn't request a useful format, throw a regular client error
1062 throw new ClientException($msg, $code);
1066 function serverError($msg, $code = 500, $content_type = 'json')
1068 $action = $this->trimmed('action');
1070 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1072 if (!array_key_exists($code, ServerErrorAction::$status)) {
1076 $status_string = ServerErrorAction::$status[$code];
1078 header('HTTP/1.1 '.$code.' '.$status_string);
1080 if ($content_type == 'xml') {
1081 $this->initDocument('xml');
1082 $this->elementStart('hash');
1083 $this->element('error', null, $msg);
1084 $this->element('request', null, $_SERVER['REQUEST_URI']);
1085 $this->elementEnd('hash');
1086 $this->endDocument('xml');
1088 $this->initDocument('json');
1089 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1090 print(json_encode($error_array));
1091 $this->endDocument('json');
1095 function initTwitterRss()
1098 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1099 $this->elementStart('channel');
1100 Event::handle('StartApiRss', array($this));
1103 function endTwitterRss()
1105 $this->elementEnd('channel');
1106 $this->elementEnd('rss');
1110 function initTwitterAtom()
1113 // FIXME: don't hardcode the language here!
1114 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1115 'xml:lang' => 'en-US',
1116 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1117 Event::handle('StartApiAtom', array($this));
1120 function endTwitterAtom()
1122 $this->elementEnd('feed');
1126 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1128 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1129 switch ($content_type) {
1131 $this->showTwitterXmlUser($profile_array);
1134 $this->showJsonObjects($profile_array);
1137 $this->clientError(_('Not a supported data format.'));
1143 function getTargetUser($id)
1147 // Twitter supports these other ways of passing the user ID
1148 if (is_numeric($this->arg('id'))) {
1149 return User::staticGet($this->arg('id'));
1150 } else if ($this->arg('id')) {
1151 $nickname = common_canonical_nickname($this->arg('id'));
1152 return User::staticGet('nickname', $nickname);
1153 } else if ($this->arg('user_id')) {
1154 // This is to ensure that a non-numeric user_id still
1155 // overrides screen_name even if it doesn't get used
1156 if (is_numeric($this->arg('user_id'))) {
1157 return User::staticGet('id', $this->arg('user_id'));
1159 } else if ($this->arg('screen_name')) {
1160 $nickname = common_canonical_nickname($this->arg('screen_name'));
1161 return User::staticGet('nickname', $nickname);
1163 // Fall back to trying the currently authenticated user
1164 return $this->auth_user;
1167 } else if (is_numeric($id)) {
1168 return User::staticGet($id);
1170 $nickname = common_canonical_nickname($id);
1171 return User::staticGet('nickname', $nickname);
1175 function getTargetGroup($id)
1178 if (is_numeric($this->arg('id'))) {
1179 return User_group::staticGet($this->arg('id'));
1180 } else if ($this->arg('id')) {
1181 $nickname = common_canonical_nickname($this->arg('id'));
1182 return User_group::staticGet('nickname', $nickname);
1183 } else if ($this->arg('group_id')) {
1184 // This is to ensure that a non-numeric user_id still
1185 // overrides screen_name even if it doesn't get used
1186 if (is_numeric($this->arg('group_id'))) {
1187 return User_group::staticGet('id', $this->arg('group_id'));
1189 } else if ($this->arg('group_name')) {
1190 $nickname = common_canonical_nickname($this->arg('group_name'));
1191 return User_group::staticGet('nickname', $nickname);
1194 } else if (is_numeric($id)) {
1195 return User_group::staticGet($id);
1197 $nickname = common_canonical_nickname($id);
1198 return User_group::staticGet('nickname', $nickname);
1202 function sourceLink($source)
1204 $source_name = _($source);
1213 $ns = Notice_source::staticGet($source);
1215 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1219 return $source_name;
1223 * Returns query argument or default value if not found. Certain
1224 * parameters used throughout the API are lightly scrubbed and
1225 * bounds checked. This overrides Action::arg().
1227 * @param string $key requested argument
1228 * @param string $def default value to return if $key is not provided
1232 function arg($key, $def=null)
1235 // XXX: Do even more input validation/scrubbing?
1237 if (array_key_exists($key, $this->args)) {
1240 $page = (int)$this->args['page'];
1241 return ($page < 1) ? 1 : $page;
1243 $count = (int)$this->args['count'];
1246 } elseif ($count > 200) {
1252 $since_id = (int)$this->args['since_id'];
1253 return ($since_id < 1) ? 0 : $since_id;
1255 $max_id = (int)$this->args['max_id'];
1256 return ($max_id < 1) ? 0 : $max_id;
1258 return strtotime($this->args['since']);
1260 return parent::arg($key, $def);