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 if (!isset($_SERVER['PHP_AUTH_USER'])) {
31 header('WWW-Authenticate: Basic realm="Friendika"');
32 header('HTTP/1.0 401 Unauthorized');
33 die('This api require login');
36 $user = $_SERVER['PHP_AUTH_USER'];
37 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
41 * next code from mod/auth.php. needs better solution
44 // process normal login request
46 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
47 AND `password` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1",
55 header('WWW-Authenticate: Basic realm="Friendika"');
56 header('HTTP/1.0 401 Unauthorized');
57 die('This api require login');
59 $_SESSION['uid'] = $record['uid'];
60 $_SESSION['theme'] = $record['theme'];
61 $_SESSION['authenticated'] = 1;
62 $_SESSION['page_flags'] = $record['page-flags'];
63 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
64 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
66 //notice( t("Welcome back ") . $record['username'] . EOL);
69 if(strlen($a->user['timezone'])) {
70 date_default_timezone_set($a->user['timezone']);
71 $a->timezone = $a->user['timezone'];
74 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
75 intval($_SESSION['uid']));
78 $a->cid = $r[0]['id'];
79 $_SESSION['cid'] = $a->cid;
81 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
82 dbesc(datetime_convert()),
83 intval($_SESSION['uid'])
86 call_hooks('logged_in', $a->user);
88 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
91 /**************************
92 * MAIN API ENTRY POINT *
93 **************************/
94 function api_call(&$a){
96 foreach ($API as $p=>$info){
97 if (strpos($a->query_string, $p)===0){
98 #unset($_SERVER['PHP_AUTH_USER']);
99 if ($info['auth']===true && local_user()===false) {
104 if (strpos($a->query_string, ".xml")>0) $type="xml";
105 if (strpos($a->query_string, ".json")>0) $type="json";
106 if (strpos($a->query_string, ".rss")>0) $type="rss";
107 if (strpos($a->query_string, ".atom")>0) $type="atom";
109 $r = call_user_func($info['func'], $a, $type);
110 if ($r===false) return;
114 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
115 header ("Content-Type: text/xml");
116 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
119 header ("Content-Type: application/json");
120 return json_encode($r);
123 header ("Content-Type: application/rss+xml");
124 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
127 #header ("Content-Type: application/atom+xml");
128 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
132 //echo "<pre>"; var_dump($r); die();
141 function api_rss_extra(&$a, $arr, $user_info){
142 if (is_null($user_info)) $user_info = api_get_user($a);
143 $arr['$rss'] = array(
144 'alternate' => $user_info['url'],
145 'self' => $a->get_baseurl(). "/". $a->query_string,
146 'updated' => api_date(null),
147 'language' => $user_info['language'],
148 'logo' => $a->get_baseurl()."/images/friendika-32.png",
155 * Returns user info array.
157 function api_get_user(&$a){
160 if(x($_GET, 'user_id')) {
161 $user = intval($_GET['user_id']);
162 $extra_query = "AND `contact`.`id` = %d ";
164 if(x($_GET, 'screen_name')) {
165 $user = dbesc($_GET['screen_name']);
166 $extra_query = "AND `contact`.`nick` = '%s' ";
170 list($user, $null) = explode(".",$a->argv[3]);
171 if(is_numeric($user)){
172 $user = intval($user);
173 $extra_query = "AND `contact`.`id` = %d ";
175 $user = dbesc($user);
176 $extra_query = "AND `contact`.`nick` = '%s' ";
181 if (local_user()===false) {
182 api_login($a); return False;
184 $user = $_SESSION['uid'];
185 $extra_query = "AND `user`.`uid` = %d ";
192 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `user`, `contact`
193 WHERE `user`.`uid`=`contact`.`uid` AND `contact`.`self`=1
197 if (count($uinfo)==0) {
201 // count public wall messages
202 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
205 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
206 intval($uinfo[0]['uid'])
208 $countitms = $r[0]['count'];
211 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
213 AND `self`=0 AND `blocked`=0",
214 intval($uinfo[0]['uid'])
216 $countfriends = $r[0]['count'];
220 'id' => $uinfo[0]['cid'],
221 'name' => $uinfo[0]['username'],
222 'screen_name' => $uinfo[0]['nickname'],
223 'location' => $uinfo[0]['default-location'],
224 'profile_image_url' => $uinfo[0]['micro'],
225 'url' => $uinfo[0]['url'],
226 'protected' => false, #
227 'friends_count' => $countfriends,
228 'created_at' => api_date($uinfo[0]['created']),
229 'utc_offset' => 0, #XXX: fix me
230 'time_zone' => $uinfo[0]['timezone'],
231 'geo_enabled' => false,
232 'statuses_count' => $countitms, #XXX: fix me
233 'lang' => 'en', #XXX: fix me
235 'followers_count' => $countfriends, #XXX: fix me
236 'favourites_count' => 0,
237 'contributors_enabled' => false,
238 'follow_request_sent' => false,
239 'profile_background_color' => 'cfe8f6',
240 'profile_text_color' => '000000',
241 'profile_link_color' => 'FF8500',
242 'profile_sidebar_fill_color' =>'AD0066',
243 'profile_sidebar_border_color' => 'AD0066',
244 'profile_background_image_url' => '',
245 'profile_background_tile' => false,
246 'profile_use_background_image' => false,
247 'notifications' => false,
248 'verified' => true, #XXX: fix me
249 'followers' => '', #XXX: fix me
258 * apply xmlify() to all values of array $val, recursively
260 function api_xmlify($val){
261 if (is_bool($val)) return $val?"true":"false";
262 if (is_array($val)) return array_map('api_xmlify', $val);
267 * load api $templatename for $type and replace $data array
269 function api_apply_template($templatename, $type, $data){
274 $data = api_xmlify($data);
275 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
276 $ret = replace_macros($tpl, $data);
290 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
291 * returns a 401 status code and an error message if not.
292 * http://developer.twitter.com/doc/get/account/verify_credentials
294 function api_account_verify_credentials(&$a, $type){
295 if (local_user()===false) return false;
296 $user_info = api_get_user($a);
298 return api_apply_template("user", $type, array('$user' => $user_info));
301 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
304 // TODO - media uploads and alternate 'source'
306 function api_post_message(&$a, $type) {
307 if (local_user()===false) return false;
308 $user_info = api_get_user($a);
310 // convert $_POST array items to the form we use for web posts.
312 $_POST['body'] = urldecode($_POST['status']);
313 $_POST['parent'] = $_POST['in_reply_to_status_id'];
314 if($_POST['lat'] && $_POST['long'])
315 $_POST['coord'] = sprintf("%s %s",$_POST['lat'],$_POST['long']);
316 $_POST['profile_uid'] = local_user();
318 $_POST['type'] = 'net-comment';
320 $_POST['type'] = 'wall';
322 // set this so that the item_post() function is quiet and doesn't redirect or emit json
324 $_POST['api_source'] = true;
326 // call out normal post function
328 require_once('mod/item.php');
331 // this should output the last post (the one we just posted).
332 return api_users_show();
334 api_register_func('api/statuses/update','api_statuses_update', true);
338 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
339 * The author's most recent status will be returned inline.
340 * http://developer.twitter.com/doc/get/users/show
342 function api_users_show(&$a, $type){
343 $user_info = api_get_user($a);
344 // get last public wall message
345 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
346 FROM `item`, `contact`,
347 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
348 WHERE `item`.`contact-id` = %d
349 AND `i`.`id` = `item`.`parent`
350 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
351 AND `type`!='activity'
352 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
353 ORDER BY `created` DESC
355 intval($user_info['id'])
358 if (count($lastwall)>0){
359 $lastwall = $lastwall[0];
361 $in_reply_to_status_id = '';
362 $in_reply_to_user_id = '';
363 $in_reply_to_screen_name = '';
364 if ($lastwall['parent']!=$lastwall['id']) {
365 $in_reply_to_status_id=$lastwall['parent'];
366 $in_reply_to_user_id = $lastwall['reply_uid'];
367 $in_reply_to_screen_name = $lastwall['reply_author'];
369 $user_info['status'] = array(
370 'created_at' => api_date($lastwall['created']),
371 'id' => $lastwall['contact-id'],
372 'text' => strip_tags(bbcode($lastwall['body'])),
374 'truncated' => false,
375 'in_reply_to_status_id' => $in_reply_to_status_id,
376 'in_reply_to_user_id' => $in_reply_to_user_id,
377 'favorited' => false,
378 'in_reply_to_screen_name' => $in_reply_to_screen_name,
380 'coordinates' => $lastwall['coord'],
381 'place' => $lastwall['location'],
385 return api_apply_template("user", $type, array('$user' => $user_info));
388 api_register_func('api/users/show','api_users_show');
392 * http://developer.twitter.com/doc/get/statuses/home_timeline
394 * TODO: Optional parameters
395 * TODO: Add reply info
397 function api_statuses_home_timeline(&$a, $type){
398 if (local_user()===false) return false;
400 $user_info = api_get_user($a);
402 // get last newtork messages
403 $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
405 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
406 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
407 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
408 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
409 FROM `item`, `contact`, `user`
410 WHERE `item`.`contact-id` = %d AND `user`.`uid` = `item`.`uid`
411 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
412 AND `contact`.`id` = `item`.`contact-id`
413 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
415 ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
416 intval($user_info['id']),
421 foreach($r as $item) {
423 'created_at'=> api_date($item['created']),
425 'text' => strip_tags(bbcode($item['body'])),
426 'html' => bbcode($item['body']),
428 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
429 'truncated' => False,
430 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
431 'in_reply_to_user_id' => '',
432 'favorited' => false,
433 'in_reply_to_screen_name' => '',
435 'coordinates' => $item['coord'],
436 'place' => $item['location'],
437 'contributors' => '',
440 'user' => $user_info,
441 'objecttype' => $item['object-type'],
442 'verb' => $item['verb'],
443 'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
444 'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
449 $data = array('$statuses' => $ret);
453 $data = api_rss_extra($a, $data, $user_info);
456 return api_apply_template("timeline", $type, $data);
458 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
459 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
460 api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
461 # TODO: user_timeline should be profile view