2 require_once("bbcode.php");
3 require_once("datetime.php");
14 function api_date($str){
15 //Wed May 23 06:01:13 +0000 2007
16 return datetime_convert('UTC', 'UTC', $str, "D M d h:i:s +0000 Y" );
20 function api_register_func($path, $func, $auth=false){
22 $API[$path] = array('func'=>$func,
29 function api_login(&$a){
30 // workaround for HTTP-auth in CGI mode
31 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
32 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
33 if(strlen($userpass)) {
34 list($name, $password) = explode(':', $userpass);
35 $_SERVER['PHP_AUTH_USER'] = $name;
36 $_SERVER['PHP_AUTH_PW'] = $password;
40 if (!isset($_SERVER['PHP_AUTH_USER'])) {
41 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
42 header('WWW-Authenticate: Basic realm="Friendika"');
43 header('HTTP/1.0 401 Unauthorized');
44 die('This api requires login');
47 $user = $_SERVER['PHP_AUTH_USER'];
48 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
52 * next code from mod/auth.php. needs better solution
55 // process normal login request
57 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
58 AND `password` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1",
66 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
67 header('WWW-Authenticate: Basic realm="Friendika"');
68 header('HTTP/1.0 401 Unauthorized');
69 die('This api requires login');
71 $_SESSION['uid'] = $record['uid'];
72 $_SESSION['theme'] = $record['theme'];
73 $_SESSION['authenticated'] = 1;
74 $_SESSION['page_flags'] = $record['page-flags'];
75 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
76 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
78 //notice( t("Welcome back ") . $record['username'] . EOL);
81 if(strlen($a->user['timezone'])) {
82 date_default_timezone_set($a->user['timezone']);
83 $a->timezone = $a->user['timezone'];
86 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
87 intval($_SESSION['uid']));
90 $a->cid = $r[0]['id'];
91 $_SESSION['cid'] = $a->cid;
93 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
94 dbesc(datetime_convert()),
95 intval($_SESSION['uid'])
98 call_hooks('logged_in', $a->user);
100 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
103 /**************************
104 * MAIN API ENTRY POINT *
105 **************************/
106 function api_call(&$a){
108 foreach ($API as $p=>$info){
109 if (strpos($a->query_string, $p)===0){
110 #unset($_SERVER['PHP_AUTH_USER']);
111 if ($info['auth']===true && local_user()===false) {
116 if (strpos($a->query_string, ".xml")>0) $type="xml";
117 if (strpos($a->query_string, ".json")>0) $type="json";
118 if (strpos($a->query_string, ".rss")>0) $type="rss";
119 if (strpos($a->query_string, ".atom")>0) $type="atom";
121 $r = call_user_func($info['func'], $a, $type);
122 if ($r===false) return;
126 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
127 header ("Content-Type: text/xml");
128 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
131 header ("Content-Type: application/json");
132 return json_encode($r);
135 header ("Content-Type: application/rss+xml");
136 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
139 #header ("Content-Type: application/atom+xml");
140 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
144 //echo "<pre>"; var_dump($r); die();
153 function api_rss_extra(&$a, $arr, $user_info){
154 if (is_null($user_info)) $user_info = api_get_user($a);
155 $arr['$rss'] = array(
156 'alternate' => $user_info['url'],
157 'self' => $a->get_baseurl(). "/". $a->query_string,
158 'updated' => api_date(null),
159 'language' => $user_info['language'],
160 'logo' => $a->get_baseurl()."/images/friendika-32.png",
167 * Returns user info array.
169 function api_get_user(&$a){
172 if(x($_GET, 'user_id')) {
173 $user = intval($_GET['user_id']);
174 $extra_query = "AND `contact`.`id` = %d ";
176 if(x($_GET, 'screen_name')) {
177 $user = dbesc($_GET['screen_name']);
178 $extra_query = "AND `contact`.`nick` = '%s' ";
182 list($user, $null) = explode(".",$a->argv[3]);
183 if(is_numeric($user)){
184 $user = intval($user);
185 $extra_query = "AND `contact`.`id` = %d ";
187 $user = dbesc($user);
188 $extra_query = "AND `contact`.`nick` = '%s' ";
193 if (local_user()===false) {
194 api_login($a); return False;
196 $user = $_SESSION['uid'];
197 $extra_query = "AND `user`.`uid` = %d ";
204 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `user`, `contact`
205 WHERE `user`.`uid`=`contact`.`uid` AND `contact`.`self`=1
209 if (count($uinfo)==0) {
213 // count public wall messages
214 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
217 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
218 intval($uinfo[0]['uid'])
220 $countitms = $r[0]['count'];
223 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
225 AND `self`=0 AND `blocked`=0",
226 intval($uinfo[0]['uid'])
228 $countfriends = $r[0]['count'];
232 'id' => $uinfo[0]['cid'],
233 'name' => $uinfo[0]['username'],
234 'screen_name' => $uinfo[0]['nickname'],
235 'location' => $uinfo[0]['default-location'],
236 'profile_image_url' => $uinfo[0]['micro'],
237 'url' => $uinfo[0]['url'],
238 'protected' => false, #
239 'friends_count' => $countfriends,
240 'created_at' => api_date($uinfo[0]['created']),
241 'utc_offset' => 0, #XXX: fix me
242 'time_zone' => $uinfo[0]['timezone'],
243 'geo_enabled' => false,
244 'statuses_count' => $countitms, #XXX: fix me
245 'lang' => 'en', #XXX: fix me
247 'followers_count' => $countfriends, #XXX: fix me
248 'favourites_count' => 0,
249 'contributors_enabled' => false,
250 'follow_request_sent' => false,
251 'profile_background_color' => 'cfe8f6',
252 'profile_text_color' => '000000',
253 'profile_link_color' => 'FF8500',
254 'profile_sidebar_fill_color' =>'AD0066',
255 'profile_sidebar_border_color' => 'AD0066',
256 'profile_background_image_url' => '',
257 'profile_background_tile' => false,
258 'profile_use_background_image' => false,
259 'notifications' => false,
260 'verified' => true, #XXX: fix me
261 'followers' => '', #XXX: fix me
270 * apply xmlify() to all values of array $val, recursively
272 function api_xmlify($val){
273 if (is_bool($val)) return $val?"true":"false";
274 if (is_array($val)) return array_map('api_xmlify', $val);
279 * load api $templatename for $type and replace $data array
281 function api_apply_template($templatename, $type, $data){
286 $data = api_xmlify($data);
287 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
288 $ret = replace_macros($tpl, $data);
302 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
303 * returns a 401 status code and an error message if not.
304 * http://developer.twitter.com/doc/get/account/verify_credentials
306 function api_account_verify_credentials(&$a, $type){
307 if (local_user()===false) return false;
308 $user_info = api_get_user($a);
310 return api_apply_template("user", $type, array('$user' => $user_info));
313 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
316 // TODO - media uploads and alternate 'source'
318 function api_statuses_update(&$a, $type) {
319 if (local_user()===false) return false;
320 $user_info = api_get_user($a);
322 // convert $_POST array items to the form we use for web posts.
324 $_POST['body'] = urldecode($_POST['status']);
325 $_POST['parent'] = $_POST['in_reply_to_status_id'];
326 if($_POST['lat'] && $_POST['long'])
327 $_POST['coord'] = sprintf("%s %s",$_POST['lat'],$_POST['long']);
328 $_POST['profile_uid'] = local_user();
330 $_POST['type'] = 'net-comment';
332 $_POST['type'] = 'wall';
334 // set this so that the item_post() function is quiet and doesn't redirect or emit json
336 $_POST['api_source'] = true;
338 // call out normal post function
340 require_once('mod/item.php');
343 // this should output the last post (the one we just posted).
344 return api_status_show($a,$type);
346 api_register_func('api/statuses/update','api_statuses_update', true);
349 function api_status_show(&$a, $type){
350 $user_info = api_get_user($a);
351 // get last public wall message
352 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
353 FROM `item`, `contact`,
354 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
355 WHERE `item`.`contact-id` = %d
356 AND `i`.`id` = `item`.`parent`
357 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
358 AND `type`!='activity'
359 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
360 ORDER BY `created` DESC
362 intval($user_info['id'])
365 if (count($lastwall)>0){
366 $lastwall = $lastwall[0];
368 $in_reply_to_status_id = '';
369 $in_reply_to_user_id = '';
370 $in_reply_to_screen_name = '';
371 if ($lastwall['parent']!=$lastwall['id']) {
372 $in_reply_to_status_id=$lastwall['parent'];
373 $in_reply_to_user_id = $lastwall['reply_uid'];
374 $in_reply_to_screen_name = $lastwall['reply_author'];
376 $status_info = array(
377 'created_at' => api_date($lastwall['created']),
378 'id' => $lastwall['contact-id'],
379 'text' => strip_tags(bbcode($lastwall['body'])),
381 'truncated' => false,
382 'in_reply_to_status_id' => $in_reply_to_status_id,
383 'in_reply_to_user_id' => $in_reply_to_user_id,
384 'favorited' => false,
385 'in_reply_to_screen_name' => $in_reply_to_screen_name,
387 'coordinates' => $lastwall['coord'],
388 'place' => $lastwall['location'],
391 $status_info['user'] = $user_info;
393 return api_apply_template("status", $type, array('$status' => $status_info));
402 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
403 * The author's most recent status will be returned inline.
404 * http://developer.twitter.com/doc/get/users/show
406 function api_users_show(&$a, $type){
407 $user_info = api_get_user($a);
408 // get last public wall message
409 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
410 FROM `item`, `contact`,
411 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
412 WHERE `item`.`contact-id` = %d
413 AND `i`.`id` = `item`.`parent`
414 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
415 AND `type`!='activity'
416 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
417 ORDER BY `created` DESC
419 intval($user_info['id'])
422 if (count($lastwall)>0){
423 $lastwall = $lastwall[0];
425 $in_reply_to_status_id = '';
426 $in_reply_to_user_id = '';
427 $in_reply_to_screen_name = '';
428 if ($lastwall['parent']!=$lastwall['id']) {
429 $in_reply_to_status_id=$lastwall['parent'];
430 $in_reply_to_user_id = $lastwall['reply_uid'];
431 $in_reply_to_screen_name = $lastwall['reply_author'];
433 $user_info['status'] = array(
434 'created_at' => api_date($lastwall['created']),
435 'id' => $lastwall['contact-id'],
436 'text' => strip_tags(bbcode($lastwall['body'])),
438 'truncated' => false,
439 'in_reply_to_status_id' => $in_reply_to_status_id,
440 'in_reply_to_user_id' => $in_reply_to_user_id,
441 'favorited' => false,
442 'in_reply_to_screen_name' => $in_reply_to_screen_name,
444 'coordinates' => $lastwall['coord'],
445 'place' => $lastwall['location'],
449 return api_apply_template("user", $type, array('$user' => $user_info));
452 api_register_func('api/users/show','api_users_show');
456 * http://developer.twitter.com/doc/get/statuses/home_timeline
458 * TODO: Optional parameters
459 * TODO: Add reply info
461 function api_statuses_home_timeline(&$a, $type){
462 if (local_user()===false) return false;
464 $user_info = api_get_user($a);
466 // get last newtork messages
467 $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
469 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
470 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
471 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
472 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
473 FROM `item`, `contact`, `user`
474 WHERE `item`.`contact-id` = %d AND `user`.`uid` = `item`.`uid`
475 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
476 AND `contact`.`id` = `item`.`contact-id`
477 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
479 ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
480 intval($user_info['id']),
485 foreach($r as $item) {
487 'created_at'=> api_date($item['created']),
488 'published' => datetime_convert('UTC','UTC',$item['created'],ATOM_TIME),
489 'updated' => datetime_convert('UTC','UTC',$item['edited'],ATOM_TIME),
491 'text' => strip_tags(bbcode($item['body'])),
492 'html' => bbcode($item['body']),
494 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
495 'truncated' => False,
496 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
497 'in_reply_to_user_id' => '',
498 'favorited' => false,
499 'in_reply_to_screen_name' => '',
501 'coordinates' => $item['coord'],
502 'place' => $item['location'],
503 'contributors' => '',
506 'user' => $user_info,
507 'objecttype' => $item['object-type'],
508 'verb' => $item['verb'],
509 'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
510 'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
515 $data = array('$statuses' => $ret);
519 $data = api_rss_extra($a, $data, $user_info);
522 return api_apply_template("timeline", $type, $data);
524 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
525 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
526 api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
527 # TODO: user_timeline should be profile view