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,
30 function api_login(&$a){
33 $oauth = new FKOAuth1();
34 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
35 if (!is_null($token)){
36 $oauth->loginUser($token->uid);
37 call_hooks('logged_in', $a->user);
40 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
42 logger(__file__.__line__.__function__."\n".$e);
43 //die(__file__.__line__.__function__."<pre>".$e); die();
48 // workaround for HTTP-auth in CGI mode
49 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
50 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
51 if(strlen($userpass)) {
52 list($name, $password) = explode(':', $userpass);
53 $_SERVER['PHP_AUTH_USER'] = $name;
54 $_SERVER['PHP_AUTH_PW'] = $password;
58 if (!isset($_SERVER['PHP_AUTH_USER'])) {
59 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
60 header('WWW-Authenticate: Basic realm="Friendica"');
61 header('HTTP/1.0 401 Unauthorized');
62 die('This api requires login');
65 $user = $_SERVER['PHP_AUTH_USER'];
66 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
70 * next code from mod/auth.php. needs better solution
73 // process normal login request
75 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
76 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
84 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
85 header('WWW-Authenticate: Basic realm="Friendika"');
86 header('HTTP/1.0 401 Unauthorized');
87 die('This api requires login');
90 require_once('include/security.php');
91 authenticate_success($record);
93 call_hooks('logged_in', $a->user);
97 /**************************
98 * MAIN API ENTRY POINT *
99 **************************/
100 function api_call(&$a){
101 GLOBAL $API, $called_api;
102 foreach ($API as $p=>$info){
103 if (strpos($a->query_string, $p)===0){
104 $called_api= explode("/",$p);
105 //unset($_SERVER['PHP_AUTH_USER']);
106 if ($info['auth']===true && local_user()===false) {
110 load_contact_links(local_user());
112 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
113 logger('API parameters: ' . print_r($_REQUEST,true));
115 if (strpos($a->query_string, ".xml")>0) $type="xml";
116 if (strpos($a->query_string, ".json")>0) $type="json";
117 if (strpos($a->query_string, ".rss")>0) $type="rss";
118 if (strpos($a->query_string, ".atom")>0) $type="atom";
120 $r = call_user_func($info['func'], $a, $type);
121 if ($r===false) return;
125 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
126 header ("Content-Type: text/xml");
127 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
130 //header ("Content-Type: application/json");
132 return json_encode($rr);
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();
147 $r = '<status><error>not implemented</error></status>';
150 header ("Content-Type: text/xml");
151 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
154 header ("Content-Type: application/json");
155 return json_encode(array('error' => 'not implemented'));
158 header ("Content-Type: application/rss+xml");
159 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
162 header ("Content-Type: application/atom+xml");
163 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
172 function api_rss_extra(&$a, $arr, $user_info){
173 if (is_null($user_info)) $user_info = api_get_user($a);
174 $arr['$user'] = $user_info;
175 $arr['$rss'] = array(
176 'alternate' => $user_info['url'],
177 'self' => $a->get_baseurl(). "/". $a->query_string,
178 'base' => $a->get_baseurl(),
179 'updated' => api_date(null),
180 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
181 'language' => $user_info['language'],
182 'logo' => $a->get_baseurl()."/images/friendika-32.png",
189 * Returns user info array.
191 function api_get_user(&$a, $contact_id = Null){
197 if(!is_null($contact_id)){
199 $extra_query = "AND `contact`.`id` = %d ";
202 if(is_null($user) && x($_GET, 'user_id')) {
203 $user = intval($_GET['user_id']);
204 $extra_query = "AND `contact`.`id` = %d ";
206 if(is_null($user) && x($_GET, 'screen_name')) {
207 $user = dbesc($_GET['screen_name']);
208 $extra_query = "AND `contact`.`nick` = '%s' ";
209 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
213 if (is_null($user) && $a->argc > (count($called_api)-1)){
214 $argid = count($called_api);
215 list($user, $null) = explode(".",$a->argv[$argid]);
216 if(is_numeric($user)){
217 $user = intval($user);
218 $extra_query = "AND `contact`.`id` = %d ";
220 $user = dbesc($user);
221 $extra_query = "AND `contact`.`nick` = '%s' ";
222 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
227 if (local_user()===false) {
228 api_login($a); return False;
230 $user = $_SESSION['uid'];
231 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
236 logger('api_user: ' . $extra_query . ' ' , $user);
238 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
243 if (count($uinfo)==0) {
247 if($uinfo[0]['self']) {
248 $usr = q("select * from user where uid = %d limit 1",
251 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
255 // count public wall messages
256 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
259 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
260 intval($uinfo[0]['uid'])
262 $countitms = $r[0]['count'];
265 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
266 WHERE `contact-id` = %d
267 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
268 intval($uinfo[0]['id'])
270 $countitms = $r[0]['count'];
274 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
275 WHERE `uid` = %d AND `rel` IN ( %d, %d )
276 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
277 intval($uinfo[0]['uid']),
278 intval(CONTACT_IS_SHARING),
279 intval(CONTACT_IS_FRIEND)
281 $countfriends = $r[0]['count'];
283 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
284 WHERE `uid` = %d AND `rel` IN ( %d, %d )
285 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
286 intval($uinfo[0]['uid']),
287 intval(CONTACT_IS_FOLLOWER),
288 intval(CONTACT_IS_FRIEND)
290 $countfollowers = $r[0]['count'];
292 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
293 intval($uinfo[0]['uid'])
295 $starred = $r[0]['count'];
298 if(! $uinfo[0]['self']) {
305 'self' => intval($uinfo[0]['self']),
306 'uid' => intval($uinfo[0]['uid']),
307 'id' => intval($uinfo[0]['cid']),
308 'name' => $uinfo[0]['name'],
309 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
310 'location' => ($usr) ? $usr[0]['default-location'] : '',
311 'profile_image_url' => $uinfo[0]['micro'],
312 'url' => $uinfo[0]['url'],
313 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
314 'protected' => false,
315 'friends_count' => intval($countfriends),
316 'created_at' => api_date($uinfo[0]['name-date']),
317 'utc_offset' => "+00:00",
318 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
319 'geo_enabled' => false,
320 'statuses_count' => intval($countitms), #XXX: fix me
321 'lang' => 'en', #XXX: fix me
322 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
323 'followers_count' => intval($countfollowers),
324 'favourites_count' => intval($starred),
325 'contributors_enabled' => false,
326 'follow_request_sent' => true,
327 'profile_background_color' => 'cfe8f6',
328 'profile_text_color' => '000000',
329 'profile_link_color' => 'FF8500',
330 'profile_sidebar_fill_color' =>'AD0066',
331 'profile_sidebar_border_color' => 'AD0066',
332 'profile_background_image_url' => '',
333 'profile_background_tile' => false,
334 'profile_use_background_image' => false,
335 'notifications' => false,
336 'following' => '', #XXX: fix me
337 'verified' => true, #XXX: fix me
345 function api_item_get_user(&$a, $item) {
346 // The author is our direct contact, in a conversation with us.
347 if(link_compare($item['url'],$item['author-link'])) {
348 return api_get_user($a,$item['cid']);
351 // The author may be a contact of ours, but is replying to somebody else.
352 // Figure out if we know him/her.
353 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
354 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
355 return api_get_user($a,$a->contacts[$normalised]['id']);
357 // We don't know this person directly.
359 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
360 $name=str_replace(")","",$name);
366 'screen_name' => $nick,
367 'location' => '', //$uinfo[0]['default-location'],
368 'profile_image_url' => $item['author-avatar'],
369 'url' => $item['author-link'],
371 'protected' => false, #
372 'friends_count' => 0,
374 'utc_offset' => 0, #XXX: fix me
375 'time_zone' => '', //$uinfo[0]['timezone'],
376 'geo_enabled' => false,
377 'statuses_count' => 0,
378 'lang' => 'en', #XXX: fix me
380 'followers_count' => 0,
381 'favourites_count' => 0,
382 'contributors_enabled' => false,
383 'follow_request_sent' => false,
384 'profile_background_color' => 'cfe8f6',
385 'profile_text_color' => '000000',
386 'profile_link_color' => 'FF8500',
387 'profile_sidebar_fill_color' =>'AD0066',
388 'profile_sidebar_border_color' => 'AD0066',
389 'profile_background_image_url' => '',
390 'profile_background_tile' => false,
391 'profile_use_background_image' => false,
392 'notifications' => false,
393 'verified' => true, #XXX: fix me
394 'followers' => '', #XXX: fix me
403 * load api $templatename for $type and replace $data array
405 function api_apply_template($templatename, $type, $data){
413 $data = array_xmlify($data);
414 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
415 $ret = replace_macros($tpl, $data);
429 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
430 * returns a 401 status code and an error message if not.
431 * http://developer.twitter.com/doc/get/account/verify_credentials
433 function api_account_verify_credentials(&$a, $type){
434 if (local_user()===false) return false;
435 $user_info = api_get_user($a);
437 return api_apply_template("user", $type, array('$user' => $user_info));
440 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
444 * get data from $_POST or $_GET
446 function requestdata($k){
447 if (isset($_POST[$k])){
450 if (isset($_GET[$k])){
456 // TODO - media uploads
457 function api_statuses_update(&$a, $type) {
458 if (local_user()===false) {
459 logger('api_statuses_update: no user');
462 $user_info = api_get_user($a);
464 // convert $_POST array items to the form we use for web posts.
466 // logger('api_post: ' . print_r($_POST,true));
468 if(requestdata('htmlstatus')) {
469 require_once('library/HTMLPurifier.auto.php');
470 require_once('include/html2bbcode.php');
472 $txt = requestdata('htmlstatus');
473 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
475 $txt = html2bb_video($txt);
477 $config = HTMLPurifier_Config::createDefault();
478 $config->set('Cache.DefinitionImpl', null);
481 $purifier = new HTMLPurifier($config);
482 $txt = $purifier->purify($txt);
484 $_REQUEST['body'] = html2bbcode($txt);
489 $_REQUEST['body'] = urldecode(requestdata('status'));
491 $parent = requestdata('in_reply_to_status_id');
492 if(ctype_digit($parent))
493 $_REQUEST['parent'] = $parent;
495 $_REQUEST['parent_uri'] = $parent;
497 if(requestdata('lat') && requestdata('long'))
498 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
499 $_REQUEST['profile_uid'] = local_user();
500 if(requestdata('parent'))
501 $_REQUEST['type'] = 'net-comment';
503 $_REQUEST['type'] = 'wall';
505 // set this so that the item_post() function is quiet and doesn't redirect or emit json
507 $_REQUEST['api_source'] = true;
509 // call out normal post function
511 require_once('mod/item.php');
514 // this should output the last post (the one we just posted).
515 return api_status_show($a,$type);
517 api_register_func('api/statuses/update','api_statuses_update', true);
520 function api_status_show(&$a, $type){
521 $user_info = api_get_user($a);
522 // get last public wall message
523 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
524 FROM `item`, `contact`,
525 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
526 WHERE `item`.`contact-id` = %d
527 AND `i`.`id` = `item`.`parent`
528 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
529 AND `type`!='activity'
530 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
531 ORDER BY `created` DESC
533 intval($user_info['id'])
536 if (count($lastwall)>0){
537 $lastwall = $lastwall[0];
539 $in_reply_to_status_id = '';
540 $in_reply_to_user_id = '';
541 $in_reply_to_screen_name = '';
542 if ($lastwall['parent']!=$lastwall['id']) {
543 $in_reply_to_status_id=$lastwall['parent'];
544 $in_reply_to_user_id = $lastwall['reply_uid'];
545 $in_reply_to_screen_name = $lastwall['reply_author'];
547 $status_info = array(
548 'created_at' => api_date($lastwall['created']),
549 'id' => $lastwall['contact-id'],
550 'text' => strip_tags(bbcode($lastwall['body'])),
551 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
552 'truncated' => false,
553 'in_reply_to_status_id' => $in_reply_to_status_id,
554 'in_reply_to_user_id' => $in_reply_to_user_id,
555 'favorited' => false,
556 'in_reply_to_screen_name' => $in_reply_to_screen_name,
558 'coordinates' => $lastwall['coord'],
559 'place' => $lastwall['location'],
562 $status_info['user'] = $user_info;
564 return api_apply_template("status", $type, array('$status' => $status_info));
573 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
574 * The author's most recent status will be returned inline.
575 * http://developer.twitter.com/doc/get/users/show
577 function api_users_show(&$a, $type){
578 $user_info = api_get_user($a);
579 // get last public wall message
580 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
581 FROM `item`, `contact`,
582 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
583 WHERE `item`.`contact-id` = %d
584 AND `i`.`id` = `item`.`parent`
585 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
586 AND `type`!='activity'
587 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
588 ORDER BY `created` DESC
590 intval($user_info['id'])
593 if (count($lastwall)>0){
594 $lastwall = $lastwall[0];
596 $in_reply_to_status_id = '';
597 $in_reply_to_user_id = '';
598 $in_reply_to_screen_name = '';
599 if ($lastwall['parent']!=$lastwall['id']) {
600 $in_reply_to_status_id=$lastwall['parent'];
601 $in_reply_to_user_id = $lastwall['reply_uid'];
602 $in_reply_to_screen_name = $lastwall['reply_author'];
604 $user_info['status'] = array(
605 'created_at' => api_date($lastwall['created']),
606 'id' => $lastwall['contact-id'],
607 'text' => strip_tags(bbcode($lastwall['body'])),
608 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
609 'truncated' => false,
610 'in_reply_to_status_id' => $in_reply_to_status_id,
611 'in_reply_to_user_id' => $in_reply_to_user_id,
612 'favorited' => false,
613 'in_reply_to_screen_name' => $in_reply_to_screen_name,
615 'coordinates' => $lastwall['coord'],
616 'place' => $lastwall['location'],
620 return api_apply_template("user", $type, array('$user' => $user_info));
623 api_register_func('api/users/show','api_users_show');
627 * http://developer.twitter.com/doc/get/statuses/home_timeline
629 * TODO: Optional parameters
630 * TODO: Add reply info
632 function api_statuses_home_timeline(&$a, $type){
633 if (local_user()===false) return false;
635 $user_info = api_get_user($a);
636 // get last newtork messages
640 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
641 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
642 if ($page<0) $page=0;
643 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
645 $start = $page*$count;
647 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
648 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
649 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
650 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
651 FROM `item`, `contact`
652 WHERE `item`.`uid` = %d
653 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
654 AND `contact`.`id` = `item`.`contact-id`
655 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
658 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
659 intval($user_info['uid']),
661 intval($start), intval($count)
664 $ret = api_format_items($r,$user_info);
667 $data = array('$statuses' => $ret);
671 $data = api_rss_extra($a, $data, $user_info);
674 return api_apply_template("timeline", $type, $data);
676 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
677 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
681 function api_statuses_user_timeline(&$a, $type){
682 if (local_user()===false) return false;
684 $user_info = api_get_user($a);
685 // get last newtork messages
688 logger("api_statuses_user_timeline: local_user: ". local_user() .
689 "\nuser_info: ".print_r($user_info, true) .
690 "\n_REQUEST: ".print_r($_REQUEST, true),
694 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
695 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
696 if ($page<0) $page=0;
697 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
699 $start = $page*$count;
701 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
703 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
704 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
705 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
706 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
707 FROM `item`, `contact`
708 WHERE `item`.`uid` = %d
709 AND `item`.`contact-id` = %d
710 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
711 AND `contact`.`id` = `item`.`contact-id`
712 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
715 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
716 intval(local_user()),
717 intval($user_info['id']),
719 intval($start), intval($count)
722 $ret = api_format_items($r,$user_info);
725 $data = array('$statuses' => $ret);
729 $data = api_rss_extra($a, $data, $user_info);
732 return api_apply_template("timeline", $type, $data);
735 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
738 function api_favorites(&$a, $type){
739 if (local_user()===false) return false;
741 $user_info = api_get_user($a);
742 // in friendika starred item are private
743 // return favorites only for self
744 logger('api_favorites: self:' . $user_info['self']);
746 if ($user_info['self']==0) {
752 $count = (x($_GET,'count')?$_GET['count']:20);
753 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
754 if ($page<0) $page=0;
756 $start = $page*$count;
758 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
759 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
760 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
761 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
762 FROM `item`, `contact`
763 WHERE `item`.`uid` = %d
764 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
765 AND `item`.`starred` = 1
766 AND `contact`.`id` = `item`.`contact-id`
767 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
769 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
770 intval($user_info['uid']),
771 intval($start), intval($count)
774 $ret = api_format_items($r,$user_info);
778 $data = array('$statuses' => $ret);
782 $data = api_rss_extra($a, $data, $user_info);
785 return api_apply_template("timeline", $type, $data);
788 api_register_func('api/favorites','api_favorites', true);
791 function api_format_items($r,$user_info) {
793 //logger('api_format_items: ' . print_r($r,true));
795 //logger('api_format_items: ' . print_r($user_info,true));
800 foreach($r as $item) {
801 localize_item($item);
802 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
804 'created_at'=> api_date($item['created']),
805 'published' => api_date($item['created']),
806 'updated' => api_date($item['edited']),
807 'id' => intval($item['id']),
808 'message_id' => $item['uri'],
809 'text' => strip_tags(bbcode($item['body'])),
810 'statusnet_html' => bbcode($item['body']),
811 'source' => (($item['app']) ? $item['app'] : 'web'),
812 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
813 'truncated' => False,
814 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
815 'in_reply_to_user_id' => '',
816 'favorited' => $item['starred'] ? true : false,
817 'in_reply_to_screen_name' => '',
819 'coordinates' => $item['coord'],
820 'place' => $item['location'],
821 'contributors' => '',
824 'user' => $status_user ,
825 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
826 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
827 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
828 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
836 function api_account_rate_limit_status(&$a,$type) {
839 'remaining_hits' => (string) 150,
840 'hourly_limit' => (string) 150,
841 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
842 'reset_time_in_seconds' => strtotime('now + 1 hour')
845 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
848 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
851 * https://dev.twitter.com/docs/api/1/get/statuses/friends
852 * This function is deprecated by Twitter
855 function api_statuses_f(&$a, $type, $qtype) {
856 if (local_user()===false) return false;
857 $user_info = api_get_user($a);
860 // friends and followers only for self
861 if ($user_info['self']==0){
865 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
866 /* this is to stop Hotot to load friends multiple times
867 * I'm not sure if I'm missing return something or
868 * is a bug in hotot. Workaround, meantime
872 return array('$users' => $ret);*/
876 if($qtype == 'friends')
877 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
878 if($qtype == 'followers')
879 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
881 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
887 $ret[] = api_get_user($a, $cid['id']);
891 return array('$users' => $ret);
894 function api_statuses_friends(&$a, $type){
895 $data = api_statuses_f($a,$type,"friends");
896 if ($data===false) return false;
897 return api_apply_template("friends", $type, $data);
899 function api_statuses_followers(&$a, $type){
900 $data = api_statuses_f($a,$type,"followers");
901 if ($data===false) return false;
902 return api_apply_template("friends", $type, $data);
904 api_register_func('api/statuses/friends','api_statuses_friends',true);
905 api_register_func('api/statuses/followers','api_statuses_followers',true);
912 function api_statusnet_config(&$a,$type) {
913 $name = $a->config['sitename'];
914 $server = $a->get_hostname();
915 $logo = $a->get_baseurl() . '/images/friendika-64.png';
916 $email = $a->config['admin_email'];
917 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
918 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
919 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
920 if($a->config['api_import_size'])
921 $texlimit = string($a->config['api_import_size']);
922 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
923 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
926 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
927 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
928 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
929 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
930 'shorturllength' => '30'
934 return api_apply_template('config', $type, array('$config' => $config));
937 api_register_func('api/statusnet/config','api_statusnet_config',false);
939 function api_statusnet_version(&$a,$type) {
943 if($type === 'xml') {
944 header("Content-type: application/xml");
945 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
948 elseif($type === 'json') {
949 header("Content-type: application/json");
954 api_register_func('api/statusnet/version','api_statusnet_version',false);
957 function api_ff_ids(&$a,$type,$qtype) {
961 if($qtype == 'friends')
962 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
963 if($qtype == 'followers')
964 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
967 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
972 if($type === 'xml') {
973 header("Content-type: application/xml");
974 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
976 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
977 echo '</ids>' . "\r\n";
980 elseif($type === 'json') {
982 header("Content-type: application/json");
983 foreach($r as $rr) $ret[] = $rr['id'];
984 echo json_encode($ret);
990 function api_friends_ids(&$a,$type) {
991 api_ff_ids($a,$type,'friends');
993 function api_followers_ids(&$a,$type) {
994 api_ff_ids($a,$type,'followers');
996 api_register_func('api/friends/ids','api_friends_ids',true);
997 api_register_func('api/followers/ids','api_followers_ids',true);
1000 function api_direct_messages_new(&$a, $type) {
1001 if (local_user()===false) return false;
1003 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1005 $sender = api_get_user($a);
1007 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1008 intval(local_user()),
1009 dbesc($_POST['screen_name']));
1011 $recipient = api_get_user($a, $r[0]['id']);
1014 require_once("include/message.php");
1015 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1016 $id = send_message($recipient['id'], $_POST['text'], $sub);
1020 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1023 'id' => $item['id'],
1024 'created_at'=> api_date($item['created']),
1025 'sender_id'=> $sender['id'] ,
1026 'sender_screen_name'=> $sender['screen_name'],
1028 'recipient_id'=> $recipient['id'],
1029 'recipient_screen_name'=> $recipient['screen_name'],
1030 'recipient'=> $recipient,
1032 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1037 $ret = array("error"=>$id);
1040 $data = Array('$messages'=>$ret);
1045 $data = api_rss_extra($a, $data, $user_info);
1048 return api_apply_template("direct_messages", $type, $data);
1051 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1053 function api_direct_messages_box(&$a, $type, $box) {
1054 if (local_user()===false) return false;
1056 $user_info = api_get_user($a);
1059 $count = (x($_GET,'count')?$_GET['count']:20);
1060 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1061 if ($page<0) $page=0;
1063 $start = $page*$count;
1066 if ($box=="sentbox") {
1067 $sql_extra = "`from-url`='%s'";
1069 $sql_extra = "`from-url`!='%s'";
1072 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1073 intval(local_user()),
1074 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1075 intval($start), intval($count)
1079 foreach($r as $item){
1082 $recipient = $user_info;
1083 $sender = api_get_user($a,$item['contact-id']);
1086 $recipient = api_get_user($a,$item['contact-id']);
1087 $sender = $user_info;
1092 'id' => $item['id'],
1093 'created_at'=> api_date($item['created']),
1094 'sender_id'=> $sender['id'] ,
1095 'sender_screen_name'=> $sender['screen_name'],
1097 'recipient_id'=> $recipient['id'],
1098 'recipient_screen_name'=> $recipient['screen_name'],
1099 'recipient'=> $recipient,
1101 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1108 $data = array('$messages' => $ret);
1112 $data = api_rss_extra($a, $data, $user_info);
1115 return api_apply_template("direct_messages", $type, $data);
1119 function api_direct_messages_sentbox(&$a, $type){
1120 return api_direct_messages_box($a, $type, "sentbox");
1122 function api_direct_messages_inbox(&$a, $type){
1123 return api_direct_messages_box($a, $type, "inbox");
1125 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1126 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1130 function api_oauth_request_token(&$a, $type){
1132 $oauth = new FKOAuth1();
1133 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1134 }catch(Exception $e){
1135 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1140 function api_oauth_access_token(&$a, $type){
1142 $oauth = new FKOAuth1();
1143 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1144 }catch(Exception $e){
1145 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1151 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1152 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);