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-2010 StatusNet, Inc.
31 * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
32 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
33 * @link http://status.net/
36 /* External API usage documentation. Please update when you change how the API works. */
38 /*! @mainpage StatusNet REST API
42 Some explanatory text about the API would be nice.
46 @subsection timelinesmethods_sec Timeline Methods
48 @li @ref publictimeline
49 @li @ref friendstimeline
51 @subsection statusmethods_sec Status Methods
53 @li @ref statusesupdate
55 @subsection usermethods_sec User Methods
57 @subsection directmessagemethods_sec Direct Message Methods
59 @subsection friendshipmethods_sec Friendship Methods
61 @subsection socialgraphmethods_sec Social Graph Methods
63 @subsection accountmethods_sec Account Methods
65 @subsection favoritesmethods_sec Favorites Methods
67 @subsection blockmethods_sec Block Methods
69 @subsection oauthmethods_sec OAuth Methods
71 @subsection helpmethods_sec Help Methods
73 @subsection groupmethods_sec Group Methods
75 @page apiroot API Root
77 The URLs for methods referred to in this API documentation are
78 relative to the StatusNet API root. The API root is determined by the
79 site's @b server and @b path variables, which are generally specified
80 in config.php. For example:
83 $config['site']['server'] = 'example.org';
84 $config['site']['path'] = 'statusnet'
87 The pattern for a site's API root is: @c protocol://server/path/api E.g:
89 @c http://example.org/statusnet/api
91 The @b path can be empty. In that case the API root would simply be:
93 @c http://example.org/api
97 if (!defined('STATUSNET')) {
101 class ApiValidationException extends Exception { }
104 * Contains most of the Twitter-compatible API output functions.
108 * @author Craig Andrews <candrews@integralblue.com>
109 * @author Dan Moore <dan@moore.cx>
110 * @author Evan Prodromou <evan@status.net>
111 * @author Jeffery To <jeffery.to@gmail.com>
112 * @author Toby Inkster <mail@tobyinkster.co.uk>
113 * @author Zach Copley <zach@status.net>
114 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
115 * @link http://status.net/
117 class ApiAction extends Action
120 const READ_WRITE = 2;
124 var $auth_user = null;
128 var $since_id = null;
130 var $callback = null;
132 var $access = self::READ_ONLY; // read (default) or read-write
134 static $reserved_sources = array('web', 'omb', 'ostatus', 'mail', 'xmpp', 'api');
139 * @param array $args Web and URL arguments
141 * @return boolean false if user doesn't exist
143 function prepare($args)
145 StatusNet::setApi(true); // reduce exception reports to aid in debugging
146 parent::prepare($args);
148 $this->format = $this->arg('format');
149 $this->callback = $this->arg('callback');
150 $this->page = (int)$this->arg('page', 1);
151 $this->count = (int)$this->arg('count', 20);
152 $this->max_id = (int)$this->arg('max_id', 0);
153 $this->since_id = (int)$this->arg('since_id', 0);
155 if ($this->arg('since')) {
156 header('X-StatusNet-Warning: since parameter is disabled; use since_id');
159 $this->source = $this->trimmed('source');
161 if (empty($this->source) || in_array($this->source, self::$reserved_sources)) {
162 $this->source = 'api';
171 * @param array $args Arguments from $_REQUEST
175 function handle($args)
177 header('Access-Control-Allow-Origin: *');
178 parent::handle($args);
182 * Overrides XMLOutputter::element to write booleans as strings (true|false).
183 * See that method's documentation for more info.
185 * @param string $tag Element type or tagname
186 * @param array $attrs Array of element attributes, as
188 * @param string $content string content of the element
192 function element($tag, $attrs=null, $content=null)
194 if (is_bool($content)) {
195 $content = ($content ? 'true' : 'false');
198 return parent::element($tag, $attrs, $content);
201 function twitterUserArray($profile, $get_notice=false)
203 $twitter_user = array();
205 $twitter_user['id'] = intval($profile->id);
206 $twitter_user['name'] = $profile->getBestName();
207 $twitter_user['screen_name'] = $profile->nickname;
208 $twitter_user['location'] = ($profile->location) ? $profile->location : null;
209 $twitter_user['description'] = ($profile->bio) ? $profile->bio : null;
211 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
212 $twitter_user['profile_image_url'] = ($avatar) ? $avatar->displayUrl() :
213 Avatar::defaultImage(AVATAR_STREAM_SIZE);
215 $twitter_user['url'] = ($profile->homepage) ? $profile->homepage : null;
216 $twitter_user['protected'] = false; # not supported by StatusNet yet
217 $twitter_user['followers_count'] = $profile->subscriberCount();
220 $user = $profile->getUser();
222 // Note: some profiles don't have an associated user
224 $defaultDesign = Design::siteDesign();
227 $design = $user->getDesign();
230 if (empty($design)) {
231 $design = $defaultDesign;
234 $color = Design::toWebColor(empty($design->backgroundcolor) ? $defaultDesign->backgroundcolor : $design->backgroundcolor);
235 $twitter_user['profile_background_color'] = ($color == null) ? '' : '#'.$color->hexValue();
236 $color = Design::toWebColor(empty($design->textcolor) ? $defaultDesign->textcolor : $design->textcolor);
237 $twitter_user['profile_text_color'] = ($color == null) ? '' : '#'.$color->hexValue();
238 $color = Design::toWebColor(empty($design->linkcolor) ? $defaultDesign->linkcolor : $design->linkcolor);
239 $twitter_user['profile_link_color'] = ($color == null) ? '' : '#'.$color->hexValue();
240 $color = Design::toWebColor(empty($design->sidebarcolor) ? $defaultDesign->sidebarcolor : $design->sidebarcolor);
241 $twitter_user['profile_sidebar_fill_color'] = ($color == null) ? '' : '#'.$color->hexValue();
242 $twitter_user['profile_sidebar_border_color'] = '';
244 $twitter_user['friends_count'] = $profile->subscriptionCount();
246 $twitter_user['created_at'] = $this->dateTwitter($profile->created);
248 $twitter_user['favourites_count'] = $profile->faveCount(); // British spelling!
252 if (!empty($user) && $user->timezone) {
253 $timezone = $user->timezone;
257 $t->setTimezone(new DateTimeZone($timezone));
259 $twitter_user['utc_offset'] = $t->format('Z');
260 $twitter_user['time_zone'] = $timezone;
262 $twitter_user['profile_background_image_url']
263 = empty($design->backgroundimage)
264 ? '' : ($design->disposition & BACKGROUND_ON)
265 ? Design::url($design->backgroundimage) : '';
267 $twitter_user['profile_background_tile']
268 = empty($design->disposition)
269 ? '' : ($design->disposition & BACKGROUND_TILE) ? 'true' : 'false';
271 $twitter_user['statuses_count'] = $profile->noticeCount();
273 // Is the requesting user following this user?
274 $twitter_user['following'] = false;
275 $twitter_user['statusnet:blocking'] = false;
276 $twitter_user['notifications'] = false;
278 if (isset($this->auth_user)) {
280 $twitter_user['following'] = $this->auth_user->isSubscribed($profile);
281 $twitter_user['statusnet:blocking'] = $this->auth_user->hasBlocked($profile);
284 $sub = Subscription::pkeyGet(array('subscriber' =>
285 $this->auth_user->id,
286 'subscribed' => $profile->id));
289 $twitter_user['notifications'] = ($sub->jabber || $sub->sms);
294 $notice = $profile->getCurrentNotice();
297 $twitter_user['status'] = $this->twitterStatusArray($notice, false);
301 // StatusNet-specific
303 $twitter_user['statusnet_profile_url'] = $profile->profileurl;
305 return $twitter_user;
308 function twitterStatusArray($notice, $include_user=true)
310 $base = $this->twitterSimpleStatusArray($notice, $include_user);
312 if (!empty($notice->repeat_of)) {
313 $original = Notice::staticGet('id', $notice->repeat_of);
314 if (!empty($original)) {
315 $original_array = $this->twitterSimpleStatusArray($original, $include_user);
316 $base['retweeted_status'] = $original_array;
323 function twitterSimpleStatusArray($notice, $include_user=true)
325 $profile = $notice->getProfile();
327 $twitter_status = array();
328 $twitter_status['text'] = $notice->content;
329 $twitter_status['truncated'] = false; # Not possible on StatusNet
330 $twitter_status['created_at'] = $this->dateTwitter($notice->created);
331 $twitter_status['in_reply_to_status_id'] = ($notice->reply_to) ?
332 intval($notice->reply_to) : null;
336 $ns = $notice->getSource();
338 if (!empty($ns->name) && !empty($ns->url)) {
339 $source = '<a href="'
340 . htmlspecialchars($ns->url)
341 . '" rel="nofollow">'
342 . htmlspecialchars($ns->name)
349 $twitter_status['source'] = $source;
350 $twitter_status['id'] = intval($notice->id);
352 $replier_profile = null;
354 if ($notice->reply_to) {
355 $reply = Notice::staticGet(intval($notice->reply_to));
357 $replier_profile = $reply->getProfile();
361 $twitter_status['in_reply_to_user_id'] =
362 ($replier_profile) ? intval($replier_profile->id) : null;
363 $twitter_status['in_reply_to_screen_name'] =
364 ($replier_profile) ? $replier_profile->nickname : null;
366 if (isset($notice->lat) && isset($notice->lon)) {
367 // This is the format that GeoJSON expects stuff to be in
368 $twitter_status['geo'] = array('type' => 'Point',
369 'coordinates' => array((float) $notice->lat,
370 (float) $notice->lon));
372 $twitter_status['geo'] = null;
375 if (isset($this->auth_user)) {
376 $twitter_status['favorited'] = $this->auth_user->hasFave($notice);
378 $twitter_status['favorited'] = false;
382 $attachments = $notice->attachments();
384 if (!empty($attachments)) {
386 $twitter_status['attachments'] = array();
388 foreach ($attachments as $attachment) {
389 $enclosure_o=$attachment->getEnclosure();
391 $enclosure = array();
392 $enclosure['url'] = $enclosure_o->url;
393 $enclosure['mimetype'] = $enclosure_o->mimetype;
394 $enclosure['size'] = $enclosure_o->size;
395 $twitter_status['attachments'][] = $enclosure;
400 if ($include_user && $profile) {
401 # Don't get notice (recursive!)
402 $twitter_user = $this->twitterUserArray($profile, false);
403 $twitter_status['user'] = $twitter_user;
406 // StatusNet-specific
408 $twitter_status['statusnet_html'] = $notice->rendered;
410 return $twitter_status;
413 function twitterGroupArray($group)
415 $twitter_group = array();
417 $twitter_group['id'] = $group->id;
418 $twitter_group['url'] = $group->permalink();
419 $twitter_group['nickname'] = $group->nickname;
420 $twitter_group['fullname'] = $group->fullname;
422 if (isset($this->auth_user)) {
423 $twitter_group['member'] = $this->auth_user->isMember($group);
424 $twitter_group['blocked'] = Group_block::isBlocked(
426 $this->auth_user->getProfile()
430 $twitter_group['member_count'] = $group->getMemberCount();
431 $twitter_group['original_logo'] = $group->original_logo;
432 $twitter_group['homepage_logo'] = $group->homepage_logo;
433 $twitter_group['stream_logo'] = $group->stream_logo;
434 $twitter_group['mini_logo'] = $group->mini_logo;
435 $twitter_group['homepage'] = $group->homepage;
436 $twitter_group['description'] = $group->description;
437 $twitter_group['location'] = $group->location;
438 $twitter_group['created'] = $this->dateTwitter($group->created);
439 $twitter_group['modified'] = $this->dateTwitter($group->modified);
441 return $twitter_group;
444 function twitterRssGroupArray($group)
447 $entry['content']=$group->description;
448 $entry['title']=$group->nickname;
449 $entry['link']=$group->permalink();
450 $entry['published']=common_date_iso8601($group->created);
451 $entry['updated']==common_date_iso8601($group->modified);
452 $taguribase = common_config('integration', 'groupuri');
453 $entry['id'] = "group:$groupuribase:$entry[link]";
455 $entry['description'] = $entry['content'];
456 $entry['pubDate'] = common_date_rfc2822($group->created);
457 $entry['guid'] = $entry['link'];
462 function twitterRssEntryArray($notice)
466 if (Event::handle('StartRssEntryArray', array($notice, &$entry))) {
467 $profile = $notice->getProfile();
469 // We trim() to avoid extraneous whitespace in the output
471 $entry['content'] = common_xml_safe_str(trim($notice->rendered));
472 $entry['title'] = $profile->nickname . ': ' . common_xml_safe_str(trim($notice->content));
473 $entry['link'] = common_local_url('shownotice', array('notice' => $notice->id));
474 $entry['published'] = common_date_iso8601($notice->created);
476 $taguribase = TagURI::base();
477 $entry['id'] = "tag:$taguribase:$entry[link]";
479 $entry['updated'] = $entry['published'];
480 $entry['author'] = $profile->getBestName();
483 $attachments = $notice->attachments();
484 $enclosures = array();
486 foreach ($attachments as $attachment) {
487 $enclosure_o=$attachment->getEnclosure();
489 $enclosure = array();
490 $enclosure['url'] = $enclosure_o->url;
491 $enclosure['mimetype'] = $enclosure_o->mimetype;
492 $enclosure['size'] = $enclosure_o->size;
493 $enclosures[] = $enclosure;
497 if (!empty($enclosures)) {
498 $entry['enclosures'] = $enclosures;
502 $tag = new Notice_tag();
503 $tag->notice_id = $notice->id;
505 $entry['tags']=array();
506 while ($tag->fetch()) {
507 $entry['tags'][]=$tag->tag;
513 $entry['description'] = $entry['content'];
514 $entry['pubDate'] = common_date_rfc2822($notice->created);
515 $entry['guid'] = $entry['link'];
517 if (isset($notice->lat) && isset($notice->lon)) {
518 // This is the format that GeoJSON expects stuff to be in.
519 // showGeoRSS() below uses it for XML output, so we reuse it
520 $entry['geo'] = array('type' => 'Point',
521 'coordinates' => array((float) $notice->lat,
522 (float) $notice->lon));
524 $entry['geo'] = null;
527 Event::handle('EndRssEntryArray', array($notice, &$entry));
533 function twitterRelationshipArray($source, $target)
535 $relationship = array();
537 $relationship['source'] =
538 $this->relationshipDetailsArray($source, $target);
539 $relationship['target'] =
540 $this->relationshipDetailsArray($target, $source);
542 return array('relationship' => $relationship);
545 function relationshipDetailsArray($source, $target)
549 $details['screen_name'] = $source->nickname;
550 $details['followed_by'] = $target->isSubscribed($source);
551 $details['following'] = $source->isSubscribed($target);
553 $notifications = false;
555 if ($source->isSubscribed($target)) {
556 $sub = Subscription::pkeyGet(array('subscriber' =>
557 $source->id, 'subscribed' => $target->id));
560 $notifications = ($sub->jabber || $sub->sms);
564 $details['notifications_enabled'] = $notifications;
565 $details['blocking'] = $source->hasBlocked($target);
566 $details['id'] = $source->id;
571 function showTwitterXmlRelationship($relationship)
573 $this->elementStart('relationship');
575 foreach($relationship as $element => $value) {
576 if ($element == 'source' || $element == 'target') {
577 $this->elementStart($element);
578 $this->showXmlRelationshipDetails($value);
579 $this->elementEnd($element);
583 $this->elementEnd('relationship');
586 function showXmlRelationshipDetails($details)
588 foreach($details as $element => $value) {
589 $this->element($element, null, $value);
593 function showTwitterXmlStatus($twitter_status, $tag='status', $namespaces=false)
597 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
599 $this->elementStart($tag, $attrs);
600 foreach($twitter_status as $element => $value) {
603 $this->showTwitterXmlUser($twitter_status['user']);
606 $this->element($element, null, common_xml_safe_str($value));
609 $this->showXmlAttachments($twitter_status['attachments']);
612 $this->showGeoXML($value);
614 case 'retweeted_status':
615 $this->showTwitterXmlStatus($value, 'retweeted_status');
618 if (strncmp($element, 'statusnet_', 10) == 0) {
619 $this->element('statusnet:'.substr($element, 10), null, $value);
621 $this->element($element, null, $value);
625 $this->elementEnd($tag);
628 function showTwitterXmlGroup($twitter_group)
630 $this->elementStart('group');
631 foreach($twitter_group as $element => $value) {
632 $this->element($element, null, $value);
634 $this->elementEnd('group');
637 function showTwitterXmlUser($twitter_user, $role='user', $namespaces=false)
641 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
643 $this->elementStart($role, $attrs);
644 foreach($twitter_user as $element => $value) {
645 if ($element == 'status') {
646 $this->showTwitterXmlStatus($twitter_user['status']);
647 } else if (strncmp($element, 'statusnet_', 10) == 0) {
648 $this->element('statusnet:'.substr($element, 10), null, $value);
650 $this->element($element, null, $value);
653 $this->elementEnd($role);
656 function showXmlAttachments($attachments) {
657 if (!empty($attachments)) {
658 $this->elementStart('attachments', array('type' => 'array'));
659 foreach ($attachments as $attachment) {
661 $attrs['url'] = $attachment['url'];
662 $attrs['mimetype'] = $attachment['mimetype'];
663 $attrs['size'] = $attachment['size'];
664 $this->element('enclosure', $attrs, '');
666 $this->elementEnd('attachments');
670 function showGeoXML($geo)
674 $this->element('geo');
676 $this->elementStart('geo', array('xmlns:georss' => 'http://www.georss.org/georss'));
677 $this->element('georss:point', null, $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]);
678 $this->elementEnd('geo');
682 function showGeoRSS($geo)
688 $geo['coordinates'][0] . ' ' . $geo['coordinates'][1]
693 function showTwitterRssItem($entry)
695 $this->elementStart('item');
696 $this->element('title', null, $entry['title']);
697 $this->element('description', null, $entry['description']);
698 $this->element('pubDate', null, $entry['pubDate']);
699 $this->element('guid', null, $entry['guid']);
700 $this->element('link', null, $entry['link']);
702 # RSS only supports 1 enclosure per item
703 if(array_key_exists('enclosures', $entry) and !empty($entry['enclosures'])){
704 $enclosure = $entry['enclosures'][0];
705 $this->element('enclosure', array('url'=>$enclosure['url'],'type'=>$enclosure['mimetype'],'length'=>$enclosure['size']), null);
708 if(array_key_exists('tags', $entry)){
709 foreach($entry['tags'] as $tag){
710 $this->element('category', null,$tag);
714 $this->showGeoRSS($entry['geo']);
715 $this->elementEnd('item');
718 function showJsonObjects($objects)
720 print(json_encode($objects));
723 function showSingleXmlStatus($notice)
725 $this->initDocument('xml');
726 $twitter_status = $this->twitterStatusArray($notice);
727 $this->showTwitterXmlStatus($twitter_status, 'status', true);
728 $this->endDocument('xml');
731 function show_single_json_status($notice)
733 $this->initDocument('json');
734 $status = $this->twitterStatusArray($notice);
735 $this->showJsonObjects($status);
736 $this->endDocument('json');
739 function showXmlTimeline($notice)
741 $this->initDocument('xml');
742 $this->elementStart('statuses', array('type' => 'array',
743 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
745 if (is_array($notice)) {
746 $notice = new ArrayWrapper($notice);
749 while ($notice->fetch()) {
751 $twitter_status = $this->twitterStatusArray($notice);
752 $this->showTwitterXmlStatus($twitter_status);
753 } catch (Exception $e) {
754 common_log(LOG_ERR, $e->getMessage());
759 $this->elementEnd('statuses');
760 $this->endDocument('xml');
763 function showRssTimeline($notice, $title, $link, $subtitle, $suplink = null, $logo = null, $self = null)
765 $this->initDocument('rss');
767 $this->element('title', null, $title);
768 $this->element('link', null, $link);
770 if (!is_null($self)) {
774 'type' => 'application/rss+xml',
781 if (!is_null($suplink)) {
782 // For FriendFeed's SUP protocol
783 $this->element('link', array('xmlns' => 'http://www.w3.org/2005/Atom',
784 'rel' => 'http://api.friendfeed.com/2008/03#sup',
786 'type' => 'application/json'));
789 if (!is_null($logo)) {
790 $this->elementStart('image');
791 $this->element('link', null, $link);
792 $this->element('title', null, $title);
793 $this->element('url', null, $logo);
794 $this->elementEnd('image');
797 $this->element('description', null, $subtitle);
798 $this->element('language', null, 'en-us');
799 $this->element('ttl', null, '40');
801 if (is_array($notice)) {
802 $notice = new ArrayWrapper($notice);
805 while ($notice->fetch()) {
807 $entry = $this->twitterRssEntryArray($notice);
808 $this->showTwitterRssItem($entry);
809 } catch (Exception $e) {
810 common_log(LOG_ERR, $e->getMessage());
811 // continue on exceptions
815 $this->endTwitterRss();
818 function showAtomTimeline($notice, $title, $id, $link, $subtitle=null, $suplink=null, $selfuri=null, $logo=null)
820 $this->initDocument('atom');
822 $this->element('title', null, $title);
823 $this->element('id', null, $id);
824 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
826 if (!is_null($logo)) {
827 $this->element('logo',null,$logo);
830 if (!is_null($suplink)) {
831 # For FriendFeed's SUP protocol
832 $this->element('link', array('rel' => 'http://api.friendfeed.com/2008/03#sup',
834 'type' => 'application/json'));
837 if (!is_null($selfuri)) {
838 $this->element('link', array('href' => $selfuri,
839 'rel' => 'self', 'type' => 'application/atom+xml'), null);
842 $this->element('updated', null, common_date_iso8601('now'));
843 $this->element('subtitle', null, $subtitle);
845 if (is_array($notice)) {
846 $notice = new ArrayWrapper($notice);
849 while ($notice->fetch()) {
851 $this->raw($notice->asAtomEntry());
852 } catch (Exception $e) {
853 common_log(LOG_ERR, $e->getMessage());
858 $this->endDocument('atom');
861 function showRssGroups($group, $title, $link, $subtitle)
863 $this->initDocument('rss');
865 $this->element('title', null, $title);
866 $this->element('link', null, $link);
867 $this->element('description', null, $subtitle);
868 $this->element('language', null, 'en-us');
869 $this->element('ttl', null, '40');
871 if (is_array($group)) {
872 foreach ($group as $g) {
873 $twitter_group = $this->twitterRssGroupArray($g);
874 $this->showTwitterRssItem($twitter_group);
877 while ($group->fetch()) {
878 $twitter_group = $this->twitterRssGroupArray($group);
879 $this->showTwitterRssItem($twitter_group);
883 $this->endTwitterRss();
886 function showTwitterAtomEntry($entry)
888 $this->elementStart('entry');
889 $this->element('title', null, common_xml_safe_str($entry['title']));
892 array('type' => 'html'),
893 common_xml_safe_str($entry['content'])
895 $this->element('id', null, $entry['id']);
896 $this->element('published', null, $entry['published']);
897 $this->element('updated', null, $entry['updated']);
898 $this->element('link', array('type' => 'text/html',
899 'href' => $entry['link'],
900 'rel' => 'alternate'));
901 $this->element('link', array('type' => $entry['avatar-type'],
902 'href' => $entry['avatar'],
904 $this->elementStart('author');
906 $this->element('name', null, $entry['author-name']);
907 $this->element('uri', null, $entry['author-uri']);
909 $this->elementEnd('author');
910 $this->elementEnd('entry');
913 function showXmlDirectMessage($dm, $namespaces=false)
917 $attrs['xmlns:statusnet'] = 'http://status.net/schema/api/1/';
919 $this->elementStart('direct_message', $attrs);
920 foreach($dm as $element => $value) {
924 $this->showTwitterXmlUser($value, $element);
927 $this->element($element, null, common_xml_safe_str($value));
930 $this->element($element, null, $value);
934 $this->elementEnd('direct_message');
937 function directMessageArray($message)
941 $from_profile = $message->getFrom();
942 $to_profile = $message->getTo();
944 $dmsg['id'] = $message->id;
945 $dmsg['sender_id'] = $message->from_profile;
946 $dmsg['text'] = trim($message->content);
947 $dmsg['recipient_id'] = $message->to_profile;
948 $dmsg['created_at'] = $this->dateTwitter($message->created);
949 $dmsg['sender_screen_name'] = $from_profile->nickname;
950 $dmsg['recipient_screen_name'] = $to_profile->nickname;
951 $dmsg['sender'] = $this->twitterUserArray($from_profile, false);
952 $dmsg['recipient'] = $this->twitterUserArray($to_profile, false);
957 function rssDirectMessageArray($message)
961 $from = $message->getFrom();
963 $entry['title'] = sprintf('Message from %1$s to %2$s',
964 $from->nickname, $message->getTo()->nickname);
966 $entry['content'] = common_xml_safe_str($message->rendered);
967 $entry['link'] = common_local_url('showmessage', array('message' => $message->id));
968 $entry['published'] = common_date_iso8601($message->created);
970 $taguribase = TagURI::base();
972 $entry['id'] = "tag:$taguribase:$entry[link]";
973 $entry['updated'] = $entry['published'];
975 $entry['author-name'] = $from->getBestName();
976 $entry['author-uri'] = $from->homepage;
978 $avatar = $from->getAvatar(AVATAR_STREAM_SIZE);
980 $entry['avatar'] = (!empty($avatar)) ? $avatar->url : Avatar::defaultImage(AVATAR_STREAM_SIZE);
981 $entry['avatar-type'] = (!empty($avatar)) ? $avatar->mediatype : 'image/png';
985 $entry['description'] = $entry['content'];
986 $entry['pubDate'] = common_date_rfc2822($message->created);
987 $entry['guid'] = $entry['link'];
992 function showSingleXmlDirectMessage($message)
994 $this->initDocument('xml');
995 $dmsg = $this->directMessageArray($message);
996 $this->showXmlDirectMessage($dmsg, true);
997 $this->endDocument('xml');
1000 function showSingleJsonDirectMessage($message)
1002 $this->initDocument('json');
1003 $dmsg = $this->directMessageArray($message);
1004 $this->showJsonObjects($dmsg);
1005 $this->endDocument('json');
1008 function showAtomGroups($group, $title, $id, $link, $subtitle=null, $selfuri=null)
1010 $this->initDocument('atom');
1012 $this->element('title', null, common_xml_safe_str($title));
1013 $this->element('id', null, $id);
1014 $this->element('link', array('href' => $link, 'rel' => 'alternate', 'type' => 'text/html'), null);
1016 if (!is_null($selfuri)) {
1017 $this->element('link', array('href' => $selfuri,
1018 'rel' => 'self', 'type' => 'application/atom+xml'), null);
1021 $this->element('updated', null, common_date_iso8601('now'));
1022 $this->element('subtitle', null, common_xml_safe_str($subtitle));
1024 if (is_array($group)) {
1025 foreach ($group as $g) {
1026 $this->raw($g->asAtomEntry());
1029 while ($group->fetch()) {
1030 $this->raw($group->asAtomEntry());
1034 $this->endDocument('atom');
1038 function showJsonTimeline($notice)
1040 $this->initDocument('json');
1042 $statuses = array();
1044 if (is_array($notice)) {
1045 $notice = new ArrayWrapper($notice);
1048 while ($notice->fetch()) {
1050 $twitter_status = $this->twitterStatusArray($notice);
1051 array_push($statuses, $twitter_status);
1052 } catch (Exception $e) {
1053 common_log(LOG_ERR, $e->getMessage());
1058 $this->showJsonObjects($statuses);
1060 $this->endDocument('json');
1063 function showJsonGroups($group)
1065 $this->initDocument('json');
1069 if (is_array($group)) {
1070 foreach ($group as $g) {
1071 $twitter_group = $this->twitterGroupArray($g);
1072 array_push($groups, $twitter_group);
1075 while ($group->fetch()) {
1076 $twitter_group = $this->twitterGroupArray($group);
1077 array_push($groups, $twitter_group);
1081 $this->showJsonObjects($groups);
1083 $this->endDocument('json');
1086 function showXmlGroups($group)
1089 $this->initDocument('xml');
1090 $this->elementStart('groups', array('type' => 'array'));
1092 if (is_array($group)) {
1093 foreach ($group as $g) {
1094 $twitter_group = $this->twitterGroupArray($g);
1095 $this->showTwitterXmlGroup($twitter_group);
1098 while ($group->fetch()) {
1099 $twitter_group = $this->twitterGroupArray($group);
1100 $this->showTwitterXmlGroup($twitter_group);
1104 $this->elementEnd('groups');
1105 $this->endDocument('xml');
1108 function showTwitterXmlUsers($user)
1110 $this->initDocument('xml');
1111 $this->elementStart('users', array('type' => 'array',
1112 'xmlns:statusnet' => 'http://status.net/schema/api/1/'));
1114 if (is_array($user)) {
1115 foreach ($user as $u) {
1116 $twitter_user = $this->twitterUserArray($u);
1117 $this->showTwitterXmlUser($twitter_user);
1120 while ($user->fetch()) {
1121 $twitter_user = $this->twitterUserArray($user);
1122 $this->showTwitterXmlUser($twitter_user);
1126 $this->elementEnd('users');
1127 $this->endDocument('xml');
1130 function showJsonUsers($user)
1132 $this->initDocument('json');
1136 if (is_array($user)) {
1137 foreach ($user as $u) {
1138 $twitter_user = $this->twitterUserArray($u);
1139 array_push($users, $twitter_user);
1142 while ($user->fetch()) {
1143 $twitter_user = $this->twitterUserArray($user);
1144 array_push($users, $twitter_user);
1148 $this->showJsonObjects($users);
1150 $this->endDocument('json');
1153 function showSingleJsonGroup($group)
1155 $this->initDocument('json');
1156 $twitter_group = $this->twitterGroupArray($group);
1157 $this->showJsonObjects($twitter_group);
1158 $this->endDocument('json');
1161 function showSingleXmlGroup($group)
1163 $this->initDocument('xml');
1164 $twitter_group = $this->twitterGroupArray($group);
1165 $this->showTwitterXmlGroup($twitter_group);
1166 $this->endDocument('xml');
1169 function dateTwitter($dt)
1171 $dateStr = date('d F Y H:i:s', strtotime($dt));
1172 $d = new DateTime($dateStr, new DateTimeZone('UTC'));
1173 $d->setTimezone(new DateTimeZone(common_timezone()));
1174 return $d->format('D M d H:i:s O Y');
1177 function initDocument($type='xml')
1181 header('Content-Type: application/xml; charset=utf-8');
1185 header('Content-Type: application/json; charset=utf-8');
1187 // Check for JSONP callback
1188 if (isset($this->callback)) {
1189 print $this->callback . '(';
1193 header("Content-Type: application/rss+xml; charset=utf-8");
1194 $this->initTwitterRss();
1197 header('Content-Type: application/atom+xml; charset=utf-8');
1198 $this->initTwitterAtom();
1201 // TRANS: Client error on an API request with an unsupported data format.
1202 $this->clientError(_('Not a supported data format.'));
1209 function endDocument($type='xml')
1216 // Check for JSONP callback
1217 if (isset($this->callback)) {
1222 $this->endTwitterRss();
1225 $this->endTwitterRss();
1228 // TRANS: Client error on an API request with an unsupported data format.
1229 $this->clientError(_('Not a supported data format.'));
1235 function clientError($msg, $code = 400, $format = 'xml')
1237 $action = $this->trimmed('action');
1239 common_debug("User error '$code' on '$action': $msg", __FILE__);
1241 if (!array_key_exists($code, ClientErrorAction::$status)) {
1245 $status_string = ClientErrorAction::$status[$code];
1247 // Do not emit error header for JSONP
1248 if (!isset($this->callback)) {
1249 header('HTTP/1.1 ' . $code . ' ' . $status_string);
1254 $this->initDocument('xml');
1255 $this->elementStart('hash');
1256 $this->element('error', null, $msg);
1257 $this->element('request', null, $_SERVER['REQUEST_URI']);
1258 $this->elementEnd('hash');
1259 $this->endDocument('xml');
1262 $this->initDocument('json');
1263 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1264 print(json_encode($error_array));
1265 $this->endDocument('json');
1268 header('Content-Type: text/plain; charset=utf-8');
1272 // If user didn't request a useful format, throw a regular client error
1273 throw new ClientException($msg, $code);
1277 function serverError($msg, $code = 500, $content_type = 'xml')
1279 $action = $this->trimmed('action');
1281 common_debug("Server error '$code' on '$action': $msg", __FILE__);
1283 if (!array_key_exists($code, ServerErrorAction::$status)) {
1287 $status_string = ServerErrorAction::$status[$code];
1289 // Do not emit error header for JSONP
1290 if (!isset($this->callback)) {
1291 header('HTTP/1.1 '.$code.' '.$status_string);
1294 if ($content_type == 'xml') {
1295 $this->initDocument('xml');
1296 $this->elementStart('hash');
1297 $this->element('error', null, $msg);
1298 $this->element('request', null, $_SERVER['REQUEST_URI']);
1299 $this->elementEnd('hash');
1300 $this->endDocument('xml');
1302 $this->initDocument('json');
1303 $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
1304 print(json_encode($error_array));
1305 $this->endDocument('json');
1309 function initTwitterRss()
1312 $this->elementStart(
1316 'xmlns:atom' => 'http://www.w3.org/2005/Atom',
1317 'xmlns:georss' => 'http://www.georss.org/georss'
1320 $this->elementStart('channel');
1321 Event::handle('StartApiRss', array($this));
1324 function endTwitterRss()
1326 $this->elementEnd('channel');
1327 $this->elementEnd('rss');
1331 function initTwitterAtom()
1334 // FIXME: don't hardcode the language here!
1335 $this->elementStart('feed', array('xmlns' => 'http://www.w3.org/2005/Atom',
1336 'xml:lang' => 'en-US',
1337 'xmlns:thr' => 'http://purl.org/syndication/thread/1.0'));
1340 function endTwitterAtom()
1342 $this->elementEnd('feed');
1346 function showProfile($profile, $content_type='xml', $notice=null, $includeStatuses=true)
1348 $profile_array = $this->twitterUserArray($profile, $includeStatuses);
1349 switch ($content_type) {
1351 $this->showTwitterXmlUser($profile_array);
1354 $this->showJsonObjects($profile_array);
1357 // TRANS: Client error on an API request with an unsupported data format.
1358 $this->clientError(_('Not a supported data format.'));
1364 function getTargetUser($id)
1367 // Twitter supports these other ways of passing the user ID
1368 if (is_numeric($this->arg('id'))) {
1369 return User::staticGet($this->arg('id'));
1370 } else if ($this->arg('id')) {
1371 $nickname = common_canonical_nickname($this->arg('id'));
1372 return User::staticGet('nickname', $nickname);
1373 } else if ($this->arg('user_id')) {
1374 // This is to ensure that a non-numeric user_id still
1375 // overrides screen_name even if it doesn't get used
1376 if (is_numeric($this->arg('user_id'))) {
1377 return User::staticGet('id', $this->arg('user_id'));
1379 } else if ($this->arg('screen_name')) {
1380 $nickname = common_canonical_nickname($this->arg('screen_name'));
1381 return User::staticGet('nickname', $nickname);
1383 // Fall back to trying the currently authenticated user
1384 return $this->auth_user;
1387 } else if (is_numeric($id)) {
1388 return User::staticGet($id);
1390 $nickname = common_canonical_nickname($id);
1391 return User::staticGet('nickname', $nickname);
1395 function getTargetProfile($id)
1399 // Twitter supports these other ways of passing the user ID
1400 if (is_numeric($this->arg('id'))) {
1401 return Profile::staticGet($this->arg('id'));
1402 } else if ($this->arg('id')) {
1403 // Screen names currently can only uniquely identify a local user.
1404 $nickname = common_canonical_nickname($this->arg('id'));
1405 $user = User::staticGet('nickname', $nickname);
1406 return $user ? $user->getProfile() : null;
1407 } else if ($this->arg('user_id')) {
1408 // This is to ensure that a non-numeric user_id still
1409 // overrides screen_name even if it doesn't get used
1410 if (is_numeric($this->arg('user_id'))) {
1411 return Profile::staticGet('id', $this->arg('user_id'));
1413 } else if ($this->arg('screen_name')) {
1414 $nickname = common_canonical_nickname($this->arg('screen_name'));
1415 $user = User::staticGet('nickname', $nickname);
1416 return $user ? $user->getProfile() : null;
1418 } else if (is_numeric($id)) {
1419 return Profile::staticGet($id);
1421 $nickname = common_canonical_nickname($id);
1422 $user = User::staticGet('nickname', $nickname);
1423 return $user ? $user->getProfile() : null;
1427 function getTargetGroup($id)
1430 if (is_numeric($this->arg('id'))) {
1431 return User_group::staticGet($this->arg('id'));
1432 } else if ($this->arg('id')) {
1433 $nickname = common_canonical_nickname($this->arg('id'));
1434 $local = Local_group::staticGet('nickname', $nickname);
1435 if (empty($local)) {
1438 return User_group::staticGet('id', $local->id);
1440 } else if ($this->arg('group_id')) {
1441 // This is to ensure that a non-numeric user_id still
1442 // overrides screen_name even if it doesn't get used
1443 if (is_numeric($this->arg('group_id'))) {
1444 return User_group::staticGet('id', $this->arg('group_id'));
1446 } else if ($this->arg('group_name')) {
1447 $nickname = common_canonical_nickname($this->arg('group_name'));
1448 $local = Local_group::staticGet('nickname', $nickname);
1449 if (empty($local)) {
1452 return User_group::staticGet('id', $local->group_id);
1456 } else if (is_numeric($id)) {
1457 return User_group::staticGet($id);
1459 $nickname = common_canonical_nickname($id);
1460 $local = Local_group::staticGet('nickname', $nickname);
1461 if (empty($local)) {
1464 return User_group::staticGet('id', $local->group_id);
1470 * Returns query argument or default value if not found. Certain
1471 * parameters used throughout the API are lightly scrubbed and
1472 * bounds checked. This overrides Action::arg().
1474 * @param string $key requested argument
1475 * @param string $def default value to return if $key is not provided
1479 function arg($key, $def=null)
1481 // XXX: Do even more input validation/scrubbing?
1483 if (array_key_exists($key, $this->args)) {
1486 $page = (int)$this->args['page'];
1487 return ($page < 1) ? 1 : $page;
1489 $count = (int)$this->args['count'];
1492 } elseif ($count > 200) {
1498 $since_id = (int)$this->args['since_id'];
1499 return ($since_id < 1) ? 0 : $since_id;
1501 $max_id = (int)$this->args['max_id'];
1502 return ($max_id < 1) ? 0 : $max_id;
1504 return parent::arg($key, $def);
1512 * Calculate the complete URI that called up this action. Used for
1513 * Atom rel="self" links. Warning: this is funky.
1515 * @return string URL a URL suitable for rel="self" Atom links
1517 function getSelfUri()
1519 $action = mb_substr(get_class($this), 0, -6); // remove 'Action'
1521 $id = $this->arg('id');
1522 $aargs = array('format' => $this->format);
1527 $tag = $this->arg('tag');
1529 $aargs['tag'] = $tag;
1532 parse_str($_SERVER['QUERY_STRING'], $params);
1534 if (!empty($params)) {
1535 unset($params['p']);
1536 $pstring = http_build_query($params);
1539 $uri = common_local_url($action, $aargs);
1541 if (!empty($pstring)) {
1542 $uri .= '?' . $pstring;