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/friendica-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 /*Waitman Gobble Mod*/
457 function api_statuses_mediap(&$a, $type) {
458 if (local_user()===false) {
459 logger('api_statuses_update: no user');
462 $user_info = api_get_user($a);
464 $_REQUEST['type'] = 'wall';
465 $_REQUEST['profile_uid'] = local_user();
466 $_REQUEST['api_source'] = true;
467 $txt = urldecode(requestdata('status'));
469 require_once('library/HTMLPurifier.auto.php');
470 require_once('include/html2bbcode.php');
472 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
473 $txt = html2bb_video($txt);
474 $config = HTMLPurifier_Config::createDefault();
475 $config->set('Cache.DefinitionImpl', null);
476 $purifier = new HTMLPurifier($config);
477 $txt = $purifier->purify($txt);
479 $txt = html2bbcode($txt);
481 $a->argv[1]=$user_info['screen_name']; //should be set to username?
483 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
484 require_once('mod/wall_upload.php');
485 $bebop = wall_upload_post($a);
487 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
488 $_REQUEST['body']=$txt."\n\n".$bebop;
489 require_once('mod/item.php');
492 // this should output the last post (the one we just posted).
493 return api_status_show($a,$type);
495 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
496 /*Waitman Gobble Mod*/
499 function api_statuses_update(&$a, $type) {
500 if (local_user()===false) {
501 logger('api_statuses_update: no user');
504 $user_info = api_get_user($a);
506 // convert $_POST array items to the form we use for web posts.
508 // logger('api_post: ' . print_r($_POST,true));
510 if(requestdata('htmlstatus')) {
511 require_once('library/HTMLPurifier.auto.php');
512 require_once('include/html2bbcode.php');
514 $txt = requestdata('htmlstatus');
515 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
517 $txt = html2bb_video($txt);
519 $config = HTMLPurifier_Config::createDefault();
520 $config->set('Cache.DefinitionImpl', null);
523 $purifier = new HTMLPurifier($config);
524 $txt = $purifier->purify($txt);
526 $_REQUEST['body'] = html2bbcode($txt);
531 $_REQUEST['body'] = urldecode(requestdata('status'));
533 $parent = requestdata('in_reply_to_status_id');
534 if(ctype_digit($parent))
535 $_REQUEST['parent'] = $parent;
537 $_REQUEST['parent_uri'] = $parent;
539 if(requestdata('lat') && requestdata('long'))
540 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
541 $_REQUEST['profile_uid'] = local_user();
542 if(requestdata('parent'))
543 $_REQUEST['type'] = 'net-comment';
545 $_REQUEST['type'] = 'wall';
547 // set this so that the item_post() function is quiet and doesn't redirect or emit json
549 $_REQUEST['api_source'] = true;
551 // call out normal post function
553 require_once('mod/item.php');
556 // this should output the last post (the one we just posted).
557 return api_status_show($a,$type);
559 api_register_func('api/statuses/update','api_statuses_update', true);
562 function api_status_show(&$a, $type){
563 $user_info = api_get_user($a);
564 // get last public wall message
565 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
566 FROM `item`, `contact`,
567 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
568 WHERE `item`.`contact-id` = %d
569 AND `i`.`id` = `item`.`parent`
570 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
571 AND `type`!='activity'
572 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
573 ORDER BY `created` DESC
575 intval($user_info['id'])
578 if (count($lastwall)>0){
579 $lastwall = $lastwall[0];
581 $in_reply_to_status_id = '';
582 $in_reply_to_user_id = '';
583 $in_reply_to_screen_name = '';
584 if ($lastwall['parent']!=$lastwall['id']) {
585 $in_reply_to_status_id=$lastwall['parent'];
586 $in_reply_to_user_id = $lastwall['reply_uid'];
587 $in_reply_to_screen_name = $lastwall['reply_author'];
589 $status_info = array(
590 'created_at' => api_date($lastwall['created']),
591 'id' => $lastwall['contact-id'],
592 'text' => strip_tags(bbcode($lastwall['body'])),
593 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
594 'truncated' => false,
595 'in_reply_to_status_id' => $in_reply_to_status_id,
596 'in_reply_to_user_id' => $in_reply_to_user_id,
597 'favorited' => false,
598 'in_reply_to_screen_name' => $in_reply_to_screen_name,
600 'coordinates' => $lastwall['coord'],
601 'place' => $lastwall['location'],
604 $status_info['user'] = $user_info;
606 return api_apply_template("status", $type, array('$status' => $status_info));
615 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
616 * The author's most recent status will be returned inline.
617 * http://developer.twitter.com/doc/get/users/show
619 function api_users_show(&$a, $type){
620 $user_info = api_get_user($a);
621 // get last public wall message
622 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
623 FROM `item`, `contact`,
624 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
625 WHERE `item`.`contact-id` = %d
626 AND `i`.`id` = `item`.`parent`
627 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
628 AND `type`!='activity'
629 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
630 ORDER BY `created` DESC
632 intval($user_info['id'])
635 if (count($lastwall)>0){
636 $lastwall = $lastwall[0];
638 $in_reply_to_status_id = '';
639 $in_reply_to_user_id = '';
640 $in_reply_to_screen_name = '';
641 if ($lastwall['parent']!=$lastwall['id']) {
642 $in_reply_to_status_id=$lastwall['parent'];
643 $in_reply_to_user_id = $lastwall['reply_uid'];
644 $in_reply_to_screen_name = $lastwall['reply_author'];
646 $user_info['status'] = array(
647 'created_at' => api_date($lastwall['created']),
648 'id' => $lastwall['contact-id'],
649 'text' => strip_tags(bbcode($lastwall['body'])),
650 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
651 'truncated' => false,
652 'in_reply_to_status_id' => $in_reply_to_status_id,
653 'in_reply_to_user_id' => $in_reply_to_user_id,
654 'favorited' => false,
655 'in_reply_to_screen_name' => $in_reply_to_screen_name,
657 'coordinates' => $lastwall['coord'],
658 'place' => $lastwall['location'],
662 return api_apply_template("user", $type, array('$user' => $user_info));
665 api_register_func('api/users/show','api_users_show');
669 * http://developer.twitter.com/doc/get/statuses/home_timeline
671 * TODO: Optional parameters
672 * TODO: Add reply info
674 function api_statuses_home_timeline(&$a, $type){
675 if (local_user()===false) return false;
677 $user_info = api_get_user($a);
678 // get last newtork messages
682 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
683 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
684 if ($page<0) $page=0;
685 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
687 $start = $page*$count;
689 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
690 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
691 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
692 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
693 FROM `item`, `contact`
694 WHERE `item`.`uid` = %d
695 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
696 AND `contact`.`id` = `item`.`contact-id`
697 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
700 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
701 intval($user_info['uid']),
703 intval($start), intval($count)
706 $ret = api_format_items($r,$user_info);
709 $data = array('$statuses' => $ret);
713 $data = api_rss_extra($a, $data, $user_info);
716 return api_apply_template("timeline", $type, $data);
718 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
719 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
723 function api_statuses_user_timeline(&$a, $type){
724 if (local_user()===false) return false;
726 $user_info = api_get_user($a);
727 // get last newtork messages
730 logger("api_statuses_user_timeline: local_user: ". local_user() .
731 "\nuser_info: ".print_r($user_info, true) .
732 "\n_REQUEST: ".print_r($_REQUEST, true),
736 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
737 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
738 if ($page<0) $page=0;
739 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
741 $start = $page*$count;
743 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
745 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
746 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
747 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
748 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
749 FROM `item`, `contact`
750 WHERE `item`.`uid` = %d
751 AND `item`.`contact-id` = %d
752 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
753 AND `contact`.`id` = `item`.`contact-id`
754 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
757 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
758 intval(local_user()),
759 intval($user_info['id']),
761 intval($start), intval($count)
764 $ret = api_format_items($r,$user_info);
767 $data = array('$statuses' => $ret);
771 $data = api_rss_extra($a, $data, $user_info);
774 return api_apply_template("timeline", $type, $data);
777 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
780 function api_favorites(&$a, $type){
781 if (local_user()===false) return false;
783 $user_info = api_get_user($a);
784 // in friendica starred item are private
785 // return favorites only for self
786 logger('api_favorites: self:' . $user_info['self']);
788 if ($user_info['self']==0) {
794 $count = (x($_GET,'count')?$_GET['count']:20);
795 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
796 if ($page<0) $page=0;
798 $start = $page*$count;
800 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
801 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
802 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
803 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
804 FROM `item`, `contact`
805 WHERE `item`.`uid` = %d
806 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
807 AND `item`.`starred` = 1
808 AND `contact`.`id` = `item`.`contact-id`
809 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
811 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
812 intval($user_info['uid']),
813 intval($start), intval($count)
816 $ret = api_format_items($r,$user_info);
820 $data = array('$statuses' => $ret);
824 $data = api_rss_extra($a, $data, $user_info);
827 return api_apply_template("timeline", $type, $data);
830 api_register_func('api/favorites','api_favorites', true);
833 function api_format_items($r,$user_info) {
835 //logger('api_format_items: ' . print_r($r,true));
837 //logger('api_format_items: ' . print_r($user_info,true));
842 foreach($r as $item) {
843 localize_item($item);
844 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
846 'created_at'=> api_date($item['created']),
847 'published' => api_date($item['created']),
848 'updated' => api_date($item['edited']),
849 'id' => intval($item['id']),
850 'message_id' => $item['uri'],
851 'text' => strip_tags(bbcode($item['body'])),
852 'statusnet_html' => bbcode($item['body']),
853 'source' => (($item['app']) ? $item['app'] : 'web'),
854 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
855 'truncated' => False,
856 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
857 'in_reply_to_user_id' => '',
858 'favorited' => $item['starred'] ? true : false,
859 'in_reply_to_screen_name' => '',
861 'coordinates' => $item['coord'],
862 'place' => $item['location'],
863 'contributors' => '',
866 'user' => $status_user ,
867 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
868 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
869 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
870 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
878 function api_account_rate_limit_status(&$a,$type) {
881 'remaining_hits' => (string) 150,
882 'hourly_limit' => (string) 150,
883 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
884 'reset_time_in_seconds' => strtotime('now + 1 hour')
887 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
890 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
893 * https://dev.twitter.com/docs/api/1/get/statuses/friends
894 * This function is deprecated by Twitter
897 function api_statuses_f(&$a, $type, $qtype) {
898 if (local_user()===false) return false;
899 $user_info = api_get_user($a);
902 // friends and followers only for self
903 if ($user_info['self']==0){
907 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
908 /* this is to stop Hotot to load friends multiple times
909 * I'm not sure if I'm missing return something or
910 * is a bug in hotot. Workaround, meantime
914 return array('$users' => $ret);*/
918 if($qtype == 'friends')
919 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
920 if($qtype == 'followers')
921 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
923 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
929 $ret[] = api_get_user($a, $cid['id']);
933 return array('$users' => $ret);
936 function api_statuses_friends(&$a, $type){
937 $data = api_statuses_f($a,$type,"friends");
938 if ($data===false) return false;
939 return api_apply_template("friends", $type, $data);
941 function api_statuses_followers(&$a, $type){
942 $data = api_statuses_f($a,$type,"followers");
943 if ($data===false) return false;
944 return api_apply_template("friends", $type, $data);
946 api_register_func('api/statuses/friends','api_statuses_friends',true);
947 api_register_func('api/statuses/followers','api_statuses_followers',true);
954 function api_statusnet_config(&$a,$type) {
955 $name = $a->config['sitename'];
956 $server = $a->get_hostname();
957 $logo = $a->get_baseurl() . '/images/friendica-64.png';
958 $email = $a->config['admin_email'];
959 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
960 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
961 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
962 if($a->config['api_import_size'])
963 $texlimit = string($a->config['api_import_size']);
964 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
965 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
968 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
969 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
970 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
971 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
972 'shorturllength' => '30'
976 return api_apply_template('config', $type, array('$config' => $config));
979 api_register_func('api/statusnet/config','api_statusnet_config',false);
981 function api_statusnet_version(&$a,$type) {
985 if($type === 'xml') {
986 header("Content-type: application/xml");
987 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
990 elseif($type === 'json') {
991 header("Content-type: application/json");
996 api_register_func('api/statusnet/version','api_statusnet_version',false);
999 function api_ff_ids(&$a,$type,$qtype) {
1003 if($qtype == 'friends')
1004 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1005 if($qtype == 'followers')
1006 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1009 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1010 intval(local_user())
1014 if($type === 'xml') {
1015 header("Content-type: application/xml");
1016 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1018 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1019 echo '</ids>' . "\r\n";
1022 elseif($type === 'json') {
1024 header("Content-type: application/json");
1025 foreach($r as $rr) $ret[] = $rr['id'];
1026 echo json_encode($ret);
1032 function api_friends_ids(&$a,$type) {
1033 api_ff_ids($a,$type,'friends');
1035 function api_followers_ids(&$a,$type) {
1036 api_ff_ids($a,$type,'followers');
1038 api_register_func('api/friends/ids','api_friends_ids',true);
1039 api_register_func('api/followers/ids','api_followers_ids',true);
1042 function api_direct_messages_new(&$a, $type) {
1043 if (local_user()===false) return false;
1045 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1047 $sender = api_get_user($a);
1049 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1050 intval(local_user()),
1051 dbesc($_POST['screen_name']));
1053 $recipient = api_get_user($a, $r[0]['id']);
1056 require_once("include/message.php");
1057 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1058 $id = send_message($recipient['id'], $_POST['text'], $sub);
1062 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1065 'id' => $item['id'],
1066 'created_at'=> api_date($item['created']),
1067 'sender_id'=> $sender['id'] ,
1068 'sender_screen_name'=> $sender['screen_name'],
1070 'recipient_id'=> $recipient['id'],
1071 'recipient_screen_name'=> $recipient['screen_name'],
1072 'recipient'=> $recipient,
1074 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1079 $ret = array("error"=>$id);
1082 $data = Array('$messages'=>$ret);
1087 $data = api_rss_extra($a, $data, $user_info);
1090 return api_apply_template("direct_messages", $type, $data);
1093 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1095 function api_direct_messages_box(&$a, $type, $box) {
1096 if (local_user()===false) return false;
1098 $user_info = api_get_user($a);
1101 $count = (x($_GET,'count')?$_GET['count']:20);
1102 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1103 if ($page<0) $page=0;
1105 $start = $page*$count;
1108 if ($box=="sentbox") {
1109 $sql_extra = "`from-url`='%s'";
1111 $sql_extra = "`from-url`!='%s'";
1114 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1115 intval(local_user()),
1116 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1117 intval($start), intval($count)
1121 foreach($r as $item){
1124 $recipient = $user_info;
1125 $sender = api_get_user($a,$item['contact-id']);
1128 $recipient = api_get_user($a,$item['contact-id']);
1129 $sender = $user_info;
1134 'id' => $item['id'],
1135 'created_at'=> api_date($item['created']),
1136 'sender_id'=> $sender['id'] ,
1137 'sender_screen_name'=> $sender['screen_name'],
1139 'recipient_id'=> $recipient['id'],
1140 'recipient_screen_name'=> $recipient['screen_name'],
1141 'recipient'=> $recipient,
1143 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1150 $data = array('$messages' => $ret);
1154 $data = api_rss_extra($a, $data, $user_info);
1157 return api_apply_template("direct_messages", $type, $data);
1161 function api_direct_messages_sentbox(&$a, $type){
1162 return api_direct_messages_box($a, $type, "sentbox");
1164 function api_direct_messages_inbox(&$a, $type){
1165 return api_direct_messages_box($a, $type, "inbox");
1167 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1168 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1172 function api_oauth_request_token(&$a, $type){
1174 $oauth = new FKOAuth1();
1175 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1176 }catch(Exception $e){
1177 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1182 function api_oauth_access_token(&$a, $type){
1184 $oauth = new FKOAuth1();
1185 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1186 }catch(Exception $e){
1187 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1193 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1194 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);