2 require_once("bbcode.php");
3 require_once("datetime.php");
4 require_once("conversation.php");
5 require_once("oauth.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){
32 $oauth = new FKOAuth1();
33 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
34 if (!is_null($token)){
35 $oauth->loginUser($token->uid);
36 call_hooks('logged_in', $a->user);
39 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
41 logger(__file__.__line__.__function__."\n".$e);
42 //die(__file__.__line__.__function__."<pre>".$e); die();
47 // workaround for HTTP-auth in CGI mode
48 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
49 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
50 if(strlen($userpass)) {
51 list($name, $password) = explode(':', $userpass);
52 $_SERVER['PHP_AUTH_USER'] = $name;
53 $_SERVER['PHP_AUTH_PW'] = $password;
57 if (!isset($_SERVER['PHP_AUTH_USER'])) {
58 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
59 header('WWW-Authenticate: Basic realm="Friendika"');
60 header('HTTP/1.0 401 Unauthorized');
61 die('This api requires login');
64 $user = $_SERVER['PHP_AUTH_USER'];
65 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
69 * next code from mod/auth.php. needs better solution
72 // process normal login request
74 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
75 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
83 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
84 header('WWW-Authenticate: Basic realm="Friendika"');
85 header('HTTP/1.0 401 Unauthorized');
86 die('This api requires login');
89 require_once('include/security.php');
90 authenticate_success($record);
92 call_hooks('logged_in', $a->user);
96 /**************************
97 * MAIN API ENTRY POINT *
98 **************************/
99 function api_call(&$a){
100 GLOBAL $API, $called_api;
101 foreach ($API as $p=>$info){
102 if (strpos($a->query_string, $p)===0){
103 $called_api= explode("/",$p);
104 //unset($_SERVER['PHP_AUTH_USER']);
105 if ($info['auth']===true && local_user()===false) {
109 load_contact_links(local_user());
111 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
112 logger('API parameters: ' . print_r($_REQUEST,true));
114 if (strpos($a->query_string, ".xml")>0) $type="xml";
115 if (strpos($a->query_string, ".json")>0) $type="json";
116 if (strpos($a->query_string, ".rss")>0) $type="rss";
117 if (strpos($a->query_string, ".atom")>0) $type="atom";
119 $r = call_user_func($info['func'], $a, $type);
120 if ($r===false) return;
124 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
125 header ("Content-Type: text/xml");
126 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
129 //header ("Content-Type: application/json");
131 return json_encode($rr);
134 header ("Content-Type: application/rss+xml");
135 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
138 header ("Content-Type: application/atom+xml");
139 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
143 //echo "<pre>"; var_dump($r); die();
146 $r = '<status><error>not implemented</error></status>';
149 header ("Content-Type: text/xml");
150 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
153 header ("Content-Type: application/json");
154 return json_encode(array('error' => 'not implemented'));
157 header ("Content-Type: application/rss+xml");
158 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
161 header ("Content-Type: application/atom+xml");
162 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
171 function api_rss_extra(&$a, $arr, $user_info){
172 if (is_null($user_info)) $user_info = api_get_user($a);
173 $arr['$user'] = $user_info;
174 $arr['$rss'] = array(
175 'alternate' => $user_info['url'],
176 'self' => $a->get_baseurl(). "/". $a->query_string,
177 'base' => $a->get_baseurl(),
178 'updated' => api_date(null),
179 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
180 'language' => $user_info['language'],
181 'logo' => $a->get_baseurl()."/images/friendika-32.png",
188 * Returns user info array.
190 function api_get_user(&$a, $contact_id = Null){
196 if(!is_null($contact_id)){
198 $extra_query = "AND `contact`.`id` = %d ";
201 if(is_null($user) && x($_GET, 'user_id')) {
202 $user = intval($_GET['user_id']);
203 $extra_query = "AND `contact`.`id` = %d ";
205 if(is_null($user) && x($_GET, 'screen_name')) {
206 $user = dbesc($_GET['screen_name']);
207 $extra_query = "AND `contact`.`nick` = '%s' ";
208 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
212 if (is_null($user) && $a->argc > (count($called_api)-1)){
213 $argid = count($called_api);
214 list($user, $null) = explode(".",$a->argv[$argid]);
215 if(is_numeric($user)){
216 $user = intval($user);
217 $extra_query = "AND `contact`.`id` = %d ";
219 $user = dbesc($user);
220 $extra_query = "AND `contact`.`nick` = '%s' ";
221 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
226 if (local_user()===false) {
227 api_login($a); return False;
229 $user = $_SESSION['uid'];
230 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
235 logger('api_user: ' . $extra_query . ' ' , $user);
237 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
242 if (count($uinfo)==0) {
246 if($uinfo[0]['self']) {
247 $usr = q("select * from user where uid = %d limit 1",
250 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
254 // count public wall messages
255 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
258 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
259 intval($uinfo[0]['uid'])
261 $countitms = $r[0]['count'];
264 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
265 WHERE `contact-id` = %d
266 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
267 intval($uinfo[0]['id'])
269 $countitms = $r[0]['count'];
273 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
274 WHERE `uid` = %d AND `rel` IN ( %d, %d )
275 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
276 intval($uinfo[0]['uid']),
277 intval(CONTACT_IS_SHARING),
278 intval(CONTACT_IS_FRIEND)
280 $countfriends = $r[0]['count'];
282 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
283 WHERE `uid` = %d AND `rel` IN ( %d, %d )
284 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
285 intval($uinfo[0]['uid']),
286 intval(CONTACT_IS_FOLLOWER),
287 intval(CONTACT_IS_FRIEND)
289 $countfollowers = $r[0]['count'];
291 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
292 intval($uinfo[0]['uid'])
294 $starred = $r[0]['count'];
297 if(! $uinfo[0]['self']) {
304 'self' => intval($uinfo[0]['self']),
305 'uid' => intval($uinfo[0]['uid']),
306 'id' => intval($uinfo[0]['cid']),
307 'name' => $uinfo[0]['name'],
308 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
309 'location' => ($usr) ? $usr[0]['default-location'] : '',
310 'profile_image_url' => $uinfo[0]['micro'],
311 'url' => $uinfo[0]['url'],
312 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
313 'protected' => false,
314 'friends_count' => intval($countfriends),
315 'created_at' => api_date($uinfo[0]['name-date']),
316 'utc_offset' => "+00:00",
317 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
318 'geo_enabled' => false,
319 'statuses_count' => intval($countitms), #XXX: fix me
320 'lang' => 'en', #XXX: fix me
321 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
322 'followers_count' => intval($countfollowers),
323 'favourites_count' => intval($starred),
324 'contributors_enabled' => false,
325 'follow_request_sent' => true,
326 'profile_background_color' => 'cfe8f6',
327 'profile_text_color' => '000000',
328 'profile_link_color' => 'FF8500',
329 'profile_sidebar_fill_color' =>'AD0066',
330 'profile_sidebar_border_color' => 'AD0066',
331 'profile_background_image_url' => '',
332 'profile_background_tile' => false,
333 'profile_use_background_image' => false,
334 'notifications' => false,
335 'following' => '', #XXX: fix me
336 'verified' => true, #XXX: fix me
344 function api_item_get_user(&$a, $item) {
345 // The author is our direct contact, in a conversation with us.
346 if(link_compare($item['url'],$item['author-link'])) {
347 return api_get_user($a,$item['cid']);
350 // The author may be a contact of ours, but is replying to somebody else.
351 // Figure out if we know him/her.
352 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
353 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
354 return api_get_user($a,$a->contacts[$normalised]['id']);
356 // We don't know this person directly.
358 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
359 $name=str_replace(")","",$name);
365 'screen_name' => $nick,
366 'location' => '', //$uinfo[0]['default-location'],
367 'profile_image_url' => $item['author-avatar'],
368 'url' => $item['author-link'],
370 'protected' => false, #
371 'friends_count' => 0,
373 'utc_offset' => 0, #XXX: fix me
374 'time_zone' => '', //$uinfo[0]['timezone'],
375 'geo_enabled' => false,
376 'statuses_count' => 0,
377 'lang' => 'en', #XXX: fix me
379 'followers_count' => 0,
380 'favourites_count' => 0,
381 'contributors_enabled' => false,
382 'follow_request_sent' => false,
383 'profile_background_color' => 'cfe8f6',
384 'profile_text_color' => '000000',
385 'profile_link_color' => 'FF8500',
386 'profile_sidebar_fill_color' =>'AD0066',
387 'profile_sidebar_border_color' => 'AD0066',
388 'profile_background_image_url' => '',
389 'profile_background_tile' => false,
390 'profile_use_background_image' => false,
391 'notifications' => false,
392 'verified' => true, #XXX: fix me
393 'followers' => '', #XXX: fix me
402 * load api $templatename for $type and replace $data array
404 function api_apply_template($templatename, $type, $data){
412 $data = array_xmlify($data);
413 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
414 $ret = replace_macros($tpl, $data);
428 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
429 * returns a 401 status code and an error message if not.
430 * http://developer.twitter.com/doc/get/account/verify_credentials
432 function api_account_verify_credentials(&$a, $type){
433 if (local_user()===false) return false;
434 $user_info = api_get_user($a);
436 return api_apply_template("user", $type, array('$user' => $user_info));
439 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
443 * get data from $_POST or $_GET
445 function requestdata($k){
446 if (isset($_POST[$k])){
449 if (isset($_GET[$k])){
455 // TODO - media uploads
456 function api_statuses_update(&$a, $type) {
457 if (local_user()===false) return false;
458 $user_info = api_get_user($a);
460 // convert $_POST array items to the form we use for web posts.
462 // logger('api_post: ' . print_r($_POST,true));
464 if(requestdata('htmlstatus')) {
465 require_once('library/HTMLPurifier.auto.php');
466 require_once('include/html2bbcode.php');
468 $txt = requestdata('htmlstatus');
469 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
471 $txt = html2bb_video($txt);
473 $config = HTMLPurifier_Config::createDefault();
474 $config->set('Cache.DefinitionImpl', null);
477 $purifier = new HTMLPurifier($config);
478 $txt = $purifier->purify($txt);
480 $_POST['body'] = html2bbcode($txt);
485 $_POST['body'] = urldecode(requestdata('status'));
487 $parent = requestdata('in_reply_to_status_id');
488 if(ctype_digit($parent))
489 $_POST['parent'] = $parent;
491 $_POST['parent_uri'] = $parent;
493 if(requestdata('lat') && requestdata('long'))
494 $_POST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
495 $_POST['profile_uid'] = local_user();
496 if(requestdata('parent'))
497 $_POST['type'] = 'net-comment';
499 $_POST['type'] = 'wall';
501 // set this so that the item_post() function is quiet and doesn't redirect or emit json
503 $_POST['api_source'] = true;
505 // call out normal post function
507 require_once('mod/item.php');
510 // this should output the last post (the one we just posted).
511 return api_status_show($a,$type);
513 api_register_func('api/statuses/update','api_statuses_update', true);
516 function api_status_show(&$a, $type){
517 $user_info = api_get_user($a);
518 // get last public wall message
519 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
520 FROM `item`, `contact`,
521 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
522 WHERE `item`.`contact-id` = %d
523 AND `i`.`id` = `item`.`parent`
524 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
525 AND `type`!='activity'
526 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
527 ORDER BY `created` DESC
529 intval($user_info['id'])
532 if (count($lastwall)>0){
533 $lastwall = $lastwall[0];
535 $in_reply_to_status_id = '';
536 $in_reply_to_user_id = '';
537 $in_reply_to_screen_name = '';
538 if ($lastwall['parent']!=$lastwall['id']) {
539 $in_reply_to_status_id=$lastwall['parent'];
540 $in_reply_to_user_id = $lastwall['reply_uid'];
541 $in_reply_to_screen_name = $lastwall['reply_author'];
543 $status_info = array(
544 'created_at' => api_date($lastwall['created']),
545 'id' => $lastwall['contact-id'],
546 'text' => strip_tags(bbcode($lastwall['body'])),
547 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
548 'truncated' => false,
549 'in_reply_to_status_id' => $in_reply_to_status_id,
550 'in_reply_to_user_id' => $in_reply_to_user_id,
551 'favorited' => false,
552 'in_reply_to_screen_name' => $in_reply_to_screen_name,
554 'coordinates' => $lastwall['coord'],
555 'place' => $lastwall['location'],
558 $status_info['user'] = $user_info;
560 return api_apply_template("status", $type, array('$status' => $status_info));
569 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
570 * The author's most recent status will be returned inline.
571 * http://developer.twitter.com/doc/get/users/show
573 function api_users_show(&$a, $type){
574 $user_info = api_get_user($a);
575 // get last public wall message
576 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
577 FROM `item`, `contact`,
578 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
579 WHERE `item`.`contact-id` = %d
580 AND `i`.`id` = `item`.`parent`
581 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
582 AND `type`!='activity'
583 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
584 ORDER BY `created` DESC
586 intval($user_info['id'])
589 if (count($lastwall)>0){
590 $lastwall = $lastwall[0];
592 $in_reply_to_status_id = '';
593 $in_reply_to_user_id = '';
594 $in_reply_to_screen_name = '';
595 if ($lastwall['parent']!=$lastwall['id']) {
596 $in_reply_to_status_id=$lastwall['parent'];
597 $in_reply_to_user_id = $lastwall['reply_uid'];
598 $in_reply_to_screen_name = $lastwall['reply_author'];
600 $user_info['status'] = array(
601 'created_at' => api_date($lastwall['created']),
602 'id' => $lastwall['contact-id'],
603 'text' => strip_tags(bbcode($lastwall['body'])),
604 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
605 'truncated' => false,
606 'in_reply_to_status_id' => $in_reply_to_status_id,
607 'in_reply_to_user_id' => $in_reply_to_user_id,
608 'favorited' => false,
609 'in_reply_to_screen_name' => $in_reply_to_screen_name,
611 'coordinates' => $lastwall['coord'],
612 'place' => $lastwall['location'],
616 return api_apply_template("user", $type, array('$user' => $user_info));
619 api_register_func('api/users/show','api_users_show');
623 * http://developer.twitter.com/doc/get/statuses/home_timeline
625 * TODO: Optional parameters
626 * TODO: Add reply info
628 function api_statuses_home_timeline(&$a, $type){
629 if (local_user()===false) return false;
631 $user_info = api_get_user($a);
632 // get last newtork messages
636 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
637 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
638 if ($page<0) $page=0;
639 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
641 $start = $page*$count;
643 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
644 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
645 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
646 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
647 FROM `item`, `contact`
648 WHERE `item`.`uid` = %d
649 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
650 AND `contact`.`id` = `item`.`contact-id`
651 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
654 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
655 intval($user_info['uid']),
657 intval($start), intval($count)
660 $ret = api_format_items($r,$user_info);
663 $data = array('$statuses' => $ret);
667 $data = api_rss_extra($a, $data, $user_info);
670 return api_apply_template("timeline", $type, $data);
672 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
673 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
677 function api_statuses_user_timeline(&$a, $type){
678 if (local_user()===false) return false;
680 $user_info = api_get_user($a);
681 // get last newtork messages
684 logger("api_statuses_user_timeline: local_user: ". local_user() .
685 "\nuser_info: ".print_r($user_info, true) .
686 "\n_REQUEST: ".print_r($_REQUEST, true),
690 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
691 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
692 if ($page<0) $page=0;
693 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
695 $start = $page*$count;
697 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
699 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
700 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
701 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
702 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
703 FROM `item`, `contact`
704 WHERE `item`.`uid` = %d
705 AND `item`.`contact-id` = %d
706 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
707 AND `contact`.`id` = `item`.`contact-id`
708 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
711 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
712 intval(local_user()),
713 intval($user_info['id']),
715 intval($start), intval($count)
718 $ret = api_format_items($r,$user_info);
721 $data = array('$statuses' => $ret);
725 $data = api_rss_extra($a, $data, $user_info);
728 return api_apply_template("timeline", $type, $data);
731 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
734 function api_favorites(&$a, $type){
735 if (local_user()===false) return false;
737 $user_info = api_get_user($a);
738 // in friendika starred item are private
739 // return favorites only for self
740 logger('api_favorites: self:' . $user_info['self']);
742 if ($user_info['self']==0) {
748 $count = (x($_GET,'count')?$_GET['count']:20);
749 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
750 if ($page<0) $page=0;
752 $start = $page*$count;
754 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
755 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
756 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
757 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
758 FROM `item`, `contact`
759 WHERE `item`.`uid` = %d
760 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
761 AND `item`.`starred` = 1
762 AND `contact`.`id` = `item`.`contact-id`
763 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
765 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
766 intval($user_info['uid']),
767 intval($start), intval($count)
770 $ret = api_format_items($r,$user_info);
774 $data = array('$statuses' => $ret);
778 $data = api_rss_extra($a, $data, $user_info);
781 return api_apply_template("timeline", $type, $data);
784 api_register_func('api/favorites','api_favorites', true);
787 function api_format_items($r,$user_info) {
789 //logger('api_format_items: ' . print_r($r,true));
791 //logger('api_format_items: ' . print_r($user_info,true));
796 foreach($r as $item) {
797 localize_item($item);
798 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
800 'created_at'=> api_date($item['created']),
801 'published' => api_date($item['created']),
802 'updated' => api_date($item['edited']),
803 'id' => intval($item['id']),
804 'message_id' => $item['uri'],
805 'text' => strip_tags(bbcode($item['body'])),
806 'statusnet_html' => bbcode($item['body']),
807 'source' => (($item['app']) ? $item['app'] : 'web'),
808 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
809 'truncated' => False,
810 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
811 'in_reply_to_user_id' => '',
812 'favorited' => $item['starred'] ? true : false,
813 'in_reply_to_screen_name' => '',
815 'coordinates' => $item['coord'],
816 'place' => $item['location'],
817 'contributors' => '',
820 'user' => $status_user ,
821 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
822 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
823 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
824 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
832 function api_account_rate_limit_status(&$a,$type) {
835 'remaining_hits' => (string) 150,
836 'hourly_limit' => (string) 150,
837 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
838 'reset_time_in_seconds' => strtotime('now + 1 hour')
841 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
844 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
847 * https://dev.twitter.com/docs/api/1/get/statuses/friends
848 * This function is deprecated by Twitter
851 function api_statuses_f(&$a, $type, $qtype) {
852 if (local_user()===false) return false;
853 $user_info = api_get_user($a);
856 // friends and followers only for self
857 if ($user_info['self']==0){
861 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
862 /* this is to stop Hotot to load friends multiple times
863 * I'm not sure if I'm missing return something or
864 * is a bug in hotot. Workaround, meantime
868 return array('$users' => $ret);*/
872 if($qtype == 'friends')
873 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
874 if($qtype == 'followers')
875 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
877 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
883 $ret[] = api_get_user($a, $cid['id']);
887 return array('$users' => $ret);
890 function api_statuses_friends(&$a, $type){
891 $data = api_statuses_f($a,$type,"friends");
892 if ($data===false) return false;
893 return api_apply_template("friends", $type, $data);
895 function api_statuses_followers(&$a, $type){
896 $data = api_statuses_f($a,$type,"followers");
897 if ($data===false) return false;
898 return api_apply_template("friends", $type, $data);
900 api_register_func('api/statuses/friends','api_statuses_friends',true);
901 api_register_func('api/statuses/followers','api_statuses_followers',true);
908 function api_statusnet_config(&$a,$type) {
909 $name = $a->config['sitename'];
910 $server = $a->get_hostname();
911 $logo = $a->get_baseurl() . '/images/friendika-64.png';
912 $email = $a->config['admin_email'];
913 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
914 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
915 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
916 if($a->config['api_import_size'])
917 $texlimit = string($a->config['api_import_size']);
918 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
919 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
922 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
923 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
924 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
925 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
926 'shorturllength' => '30'
930 return api_apply_template('config', $type, array('$config' => $config));
933 api_register_func('api/statusnet/config','api_statusnet_config',false);
935 function api_statusnet_version(&$a,$type) {
939 if($type === 'xml') {
940 header("Content-type: application/xml");
941 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
944 elseif($type === 'json') {
945 header("Content-type: application/json");
950 api_register_func('api/statusnet/version','api_statusnet_version',false);
953 function api_ff_ids(&$a,$type,$qtype) {
957 if($qtype == 'friends')
958 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
959 if($qtype == 'followers')
960 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
963 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
968 if($type === 'xml') {
969 header("Content-type: application/xml");
970 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
972 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
973 echo '</ids>' . "\r\n";
976 elseif($type === 'json') {
978 header("Content-type: application/json");
979 foreach($r as $rr) $ret[] = $rr['id'];
980 echo json_encode($ret);
986 function api_friends_ids(&$a,$type) {
987 api_ff_ids($a,$type,'friends');
989 function api_followers_ids(&$a,$type) {
990 api_ff_ids($a,$type,'followers');
992 api_register_func('api/friends/ids','api_friends_ids',true);
993 api_register_func('api/followers/ids','api_followers_ids',true);
996 function api_direct_messages_new(&$a, $type) {
997 if (local_user()===false) return false;
999 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1001 $sender = api_get_user($a);
1003 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1004 intval(local_user()),
1005 dbesc($_POST['screen_name']));
1007 $recipient = api_get_user($a, $r[0]['id']);
1010 require_once("include/message.php");
1011 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1012 $id = send_message($recipient['id'], $_POST['text'], $sub);
1016 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1019 'id' => $item['id'],
1020 'created_at'=> api_date($item['created']),
1021 'sender_id'=> $sender['id'] ,
1022 'sender_screen_name'=> $sender['screen_name'],
1024 'recipient_id'=> $recipient['id'],
1025 'recipient_screen_name'=> $recipient['screen_name'],
1026 'recipient'=> $recipient,
1028 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1033 $ret = array("error"=>$id);
1036 $data = Array('$messages'=>$ret);
1041 $data = api_rss_extra($a, $data, $user_info);
1044 return api_apply_template("direct_messages", $type, $data);
1047 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1049 function api_direct_messages_box(&$a, $type, $box) {
1050 if (local_user()===false) return false;
1052 $user_info = api_get_user($a);
1055 $count = (x($_GET,'count')?$_GET['count']:20);
1056 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1057 if ($page<0) $page=0;
1059 $start = $page*$count;
1062 if ($box=="sentbox") {
1063 $sql_extra = "`from-url`='%s'";
1065 $sql_extra = "`from-url`!='%s'";
1068 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1069 intval(local_user()),
1070 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1071 intval($start), intval($count)
1075 foreach($r as $item){
1078 $recipient = $user_info;
1079 $sender = api_get_user($a,$item['contact-id']);
1082 $recipient = api_get_user($a,$item['contact-id']);
1083 $sender = $user_info;
1088 'id' => $item['id'],
1089 'created_at'=> api_date($item['created']),
1090 'sender_id'=> $sender['id'] ,
1091 'sender_screen_name'=> $sender['screen_name'],
1093 'recipient_id'=> $recipient['id'],
1094 'recipient_screen_name'=> $recipient['screen_name'],
1095 'recipient'=> $recipient,
1097 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1104 $data = array('$messages' => $ret);
1108 $data = api_rss_extra($a, $data, $user_info);
1111 return api_apply_template("direct_messages", $type, $data);
1115 function api_direct_messages_sentbox(&$a, $type){
1116 return api_direct_messages_box($a, $type, "sentbox");
1118 function api_direct_messages_inbox(&$a, $type){
1119 return api_direct_messages_box($a, $type, "inbox");
1121 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1122 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1126 function api_oauth_request_token(&$a, $type){
1128 $oauth = new FKOAuth1();
1129 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1130 }catch(Exception $e){
1131 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1136 function api_oauth_access_token(&$a, $type){
1138 $oauth = new FKOAuth1();
1139 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1140 }catch(Exception $e){
1141 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1147 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1148 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);