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)
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'));
605 $this->element('description', null, $subtitle);
606 $this->element('language', null, 'en-us');
607 $this->element('ttl', null, '40');
609 if (is_array($notice)) {
610 foreach ($notice as $n) {
611 $entry = $this->twitterRssEntryArray($n);
612 $this->showTwitterRssItem($entry);
615 while ($notice->fetch()) {
616 $entry = $this->twitterRssEntryArray($notice);
617 $this->showTwitterRssItem($entry);
621 $this->endTwitterRss();
624 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null)
627 $this->initDocument('atom');
629 $this->element('title', null, $title);
630 $this->element('id', null, $id);
631 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
633 if (!is_null($suplink)) {
634 # For FriendFeed's SUP protocol
635 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
637 'type' => 'application/json'));
640 if (!is_null($selfuri)) {
641 $this->element('link', array('href' => $selfuri,
642 'rel' => 'self', 'type' => 'application/atom+xml'), null);
645 $this->element('updated', null, common_date_iso8601('now'));
646 $this->element('subtitle', null, $subtitle);
648 if (is_array($notice)) {
649 foreach ($notice as $n) {
650 $this->raw($n->asAtomEntry());
653 while ($notice->fetch()) {
654 $this->raw($notice->asAtomEntry());
658 $this->endDocument('atom');
662 function showRssGroups($group, $title, $link, $subtitle)
665 $this->initDocument('rss');
667 $this->element('title', null, $title);
668 $this->element('link', null, $link);
669 $this->element('description', null, $subtitle);
670 $this->element('language', null, 'en-us');
671 $this->element('ttl', null, '40');
673 if (is_array($group)) {
674 foreach ($group as $g) {
675 $twitter_group = $this->twitterRssGroupArray($g);
676 $this->showTwitterRssItem($twitter_group);
679 while ($group->fetch()) {
680 $twitter_group = $this->twitterRssGroupArray($group);
681 $this->showTwitterRssItem($twitter_group);
685 $this->endTwitterRss();
688 function showTwitterAtomEntry($entry)
690 $this->elementStart('entry');
691 $this->element('title', null, $entry['title']);
692 $this->element('content', array('type' => 'html'), $entry['content']);
693 $this->element('id', null, $entry['id']);
694 $this->element('published', null, $entry['published']);
695 $this->element('updated', null, $entry['updated']);
696 $this->element('link', array('type' => 'text/html',
697 'href' => $entry['link'],
698 'rel' => 'alternate'));
699 $this->element('link', array('type' => $entry['avatar-type'],
700 'href' => $entry['avatar'],
702 $this->elementStart('author');
704 $this->element('name', null, $entry['author-name']);
705 $this->element('uri', null, $entry['author-uri']);
707 $this->elementEnd('author');
708 $this->elementEnd('entry');
711 function showXmlDirectMessage($dm)
713 $this->elementStart('direct_message');
714 foreach($dm as $element => $value) {
718 $this->showTwitterXmlUser($value, $element);
721 $this->element($element, null, common_xml_safe_str($value));
724 $this->element($element, null, $value);
728 $this->elementEnd('direct_message');
731 function directMessageArray($message)
735 $from_profile = $message->getFrom();
736 $to_profile = $message->getTo();
738 $dmsg['id'] = $message->id;
739 $dmsg['sender_id'] = $message->from_profile;
740 $dmsg['text'] = trim($message->content);
741 $dmsg['recipient_id'] = $message->to_profile;
742 $dmsg['created_at'] = $this->dateTwitter($message->created);
743 $dmsg['sender_screen_name'] = $from_profile->nickname;
744 $dmsg['recipient_screen_name'] = $to_profile->nickname;
745 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
746 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
751 function rssDirectMessageArray($message)
755 $from = $message->getFrom();
757 $entry['title'] = sprintf('Message from %s to %s',
758 $from->nickname, $message->getTo()->nickname);
760 $entry['content'] = common_xml_safe_str($message->rendered);
761 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
762 $entry['published'] = common_date_iso8601($message->created);
764 $taguribase = common_config('integration', 'taguri');
766 $entry['id'] = "tag:$taguribase:$entry[link]";
767 $entry['updated'] = $entry['published'];
769 $entry['author-name'] = $from->getBestName();
770 $entry['author-uri'] = $from->homepage;
772 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
774 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
775 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
779 $entry['description'] = $entry['content'];
780 $entry['pubDate'] = common_date_rfc2822($message->created);
781 $entry['guid'] = $entry['link'];
786 function showSingleXmlDirectMessage($message)
788 $this->initDocument('xml');
789 $dmsg = $this->directMessageArray($message);
790 $this->showXmlDirectMessage($dmsg);
791 $this->endDocument('xml');
794 function showSingleJsonDirectMessage($message)
796 $this->initDocument('json');
797 $dmsg = $this->directMessageArray($message);
798 $this->showJsonObjects($dmsg);
799 $this->endDocument('json');
802 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
805 $this->initDocument('atom');
807 $this->element('title', null, $title);
808 $this->element('id', null, $id);
809 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
811 if (!is_null($selfuri)) {
812 $this->element('link', array('href' => $selfuri,
813 'rel' => 'self', 'type' => 'application/atom+xml'), null);
816 $this->element('updated', null, common_date_iso8601('now'));
817 $this->element('subtitle', null, $subtitle);
819 if (is_array($group)) {
820 foreach ($group as $g) {
821 $this->raw($g->asAtomEntry());
824 while ($group->fetch()) {
825 $this->raw($group->asAtomEntry());
829 $this->endDocument('atom');
833 function showJsonTimeline($notice)
836 $this->initDocument('json');
840 if (is_array($notice)) {
841 foreach ($notice as $n) {
842 $twitter_status = $this->twitterStatusArray($n);
843 array_push($statuses, $twitter_status);
846 while ($notice->fetch()) {
847 $twitter_status = $this->twitterStatusArray($notice);
848 array_push($statuses, $twitter_status);
852 $this->showJsonObjects($statuses);
854 $this->endDocument('json');
857 function showJsonGroups($group)
860 $this->initDocument('json');
864 if (is_array($group)) {
865 foreach ($group as $g) {
866 $twitter_group = $this->twitterGroupArray($g);
867 array_push($groups, $twitter_group);
870 while ($group->fetch()) {
871 $twitter_group = $this->twitterGroupArray($group);
872 array_push($groups, $twitter_group);
876 $this->showJsonObjects($groups);
878 $this->endDocument('json');
881 function showXmlGroups($group)
884 $this->initDocument('xml');
885 $this->elementStart('groups', array('type' => 'array'));
887 if (is_array($group)) {
888 foreach ($group as $g) {
889 $twitter_group = $this->twitterGroupArray($g);
890 $this->showTwitterXmlGroup($twitter_group);
893 while ($group->fetch()) {
894 $twitter_group = $this->twitterGroupArray($group);
895 $this->showTwitterXmlGroup($twitter_group);
899 $this->elementEnd('groups');
900 $this->endDocument('xml');
903 function showTwitterXmlUsers($user)
906 $this->initDocument('xml');
907 $this->elementStart('users', array('type' => 'array'));
909 if (is_array($user)) {
910 foreach ($user as $u) {
911 $twitter_user = $this->twitterUserArray($u);
912 $this->showTwitterXmlUser($twitter_user);
915 while ($user->fetch()) {
916 $twitter_user = $this->twitterUserArray($user);
917 $this->showTwitterXmlUser($twitter_user);
921 $this->elementEnd('users');
922 $this->endDocument('xml');
925 function showJsonUsers($user)
928 $this->initDocument('json');
932 if (is_array($user)) {
933 foreach ($user as $u) {
934 $twitter_user = $this->twitterUserArray($u);
935 array_push($users, $twitter_user);
938 while ($user->fetch()) {
939 $twitter_user = $this->twitterUserArray($user);
940 array_push($users, $twitter_user);
944 $this->showJsonObjects($users);
946 $this->endDocument('json');
949 function showSingleJsonGroup($group)
951 $this->initDocument('json');
952 $twitter_group = $this->twitterGroupArray($group);
953 $this->showJsonObjects($twitter_group);
954 $this->endDocument('json');
957 function showSingleXmlGroup($group)
959 $this->initDocument('xml');
960 $twitter_group = $this->twitterGroupArray($group);
961 $this->showTwitterXmlGroup($twitter_group);
962 $this->endDocument('xml');
965 function dateTwitter($dt)
967 $dateStr = date('d F Y H:i:s', strtotime($dt));
968 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
969 $d->setTimezone(new DateTimeZone(common_timezone()));
970 return $d->format('D M d H:i:s O Y');
973 function initDocument($type='xml')
977 header('Content-Type: application/xml; charset=utf-8');
981 header('Content-Type: application/json; charset=utf-8');
983 // Check for JSONP callback
984 $callback = $this->arg('callback');
986 print $callback . '(';
990 header("Content-Type: application/rss+xml; charset=utf-8");
991 $this->initTwitterRss();
994 header('Content-Type: application/atom+xml; charset=utf-8');
995 $this->initTwitterAtom();
998 $this->clientError(_('Not a supported data format.'));
1005 function endDocument($type='xml')
1013 // Check for JSONP callback
1014 $callback = $this->arg('callback');
1020 $this->endTwitterRss();
1023 $this->endTwitterRss();
1026 $this->clientError(_('Not a supported data format.'));
1032 function clientError($msg, $code = 400, $format = 'xml')
1034 $action = $this->trimmed('action');
1036 common_debug("User error '$code' on '$action': $msg", __FILE__);
1038 if (!array_key_exists($code, ClientErrorAction::$status)) {
1042 $status_string = ClientErrorAction::$status[$code];
1044 header('HTTP/1.1 '.$code.' '.$status_string);
1046 if ($format == 'xml') {
1047 $this->initDocument('xml');
1048 $this->elementStart('hash');
1049 $this->element('error', null, $msg);
1050 $this->element('request', null, $_SERVER['REQUEST_URI']);
1051 $this->elementEnd('hash');
1052 $this->endDocument('xml');
1053 } elseif ($format == 'json'){
1054 $this->initDocument('json');
1055 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1056 print(json_encode($error_array));
1057 $this->endDocument('json');
1060 // If user didn't request a useful format, throw a regular client error
1061 throw new ClientException($msg, $code);
1065 function serverError($msg, $code = 500, $content_type = 'json')
1067 $action = $this->trimmed('action');
1069 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1071 if (!array_key_exists($code, ServerErrorAction::$status)) {
1075 $status_string = ServerErrorAction::$status[$code];
1077 header('HTTP/1.1 '.$code.' '.$status_string);
1079 if ($content_type == 'xml') {
1080 $this->initDocument('xml');
1081 $this->elementStart('hash');
1082 $this->element('error', null, $msg);
1083 $this->element('request', null, $_SERVER['REQUEST_URI']);
1084 $this->elementEnd('hash');
1085 $this->endDocument('xml');
1087 $this->initDocument('json');
1088 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1089 print(json_encode($error_array));
1090 $this->endDocument('json');
1094 function initTwitterRss()
1097 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1098 $this->elementStart('channel');
1099 Event::handle('StartApiRss', array($this));
1102 function endTwitterRss()
1104 $this->elementEnd('channel');
1105 $this->elementEnd('rss');
1109 function initTwitterAtom()
1112 // FIXME: don't hardcode the language here!
1113 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1114 'xml:lang' => 'en-US',
1115 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1116 Event::handle('StartApiAtom', array($this));
1119 function endTwitterAtom()
1121 $this->elementEnd('feed');
1125 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1127 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1128 switch ($content_type) {
1130 $this->showTwitterXmlUser($profile_array);
1133 $this->showJsonObjects($profile_array);
1136 $this->clientError(_('Not a supported data format.'));
1142 function getTargetUser($id)
1146 // Twitter supports these other ways of passing the user ID
1147 if (is_numeric($this->arg('id'))) {
1148 return User::staticGet($this->arg('id'));
1149 } else if ($this->arg('id')) {
1150 $nickname = common_canonical_nickname($this->arg('id'));
1151 return User::staticGet('nickname', $nickname);
1152 } else if ($this->arg('user_id')) {
1153 // This is to ensure that a non-numeric user_id still
1154 // overrides screen_name even if it doesn't get used
1155 if (is_numeric($this->arg('user_id'))) {
1156 return User::staticGet('id', $this->arg('user_id'));
1158 } else if ($this->arg('screen_name')) {
1159 $nickname = common_canonical_nickname($this->arg('screen_name'));
1160 return User::staticGet('nickname', $nickname);
1162 // Fall back to trying the currently authenticated user
1163 return $this->auth_user;
1166 } else if (is_numeric($id)) {
1167 return User::staticGet($id);
1169 $nickname = common_canonical_nickname($id);
1170 return User::staticGet('nickname', $nickname);
1174 function getTargetGroup($id)
1177 if (is_numeric($this->arg('id'))) {
1178 return User_group::staticGet($this->arg('id'));
1179 } else if ($this->arg('id')) {
1180 $nickname = common_canonical_nickname($this->arg('id'));
1181 return User_group::staticGet('nickname', $nickname);
1182 } else if ($this->arg('group_id')) {
1183 // This is to ensure that a non-numeric user_id still
1184 // overrides screen_name even if it doesn't get used
1185 if (is_numeric($this->arg('group_id'))) {
1186 return User_group::staticGet('id', $this->arg('group_id'));
1188 } else if ($this->arg('group_name')) {
1189 $nickname = common_canonical_nickname($this->arg('group_name'));
1190 return User_group::staticGet('nickname', $nickname);
1193 } else if (is_numeric($id)) {
1194 return User_group::staticGet($id);
1196 $nickname = common_canonical_nickname($id);
1197 return User_group::staticGet('nickname', $nickname);
1201 function sourceLink($source)
1203 $source_name = _($source);
1212 $ns = Notice_source::staticGet($source);
1214 $source_name = '<a href="' . $ns->url . '">' . $ns->name . '</a>';
1218 return $source_name;
1222 * Returns query argument or default value if not found. Certain
1223 * parameters used throughout the API are lightly scrubbed and
1224 * bounds checked. This overrides Action::arg().
1226 * @param string $key requested argument
1227 * @param string $def default value to return if $key is not provided
1231 function arg($key, $def=null)
1234 // XXX: Do even more input validation/scrubbing?
1236 if (array_key_exists($key, $this->args)) {
1239 $page = (int)$this->args['page'];
1240 return ($page < 1) ? 1 : $page;
1242 $count = (int)$this->args['count'];
1245 } elseif ($count > 200) {
1251 $since_id = (int)$this->args['since_id'];
1252 return ($since_id < 1) ? 0 : $since_id;
1254 $max_id = (int)$this->args['max_id'];
1255 return ($max_id < 1) ? 0 : $max_id;
1257 return strtotime($this->args['since']);
1259 return parent::arg($key, $def);