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;
106 foreach ($API as $p=>$info){
107 if (strpos($a->query_string, $p)===0){
108 $called_api= explode("/",$p);
109 //unset($_SERVER['PHP_AUTH_USER']);
110 if ($info['auth']===true && local_user()===false) {
114 load_contact_links(local_user());
116 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
117 logger('API parameters: ' . print_r($_REQUEST,true));
119 if (strpos($a->query_string, ".xml")>0) $type="xml";
120 if (strpos($a->query_string, ".json")>0) $type="json";
121 if (strpos($a->query_string, ".rss")>0) $type="rss";
122 if (strpos($a->query_string, ".atom")>0) $type="atom";
124 $r = call_user_func($info['func'], $a, $type);
125 if ($r===false) return;
129 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
130 header ("Content-Type: text/xml");
131 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
134 //header ("Content-Type: application/json");
136 return json_encode($rr);
139 header ("Content-Type: application/rss+xml");
140 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
143 header ("Content-Type: application/atom+xml");
144 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
148 //echo "<pre>"; var_dump($r); die();
151 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
152 $r = '<status><error>not implemented</error></status>';
155 header ("Content-Type: text/xml");
156 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
159 header ("Content-Type: application/json");
160 return json_encode(array('error' => 'not implemented'));
163 header ("Content-Type: application/rss+xml");
164 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
167 header ("Content-Type: application/atom+xml");
168 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
176 function api_rss_extra(&$a, $arr, $user_info){
177 if (is_null($user_info)) $user_info = api_get_user($a);
178 $arr['$user'] = $user_info;
179 $arr['$rss'] = array(
180 'alternate' => $user_info['url'],
181 'self' => $a->get_baseurl(). "/". $a->query_string,
182 'base' => $a->get_baseurl(),
183 'updated' => api_date(null),
184 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
185 'language' => $user_info['language'],
186 'logo' => $a->get_baseurl()."/images/friendika-32.png",
193 * Returns user info array.
195 function api_get_user(&$a, $contact_id = Null){
201 if(!is_null($contact_id)){
203 $extra_query = "AND `contact`.`id` = %d ";
206 if(is_null($user) && x($_GET, 'user_id')) {
207 $user = intval($_GET['user_id']);
208 $extra_query = "AND `contact`.`id` = %d ";
210 if(is_null($user) && x($_GET, 'screen_name')) {
211 $user = dbesc($_GET['screen_name']);
212 $extra_query = "AND `contact`.`nick` = '%s' ";
213 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
217 if (is_null($user) && $a->argc > (count($called_api)-1)){
218 $argid = count($called_api);
219 list($user, $null) = explode(".",$a->argv[$argid]);
220 if(is_numeric($user)){
221 $user = intval($user);
222 $extra_query = "AND `contact`.`id` = %d ";
224 $user = dbesc($user);
225 $extra_query = "AND `contact`.`nick` = '%s' ";
226 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
231 if (local_user()===false) {
232 api_login($a); return False;
234 $user = $_SESSION['uid'];
235 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
240 logger('api_user: ' . $extra_query . ' ' , $user);
242 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
247 if (count($uinfo)==0) {
251 if($uinfo[0]['self']) {
252 $usr = q("select * from user where uid = %d limit 1",
255 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
259 // count public wall messages
260 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
263 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
264 intval($uinfo[0]['uid'])
266 $countitms = $r[0]['count'];
269 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
270 WHERE `contact-id` = %d
271 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
272 intval($uinfo[0]['id'])
274 $countitms = $r[0]['count'];
278 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
279 WHERE `uid` = %d AND `rel` IN ( %d, %d )
280 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
281 intval($uinfo[0]['uid']),
282 intval(CONTACT_IS_SHARING),
283 intval(CONTACT_IS_FRIEND)
285 $countfriends = $r[0]['count'];
287 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
288 WHERE `uid` = %d AND `rel` IN ( %d, %d )
289 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
290 intval($uinfo[0]['uid']),
291 intval(CONTACT_IS_FOLLOWER),
292 intval(CONTACT_IS_FRIEND)
294 $countfollowers = $r[0]['count'];
296 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
297 intval($uinfo[0]['uid'])
299 $starred = $r[0]['count'];
302 if(! $uinfo[0]['self']) {
309 'self' => intval($uinfo[0]['self']),
310 'uid' => intval($uinfo[0]['uid']),
311 'id' => intval($uinfo[0]['cid']),
312 'name' => $uinfo[0]['name'],
313 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
314 'location' => ($usr) ? $usr[0]['default-location'] : '',
315 'profile_image_url' => $uinfo[0]['micro'],
316 'url' => $uinfo[0]['url'],
317 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
318 'protected' => false,
319 'friends_count' => intval($countfriends),
320 'created_at' => api_date($uinfo[0]['name-date']),
321 'utc_offset' => "+00:00",
322 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
323 'geo_enabled' => false,
324 'statuses_count' => intval($countitms), #XXX: fix me
325 'lang' => 'en', #XXX: fix me
326 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
327 'followers_count' => intval($countfollowers),
328 'favourites_count' => intval($starred),
329 'contributors_enabled' => false,
330 'follow_request_sent' => true,
331 'profile_background_color' => 'cfe8f6',
332 'profile_text_color' => '000000',
333 'profile_link_color' => 'FF8500',
334 'profile_sidebar_fill_color' =>'AD0066',
335 'profile_sidebar_border_color' => 'AD0066',
336 'profile_background_image_url' => '',
337 'profile_background_tile' => false,
338 'profile_use_background_image' => false,
339 'notifications' => false,
340 'following' => '', #XXX: fix me
341 'verified' => true, #XXX: fix me
349 function api_item_get_user(&$a, $item) {
350 // The author is our direct contact, in a conversation with us.
351 if(link_compare($item['url'],$item['author-link'])) {
352 return api_get_user($a,$item['cid']);
355 // The author may be a contact of ours, but is replying to somebody else.
356 // Figure out if we know him/her.
357 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
358 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
359 return api_get_user($a,$a->contacts[$normalised]['id']);
361 // We don't know this person directly.
363 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
364 $name=str_replace(")","",$name);
370 'screen_name' => $nick,
371 'location' => '', //$uinfo[0]['default-location'],
372 'profile_image_url' => $item['author-avatar'],
373 'url' => $item['author-link'],
375 'protected' => false, #
376 'friends_count' => 0,
378 'utc_offset' => 0, #XXX: fix me
379 'time_zone' => '', //$uinfo[0]['timezone'],
380 'geo_enabled' => false,
381 'statuses_count' => 0,
382 'lang' => 'en', #XXX: fix me
384 'followers_count' => 0,
385 'favourites_count' => 0,
386 'contributors_enabled' => false,
387 'follow_request_sent' => false,
388 'profile_background_color' => 'cfe8f6',
389 'profile_text_color' => '000000',
390 'profile_link_color' => 'FF8500',
391 'profile_sidebar_fill_color' =>'AD0066',
392 'profile_sidebar_border_color' => 'AD0066',
393 'profile_background_image_url' => '',
394 'profile_background_tile' => false,
395 'profile_use_background_image' => false,
396 'notifications' => false,
397 'verified' => true, #XXX: fix me
398 'followers' => '', #XXX: fix me
407 * load api $templatename for $type and replace $data array
409 function api_apply_template($templatename, $type, $data){
417 $data = array_xmlify($data);
418 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
419 $ret = replace_macros($tpl, $data);
433 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
434 * returns a 401 status code and an error message if not.
435 * http://developer.twitter.com/doc/get/account/verify_credentials
437 function api_account_verify_credentials(&$a, $type){
438 if (local_user()===false) return false;
439 $user_info = api_get_user($a);
441 return api_apply_template("user", $type, array('$user' => $user_info));
444 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
448 * get data from $_POST or $_GET
450 function requestdata($k){
451 if (isset($_POST[$k])){
454 if (isset($_GET[$k])){
460 // TODO - media uploads
461 function api_statuses_update(&$a, $type) {
462 if (local_user()===false) {
463 logger('api_statuses_update: no user');
466 $user_info = api_get_user($a);
468 // convert $_POST array items to the form we use for web posts.
470 // logger('api_post: ' . print_r($_POST,true));
472 if(requestdata('htmlstatus')) {
473 require_once('library/HTMLPurifier.auto.php');
474 require_once('include/html2bbcode.php');
476 $txt = requestdata('htmlstatus');
477 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
479 $txt = html2bb_video($txt);
481 $config = HTMLPurifier_Config::createDefault();
482 $config->set('Cache.DefinitionImpl', null);
485 $purifier = new HTMLPurifier($config);
486 $txt = $purifier->purify($txt);
488 $_REQUEST['body'] = html2bbcode($txt);
493 $_REQUEST['body'] = urldecode(requestdata('status'));
495 $parent = requestdata('in_reply_to_status_id');
496 if(ctype_digit($parent))
497 $_REQUEST['parent'] = $parent;
499 $_REQUEST['parent_uri'] = $parent;
501 if(requestdata('lat') && requestdata('long'))
502 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
503 $_REQUEST['profile_uid'] = local_user();
504 if(requestdata('parent'))
505 $_REQUEST['type'] = 'net-comment';
507 $_REQUEST['type'] = 'wall';
509 // set this so that the item_post() function is quiet and doesn't redirect or emit json
511 $_REQUEST['api_source'] = true;
513 // call out normal post function
515 require_once('mod/item.php');
518 // this should output the last post (the one we just posted).
519 return api_status_show($a,$type);
521 api_register_func('api/statuses/update','api_statuses_update', true);
524 function api_status_show(&$a, $type){
525 $user_info = api_get_user($a);
526 // get last public wall message
527 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
528 FROM `item`, `contact`,
529 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
530 WHERE `item`.`contact-id` = %d
531 AND `i`.`id` = `item`.`parent`
532 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
533 AND `type`!='activity'
534 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
535 ORDER BY `created` DESC
537 intval($user_info['id'])
540 if (count($lastwall)>0){
541 $lastwall = $lastwall[0];
543 $in_reply_to_status_id = '';
544 $in_reply_to_user_id = '';
545 $in_reply_to_screen_name = '';
546 if ($lastwall['parent']!=$lastwall['id']) {
547 $in_reply_to_status_id=$lastwall['parent'];
548 $in_reply_to_user_id = $lastwall['reply_uid'];
549 $in_reply_to_screen_name = $lastwall['reply_author'];
551 $status_info = array(
552 'created_at' => api_date($lastwall['created']),
553 'id' => $lastwall['contact-id'],
554 'text' => strip_tags(bbcode($lastwall['body'])),
555 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
556 'truncated' => false,
557 'in_reply_to_status_id' => $in_reply_to_status_id,
558 'in_reply_to_user_id' => $in_reply_to_user_id,
559 'favorited' => false,
560 'in_reply_to_screen_name' => $in_reply_to_screen_name,
562 'coordinates' => $lastwall['coord'],
563 'place' => $lastwall['location'],
566 $status_info['user'] = $user_info;
568 return api_apply_template("status", $type, array('$status' => $status_info));
577 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
578 * The author's most recent status will be returned inline.
579 * http://developer.twitter.com/doc/get/users/show
581 function api_users_show(&$a, $type){
582 $user_info = api_get_user($a);
583 // get last public wall message
584 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
585 FROM `item`, `contact`,
586 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
587 WHERE `item`.`contact-id` = %d
588 AND `i`.`id` = `item`.`parent`
589 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
590 AND `type`!='activity'
591 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
592 ORDER BY `created` DESC
594 intval($user_info['id'])
597 if (count($lastwall)>0){
598 $lastwall = $lastwall[0];
600 $in_reply_to_status_id = '';
601 $in_reply_to_user_id = '';
602 $in_reply_to_screen_name = '';
603 if ($lastwall['parent']!=$lastwall['id']) {
604 $in_reply_to_status_id=$lastwall['parent'];
605 $in_reply_to_user_id = $lastwall['reply_uid'];
606 $in_reply_to_screen_name = $lastwall['reply_author'];
608 $user_info['status'] = array(
609 'created_at' => api_date($lastwall['created']),
610 'id' => $lastwall['contact-id'],
611 'text' => strip_tags(bbcode($lastwall['body'])),
612 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
613 'truncated' => false,
614 'in_reply_to_status_id' => $in_reply_to_status_id,
615 'in_reply_to_user_id' => $in_reply_to_user_id,
616 'favorited' => false,
617 'in_reply_to_screen_name' => $in_reply_to_screen_name,
619 'coordinates' => $lastwall['coord'],
620 'place' => $lastwall['location'],
624 return api_apply_template("user", $type, array('$user' => $user_info));
627 api_register_func('api/users/show','api_users_show');
631 * http://developer.twitter.com/doc/get/statuses/home_timeline
633 * TODO: Optional parameters
634 * TODO: Add reply info
636 function api_statuses_home_timeline(&$a, $type){
637 if (local_user()===false) return false;
639 $user_info = api_get_user($a);
640 // get last newtork messages
644 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
645 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
646 if ($page<0) $page=0;
647 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
649 $start = $page*$count;
651 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
652 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
653 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
654 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
655 FROM `item`, `contact`
656 WHERE `item`.`uid` = %d
657 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
658 AND `contact`.`id` = `item`.`contact-id`
659 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
662 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
663 intval($user_info['uid']),
665 intval($start), intval($count)
668 $ret = api_format_items($r,$user_info);
671 $data = array('$statuses' => $ret);
675 $data = api_rss_extra($a, $data, $user_info);
678 return api_apply_template("timeline", $type, $data);
680 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
681 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
685 function api_statuses_user_timeline(&$a, $type){
686 if (local_user()===false) return false;
688 $user_info = api_get_user($a);
689 // get last newtork messages
692 logger("api_statuses_user_timeline: local_user: ". local_user() .
693 "\nuser_info: ".print_r($user_info, true) .
694 "\n_REQUEST: ".print_r($_REQUEST, true),
698 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
699 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
700 if ($page<0) $page=0;
701 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
703 $start = $page*$count;
705 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
707 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
708 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
709 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
710 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
711 FROM `item`, `contact`
712 WHERE `item`.`uid` = %d
713 AND `item`.`contact-id` = %d
714 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
715 AND `contact`.`id` = `item`.`contact-id`
716 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
719 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
720 intval(local_user()),
721 intval($user_info['id']),
723 intval($start), intval($count)
726 $ret = api_format_items($r,$user_info);
729 $data = array('$statuses' => $ret);
733 $data = api_rss_extra($a, $data, $user_info);
736 return api_apply_template("timeline", $type, $data);
739 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
742 function api_favorites(&$a, $type){
743 if (local_user()===false) return false;
745 $user_info = api_get_user($a);
746 // in friendika starred item are private
747 // return favorites only for self
748 logger('api_favorites: self:' . $user_info['self']);
750 if ($user_info['self']==0) {
756 $count = (x($_GET,'count')?$_GET['count']:20);
757 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
758 if ($page<0) $page=0;
760 $start = $page*$count;
762 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
763 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
764 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
765 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
766 FROM `item`, `contact`
767 WHERE `item`.`uid` = %d
768 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
769 AND `item`.`starred` = 1
770 AND `contact`.`id` = `item`.`contact-id`
771 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
773 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
774 intval($user_info['uid']),
775 intval($start), intval($count)
778 $ret = api_format_items($r,$user_info);
782 $data = array('$statuses' => $ret);
786 $data = api_rss_extra($a, $data, $user_info);
789 return api_apply_template("timeline", $type, $data);
792 api_register_func('api/favorites','api_favorites', true);
795 function api_format_items($r,$user_info) {
797 //logger('api_format_items: ' . print_r($r,true));
799 //logger('api_format_items: ' . print_r($user_info,true));
804 foreach($r as $item) {
805 localize_item($item);
806 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
808 'created_at'=> api_date($item['created']),
809 'published' => api_date($item['created']),
810 'updated' => api_date($item['edited']),
811 'id' => intval($item['id']),
812 'message_id' => $item['uri'],
813 'text' => strip_tags(bbcode($item['body'])),
814 'statusnet_html' => bbcode($item['body']),
815 'source' => (($item['app']) ? $item['app'] : 'web'),
816 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
817 'truncated' => False,
818 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
819 'in_reply_to_user_id' => '',
820 'favorited' => $item['starred'] ? true : false,
821 'in_reply_to_screen_name' => '',
823 'coordinates' => $item['coord'],
824 'place' => $item['location'],
825 'contributors' => '',
828 'user' => $status_user ,
829 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
830 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
831 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
832 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
840 function api_account_rate_limit_status(&$a,$type) {
843 'remaining_hits' => (string) 150,
844 'hourly_limit' => (string) 150,
845 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
846 'reset_time_in_seconds' => strtotime('now + 1 hour')
849 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
852 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
855 * https://dev.twitter.com/docs/api/1/get/statuses/friends
856 * This function is deprecated by Twitter
859 function api_statuses_f(&$a, $type, $qtype) {
860 if (local_user()===false) return false;
861 $user_info = api_get_user($a);
864 // friends and followers only for self
865 if ($user_info['self']==0){
869 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
870 /* this is to stop Hotot to load friends multiple times
871 * I'm not sure if I'm missing return something or
872 * is a bug in hotot. Workaround, meantime
876 return array('$users' => $ret);*/
880 if($qtype == 'friends')
881 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
882 if($qtype == 'followers')
883 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
885 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
891 $ret[] = api_get_user($a, $cid['id']);
895 return array('$users' => $ret);
898 function api_statuses_friends(&$a, $type){
899 $data = api_statuses_f($a,$type,"friends");
900 if ($data===false) return false;
901 return api_apply_template("friends", $type, $data);
903 function api_statuses_followers(&$a, $type){
904 $data = api_statuses_f($a,$type,"followers");
905 if ($data===false) return false;
906 return api_apply_template("friends", $type, $data);
908 api_register_func('api/statuses/friends','api_statuses_friends',true);
909 api_register_func('api/statuses/followers','api_statuses_followers',true);
916 function api_statusnet_config(&$a,$type) {
917 $name = $a->config['sitename'];
918 $server = $a->get_hostname();
919 $logo = $a->get_baseurl() . '/images/friendika-64.png';
920 $email = $a->config['admin_email'];
921 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
922 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
923 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
924 if($a->config['api_import_size'])
925 $texlimit = string($a->config['api_import_size']);
926 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
927 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
930 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
931 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
932 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
933 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
934 'shorturllength' => '30'
938 return api_apply_template('config', $type, array('$config' => $config));
941 api_register_func('api/statusnet/config','api_statusnet_config',false);
943 function api_statusnet_version(&$a,$type) {
947 if($type === 'xml') {
948 header("Content-type: application/xml");
949 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
952 elseif($type === 'json') {
953 header("Content-type: application/json");
958 api_register_func('api/statusnet/version','api_statusnet_version',false);
961 function api_ff_ids(&$a,$type,$qtype) {
965 if($qtype == 'friends')
966 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
967 if($qtype == 'followers')
968 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
971 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
976 if($type === 'xml') {
977 header("Content-type: application/xml");
978 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
980 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
981 echo '</ids>' . "\r\n";
984 elseif($type === 'json') {
986 header("Content-type: application/json");
987 foreach($r as $rr) $ret[] = $rr['id'];
988 echo json_encode($ret);
994 function api_friends_ids(&$a,$type) {
995 api_ff_ids($a,$type,'friends');
997 function api_followers_ids(&$a,$type) {
998 api_ff_ids($a,$type,'followers');
1000 api_register_func('api/friends/ids','api_friends_ids',true);
1001 api_register_func('api/followers/ids','api_followers_ids',true);
1004 function api_direct_messages_new(&$a, $type) {
1005 if (local_user()===false) return false;
1007 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1009 $sender = api_get_user($a);
1011 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1012 intval(local_user()),
1013 dbesc($_POST['screen_name']));
1015 $recipient = api_get_user($a, $r[0]['id']);
1018 require_once("include/message.php");
1019 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1020 $id = send_message($recipient['id'], $_POST['text'], $sub);
1024 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1027 'id' => $item['id'],
1028 'created_at'=> api_date($item['created']),
1029 'sender_id'=> $sender['id'] ,
1030 'sender_screen_name'=> $sender['screen_name'],
1032 'recipient_id'=> $recipient['id'],
1033 'recipient_screen_name'=> $recipient['screen_name'],
1034 'recipient'=> $recipient,
1036 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1041 $ret = array("error"=>$id);
1044 $data = Array('$messages'=>$ret);
1049 $data = api_rss_extra($a, $data, $user_info);
1052 return api_apply_template("direct_messages", $type, $data);
1055 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1057 function api_direct_messages_box(&$a, $type, $box) {
1058 if (local_user()===false) return false;
1060 $user_info = api_get_user($a);
1063 $count = (x($_GET,'count')?$_GET['count']:20);
1064 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1065 if ($page<0) $page=0;
1067 $start = $page*$count;
1070 if ($box=="sentbox") {
1071 $sql_extra = "`from-url`='%s'";
1073 $sql_extra = "`from-url`!='%s'";
1076 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1077 intval(local_user()),
1078 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1079 intval($start), intval($count)
1083 foreach($r as $item){
1086 $recipient = $user_info;
1087 $sender = api_get_user($a,$item['contact-id']);
1090 $recipient = api_get_user($a,$item['contact-id']);
1091 $sender = $user_info;
1096 'id' => $item['id'],
1097 'created_at'=> api_date($item['created']),
1098 'sender_id'=> $sender['id'] ,
1099 'sender_screen_name'=> $sender['screen_name'],
1101 'recipient_id'=> $recipient['id'],
1102 'recipient_screen_name'=> $recipient['screen_name'],
1103 'recipient'=> $recipient,
1105 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1112 $data = array('$messages' => $ret);
1116 $data = api_rss_extra($a, $data, $user_info);
1119 return api_apply_template("direct_messages", $type, $data);
1123 function api_direct_messages_sentbox(&$a, $type){
1124 return api_direct_messages_box($a, $type, "sentbox");
1126 function api_direct_messages_inbox(&$a, $type){
1127 return api_direct_messages_box($a, $type, "inbox");
1129 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1130 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1134 function api_oauth_request_token(&$a, $type){
1136 $oauth = new FKOAuth1();
1137 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1138 }catch(Exception $e){
1139 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1144 function api_oauth_access_token(&$a, $type){
1146 $oauth = new FKOAuth1();
1147 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1148 }catch(Exception $e){
1149 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1155 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1156 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);