2 require_once("bbcode.php");
3 require_once("datetime.php");
4 require_once("conversation.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 `account_expired` = 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){
107 GLOBAL $API, $called_api;
108 foreach ($API as $p=>$info){
109 if (strpos($a->query_string, $p)===0){
110 $called_api= explode("/",$p);
111 #unset($_SERVER['PHP_AUTH_USER']);
112 if ($info['auth']===true && local_user()===false) {
116 load_contact_links(local_user());
118 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
119 logger('API parameters: ' . print_r($_REQUEST,true));
121 if (strpos($a->query_string, ".xml")>0) $type="xml";
122 if (strpos($a->query_string, ".json")>0) $type="json";
123 if (strpos($a->query_string, ".rss")>0) $type="rss";
124 if (strpos($a->query_string, ".atom")>0) $type="atom";
126 $r = call_user_func($info['func'], $a, $type);
127 if ($r===false) return;
131 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
132 header ("Content-Type: text/xml");
133 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
136 //header ("Content-Type: application/json");
138 return json_encode($rr);
141 header ("Content-Type: application/rss+xml");
142 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
145 header ("Content-Type: application/atom+xml");
146 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
150 //echo "<pre>"; var_dump($r); die();
153 $r = '<status><error>not implemented</error></status>';
156 header ("Content-Type: text/xml");
157 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
160 header ("Content-Type: application/json");
161 return json_encode(array('error' => 'not implemented'));
164 header ("Content-Type: application/rss+xml");
165 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
168 header ("Content-Type: application/atom+xml");
169 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
178 function api_rss_extra(&$a, $arr, $user_info){
179 if (is_null($user_info)) $user_info = api_get_user($a);
180 $arr['$user'] = $user_info;
181 $arr['$rss'] = array(
182 'alternate' => $user_info['url'],
183 'self' => $a->get_baseurl(). "/". $a->query_string,
184 'base' => $a->get_baseurl(),
185 'updated' => api_date(null),
186 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
187 'language' => $user_info['language'],
188 'logo' => $a->get_baseurl()."/images/friendika-32.png",
195 * Returns user info array.
197 function api_get_user(&$a, $contact_id = Null){
203 if(!is_null($contact_id)){
205 $extra_query = "AND `contact`.`id` = %d ";
208 if(is_null($user) && x($_GET, 'user_id')) {
209 $user = intval($_GET['user_id']);
210 $extra_query = "AND `contact`.`id` = %d ";
212 if(is_null($user) && x($_GET, 'screen_name')) {
213 $user = dbesc($_GET['screen_name']);
214 $extra_query = "AND `contact`.`nick` = '%s' ";
215 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
219 if (is_null($user) && $a->argc > (count($called_api)-1)){
220 $argid = count($called_api);
221 list($user, $null) = explode(".",$a->argv[$argid]);
222 if(is_numeric($user)){
223 $user = intval($user);
224 $extra_query = "AND `contact`.`id` = %d ";
226 $user = dbesc($user);
227 $extra_query = "AND `contact`.`nick` = '%s' ";
228 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
233 if (local_user()===false) {
234 api_login($a); return False;
236 $user = $_SESSION['uid'];
237 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
242 logger('api_user: ' . $extra_query . ' ' , $user);
244 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
249 if (count($uinfo)==0) {
253 if($uinfo[0]['self']) {
254 $usr = q("select * from user where uid = %d limit 1",
257 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
261 // count public wall messages
262 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
265 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
266 intval($uinfo[0]['uid'])
268 $countitms = $r[0]['count'];
271 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
272 WHERE `contact-id` = %d
273 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
274 intval($uinfo[0]['id'])
276 $countitms = $r[0]['count'];
280 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
281 WHERE `uid` = %d AND `rel` IN ( %d, %d )
282 AND `self`=0 AND `blocked`=0",
283 intval($uinfo[0]['uid']),
284 intval(CONTACT_IS_SHARING),
285 intval(CONTACT_IS_FRIEND)
287 $countfriends = $r[0]['count'];
289 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
290 WHERE `uid` = %d AND `rel` IN ( %d, %d )
291 AND `self`=0 AND `blocked`=0",
292 intval($uinfo[0]['uid']),
293 intval(CONTACT_IS_FOLLOWER),
294 intval(CONTACT_IS_FRIEND)
296 $countfollowers = $r[0]['count'];
298 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
299 intval($uinfo[0]['uid'])
301 $starred = $r[0]['count'];
304 if(! $uinfo[0]['self']) {
311 'self' => intval($uinfo[0]['self']),
312 'uid' => intval($uinfo[0]['uid']),
313 'id' => intval($uinfo[0]['cid']),
314 'name' => $uinfo[0]['name'],
315 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
316 'location' => ($usr) ? $usr[0]['default-location'] : '',
317 'profile_image_url' => $uinfo[0]['micro'],
318 'url' => $uinfo[0]['url'],
319 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
320 'protected' => false,
321 'friends_count' => intval($countfriends),
322 'created_at' => api_date($uinfo[0]['name-date']),
323 'utc_offset' => "+00:00",
324 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
325 'geo_enabled' => false,
326 'statuses_count' => intval($countitms), #XXX: fix me
327 'lang' => 'en', #XXX: fix me
328 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
329 'followers_count' => intval($countfollowers),
330 'favourites_count' => intval($starred),
331 'contributors_enabled' => false,
332 'follow_request_sent' => true,
333 'profile_background_color' => 'cfe8f6',
334 'profile_text_color' => '000000',
335 'profile_link_color' => 'FF8500',
336 'profile_sidebar_fill_color' =>'AD0066',
337 'profile_sidebar_border_color' => 'AD0066',
338 'profile_background_image_url' => '',
339 'profile_background_tile' => false,
340 'profile_use_background_image' => false,
341 'notifications' => false,
342 'following' => '', #XXX: fix me
343 'verified' => true, #XXX: fix me
351 function api_item_get_user(&$a, $item) {
352 // The author is our direct contact, in a conversation with us.
353 if(link_compare($item['url'],$item['author-link'])) {
354 return api_get_user($a,$item['cid']);
357 // The author may be a contact of ours, but is replying to somebody else.
358 // Figure out if we know him/her.
359 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
360 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
361 return api_get_user($a,$a->contacts[$normalised]['id']);
363 // We don't know this person directly.
365 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
366 $name=str_replace(")","",$name);
372 'screen_name' => $nick,
373 'location' => '', //$uinfo[0]['default-location'],
374 'profile_image_url' => $item['author-avatar'],
375 'url' => $item['author-link'],
377 'protected' => false, #
378 'friends_count' => 0,
380 'utc_offset' => 0, #XXX: fix me
381 'time_zone' => '', //$uinfo[0]['timezone'],
382 'geo_enabled' => false,
383 'statuses_count' => 0,
384 'lang' => 'en', #XXX: fix me
386 'followers_count' => 0,
387 'favourites_count' => 0,
388 'contributors_enabled' => false,
389 'follow_request_sent' => false,
390 'profile_background_color' => 'cfe8f6',
391 'profile_text_color' => '000000',
392 'profile_link_color' => 'FF8500',
393 'profile_sidebar_fill_color' =>'AD0066',
394 'profile_sidebar_border_color' => 'AD0066',
395 'profile_background_image_url' => '',
396 'profile_background_tile' => false,
397 'profile_use_background_image' => false,
398 'notifications' => false,
399 'verified' => true, #XXX: fix me
400 'followers' => '', #XXX: fix me
409 * load api $templatename for $type and replace $data array
411 function api_apply_template($templatename, $type, $data){
419 $data = array_xmlify($data);
420 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
421 $ret = replace_macros($tpl, $data);
435 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
436 * returns a 401 status code and an error message if not.
437 * http://developer.twitter.com/doc/get/account/verify_credentials
439 function api_account_verify_credentials(&$a, $type){
440 if (local_user()===false) return false;
441 $user_info = api_get_user($a);
443 return api_apply_template("user", $type, array('$user' => $user_info));
446 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
450 * get data from $_POST or $_GET
452 function requestdata($k){
453 if (isset($_POST[$k])){
456 if (isset($_GET[$k])){
462 // TODO - media uploads
463 function api_statuses_update(&$a, $type) {
464 if (local_user()===false) return false;
465 $user_info = api_get_user($a);
467 // convert $_POST array items to the form we use for web posts.
469 // logger('api_post: ' . print_r($_POST,true));
471 if(requestdata('htmlstatus')) {
472 require_once('library/HTMLPurifier.auto.php');
473 require_once('include/html2bbcode.php');
475 $txt = requestdata('htmlstatus');
476 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
478 $txt = html2bb_video($txt);
480 $config = HTMLPurifier_Config::createDefault();
481 $config->set('Cache.DefinitionImpl', null);
484 $purifier = new HTMLPurifier($config);
485 $txt = $purifier->purify($txt);
487 $_POST['body'] = html2bbcode($txt);
492 $_POST['body'] = urldecode(requestdata('status'));
494 $parent = requestdata('in_reply_to_status_id');
495 if(ctype_digit($parent))
496 $_POST['parent'] = $parent;
498 $_POST['parent_uri'] = $parent;
500 if(requestdata('lat') && requestdata('long'))
501 $_POST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
502 $_POST['profile_uid'] = local_user();
503 if(requestdata('parent'))
504 $_POST['type'] = 'net-comment';
506 $_POST['type'] = 'wall';
508 // set this so that the item_post() function is quiet and doesn't redirect or emit json
510 $_POST['api_source'] = true;
512 // call out normal post function
514 require_once('mod/item.php');
517 // this should output the last post (the one we just posted).
518 return api_status_show($a,$type);
520 api_register_func('api/statuses/update','api_statuses_update', true);
523 function api_status_show(&$a, $type){
524 $user_info = api_get_user($a);
525 // get last public wall message
526 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
527 FROM `item`, `contact`,
528 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
529 WHERE `item`.`contact-id` = %d
530 AND `i`.`id` = `item`.`parent`
531 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
532 AND `type`!='activity'
533 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
534 ORDER BY `created` DESC
536 intval($user_info['id'])
539 if (count($lastwall)>0){
540 $lastwall = $lastwall[0];
542 $in_reply_to_status_id = '';
543 $in_reply_to_user_id = '';
544 $in_reply_to_screen_name = '';
545 if ($lastwall['parent']!=$lastwall['id']) {
546 $in_reply_to_status_id=$lastwall['parent'];
547 $in_reply_to_user_id = $lastwall['reply_uid'];
548 $in_reply_to_screen_name = $lastwall['reply_author'];
550 $status_info = array(
551 'created_at' => api_date($lastwall['created']),
552 'id' => $lastwall['contact-id'],
553 'text' => strip_tags(bbcode($lastwall['body'])),
554 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
555 'truncated' => false,
556 'in_reply_to_status_id' => $in_reply_to_status_id,
557 'in_reply_to_user_id' => $in_reply_to_user_id,
558 'favorited' => false,
559 'in_reply_to_screen_name' => $in_reply_to_screen_name,
561 'coordinates' => $lastwall['coord'],
562 'place' => $lastwall['location'],
565 $status_info['user'] = $user_info;
567 return api_apply_template("status", $type, array('$status' => $status_info));
576 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
577 * The author's most recent status will be returned inline.
578 * http://developer.twitter.com/doc/get/users/show
580 function api_users_show(&$a, $type){
581 $user_info = api_get_user($a);
582 // get last public wall message
583 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
584 FROM `item`, `contact`,
585 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
586 WHERE `item`.`contact-id` = %d
587 AND `i`.`id` = `item`.`parent`
588 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
589 AND `type`!='activity'
590 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
591 ORDER BY `created` DESC
593 intval($user_info['id'])
596 if (count($lastwall)>0){
597 $lastwall = $lastwall[0];
599 $in_reply_to_status_id = '';
600 $in_reply_to_user_id = '';
601 $in_reply_to_screen_name = '';
602 if ($lastwall['parent']!=$lastwall['id']) {
603 $in_reply_to_status_id=$lastwall['parent'];
604 $in_reply_to_user_id = $lastwall['reply_uid'];
605 $in_reply_to_screen_name = $lastwall['reply_author'];
607 $user_info['status'] = array(
608 'created_at' => api_date($lastwall['created']),
609 'id' => $lastwall['contact-id'],
610 'text' => strip_tags(bbcode($lastwall['body'])),
611 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
612 'truncated' => false,
613 'in_reply_to_status_id' => $in_reply_to_status_id,
614 'in_reply_to_user_id' => $in_reply_to_user_id,
615 'favorited' => false,
616 'in_reply_to_screen_name' => $in_reply_to_screen_name,
618 'coordinates' => $lastwall['coord'],
619 'place' => $lastwall['location'],
623 return api_apply_template("user", $type, array('$user' => $user_info));
626 api_register_func('api/users/show','api_users_show');
630 * http://developer.twitter.com/doc/get/statuses/home_timeline
632 * TODO: Optional parameters
633 * TODO: Add reply info
635 function api_statuses_home_timeline(&$a, $type){
636 if (local_user()===false) return false;
638 $user_info = api_get_user($a);
639 // get last newtork messages
643 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
644 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
645 if ($page<0) $page=0;
646 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
648 $start = $page*$count;
650 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
651 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
652 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
653 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
654 FROM `item`, `contact`
655 WHERE `item`.`uid` = %d
656 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
657 AND `contact`.`id` = `item`.`contact-id`
658 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
661 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
662 intval($user_info['uid']),
664 intval($start), intval($count)
667 $ret = api_format_items($r,$user_info);
670 $data = array('$statuses' => $ret);
674 $data = api_rss_extra($a, $data, $user_info);
677 return api_apply_template("timeline", $type, $data);
679 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
680 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
684 function api_statuses_user_timeline(&$a, $type){
685 if (local_user()===false) return false;
687 $user_info = api_get_user($a);
688 // get last newtork messages
691 logger("api_statuses_user_timeline: local_user: ". local_user() .
692 "\nuser_info: ".print_r($user_info, true) .
693 "\n_REQUEST: ".print_r($_REQUEST, true),
697 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
698 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
699 if ($page<0) $page=0;
700 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
702 $start = $page*$count;
704 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
706 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
707 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
708 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
709 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
710 FROM `item`, `contact`
711 WHERE `item`.`uid` = %d
712 AND `item`.`contact-id` = %d
713 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
714 AND `contact`.`id` = `item`.`contact-id`
715 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
718 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
719 intval(local_user()),
720 intval($user_info['id']),
722 intval($start), intval($count)
725 $ret = api_format_items($r,$user_info);
728 $data = array('$statuses' => $ret);
732 $data = api_rss_extra($a, $data, $user_info);
735 return api_apply_template("timeline", $type, $data);
738 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
741 function api_favorites(&$a, $type){
742 if (local_user()===false) return false;
744 $user_info = api_get_user($a);
745 // in friendika starred item are private
746 // return favorites only for self
747 logger('api_favorites: self:' . $user_info['self']);
749 if ($user_info['self']==0) {
755 $count = (x($_GET,'count')?$_GET['count']:20);
756 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
757 if ($page<0) $page=0;
759 $start = $page*$count;
761 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
762 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
763 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
764 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
765 FROM `item`, `contact`
766 WHERE `item`.`uid` = %d
767 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
768 AND `item`.`starred` = 1
769 AND `contact`.`id` = `item`.`contact-id`
770 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
772 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
773 intval($user_info['uid']),
774 intval($start), intval($count)
777 $ret = api_format_items($r,$user_info);
781 $data = array('$statuses' => $ret);
785 $data = api_rss_extra($a, $data, $user_info);
788 return api_apply_template("timeline", $type, $data);
791 api_register_func('api/favorites','api_favorites', true);
794 function api_format_items($r,$user_info) {
796 //logger('api_format_items: ' . print_r($r,true));
798 //logger('api_format_items: ' . print_r($user_info,true));
803 foreach($r as $item) {
804 localize_item($item);
805 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
807 'created_at'=> api_date($item['created']),
808 'published' => api_date($item['created']),
809 'updated' => api_date($item['edited']),
810 'id' => intval($item['id']),
811 'message_id' => $item['uri'],
812 'text' => strip_tags(bbcode($item['body'])),
813 'statusnet_html' => bbcode($item['body']),
814 'source' => (($item['app']) ? $item['app'] : 'web'),
815 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
816 'truncated' => False,
817 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
818 'in_reply_to_user_id' => '',
819 'favorited' => $item['starred'] ? true : false,
820 'in_reply_to_screen_name' => '',
822 'coordinates' => $item['coord'],
823 'place' => $item['location'],
824 'contributors' => '',
827 'user' => $status_user ,
828 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
829 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
830 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
831 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
839 function api_account_rate_limit_status(&$a,$type) {
842 'remaining_hits' => (string) 150,
843 'hourly_limit' => (string) 150,
844 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
845 'reset_time_in_seconds' => strtotime('now + 1 hour')
848 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
851 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
854 * https://dev.twitter.com/docs/api/1/get/statuses/friends
855 * This function is deprecated by Twitter
858 function api_statuses_f(&$a, $type, $qtype) {
859 if (local_user()===false) return false;
860 $user_info = api_get_user($a);
863 // friends and followers only for self
864 if ($user_info['self']==0){
868 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
869 /* this is to stop Hotot to load friends multiple times
870 * I'm not sure if I'm missing return something or
871 * is a bug in hotot. Workaround, meantime
875 return array('$users' => $ret);*/
879 if($qtype == 'friends')
880 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
881 if($qtype == 'followers')
882 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
884 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
890 $ret[] = api_get_user($a, $cid['id']);
894 return array('$users' => $ret);
897 function api_statuses_friends(&$a, $type){
898 $data = api_statuses_f($a,$type,"friends");
899 if ($data===false) return false;
900 return api_apply_template("friends", $type, $data);
902 function api_statuses_followers(&$a, $type){
903 $data = api_statuses_f($a,$type,"followers");
904 if ($data===false) return false;
905 return api_apply_template("friends", $type, $data);
907 api_register_func('api/statuses/friends','api_statuses_friends',true);
908 api_register_func('api/statuses/followers','api_statuses_followers',true);
915 function api_statusnet_config(&$a,$type) {
916 $name = $a->config['sitename'];
917 $server = $a->get_hostname();
918 $logo = $a->get_baseurl() . '/images/friendika-64.png';
919 $email = $a->config['admin_email'];
920 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
921 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
922 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
923 if($a->config['api_import_size'])
924 $texlimit = string($a->config['api_import_size']);
925 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
926 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
929 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
930 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
931 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
932 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
933 'shorturllength' => '30'
937 return api_apply_template('config', $type, array('$config' => $config));
940 api_register_func('api/statusnet/config','api_statusnet_config',false);
942 function api_statusnet_version(&$a,$type) {
946 if($type === 'xml') {
947 header("Content-type: application/xml");
948 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
951 elseif($type === 'json') {
952 header("Content-type: application/json");
957 api_register_func('api/statusnet/version','api_statusnet_version',false);
960 function api_ff_ids(&$a,$type,$qtype) {
964 if($qtype == 'friends')
965 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
966 if($qtype == 'followers')
967 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
970 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
975 if($type === 'xml') {
976 header("Content-type: application/xml");
977 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
979 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
980 echo '</ids>' . "\r\n";
983 elseif($type === 'json') {
985 header("Content-type: application/json");
986 foreach($r as $rr) $ret[] = $rr['id'];
987 echo json_encode($ret);
993 function api_friends_ids(&$a,$type) {
994 api_ff_ids($a,$type,'friends');
996 function api_followers_ids(&$a,$type) {
997 api_ff_ids($a,$type,'followers');
999 api_register_func('api/friends/ids','api_friends_ids',true);
1000 api_register_func('api/followers/ids','api_followers_ids',true);
1003 function api_direct_messages_new(&$a, $type) {
1004 if (local_user()===false) return false;
1006 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1008 $sender = api_get_user($a);
1010 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1011 intval(local_user()),
1012 dbesc($_POST['screen_name']));
1014 $recipient = api_get_user($a, $r[0]['id']);
1017 require_once("include/message.php");
1018 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1019 $id = send_message($recipient['id'], $_POST['text'], $sub);
1023 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1026 'id' => $item['id'],
1027 'created_at'=> api_date($item['created']),
1028 'sender_id'=> $sender['id'] ,
1029 'sender_screen_name'=> $sender['screen_name'],
1031 'recipient_id'=> $recipient['id'],
1032 'recipient_screen_name'=> $recipient['screen_name'],
1033 'recipient'=> $recipient,
1035 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1040 $ret = array("error"=>$id);
1043 $data = Array('$messages'=>$ret);
1048 $data = api_rss_extra($a, $data, $user_info);
1051 return api_apply_template("direct_messages", $type, $data);
1054 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1056 function api_direct_messages_box(&$a, $type, $box) {
1057 if (local_user()===false) return false;
1059 $user_info = api_get_user($a);
1062 $count = (x($_GET,'count')?$_GET['count']:20);
1063 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1064 if ($page<0) $page=0;
1066 $start = $page*$count;
1069 if ($box=="sentbox") {
1070 $sql_extra = "`from-url`='%s'";
1072 $sql_extra = "`from-url`!='%s'";
1075 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1076 intval(local_user()),
1077 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1078 intval($start), intval($count)
1082 foreach($r as $item){
1085 $recipient = $user_info;
1086 $sender = api_get_user($a,$item['contact-id']);
1089 $recipient = api_get_user($a,$item['contact-id']);
1090 $sender = $user_info;
1095 'id' => $item['id'],
1096 'created_at'=> api_date($item['created']),
1097 'sender_id'=> $sender['id'] ,
1098 'sender_screen_name'=> $sender['screen_name'],
1100 'recipient_id'=> $recipient['id'],
1101 'recipient_screen_name'=> $recipient['screen_name'],
1102 'recipient'=> $recipient,
1104 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1111 $data = array('$messages' => $ret);
1115 $data = api_rss_extra($a, $data, $user_info);
1118 return api_apply_template("direct_messages", $type, $data);
1122 function api_direct_messages_sentbox(&$a, $type){
1123 return api_direct_messages_box($a, $type, "sentbox");
1125 function api_direct_messages_inbox(&$a, $type){
1126 return api_direct_messages_box($a, $type, "inbox");
1128 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1129 api_register_func('api/direct_messages','api_direct_messages_inbox',true);