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();
138 $user = $profile->getUser();
140 // Note: some profiles don't have an associated user
143 $design = $user->getDesign();
146 if (empty($design)) {
147 $design = Design::siteDesign();
150 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
151 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
152 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
153 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
154 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
155 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
156 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
157 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
158 $twitter_user['profile_sidebar_border_color'] = '';
160 $twitter_user['friends_count'] = $profile->subscriptionCount();
162 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
164 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
168 if ($user->timezone) {
169 $timezone = $user->timezone;
173 $t->setTimezone(new DateTimeZone($timezone));
175 $twitter_user['utc_offset'] = $t->format('Z');
176 $twitter_user['time_zone'] = $timezone;
178 $twitter_user['profile_background_image_url']
179 = empty($design->backgroundimage)
180 ? '' : ($design->disposition & BACKGROUND_ON)
181 ? Design::url($design->backgroundimage) : '';
183 $twitter_user['profile_background_tile']
184 = empty($design->disposition)
185 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
187 $twitter_user['statuses_count'] = $profile->noticeCount();
189 // Is the requesting user following this user?
190 $twitter_user['following'] = false;
191 $twitter_user['notifications'] = false;
193 if (isset($apidata['user'])) {
195 $twitter_user['following'] = $apidata['user']->isSubscribed($profile);
198 $sub = Subscription::pkeyGet(array('subscriber' =>
199 $apidata['user']->id, 'subscribed' => $profile->id));
202 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
207 $notice = $profile->getCurrentNotice();
210 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
214 return $twitter_user;
217 function twitterStatusArray($notice, $include_user=true)
219 $base = $this->twitterSimpleStatusArray($notice, $include_user);
221 if (empty($notice->repeat_of)) {
224 $original = Notice::staticGet('id', $notice->repeat_of);
225 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
226 $original_array['retweeted_status'] = $base;
227 return $original_array;
231 function twitterSimpleStatusArray($notice, $include_user=true)
233 $profile = $notice->getProfile();
235 $twitter_status = array();
236 $twitter_status['text'] = $notice->content;
237 $twitter_status['truncated'] = false; # Not possible on StatusNet
238 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
239 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
240 intval($notice->reply_to) : null;
241 $twitter_status['source'] = $this->sourceLink($notice->source);
242 $twitter_status['id'] = intval($notice->id);
244 $replier_profile = null;
246 if ($notice->reply_to) {
247 $reply = Notice::staticGet(intval($notice->reply_to));
249 $replier_profile = $reply->getProfile();
253 $twitter_status['in_reply_to_user_id'] =
254 ($replier_profile) ? intval($replier_profile->id) : null;
255 $twitter_status['in_reply_to_screen_name'] =
256 ($replier_profile) ? $replier_profile->nickname : null;
258 if (isset($notice->lat) && isset($notice->lon)) {
259 // This is the format that GeoJSON expects stuff to be in
260 $twitter_status['geo'] = array('type' => 'Point',
261 'coordinates' => array((float) $notice->lat,
262 (float) $notice->lon));
264 $twitter_status['geo'] = null;
267 if (isset($this->auth_user)) {
268 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
270 $twitter_status['favorited'] = false;
274 $attachments = $notice->attachments();
276 if (!empty($attachments)) {
278 $twitter_status['attachments'] = array();
280 foreach ($attachments as $attachment) {
281 if ($attachment->isEnclosure()) {
282 $enclosure = array();
283 $enclosure['url'] = $attachment->url;
284 $enclosure['mimetype'] = $attachment->mimetype;
285 $enclosure['size'] = $attachment->size;
286 $twitter_status['attachments'][] = $enclosure;
292 # Don't get notice (recursive!)
293 $twitter_user = $this->twitterUserArray($profile, false);
294 $twitter_status['user'] = $twitter_user;
297 return $twitter_status;
300 function twitterGroupArray($group)
302 $twitter_group=array();
303 $twitter_group['id']=$group->id;
304 $twitter_group['url']=$group->permalink();
305 $twitter_group['nickname']=$group->nickname;
306 $twitter_group['fullname']=$group->fullname;
307 $twitter_group['homepage_url']=$group->homepage_url;
308 $twitter_group['original_logo']=$group->original_logo;
309 $twitter_group['homepage_logo']=$group->homepage_logo;
310 $twitter_group['stream_logo']=$group->stream_logo;
311 $twitter_group['mini_logo']=$group->mini_logo;
312 $twitter_group['homepage']=$group->homepage;
313 $twitter_group['description']=$group->description;
314 $twitter_group['location']=$group->location;
315 $twitter_group['created']=$this->dateTwitter($group->created);
316 $twitter_group['modified']=$this->dateTwitter($group->modified);
317 return $twitter_group;
320 function twitterRssGroupArray($group)
323 $entry['content']=$group->description;
324 $entry['title']=$group->nickname;
325 $entry['link']=$group->permalink();
326 $entry['published']=common_date_iso8601($group->created);
327 $entry['updated']==common_date_iso8601($group->modified);
328 $taguribase = common_config('integration', 'groupuri');
329 $entry['id'] = "group:$groupuribase:$entry[link]";
331 $entry['description'] = $entry['content'];
332 $entry['pubDate'] = common_date_rfc2822($group->created);
333 $entry['guid'] = $entry['link'];
338 function twitterRssEntryArray($notice)
340 $profile = $notice->getProfile();
343 // We trim() to avoid extraneous whitespace in the output
345 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
346 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
347 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
348 $entry['published'] = common_date_iso8601($notice->created);
350 $taguribase = common_config('integration', 'taguri');
351 $entry['id'] = "tag:$taguribase:$entry[link]";
353 $entry['updated'] = $entry['published'];
354 $entry['author'] = $profile->getBestName();
357 $attachments = $notice->attachments();
358 $enclosures = array();
360 foreach ($attachments as $attachment) {
361 $enclosure_o=$attachment->getEnclosure();
363 $enclosure = array();
364 $enclosure['url'] = $enclosure_o->url;
365 $enclosure['mimetype'] = $enclosure_o->mimetype;
366 $enclosure['size'] = $enclosure_o->size;
367 $enclosures[] = $enclosure;
371 if (!empty($enclosures)) {
372 $entry['enclosures'] = $enclosures;
376 $tag = new Notice_tag();
377 $tag->notice_id = $notice->id;
379 $entry['tags']=array();
380 while ($tag->fetch()) {
381 $entry['tags'][]=$tag->tag;
387 $entry['description'] = $entry['content'];
388 $entry['pubDate'] = common_date_rfc2822($notice->created);
389 $entry['guid'] = $entry['link'];
391 if (isset($notice->lat) && isset($notice->lon)) {
392 // This is the format that GeoJSON expects stuff to be in.
393 // showGeoRSS() below uses it for XML output, so we reuse it
394 $entry['geo'] = array('type' => 'Point',
395 'coordinates' => array((float) $notice->lat,
396 (float) $notice->lon));
398 $entry['geo'] = null;
404 function twitterRelationshipArray($source, $target)
406 $relationship = array();
408 $relationship['source'] =
409 $this->relationshipDetailsArray($source, $target);
410 $relationship['target'] =
411 $this->relationshipDetailsArray($target, $source);
413 return array('relationship' => $relationship);
416 function relationshipDetailsArray($source, $target)
420 $details['screen_name'] = $source->nickname;
421 $details['followed_by'] = $target->isSubscribed($source);
422 $details['following'] = $source->isSubscribed($target);
424 $notifications = false;
426 if ($source->isSubscribed($target)) {
428 $sub = Subscription::pkeyGet(array('subscriber' =>
429 $source->id, 'subscribed' => $target->id));
432 $notifications = ($sub->jabber || $sub->sms);
436 $details['notifications_enabled'] = $notifications;
437 $details['blocking'] = $source->hasBlocked($target);
438 $details['id'] = $source->id;
443 function showTwitterXmlRelationship($relationship)
445 $this->elementStart('relationship');
447 foreach($relationship as $element => $value) {
448 if ($element == 'source' || $element == 'target') {
449 $this->elementStart($element);
450 $this->showXmlRelationshipDetails($value);
451 $this->elementEnd($element);
455 $this->elementEnd('relationship');
458 function showXmlRelationshipDetails($details)
460 foreach($details as $element => $value) {
461 $this->element($element, null, $value);
465 function showTwitterXmlStatus($twitter_status, $tag='status')
467 $this->elementStart($tag);
468 foreach($twitter_status as $element => $value) {
471 $this->showTwitterXmlUser($twitter_status['user']);
474 $this->element($element, null, common_xml_safe_str($value));
477 $this->showXmlAttachments($twitter_status['attachments']);
480 $this->showGeoRSS($value);
482 case 'retweeted_status':
483 $this->showTwitterXmlStatus($value, 'retweeted_status');
486 $this->element($element, null, $value);
489 $this->elementEnd($tag);
492 function showTwitterXmlGroup($twitter_group)
494 $this->elementStart('group');
495 foreach($twitter_group as $element => $value) {
496 $this->element($element, null, $value);
498 $this->elementEnd('group');
501 function showTwitterXmlUser($twitter_user, $role='user')
503 $this->elementStart($role);
504 foreach($twitter_user as $element => $value) {
505 if ($element == 'status') {
506 $this->showTwitterXmlStatus($twitter_user['status']);
508 $this->element($element, null, $value);
511 $this->elementEnd($role);
514 function showXmlAttachments($attachments) {
515 if (!empty($attachments)) {
516 $this->elementStart('attachments', array('type' => 'array'));
517 foreach ($attachments as $attachment) {
519 $attrs['url'] = $attachment['url'];
520 $attrs['mimetype'] = $attachment['mimetype'];
521 $attrs['size'] = $attachment['size'];
522 $this->element('enclosure', $attrs, '');
524 $this->elementEnd('attachments');
528 function showGeoRSS($geo)
532 $this->element('geo');
534 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
535 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
536 $this->elementEnd('geo');
540 function showTwitterRssItem($entry)
542 $this->elementStart('item');
543 $this->element('title', null, $entry['title']);
544 $this->element('description', null, $entry['description']);
545 $this->element('pubDate', null, $entry['pubDate']);
546 $this->element('guid', null, $entry['guid']);
547 $this->element('link', null, $entry['link']);
549 # RSS only supports 1 enclosure per item
550 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
551 $enclosure = $entry['enclosures'][0];
552 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
555 if(array_key_exists('tags', $entry)){
556 foreach($entry['tags'] as $tag){
557 $this->element('category', null,$tag);
561 $this->showGeoRSS($entry['geo']);
562 $this->elementEnd('item');
565 function showJsonObjects($objects)
567 print(json_encode($objects));
570 function showSingleXmlStatus($notice)
572 $this->initDocument('xml');
573 $twitter_status = $this->twitterStatusArray($notice);
574 $this->showTwitterXmlStatus($twitter_status);
575 $this->endDocument('xml');
578 function show_single_json_status($notice)
580 $this->initDocument('json');
581 $status = $this->twitterStatusArray($notice);
582 $this->showJsonObjects($status);
583 $this->endDocument('json');
586 function showXmlTimeline($notice)
589 $this->initDocument('xml');
590 $this->elementStart('statuses', array('type' => 'array'));
592 if (is_array($notice)) {
593 foreach ($notice as $n) {
594 $twitter_status = $this->twitterStatusArray($n);
595 $this->showTwitterXmlStatus($twitter_status);
598 while ($notice->fetch()) {
599 $twitter_status = $this->twitterStatusArray($notice);
600 $this->showTwitterXmlStatus($twitter_status);
604 $this->elementEnd('statuses');
605 $this->endDocument('xml');
608 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
611 $this->initDocument('rss');
613 $this->element('title', null, $title);
614 $this->element('link', null, $link);
615 if (!is_null($suplink)) {
616 // For FriendFeed's SUP protocol
617 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
618 'rel' => 'http://api.friendfeed.com/2008/03#sup',
620 'type' => 'application/json'));
623 if (!is_null($logo)) {
624 $this->elementStart('image');
625 $this->element('link', null, $link);
626 $this->element('title', null, $title);
627 $this->element('url', null, $logo);
628 $this->elementEnd('image');
631 $this->element('description', null, $subtitle);
632 $this->element('language', null, 'en-us');
633 $this->element('ttl', null, '40');
635 if (is_array($notice)) {
636 foreach ($notice as $n) {
637 $entry = $this->twitterRssEntryArray($n);
638 $this->showTwitterRssItem($entry);
641 while ($notice->fetch()) {
642 $entry = $this->twitterRssEntryArray($notice);
643 $this->showTwitterRssItem($entry);
647 $this->endTwitterRss();
650 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
653 $this->initDocument('atom');
655 $this->element('title', null, $title);
656 $this->element('id', null, $id);
657 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
659 if (!is_null($logo)) {
660 $this->element('logo',null,$logo);
663 if (!is_null($suplink)) {
664 # For FriendFeed's SUP protocol
665 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
667 'type' => 'application/json'));
670 if (!is_null($selfuri)) {
671 $this->element('link', array('href' => $selfuri,
672 'rel' => 'self', 'type' => 'application/atom+xml'), null);
675 $this->element('updated', null, common_date_iso8601('now'));
676 $this->element('subtitle', null, $subtitle);
678 if (is_array($notice)) {
679 foreach ($notice as $n) {
680 $this->raw($n->asAtomEntry());
683 while ($notice->fetch()) {
684 $this->raw($notice->asAtomEntry());
688 $this->endDocument('atom');
692 function showRssGroups($group, $title, $link, $subtitle)
695 $this->initDocument('rss');
697 $this->element('title', null, $title);
698 $this->element('link', null, $link);
699 $this->element('description', null, $subtitle);
700 $this->element('language', null, 'en-us');
701 $this->element('ttl', null, '40');
703 if (is_array($group)) {
704 foreach ($group as $g) {
705 $twitter_group = $this->twitterRssGroupArray($g);
706 $this->showTwitterRssItem($twitter_group);
709 while ($group->fetch()) {
710 $twitter_group = $this->twitterRssGroupArray($group);
711 $this->showTwitterRssItem($twitter_group);
715 $this->endTwitterRss();
718 function showTwitterAtomEntry($entry)
720 $this->elementStart('entry');
721 $this->element('title', null, $entry['title']);
722 $this->element('content', array('type' => 'html'), $entry['content']);
723 $this->element('id', null, $entry['id']);
724 $this->element('published', null, $entry['published']);
725 $this->element('updated', null, $entry['updated']);
726 $this->element('link', array('type' => 'text/html',
727 'href' => $entry['link'],
728 'rel' => 'alternate'));
729 $this->element('link', array('type' => $entry['avatar-type'],
730 'href' => $entry['avatar'],
732 $this->elementStart('author');
734 $this->element('name', null, $entry['author-name']);
735 $this->element('uri', null, $entry['author-uri']);
737 $this->elementEnd('author');
738 $this->elementEnd('entry');
741 function showXmlDirectMessage($dm)
743 $this->elementStart('direct_message');
744 foreach($dm as $element => $value) {
748 $this->showTwitterXmlUser($value, $element);
751 $this->element($element, null, common_xml_safe_str($value));
754 $this->element($element, null, $value);
758 $this->elementEnd('direct_message');
761 function directMessageArray($message)
765 $from_profile = $message->getFrom();
766 $to_profile = $message->getTo();
768 $dmsg['id'] = $message->id;
769 $dmsg['sender_id'] = $message->from_profile;
770 $dmsg['text'] = trim($message->content);
771 $dmsg['recipient_id'] = $message->to_profile;
772 $dmsg['created_at'] = $this->dateTwitter($message->created);
773 $dmsg['sender_screen_name'] = $from_profile->nickname;
774 $dmsg['recipient_screen_name'] = $to_profile->nickname;
775 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
776 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
781 function rssDirectMessageArray($message)
785 $from = $message->getFrom();
787 $entry['title'] = sprintf('Message from %s to %s',
788 $from->nickname, $message->getTo()->nickname);
790 $entry['content'] = common_xml_safe_str($message->rendered);
791 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
792 $entry['published'] = common_date_iso8601($message->created);
794 $taguribase = common_config('integration', 'taguri');
796 $entry['id'] = "tag:$taguribase:$entry[link]";
797 $entry['updated'] = $entry['published'];
799 $entry['author-name'] = $from->getBestName();
800 $entry['author-uri'] = $from->homepage;
802 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
804 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
805 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
809 $entry['description'] = $entry['content'];
810 $entry['pubDate'] = common_date_rfc2822($message->created);
811 $entry['guid'] = $entry['link'];
816 function showSingleXmlDirectMessage($message)
818 $this->initDocument('xml');
819 $dmsg = $this->directMessageArray($message);
820 $this->showXmlDirectMessage($dmsg);
821 $this->endDocument('xml');
824 function showSingleJsonDirectMessage($message)
826 $this->initDocument('json');
827 $dmsg = $this->directMessageArray($message);
828 $this->showJsonObjects($dmsg);
829 $this->endDocument('json');
832 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
835 $this->initDocument('atom');
837 $this->element('title', null, $title);
838 $this->element('id', null, $id);
839 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
841 if (!is_null($selfuri)) {
842 $this->element('link', array('href' => $selfuri,
843 'rel' => 'self', 'type' => 'application/atom+xml'), null);
846 $this->element('updated', null, common_date_iso8601('now'));
847 $this->element('subtitle', null, $subtitle);
849 if (is_array($group)) {
850 foreach ($group as $g) {
851 $this->raw($g->asAtomEntry());
854 while ($group->fetch()) {
855 $this->raw($group->asAtomEntry());
859 $this->endDocument('atom');
863 function showJsonTimeline($notice)
866 $this->initDocument('json');
870 if (is_array($notice)) {
871 foreach ($notice as $n) {
872 $twitter_status = $this->twitterStatusArray($n);
873 array_push($statuses, $twitter_status);
876 while ($notice->fetch()) {
877 $twitter_status = $this->twitterStatusArray($notice);
878 array_push($statuses, $twitter_status);
882 $this->showJsonObjects($statuses);
884 $this->endDocument('json');
887 function showJsonGroups($group)
890 $this->initDocument('json');
894 if (is_array($group)) {
895 foreach ($group as $g) {
896 $twitter_group = $this->twitterGroupArray($g);
897 array_push($groups, $twitter_group);
900 while ($group->fetch()) {
901 $twitter_group = $this->twitterGroupArray($group);
902 array_push($groups, $twitter_group);
906 $this->showJsonObjects($groups);
908 $this->endDocument('json');
911 function showXmlGroups($group)
914 $this->initDocument('xml');
915 $this->elementStart('groups', array('type' => 'array'));
917 if (is_array($group)) {
918 foreach ($group as $g) {
919 $twitter_group = $this->twitterGroupArray($g);
920 $this->showTwitterXmlGroup($twitter_group);
923 while ($group->fetch()) {
924 $twitter_group = $this->twitterGroupArray($group);
925 $this->showTwitterXmlGroup($twitter_group);
929 $this->elementEnd('groups');
930 $this->endDocument('xml');
933 function showTwitterXmlUsers($user)
936 $this->initDocument('xml');
937 $this->elementStart('users', array('type' => 'array'));
939 if (is_array($user)) {
940 foreach ($user as $u) {
941 $twitter_user = $this->twitterUserArray($u);
942 $this->showTwitterXmlUser($twitter_user);
945 while ($user->fetch()) {
946 $twitter_user = $this->twitterUserArray($user);
947 $this->showTwitterXmlUser($twitter_user);
951 $this->elementEnd('users');
952 $this->endDocument('xml');
955 function showJsonUsers($user)
958 $this->initDocument('json');
962 if (is_array($user)) {
963 foreach ($user as $u) {
964 $twitter_user = $this->twitterUserArray($u);
965 array_push($users, $twitter_user);
968 while ($user->fetch()) {
969 $twitter_user = $this->twitterUserArray($user);
970 array_push($users, $twitter_user);
974 $this->showJsonObjects($users);
976 $this->endDocument('json');
979 function showSingleJsonGroup($group)
981 $this->initDocument('json');
982 $twitter_group = $this->twitterGroupArray($group);
983 $this->showJsonObjects($twitter_group);
984 $this->endDocument('json');
987 function showSingleXmlGroup($group)
989 $this->initDocument('xml');
990 $twitter_group = $this->twitterGroupArray($group);
991 $this->showTwitterXmlGroup($twitter_group);
992 $this->endDocument('xml');
995 function dateTwitter($dt)
997 $dateStr = date('d F Y H:i:s', strtotime($dt));
998 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
999 $d->setTimezone(new DateTimeZone(common_timezone()));
1000 return $d->format('D M d H:i:s O Y');
1003 function initDocument($type='xml')
1007 header('Content-Type: application/xml; charset=utf-8');
1011 header('Content-Type: application/json; charset=utf-8');
1013 // Check for JSONP callback
1014 $callback = $this->arg('callback');
1016 print $callback . '(';
1020 header("Content-Type: application/rss+xml; charset=utf-8");
1021 $this->initTwitterRss();
1024 header('Content-Type: application/atom+xml; charset=utf-8');
1025 $this->initTwitterAtom();
1028 $this->clientError(_('Not a supported data format.'));
1035 function endDocument($type='xml')
1043 // Check for JSONP callback
1044 $callback = $this->arg('callback');
1050 $this->endTwitterRss();
1053 $this->endTwitterRss();
1056 $this->clientError(_('Not a supported data format.'));
1062 function clientError($msg, $code = 400, $format = 'xml')
1064 $action = $this->trimmed('action');
1066 common_debug("User error '$code' on '$action': $msg", __FILE__);
1068 if (!array_key_exists($code, ClientErrorAction::$status)) {
1072 $status_string = ClientErrorAction::$status[$code];
1074 header('HTTP/1.1 '.$code.' '.$status_string);
1076 if ($format == 'xml') {
1077 $this->initDocument('xml');
1078 $this->elementStart('hash');
1079 $this->element('error', null, $msg);
1080 $this->element('request', null, $_SERVER['REQUEST_URI']);
1081 $this->elementEnd('hash');
1082 $this->endDocument('xml');
1083 } elseif ($format == 'json'){
1084 $this->initDocument('json');
1085 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1086 print(json_encode($error_array));
1087 $this->endDocument('json');
1090 // If user didn't request a useful format, throw a regular client error
1091 throw new ClientException($msg, $code);
1095 function serverError($msg, $code = 500, $content_type = 'json')
1097 $action = $this->trimmed('action');
1099 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1101 if (!array_key_exists($code, ServerErrorAction::$status)) {
1105 $status_string = ServerErrorAction::$status[$code];
1107 header('HTTP/1.1 '.$code.' '.$status_string);
1109 if ($content_type == 'xml') {
1110 $this->initDocument('xml');
1111 $this->elementStart('hash');
1112 $this->element('error', null, $msg);
1113 $this->element('request', null, $_SERVER['REQUEST_URI']);
1114 $this->elementEnd('hash');
1115 $this->endDocument('xml');
1117 $this->initDocument('json');
1118 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1119 print(json_encode($error_array));
1120 $this->endDocument('json');
1124 function initTwitterRss()
1127 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1128 $this->elementStart('channel');
1129 Event::handle('StartApiRss', array($this));
1132 function endTwitterRss()
1134 $this->elementEnd('channel');
1135 $this->elementEnd('rss');
1139 function initTwitterAtom()
1142 // FIXME: don't hardcode the language here!
1143 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1144 'xml:lang' => 'en-US',
1145 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1146 Event::handle('StartApiAtom', array($this));
1149 function endTwitterAtom()
1151 $this->elementEnd('feed');
1155 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1157 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1158 switch ($content_type) {
1160 $this->showTwitterXmlUser($profile_array);
1163 $this->showJsonObjects($profile_array);
1166 $this->clientError(_('Not a supported data format.'));
1172 function getTargetUser($id)
1176 // Twitter supports these other ways of passing the user ID
1177 if (is_numeric($this->arg('id'))) {
1178 return User::staticGet($this->arg('id'));
1179 } else if ($this->arg('id')) {
1180 $nickname = common_canonical_nickname($this->arg('id'));
1181 return User::staticGet('nickname', $nickname);
1182 } else if ($this->arg('user_id')) {
1183 // This is to ensure that a non-numeric user_id still
1184 // overrides screen_name even if it doesn't get used
1185 if (is_numeric($this->arg('user_id'))) {
1186 return User::staticGet('id', $this->arg('user_id'));
1188 } else if ($this->arg('screen_name')) {
1189 $nickname = common_canonical_nickname($this->arg('screen_name'));
1190 return User::staticGet('nickname', $nickname);
1192 // Fall back to trying the currently authenticated user
1193 return $this->auth_user;
1196 } else if (is_numeric($id)) {
1197 return User::staticGet($id);
1199 $nickname = common_canonical_nickname($id);
1200 return User::staticGet('nickname', $nickname);
1204 function getTargetGroup($id)
1207 if (is_numeric($this->arg('id'))) {
1208 return User_group::staticGet($this->arg('id'));
1209 } else if ($this->arg('id')) {
1210 $nickname = common_canonical_nickname($this->arg('id'));
1211 return User_group::staticGet('nickname', $nickname);
1212 } else if ($this->arg('group_id')) {
1213 // This is to ensure that a non-numeric user_id still
1214 // overrides screen_name even if it doesn't get used
1215 if (is_numeric($this->arg('group_id'))) {
1216 return User_group::staticGet('id', $this->arg('group_id'));
1218 } else if ($this->arg('group_name')) {
1219 $nickname = common_canonical_nickname($this->arg('group_name'));
1220 return User_group::staticGet('nickname', $nickname);
1223 } else if (is_numeric($id)) {
1224 return User_group::staticGet($id);
1226 $nickname = common_canonical_nickname($id);
1227 return User_group::staticGet('nickname', $nickname);
1231 function sourceLink($source)
1233 $source_name = _($source);
1242 $ns = Notice_source::staticGet($source);
1244 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1248 return $source_name;
1252 * Returns query argument or default value if not found. Certain
1253 * parameters used throughout the API are lightly scrubbed and
1254 * bounds checked. This overrides Action::arg().
1256 * @param string $key requested argument
1257 * @param string $def default value to return if $key is not provided
1261 function arg($key, $def=null)
1264 // XXX: Do even more input validation/scrubbing?
1266 if (array_key_exists($key, $this->args)) {
1269 $page = (int)$this->args['page'];
1270 return ($page < 1) ? 1 : $page;
1272 $count = (int)$this->args['count'];
1275 } elseif ($count > 200) {
1281 $since_id = (int)$this->args['since_id'];
1282 return ($since_id < 1) ? 0 : $since_id;
1284 $max_id = (int)$this->args['max_id'];
1285 return ($max_id < 1) ? 0 : $max_id;
1287 return strtotime($this->args['since']);
1289 return parent::arg($key, $def);