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
61 var $auth_user = null;
68 var $access = self::READ_ONLY; // read (default) or read-write
73 * @param array $args Web and URL arguments
75 * @return boolean false if user doesn't exist
78 function prepare($args)
80 StatusNet::setApi(true); // reduce exception reports to aid in debugging
81 parent::prepare($args);
83 $this->format = $this->arg('format');
84 $this->page = (int)$this->arg('page', 1);
85 $this->count = (int)$this->arg('count', 20);
86 $this->max_id = (int)$this->arg('max_id', 0);
87 $this->since_id = (int)$this->arg('since_id', 0);
88 $this->since = $this->arg('since');
96 * @param array $args Arguments from $_REQUEST
101 function handle($args)
103 parent::handle($args);
107 * Overrides XMLOutputter::element to write booleans as strings (true|false).
108 * See that method's documentation for more info.
110 * @param string $tag Element type or tagname
111 * @param array $attrs Array of element attributes, as
113 * @param string $content string content of the element
117 function element($tag, $attrs=null, $content=null)
119 if (is_bool($content)) {
120 $content = ($content ? 'true' : 'false');
123 return parent::element($tag, $attrs, $content);
126 function twitterUserArray($profile, $get_notice=false)
128 $twitter_user = array();
130 $twitter_user['id'] = intval($profile->id);
131 $twitter_user['name'] = $profile->getBestName();
132 $twitter_user['screen_name'] = $profile->nickname;
133 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
134 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
136 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
137 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
138 Avatar::defaultImage(AVATAR_STREAM_SIZE);
140 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
141 $twitter_user['protected'] = false; # not supported by StatusNet yet
142 $twitter_user['followers_count'] = $profile->subscriberCount();
145 $user = $profile->getUser();
147 // Note: some profiles don't have an associated user
149 $defaultDesign = Design::siteDesign();
152 $design = $user->getDesign();
155 if (empty($design)) {
156 $design = $defaultDesign;
159 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
160 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
161 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
162 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
163 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
164 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
165 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
166 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
167 $twitter_user['profile_sidebar_border_color'] = '';
169 $twitter_user['friends_count'] = $profile->subscriptionCount();
171 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
173 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
177 if (!empty($user) && $user->timezone) {
178 $timezone = $user->timezone;
182 $t->setTimezone(new DateTimeZone($timezone));
184 $twitter_user['utc_offset'] = $t->format('Z');
185 $twitter_user['time_zone'] = $timezone;
187 $twitter_user['profile_background_image_url']
188 = empty($design->backgroundimage)
189 ? '' : ($design->disposition & BACKGROUND_ON)
190 ? Design::url($design->backgroundimage) : '';
192 $twitter_user['profile_background_tile']
193 = empty($design->disposition)
194 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
196 $twitter_user['statuses_count'] = $profile->noticeCount();
198 // Is the requesting user following this user?
199 $twitter_user['following'] = false;
200 $twitter_user['notifications'] = false;
202 if (isset($this->auth_user)) {
204 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
207 $sub = Subscription::pkeyGet(array('subscriber' =>
208 $this->auth_user->id,
209 'subscribed' => $profile->id));
212 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
217 $notice = $profile->getCurrentNotice();
220 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
224 return $twitter_user;
227 function twitterStatusArray($notice, $include_user=true)
229 $base = $this->twitterSimpleStatusArray($notice, $include_user);
231 if (!empty($notice->repeat_of)) {
232 $original = Notice::staticGet('id', $notice->repeat_of);
233 if (!empty($original)) {
234 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
235 $base['retweeted_status'] = $original_array;
242 function twitterSimpleStatusArray($notice, $include_user=true)
244 $profile = $notice->getProfile();
246 $twitter_status = array();
247 $twitter_status['text'] = $notice->content;
248 $twitter_status['truncated'] = false; # Not possible on StatusNet
249 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
250 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
251 intval($notice->reply_to) : null;
252 $twitter_status['source'] = $this->sourceLink($notice->source);
253 $twitter_status['id'] = intval($notice->id);
255 $replier_profile = null;
257 if ($notice->reply_to) {
258 $reply = Notice::staticGet(intval($notice->reply_to));
260 $replier_profile = $reply->getProfile();
264 $twitter_status['in_reply_to_user_id'] =
265 ($replier_profile) ? intval($replier_profile->id) : null;
266 $twitter_status['in_reply_to_screen_name'] =
267 ($replier_profile) ? $replier_profile->nickname : null;
269 if (isset($notice->lat) && isset($notice->lon)) {
270 // This is the format that GeoJSON expects stuff to be in
271 $twitter_status['geo'] = array('type' => 'Point',
272 'coordinates' => array((float) $notice->lat,
273 (float) $notice->lon));
275 $twitter_status['geo'] = null;
278 if (isset($this->auth_user)) {
279 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
281 $twitter_status['favorited'] = false;
285 $attachments = $notice->attachments();
287 if (!empty($attachments)) {
289 $twitter_status['attachments'] = array();
291 foreach ($attachments as $attachment) {
292 $enclosure_o=$attachment->getEnclosure();
294 $enclosure = array();
295 $enclosure['url'] = $enclosure_o->url;
296 $enclosure['mimetype'] = $enclosure_o->mimetype;
297 $enclosure['size'] = $enclosure_o->size;
298 $twitter_status['attachments'][] = $enclosure;
303 if ($include_user && $profile) {
304 # Don't get notice (recursive!)
305 $twitter_user = $this->twitterUserArray($profile, false);
306 $twitter_status['user'] = $twitter_user;
309 return $twitter_status;
312 function twitterGroupArray($group)
314 $twitter_group=array();
315 $twitter_group['id']=$group->id;
316 $twitter_group['url']=$group->permalink();
317 $twitter_group['nickname']=$group->nickname;
318 $twitter_group['fullname']=$group->fullname;
319 $twitter_group['homepage_url']=$group->homepage_url;
320 $twitter_group['original_logo']=$group->original_logo;
321 $twitter_group['homepage_logo']=$group->homepage_logo;
322 $twitter_group['stream_logo']=$group->stream_logo;
323 $twitter_group['mini_logo']=$group->mini_logo;
324 $twitter_group['homepage']=$group->homepage;
325 $twitter_group['description']=$group->description;
326 $twitter_group['location']=$group->location;
327 $twitter_group['created']=$this->dateTwitter($group->created);
328 $twitter_group['modified']=$this->dateTwitter($group->modified);
329 return $twitter_group;
332 function twitterRssGroupArray($group)
335 $entry['content']=$group->description;
336 $entry['title']=$group->nickname;
337 $entry['link']=$group->permalink();
338 $entry['published']=common_date_iso8601($group->created);
339 $entry['updated']==common_date_iso8601($group->modified);
340 $taguribase = common_config('integration', 'groupuri');
341 $entry['id'] = "group:$groupuribase:$entry[link]";
343 $entry['description'] = $entry['content'];
344 $entry['pubDate'] = common_date_rfc2822($group->created);
345 $entry['guid'] = $entry['link'];
350 function twitterRssEntryArray($notice)
352 $profile = $notice->getProfile();
355 // We trim() to avoid extraneous whitespace in the output
357 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
358 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
359 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
360 $entry['published'] = common_date_iso8601($notice->created);
362 $taguribase = common_config('integration', 'taguri');
363 $entry['id'] = "tag:$taguribase:$entry[link]";
365 $entry['updated'] = $entry['published'];
366 $entry['author'] = $profile->getBestName();
369 $attachments = $notice->attachments();
370 $enclosures = array();
372 foreach ($attachments as $attachment) {
373 $enclosure_o=$attachment->getEnclosure();
375 $enclosure = array();
376 $enclosure['url'] = $enclosure_o->url;
377 $enclosure['mimetype'] = $enclosure_o->mimetype;
378 $enclosure['size'] = $enclosure_o->size;
379 $enclosures[] = $enclosure;
383 if (!empty($enclosures)) {
384 $entry['enclosures'] = $enclosures;
388 $tag = new Notice_tag();
389 $tag->notice_id = $notice->id;
391 $entry['tags']=array();
392 while ($tag->fetch()) {
393 $entry['tags'][]=$tag->tag;
399 $entry['description'] = $entry['content'];
400 $entry['pubDate'] = common_date_rfc2822($notice->created);
401 $entry['guid'] = $entry['link'];
403 if (isset($notice->lat) && isset($notice->lon)) {
404 // This is the format that GeoJSON expects stuff to be in.
405 // showGeoRSS() below uses it for XML output, so we reuse it
406 $entry['geo'] = array('type' => 'Point',
407 'coordinates' => array((float) $notice->lat,
408 (float) $notice->lon));
410 $entry['geo'] = null;
416 function twitterRelationshipArray($source, $target)
418 $relationship = array();
420 $relationship['source'] =
421 $this->relationshipDetailsArray($source, $target);
422 $relationship['target'] =
423 $this->relationshipDetailsArray($target, $source);
425 return array('relationship' => $relationship);
428 function relationshipDetailsArray($source, $target)
432 $details['screen_name'] = $source->nickname;
433 $details['followed_by'] = $target->isSubscribed($source);
434 $details['following'] = $source->isSubscribed($target);
436 $notifications = false;
438 if ($source->isSubscribed($target)) {
440 $sub = Subscription::pkeyGet(array('subscriber' =>
441 $source->id, 'subscribed' => $target->id));
444 $notifications = ($sub->jabber || $sub->sms);
448 $details['notifications_enabled'] = $notifications;
449 $details['blocking'] = $source->hasBlocked($target);
450 $details['id'] = $source->id;
455 function showTwitterXmlRelationship($relationship)
457 $this->elementStart('relationship');
459 foreach($relationship as $element => $value) {
460 if ($element == 'source' || $element == 'target') {
461 $this->elementStart($element);
462 $this->showXmlRelationshipDetails($value);
463 $this->elementEnd($element);
467 $this->elementEnd('relationship');
470 function showXmlRelationshipDetails($details)
472 foreach($details as $element => $value) {
473 $this->element($element, null, $value);
477 function showTwitterXmlStatus($twitter_status, $tag='status')
479 $this->elementStart($tag);
480 foreach($twitter_status as $element => $value) {
483 $this->showTwitterXmlUser($twitter_status['user']);
486 $this->element($element, null, common_xml_safe_str($value));
489 $this->showXmlAttachments($twitter_status['attachments']);
492 $this->showGeoRSS($value);
494 case 'retweeted_status':
495 $this->showTwitterXmlStatus($value, 'retweeted_status');
498 $this->element($element, null, $value);
501 $this->elementEnd($tag);
504 function showTwitterXmlGroup($twitter_group)
506 $this->elementStart('group');
507 foreach($twitter_group as $element => $value) {
508 $this->element($element, null, $value);
510 $this->elementEnd('group');
513 function showTwitterXmlUser($twitter_user, $role='user')
515 $this->elementStart($role);
516 foreach($twitter_user as $element => $value) {
517 if ($element == 'status') {
518 $this->showTwitterXmlStatus($twitter_user['status']);
520 $this->element($element, null, $value);
523 $this->elementEnd($role);
526 function showXmlAttachments($attachments) {
527 if (!empty($attachments)) {
528 $this->elementStart('attachments', array('type' => 'array'));
529 foreach ($attachments as $attachment) {
531 $attrs['url'] = $attachment['url'];
532 $attrs['mimetype'] = $attachment['mimetype'];
533 $attrs['size'] = $attachment['size'];
534 $this->element('enclosure', $attrs, '');
536 $this->elementEnd('attachments');
540 function showGeoRSS($geo)
544 $this->element('geo');
546 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
547 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
548 $this->elementEnd('geo');
552 function showTwitterRssItem($entry)
554 $this->elementStart('item');
555 $this->element('title', null, $entry['title']);
556 $this->element('description', null, $entry['description']);
557 $this->element('pubDate', null, $entry['pubDate']);
558 $this->element('guid', null, $entry['guid']);
559 $this->element('link', null, $entry['link']);
561 # RSS only supports 1 enclosure per item
562 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
563 $enclosure = $entry['enclosures'][0];
564 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
567 if(array_key_exists('tags', $entry)){
568 foreach($entry['tags'] as $tag){
569 $this->element('category', null,$tag);
573 $this->showGeoRSS($entry['geo']);
574 $this->elementEnd('item');
577 function showJsonObjects($objects)
579 print(json_encode($objects));
582 function showSingleXmlStatus($notice)
584 $this->initDocument('xml');
585 $twitter_status = $this->twitterStatusArray($notice);
586 $this->showTwitterXmlStatus($twitter_status);
587 $this->endDocument('xml');
590 function show_single_json_status($notice)
592 $this->initDocument('json');
593 $status = $this->twitterStatusArray($notice);
594 $this->showJsonObjects($status);
595 $this->endDocument('json');
598 function showXmlTimeline($notice)
601 $this->initDocument('xml');
602 $this->elementStart('statuses', array('type' => 'array'));
604 if (is_array($notice)) {
605 foreach ($notice as $n) {
606 $twitter_status = $this->twitterStatusArray($n);
607 $this->showTwitterXmlStatus($twitter_status);
610 while ($notice->fetch()) {
611 $twitter_status = $this->twitterStatusArray($notice);
612 $this->showTwitterXmlStatus($twitter_status);
616 $this->elementEnd('statuses');
617 $this->endDocument('xml');
620 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
623 $this->initDocument('rss');
625 $this->element('title', null, $title);
626 $this->element('link', null, $link);
627 if (!is_null($suplink)) {
628 // For FriendFeed's SUP protocol
629 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
630 'rel' => 'http://api.friendfeed.com/2008/03#sup',
632 'type' => 'application/json'));
635 if (!is_null($logo)) {
636 $this->elementStart('image');
637 $this->element('link', null, $link);
638 $this->element('title', null, $title);
639 $this->element('url', null, $logo);
640 $this->elementEnd('image');
643 $this->element('description', null, $subtitle);
644 $this->element('language', null, 'en-us');
645 $this->element('ttl', null, '40');
647 if (is_array($notice)) {
648 foreach ($notice as $n) {
649 $entry = $this->twitterRssEntryArray($n);
650 $this->showTwitterRssItem($entry);
653 while ($notice->fetch()) {
654 $entry = $this->twitterRssEntryArray($notice);
655 $this->showTwitterRssItem($entry);
659 $this->endTwitterRss();
662 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
665 $this->initDocument('atom');
667 $this->element('title', null, $title);
668 $this->element('id', null, $id);
669 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
671 if (!is_null($logo)) {
672 $this->element('logo',null,$logo);
675 if (!is_null($suplink)) {
676 # For FriendFeed's SUP protocol
677 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
679 'type' => 'application/json'));
682 if (!is_null($selfuri)) {
683 $this->element('link', array('href' => $selfuri,
684 'rel' => 'self', 'type' => 'application/atom+xml'), null);
687 $this->element('updated', null, common_date_iso8601('now'));
688 $this->element('subtitle', null, $subtitle);
690 if (is_array($notice)) {
691 foreach ($notice as $n) {
692 $this->raw($n->asAtomEntry());
695 while ($notice->fetch()) {
696 $this->raw($notice->asAtomEntry());
700 $this->endDocument('atom');
704 function showRssGroups($group, $title, $link, $subtitle)
707 $this->initDocument('rss');
709 $this->element('title', null, $title);
710 $this->element('link', null, $link);
711 $this->element('description', null, $subtitle);
712 $this->element('language', null, 'en-us');
713 $this->element('ttl', null, '40');
715 if (is_array($group)) {
716 foreach ($group as $g) {
717 $twitter_group = $this->twitterRssGroupArray($g);
718 $this->showTwitterRssItem($twitter_group);
721 while ($group->fetch()) {
722 $twitter_group = $this->twitterRssGroupArray($group);
723 $this->showTwitterRssItem($twitter_group);
727 $this->endTwitterRss();
730 function showTwitterAtomEntry($entry)
732 $this->elementStart('entry');
733 $this->element('title', null, $entry['title']);
734 $this->element('content', array('type' => 'html'), $entry['content']);
735 $this->element('id', null, $entry['id']);
736 $this->element('published', null, $entry['published']);
737 $this->element('updated', null, $entry['updated']);
738 $this->element('link', array('type' => 'text/html',
739 'href' => $entry['link'],
740 'rel' => 'alternate'));
741 $this->element('link', array('type' => $entry['avatar-type'],
742 'href' => $entry['avatar'],
744 $this->elementStart('author');
746 $this->element('name', null, $entry['author-name']);
747 $this->element('uri', null, $entry['author-uri']);
749 $this->elementEnd('author');
750 $this->elementEnd('entry');
753 function showXmlDirectMessage($dm)
755 $this->elementStart('direct_message');
756 foreach($dm as $element => $value) {
760 $this->showTwitterXmlUser($value, $element);
763 $this->element($element, null, common_xml_safe_str($value));
766 $this->element($element, null, $value);
770 $this->elementEnd('direct_message');
773 function directMessageArray($message)
777 $from_profile = $message->getFrom();
778 $to_profile = $message->getTo();
780 $dmsg['id'] = $message->id;
781 $dmsg['sender_id'] = $message->from_profile;
782 $dmsg['text'] = trim($message->content);
783 $dmsg['recipient_id'] = $message->to_profile;
784 $dmsg['created_at'] = $this->dateTwitter($message->created);
785 $dmsg['sender_screen_name'] = $from_profile->nickname;
786 $dmsg['recipient_screen_name'] = $to_profile->nickname;
787 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
788 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
793 function rssDirectMessageArray($message)
797 $from = $message->getFrom();
799 $entry['title'] = sprintf('Message from %1$s to %2$s',
800 $from->nickname, $message->getTo()->nickname);
802 $entry['content'] = common_xml_safe_str($message->rendered);
803 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
804 $entry['published'] = common_date_iso8601($message->created);
806 $taguribase = common_config('integration', 'taguri');
808 $entry['id'] = "tag:$taguribase:$entry[link]";
809 $entry['updated'] = $entry['published'];
811 $entry['author-name'] = $from->getBestName();
812 $entry['author-uri'] = $from->homepage;
814 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
816 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
817 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
821 $entry['description'] = $entry['content'];
822 $entry['pubDate'] = common_date_rfc2822($message->created);
823 $entry['guid'] = $entry['link'];
828 function showSingleXmlDirectMessage($message)
830 $this->initDocument('xml');
831 $dmsg = $this->directMessageArray($message);
832 $this->showXmlDirectMessage($dmsg);
833 $this->endDocument('xml');
836 function showSingleJsonDirectMessage($message)
838 $this->initDocument('json');
839 $dmsg = $this->directMessageArray($message);
840 $this->showJsonObjects($dmsg);
841 $this->endDocument('json');
844 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
847 $this->initDocument('atom');
849 $this->element('title', null, $title);
850 $this->element('id', null, $id);
851 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
853 if (!is_null($selfuri)) {
854 $this->element('link', array('href' => $selfuri,
855 'rel' => 'self', 'type' => 'application/atom+xml'), null);
858 $this->element('updated', null, common_date_iso8601('now'));
859 $this->element('subtitle', null, $subtitle);
861 if (is_array($group)) {
862 foreach ($group as $g) {
863 $this->raw($g->asAtomEntry());
866 while ($group->fetch()) {
867 $this->raw($group->asAtomEntry());
871 $this->endDocument('atom');
875 function showJsonTimeline($notice)
878 $this->initDocument('json');
882 if (is_array($notice)) {
883 foreach ($notice as $n) {
884 $twitter_status = $this->twitterStatusArray($n);
885 array_push($statuses, $twitter_status);
888 while ($notice->fetch()) {
889 $twitter_status = $this->twitterStatusArray($notice);
890 array_push($statuses, $twitter_status);
894 $this->showJsonObjects($statuses);
896 $this->endDocument('json');
899 function showJsonGroups($group)
902 $this->initDocument('json');
906 if (is_array($group)) {
907 foreach ($group as $g) {
908 $twitter_group = $this->twitterGroupArray($g);
909 array_push($groups, $twitter_group);
912 while ($group->fetch()) {
913 $twitter_group = $this->twitterGroupArray($group);
914 array_push($groups, $twitter_group);
918 $this->showJsonObjects($groups);
920 $this->endDocument('json');
923 function showXmlGroups($group)
926 $this->initDocument('xml');
927 $this->elementStart('groups', array('type' => 'array'));
929 if (is_array($group)) {
930 foreach ($group as $g) {
931 $twitter_group = $this->twitterGroupArray($g);
932 $this->showTwitterXmlGroup($twitter_group);
935 while ($group->fetch()) {
936 $twitter_group = $this->twitterGroupArray($group);
937 $this->showTwitterXmlGroup($twitter_group);
941 $this->elementEnd('groups');
942 $this->endDocument('xml');
945 function showTwitterXmlUsers($user)
948 $this->initDocument('xml');
949 $this->elementStart('users', array('type' => 'array'));
951 if (is_array($user)) {
952 foreach ($user as $u) {
953 $twitter_user = $this->twitterUserArray($u);
954 $this->showTwitterXmlUser($twitter_user);
957 while ($user->fetch()) {
958 $twitter_user = $this->twitterUserArray($user);
959 $this->showTwitterXmlUser($twitter_user);
963 $this->elementEnd('users');
964 $this->endDocument('xml');
967 function showJsonUsers($user)
970 $this->initDocument('json');
974 if (is_array($user)) {
975 foreach ($user as $u) {
976 $twitter_user = $this->twitterUserArray($u);
977 array_push($users, $twitter_user);
980 while ($user->fetch()) {
981 $twitter_user = $this->twitterUserArray($user);
982 array_push($users, $twitter_user);
986 $this->showJsonObjects($users);
988 $this->endDocument('json');
991 function showSingleJsonGroup($group)
993 $this->initDocument('json');
994 $twitter_group = $this->twitterGroupArray($group);
995 $this->showJsonObjects($twitter_group);
996 $this->endDocument('json');
999 function showSingleXmlGroup($group)
1001 $this->initDocument('xml');
1002 $twitter_group = $this->twitterGroupArray($group);
1003 $this->showTwitterXmlGroup($twitter_group);
1004 $this->endDocument('xml');
1007 function dateTwitter($dt)
1009 $dateStr = date('d F Y H:i:s', strtotime($dt));
1010 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1011 $d->setTimezone(new DateTimeZone(common_timezone()));
1012 return $d->format('D M d H:i:s O Y');
1015 function initDocument($type='xml')
1019 header('Content-Type: application/xml; charset=utf-8');
1023 header('Content-Type: application/json; charset=utf-8');
1025 // Check for JSONP callback
1026 $callback = $this->arg('callback');
1028 print $callback . '(';
1032 header("Content-Type: application/rss+xml; charset=utf-8");
1033 $this->initTwitterRss();
1036 header('Content-Type: application/atom+xml; charset=utf-8');
1037 $this->initTwitterAtom();
1040 $this->clientError(_('Not a supported data format.'));
1047 function endDocument($type='xml')
1055 // Check for JSONP callback
1056 $callback = $this->arg('callback');
1062 $this->endTwitterRss();
1065 $this->endTwitterRss();
1068 $this->clientError(_('Not a supported data format.'));
1074 function clientError($msg, $code = 400, $format = 'xml')
1076 $action = $this->trimmed('action');
1078 common_debug("User error '$code' on '$action': $msg", __FILE__);
1080 if (!array_key_exists($code, ClientErrorAction::$status)) {
1084 $status_string = ClientErrorAction::$status[$code];
1086 header('HTTP/1.1 '.$code.' '.$status_string);
1088 if ($format == 'xml') {
1089 $this->initDocument('xml');
1090 $this->elementStart('hash');
1091 $this->element('error', null, $msg);
1092 $this->element('request', null, $_SERVER['REQUEST_URI']);
1093 $this->elementEnd('hash');
1094 $this->endDocument('xml');
1095 } elseif ($format == 'json'){
1096 $this->initDocument('json');
1097 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1098 print(json_encode($error_array));
1099 $this->endDocument('json');
1102 // If user didn't request a useful format, throw a regular client error
1103 throw new ClientException($msg, $code);
1107 function serverError($msg, $code = 500, $content_type = 'json')
1109 $action = $this->trimmed('action');
1111 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1113 if (!array_key_exists($code, ServerErrorAction::$status)) {
1117 $status_string = ServerErrorAction::$status[$code];
1119 header('HTTP/1.1 '.$code.' '.$status_string);
1121 if ($content_type == 'xml') {
1122 $this->initDocument('xml');
1123 $this->elementStart('hash');
1124 $this->element('error', null, $msg);
1125 $this->element('request', null, $_SERVER['REQUEST_URI']);
1126 $this->elementEnd('hash');
1127 $this->endDocument('xml');
1129 $this->initDocument('json');
1130 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1131 print(json_encode($error_array));
1132 $this->endDocument('json');
1136 function initTwitterRss()
1139 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1140 $this->elementStart('channel');
1141 Event::handle('StartApiRss', array($this));
1144 function endTwitterRss()
1146 $this->elementEnd('channel');
1147 $this->elementEnd('rss');
1151 function initTwitterAtom()
1154 // FIXME: don't hardcode the language here!
1155 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1156 'xml:lang' => 'en-US',
1157 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1158 Event::handle('StartApiAtom', array($this));
1161 function endTwitterAtom()
1163 $this->elementEnd('feed');
1167 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1169 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1170 switch ($content_type) {
1172 $this->showTwitterXmlUser($profile_array);
1175 $this->showJsonObjects($profile_array);
1178 $this->clientError(_('Not a supported data format.'));
1184 function getTargetUser($id)
1188 // Twitter supports these other ways of passing the user ID
1189 if (is_numeric($this->arg('id'))) {
1190 return User::staticGet($this->arg('id'));
1191 } else if ($this->arg('id')) {
1192 $nickname = common_canonical_nickname($this->arg('id'));
1193 return User::staticGet('nickname', $nickname);
1194 } else if ($this->arg('user_id')) {
1195 // This is to ensure that a non-numeric user_id still
1196 // overrides screen_name even if it doesn't get used
1197 if (is_numeric($this->arg('user_id'))) {
1198 return User::staticGet('id', $this->arg('user_id'));
1200 } else if ($this->arg('screen_name')) {
1201 $nickname = common_canonical_nickname($this->arg('screen_name'));
1202 return User::staticGet('nickname', $nickname);
1204 // Fall back to trying the currently authenticated user
1205 return $this->auth_user;
1208 } else if (is_numeric($id)) {
1209 return User::staticGet($id);
1211 $nickname = common_canonical_nickname($id);
1212 return User::staticGet('nickname', $nickname);
1216 function getTargetGroup($id)
1219 if (is_numeric($this->arg('id'))) {
1220 return User_group::staticGet($this->arg('id'));
1221 } else if ($this->arg('id')) {
1222 $nickname = common_canonical_nickname($this->arg('id'));
1223 return User_group::staticGet('nickname', $nickname);
1224 } else if ($this->arg('group_id')) {
1225 // This is to ensure that a non-numeric user_id still
1226 // overrides screen_name even if it doesn't get used
1227 if (is_numeric($this->arg('group_id'))) {
1228 return User_group::staticGet('id', $this->arg('group_id'));
1230 } else if ($this->arg('group_name')) {
1231 $nickname = common_canonical_nickname($this->arg('group_name'));
1232 return User_group::staticGet('nickname', $nickname);
1235 } else if (is_numeric($id)) {
1236 return User_group::staticGet($id);
1238 $nickname = common_canonical_nickname($id);
1239 return User_group::staticGet('nickname', $nickname);
1243 function sourceLink($source)
1245 $source_name = _($source);
1258 $ns = Notice_source::staticGet($source);
1264 $app = Oauth_application::staticGet('name', $source);
1267 $url = $app->source_url;
1271 if (!empty($name) && !empty($url)) {
1272 $source_name = '<a href="' . $url . '">' . $name . '</a>';
1277 return $source_name;
1281 * Returns query argument or default value if not found. Certain
1282 * parameters used throughout the API are lightly scrubbed and
1283 * bounds checked. This overrides Action::arg().
1285 * @param string $key requested argument
1286 * @param string $def default value to return if $key is not provided
1290 function arg($key, $def=null)
1293 // XXX: Do even more input validation/scrubbing?
1295 if (array_key_exists($key, $this->args)) {
1298 $page = (int)$this->args['page'];
1299 return ($page < 1) ? 1 : $page;
1301 $count = (int)$this->args['count'];
1304 } elseif ($count > 200) {
1310 $since_id = (int)$this->args['since_id'];
1311 return ($since_id < 1) ? 0 : $since_id;
1313 $max_id = (int)$this->args['max_id'];
1314 return ($max_id < 1) ? 0 : $max_id;
1316 return strtotime($this->args['since']);
1318 return parent::arg($key, $def);