3 * StatusNet, the distributed open-source microblogging tool
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Dan Moore <dan@moore.cx>
26 * @author Evan Prodromou <evan@status.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Toby Inkster <mail@tobyinkster.co.uk>
29 * @author Zach Copley <zach@status.net>
30 * @copyright 2009 StatusNet, Inc.
31 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
32 * @link http://status.net/
35 if (!defined('STATUSNET')) {
40 * Contains most of the Twitter-compatible API output functions.
44 * @author Craig Andrews <candrews@integralblue.com>
45 * @author Dan Moore <dan@moore.cx>
46 * @author Evan Prodromou <evan@status.net>
47 * @author Jeffery To <jeffery.to@gmail.com>
48 * @author Toby Inkster <mail@tobyinkster.co.uk>
49 * @author Zach Copley <zach@status.net>
50 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51 * @link http://status.net/
54 class ApiAction extends Action
58 var $auth_user = null;
68 * @param array $args Web and URL arguments
70 * @return boolean false if user doesn't exist
73 function prepare($args)
75 parent::prepare($args);
77 $this->format = $this->arg('format');
78 $this->page = (int)$this->arg('page', 1);
79 $this->count = (int)$this->arg('count', 20);
80 $this->max_id = (int)$this->arg('max_id', 0);
81 $this->since_id = (int)$this->arg('since_id', 0);
82 $this->since = $this->arg('since');
90 * @param array $args Arguments from $_REQUEST
95 function handle($args)
97 parent::handle($args);
101 * Overrides XMLOutputter::element to write booleans as strings (true|false).
102 * See that method's documentation for more info.
104 * @param string $tag Element type or tagname
105 * @param array $attrs Array of element attributes, as
107 * @param string $content string content of the element
111 function element($tag, $attrs=null, $content=null)
113 if (is_bool($content)) {
114 $content = ($content ? 'true' : 'false');
117 return parent::element($tag, $attrs, $content);
120 function twitterUserArray($profile, $get_notice=false)
122 $twitter_user = array();
124 $twitter_user['id'] = intval($profile->id);
125 $twitter_user['name'] = $profile->getBestName();
126 $twitter_user['screen_name'] = $profile->nickname;
127 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
128 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
130 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
131 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
132 Avatar::defaultImage(AVATAR_STREAM_SIZE);
134 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
135 $twitter_user['protected'] = false; # not supported by StatusNet yet
136 $twitter_user['followers_count'] = $profile->subscriberCount();
139 $user = $profile->getUser();
141 // Note: some profiles don't have an associated user
143 $defaultDesign = Design::siteDesign();
146 $design = $user->getDesign();
149 if (empty($design)) {
150 $design = $defaultDesign;
153 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
154 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
155 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
156 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
157 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
158 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
159 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
160 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
161 $twitter_user['profile_sidebar_border_color'] = '';
163 $twitter_user['friends_count'] = $profile->subscriptionCount();
165 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
167 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
171 if (!empty($user) && $user->timezone) {
172 $timezone = $user->timezone;
176 $t->setTimezone(new DateTimeZone($timezone));
178 $twitter_user['utc_offset'] = $t->format('Z');
179 $twitter_user['time_zone'] = $timezone;
181 $twitter_user['profile_background_image_url']
182 = empty($design->backgroundimage)
183 ? '' : ($design->disposition & BACKGROUND_ON)
184 ? Design::url($design->backgroundimage) : '';
186 $twitter_user['profile_background_tile']
187 = empty($design->disposition)
188 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
190 $twitter_user['statuses_count'] = $profile->noticeCount();
192 // Is the requesting user following this user?
193 $twitter_user['following'] = false;
194 $twitter_user['notifications'] = false;
196 if (isset($this->auth_user)) {
198 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
201 $sub = Subscription::pkeyGet(array('subscriber' =>
202 $this->auth_user->id,
203 'subscribed' => $profile->id));
206 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
211 $notice = $profile->getCurrentNotice();
214 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
218 return $twitter_user;
221 function twitterStatusArray($notice, $include_user=true)
223 $base = $this->twitterSimpleStatusArray($notice, $include_user);
225 if (!empty($notice->repeat_of)) {
226 $original = Notice::staticGet('id', $notice->repeat_of);
227 if (!empty($original)) {
228 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
229 $base['retweeted_status'] = $original_array;
236 function twitterSimpleStatusArray($notice, $include_user=true)
238 $profile = $notice->getProfile();
240 $twitter_status = array();
241 $twitter_status['text'] = $notice->content;
242 $twitter_status['truncated'] = false; # Not possible on StatusNet
243 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
244 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
245 intval($notice->reply_to) : null;
246 $twitter_status['source'] = $this->sourceLink($notice->source);
247 $twitter_status['id'] = intval($notice->id);
249 $replier_profile = null;
251 if ($notice->reply_to) {
252 $reply = Notice::staticGet(intval($notice->reply_to));
254 $replier_profile = $reply->getProfile();
258 $twitter_status['in_reply_to_user_id'] =
259 ($replier_profile) ? intval($replier_profile->id) : null;
260 $twitter_status['in_reply_to_screen_name'] =
261 ($replier_profile) ? $replier_profile->nickname : null;
263 if (isset($notice->lat) && isset($notice->lon)) {
264 // This is the format that GeoJSON expects stuff to be in
265 $twitter_status['geo'] = array('type' => 'Point',
266 'coordinates' => array((float) $notice->lat,
267 (float) $notice->lon));
269 $twitter_status['geo'] = null;
272 if (isset($this->auth_user)) {
273 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
275 $twitter_status['favorited'] = false;
279 $attachments = $notice->attachments();
281 if (!empty($attachments)) {
283 $twitter_status['attachments'] = array();
285 foreach ($attachments as $attachment) {
286 if ($attachment->isEnclosure()) {
287 $enclosure = array();
288 $enclosure['url'] = $attachment->url;
289 $enclosure['mimetype'] = $attachment->mimetype;
290 $enclosure['size'] = $attachment->size;
291 $twitter_status['attachments'][] = $enclosure;
297 # Don't get notice (recursive!)
298 $twitter_user = $this->twitterUserArray($profile, false);
299 $twitter_status['user'] = $twitter_user;
302 return $twitter_status;
305 function twitterGroupArray($group)
307 $twitter_group=array();
308 $twitter_group['id']=$group->id;
309 $twitter_group['url']=$group->permalink();
310 $twitter_group['nickname']=$group->nickname;
311 $twitter_group['fullname']=$group->fullname;
312 $twitter_group['homepage_url']=$group->homepage_url;
313 $twitter_group['original_logo']=$group->original_logo;
314 $twitter_group['homepage_logo']=$group->homepage_logo;
315 $twitter_group['stream_logo']=$group->stream_logo;
316 $twitter_group['mini_logo']=$group->mini_logo;
317 $twitter_group['homepage']=$group->homepage;
318 $twitter_group['description']=$group->description;
319 $twitter_group['location']=$group->location;
320 $twitter_group['created']=$this->dateTwitter($group->created);
321 $twitter_group['modified']=$this->dateTwitter($group->modified);
322 return $twitter_group;
325 function twitterRssGroupArray($group)
328 $entry['content']=$group->description;
329 $entry['title']=$group->nickname;
330 $entry['link']=$group->permalink();
331 $entry['published']=common_date_iso8601($group->created);
332 $entry['updated']==common_date_iso8601($group->modified);
333 $taguribase = common_config('integration', 'groupuri');
334 $entry['id'] = "group:$groupuribase:$entry[link]";
336 $entry['description'] = $entry['content'];
337 $entry['pubDate'] = common_date_rfc2822($group->created);
338 $entry['guid'] = $entry['link'];
343 function twitterRssEntryArray($notice)
345 $profile = $notice->getProfile();
348 // We trim() to avoid extraneous whitespace in the output
350 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
351 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
352 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
353 $entry['published'] = common_date_iso8601($notice->created);
355 $taguribase = common_config('integration', 'taguri');
356 $entry['id'] = "tag:$taguribase:$entry[link]";
358 $entry['updated'] = $entry['published'];
359 $entry['author'] = $profile->getBestName();
362 $attachments = $notice->attachments();
363 $enclosures = array();
365 foreach ($attachments as $attachment) {
366 $enclosure_o=$attachment->getEnclosure();
368 $enclosure = array();
369 $enclosure['url'] = $enclosure_o->url;
370 $enclosure['mimetype'] = $enclosure_o->mimetype;
371 $enclosure['size'] = $enclosure_o->size;
372 $enclosures[] = $enclosure;
376 if (!empty($enclosures)) {
377 $entry['enclosures'] = $enclosures;
381 $tag = new Notice_tag();
382 $tag->notice_id = $notice->id;
384 $entry['tags']=array();
385 while ($tag->fetch()) {
386 $entry['tags'][]=$tag->tag;
392 $entry['description'] = $entry['content'];
393 $entry['pubDate'] = common_date_rfc2822($notice->created);
394 $entry['guid'] = $entry['link'];
396 if (isset($notice->lat) && isset($notice->lon)) {
397 // This is the format that GeoJSON expects stuff to be in.
398 // showGeoRSS() below uses it for XML output, so we reuse it
399 $entry['geo'] = array('type' => 'Point',
400 'coordinates' => array((float) $notice->lat,
401 (float) $notice->lon));
403 $entry['geo'] = null;
409 function twitterRelationshipArray($source, $target)
411 $relationship = array();
413 $relationship['source'] =
414 $this->relationshipDetailsArray($source, $target);
415 $relationship['target'] =
416 $this->relationshipDetailsArray($target, $source);
418 return array('relationship' => $relationship);
421 function relationshipDetailsArray($source, $target)
425 $details['screen_name'] = $source->nickname;
426 $details['followed_by'] = $target->isSubscribed($source);
427 $details['following'] = $source->isSubscribed($target);
429 $notifications = false;
431 if ($source->isSubscribed($target)) {
433 $sub = Subscription::pkeyGet(array('subscriber' =>
434 $source->id, 'subscribed' => $target->id));
437 $notifications = ($sub->jabber || $sub->sms);
441 $details['notifications_enabled'] = $notifications;
442 $details['blocking'] = $source->hasBlocked($target);
443 $details['id'] = $source->id;
448 function showTwitterXmlRelationship($relationship)
450 $this->elementStart('relationship');
452 foreach($relationship as $element => $value) {
453 if ($element == 'source' || $element == 'target') {
454 $this->elementStart($element);
455 $this->showXmlRelationshipDetails($value);
456 $this->elementEnd($element);
460 $this->elementEnd('relationship');
463 function showXmlRelationshipDetails($details)
465 foreach($details as $element => $value) {
466 $this->element($element, null, $value);
470 function showTwitterXmlStatus($twitter_status, $tag='status')
472 $this->elementStart($tag);
473 foreach($twitter_status as $element => $value) {
476 $this->showTwitterXmlUser($twitter_status['user']);
479 $this->element($element, null, common_xml_safe_str($value));
482 $this->showXmlAttachments($twitter_status['attachments']);
485 $this->showGeoRSS($value);
487 case 'retweeted_status':
488 $this->showTwitterXmlStatus($value, 'retweeted_status');
491 $this->element($element, null, $value);
494 $this->elementEnd($tag);
497 function showTwitterXmlGroup($twitter_group)
499 $this->elementStart('group');
500 foreach($twitter_group as $element => $value) {
501 $this->element($element, null, $value);
503 $this->elementEnd('group');
506 function showTwitterXmlUser($twitter_user, $role='user')
508 $this->elementStart($role);
509 foreach($twitter_user as $element => $value) {
510 if ($element == 'status') {
511 $this->showTwitterXmlStatus($twitter_user['status']);
513 $this->element($element, null, $value);
516 $this->elementEnd($role);
519 function showXmlAttachments($attachments) {
520 if (!empty($attachments)) {
521 $this->elementStart('attachments', array('type' => 'array'));
522 foreach ($attachments as $attachment) {
524 $attrs['url'] = $attachment['url'];
525 $attrs['mimetype'] = $attachment['mimetype'];
526 $attrs['size'] = $attachment['size'];
527 $this->element('enclosure', $attrs, '');
529 $this->elementEnd('attachments');
533 function showGeoRSS($geo)
537 $this->element('geo');
539 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
540 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
541 $this->elementEnd('geo');
545 function showTwitterRssItem($entry)
547 $this->elementStart('item');
548 $this->element('title', null, $entry['title']);
549 $this->element('description', null, $entry['description']);
550 $this->element('pubDate', null, $entry['pubDate']);
551 $this->element('guid', null, $entry['guid']);
552 $this->element('link', null, $entry['link']);
554 # RSS only supports 1 enclosure per item
555 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
556 $enclosure = $entry['enclosures'][0];
557 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
560 if(array_key_exists('tags', $entry)){
561 foreach($entry['tags'] as $tag){
562 $this->element('category', null,$tag);
566 $this->showGeoRSS($entry['geo']);
567 $this->elementEnd('item');
570 function showJsonObjects($objects)
572 print(json_encode($objects));
575 function showSingleXmlStatus($notice)
577 $this->initDocument('xml');
578 $twitter_status = $this->twitterStatusArray($notice);
579 $this->showTwitterXmlStatus($twitter_status);
580 $this->endDocument('xml');
583 function show_single_json_status($notice)
585 $this->initDocument('json');
586 $status = $this->twitterStatusArray($notice);
587 $this->showJsonObjects($status);
588 $this->endDocument('json');
591 function showXmlTimeline($notice)
594 $this->initDocument('xml');
595 $this->elementStart('statuses', array('type' => 'array'));
597 if (is_array($notice)) {
598 foreach ($notice as $n) {
599 $twitter_status = $this->twitterStatusArray($n);
600 $this->showTwitterXmlStatus($twitter_status);
603 while ($notice->fetch()) {
604 $twitter_status = $this->twitterStatusArray($notice);
605 $this->showTwitterXmlStatus($twitter_status);
609 $this->elementEnd('statuses');
610 $this->endDocument('xml');
613 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
616 $this->initDocument('rss');
618 $this->element('title', null, $title);
619 $this->element('link', null, $link);
620 if (!is_null($suplink)) {
621 // For FriendFeed's SUP protocol
622 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
623 'rel' => 'http://api.friendfeed.com/2008/03#sup',
625 'type' => 'application/json'));
628 if (!is_null($logo)) {
629 $this->elementStart('image');
630 $this->element('link', null, $link);
631 $this->element('title', null, $title);
632 $this->element('url', null, $logo);
633 $this->elementEnd('image');
636 $this->element('description', null, $subtitle);
637 $this->element('language', null, 'en-us');
638 $this->element('ttl', null, '40');
640 if (is_array($notice)) {
641 foreach ($notice as $n) {
642 $entry = $this->twitterRssEntryArray($n);
643 $this->showTwitterRssItem($entry);
646 while ($notice->fetch()) {
647 $entry = $this->twitterRssEntryArray($notice);
648 $this->showTwitterRssItem($entry);
652 $this->endTwitterRss();
655 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
658 $this->initDocument('atom');
660 $this->element('title', null, $title);
661 $this->element('id', null, $id);
662 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
664 if (!is_null($logo)) {
665 $this->element('logo',null,$logo);
668 if (!is_null($suplink)) {
669 # For FriendFeed's SUP protocol
670 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
672 'type' => 'application/json'));
675 if (!is_null($selfuri)) {
676 $this->element('link', array('href' => $selfuri,
677 'rel' => 'self', 'type' => 'application/atom+xml'), null);
680 $this->element('updated', null, common_date_iso8601('now'));
681 $this->element('subtitle', null, $subtitle);
683 if (is_array($notice)) {
684 foreach ($notice as $n) {
685 $this->raw($n->asAtomEntry());
688 while ($notice->fetch()) {
689 $this->raw($notice->asAtomEntry());
693 $this->endDocument('atom');
697 function showRssGroups($group, $title, $link, $subtitle)
700 $this->initDocument('rss');
702 $this->element('title', null, $title);
703 $this->element('link', null, $link);
704 $this->element('description', null, $subtitle);
705 $this->element('language', null, 'en-us');
706 $this->element('ttl', null, '40');
708 if (is_array($group)) {
709 foreach ($group as $g) {
710 $twitter_group = $this->twitterRssGroupArray($g);
711 $this->showTwitterRssItem($twitter_group);
714 while ($group->fetch()) {
715 $twitter_group = $this->twitterRssGroupArray($group);
716 $this->showTwitterRssItem($twitter_group);
720 $this->endTwitterRss();
723 function showTwitterAtomEntry($entry)
725 $this->elementStart('entry');
726 $this->element('title', null, $entry['title']);
727 $this->element('content', array('type' => 'html'), $entry['content']);
728 $this->element('id', null, $entry['id']);
729 $this->element('published', null, $entry['published']);
730 $this->element('updated', null, $entry['updated']);
731 $this->element('link', array('type' => 'text/html',
732 'href' => $entry['link'],
733 'rel' => 'alternate'));
734 $this->element('link', array('type' => $entry['avatar-type'],
735 'href' => $entry['avatar'],
737 $this->elementStart('author');
739 $this->element('name', null, $entry['author-name']);
740 $this->element('uri', null, $entry['author-uri']);
742 $this->elementEnd('author');
743 $this->elementEnd('entry');
746 function showXmlDirectMessage($dm)
748 $this->elementStart('direct_message');
749 foreach($dm as $element => $value) {
753 $this->showTwitterXmlUser($value, $element);
756 $this->element($element, null, common_xml_safe_str($value));
759 $this->element($element, null, $value);
763 $this->elementEnd('direct_message');
766 function directMessageArray($message)
770 $from_profile = $message->getFrom();
771 $to_profile = $message->getTo();
773 $dmsg['id'] = $message->id;
774 $dmsg['sender_id'] = $message->from_profile;
775 $dmsg['text'] = trim($message->content);
776 $dmsg['recipient_id'] = $message->to_profile;
777 $dmsg['created_at'] = $this->dateTwitter($message->created);
778 $dmsg['sender_screen_name'] = $from_profile->nickname;
779 $dmsg['recipient_screen_name'] = $to_profile->nickname;
780 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
781 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
786 function rssDirectMessageArray($message)
790 $from = $message->getFrom();
792 $entry['title'] = sprintf('Message from %1$s to %2$s',
793 $from->nickname, $message->getTo()->nickname);
795 $entry['content'] = common_xml_safe_str($message->rendered);
796 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
797 $entry['published'] = common_date_iso8601($message->created);
799 $taguribase = common_config('integration', 'taguri');
801 $entry['id'] = "tag:$taguribase:$entry[link]";
802 $entry['updated'] = $entry['published'];
804 $entry['author-name'] = $from->getBestName();
805 $entry['author-uri'] = $from->homepage;
807 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
809 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
810 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
814 $entry['description'] = $entry['content'];
815 $entry['pubDate'] = common_date_rfc2822($message->created);
816 $entry['guid'] = $entry['link'];
821 function showSingleXmlDirectMessage($message)
823 $this->initDocument('xml');
824 $dmsg = $this->directMessageArray($message);
825 $this->showXmlDirectMessage($dmsg);
826 $this->endDocument('xml');
829 function showSingleJsonDirectMessage($message)
831 $this->initDocument('json');
832 $dmsg = $this->directMessageArray($message);
833 $this->showJsonObjects($dmsg);
834 $this->endDocument('json');
837 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
840 $this->initDocument('atom');
842 $this->element('title', null, $title);
843 $this->element('id', null, $id);
844 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
846 if (!is_null($selfuri)) {
847 $this->element('link', array('href' => $selfuri,
848 'rel' => 'self', 'type' => 'application/atom+xml'), null);
851 $this->element('updated', null, common_date_iso8601('now'));
852 $this->element('subtitle', null, $subtitle);
854 if (is_array($group)) {
855 foreach ($group as $g) {
856 $this->raw($g->asAtomEntry());
859 while ($group->fetch()) {
860 $this->raw($group->asAtomEntry());
864 $this->endDocument('atom');
868 function showJsonTimeline($notice)
871 $this->initDocument('json');
875 if (is_array($notice)) {
876 foreach ($notice as $n) {
877 $twitter_status = $this->twitterStatusArray($n);
878 array_push($statuses, $twitter_status);
881 while ($notice->fetch()) {
882 $twitter_status = $this->twitterStatusArray($notice);
883 array_push($statuses, $twitter_status);
887 $this->showJsonObjects($statuses);
889 $this->endDocument('json');
892 function showJsonGroups($group)
895 $this->initDocument('json');
899 if (is_array($group)) {
900 foreach ($group as $g) {
901 $twitter_group = $this->twitterGroupArray($g);
902 array_push($groups, $twitter_group);
905 while ($group->fetch()) {
906 $twitter_group = $this->twitterGroupArray($group);
907 array_push($groups, $twitter_group);
911 $this->showJsonObjects($groups);
913 $this->endDocument('json');
916 function showXmlGroups($group)
919 $this->initDocument('xml');
920 $this->elementStart('groups', array('type' => 'array'));
922 if (is_array($group)) {
923 foreach ($group as $g) {
924 $twitter_group = $this->twitterGroupArray($g);
925 $this->showTwitterXmlGroup($twitter_group);
928 while ($group->fetch()) {
929 $twitter_group = $this->twitterGroupArray($group);
930 $this->showTwitterXmlGroup($twitter_group);
934 $this->elementEnd('groups');
935 $this->endDocument('xml');
938 function showTwitterXmlUsers($user)
941 $this->initDocument('xml');
942 $this->elementStart('users', array('type' => 'array'));
944 if (is_array($user)) {
945 foreach ($user as $u) {
946 $twitter_user = $this->twitterUserArray($u);
947 $this->showTwitterXmlUser($twitter_user);
950 while ($user->fetch()) {
951 $twitter_user = $this->twitterUserArray($user);
952 $this->showTwitterXmlUser($twitter_user);
956 $this->elementEnd('users');
957 $this->endDocument('xml');
960 function showJsonUsers($user)
963 $this->initDocument('json');
967 if (is_array($user)) {
968 foreach ($user as $u) {
969 $twitter_user = $this->twitterUserArray($u);
970 array_push($users, $twitter_user);
973 while ($user->fetch()) {
974 $twitter_user = $this->twitterUserArray($user);
975 array_push($users, $twitter_user);
979 $this->showJsonObjects($users);
981 $this->endDocument('json');
984 function showSingleJsonGroup($group)
986 $this->initDocument('json');
987 $twitter_group = $this->twitterGroupArray($group);
988 $this->showJsonObjects($twitter_group);
989 $this->endDocument('json');
992 function showSingleXmlGroup($group)
994 $this->initDocument('xml');
995 $twitter_group = $this->twitterGroupArray($group);
996 $this->showTwitterXmlGroup($twitter_group);
997 $this->endDocument('xml');
1000 function dateTwitter($dt)
1002 $dateStr = date('d F Y H:i:s', strtotime($dt));
1003 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1004 $d->setTimezone(new DateTimeZone(common_timezone()));
1005 return $d->format('D M d H:i:s O Y');
1008 function initDocument($type='xml')
1012 header('Content-Type: application/xml; charset=utf-8');
1016 header('Content-Type: application/json; charset=utf-8');
1018 // Check for JSONP callback
1019 $callback = $this->arg('callback');
1021 print $callback . '(';
1025 header("Content-Type: application/rss+xml; charset=utf-8");
1026 $this->initTwitterRss();
1029 header('Content-Type: application/atom+xml; charset=utf-8');
1030 $this->initTwitterAtom();
1033 $this->clientError(_('Not a supported data format.'));
1040 function endDocument($type='xml')
1048 // Check for JSONP callback
1049 $callback = $this->arg('callback');
1055 $this->endTwitterRss();
1058 $this->endTwitterRss();
1061 $this->clientError(_('Not a supported data format.'));
1067 function clientError($msg, $code = 400, $format = 'xml')
1069 $action = $this->trimmed('action');
1071 common_debug("User error '$code' on '$action': $msg", __FILE__);
1073 if (!array_key_exists($code, ClientErrorAction::$status)) {
1077 $status_string = ClientErrorAction::$status[$code];
1079 header('HTTP/1.1 '.$code.' '.$status_string);
1081 if ($format == 'xml') {
1082 $this->initDocument('xml');
1083 $this->elementStart('hash');
1084 $this->element('error', null, $msg);
1085 $this->element('request', null, $_SERVER['REQUEST_URI']);
1086 $this->elementEnd('hash');
1087 $this->endDocument('xml');
1088 } elseif ($format == 'json'){
1089 $this->initDocument('json');
1090 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1091 print(json_encode($error_array));
1092 $this->endDocument('json');
1095 // If user didn't request a useful format, throw a regular client error
1096 throw new ClientException($msg, $code);
1100 function serverError($msg, $code = 500, $content_type = 'json')
1102 $action = $this->trimmed('action');
1104 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1106 if (!array_key_exists($code, ServerErrorAction::$status)) {
1110 $status_string = ServerErrorAction::$status[$code];
1112 header('HTTP/1.1 '.$code.' '.$status_string);
1114 if ($content_type == 'xml') {
1115 $this->initDocument('xml');
1116 $this->elementStart('hash');
1117 $this->element('error', null, $msg);
1118 $this->element('request', null, $_SERVER['REQUEST_URI']);
1119 $this->elementEnd('hash');
1120 $this->endDocument('xml');
1122 $this->initDocument('json');
1123 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1124 print(json_encode($error_array));
1125 $this->endDocument('json');
1129 function initTwitterRss()
1132 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1133 $this->elementStart('channel');
1134 Event::handle('StartApiRss', array($this));
1137 function endTwitterRss()
1139 $this->elementEnd('channel');
1140 $this->elementEnd('rss');
1144 function initTwitterAtom()
1147 // FIXME: don't hardcode the language here!
1148 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1149 'xml:lang' => 'en-US',
1150 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1151 Event::handle('StartApiAtom', array($this));
1154 function endTwitterAtom()
1156 $this->elementEnd('feed');
1160 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1162 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1163 switch ($content_type) {
1165 $this->showTwitterXmlUser($profile_array);
1168 $this->showJsonObjects($profile_array);
1171 $this->clientError(_('Not a supported data format.'));
1177 function getTargetUser($id)
1181 // Twitter supports these other ways of passing the user ID
1182 if (is_numeric($this->arg('id'))) {
1183 return User::staticGet($this->arg('id'));
1184 } else if ($this->arg('id')) {
1185 $nickname = common_canonical_nickname($this->arg('id'));
1186 return User::staticGet('nickname', $nickname);
1187 } else if ($this->arg('user_id')) {
1188 // This is to ensure that a non-numeric user_id still
1189 // overrides screen_name even if it doesn't get used
1190 if (is_numeric($this->arg('user_id'))) {
1191 return User::staticGet('id', $this->arg('user_id'));
1193 } else if ($this->arg('screen_name')) {
1194 $nickname = common_canonical_nickname($this->arg('screen_name'));
1195 return User::staticGet('nickname', $nickname);
1197 // Fall back to trying the currently authenticated user
1198 return $this->auth_user;
1201 } else if (is_numeric($id)) {
1202 return User::staticGet($id);
1204 $nickname = common_canonical_nickname($id);
1205 return User::staticGet('nickname', $nickname);
1209 function getTargetGroup($id)
1212 if (is_numeric($this->arg('id'))) {
1213 return User_group::staticGet($this->arg('id'));
1214 } else if ($this->arg('id')) {
1215 $nickname = common_canonical_nickname($this->arg('id'));
1216 return User_group::staticGet('nickname', $nickname);
1217 } else if ($this->arg('group_id')) {
1218 // This is to ensure that a non-numeric user_id still
1219 // overrides screen_name even if it doesn't get used
1220 if (is_numeric($this->arg('group_id'))) {
1221 return User_group::staticGet('id', $this->arg('group_id'));
1223 } else if ($this->arg('group_name')) {
1224 $nickname = common_canonical_nickname($this->arg('group_name'));
1225 return User_group::staticGet('nickname', $nickname);
1228 } else if (is_numeric($id)) {
1229 return User_group::staticGet($id);
1231 $nickname = common_canonical_nickname($id);
1232 return User_group::staticGet('nickname', $nickname);
1236 function sourceLink($source)
1238 $source_name = _($source);
1247 $ns = Notice_source::staticGet($source);
1249 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1253 return $source_name;
1257 * Returns query argument or default value if not found. Certain
1258 * parameters used throughout the API are lightly scrubbed and
1259 * bounds checked. This overrides Action::arg().
1261 * @param string $key requested argument
1262 * @param string $def default value to return if $key is not provided
1266 function arg($key, $def=null)
1269 // XXX: Do even more input validation/scrubbing?
1271 if (array_key_exists($key, $this->args)) {
1274 $page = (int)$this->args['page'];
1275 return ($page < 1) ? 1 : $page;
1277 $count = (int)$this->args['count'];
1280 } elseif ($count > 200) {
1286 $since_id = (int)$this->args['since_id'];
1287 return ($since_id < 1) ? 0 : $since_id;
1289 $max_id = (int)$this->args['max_id'];
1290 return ($max_id < 1) ? 0 : $max_id;
1292 return strtotime($this->args['since']);
1294 return parent::arg($key, $def);