2 require_once("bbcode.php");
3 require_once("datetime.php");
13 function api_date($str){
14 //Wed May 23 06:01:13 +0000 2007
15 return datetime_convert('UTC', 'UTC', $str, "D M d h:i:s +0000 Y" );
19 function api_register_func($path, $func, $auth=false){
21 $API[$path] = array('func'=>$func,
28 function api_login(&$a){
29 // workaround for HTTP-auth in CGI mode
30 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
31 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
32 if(strlen($userpass)) {
33 list($name, $password) = explode(':', $userpass);
34 $_SERVER['PHP_AUTH_USER'] = $name;
35 $_SERVER['PHP_AUTH_PW'] = $password;
39 if (!isset($_SERVER['PHP_AUTH_USER'])) {
40 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
41 header('WWW-Authenticate: Basic realm="Friendika"');
42 header('HTTP/1.0 401 Unauthorized');
43 die('This api requires login');
46 $user = $_SERVER['PHP_AUTH_USER'];
47 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
51 * next code from mod/auth.php. needs better solution
54 // process normal login request
56 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
57 AND `password` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1",
65 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
66 header('WWW-Authenticate: Basic realm="Friendika"');
67 header('HTTP/1.0 401 Unauthorized');
68 die('This api requires login');
70 $_SESSION['uid'] = $record['uid'];
71 $_SESSION['theme'] = $record['theme'];
72 $_SESSION['authenticated'] = 1;
73 $_SESSION['page_flags'] = $record['page-flags'];
74 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
75 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
77 //notice( t("Welcome back ") . $record['username'] . EOL);
80 if(strlen($a->user['timezone'])) {
81 date_default_timezone_set($a->user['timezone']);
82 $a->timezone = $a->user['timezone'];
85 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
86 intval($_SESSION['uid']));
89 $a->cid = $r[0]['id'];
90 $_SESSION['cid'] = $a->cid;
92 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
93 dbesc(datetime_convert()),
94 intval($_SESSION['uid'])
97 call_hooks('logged_in', $a->user);
99 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
102 /**************************
103 * MAIN API ENTRY POINT *
104 **************************/
105 function api_call(&$a){
107 foreach ($API as $p=>$info){
108 if (strpos($a->query_string, $p)===0){
109 #unset($_SERVER['PHP_AUTH_USER']);
110 if ($info['auth']===true && local_user()===false) {
114 load_contact_links(local_user());
116 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
118 if (strpos($a->query_string, ".xml")>0) $type="xml";
119 if (strpos($a->query_string, ".json")>0) $type="json";
120 if (strpos($a->query_string, ".rss")>0) $type="rss";
121 if (strpos($a->query_string, ".atom")>0) $type="atom";
123 $r = call_user_func($info['func'], $a, $type);
124 if ($r===false) return;
128 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
129 header ("Content-Type: text/xml");
130 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
133 header ("Content-Type: application/json");
135 return json_encode($rr);
138 header ("Content-Type: application/rss+xml");
139 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
142 header ("Content-Type: application/atom+xml");
143 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
147 //echo "<pre>"; var_dump($r); die();
156 function api_rss_extra(&$a, $arr, $user_info){
157 if (is_null($user_info)) $user_info = api_get_user($a);
158 $arr['$user'] = $user_info;
159 $arr['$rss'] = array(
160 'alternate' => $user_info['url'],
161 'self' => $a->get_baseurl(). "/". $a->query_string,
162 'base' => $a->get_baseurl(),
163 'updated' => api_date(null),
164 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
165 'language' => $user_info['language'],
166 'logo' => $a->get_baseurl()."/images/friendika-32.png",
173 * Returns user info array.
175 function api_get_user(&$a, $contact_id = Null){
179 if(!is_null($contact_id)){
181 $extra_query = "AND `contact`.`id` = %d ";
184 if(is_null($user) && x($_GET, 'user_id')) {
185 $user = intval($_GET['user_id']);
186 $extra_query = "AND `contact`.`id` = %d ";
188 if(is_null($user) && x($_GET, 'screen_name')) {
189 $user = dbesc($_GET['screen_name']);
190 $extra_query = "AND `contact`.`nick` = '%s' ";
194 list($user, $null) = explode(".",$a->argv[3]);
195 if(is_numeric($user)){
196 $user = intval($user);
197 $extra_query = "AND `contact`.`id` = %d ";
199 $user = dbesc($user);
200 $extra_query = "AND `contact`.`nick` = '%s' ";
205 if (local_user()===false) {
206 api_login($a); return False;
208 $user = $_SESSION['uid'];
209 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
216 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
221 if (count($uinfo)==0) {
225 // count public wall messages
226 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
229 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
230 intval($uinfo[0]['uid'])
232 $countitms = $r[0]['count'];
235 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
237 AND `self`=0 AND `blocked`=0",
238 intval($uinfo[0]['uid'])
240 $countfriends = $r[0]['count'];
244 'uid' => $uinfo[0]['uid'],
245 'id' => $uinfo[0]['cid'],
246 'name' => $uinfo[0]['name'],
247 'screen_name' => $uinfo[0]['nick'],
248 'location' => '', //$uinfo[0]['default-location'],
249 'profile_image_url' => $uinfo[0]['micro'],
250 'url' => $uinfo[0]['url'],
251 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
252 'protected' => false, #
253 'friends_count' => $countfriends,
254 'created_at' => api_date($uinfo[0]['name-date']),
255 'utc_offset' => 0, #XXX: fix me
256 'time_zone' => '', //$uinfo[0]['timezone'],
257 'geo_enabled' => false,
258 'statuses_count' => $countitms, #XXX: fix me
259 'lang' => 'en', #XXX: fix me
261 'followers_count' => $countfriends, #XXX: fix me
262 'favourites_count' => 0,
263 'contributors_enabled' => false,
264 'follow_request_sent' => false,
265 'profile_background_color' => 'cfe8f6',
266 'profile_text_color' => '000000',
267 'profile_link_color' => 'FF8500',
268 'profile_sidebar_fill_color' =>'AD0066',
269 'profile_sidebar_border_color' => 'AD0066',
270 'profile_background_image_url' => '',
271 'profile_background_tile' => false,
272 'profile_use_background_image' => false,
273 'notifications' => false,
274 'verified' => true, #XXX: fix me
275 'followers' => '', #XXX: fix me
283 function api_item_get_user(&$a, $item) {
284 // The author is our direct contact, in a conversation with us.
285 if(link_compare($item['url'],$item['author-link'])) {
286 return api_get_user($a,$item['cid']);
289 // The author may be a contact of ours, but is replying to somebody else.
290 // Figure out if we know him/her.
291 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
292 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
293 return api_get_user($a,$a->contacts[$normalised]['id']);
295 // We don't know this person directly.
299 'name' => $item['author-name'],
301 'location' => '', //$uinfo[0]['default-location'],
302 'profile_image_url' => $item['author-avatar'],
303 'url' => $item['author-link'],
305 'protected' => false, #
306 'friends_count' => 0,
308 'utc_offset' => 0, #XXX: fix me
309 'time_zone' => '', //$uinfo[0]['timezone'],
310 'geo_enabled' => false,
311 'statuses_count' => 0,
312 'lang' => 'en', #XXX: fix me
314 'followers_count' => 0,
315 'favourites_count' => 0,
316 'contributors_enabled' => false,
317 'follow_request_sent' => false,
318 'profile_background_color' => 'cfe8f6',
319 'profile_text_color' => '000000',
320 'profile_link_color' => 'FF8500',
321 'profile_sidebar_fill_color' =>'AD0066',
322 'profile_sidebar_border_color' => 'AD0066',
323 'profile_background_image_url' => '',
324 'profile_background_tile' => false,
325 'profile_use_background_image' => false,
326 'notifications' => false,
327 'verified' => true, #XXX: fix me
328 'followers' => '', #XXX: fix me
336 * apply xmlify() to all values of array $val, recursively
338 function api_xmlify($val){
339 if (is_bool($val)) return $val?"true":"false";
340 if (is_array($val)) return array_map('api_xmlify', $val);
345 * load api $templatename for $type and replace $data array
347 function api_apply_template($templatename, $type, $data){
355 $data = api_xmlify($data);
356 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
357 $ret = replace_macros($tpl, $data);
371 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
372 * returns a 401 status code and an error message if not.
373 * http://developer.twitter.com/doc/get/account/verify_credentials
375 function api_account_verify_credentials(&$a, $type){
376 if (local_user()===false) return false;
377 $user_info = api_get_user($a);
379 return api_apply_template("user", $type, array('$user' => $user_info));
382 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
386 * get data from $_POST or $_GET
388 function requestdata($k){
389 if (isset($_POST[$k])){
392 if (isset($_GET[$k])){
397 // TODO - media uploads
398 function api_statuses_update(&$a, $type) {
399 if (local_user()===false) return false;
400 $user_info = api_get_user($a);
402 // convert $_POST array items to the form we use for web posts.
404 $_POST['body'] = urldecode(requestdata('status'));
405 $_POST['parent'] = requestdata('in_reply_to_status_id');
406 if(requestdata('lat') && requestdata('long'))
407 $_POST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
408 $_POST['profile_uid'] = local_user();
409 if(requestdata('parent'))
410 $_POST['type'] = 'net-comment';
412 $_POST['type'] = 'wall';
414 // set this so that the item_post() function is quiet and doesn't redirect or emit json
416 $_POST['api_source'] = true;
418 // call out normal post function
420 require_once('mod/item.php');
423 // this should output the last post (the one we just posted).
424 return api_status_show($a,$type);
426 api_register_func('api/statuses/update','api_statuses_update', true);
429 function api_status_show(&$a, $type){
430 $user_info = api_get_user($a);
431 // get last public wall message
432 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
433 FROM `item`, `contact`,
434 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
435 WHERE `item`.`contact-id` = %d
436 AND `i`.`id` = `item`.`parent`
437 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
438 AND `type`!='activity'
439 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
440 ORDER BY `created` DESC
442 intval($user_info['id'])
445 if (count($lastwall)>0){
446 $lastwall = $lastwall[0];
448 $in_reply_to_status_id = '';
449 $in_reply_to_user_id = '';
450 $in_reply_to_screen_name = '';
451 if ($lastwall['parent']!=$lastwall['id']) {
452 $in_reply_to_status_id=$lastwall['parent'];
453 $in_reply_to_user_id = $lastwall['reply_uid'];
454 $in_reply_to_screen_name = $lastwall['reply_author'];
456 $status_info = array(
457 'created_at' => api_date($lastwall['created']),
458 'id' => $lastwall['contact-id'],
459 'text' => strip_tags(bbcode($lastwall['body'])),
460 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
461 'truncated' => false,
462 'in_reply_to_status_id' => $in_reply_to_status_id,
463 'in_reply_to_user_id' => $in_reply_to_user_id,
464 'favorited' => false,
465 'in_reply_to_screen_name' => $in_reply_to_screen_name,
467 'coordinates' => $lastwall['coord'],
468 'place' => $lastwall['location'],
471 $status_info['user'] = $user_info;
473 return api_apply_template("status", $type, array('$status' => $status_info));
482 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
483 * The author's most recent status will be returned inline.
484 * http://developer.twitter.com/doc/get/users/show
486 function api_users_show(&$a, $type){
487 $user_info = api_get_user($a);
488 // get last public wall message
489 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
490 FROM `item`, `contact`,
491 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
492 WHERE `item`.`contact-id` = %d
493 AND `i`.`id` = `item`.`parent`
494 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
495 AND `type`!='activity'
496 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
497 ORDER BY `created` DESC
499 intval($user_info['id'])
502 if (count($lastwall)>0){
503 $lastwall = $lastwall[0];
505 $in_reply_to_status_id = '';
506 $in_reply_to_user_id = '';
507 $in_reply_to_screen_name = '';
508 if ($lastwall['parent']!=$lastwall['id']) {
509 $in_reply_to_status_id=$lastwall['parent'];
510 $in_reply_to_user_id = $lastwall['reply_uid'];
511 $in_reply_to_screen_name = $lastwall['reply_author'];
513 $user_info['status'] = array(
514 'created_at' => api_date($lastwall['created']),
515 'id' => $lastwall['contact-id'],
516 'text' => strip_tags(bbcode($lastwall['body'])),
517 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
518 'truncated' => false,
519 'in_reply_to_status_id' => $in_reply_to_status_id,
520 'in_reply_to_user_id' => $in_reply_to_user_id,
521 'favorited' => false,
522 'in_reply_to_screen_name' => $in_reply_to_screen_name,
524 'coordinates' => $lastwall['coord'],
525 'place' => $lastwall['location'],
529 return api_apply_template("user", $type, array('$user' => $user_info));
532 api_register_func('api/users/show','api_users_show');
536 * http://developer.twitter.com/doc/get/statuses/home_timeline
538 * TODO: Optional parameters
539 * TODO: Add reply info
541 function api_statuses_home_timeline(&$a, $type){
542 if (local_user()===false) return false;
544 $user_info = api_get_user($a);
545 // get last newtork messages
546 // $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
548 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
549 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
550 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
551 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
552 FROM `item`, `contact`
553 WHERE `item`.`uid` = %d
554 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
555 AND `contact`.`id` = `item`.`contact-id`
556 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
558 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
559 intval($user_info['uid']),
563 $ret = api_format_items($r,$user_info);
566 $data = array('$statuses' => $ret);
570 $data = api_rss_extra($a, $data, $user_info);
573 return api_apply_template("timeline", $type, $data);
575 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
576 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
580 function api_statuses_user_timeline(&$a, $type){
581 if (local_user()===false) return false;
583 $user_info = api_get_user($a);
584 // get last newtork messages
585 // $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
587 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
588 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
589 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
590 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
591 FROM `item`, `contact`
592 WHERE `item`.`uid` = %d
593 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
594 AND `item`.`wall` = 1
595 AND `contact`.`id` = `item`.`contact-id`
596 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
598 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
599 intval($user_info['uid']),
603 $ret = api_format_items($r,$user_info);
606 $data = array('$statuses' => $ret);
610 $data = api_rss_extra($a, $data, $user_info);
613 return api_apply_template("timeline", $type, $data);
616 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
619 function api_favorites(&$a, $type){
620 if (local_user()===false) return false;
622 $user_info = api_get_user($a);
623 // get last newtork messages
624 // $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
626 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
627 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
628 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
629 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
630 FROM `item`, `contact`
631 WHERE `item`.`uid` = %d
632 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
633 AND `item`.`starred` = 1
634 AND `contact`.`id` = `item`.`contact-id`
635 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
637 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
638 intval($user_info['uid']),
642 $ret = api_format_items($r,$user_info);
645 $data = array('$statuses' => $ret);
649 $data = api_rss_extra($a, $data, $user_info);
652 return api_apply_template("timeline", $type, $data);
655 api_register_func('api/favorites','api_favorites', true);
658 function api_format_items($r,$user_info) {
662 foreach($r as $item) {
663 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
665 'created_at'=> api_date($item['created']),
666 'published' => datetime_convert('UTC','UTC',$item['created'],ATOM_TIME),
667 'updated' => datetime_convert('UTC','UTC',$item['edited'],ATOM_TIME),
668 'id' => $item['uri'],
669 'text' => strip_tags(bbcode($item['body'])),
670 'html' => bbcode($item['body']),
671 'source' => (($item['app']) ? $item['app'] : 'web'),
672 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
673 'truncated' => False,
674 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
675 'in_reply_to_user_id' => '',
676 'favorited' => false,
677 'in_reply_to_screen_name' => '',
679 'coordinates' => $item['coord'],
680 'place' => $item['location'],
681 'contributors' => '',
684 'user' => $status_user ,
685 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
686 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
687 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
688 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
696 function api_account_rate_limit_status(&$a,$type) {
699 'remaining_hits' => (string) 150,
700 'hourly_limit' => (string) 150,
701 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
702 'reset_time_in_seconds' => strtotime('now + 1 hour')
705 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
708 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
711 function api_statusnet_config(&$a,$type) {
712 $name = $a->config['sitename'];
713 $server = $a->get_hostname();
714 $logo = $a->get_baseurl() . '/images/friendika-64.png';
715 $email = $a->config['admin_email'];
716 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
717 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
718 $textlimit = (($a->config['max_import_size']) ? $a->config['max_import_size'] : '200000');
719 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
720 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
723 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
724 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
725 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
726 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
727 'shorturllength' => '30'
731 return api_apply_template('config', $type, array('$config' => $config));
734 api_register_func('api/statusnet/config','api_statusnet_config',false);
737 function api_statusnet_version(&$a,$type) {
741 if($type === 'xml') {
742 header("Content-type: application/xml");
743 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
746 elseif($type === 'json') {
747 header("Content-type: application/json");
752 api_register_func('api/statusnet/version','api_statusnet_version',false);