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/friendica-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 /*Waitman Gobble Mod*/
461 function api_statuses_mediap(&$a, $type) {
462 if (local_user()===false) {
463 logger('api_statuses_update: no user');
466 $user_info = api_get_user($a);
468 $_REQUEST['type'] = 'wall';
469 $_REQUEST['profile_uid'] = local_user();
470 $_REQUEST['api_source'] = true;
471 $txt = urldecode(requestdata('status'));
473 require_once('library/HTMLPurifier.auto.php');
474 require_once('include/html2bbcode.php');
476 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
477 $txt = html2bb_video($txt);
478 $config = HTMLPurifier_Config::createDefault();
479 $config->set('Cache.DefinitionImpl', null);
480 $purifier = new HTMLPurifier($config);
481 $txt = $purifier->purify($txt);
483 $txt = html2bbcode($txt);
485 $a->argv[1]=$user_info['screen_name']; //should be set to username?
487 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
488 require_once('mod/wall_upload.php');
489 $bebop = wall_upload_post($a);
491 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
492 $_REQUEST['body']=$txt."\n\n".$bebop;
493 require_once('mod/item.php');
496 // this should output the last post (the one we just posted).
497 return api_status_show($a,$type);
499 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
500 /*Waitman Gobble Mod*/
503 function api_statuses_update(&$a, $type) {
504 if (local_user()===false) {
505 logger('api_statuses_update: no user');
508 $user_info = api_get_user($a);
510 // convert $_POST array items to the form we use for web posts.
512 // logger('api_post: ' . print_r($_POST,true));
514 if(requestdata('htmlstatus')) {
515 require_once('library/HTMLPurifier.auto.php');
516 require_once('include/html2bbcode.php');
518 $txt = requestdata('htmlstatus');
519 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
521 $txt = html2bb_video($txt);
523 $config = HTMLPurifier_Config::createDefault();
524 $config->set('Cache.DefinitionImpl', null);
527 $purifier = new HTMLPurifier($config);
528 $txt = $purifier->purify($txt);
530 $_REQUEST['body'] = html2bbcode($txt);
535 $_REQUEST['body'] = urldecode(requestdata('status'));
537 $parent = requestdata('in_reply_to_status_id');
538 if(ctype_digit($parent))
539 $_REQUEST['parent'] = $parent;
541 $_REQUEST['parent_uri'] = $parent;
543 if(requestdata('lat') && requestdata('long'))
544 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
545 $_REQUEST['profile_uid'] = local_user();
546 if(requestdata('parent'))
547 $_REQUEST['type'] = 'net-comment';
549 $_REQUEST['type'] = 'wall';
551 // set this so that the item_post() function is quiet and doesn't redirect or emit json
553 $_REQUEST['api_source'] = true;
555 // call out normal post function
557 require_once('mod/item.php');
560 // this should output the last post (the one we just posted).
561 return api_status_show($a,$type);
563 api_register_func('api/statuses/update','api_statuses_update', true);
566 function api_status_show(&$a, $type){
567 $user_info = api_get_user($a);
568 // get last public wall message
569 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
570 FROM `item`, `contact`,
571 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
572 WHERE `item`.`contact-id` = %d
573 AND `i`.`id` = `item`.`parent`
574 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
575 AND `type`!='activity'
576 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
577 ORDER BY `created` DESC
579 intval($user_info['id'])
582 if (count($lastwall)>0){
583 $lastwall = $lastwall[0];
585 $in_reply_to_status_id = '';
586 $in_reply_to_user_id = '';
587 $in_reply_to_screen_name = '';
588 if ($lastwall['parent']!=$lastwall['id']) {
589 $in_reply_to_status_id=$lastwall['parent'];
590 $in_reply_to_user_id = $lastwall['reply_uid'];
591 $in_reply_to_screen_name = $lastwall['reply_author'];
593 $status_info = array(
594 'created_at' => api_date($lastwall['created']),
595 'id' => $lastwall['contact-id'],
596 'text' => strip_tags(bbcode($lastwall['body'])),
597 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
598 'truncated' => false,
599 'in_reply_to_status_id' => $in_reply_to_status_id,
600 'in_reply_to_user_id' => $in_reply_to_user_id,
601 'favorited' => false,
602 'in_reply_to_screen_name' => $in_reply_to_screen_name,
604 'coordinates' => $lastwall['coord'],
605 'place' => $lastwall['location'],
608 $status_info['user'] = $user_info;
610 return api_apply_template("status", $type, array('$status' => $status_info));
619 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
620 * The author's most recent status will be returned inline.
621 * http://developer.twitter.com/doc/get/users/show
623 function api_users_show(&$a, $type){
624 $user_info = api_get_user($a);
625 // get last public wall message
626 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
627 FROM `item`, `contact`,
628 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
629 WHERE `item`.`contact-id` = %d
630 AND `i`.`id` = `item`.`parent`
631 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
632 AND `type`!='activity'
633 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
634 ORDER BY `created` DESC
636 intval($user_info['id'])
639 if (count($lastwall)>0){
640 $lastwall = $lastwall[0];
642 $in_reply_to_status_id = '';
643 $in_reply_to_user_id = '';
644 $in_reply_to_screen_name = '';
645 if ($lastwall['parent']!=$lastwall['id']) {
646 $in_reply_to_status_id=$lastwall['parent'];
647 $in_reply_to_user_id = $lastwall['reply_uid'];
648 $in_reply_to_screen_name = $lastwall['reply_author'];
650 $user_info['status'] = array(
651 'created_at' => api_date($lastwall['created']),
652 'id' => $lastwall['contact-id'],
653 'text' => strip_tags(bbcode($lastwall['body'])),
654 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
655 'truncated' => false,
656 'in_reply_to_status_id' => $in_reply_to_status_id,
657 'in_reply_to_user_id' => $in_reply_to_user_id,
658 'favorited' => false,
659 'in_reply_to_screen_name' => $in_reply_to_screen_name,
661 'coordinates' => $lastwall['coord'],
662 'place' => $lastwall['location'],
666 return api_apply_template("user", $type, array('$user' => $user_info));
669 api_register_func('api/users/show','api_users_show');
673 * http://developer.twitter.com/doc/get/statuses/home_timeline
675 * TODO: Optional parameters
676 * TODO: Add reply info
678 function api_statuses_home_timeline(&$a, $type){
679 if (local_user()===false) return false;
681 $user_info = api_get_user($a);
682 // get last newtork messages
686 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
687 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
688 if ($page<0) $page=0;
689 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
691 $start = $page*$count;
693 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
694 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
695 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
696 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
697 FROM `item`, `contact`
698 WHERE `item`.`uid` = %d
699 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
700 AND `contact`.`id` = `item`.`contact-id`
701 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
704 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
705 intval($user_info['uid']),
707 intval($start), intval($count)
710 $ret = api_format_items($r,$user_info);
713 $data = array('$statuses' => $ret);
717 $data = api_rss_extra($a, $data, $user_info);
720 return api_apply_template("timeline", $type, $data);
722 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
723 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
727 function api_statuses_user_timeline(&$a, $type){
728 if (local_user()===false) return false;
730 $user_info = api_get_user($a);
731 // get last newtork messages
734 logger("api_statuses_user_timeline: local_user: ". local_user() .
735 "\nuser_info: ".print_r($user_info, true) .
736 "\n_REQUEST: ".print_r($_REQUEST, true),
740 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
741 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
742 if ($page<0) $page=0;
743 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
745 $start = $page*$count;
747 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
749 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
750 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
751 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
752 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
753 FROM `item`, `contact`
754 WHERE `item`.`uid` = %d
755 AND `item`.`contact-id` = %d
756 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
757 AND `contact`.`id` = `item`.`contact-id`
758 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
761 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
762 intval(local_user()),
763 intval($user_info['id']),
765 intval($start), intval($count)
768 $ret = api_format_items($r,$user_info);
771 $data = array('$statuses' => $ret);
775 $data = api_rss_extra($a, $data, $user_info);
778 return api_apply_template("timeline", $type, $data);
781 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
784 function api_favorites(&$a, $type){
785 if (local_user()===false) return false;
787 $user_info = api_get_user($a);
788 // in friendica starred item are private
789 // return favorites only for self
790 logger('api_favorites: self:' . $user_info['self']);
792 if ($user_info['self']==0) {
798 $count = (x($_GET,'count')?$_GET['count']:20);
799 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
800 if ($page<0) $page=0;
802 $start = $page*$count;
804 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
805 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
806 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
807 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
808 FROM `item`, `contact`
809 WHERE `item`.`uid` = %d
810 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
811 AND `item`.`starred` = 1
812 AND `contact`.`id` = `item`.`contact-id`
813 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
815 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
816 intval($user_info['uid']),
817 intval($start), intval($count)
820 $ret = api_format_items($r,$user_info);
824 $data = array('$statuses' => $ret);
828 $data = api_rss_extra($a, $data, $user_info);
831 return api_apply_template("timeline", $type, $data);
834 api_register_func('api/favorites','api_favorites', true);
837 function api_format_items($r,$user_info) {
839 //logger('api_format_items: ' . print_r($r,true));
841 //logger('api_format_items: ' . print_r($user_info,true));
846 foreach($r as $item) {
847 localize_item($item);
848 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
850 'created_at'=> api_date($item['created']),
851 'published' => api_date($item['created']),
852 'updated' => api_date($item['edited']),
853 'id' => intval($item['id']),
854 'message_id' => $item['uri'],
855 'text' => strip_tags(bbcode($item['body'])),
856 'statusnet_html' => bbcode($item['body']),
857 'source' => (($item['app']) ? $item['app'] : 'web'),
858 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
859 'truncated' => False,
860 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
861 'in_reply_to_user_id' => '',
862 'favorited' => $item['starred'] ? true : false,
863 'in_reply_to_screen_name' => '',
865 'coordinates' => $item['coord'],
866 'place' => $item['location'],
867 'contributors' => '',
870 'user' => $status_user ,
871 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
872 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
873 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
874 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
882 function api_account_rate_limit_status(&$a,$type) {
885 'remaining_hits' => (string) 150,
886 'hourly_limit' => (string) 150,
887 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
888 'reset_time_in_seconds' => strtotime('now + 1 hour')
891 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
894 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
897 * https://dev.twitter.com/docs/api/1/get/statuses/friends
898 * This function is deprecated by Twitter
901 function api_statuses_f(&$a, $type, $qtype) {
902 if (local_user()===false) return false;
903 $user_info = api_get_user($a);
906 // friends and followers only for self
907 if ($user_info['self']==0){
911 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
912 /* this is to stop Hotot to load friends multiple times
913 * I'm not sure if I'm missing return something or
914 * is a bug in hotot. Workaround, meantime
918 return array('$users' => $ret);*/
922 if($qtype == 'friends')
923 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
924 if($qtype == 'followers')
925 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
927 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
933 $ret[] = api_get_user($a, $cid['id']);
937 return array('$users' => $ret);
940 function api_statuses_friends(&$a, $type){
941 $data = api_statuses_f($a,$type,"friends");
942 if ($data===false) return false;
943 return api_apply_template("friends", $type, $data);
945 function api_statuses_followers(&$a, $type){
946 $data = api_statuses_f($a,$type,"followers");
947 if ($data===false) return false;
948 return api_apply_template("friends", $type, $data);
950 api_register_func('api/statuses/friends','api_statuses_friends',true);
951 api_register_func('api/statuses/followers','api_statuses_followers',true);
958 function api_statusnet_config(&$a,$type) {
959 $name = $a->config['sitename'];
960 $server = $a->get_hostname();
961 $logo = $a->get_baseurl() . '/images/friendica-64.png';
962 $email = $a->config['admin_email'];
963 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
964 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
965 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
966 if($a->config['api_import_size'])
967 $texlimit = string($a->config['api_import_size']);
968 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
969 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
972 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
973 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
974 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
975 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
976 'shorturllength' => '30'
980 return api_apply_template('config', $type, array('$config' => $config));
983 api_register_func('api/statusnet/config','api_statusnet_config',false);
985 function api_statusnet_version(&$a,$type) {
989 if($type === 'xml') {
990 header("Content-type: application/xml");
991 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
994 elseif($type === 'json') {
995 header("Content-type: application/json");
1000 api_register_func('api/statusnet/version','api_statusnet_version',false);
1003 function api_ff_ids(&$a,$type,$qtype) {
1007 if($qtype == 'friends')
1008 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1009 if($qtype == 'followers')
1010 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1013 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1014 intval(local_user())
1018 if($type === 'xml') {
1019 header("Content-type: application/xml");
1020 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1022 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1023 echo '</ids>' . "\r\n";
1026 elseif($type === 'json') {
1028 header("Content-type: application/json");
1029 foreach($r as $rr) $ret[] = $rr['id'];
1030 echo json_encode($ret);
1036 function api_friends_ids(&$a,$type) {
1037 api_ff_ids($a,$type,'friends');
1039 function api_followers_ids(&$a,$type) {
1040 api_ff_ids($a,$type,'followers');
1042 api_register_func('api/friends/ids','api_friends_ids',true);
1043 api_register_func('api/followers/ids','api_followers_ids',true);
1046 function api_direct_messages_new(&$a, $type) {
1047 if (local_user()===false) return false;
1049 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1051 $sender = api_get_user($a);
1053 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1054 intval(local_user()),
1055 dbesc($_POST['screen_name']));
1057 $recipient = api_get_user($a, $r[0]['id']);
1060 require_once("include/message.php");
1061 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1062 $id = send_message($recipient['id'], $_POST['text'], $sub);
1066 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1069 'id' => $item['id'],
1070 'created_at'=> api_date($item['created']),
1071 'sender_id'=> $sender['id'] ,
1072 'sender_screen_name'=> $sender['screen_name'],
1074 'recipient_id'=> $recipient['id'],
1075 'recipient_screen_name'=> $recipient['screen_name'],
1076 'recipient'=> $recipient,
1078 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1083 $ret = array("error"=>$id);
1086 $data = Array('$messages'=>$ret);
1091 $data = api_rss_extra($a, $data, $user_info);
1094 return api_apply_template("direct_messages", $type, $data);
1097 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1099 function api_direct_messages_box(&$a, $type, $box) {
1100 if (local_user()===false) return false;
1102 $user_info = api_get_user($a);
1105 $count = (x($_GET,'count')?$_GET['count']:20);
1106 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1107 if ($page<0) $page=0;
1109 $start = $page*$count;
1112 if ($box=="sentbox") {
1113 $sql_extra = "`from-url`='%s'";
1115 $sql_extra = "`from-url`!='%s'";
1118 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1119 intval(local_user()),
1120 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1121 intval($start), intval($count)
1125 foreach($r as $item){
1128 $recipient = $user_info;
1129 $sender = api_get_user($a,$item['contact-id']);
1132 $recipient = api_get_user($a,$item['contact-id']);
1133 $sender = $user_info;
1138 'id' => $item['id'],
1139 'created_at'=> api_date($item['created']),
1140 'sender_id'=> $sender['id'] ,
1141 'sender_screen_name'=> $sender['screen_name'],
1143 'recipient_id'=> $recipient['id'],
1144 'recipient_screen_name'=> $recipient['screen_name'],
1145 'recipient'=> $recipient,
1147 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1154 $data = array('$messages' => $ret);
1158 $data = api_rss_extra($a, $data, $user_info);
1161 return api_apply_template("direct_messages", $type, $data);
1165 function api_direct_messages_sentbox(&$a, $type){
1166 return api_direct_messages_box($a, $type, "sentbox");
1168 function api_direct_messages_inbox(&$a, $type){
1169 return api_direct_messages_box($a, $type, "inbox");
1171 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1172 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1176 function api_oauth_request_token(&$a, $type){
1178 $oauth = new FKOAuth1();
1179 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1180 }catch(Exception $e){
1181 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1186 function api_oauth_access_token(&$a, $type){
1188 $oauth = new FKOAuth1();
1189 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1190 }catch(Exception $e){
1191 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1197 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1198 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);