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;
67 var $access = self::READ_ONLY; // read (default) or read-write
72 * @param array $args Web and URL arguments
74 * @return boolean false if user doesn't exist
77 function prepare($args)
79 StatusNet::setApi(true); // reduce exception reports to aid in debugging
80 parent::prepare($args);
82 $this->format = $this->arg('format');
83 $this->page = (int)$this->arg('page', 1);
84 $this->count = (int)$this->arg('count', 20);
85 $this->max_id = (int)$this->arg('max_id', 0);
86 $this->since_id = (int)$this->arg('since_id', 0);
88 if ($this->arg('since')) {
89 $this->clientError(_("since parameter is disabled for performance; use since_id"), 403);
98 * @param array $args Arguments from $_REQUEST
103 function handle($args)
105 parent::handle($args);
109 * Overrides XMLOutputter::element to write booleans as strings (true|false).
110 * See that method's documentation for more info.
112 * @param string $tag Element type or tagname
113 * @param array $attrs Array of element attributes, as
115 * @param string $content string content of the element
119 function element($tag, $attrs=null, $content=null)
121 if (is_bool($content)) {
122 $content = ($content ? 'true' : 'false');
125 return parent::element($tag, $attrs, $content);
128 function twitterUserArray($profile, $get_notice=false)
130 $twitter_user = array();
132 $twitter_user['id'] = intval($profile->id);
133 $twitter_user['name'] = $profile->getBestName();
134 $twitter_user['screen_name'] = $profile->nickname;
135 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
136 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
138 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
139 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
140 Avatar::defaultImage(AVATAR_STREAM_SIZE);
142 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
143 $twitter_user['protected'] = false; # not supported by StatusNet yet
144 $twitter_user['followers_count'] = $profile->subscriberCount();
147 $user = $profile->getUser();
149 // Note: some profiles don't have an associated user
151 $defaultDesign = Design::siteDesign();
154 $design = $user->getDesign();
157 if (empty($design)) {
158 $design = $defaultDesign;
161 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
162 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
163 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
164 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
165 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
166 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
167 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
168 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
169 $twitter_user['profile_sidebar_border_color'] = '';
171 $twitter_user['friends_count'] = $profile->subscriptionCount();
173 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
175 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
179 if (!empty($user) && $user->timezone) {
180 $timezone = $user->timezone;
184 $t->setTimezone(new DateTimeZone($timezone));
186 $twitter_user['utc_offset'] = $t->format('Z');
187 $twitter_user['time_zone'] = $timezone;
189 $twitter_user['profile_background_image_url']
190 = empty($design->backgroundimage)
191 ? '' : ($design->disposition & BACKGROUND_ON)
192 ? Design::url($design->backgroundimage) : '';
194 $twitter_user['profile_background_tile']
195 = empty($design->disposition)
196 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
198 $twitter_user['statuses_count'] = $profile->noticeCount();
200 // Is the requesting user following this user?
201 $twitter_user['following'] = false;
202 $twitter_user['notifications'] = false;
204 if (isset($this->auth_user)) {
206 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
209 $sub = Subscription::pkeyGet(array('subscriber' =>
210 $this->auth_user->id,
211 'subscribed' => $profile->id));
214 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
219 $notice = $profile->getCurrentNotice();
222 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
226 return $twitter_user;
229 function twitterStatusArray($notice, $include_user=true)
231 $base = $this->twitterSimpleStatusArray($notice, $include_user);
233 if (!empty($notice->repeat_of)) {
234 $original = Notice::staticGet('id', $notice->repeat_of);
235 if (!empty($original)) {
236 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
237 $base['retweeted_status'] = $original_array;
244 function twitterSimpleStatusArray($notice, $include_user=true)
246 $profile = $notice->getProfile();
248 $twitter_status = array();
249 $twitter_status['text'] = $notice->content;
250 $twitter_status['truncated'] = false; # Not possible on StatusNet
251 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
252 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
253 intval($notice->reply_to) : null;
254 $twitter_status['source'] = $this->sourceLink($notice->source);
255 $twitter_status['id'] = intval($notice->id);
257 $replier_profile = null;
259 if ($notice->reply_to) {
260 $reply = Notice::staticGet(intval($notice->reply_to));
262 $replier_profile = $reply->getProfile();
266 $twitter_status['in_reply_to_user_id'] =
267 ($replier_profile) ? intval($replier_profile->id) : null;
268 $twitter_status['in_reply_to_screen_name'] =
269 ($replier_profile) ? $replier_profile->nickname : null;
271 if (isset($notice->lat) && isset($notice->lon)) {
272 // This is the format that GeoJSON expects stuff to be in
273 $twitter_status['geo'] = array('type' => 'Point',
274 'coordinates' => array((float) $notice->lat,
275 (float) $notice->lon));
277 $twitter_status['geo'] = null;
280 if (isset($this->auth_user)) {
281 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
283 $twitter_status['favorited'] = false;
287 $attachments = $notice->attachments();
289 if (!empty($attachments)) {
291 $twitter_status['attachments'] = array();
293 foreach ($attachments as $attachment) {
294 $enclosure_o=$attachment->getEnclosure();
296 $enclosure = array();
297 $enclosure['url'] = $enclosure_o->url;
298 $enclosure['mimetype'] = $enclosure_o->mimetype;
299 $enclosure['size'] = $enclosure_o->size;
300 $twitter_status['attachments'][] = $enclosure;
305 if ($include_user && $profile) {
306 # Don't get notice (recursive!)
307 $twitter_user = $this->twitterUserArray($profile, false);
308 $twitter_status['user'] = $twitter_user;
311 return $twitter_status;
314 function twitterGroupArray($group)
316 $twitter_group=array();
317 $twitter_group['id']=$group->id;
318 $twitter_group['url']=$group->permalink();
319 $twitter_group['nickname']=$group->nickname;
320 $twitter_group['fullname']=$group->fullname;
321 $twitter_group['homepage_url']=$group->homepage_url;
322 $twitter_group['original_logo']=$group->original_logo;
323 $twitter_group['homepage_logo']=$group->homepage_logo;
324 $twitter_group['stream_logo']=$group->stream_logo;
325 $twitter_group['mini_logo']=$group->mini_logo;
326 $twitter_group['homepage']=$group->homepage;
327 $twitter_group['description']=$group->description;
328 $twitter_group['location']=$group->location;
329 $twitter_group['created']=$this->dateTwitter($group->created);
330 $twitter_group['modified']=$this->dateTwitter($group->modified);
331 return $twitter_group;
334 function twitterRssGroupArray($group)
337 $entry['content']=$group->description;
338 $entry['title']=$group->nickname;
339 $entry['link']=$group->permalink();
340 $entry['published']=common_date_iso8601($group->created);
341 $entry['updated']==common_date_iso8601($group->modified);
342 $taguribase = common_config('integration', 'groupuri');
343 $entry['id'] = "group:$groupuribase:$entry[link]";
345 $entry['description'] = $entry['content'];
346 $entry['pubDate'] = common_date_rfc2822($group->created);
347 $entry['guid'] = $entry['link'];
352 function twitterRssEntryArray($notice)
354 $profile = $notice->getProfile();
357 // We trim() to avoid extraneous whitespace in the output
359 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
360 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
361 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
362 $entry['published'] = common_date_iso8601($notice->created);
364 $taguribase = TagURI::base();
365 $entry['id'] = "tag:$taguribase:$entry[link]";
367 $entry['updated'] = $entry['published'];
368 $entry['author'] = $profile->getBestName();
371 $attachments = $notice->attachments();
372 $enclosures = array();
374 foreach ($attachments as $attachment) {
375 $enclosure_o=$attachment->getEnclosure();
377 $enclosure = array();
378 $enclosure['url'] = $enclosure_o->url;
379 $enclosure['mimetype'] = $enclosure_o->mimetype;
380 $enclosure['size'] = $enclosure_o->size;
381 $enclosures[] = $enclosure;
385 if (!empty($enclosures)) {
386 $entry['enclosures'] = $enclosures;
390 $tag = new Notice_tag();
391 $tag->notice_id = $notice->id;
393 $entry['tags']=array();
394 while ($tag->fetch()) {
395 $entry['tags'][]=$tag->tag;
401 $entry['description'] = $entry['content'];
402 $entry['pubDate'] = common_date_rfc2822($notice->created);
403 $entry['guid'] = $entry['link'];
405 if (isset($notice->lat) && isset($notice->lon)) {
406 // This is the format that GeoJSON expects stuff to be in.
407 // showGeoRSS() below uses it for XML output, so we reuse it
408 $entry['geo'] = array('type' => 'Point',
409 'coordinates' => array((float) $notice->lat,
410 (float) $notice->lon));
412 $entry['geo'] = null;
418 function twitterRelationshipArray($source, $target)
420 $relationship = array();
422 $relationship['source'] =
423 $this->relationshipDetailsArray($source, $target);
424 $relationship['target'] =
425 $this->relationshipDetailsArray($target, $source);
427 return array('relationship' => $relationship);
430 function relationshipDetailsArray($source, $target)
434 $details['screen_name'] = $source->nickname;
435 $details['followed_by'] = $target->isSubscribed($source);
436 $details['following'] = $source->isSubscribed($target);
438 $notifications = false;
440 if ($source->isSubscribed($target)) {
442 $sub = Subscription::pkeyGet(array('subscriber' =>
443 $source->id, 'subscribed' => $target->id));
446 $notifications = ($sub->jabber || $sub->sms);
450 $details['notifications_enabled'] = $notifications;
451 $details['blocking'] = $source->hasBlocked($target);
452 $details['id'] = $source->id;
457 function showTwitterXmlRelationship($relationship)
459 $this->elementStart('relationship');
461 foreach($relationship as $element => $value) {
462 if ($element == 'source' || $element == 'target') {
463 $this->elementStart($element);
464 $this->showXmlRelationshipDetails($value);
465 $this->elementEnd($element);
469 $this->elementEnd('relationship');
472 function showXmlRelationshipDetails($details)
474 foreach($details as $element => $value) {
475 $this->element($element, null, $value);
479 function showTwitterXmlStatus($twitter_status, $tag='status')
481 $this->elementStart($tag);
482 foreach($twitter_status as $element => $value) {
485 $this->showTwitterXmlUser($twitter_status['user']);
488 $this->element($element, null, common_xml_safe_str($value));
491 $this->showXmlAttachments($twitter_status['attachments']);
494 $this->showGeoRSS($value);
496 case 'retweeted_status':
497 $this->showTwitterXmlStatus($value, 'retweeted_status');
500 $this->element($element, null, $value);
503 $this->elementEnd($tag);
506 function showTwitterXmlGroup($twitter_group)
508 $this->elementStart('group');
509 foreach($twitter_group as $element => $value) {
510 $this->element($element, null, $value);
512 $this->elementEnd('group');
515 function showTwitterXmlUser($twitter_user, $role='user')
517 $this->elementStart($role);
518 foreach($twitter_user as $element => $value) {
519 if ($element == 'status') {
520 $this->showTwitterXmlStatus($twitter_user['status']);
522 $this->element($element, null, $value);
525 $this->elementEnd($role);
528 function showXmlAttachments($attachments) {
529 if (!empty($attachments)) {
530 $this->elementStart('attachments', array('type' => 'array'));
531 foreach ($attachments as $attachment) {
533 $attrs['url'] = $attachment['url'];
534 $attrs['mimetype'] = $attachment['mimetype'];
535 $attrs['size'] = $attachment['size'];
536 $this->element('enclosure', $attrs, '');
538 $this->elementEnd('attachments');
542 function showGeoRSS($geo)
546 $this->element('geo');
548 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
549 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
550 $this->elementEnd('geo');
554 function showTwitterRssItem($entry)
556 $this->elementStart('item');
557 $this->element('title', null, $entry['title']);
558 $this->element('description', null, $entry['description']);
559 $this->element('pubDate', null, $entry['pubDate']);
560 $this->element('guid', null, $entry['guid']);
561 $this->element('link', null, $entry['link']);
563 # RSS only supports 1 enclosure per item
564 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
565 $enclosure = $entry['enclosures'][0];
566 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
569 if(array_key_exists('tags', $entry)){
570 foreach($entry['tags'] as $tag){
571 $this->element('category', null,$tag);
575 $this->showGeoRSS($entry['geo']);
576 $this->elementEnd('item');
579 function showJsonObjects($objects)
581 print(json_encode($objects));
584 function showSingleXmlStatus($notice)
586 $this->initDocument('xml');
587 $twitter_status = $this->twitterStatusArray($notice);
588 $this->showTwitterXmlStatus($twitter_status);
589 $this->endDocument('xml');
592 function show_single_json_status($notice)
594 $this->initDocument('json');
595 $status = $this->twitterStatusArray($notice);
596 $this->showJsonObjects($status);
597 $this->endDocument('json');
600 function showXmlTimeline($notice)
603 $this->initDocument('xml');
604 $this->elementStart('statuses', array('type' => 'array'));
606 if (is_array($notice)) {
607 foreach ($notice as $n) {
608 $twitter_status = $this->twitterStatusArray($n);
609 $this->showTwitterXmlStatus($twitter_status);
612 while ($notice->fetch()) {
613 $twitter_status = $this->twitterStatusArray($notice);
614 $this->showTwitterXmlStatus($twitter_status);
618 $this->elementEnd('statuses');
619 $this->endDocument('xml');
622 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
625 $this->initDocument('rss');
627 $this->element('title', null, $title);
628 $this->element('link', null, $link);
629 if (!is_null($suplink)) {
630 // For FriendFeed's SUP protocol
631 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
632 'rel' => 'http://api.friendfeed.com/2008/03#sup',
634 'type' => 'application/json'));
637 if (!is_null($logo)) {
638 $this->elementStart('image');
639 $this->element('link', null, $link);
640 $this->element('title', null, $title);
641 $this->element('url', null, $logo);
642 $this->elementEnd('image');
645 $this->element('description', null, $subtitle);
646 $this->element('language', null, 'en-us');
647 $this->element('ttl', null, '40');
649 if (is_array($notice)) {
650 foreach ($notice as $n) {
651 $entry = $this->twitterRssEntryArray($n);
652 $this->showTwitterRssItem($entry);
655 while ($notice->fetch()) {
656 $entry = $this->twitterRssEntryArray($notice);
657 $this->showTwitterRssItem($entry);
661 $this->endTwitterRss();
664 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
667 $this->initDocument('atom');
669 $this->element('title', null, $title);
670 $this->element('id', null, $id);
671 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
673 if (!is_null($logo)) {
674 $this->element('logo',null,$logo);
677 if (!is_null($suplink)) {
678 # For FriendFeed's SUP protocol
679 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
681 'type' => 'application/json'));
684 if (!is_null($selfuri)) {
685 $this->element('link', array('href' => $selfuri,
686 'rel' => 'self', 'type' => 'application/atom+xml'), null);
689 $this->element('updated', null, common_date_iso8601('now'));
690 $this->element('subtitle', null, $subtitle);
692 if (is_array($notice)) {
693 foreach ($notice as $n) {
694 $this->raw($n->asAtomEntry());
697 while ($notice->fetch()) {
698 $this->raw($notice->asAtomEntry());
702 $this->endDocument('atom');
706 function showRssGroups($group, $title, $link, $subtitle)
709 $this->initDocument('rss');
711 $this->element('title', null, $title);
712 $this->element('link', null, $link);
713 $this->element('description', null, $subtitle);
714 $this->element('language', null, 'en-us');
715 $this->element('ttl', null, '40');
717 if (is_array($group)) {
718 foreach ($group as $g) {
719 $twitter_group = $this->twitterRssGroupArray($g);
720 $this->showTwitterRssItem($twitter_group);
723 while ($group->fetch()) {
724 $twitter_group = $this->twitterRssGroupArray($group);
725 $this->showTwitterRssItem($twitter_group);
729 $this->endTwitterRss();
732 function showTwitterAtomEntry($entry)
734 $this->elementStart('entry');
735 $this->element('title', null, $entry['title']);
736 $this->element('content', array('type' => 'html'), $entry['content']);
737 $this->element('id', null, $entry['id']);
738 $this->element('published', null, $entry['published']);
739 $this->element('updated', null, $entry['updated']);
740 $this->element('link', array('type' => 'text/html',
741 'href' => $entry['link'],
742 'rel' => 'alternate'));
743 $this->element('link', array('type' => $entry['avatar-type'],
744 'href' => $entry['avatar'],
746 $this->elementStart('author');
748 $this->element('name', null, $entry['author-name']);
749 $this->element('uri', null, $entry['author-uri']);
751 $this->elementEnd('author');
752 $this->elementEnd('entry');
755 function showXmlDirectMessage($dm)
757 $this->elementStart('direct_message');
758 foreach($dm as $element => $value) {
762 $this->showTwitterXmlUser($value, $element);
765 $this->element($element, null, common_xml_safe_str($value));
768 $this->element($element, null, $value);
772 $this->elementEnd('direct_message');
775 function directMessageArray($message)
779 $from_profile = $message->getFrom();
780 $to_profile = $message->getTo();
782 $dmsg['id'] = $message->id;
783 $dmsg['sender_id'] = $message->from_profile;
784 $dmsg['text'] = trim($message->content);
785 $dmsg['recipient_id'] = $message->to_profile;
786 $dmsg['created_at'] = $this->dateTwitter($message->created);
787 $dmsg['sender_screen_name'] = $from_profile->nickname;
788 $dmsg['recipient_screen_name'] = $to_profile->nickname;
789 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
790 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
795 function rssDirectMessageArray($message)
799 $from = $message->getFrom();
801 $entry['title'] = sprintf('Message from %1$s to %2$s',
802 $from->nickname, $message->getTo()->nickname);
804 $entry['content'] = common_xml_safe_str($message->rendered);
805 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
806 $entry['published'] = common_date_iso8601($message->created);
808 $taguribase = TagURI::base();
810 $entry['id'] = "tag:$taguribase:$entry[link]";
811 $entry['updated'] = $entry['published'];
813 $entry['author-name'] = $from->getBestName();
814 $entry['author-uri'] = $from->homepage;
816 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
818 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
819 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
823 $entry['description'] = $entry['content'];
824 $entry['pubDate'] = common_date_rfc2822($message->created);
825 $entry['guid'] = $entry['link'];
830 function showSingleXmlDirectMessage($message)
832 $this->initDocument('xml');
833 $dmsg = $this->directMessageArray($message);
834 $this->showXmlDirectMessage($dmsg);
835 $this->endDocument('xml');
838 function showSingleJsonDirectMessage($message)
840 $this->initDocument('json');
841 $dmsg = $this->directMessageArray($message);
842 $this->showJsonObjects($dmsg);
843 $this->endDocument('json');
846 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
849 $this->initDocument('atom');
851 $this->element('title', null, $title);
852 $this->element('id', null, $id);
853 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
855 if (!is_null($selfuri)) {
856 $this->element('link', array('href' => $selfuri,
857 'rel' => 'self', 'type' => 'application/atom+xml'), null);
860 $this->element('updated', null, common_date_iso8601('now'));
861 $this->element('subtitle', null, $subtitle);
863 if (is_array($group)) {
864 foreach ($group as $g) {
865 $this->raw($g->asAtomEntry());
868 while ($group->fetch()) {
869 $this->raw($group->asAtomEntry());
873 $this->endDocument('atom');
877 function showJsonTimeline($notice)
880 $this->initDocument('json');
884 if (is_array($notice)) {
885 foreach ($notice as $n) {
886 $twitter_status = $this->twitterStatusArray($n);
887 array_push($statuses, $twitter_status);
890 while ($notice->fetch()) {
891 $twitter_status = $this->twitterStatusArray($notice);
892 array_push($statuses, $twitter_status);
896 $this->showJsonObjects($statuses);
898 $this->endDocument('json');
901 function showJsonGroups($group)
904 $this->initDocument('json');
908 if (is_array($group)) {
909 foreach ($group as $g) {
910 $twitter_group = $this->twitterGroupArray($g);
911 array_push($groups, $twitter_group);
914 while ($group->fetch()) {
915 $twitter_group = $this->twitterGroupArray($group);
916 array_push($groups, $twitter_group);
920 $this->showJsonObjects($groups);
922 $this->endDocument('json');
925 function showXmlGroups($group)
928 $this->initDocument('xml');
929 $this->elementStart('groups', array('type' => 'array'));
931 if (is_array($group)) {
932 foreach ($group as $g) {
933 $twitter_group = $this->twitterGroupArray($g);
934 $this->showTwitterXmlGroup($twitter_group);
937 while ($group->fetch()) {
938 $twitter_group = $this->twitterGroupArray($group);
939 $this->showTwitterXmlGroup($twitter_group);
943 $this->elementEnd('groups');
944 $this->endDocument('xml');
947 function showTwitterXmlUsers($user)
950 $this->initDocument('xml');
951 $this->elementStart('users', array('type' => 'array'));
953 if (is_array($user)) {
954 foreach ($user as $u) {
955 $twitter_user = $this->twitterUserArray($u);
956 $this->showTwitterXmlUser($twitter_user);
959 while ($user->fetch()) {
960 $twitter_user = $this->twitterUserArray($user);
961 $this->showTwitterXmlUser($twitter_user);
965 $this->elementEnd('users');
966 $this->endDocument('xml');
969 function showJsonUsers($user)
972 $this->initDocument('json');
976 if (is_array($user)) {
977 foreach ($user as $u) {
978 $twitter_user = $this->twitterUserArray($u);
979 array_push($users, $twitter_user);
982 while ($user->fetch()) {
983 $twitter_user = $this->twitterUserArray($user);
984 array_push($users, $twitter_user);
988 $this->showJsonObjects($users);
990 $this->endDocument('json');
993 function showSingleJsonGroup($group)
995 $this->initDocument('json');
996 $twitter_group = $this->twitterGroupArray($group);
997 $this->showJsonObjects($twitter_group);
998 $this->endDocument('json');
1001 function showSingleXmlGroup($group)
1003 $this->initDocument('xml');
1004 $twitter_group = $this->twitterGroupArray($group);
1005 $this->showTwitterXmlGroup($twitter_group);
1006 $this->endDocument('xml');
1009 function dateTwitter($dt)
1011 $dateStr = date('d F Y H:i:s', strtotime($dt));
1012 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1013 $d->setTimezone(new DateTimeZone(common_timezone()));
1014 return $d->format('D M d H:i:s O Y');
1017 function initDocument($type='xml')
1021 header('Content-Type: application/xml; charset=utf-8');
1025 header('Content-Type: application/json; charset=utf-8');
1027 // Check for JSONP callback
1028 $callback = $this->arg('callback');
1030 print $callback . '(';
1034 header("Content-Type: application/rss+xml; charset=utf-8");
1035 $this->initTwitterRss();
1038 header('Content-Type: application/atom+xml; charset=utf-8');
1039 $this->initTwitterAtom();
1042 $this->clientError(_('Not a supported data format.'));
1049 function endDocument($type='xml')
1057 // Check for JSONP callback
1058 $callback = $this->arg('callback');
1064 $this->endTwitterRss();
1067 $this->endTwitterRss();
1070 $this->clientError(_('Not a supported data format.'));
1076 function clientError($msg, $code = 400, $format = 'xml')
1078 $action = $this->trimmed('action');
1080 common_debug("User error '$code' on '$action': $msg", __FILE__);
1082 if (!array_key_exists($code, ClientErrorAction::$status)) {
1086 $status_string = ClientErrorAction::$status[$code];
1088 header('HTTP/1.1 '.$code.' '.$status_string);
1090 if ($format == 'xml') {
1091 $this->initDocument('xml');
1092 $this->elementStart('hash');
1093 $this->element('error', null, $msg);
1094 $this->element('request', null, $_SERVER['REQUEST_URI']);
1095 $this->elementEnd('hash');
1096 $this->endDocument('xml');
1097 } elseif ($format == 'json'){
1098 $this->initDocument('json');
1099 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1100 print(json_encode($error_array));
1101 $this->endDocument('json');
1104 // If user didn't request a useful format, throw a regular client error
1105 throw new ClientException($msg, $code);
1109 function serverError($msg, $code = 500, $content_type = 'xml')
1111 $action = $this->trimmed('action');
1113 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1115 if (!array_key_exists($code, ServerErrorAction::$status)) {
1119 $status_string = ServerErrorAction::$status[$code];
1121 header('HTTP/1.1 '.$code.' '.$status_string);
1123 if ($content_type == 'xml') {
1124 $this->initDocument('xml');
1125 $this->elementStart('hash');
1126 $this->element('error', null, $msg);
1127 $this->element('request', null, $_SERVER['REQUEST_URI']);
1128 $this->elementEnd('hash');
1129 $this->endDocument('xml');
1131 $this->initDocument('json');
1132 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1133 print(json_encode($error_array));
1134 $this->endDocument('json');
1138 function initTwitterRss()
1141 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1142 $this->elementStart('channel');
1143 Event::handle('StartApiRss', array($this));
1146 function endTwitterRss()
1148 $this->elementEnd('channel');
1149 $this->elementEnd('rss');
1153 function initTwitterAtom()
1156 // FIXME: don't hardcode the language here!
1157 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1158 'xml:lang' => 'en-US',
1159 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1162 function endTwitterAtom()
1164 $this->elementEnd('feed');
1168 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1170 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1171 switch ($content_type) {
1173 $this->showTwitterXmlUser($profile_array);
1176 $this->showJsonObjects($profile_array);
1179 $this->clientError(_('Not a supported data format.'));
1185 function getTargetUser($id)
1189 // Twitter supports these other ways of passing the user ID
1190 if (is_numeric($this->arg('id'))) {
1191 return User::staticGet($this->arg('id'));
1192 } else if ($this->arg('id')) {
1193 $nickname = common_canonical_nickname($this->arg('id'));
1194 return User::staticGet('nickname', $nickname);
1195 } else if ($this->arg('user_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('user_id'))) {
1199 return User::staticGet('id', $this->arg('user_id'));
1201 } else if ($this->arg('screen_name')) {
1202 $nickname = common_canonical_nickname($this->arg('screen_name'));
1203 return User::staticGet('nickname', $nickname);
1205 // Fall back to trying the currently authenticated user
1206 return $this->auth_user;
1209 } else if (is_numeric($id)) {
1210 return User::staticGet($id);
1212 $nickname = common_canonical_nickname($id);
1213 return User::staticGet('nickname', $nickname);
1217 function getTargetGroup($id)
1220 if (is_numeric($this->arg('id'))) {
1221 return User_group::staticGet($this->arg('id'));
1222 } else if ($this->arg('id')) {
1223 $nickname = common_canonical_nickname($this->arg('id'));
1224 $local = Local_group::staticGet('nickname', $nickname);
1225 if (empty($local)) {
1228 return User_group::staticGet('id', $local->id);
1230 } else if ($this->arg('group_id')) {
1231 // This is to ensure that a non-numeric user_id still
1232 // overrides screen_name even if it doesn't get used
1233 if (is_numeric($this->arg('group_id'))) {
1234 return User_group::staticGet('id', $this->arg('group_id'));
1236 } else if ($this->arg('group_name')) {
1237 $nickname = common_canonical_nickname($this->arg('group_name'));
1238 $local = Local_group::staticGet('nickname', $nickname);
1239 if (empty($local)) {
1242 return User_group::staticGet('id', $local->id);
1246 } else if (is_numeric($id)) {
1247 return User_group::staticGet($id);
1249 $nickname = common_canonical_nickname($id);
1250 $local = Local_group::staticGet('nickname', $nickname);
1251 if (empty($local)) {
1254 return User_group::staticGet('id', $local->group_id);
1259 function sourceLink($source)
1261 $source_name = _($source);
1274 $ns = Notice_source::staticGet($source);
1280 $app = Oauth_application::staticGet('name', $source);
1283 $url = $app->source_url;
1287 if (!empty($name) && !empty($url)) {
1288 $source_name = '<a href="' . $url . '">' . $name . '</a>';
1293 return $source_name;
1297 * Returns query argument or default value if not found. Certain
1298 * parameters used throughout the API are lightly scrubbed and
1299 * bounds checked. This overrides Action::arg().
1301 * @param string $key requested argument
1302 * @param string $def default value to return if $key is not provided
1306 function arg($key, $def=null)
1309 // XXX: Do even more input validation/scrubbing?
1311 if (array_key_exists($key, $this->args)) {
1314 $page = (int)$this->args['page'];
1315 return ($page < 1) ? 1 : $page;
1317 $count = (int)$this->args['count'];
1320 } elseif ($count > 200) {
1326 $since_id = (int)$this->args['since_id'];
1327 return ($since_id < 1) ? 0 : $since_id;
1329 $max_id = (int)$this->args['max_id'];
1330 return ($max_id < 1) ? 0 : $max_id;
1332 return parent::arg($key, $def);
1339 function getSelfUri($action, $aargs)
1341 parse_str($_SERVER['QUERY_STRING'], $params);
1343 if (!empty($params)) {
1344 unset($params['p']);
1345 $pstring = http_build_query($params);
1348 $uri = common_local_url($action, $aargs);
1350 if (!empty($pstring)) {
1351 $uri .= '?' . $pstring;