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 $profile = $notice->getProfile();
221 $twitter_status = array();
222 $twitter_status['text'] = $notice->content;
223 $twitter_status['truncated'] = false; # Not possible on StatusNet
224 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
225 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
226 intval($notice->reply_to) : null;
227 $twitter_status['source'] = $this->sourceLink($notice->source);
228 $twitter_status['id'] = intval($notice->id);
230 $replier_profile = null;
232 if ($notice->reply_to) {
233 $reply = Notice::staticGet(intval($notice->reply_to));
235 $replier_profile = $reply->getProfile();
239 $twitter_status['in_reply_to_user_id'] =
240 ($replier_profile) ? intval($replier_profile->id) : null;
241 $twitter_status['in_reply_to_screen_name'] =
242 ($replier_profile) ? $replier_profile->nickname : null;
244 if (isset($notice->lat) && isset($notice->lon)) {
245 // This is the format that GeoJSON expects stuff to be in
246 $twitter_status['geo'] = array('type' => 'Point',
247 'coordinates' => array((float) $notice->lat,
248 (float) $notice->lon));
250 $twitter_status['geo'] = null;
253 if (isset($this->auth_user)) {
254 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
256 $twitter_status['favorited'] = false;
260 $attachments = $notice->attachments();
262 if (!empty($attachments)) {
264 $twitter_status['attachments'] = array();
266 foreach ($attachments as $attachment) {
267 if ($attachment->isEnclosure()) {
268 $enclosure = array();
269 $enclosure['url'] = $attachment->url;
270 $enclosure['mimetype'] = $attachment->mimetype;
271 $enclosure['size'] = $attachment->size;
272 $twitter_status['attachments'][] = $enclosure;
278 # Don't get notice (recursive!)
279 $twitter_user = $this->twitterUserArray($profile, false);
280 $twitter_status['user'] = $twitter_user;
283 return $twitter_status;
286 function twitterGroupArray($group)
288 $twitter_group=array();
289 $twitter_group['id']=$group->id;
290 $twitter_group['url']=$group->permalink();
291 $twitter_group['nickname']=$group->nickname;
292 $twitter_group['fullname']=$group->fullname;
293 $twitter_group['homepage_url']=$group->homepage_url;
294 $twitter_group['original_logo']=$group->original_logo;
295 $twitter_group['homepage_logo']=$group->homepage_logo;
296 $twitter_group['stream_logo']=$group->stream_logo;
297 $twitter_group['mini_logo']=$group->mini_logo;
298 $twitter_group['homepage']=$group->homepage;
299 $twitter_group['description']=$group->description;
300 $twitter_group['location']=$group->location;
301 $twitter_group['created']=$this->dateTwitter($group->created);
302 $twitter_group['modified']=$this->dateTwitter($group->modified);
303 return $twitter_group;
306 function twitterRssGroupArray($group)
309 $entry['content']=$group->description;
310 $entry['title']=$group->nickname;
311 $entry['link']=$group->permalink();
312 $entry['published']=common_date_iso8601($group->created);
313 $entry['updated']==common_date_iso8601($group->modified);
314 $taguribase = common_config('integration', 'groupuri');
315 $entry['id'] = "group:$groupuribase:$entry[link]";
317 $entry['description'] = $entry['content'];
318 $entry['pubDate'] = common_date_rfc2822($group->created);
319 $entry['guid'] = $entry['link'];
324 function twitterRssEntryArray($notice)
326 $profile = $notice->getProfile();
329 // We trim() to avoid extraneous whitespace in the output
331 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
332 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
333 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
334 $entry['published'] = common_date_iso8601($notice->created);
336 $taguribase = common_config('integration', 'taguri');
337 $entry['id'] = "tag:$taguribase:$entry[link]";
339 $entry['updated'] = $entry['published'];
340 $entry['author'] = $profile->getBestName();
343 $attachments = $notice->attachments();
344 $enclosures = array();
346 foreach ($attachments as $attachment) {
347 $enclosure_o=$attachment->getEnclosure();
349 $enclosure = array();
350 $enclosure['url'] = $enclosure_o->url;
351 $enclosure['mimetype'] = $enclosure_o->mimetype;
352 $enclosure['size'] = $enclosure_o->size;
353 $enclosures[] = $enclosure;
357 if (!empty($enclosures)) {
358 $entry['enclosures'] = $enclosures;
362 $tag = new Notice_tag();
363 $tag->notice_id = $notice->id;
365 $entry['tags']=array();
366 while ($tag->fetch()) {
367 $entry['tags'][]=$tag->tag;
373 $entry['description'] = $entry['content'];
374 $entry['pubDate'] = common_date_rfc2822($notice->created);
375 $entry['guid'] = $entry['link'];
377 if (isset($notice->lat) && isset($notice->lon)) {
378 // This is the format that GeoJSON expects stuff to be in.
379 // showGeoRSS() below uses it for XML output, so we reuse it
380 $entry['geo'] = array('type' => 'Point',
381 'coordinates' => array((float) $notice->lat,
382 (float) $notice->lon));
384 $entry['geo'] = null;
390 function twitterRelationshipArray($source, $target)
392 $relationship = array();
394 $relationship['source'] =
395 $this->relationshipDetailsArray($source, $target);
396 $relationship['target'] =
397 $this->relationshipDetailsArray($target, $source);
399 return array('relationship' => $relationship);
402 function relationshipDetailsArray($source, $target)
406 $details['screen_name'] = $source->nickname;
407 $details['followed_by'] = $target->isSubscribed($source);
408 $details['following'] = $source->isSubscribed($target);
410 $notifications = false;
412 if ($source->isSubscribed($target)) {
414 $sub = Subscription::pkeyGet(array('subscriber' =>
415 $source->id, 'subscribed' => $target->id));
418 $notifications = ($sub->jabber || $sub->sms);
422 $details['notifications_enabled'] = $notifications;
423 $details['blocking'] = $source->hasBlocked($target);
424 $details['id'] = $source->id;
429 function showTwitterXmlRelationship($relationship)
431 $this->elementStart('relationship');
433 foreach($relationship as $element => $value) {
434 if ($element == 'source' || $element == 'target') {
435 $this->elementStart($element);
436 $this->showXmlRelationshipDetails($value);
437 $this->elementEnd($element);
441 $this->elementEnd('relationship');
444 function showXmlRelationshipDetails($details)
446 foreach($details as $element => $value) {
447 $this->element($element, null, $value);
451 function showTwitterXmlStatus($twitter_status)
453 $this->elementStart('status');
454 foreach($twitter_status as $element => $value) {
457 $this->showTwitterXmlUser($twitter_status['user']);
460 $this->element($element, null, common_xml_safe_str($value));
463 $this->showXmlAttachments($twitter_status['attachments']);
466 $this->showGeoRSS($value);
469 $this->element($element, null, $value);
472 $this->elementEnd('status');
475 function showTwitterXmlGroup($twitter_group)
477 $this->elementStart('group');
478 foreach($twitter_group as $element => $value) {
479 $this->element($element, null, $value);
481 $this->elementEnd('group');
484 function showTwitterXmlUser($twitter_user, $role='user')
486 $this->elementStart($role);
487 foreach($twitter_user as $element => $value) {
488 if ($element == 'status') {
489 $this->showTwitterXmlStatus($twitter_user['status']);
491 $this->element($element, null, $value);
494 $this->elementEnd($role);
497 function showXmlAttachments($attachments) {
498 if (!empty($attachments)) {
499 $this->elementStart('attachments', array('type' => 'array'));
500 foreach ($attachments as $attachment) {
502 $attrs['url'] = $attachment['url'];
503 $attrs['mimetype'] = $attachment['mimetype'];
504 $attrs['size'] = $attachment['size'];
505 $this->element('enclosure', $attrs, '');
507 $this->elementEnd('attachments');
511 function showGeoRSS($geo)
515 $this->element('geo');
517 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
518 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
519 $this->elementEnd('geo');
523 function showTwitterRssItem($entry)
525 $this->elementStart('item');
526 $this->element('title', null, $entry['title']);
527 $this->element('description', null, $entry['description']);
528 $this->element('pubDate', null, $entry['pubDate']);
529 $this->element('guid', null, $entry['guid']);
530 $this->element('link', null, $entry['link']);
532 # RSS only supports 1 enclosure per item
533 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
534 $enclosure = $entry['enclosures'][0];
535 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
538 if(array_key_exists('tags', $entry)){
539 foreach($entry['tags'] as $tag){
540 $this->element('category', null,$tag);
544 $this->showGeoRSS($entry['geo']);
545 $this->elementEnd('item');
548 function showJsonObjects($objects)
550 print(json_encode($objects));
553 function showSingleXmlStatus($notice)
555 $this->initDocument('xml');
556 $twitter_status = $this->twitterStatusArray($notice);
557 $this->showTwitterXmlStatus($twitter_status);
558 $this->endDocument('xml');
561 function show_single_json_status($notice)
563 $this->initDocument('json');
564 $status = $this->twitterStatusArray($notice);
565 $this->showJsonObjects($status);
566 $this->endDocument('json');
569 function showXmlTimeline($notice)
572 $this->initDocument('xml');
573 $this->elementStart('statuses', array('type' => 'array'));
575 if (is_array($notice)) {
576 foreach ($notice as $n) {
577 $twitter_status = $this->twitterStatusArray($n);
578 $this->showTwitterXmlStatus($twitter_status);
581 while ($notice->fetch()) {
582 $twitter_status = $this->twitterStatusArray($notice);
583 $this->showTwitterXmlStatus($twitter_status);
587 $this->elementEnd('statuses');
588 $this->endDocument('xml');
591 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
594 $this->initDocument('rss');
596 $this->element('title', null, $title);
597 $this->element('link', null, $link);
598 if (!is_null($suplink)) {
599 // For FriendFeed's SUP protocol
600 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
601 'rel' => 'http://api.friendfeed.com/2008/03#sup',
603 'type' => 'application/json'));
606 if (!is_null($logo)) {
607 $this->elementStart('image');
608 $this->element('link', null, $link);
609 $this->element('title', null, $title);
610 $this->element('url', null, $logo);
611 $this->elementEnd('image');
614 $this->element('description', null, $subtitle);
615 $this->element('language', null, 'en-us');
616 $this->element('ttl', null, '40');
618 if (is_array($notice)) {
619 foreach ($notice as $n) {
620 $entry = $this->twitterRssEntryArray($n);
621 $this->showTwitterRssItem($entry);
624 while ($notice->fetch()) {
625 $entry = $this->twitterRssEntryArray($notice);
626 $this->showTwitterRssItem($entry);
630 $this->endTwitterRss();
633 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
636 $this->initDocument('atom');
638 $this->element('title', null, $title);
639 $this->element('id', null, $id);
640 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
642 if (!is_null($logo)) {
643 $this->element('logo',null,$logo);
646 if (!is_null($suplink)) {
647 # For FriendFeed's SUP protocol
648 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
650 'type' => 'application/json'));
653 if (!is_null($selfuri)) {
654 $this->element('link', array('href' => $selfuri,
655 'rel' => 'self', 'type' => 'application/atom+xml'), null);
658 $this->element('updated', null, common_date_iso8601('now'));
659 $this->element('subtitle', null, $subtitle);
661 if (is_array($notice)) {
662 foreach ($notice as $n) {
663 $this->raw($n->asAtomEntry());
666 while ($notice->fetch()) {
667 $this->raw($notice->asAtomEntry());
671 $this->endDocument('atom');
675 function showRssGroups($group, $title, $link, $subtitle)
678 $this->initDocument('rss');
680 $this->element('title', null, $title);
681 $this->element('link', null, $link);
682 $this->element('description', null, $subtitle);
683 $this->element('language', null, 'en-us');
684 $this->element('ttl', null, '40');
686 if (is_array($group)) {
687 foreach ($group as $g) {
688 $twitter_group = $this->twitterRssGroupArray($g);
689 $this->showTwitterRssItem($twitter_group);
692 while ($group->fetch()) {
693 $twitter_group = $this->twitterRssGroupArray($group);
694 $this->showTwitterRssItem($twitter_group);
698 $this->endTwitterRss();
701 function showTwitterAtomEntry($entry)
703 $this->elementStart('entry');
704 $this->element('title', null, $entry['title']);
705 $this->element('content', array('type' => 'html'), $entry['content']);
706 $this->element('id', null, $entry['id']);
707 $this->element('published', null, $entry['published']);
708 $this->element('updated', null, $entry['updated']);
709 $this->element('link', array('type' => 'text/html',
710 'href' => $entry['link'],
711 'rel' => 'alternate'));
712 $this->element('link', array('type' => $entry['avatar-type'],
713 'href' => $entry['avatar'],
715 $this->elementStart('author');
717 $this->element('name', null, $entry['author-name']);
718 $this->element('uri', null, $entry['author-uri']);
720 $this->elementEnd('author');
721 $this->elementEnd('entry');
724 function showXmlDirectMessage($dm)
726 $this->elementStart('direct_message');
727 foreach($dm as $element => $value) {
731 $this->showTwitterXmlUser($value, $element);
734 $this->element($element, null, common_xml_safe_str($value));
737 $this->element($element, null, $value);
741 $this->elementEnd('direct_message');
744 function directMessageArray($message)
748 $from_profile = $message->getFrom();
749 $to_profile = $message->getTo();
751 $dmsg['id'] = $message->id;
752 $dmsg['sender_id'] = $message->from_profile;
753 $dmsg['text'] = trim($message->content);
754 $dmsg['recipient_id'] = $message->to_profile;
755 $dmsg['created_at'] = $this->dateTwitter($message->created);
756 $dmsg['sender_screen_name'] = $from_profile->nickname;
757 $dmsg['recipient_screen_name'] = $to_profile->nickname;
758 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
759 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
764 function rssDirectMessageArray($message)
768 $from = $message->getFrom();
770 $entry['title'] = sprintf('Message from %s to %s',
771 $from->nickname, $message->getTo()->nickname);
773 $entry['content'] = common_xml_safe_str($message->rendered);
774 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
775 $entry['published'] = common_date_iso8601($message->created);
777 $taguribase = common_config('integration', 'taguri');
779 $entry['id'] = "tag:$taguribase:$entry[link]";
780 $entry['updated'] = $entry['published'];
782 $entry['author-name'] = $from->getBestName();
783 $entry['author-uri'] = $from->homepage;
785 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
787 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
788 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
792 $entry['description'] = $entry['content'];
793 $entry['pubDate'] = common_date_rfc2822($message->created);
794 $entry['guid'] = $entry['link'];
799 function showSingleXmlDirectMessage($message)
801 $this->initDocument('xml');
802 $dmsg = $this->directMessageArray($message);
803 $this->showXmlDirectMessage($dmsg);
804 $this->endDocument('xml');
807 function showSingleJsonDirectMessage($message)
809 $this->initDocument('json');
810 $dmsg = $this->directMessageArray($message);
811 $this->showJsonObjects($dmsg);
812 $this->endDocument('json');
815 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
818 $this->initDocument('atom');
820 $this->element('title', null, $title);
821 $this->element('id', null, $id);
822 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
824 if (!is_null($selfuri)) {
825 $this->element('link', array('href' => $selfuri,
826 'rel' => 'self', 'type' => 'application/atom+xml'), null);
829 $this->element('updated', null, common_date_iso8601('now'));
830 $this->element('subtitle', null, $subtitle);
832 if (is_array($group)) {
833 foreach ($group as $g) {
834 $this->raw($g->asAtomEntry());
837 while ($group->fetch()) {
838 $this->raw($group->asAtomEntry());
842 $this->endDocument('atom');
846 function showJsonTimeline($notice)
849 $this->initDocument('json');
853 if (is_array($notice)) {
854 foreach ($notice as $n) {
855 $twitter_status = $this->twitterStatusArray($n);
856 array_push($statuses, $twitter_status);
859 while ($notice->fetch()) {
860 $twitter_status = $this->twitterStatusArray($notice);
861 array_push($statuses, $twitter_status);
865 $this->showJsonObjects($statuses);
867 $this->endDocument('json');
870 function showJsonGroups($group)
873 $this->initDocument('json');
877 if (is_array($group)) {
878 foreach ($group as $g) {
879 $twitter_group = $this->twitterGroupArray($g);
880 array_push($groups, $twitter_group);
883 while ($group->fetch()) {
884 $twitter_group = $this->twitterGroupArray($group);
885 array_push($groups, $twitter_group);
889 $this->showJsonObjects($groups);
891 $this->endDocument('json');
894 function showXmlGroups($group)
897 $this->initDocument('xml');
898 $this->elementStart('groups', array('type' => 'array'));
900 if (is_array($group)) {
901 foreach ($group as $g) {
902 $twitter_group = $this->twitterGroupArray($g);
903 $this->showTwitterXmlGroup($twitter_group);
906 while ($group->fetch()) {
907 $twitter_group = $this->twitterGroupArray($group);
908 $this->showTwitterXmlGroup($twitter_group);
912 $this->elementEnd('groups');
913 $this->endDocument('xml');
916 function showTwitterXmlUsers($user)
919 $this->initDocument('xml');
920 $this->elementStart('users', array('type' => 'array'));
922 if (is_array($user)) {
923 foreach ($user as $u) {
924 $twitter_user = $this->twitterUserArray($u);
925 $this->showTwitterXmlUser($twitter_user);
928 while ($user->fetch()) {
929 $twitter_user = $this->twitterUserArray($user);
930 $this->showTwitterXmlUser($twitter_user);
934 $this->elementEnd('users');
935 $this->endDocument('xml');
938 function showJsonUsers($user)
941 $this->initDocument('json');
945 if (is_array($user)) {
946 foreach ($user as $u) {
947 $twitter_user = $this->twitterUserArray($u);
948 array_push($users, $twitter_user);
951 while ($user->fetch()) {
952 $twitter_user = $this->twitterUserArray($user);
953 array_push($users, $twitter_user);
957 $this->showJsonObjects($users);
959 $this->endDocument('json');
962 function showSingleJsonGroup($group)
964 $this->initDocument('json');
965 $twitter_group = $this->twitterGroupArray($group);
966 $this->showJsonObjects($twitter_group);
967 $this->endDocument('json');
970 function showSingleXmlGroup($group)
972 $this->initDocument('xml');
973 $twitter_group = $this->twitterGroupArray($group);
974 $this->showTwitterXmlGroup($twitter_group);
975 $this->endDocument('xml');
978 function dateTwitter($dt)
980 $dateStr = date('d F Y H:i:s', strtotime($dt));
981 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
982 $d->setTimezone(new DateTimeZone(common_timezone()));
983 return $d->format('D M d H:i:s O Y');
986 function initDocument($type='xml')
990 header('Content-Type: application/xml; charset=utf-8');
994 header('Content-Type: application/json; charset=utf-8');
996 // Check for JSONP callback
997 $callback = $this->arg('callback');
999 print $callback . '(';
1003 header("Content-Type: application/rss+xml; charset=utf-8");
1004 $this->initTwitterRss();
1007 header('Content-Type: application/atom+xml; charset=utf-8');
1008 $this->initTwitterAtom();
1011 $this->clientError(_('Not a supported data format.'));
1018 function endDocument($type='xml')
1026 // Check for JSONP callback
1027 $callback = $this->arg('callback');
1033 $this->endTwitterRss();
1036 $this->endTwitterRss();
1039 $this->clientError(_('Not a supported data format.'));
1045 function clientError($msg, $code = 400, $format = 'xml')
1047 $action = $this->trimmed('action');
1049 common_debug("User error '$code' on '$action': $msg", __FILE__);
1051 if (!array_key_exists($code, ClientErrorAction::$status)) {
1055 $status_string = ClientErrorAction::$status[$code];
1057 header('HTTP/1.1 '.$code.' '.$status_string);
1059 if ($format == 'xml') {
1060 $this->initDocument('xml');
1061 $this->elementStart('hash');
1062 $this->element('error', null, $msg);
1063 $this->element('request', null, $_SERVER['REQUEST_URI']);
1064 $this->elementEnd('hash');
1065 $this->endDocument('xml');
1066 } elseif ($format == 'json'){
1067 $this->initDocument('json');
1068 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1069 print(json_encode($error_array));
1070 $this->endDocument('json');
1073 // If user didn't request a useful format, throw a regular client error
1074 throw new ClientException($msg, $code);
1078 function serverError($msg, $code = 500, $content_type = 'json')
1080 $action = $this->trimmed('action');
1082 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1084 if (!array_key_exists($code, ServerErrorAction::$status)) {
1088 $status_string = ServerErrorAction::$status[$code];
1090 header('HTTP/1.1 '.$code.' '.$status_string);
1092 if ($content_type == 'xml') {
1093 $this->initDocument('xml');
1094 $this->elementStart('hash');
1095 $this->element('error', null, $msg);
1096 $this->element('request', null, $_SERVER['REQUEST_URI']);
1097 $this->elementEnd('hash');
1098 $this->endDocument('xml');
1100 $this->initDocument('json');
1101 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1102 print(json_encode($error_array));
1103 $this->endDocument('json');
1107 function initTwitterRss()
1110 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1111 $this->elementStart('channel');
1112 Event::handle('StartApiRss', array($this));
1115 function endTwitterRss()
1117 $this->elementEnd('channel');
1118 $this->elementEnd('rss');
1122 function initTwitterAtom()
1125 // FIXME: don't hardcode the language here!
1126 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1127 'xml:lang' => 'en-US',
1128 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1129 Event::handle('StartApiAtom', array($this));
1132 function endTwitterAtom()
1134 $this->elementEnd('feed');
1138 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1140 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1141 switch ($content_type) {
1143 $this->showTwitterXmlUser($profile_array);
1146 $this->showJsonObjects($profile_array);
1149 $this->clientError(_('Not a supported data format.'));
1155 function getTargetUser($id)
1159 // Twitter supports these other ways of passing the user ID
1160 if (is_numeric($this->arg('id'))) {
1161 return User::staticGet($this->arg('id'));
1162 } else if ($this->arg('id')) {
1163 $nickname = common_canonical_nickname($this->arg('id'));
1164 return User::staticGet('nickname', $nickname);
1165 } else if ($this->arg('user_id')) {
1166 // This is to ensure that a non-numeric user_id still
1167 // overrides screen_name even if it doesn't get used
1168 if (is_numeric($this->arg('user_id'))) {
1169 return User::staticGet('id', $this->arg('user_id'));
1171 } else if ($this->arg('screen_name')) {
1172 $nickname = common_canonical_nickname($this->arg('screen_name'));
1173 return User::staticGet('nickname', $nickname);
1175 // Fall back to trying the currently authenticated user
1176 return $this->auth_user;
1179 } else if (is_numeric($id)) {
1180 return User::staticGet($id);
1182 $nickname = common_canonical_nickname($id);
1183 return User::staticGet('nickname', $nickname);
1187 function getTargetGroup($id)
1190 if (is_numeric($this->arg('id'))) {
1191 return User_group::staticGet($this->arg('id'));
1192 } else if ($this->arg('id')) {
1193 $nickname = common_canonical_nickname($this->arg('id'));
1194 return User_group::staticGet('nickname', $nickname);
1195 } else if ($this->arg('group_id')) {
1196 // This is to ensure that a non-numeric user_id still
1197 // overrides screen_name even if it doesn't get used
1198 if (is_numeric($this->arg('group_id'))) {
1199 return User_group::staticGet('id', $this->arg('group_id'));
1201 } else if ($this->arg('group_name')) {
1202 $nickname = common_canonical_nickname($this->arg('group_name'));
1203 return User_group::staticGet('nickname', $nickname);
1206 } else if (is_numeric($id)) {
1207 return User_group::staticGet($id);
1209 $nickname = common_canonical_nickname($id);
1210 return User_group::staticGet('nickname', $nickname);
1214 function sourceLink($source)
1216 $source_name = _($source);
1225 $ns = Notice_source::staticGet($source);
1227 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1231 return $source_name;
1235 * Returns query argument or default value if not found. Certain
1236 * parameters used throughout the API are lightly scrubbed and
1237 * bounds checked. This overrides Action::arg().
1239 * @param string $key requested argument
1240 * @param string $def default value to return if $key is not provided
1244 function arg($key, $def=null)
1247 // XXX: Do even more input validation/scrubbing?
1249 if (array_key_exists($key, $this->args)) {
1252 $page = (int)$this->args['page'];
1253 return ($page < 1) ? 1 : $page;
1255 $count = (int)$this->args['count'];
1258 } elseif ($count > 200) {
1264 $since_id = (int)$this->args['since_id'];
1265 return ($since_id < 1) ? 0 : $since_id;
1267 $max_id = (int)$this->args['max_id'];
1268 return ($max_id < 1) ? 0 : $max_id;
1270 return strtotime($this->args['since']);
1272 return parent::arg($key, $def);