3 * StatusNet, the distributed open-source microblogging tool
9 * LICENCE: This program is free software: you can redistribute it and/or modify
10 * it under the terms of the GNU Affero General Public License as published by
11 * the Free Software Foundation, either version 3 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU Affero General Public License for more details.
19 * You should have received a copy of the GNU Affero General Public License
20 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24 * @author Craig Andrews <candrews@integralblue.com>
25 * @author Dan Moore <dan@moore.cx>
26 * @author Evan Prodromou <evan@status.net>
27 * @author Jeffery To <jeffery.to@gmail.com>
28 * @author Toby Inkster <mail@tobyinkster.co.uk>
29 * @author Zach Copley <zach@status.net>
30 * @copyright 2009 StatusNet, Inc.
31 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
32 * @link http://status.net/
35 if (!defined('STATUSNET')) {
40 * Contains most of the Twitter-compatible API output functions.
44 * @author Craig Andrews <candrews@integralblue.com>
45 * @author Dan Moore <dan@moore.cx>
46 * @author Evan Prodromou <evan@status.net>
47 * @author Jeffery To <jeffery.to@gmail.com>
48 * @author Toby Inkster <mail@tobyinkster.co.uk>
49 * @author Zach Copley <zach@status.net>
50 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51 * @link http://status.net/
54 class ApiAction extends Action
61 var $auth_user = null;
68 var $access = self::READ_ONLY; // read (default) or read-write
73 * @param array $args Web and URL arguments
75 * @return boolean false if user doesn't exist
78 function prepare($args)
80 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);
87 $this->since = $this->arg('since');
95 * @param array $args Arguments from $_REQUEST
100 function handle($args)
102 parent::handle($args);
106 * Overrides XMLOutputter::element to write booleans as strings (true|false).
107 * See that method's documentation for more info.
109 * @param string $tag Element type or tagname
110 * @param array $attrs Array of element attributes, as
112 * @param string $content string content of the element
116 function element($tag, $attrs=null, $content=null)
118 if (is_bool($content)) {
119 $content = ($content ? 'true' : 'false');
122 return parent::element($tag, $attrs, $content);
125 function twitterUserArray($profile, $get_notice=false)
127 $twitter_user = array();
129 $twitter_user['id'] = intval($profile->id);
130 $twitter_user['name'] = $profile->getBestName();
131 $twitter_user['screen_name'] = $profile->nickname;
132 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
133 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
135 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
136 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
137 Avatar::defaultImage(AVATAR_STREAM_SIZE);
139 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
140 $twitter_user['protected'] = false; # not supported by StatusNet yet
141 $twitter_user['followers_count'] = $profile->subscriberCount();
144 $user = $profile->getUser();
146 // Note: some profiles don't have an associated user
148 $defaultDesign = Design::siteDesign();
151 $design = $user->getDesign();
154 if (empty($design)) {
155 $design = $defaultDesign;
158 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
159 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
160 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
161 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
162 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
163 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
164 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
165 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
166 $twitter_user['profile_sidebar_border_color'] = '';
168 $twitter_user['friends_count'] = $profile->subscriptionCount();
170 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
172 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
176 if (!empty($user) && $user->timezone) {
177 $timezone = $user->timezone;
181 $t->setTimezone(new DateTimeZone($timezone));
183 $twitter_user['utc_offset'] = $t->format('Z');
184 $twitter_user['time_zone'] = $timezone;
186 $twitter_user['profile_background_image_url']
187 = empty($design->backgroundimage)
188 ? '' : ($design->disposition & BACKGROUND_ON)
189 ? Design::url($design->backgroundimage) : '';
191 $twitter_user['profile_background_tile']
192 = empty($design->disposition)
193 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
195 $twitter_user['statuses_count'] = $profile->noticeCount();
197 // Is the requesting user following this user?
198 $twitter_user['following'] = false;
199 $twitter_user['notifications'] = false;
201 if (isset($this->auth_user)) {
203 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
206 $sub = Subscription::pkeyGet(array('subscriber' =>
207 $this->auth_user->id,
208 'subscribed' => $profile->id));
211 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
216 $notice = $profile->getCurrentNotice();
219 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
223 return $twitter_user;
226 function twitterStatusArray($notice, $include_user=true)
228 $base = $this->twitterSimpleStatusArray($notice, $include_user);
230 if (!empty($notice->repeat_of)) {
231 $original = Notice::staticGet('id', $notice->repeat_of);
232 if (!empty($original)) {
233 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
234 $base['retweeted_status'] = $original_array;
241 function twitterSimpleStatusArray($notice, $include_user=true)
243 $profile = $notice->getProfile();
245 $twitter_status = array();
246 $twitter_status['text'] = $notice->content;
247 $twitter_status['truncated'] = false; # Not possible on StatusNet
248 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
249 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
250 intval($notice->reply_to) : null;
251 $twitter_status['source'] = $this->sourceLink($notice->source);
252 $twitter_status['id'] = intval($notice->id);
254 $replier_profile = null;
256 if ($notice->reply_to) {
257 $reply = Notice::staticGet(intval($notice->reply_to));
259 $replier_profile = $reply->getProfile();
263 $twitter_status['in_reply_to_user_id'] =
264 ($replier_profile) ? intval($replier_profile->id) : null;
265 $twitter_status['in_reply_to_screen_name'] =
266 ($replier_profile) ? $replier_profile->nickname : null;
268 if (isset($notice->lat) && isset($notice->lon)) {
269 // This is the format that GeoJSON expects stuff to be in
270 $twitter_status['geo'] = array('type' => 'Point',
271 'coordinates' => array((float) $notice->lat,
272 (float) $notice->lon));
274 $twitter_status['geo'] = null;
277 if (isset($this->auth_user)) {
278 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
280 $twitter_status['favorited'] = false;
284 $attachments = $notice->attachments();
286 if (!empty($attachments)) {
288 $twitter_status['attachments'] = array();
290 foreach ($attachments as $attachment) {
291 if ($attachment->isEnclosure()) {
292 $enclosure = array();
293 $enclosure['url'] = $attachment->url;
294 $enclosure['mimetype'] = $attachment->mimetype;
295 $enclosure['size'] = $attachment->size;
296 $twitter_status['attachments'][] = $enclosure;
301 if ($include_user && $profile) {
302 # Don't get notice (recursive!)
303 $twitter_user = $this->twitterUserArray($profile, false);
304 $twitter_status['user'] = $twitter_user;
307 return $twitter_status;
310 function twitterGroupArray($group)
312 $twitter_group=array();
313 $twitter_group['id']=$group->id;
314 $twitter_group['url']=$group->permalink();
315 $twitter_group['nickname']=$group->nickname;
316 $twitter_group['fullname']=$group->fullname;
317 $twitter_group['homepage_url']=$group->homepage_url;
318 $twitter_group['original_logo']=$group->original_logo;
319 $twitter_group['homepage_logo']=$group->homepage_logo;
320 $twitter_group['stream_logo']=$group->stream_logo;
321 $twitter_group['mini_logo']=$group->mini_logo;
322 $twitter_group['homepage']=$group->homepage;
323 $twitter_group['description']=$group->description;
324 $twitter_group['location']=$group->location;
325 $twitter_group['created']=$this->dateTwitter($group->created);
326 $twitter_group['modified']=$this->dateTwitter($group->modified);
327 return $twitter_group;
330 function twitterRssGroupArray($group)
333 $entry['content']=$group->description;
334 $entry['title']=$group->nickname;
335 $entry['link']=$group->permalink();
336 $entry['published']=common_date_iso8601($group->created);
337 $entry['updated']==common_date_iso8601($group->modified);
338 $taguribase = common_config('integration', 'groupuri');
339 $entry['id'] = "group:$groupuribase:$entry[link]";
341 $entry['description'] = $entry['content'];
342 $entry['pubDate'] = common_date_rfc2822($group->created);
343 $entry['guid'] = $entry['link'];
348 function twitterRssEntryArray($notice)
350 $profile = $notice->getProfile();
353 // We trim() to avoid extraneous whitespace in the output
355 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
356 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
357 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
358 $entry['published'] = common_date_iso8601($notice->created);
360 $taguribase = common_config('integration', 'taguri');
361 $entry['id'] = "tag:$taguribase:$entry[link]";
363 $entry['updated'] = $entry['published'];
364 $entry['author'] = $profile->getBestName();
367 $attachments = $notice->attachments();
368 $enclosures = array();
370 foreach ($attachments as $attachment) {
371 $enclosure_o=$attachment->getEnclosure();
373 $enclosure = array();
374 $enclosure['url'] = $enclosure_o->url;
375 $enclosure['mimetype'] = $enclosure_o->mimetype;
376 $enclosure['size'] = $enclosure_o->size;
377 $enclosures[] = $enclosure;
381 if (!empty($enclosures)) {
382 $entry['enclosures'] = $enclosures;
386 $tag = new Notice_tag();
387 $tag->notice_id = $notice->id;
389 $entry['tags']=array();
390 while ($tag->fetch()) {
391 $entry['tags'][]=$tag->tag;
397 $entry['description'] = $entry['content'];
398 $entry['pubDate'] = common_date_rfc2822($notice->created);
399 $entry['guid'] = $entry['link'];
401 if (isset($notice->lat) && isset($notice->lon)) {
402 // This is the format that GeoJSON expects stuff to be in.
403 // showGeoRSS() below uses it for XML output, so we reuse it
404 $entry['geo'] = array('type' => 'Point',
405 'coordinates' => array((float) $notice->lat,
406 (float) $notice->lon));
408 $entry['geo'] = null;
414 function twitterRelationshipArray($source, $target)
416 $relationship = array();
418 $relationship['source'] =
419 $this->relationshipDetailsArray($source, $target);
420 $relationship['target'] =
421 $this->relationshipDetailsArray($target, $source);
423 return array('relationship' => $relationship);
426 function relationshipDetailsArray($source, $target)
430 $details['screen_name'] = $source->nickname;
431 $details['followed_by'] = $target->isSubscribed($source);
432 $details['following'] = $source->isSubscribed($target);
434 $notifications = false;
436 if ($source->isSubscribed($target)) {
438 $sub = Subscription::pkeyGet(array('subscriber' =>
439 $source->id, 'subscribed' => $target->id));
442 $notifications = ($sub->jabber || $sub->sms);
446 $details['notifications_enabled'] = $notifications;
447 $details['blocking'] = $source->hasBlocked($target);
448 $details['id'] = $source->id;
453 function showTwitterXmlRelationship($relationship)
455 $this->elementStart('relationship');
457 foreach($relationship as $element => $value) {
458 if ($element == 'source' || $element == 'target') {
459 $this->elementStart($element);
460 $this->showXmlRelationshipDetails($value);
461 $this->elementEnd($element);
465 $this->elementEnd('relationship');
468 function showXmlRelationshipDetails($details)
470 foreach($details as $element => $value) {
471 $this->element($element, null, $value);
475 function showTwitterXmlStatus($twitter_status, $tag='status')
477 $this->elementStart($tag);
478 foreach($twitter_status as $element => $value) {
481 $this->showTwitterXmlUser($twitter_status['user']);
484 $this->element($element, null, common_xml_safe_str($value));
487 $this->showXmlAttachments($twitter_status['attachments']);
490 $this->showGeoRSS($value);
492 case 'retweeted_status':
493 $this->showTwitterXmlStatus($value, 'retweeted_status');
496 $this->element($element, null, $value);
499 $this->elementEnd($tag);
502 function showTwitterXmlGroup($twitter_group)
504 $this->elementStart('group');
505 foreach($twitter_group as $element => $value) {
506 $this->element($element, null, $value);
508 $this->elementEnd('group');
511 function showTwitterXmlUser($twitter_user, $role='user')
513 $this->elementStart($role);
514 foreach($twitter_user as $element => $value) {
515 if ($element == 'status') {
516 $this->showTwitterXmlStatus($twitter_user['status']);
518 $this->element($element, null, $value);
521 $this->elementEnd($role);
524 function showXmlAttachments($attachments) {
525 if (!empty($attachments)) {
526 $this->elementStart('attachments', array('type' => 'array'));
527 foreach ($attachments as $attachment) {
529 $attrs['url'] = $attachment['url'];
530 $attrs['mimetype'] = $attachment['mimetype'];
531 $attrs['size'] = $attachment['size'];
532 $this->element('enclosure', $attrs, '');
534 $this->elementEnd('attachments');
538 function showGeoRSS($geo)
542 $this->element('geo');
544 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
545 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
546 $this->elementEnd('geo');
550 function showTwitterRssItem($entry)
552 $this->elementStart('item');
553 $this->element('title', null, $entry['title']);
554 $this->element('description', null, $entry['description']);
555 $this->element('pubDate', null, $entry['pubDate']);
556 $this->element('guid', null, $entry['guid']);
557 $this->element('link', null, $entry['link']);
559 # RSS only supports 1 enclosure per item
560 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
561 $enclosure = $entry['enclosures'][0];
562 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
565 if(array_key_exists('tags', $entry)){
566 foreach($entry['tags'] as $tag){
567 $this->element('category', null,$tag);
571 $this->showGeoRSS($entry['geo']);
572 $this->elementEnd('item');
575 function showJsonObjects($objects)
577 print(json_encode($objects));
580 function showSingleXmlStatus($notice)
582 $this->initDocument('xml');
583 $twitter_status = $this->twitterStatusArray($notice);
584 $this->showTwitterXmlStatus($twitter_status);
585 $this->endDocument('xml');
588 function show_single_json_status($notice)
590 $this->initDocument('json');
591 $status = $this->twitterStatusArray($notice);
592 $this->showJsonObjects($status);
593 $this->endDocument('json');
596 function showXmlTimeline($notice)
599 $this->initDocument('xml');
600 $this->elementStart('statuses', array('type' => 'array'));
602 if (is_array($notice)) {
603 foreach ($notice as $n) {
604 $twitter_status = $this->twitterStatusArray($n);
605 $this->showTwitterXmlStatus($twitter_status);
608 while ($notice->fetch()) {
609 $twitter_status = $this->twitterStatusArray($notice);
610 $this->showTwitterXmlStatus($twitter_status);
614 $this->elementEnd('statuses');
615 $this->endDocument('xml');
618 function showRssTimeline($notice, $title, $link, $subtitle, $suplink=null, $logo=null)
621 $this->initDocument('rss');
623 $this->element('title', null, $title);
624 $this->element('link', null, $link);
625 if (!is_null($suplink)) {
626 // For FriendFeed's SUP protocol
627 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
628 'rel' => 'http://api.friendfeed.com/2008/03#sup',
630 'type' => 'application/json'));
633 if (!is_null($logo)) {
634 $this->elementStart('image');
635 $this->element('link', null, $link);
636 $this->element('title', null, $title);
637 $this->element('url', null, $logo);
638 $this->elementEnd('image');
641 $this->element('description', null, $subtitle);
642 $this->element('language', null, 'en-us');
643 $this->element('ttl', null, '40');
645 if (is_array($notice)) {
646 foreach ($notice as $n) {
647 $entry = $this->twitterRssEntryArray($n);
648 $this->showTwitterRssItem($entry);
651 while ($notice->fetch()) {
652 $entry = $this->twitterRssEntryArray($notice);
653 $this->showTwitterRssItem($entry);
657 $this->endTwitterRss();
660 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
663 $this->initDocument('atom');
665 $this->element('title', null, $title);
666 $this->element('id', null, $id);
667 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
669 if (!is_null($logo)) {
670 $this->element('logo',null,$logo);
673 if (!is_null($suplink)) {
674 # For FriendFeed's SUP protocol
675 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
677 'type' => 'application/json'));
680 if (!is_null($selfuri)) {
681 $this->element('link', array('href' => $selfuri,
682 'rel' => 'self', 'type' => 'application/atom+xml'), null);
685 $this->element('updated', null, common_date_iso8601('now'));
686 $this->element('subtitle', null, $subtitle);
688 if (is_array($notice)) {
689 foreach ($notice as $n) {
690 $this->raw($n->asAtomEntry());
693 while ($notice->fetch()) {
694 $this->raw($notice->asAtomEntry());
698 $this->endDocument('atom');
702 function showRssGroups($group, $title, $link, $subtitle)
705 $this->initDocument('rss');
707 $this->element('title', null, $title);
708 $this->element('link', null, $link);
709 $this->element('description', null, $subtitle);
710 $this->element('language', null, 'en-us');
711 $this->element('ttl', null, '40');
713 if (is_array($group)) {
714 foreach ($group as $g) {
715 $twitter_group = $this->twitterRssGroupArray($g);
716 $this->showTwitterRssItem($twitter_group);
719 while ($group->fetch()) {
720 $twitter_group = $this->twitterRssGroupArray($group);
721 $this->showTwitterRssItem($twitter_group);
725 $this->endTwitterRss();
728 function showTwitterAtomEntry($entry)
730 $this->elementStart('entry');
731 $this->element('title', null, $entry['title']);
732 $this->element('content', array('type' => 'html'), $entry['content']);
733 $this->element('id', null, $entry['id']);
734 $this->element('published', null, $entry['published']);
735 $this->element('updated', null, $entry['updated']);
736 $this->element('link', array('type' => 'text/html',
737 'href' => $entry['link'],
738 'rel' => 'alternate'));
739 $this->element('link', array('type' => $entry['avatar-type'],
740 'href' => $entry['avatar'],
742 $this->elementStart('author');
744 $this->element('name', null, $entry['author-name']);
745 $this->element('uri', null, $entry['author-uri']);
747 $this->elementEnd('author');
748 $this->elementEnd('entry');
751 function showXmlDirectMessage($dm)
753 $this->elementStart('direct_message');
754 foreach($dm as $element => $value) {
758 $this->showTwitterXmlUser($value, $element);
761 $this->element($element, null, common_xml_safe_str($value));
764 $this->element($element, null, $value);
768 $this->elementEnd('direct_message');
771 function directMessageArray($message)
775 $from_profile = $message->getFrom();
776 $to_profile = $message->getTo();
778 $dmsg['id'] = $message->id;
779 $dmsg['sender_id'] = $message->from_profile;
780 $dmsg['text'] = trim($message->content);
781 $dmsg['recipient_id'] = $message->to_profile;
782 $dmsg['created_at'] = $this->dateTwitter($message->created);
783 $dmsg['sender_screen_name'] = $from_profile->nickname;
784 $dmsg['recipient_screen_name'] = $to_profile->nickname;
785 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
786 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
791 function rssDirectMessageArray($message)
795 $from = $message->getFrom();
797 $entry['title'] = sprintf('Message from %1$s to %2$s',
798 $from->nickname, $message->getTo()->nickname);
800 $entry['content'] = common_xml_safe_str($message->rendered);
801 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
802 $entry['published'] = common_date_iso8601($message->created);
804 $taguribase = common_config('integration', 'taguri');
806 $entry['id'] = "tag:$taguribase:$entry[link]";
807 $entry['updated'] = $entry['published'];
809 $entry['author-name'] = $from->getBestName();
810 $entry['author-uri'] = $from->homepage;
812 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
814 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
815 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
819 $entry['description'] = $entry['content'];
820 $entry['pubDate'] = common_date_rfc2822($message->created);
821 $entry['guid'] = $entry['link'];
826 function showSingleXmlDirectMessage($message)
828 $this->initDocument('xml');
829 $dmsg = $this->directMessageArray($message);
830 $this->showXmlDirectMessage($dmsg);
831 $this->endDocument('xml');
834 function showSingleJsonDirectMessage($message)
836 $this->initDocument('json');
837 $dmsg = $this->directMessageArray($message);
838 $this->showJsonObjects($dmsg);
839 $this->endDocument('json');
842 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
845 $this->initDocument('atom');
847 $this->element('title', null, $title);
848 $this->element('id', null, $id);
849 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
851 if (!is_null($selfuri)) {
852 $this->element('link', array('href' => $selfuri,
853 'rel' => 'self', 'type' => 'application/atom+xml'), null);
856 $this->element('updated', null, common_date_iso8601('now'));
857 $this->element('subtitle', null, $subtitle);
859 if (is_array($group)) {
860 foreach ($group as $g) {
861 $this->raw($g->asAtomEntry());
864 while ($group->fetch()) {
865 $this->raw($group->asAtomEntry());
869 $this->endDocument('atom');
873 function showJsonTimeline($notice)
876 $this->initDocument('json');
880 if (is_array($notice)) {
881 foreach ($notice as $n) {
882 $twitter_status = $this->twitterStatusArray($n);
883 array_push($statuses, $twitter_status);
886 while ($notice->fetch()) {
887 $twitter_status = $this->twitterStatusArray($notice);
888 array_push($statuses, $twitter_status);
892 $this->showJsonObjects($statuses);
894 $this->endDocument('json');
897 function showJsonGroups($group)
900 $this->initDocument('json');
904 if (is_array($group)) {
905 foreach ($group as $g) {
906 $twitter_group = $this->twitterGroupArray($g);
907 array_push($groups, $twitter_group);
910 while ($group->fetch()) {
911 $twitter_group = $this->twitterGroupArray($group);
912 array_push($groups, $twitter_group);
916 $this->showJsonObjects($groups);
918 $this->endDocument('json');
921 function showXmlGroups($group)
924 $this->initDocument('xml');
925 $this->elementStart('groups', array('type' => 'array'));
927 if (is_array($group)) {
928 foreach ($group as $g) {
929 $twitter_group = $this->twitterGroupArray($g);
930 $this->showTwitterXmlGroup($twitter_group);
933 while ($group->fetch()) {
934 $twitter_group = $this->twitterGroupArray($group);
935 $this->showTwitterXmlGroup($twitter_group);
939 $this->elementEnd('groups');
940 $this->endDocument('xml');
943 function showTwitterXmlUsers($user)
946 $this->initDocument('xml');
947 $this->elementStart('users', array('type' => 'array'));
949 if (is_array($user)) {
950 foreach ($user as $u) {
951 $twitter_user = $this->twitterUserArray($u);
952 $this->showTwitterXmlUser($twitter_user);
955 while ($user->fetch()) {
956 $twitter_user = $this->twitterUserArray($user);
957 $this->showTwitterXmlUser($twitter_user);
961 $this->elementEnd('users');
962 $this->endDocument('xml');
965 function showJsonUsers($user)
968 $this->initDocument('json');
972 if (is_array($user)) {
973 foreach ($user as $u) {
974 $twitter_user = $this->twitterUserArray($u);
975 array_push($users, $twitter_user);
978 while ($user->fetch()) {
979 $twitter_user = $this->twitterUserArray($user);
980 array_push($users, $twitter_user);
984 $this->showJsonObjects($users);
986 $this->endDocument('json');
989 function showSingleJsonGroup($group)
991 $this->initDocument('json');
992 $twitter_group = $this->twitterGroupArray($group);
993 $this->showJsonObjects($twitter_group);
994 $this->endDocument('json');
997 function showSingleXmlGroup($group)
999 $this->initDocument('xml');
1000 $twitter_group = $this->twitterGroupArray($group);
1001 $this->showTwitterXmlGroup($twitter_group);
1002 $this->endDocument('xml');
1005 function dateTwitter($dt)
1007 $dateStr = date('d F Y H:i:s', strtotime($dt));
1008 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1009 $d->setTimezone(new DateTimeZone(common_timezone()));
1010 return $d->format('D M d H:i:s O Y');
1013 function initDocument($type='xml')
1017 header('Content-Type: application/xml; charset=utf-8');
1021 header('Content-Type: application/json; charset=utf-8');
1023 // Check for JSONP callback
1024 $callback = $this->arg('callback');
1026 print $callback . '(';
1030 header("Content-Type: application/rss+xml; charset=utf-8");
1031 $this->initTwitterRss();
1034 header('Content-Type: application/atom+xml; charset=utf-8');
1035 $this->initTwitterAtom();
1038 $this->clientError(_('Not a supported data format.'));
1045 function endDocument($type='xml')
1053 // Check for JSONP callback
1054 $callback = $this->arg('callback');
1060 $this->endTwitterRss();
1063 $this->endTwitterRss();
1066 $this->clientError(_('Not a supported data format.'));
1072 function clientError($msg, $code = 400, $format = 'xml')
1074 $action = $this->trimmed('action');
1076 common_debug("User error '$code' on '$action': $msg", __FILE__);
1078 if (!array_key_exists($code, ClientErrorAction::$status)) {
1082 $status_string = ClientErrorAction::$status[$code];
1084 header('HTTP/1.1 '.$code.' '.$status_string);
1086 if ($format == 'xml') {
1087 $this->initDocument('xml');
1088 $this->elementStart('hash');
1089 $this->element('error', null, $msg);
1090 $this->element('request', null, $_SERVER['REQUEST_URI']);
1091 $this->elementEnd('hash');
1092 $this->endDocument('xml');
1093 } elseif ($format == 'json'){
1094 $this->initDocument('json');
1095 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1096 print(json_encode($error_array));
1097 $this->endDocument('json');
1100 // If user didn't request a useful format, throw a regular client error
1101 throw new ClientException($msg, $code);
1105 function serverError($msg, $code = 500, $content_type = 'json')
1107 $action = $this->trimmed('action');
1109 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1111 if (!array_key_exists($code, ServerErrorAction::$status)) {
1115 $status_string = ServerErrorAction::$status[$code];
1117 header('HTTP/1.1 '.$code.' '.$status_string);
1119 if ($content_type == 'xml') {
1120 $this->initDocument('xml');
1121 $this->elementStart('hash');
1122 $this->element('error', null, $msg);
1123 $this->element('request', null, $_SERVER['REQUEST_URI']);
1124 $this->elementEnd('hash');
1125 $this->endDocument('xml');
1127 $this->initDocument('json');
1128 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1129 print(json_encode($error_array));
1130 $this->endDocument('json');
1134 function initTwitterRss()
1137 $this->elementStart('rss', array('version' => '2.0', 'xmlns:atom'=>'http://www.w3.org/2005/Atom'));
1138 $this->elementStart('channel');
1139 Event::handle('StartApiRss', array($this));
1142 function endTwitterRss()
1144 $this->elementEnd('channel');
1145 $this->elementEnd('rss');
1149 function initTwitterAtom()
1152 // FIXME: don't hardcode the language here!
1153 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1154 'xml:lang' => 'en-US',
1155 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1156 Event::handle('StartApiAtom', array($this));
1159 function endTwitterAtom()
1161 $this->elementEnd('feed');
1165 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1167 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1168 switch ($content_type) {
1170 $this->showTwitterXmlUser($profile_array);
1173 $this->showJsonObjects($profile_array);
1176 $this->clientError(_('Not a supported data format.'));
1182 function getTargetUser($id)
1186 // Twitter supports these other ways of passing the user ID
1187 if (is_numeric($this->arg('id'))) {
1188 return User::staticGet($this->arg('id'));
1189 } else if ($this->arg('id')) {
1190 $nickname = common_canonical_nickname($this->arg('id'));
1191 return User::staticGet('nickname', $nickname);
1192 } else if ($this->arg('user_id')) {
1193 // This is to ensure that a non-numeric user_id still
1194 // overrides screen_name even if it doesn't get used
1195 if (is_numeric($this->arg('user_id'))) {
1196 return User::staticGet('id', $this->arg('user_id'));
1198 } else if ($this->arg('screen_name')) {
1199 $nickname = common_canonical_nickname($this->arg('screen_name'));
1200 return User::staticGet('nickname', $nickname);
1202 // Fall back to trying the currently authenticated user
1203 return $this->auth_user;
1206 } else if (is_numeric($id)) {
1207 return User::staticGet($id);
1209 $nickname = common_canonical_nickname($id);
1210 return User::staticGet('nickname', $nickname);
1214 function getTargetGroup($id)
1217 if (is_numeric($this->arg('id'))) {
1218 return User_group::staticGet($this->arg('id'));
1219 } else if ($this->arg('id')) {
1220 $nickname = common_canonical_nickname($this->arg('id'));
1221 return User_group::staticGet('nickname', $nickname);
1222 } else if ($this->arg('group_id')) {
1223 // This is to ensure that a non-numeric user_id still
1224 // overrides screen_name even if it doesn't get used
1225 if (is_numeric($this->arg('group_id'))) {
1226 return User_group::staticGet('id', $this->arg('group_id'));
1228 } else if ($this->arg('group_name')) {
1229 $nickname = common_canonical_nickname($this->arg('group_name'));
1230 return User_group::staticGet('nickname', $nickname);
1233 } else if (is_numeric($id)) {
1234 return User_group::staticGet($id);
1236 $nickname = common_canonical_nickname($id);
1237 return User_group::staticGet('nickname', $nickname);
1241 function sourceLink($source)
1243 $source_name = _($source);
1256 $ns = Notice_source::staticGet($source);
1262 $app = Oauth_application::staticGet('name', $source);
1265 $url = $app->source_url;
1269 if (!empty($name) && !empty($url)) {
1270 $source_name = '<a href="' . $url . '">' . $name . '</a>';
1275 return $source_name;
1279 * Returns query argument or default value if not found. Certain
1280 * parameters used throughout the API are lightly scrubbed and
1281 * bounds checked. This overrides Action::arg().
1283 * @param string $key requested argument
1284 * @param string $def default value to return if $key is not provided
1288 function arg($key, $def=null)
1291 // XXX: Do even more input validation/scrubbing?
1293 if (array_key_exists($key, $this->args)) {
1296 $page = (int)$this->args['page'];
1297 return ($page < 1) ? 1 : $page;
1299 $count = (int)$this->args['count'];
1302 } elseif ($count > 200) {
1308 $since_id = (int)$this->args['since_id'];
1309 return ($since_id < 1) ? 0 : $since_id;
1311 $max_id = (int)$this->args['max_id'];
1312 return ($max_id < 1) ? 0 : $max_id;
1314 return strtotime($this->args['since']);
1316 return parent::arg($key, $def);