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 $user = $profile->getUser();
140 // Note: some profiles don't have an associated user
142 $defaultDesign = Design::siteDesign();
145 $design = $user->getDesign();
148 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
149 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
150 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
151 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
152 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
153 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
154 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
155 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
156 $twitter_user['profile_sidebar_border_color'] = '';
158 $twitter_user['friends_count'] = $profile->subscriptionCount();
160 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
162 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
166 if (!empty($user) && !empty($user->timezone)) {
167 $timezone = $user->timezone;
171 $t->setTimezone(new DateTimeZone($timezone));
173 $twitter_user['utc_offset'] = $t->format('Z');
174 $twitter_user['time_zone'] = $timezone;
176 $twitter_user['profile_background_image_url']
177 = empty($design->backgroundimage)
178 ? '' : ($design->disposition & BACKGROUND_ON)
179 ? Design::url($design->backgroundimage) : '';
181 $twitter_user['profile_background_tile']
182 = empty($design->disposition)
183 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
185 $twitter_user['statuses_count'] = $profile->noticeCount();
187 // Is the requesting user following this user?
188 $twitter_user['following'] = false;
189 $twitter_user['notifications'] = false;
191 if (isset($apidata['user'])) {
193 $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
196 $sub = Subscription::pkeyGet(array('subscriber' =>
197 $apidata['user']->id, 'subscribed' => $profile->id));
200 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
205 $notice = $profile->getCurrentNotice();
208 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
212 return $twitter_user;
215 function twitterStatusArray($notice, $include_user=true)
217 $base = $this->twitterSimpleStatusArray($notice, $include_user);
219 if (empty($notice->repeat_of)) {
222 $original = Notice::staticGet('id', $notice->repeat_of);
223 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
224 $original_array['retweeted_status'] = $base;
225 return $original_array;
229 function twitterSimpleStatusArray($notice, $include_user=true)
231 $profile = $notice->getProfile();
233 $twitter_status = array();
234 $twitter_status['text'] = $notice->content;
235 $twitter_status['truncated'] = false; # Not possible on StatusNet
236 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
237 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
238 intval($notice->reply_to) : null;
239 $twitter_status['source'] = $this->sourceLink($notice->source);
240 $twitter_status['id'] = intval($notice->id);
242 $replier_profile = null;
244 if ($notice->reply_to) {
245 $reply = Notice::staticGet(intval($notice->reply_to));
247 $replier_profile = $reply->getProfile();
251 $twitter_status['in_reply_to_user_id'] =
252 ($replier_profile) ? intval($replier_profile->id) : null;
253 $twitter_status['in_reply_to_screen_name'] =
254 ($replier_profile) ? $replier_profile->nickname : null;
256 if (isset($notice->lat) && isset($notice->lon)) {
257 // This is the format that GeoJSON expects stuff to be in
258 $twitter_status['geo'] = array('type' => 'Point',
259 'coordinates' => array((float) $notice->lat,
260 (float) $notice->lon));
262 $twitter_status['geo'] = null;
265 if (isset($this->auth_user)) {
266 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
268 $twitter_status['favorited'] = false;
272 $attachments = $notice->attachments();
274 if (!empty($attachments)) {
276 $twitter_status['attachments'] = array();
278 foreach ($attachments as $attachment) {
279 if ($attachment->isEnclosure()) {
280 $enclosure = array();
281 $enclosure['url'] = $attachment->url;
282 $enclosure['mimetype'] = $attachment->mimetype;
283 $enclosure['size'] = $attachment->size;
284 $twitter_status['attachments'][] = $enclosure;
290 # Don't get notice (recursive!)
291 $twitter_user = $this->twitterUserArray($profile, false);
292 $twitter_status['user'] = $twitter_user;
295 return $twitter_status;
298 function twitterGroupArray($group)
300 $twitter_group=array();
301 $twitter_group['id']=$group->id;
302 $twitter_group['url']=$group->permalink();
303 $twitter_group['nickname']=$group->nickname;
304 $twitter_group['fullname']=$group->fullname;
305 $twitter_group['homepage_url']=$group->homepage_url;
306 $twitter_group['original_logo']=$group->original_logo;
307 $twitter_group['homepage_logo']=$group->homepage_logo;
308 $twitter_group['stream_logo']=$group->stream_logo;
309 $twitter_group['mini_logo']=$group->mini_logo;
310 $twitter_group['homepage']=$group->homepage;
311 $twitter_group['description']=$group->description;
312 $twitter_group['location']=$group->location;
313 $twitter_group['created']=$this->dateTwitter($group->created);
314 $twitter_group['modified']=$this->dateTwitter($group->modified);
315 return $twitter_group;
318 function twitterRssGroupArray($group)
321 $entry['content']=$group->description;
322 $entry['title']=$group->nickname;
323 $entry['link']=$group->permalink();
324 $entry['published']=common_date_iso8601($group->created);
325 $entry['updated']==common_date_iso8601($group->modified);
326 $taguribase = common_config('integration', 'groupuri');
327 $entry['id'] = "group:$groupuribase:$entry[link]";
329 $entry['description'] = $entry['content'];
330 $entry['pubDate'] = common_date_rfc2822($group->created);
331 $entry['guid'] = $entry['link'];
336 function twitterRssEntryArray($notice)
338 $profile = $notice->getProfile();
341 // We trim() to avoid extraneous whitespace in the output
343 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
344 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
345 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
346 $entry['published'] = common_date_iso8601($notice->created);
348 $taguribase = common_config('integration', 'taguri');
349 $entry['id'] = "tag:$taguribase:$entry[link]";
351 $entry['updated'] = $entry['published'];
352 $entry['author'] = $profile->getBestName();
355 $attachments = $notice->attachments();
356 $enclosures = array();
358 foreach ($attachments as $attachment) {
359 $enclosure_o=$attachment->getEnclosure();
361 $enclosure = array();
362 $enclosure['url'] = $enclosure_o->url;
363 $enclosure['mimetype'] = $enclosure_o->mimetype;
364 $enclosure['size'] = $enclosure_o->size;
365 $enclosures[] = $enclosure;
369 if (!empty($enclosures)) {
370 $entry['enclosures'] = $enclosures;
374 $tag = new Notice_tag();
375 $tag->notice_id = $notice->id;
377 $entry['tags']=array();
378 while ($tag->fetch()) {
379 $entry['tags'][]=$tag->tag;
385 $entry['description'] = $entry['content'];
386 $entry['pubDate'] = common_date_rfc2822($notice->created);
387 $entry['guid'] = $entry['link'];
389 if (isset($notice->lat) && isset($notice->lon)) {
390 // This is the format that GeoJSON expects stuff to be in.
391 // showGeoRSS() below uses it for XML output, so we reuse it
392 $entry['geo'] = array('type' => 'Point',
393 'coordinates' => array((float) $notice->lat,
394 (float) $notice->lon));
396 $entry['geo'] = null;
402 function twitterRelationshipArray($source, $target)
404 $relationship = array();
406 $relationship['source'] =
407 $this->relationshipDetailsArray($source, $target);
408 $relationship['target'] =
409 $this->relationshipDetailsArray($target, $source);
411 return array('relationship' => $relationship);
414 function relationshipDetailsArray($source, $target)
418 $details['screen_name'] = $source->nickname;
419 $details['followed_by'] = $target->isSubscribed($source);
420 $details['following'] = $source->isSubscribed($target);
422 $notifications = false;
424 if ($source->isSubscribed($target)) {
426 $sub = Subscription::pkeyGet(array('subscriber' =>
427 $source->id, 'subscribed' => $target->id));
430 $notifications = ($sub->jabber || $sub->sms);
434 $details['notifications_enabled'] = $notifications;
435 $details['blocking'] = $source->hasBlocked($target);
436 $details['id'] = $source->id;
441 function showTwitterXmlRelationship($relationship)
443 $this->elementStart('relationship');
445 foreach($relationship as $element => $value) {
446 if ($element == 'source' || $element == 'target') {
447 $this->elementStart($element);
448 $this->showXmlRelationshipDetails($value);
449 $this->elementEnd($element);
453 $this->elementEnd('relationship');
456 function showXmlRelationshipDetails($details)
458 foreach($details as $element => $value) {
459 $this->element($element, null, $value);
463 function showTwitterXmlStatus($twitter_status, $tag='status')
465 $this->elementStart($tag);
466 foreach($twitter_status as $element => $value) {
469 $this->showTwitterXmlUser($twitter_status['user']);
472 $this->element($element, null, common_xml_safe_str($value));
475 $this->showXmlAttachments($twitter_status['attachments']);
478 $this->showGeoRSS($value);
480 case 'retweeted_status':
481 $this->showTwitterXmlStatus($value, 'retweeted_status');
484 $this->element($element, null, $value);
487 $this->elementEnd($tag);
490 function showTwitterXmlGroup($twitter_group)
492 $this->elementStart('group');
493 foreach($twitter_group as $element => $value) {
494 $this->element($element, null, $value);
496 $this->elementEnd('group');
499 function showTwitterXmlUser($twitter_user, $role='user')
501 $this->elementStart($role);
502 foreach($twitter_user as $element => $value) {
503 if ($element == 'status') {
504 $this->showTwitterXmlStatus($twitter_user['status']);
506 $this->element($element, null, $value);
509 $this->elementEnd($role);
512 function showXmlAttachments($attachments) {
513 if (!empty($attachments)) {
514 $this->elementStart('attachments', array('type' => 'array'));
515 foreach ($attachments as $attachment) {
517 $attrs['url'] = $attachment['url'];
518 $attrs['mimetype'] = $attachment['mimetype'];
519 $attrs['size'] = $attachment['size'];
520 $this->element('enclosure', $attrs, '');
522 $this->elementEnd('attachments');
526 function showGeoRSS($geo)
530 $this->element('geo');
532 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
533 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
534 $this->elementEnd('geo');
538 function showTwitterRssItem($entry)
540 $this->elementStart('item');
541 $this->element('title', null, $entry['title']);
542 $this->element('description', null, $entry['description']);
543 $this->element('pubDate', null, $entry['pubDate']);
544 $this->element('guid', null, $entry['guid']);
545 $this->element('link', null, $entry['link']);
547 # RSS only supports 1 enclosure per item
548 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
549 $enclosure = $entry['enclosures'][0];
550 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
553 if(array_key_exists('tags', $entry)){
554 foreach($entry['tags'] as $tag){
555 $this->element('category', null,$tag);
559 $this->showGeoRSS($entry['geo']);
560 $this->elementEnd('item');
563 function showJsonObjects($objects)
565 print(json_encode($objects));
568 function showSingleXmlStatus($notice)
570 $this->initDocument('xml');
571 $twitter_status = $this->twitterStatusArray($notice);
572 $this->showTwitterXmlStatus($twitter_status);
573 $this->endDocument('xml');
576 function show_single_json_status($notice)
578 $this->initDocument('json');
579 $status = $this->twitterStatusArray($notice);
580 $this->showJsonObjects($status);
581 $this->endDocument('json');
584 function showXmlTimeline($notice)
587 $this->initDocument('xml');
588 $this->elementStart('statuses', array('type' => 'array'));
590 if (is_array($notice)) {
591 foreach ($notice as $n) {
592 $twitter_status = $this->twitterStatusArray($n);
593 $this->showTwitterXmlStatus($twitter_status);
596 while ($notice->fetch()) {
597 $twitter_status = $this->twitterStatusArray($notice);
598 $this->showTwitterXmlStatus($twitter_status);
602 $this->elementEnd('statuses');
603 $this->endDocument('xml');
606 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null)
609 $this->initDocument('rss');
611 $this->element('title', null, $title);
612 $this->element('link', null, $link);
613 if (!is_null($suplink)) {
614 // For FriendFeed's SUP protocol
615 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
616 'rel' => 'http://api.friendfeed.com/2008/03#sup',
618 'type' => 'application/json'));
620 $this->element('description', null, $subtitle);
621 $this->element('language', null, 'en-us');
622 $this->element('ttl', null, '40');
624 if (is_array($notice)) {
625 foreach ($notice as $n) {
626 $entry = $this->twitterRssEntryArray($n);
627 $this->showTwitterRssItem($entry);
630 while ($notice->fetch()) {
631 $entry = $this->twitterRssEntryArray($notice);
632 $this->showTwitterRssItem($entry);
636 $this->endTwitterRss();
639 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
642 $this->initDocument('atom');
644 $this->element('title', null, $title);
645 $this->element('id', null, $id);
646 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
648 if (!is_null($suplink)) {
649 # For FriendFeed's SUP protocol
650 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
652 'type' => 'application/json'));
655 if (!is_null($selfuri)) {
656 $this->element('link', array('href' => $selfuri,
657 'rel' => 'self', 'type' => 'application/atom+xml'), null);
660 $this->element('updated', null, common_date_iso8601('now'));
661 $this->element('subtitle', null, $subtitle);
663 if (is_array($notice)) {
664 foreach ($notice as $n) {
665 $this->raw($n->asAtomEntry());
668 while ($notice->fetch()) {
669 $this->raw($notice->asAtomEntry());
673 $this->endDocument('atom');
677 function showRssGroups($group, $title, $link, $subtitle)
680 $this->initDocument('rss');
682 $this->element('title', null, $title);
683 $this->element('link', null, $link);
684 $this->element('description', null, $subtitle);
685 $this->element('language', null, 'en-us');
686 $this->element('ttl', null, '40');
688 if (is_array($group)) {
689 foreach ($group as $g) {
690 $twitter_group = $this->twitterRssGroupArray($g);
691 $this->showTwitterRssItem($twitter_group);
694 while ($group->fetch()) {
695 $twitter_group = $this->twitterRssGroupArray($group);
696 $this->showTwitterRssItem($twitter_group);
700 $this->endTwitterRss();
703 function showTwitterAtomEntry($entry)
705 $this->elementStart('entry');
706 $this->element('title', null, $entry['title']);
707 $this->element('content', array('type' => 'html'), $entry['content']);
708 $this->element('id', null, $entry['id']);
709 $this->element('published', null, $entry['published']);
710 $this->element('updated', null, $entry['updated']);
711 $this->element('link', array('type' => 'text/html',
712 'href' => $entry['link'],
713 'rel' => 'alternate'));
714 $this->element('link', array('type' => $entry['avatar-type'],
715 'href' => $entry['avatar'],
717 $this->elementStart('author');
719 $this->element('name', null, $entry['author-name']);
720 $this->element('uri', null, $entry['author-uri']);
722 $this->elementEnd('author');
723 $this->elementEnd('entry');
726 function showXmlDirectMessage($dm)
728 $this->elementStart('direct_message');
729 foreach($dm as $element => $value) {
733 $this->showTwitterXmlUser($value, $element);
736 $this->element($element, null, common_xml_safe_str($value));
739 $this->element($element, null, $value);
743 $this->elementEnd('direct_message');
746 function directMessageArray($message)
750 $from_profile = $message->getFrom();
751 $to_profile = $message->getTo();
753 $dmsg['id'] = $message->id;
754 $dmsg['sender_id'] = $message->from_profile;
755 $dmsg['text'] = trim($message->content);
756 $dmsg['recipient_id'] = $message->to_profile;
757 $dmsg['created_at'] = $this->dateTwitter($message->created);
758 $dmsg['sender_screen_name'] = $from_profile->nickname;
759 $dmsg['recipient_screen_name'] = $to_profile->nickname;
760 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
761 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
766 function rssDirectMessageArray($message)
770 $from = $message->getFrom();
772 $entry['title'] = sprintf('Message from %s to %s',
773 $from->nickname, $message->getTo()->nickname);
775 $entry['content'] = common_xml_safe_str($message->rendered);
776 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
777 $entry['published'] = common_date_iso8601($message->created);
779 $taguribase = common_config('integration', 'taguri');
781 $entry['id'] = "tag:$taguribase:$entry[link]";
782 $entry['updated'] = $entry['published'];
784 $entry['author-name'] = $from->getBestName();
785 $entry['author-uri'] = $from->homepage;
787 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
789 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
790 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
794 $entry['description'] = $entry['content'];
795 $entry['pubDate'] = common_date_rfc2822($message->created);
796 $entry['guid'] = $entry['link'];
801 function showSingleXmlDirectMessage($message)
803 $this->initDocument('xml');
804 $dmsg = $this->directMessageArray($message);
805 $this->showXmlDirectMessage($dmsg);
806 $this->endDocument('xml');
809 function showSingleJsonDirectMessage($message)
811 $this->initDocument('json');
812 $dmsg = $this->directMessageArray($message);
813 $this->showJsonObjects($dmsg);
814 $this->endDocument('json');
817 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
820 $this->initDocument('atom');
822 $this->element('title', null, $title);
823 $this->element('id', null, $id);
824 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
826 if (!is_null($selfuri)) {
827 $this->element('link', array('href' => $selfuri,
828 'rel' => 'self', 'type' => 'application/atom+xml'), null);
831 $this->element('updated', null, common_date_iso8601('now'));
832 $this->element('subtitle', null, $subtitle);
834 if (is_array($group)) {
835 foreach ($group as $g) {
836 $this->raw($g->asAtomEntry());
839 while ($group->fetch()) {
840 $this->raw($group->asAtomEntry());
844 $this->endDocument('atom');
848 function showJsonTimeline($notice)
851 $this->initDocument('json');
855 if (is_array($notice)) {
856 foreach ($notice as $n) {
857 $twitter_status = $this->twitterStatusArray($n);
858 array_push($statuses, $twitter_status);
861 while ($notice->fetch()) {
862 $twitter_status = $this->twitterStatusArray($notice);
863 array_push($statuses, $twitter_status);
867 $this->showJsonObjects($statuses);
869 $this->endDocument('json');
872 function showJsonGroups($group)
875 $this->initDocument('json');
879 if (is_array($group)) {
880 foreach ($group as $g) {
881 $twitter_group = $this->twitterGroupArray($g);
882 array_push($groups, $twitter_group);
885 while ($group->fetch()) {
886 $twitter_group = $this->twitterGroupArray($group);
887 array_push($groups, $twitter_group);
891 $this->showJsonObjects($groups);
893 $this->endDocument('json');
896 function showXmlGroups($group)
899 $this->initDocument('xml');
900 $this->elementStart('groups', array('type' => 'array'));
902 if (is_array($group)) {
903 foreach ($group as $g) {
904 $twitter_group = $this->twitterGroupArray($g);
905 $this->showTwitterXmlGroup($twitter_group);
908 while ($group->fetch()) {
909 $twitter_group = $this->twitterGroupArray($group);
910 $this->showTwitterXmlGroup($twitter_group);
914 $this->elementEnd('groups');
915 $this->endDocument('xml');
918 function showTwitterXmlUsers($user)
921 $this->initDocument('xml');
922 $this->elementStart('users', array('type' => 'array'));
924 if (is_array($user)) {
925 foreach ($user as $u) {
926 $twitter_user = $this->twitterUserArray($u);
927 $this->showTwitterXmlUser($twitter_user);
930 while ($user->fetch()) {
931 $twitter_user = $this->twitterUserArray($user);
932 $this->showTwitterXmlUser($twitter_user);
936 $this->elementEnd('users');
937 $this->endDocument('xml');
940 function showJsonUsers($user)
943 $this->initDocument('json');
947 if (is_array($user)) {
948 foreach ($user as $u) {
949 $twitter_user = $this->twitterUserArray($u);
950 array_push($users, $twitter_user);
953 while ($user->fetch()) {
954 $twitter_user = $this->twitterUserArray($user);
955 array_push($users, $twitter_user);
959 $this->showJsonObjects($users);
961 $this->endDocument('json');
964 function showSingleJsonGroup($group)
966 $this->initDocument('json');
967 $twitter_group = $this->twitterGroupArray($group);
968 $this->showJsonObjects($twitter_group);
969 $this->endDocument('json');
972 function showSingleXmlGroup($group)
974 $this->initDocument('xml');
975 $twitter_group = $this->twitterGroupArray($group);
976 $this->showTwitterXmlGroup($twitter_group);
977 $this->endDocument('xml');
980 function dateTwitter($dt)
982 $dateStr = date('d F Y H:i:s', strtotime($dt));
983 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
984 $d->setTimezone(new DateTimeZone(common_timezone()));
985 return $d->format('D M d H:i:s O Y');
988 function initDocument($type='xml')
992 header('Content-Type: application/xml; charset=utf-8');
996 header('Content-Type: application/json; charset=utf-8');
998 // Check for JSONP callback
999 $callback = $this->arg('callback');
1001 print $callback . '(';
1005 header("Content-Type: application/rss+xml; charset=utf-8");
1006 $this->initTwitterRss();
1009 header('Content-Type: application/atom+xml; charset=utf-8');
1010 $this->initTwitterAtom();
1013 $this->clientError(_('Not a supported data format.'));
1020 function endDocument($type='xml')
1028 // Check for JSONP callback
1029 $callback = $this->arg('callback');
1035 $this->endTwitterRss();
1038 $this->endTwitterRss();
1041 $this->clientError(_('Not a supported data format.'));
1047 function clientError($msg, $code = 400, $format = 'xml')
1049 $action = $this->trimmed('action');
1051 common_debug("User error '$code' on '$action': $msg", __FILE__);
1053 if (!array_key_exists($code, ClientErrorAction::$status)) {
1057 $status_string = ClientErrorAction::$status[$code];
1059 header('HTTP/1.1 '.$code.' '.$status_string);
1061 if ($format == 'xml') {
1062 $this->initDocument('xml');
1063 $this->elementStart('hash');
1064 $this->element('error', null, $msg);
1065 $this->element('request', null, $_SERVER['REQUEST_URI']);
1066 $this->elementEnd('hash');
1067 $this->endDocument('xml');
1068 } elseif ($format == 'json'){
1069 $this->initDocument('json');
1070 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1071 print(json_encode($error_array));
1072 $this->endDocument('json');
1075 // If user didn't request a useful format, throw a regular client error
1076 throw new ClientException($msg, $code);
1080 function serverError($msg, $code = 500, $content_type = 'json')
1082 $action = $this->trimmed('action');
1084 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1086 if (!array_key_exists($code, ServerErrorAction::$status)) {
1090 $status_string = ServerErrorAction::$status[$code];
1092 header('HTTP/1.1 '.$code.' '.$status_string);
1094 if ($content_type == 'xml') {
1095 $this->initDocument('xml');
1096 $this->elementStart('hash');
1097 $this->element('error', null, $msg);
1098 $this->element('request', null, $_SERVER['REQUEST_URI']);
1099 $this->elementEnd('hash');
1100 $this->endDocument('xml');
1102 $this->initDocument('json');
1103 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1104 print(json_encode($error_array));
1105 $this->endDocument('json');
1109 function initTwitterRss()
1112 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1113 $this->elementStart('channel');
1114 Event::handle('StartApiRss', array($this));
1117 function endTwitterRss()
1119 $this->elementEnd('channel');
1120 $this->elementEnd('rss');
1124 function initTwitterAtom()
1127 // FIXME: don't hardcode the language here!
1128 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1129 'xml:lang' => 'en-US',
1130 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1131 Event::handle('StartApiAtom', array($this));
1134 function endTwitterAtom()
1136 $this->elementEnd('feed');
1140 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1142 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1143 switch ($content_type) {
1145 $this->showTwitterXmlUser($profile_array);
1148 $this->showJsonObjects($profile_array);
1151 $this->clientError(_('Not a supported data format.'));
1157 function getTargetUser($id)
1161 // Twitter supports these other ways of passing the user ID
1162 if (is_numeric($this->arg('id'))) {
1163 return User::staticGet($this->arg('id'));
1164 } else if ($this->arg('id')) {
1165 $nickname = common_canonical_nickname($this->arg('id'));
1166 return User::staticGet('nickname', $nickname);
1167 } else if ($this->arg('user_id')) {
1168 // This is to ensure that a non-numeric user_id still
1169 // overrides screen_name even if it doesn't get used
1170 if (is_numeric($this->arg('user_id'))) {
1171 return User::staticGet('id', $this->arg('user_id'));
1173 } else if ($this->arg('screen_name')) {
1174 $nickname = common_canonical_nickname($this->arg('screen_name'));
1175 return User::staticGet('nickname', $nickname);
1177 // Fall back to trying the currently authenticated user
1178 return $this->auth_user;
1181 } else if (is_numeric($id)) {
1182 return User::staticGet($id);
1184 $nickname = common_canonical_nickname($id);
1185 return User::staticGet('nickname', $nickname);
1189 function getTargetGroup($id)
1192 if (is_numeric($this->arg('id'))) {
1193 return User_group::staticGet($this->arg('id'));
1194 } else if ($this->arg('id')) {
1195 $nickname = common_canonical_nickname($this->arg('id'));
1196 return User_group::staticGet('nickname', $nickname);
1197 } else if ($this->arg('group_id')) {
1198 // This is to ensure that a non-numeric user_id still
1199 // overrides screen_name even if it doesn't get used
1200 if (is_numeric($this->arg('group_id'))) {
1201 return User_group::staticGet('id', $this->arg('group_id'));
1203 } else if ($this->arg('group_name')) {
1204 $nickname = common_canonical_nickname($this->arg('group_name'));
1205 return User_group::staticGet('nickname', $nickname);
1208 } else if (is_numeric($id)) {
1209 return User_group::staticGet($id);
1211 $nickname = common_canonical_nickname($id);
1212 return User_group::staticGet('nickname', $nickname);
1216 function sourceLink($source)
1218 $source_name = _($source);
1227 $ns = Notice_source::staticGet($source);
1229 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1233 return $source_name;
1237 * Returns query argument or default value if not found. Certain
1238 * parameters used throughout the API are lightly scrubbed and
1239 * bounds checked. This overrides Action::arg().
1241 * @param string $key requested argument
1242 * @param string $def default value to return if $key is not provided
1246 function arg($key, $def=null)
1249 // XXX: Do even more input validation/scrubbing?
1251 if (array_key_exists($key, $this->args)) {
1254 $page = (int)$this->args['page'];
1255 return ($page < 1) ? 1 : $page;
1257 $count = (int)$this->args['count'];
1260 } elseif ($count > 200) {
1266 $since_id = (int)$this->args['since_id'];
1267 return ($since_id < 1) ? 0 : $since_id;
1269 $max_id = (int)$this->args['max_id'];
1270 return ($max_id < 1) ? 0 : $max_id;
1272 return strtotime($this->args['since']);
1274 return parent::arg($key, $def);