2 require_once("bbcode.php");
3 require_once("datetime.php");
4 require_once("conversation.php");
5 require_once("oauth.php");
6 require_once("html2plain.php");
15 function api_date($str){
16 //Wed May 23 06:01:13 +0000 2007
17 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
21 function api_register_func($path, $func, $auth=false){
23 $API[$path] = array('func'=>$func,
31 function api_login(&$a){
34 $oauth = new FKOAuth1();
35 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
36 if (!is_null($token)){
37 $oauth->loginUser($token->uid);
38 call_hooks('logged_in', $a->user);
41 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
43 logger(__file__.__line__.__function__."\n".$e);
44 //die(__file__.__line__.__function__."<pre>".$e); die();
49 // workaround for HTTP-auth in CGI mode
50 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
51 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
52 if(strlen($userpass)) {
53 list($name, $password) = explode(':', $userpass);
54 $_SERVER['PHP_AUTH_USER'] = $name;
55 $_SERVER['PHP_AUTH_PW'] = $password;
59 if (!isset($_SERVER['PHP_AUTH_USER'])) {
60 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
61 header('WWW-Authenticate: Basic realm="Friendica"');
62 header('HTTP/1.0 401 Unauthorized');
63 die('This api requires login');
66 $user = $_SERVER['PHP_AUTH_USER'];
67 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
71 * next code from mod/auth.php. needs better solution
74 // process normal login request
76 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
77 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
85 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
86 header('WWW-Authenticate: Basic realm="Friendica"');
87 header('HTTP/1.0 401 Unauthorized');
88 die('This api requires login');
91 require_once('include/security.php');
92 authenticate_success($record);
94 call_hooks('logged_in', $a->user);
98 /**************************
99 * MAIN API ENTRY POINT *
100 **************************/
101 function api_call(&$a){
102 GLOBAL $API, $called_api;
107 foreach ($API as $p=>$info){
108 if (strpos($a->query_string, $p)===0){
109 $called_api= explode("/",$p);
110 //unset($_SERVER['PHP_AUTH_USER']);
111 if ($info['auth']===true && local_user()===false) {
115 load_contact_links(local_user());
117 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
118 logger('API parameters: ' . print_r($_REQUEST,true));
120 if (strpos($a->query_string, ".xml")>0) $type="xml";
121 if (strpos($a->query_string, ".json")>0) $type="json";
122 if (strpos($a->query_string, ".rss")>0) $type="rss";
123 if (strpos($a->query_string, ".atom")>0) $type="atom";
124 if (strpos($a->query_string, ".as")>0) $type="as";
126 $r = call_user_func($info['func'], $a, $type);
127 if ($r===false) return;
131 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
132 header ("Content-Type: text/xml");
133 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
136 //header ("Content-Type: application/json");
138 return json_encode($rr);
141 header ("Content-Type: application/rss+xml");
142 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
145 header ("Content-Type: application/atom+xml");
146 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
149 //header ("Content-Type: application/json");
151 // return json_encode($rr);
152 return json_encode($r);
156 //echo "<pre>"; var_dump($r); die();
159 header("HTTP/1.1 404 Not Found");
160 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
161 $r = '<status><error>not implemented</error></status>';
164 header ("Content-Type: text/xml");
165 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
168 header ("Content-Type: application/json");
169 return json_encode(array('error' => 'not implemented'));
172 header ("Content-Type: application/rss+xml");
173 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
176 header ("Content-Type: application/atom+xml");
177 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
185 function api_rss_extra(&$a, $arr, $user_info){
186 if (is_null($user_info)) $user_info = api_get_user($a);
187 $arr['$user'] = $user_info;
188 $arr['$rss'] = array(
189 'alternate' => $user_info['url'],
190 'self' => $a->get_baseurl(). "/". $a->query_string,
191 'base' => $a->get_baseurl(),
192 'updated' => api_date(null),
193 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
194 'language' => $user_info['language'],
195 'logo' => $a->get_baseurl()."/images/friendica-32.png",
202 * Returns user info array.
204 function api_get_user(&$a, $contact_id = Null){
210 if(!is_null($contact_id)){
212 $extra_query = "AND `contact`.`id` = %d ";
215 if(is_null($user) && x($_GET, 'user_id')) {
216 $user = intval($_GET['user_id']);
217 $extra_query = "AND `contact`.`id` = %d ";
219 if(is_null($user) && x($_GET, 'screen_name')) {
220 $user = dbesc($_GET['screen_name']);
221 $extra_query = "AND `contact`.`nick` = '%s' ";
222 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
226 if (is_null($user) && $a->argc > (count($called_api)-1)){
227 $argid = count($called_api);
228 list($user, $null) = explode(".",$a->argv[$argid]);
229 if(is_numeric($user)){
230 $user = intval($user);
231 $extra_query = "AND `contact`.`id` = %d ";
233 $user = dbesc($user);
234 $extra_query = "AND `contact`.`nick` = '%s' ";
235 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
240 if (local_user()===false) {
241 api_login($a); return False;
243 $user = $_SESSION['uid'];
244 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
249 logger('api_user: ' . $extra_query . ', user: ' . $user);
251 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
256 if (count($uinfo)==0) {
260 if($uinfo[0]['self']) {
261 $usr = q("select * from user where uid = %d limit 1",
264 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
268 // count public wall messages
269 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
272 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
273 intval($uinfo[0]['uid'])
275 $countitms = $r[0]['count'];
278 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
279 WHERE `contact-id` = %d
280 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
281 intval($uinfo[0]['id'])
283 $countitms = $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_SHARING),
292 intval(CONTACT_IS_FRIEND)
294 $countfriends = $r[0]['count'];
296 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
297 WHERE `uid` = %d AND `rel` IN ( %d, %d )
298 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
299 intval($uinfo[0]['uid']),
300 intval(CONTACT_IS_FOLLOWER),
301 intval(CONTACT_IS_FRIEND)
303 $countfollowers = $r[0]['count'];
305 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
306 intval($uinfo[0]['uid'])
308 $starred = $r[0]['count'];
311 if(! $uinfo[0]['self']) {
318 'id' => intval($uinfo[0]['cid']),
319 'self' => intval($uinfo[0]['self']),
320 'uid' => intval($uinfo[0]['uid']),
321 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
322 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
323 'location' => ($usr) ? $usr[0]['default-location'] : '',
324 'profile_image_url' => $uinfo[0]['micro'],
325 'url' => $uinfo[0]['url'],
326 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
327 'protected' => false,
328 'friends_count' => intval($countfriends),
329 'created_at' => api_date($uinfo[0]['name-date']),
330 'utc_offset' => "+00:00",
331 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
332 'geo_enabled' => false,
333 'statuses_count' => intval($countitms), #XXX: fix me
334 'lang' => 'en', #XXX: fix me
335 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
336 'followers_count' => intval($countfollowers),
337 'favourites_count' => intval($starred),
338 'contributors_enabled' => false,
339 'follow_request_sent' => true,
340 'profile_background_color' => 'cfe8f6',
341 'profile_text_color' => '000000',
342 'profile_link_color' => 'FF8500',
343 'profile_sidebar_fill_color' =>'AD0066',
344 'profile_sidebar_border_color' => 'AD0066',
345 'profile_background_image_url' => '',
346 'profile_background_tile' => false,
347 'profile_use_background_image' => false,
348 'notifications' => false,
349 'following' => '', #XXX: fix me
350 'verified' => true, #XXX: fix me
358 function api_item_get_user(&$a, $item) {
361 // The author is our direct contact, in a conversation with us.
362 if(link_compare($item['url'],$item['author-link'])) {
363 return api_get_user($a,$item['cid']);
366 // The author may be a contact of ours, but is replying to somebody else.
367 // Figure out if we know him/her.
368 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
369 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
370 return api_get_user($a,$a->contacts[$normalised]['id']);
372 // We don't know this person directly.
374 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
375 $name=str_replace(")","",$name);
383 // Generating a random ID
384 if (is_null($usercache[$nick]) or !array_key_exists($nick, $usercache))
385 $usercache[$nick] = mt_rand(2000000, 2100000);
388 'id' => $usercache[$nick],
390 'screen_name' => $nick,
391 'location' => '', //$uinfo[0]['default-location'],
393 'profile_image_url' => $item['author-avatar'],
394 'url' => $item['author-link'],
395 'protected' => false, #
396 'followers_count' => 0,
397 'friends_count' => 0,
399 'favourites_count' => 0,
400 'utc_offset' => 0, #XXX: fix me
401 'time_zone' => '', //$uinfo[0]['timezone'],
402 'statuses_count' => 0,
404 'statusnet_blocking' => false,
405 'notifications' => false,
408 'geo_enabled' => false,
409 'lang' => 'en', #XXX: fix me
410 'contributors_enabled' => false,
411 'follow_request_sent' => false,
412 'profile_background_color' => 'cfe8f6',
413 'profile_text_color' => '000000',
414 'profile_link_color' => 'FF8500',
415 'profile_sidebar_fill_color' =>'AD0066',
416 'profile_sidebar_border_color' => 'AD0066',
417 'profile_background_image_url' => '',
418 'profile_background_tile' => false,
419 'profile_use_background_image' => false,
420 'verified' => true, #XXX: fix me
421 'followers' => '', #XXX: fix me
430 * load api $templatename for $type and replace $data array
432 function api_apply_template($templatename, $type, $data){
440 $data = array_xmlify($data);
441 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
442 $ret = replace_macros($tpl, $data);
456 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
457 * returns a 401 status code and an error message if not.
458 * http://developer.twitter.com/doc/get/account/verify_credentials
460 function api_account_verify_credentials(&$a, $type){
461 if (local_user()===false) return false;
462 $user_info = api_get_user($a);
464 return api_apply_template("user", $type, array('$user' => $user_info));
467 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
471 * get data from $_POST or $_GET
473 function requestdata($k){
474 if (isset($_POST[$k])){
477 if (isset($_GET[$k])){
483 /*Waitman Gobble Mod*/
484 function api_statuses_mediap(&$a, $type) {
485 if (local_user()===false) {
486 logger('api_statuses_update: no user');
489 $user_info = api_get_user($a);
491 $_REQUEST['type'] = 'wall';
492 $_REQUEST['profile_uid'] = local_user();
493 $_REQUEST['api_source'] = true;
494 $txt = requestdata('status');
495 //$txt = urldecode(requestdata('status'));
497 require_once('library/HTMLPurifier.auto.php');
498 require_once('include/html2bbcode.php');
500 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
501 $txt = html2bb_video($txt);
502 $config = HTMLPurifier_Config::createDefault();
503 $config->set('Cache.DefinitionImpl', null);
504 $purifier = new HTMLPurifier($config);
505 $txt = $purifier->purify($txt);
507 $txt = html2bbcode($txt);
509 $a->argv[1]=$user_info['screen_name']; //should be set to username?
511 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
512 require_once('mod/wall_upload.php');
513 $bebop = wall_upload_post($a);
515 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
516 $_REQUEST['body']=$txt."\n\n".$bebop;
517 require_once('mod/item.php');
520 // this should output the last post (the one we just posted).
521 return api_status_show($a,$type);
523 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
524 /*Waitman Gobble Mod*/
527 function api_statuses_update(&$a, $type) {
528 if (local_user()===false) {
529 logger('api_statuses_update: no user');
532 $user_info = api_get_user($a);
534 // convert $_POST array items to the form we use for web posts.
536 // logger('api_post: ' . print_r($_POST,true));
538 if(requestdata('htmlstatus')) {
539 require_once('library/HTMLPurifier.auto.php');
540 require_once('include/html2bbcode.php');
542 $txt = requestdata('htmlstatus');
543 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
545 $txt = html2bb_video($txt);
547 $config = HTMLPurifier_Config::createDefault();
548 $config->set('Cache.DefinitionImpl', null);
551 $purifier = new HTMLPurifier($config);
552 $txt = $purifier->purify($txt);
554 $_REQUEST['body'] = html2bbcode($txt);
559 $_REQUEST['body'] = requestdata('status');
560 //$_REQUEST['body'] = urldecode(requestdata('status'));
562 $parent = requestdata('in_reply_to_status_id');
563 if(ctype_digit($parent))
564 $_REQUEST['parent'] = $parent;
566 $_REQUEST['parent_uri'] = $parent;
568 if(requestdata('lat') && requestdata('long'))
569 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
570 $_REQUEST['profile_uid'] = local_user();
573 $_REQUEST['type'] = 'net-comment';
575 $_REQUEST['type'] = 'wall';
576 if(x($_FILES,'media')) {
577 // upload the image if we have one
578 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
579 require_once('mod/wall_upload.php');
580 $media = wall_upload_post($a);
582 $_REQUEST['body'] .= "\n\n".$media;
586 // set this so that the item_post() function is quiet and doesn't redirect or emit json
588 $_REQUEST['api_source'] = true;
590 // call out normal post function
592 require_once('mod/item.php');
595 // this should output the last post (the one we just posted).
596 return api_status_show($a,$type);
598 api_register_func('api/statuses/update','api_statuses_update', true);
601 function api_status_show(&$a, $type){
602 $user_info = api_get_user($a);
603 // get last public wall message
604 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
605 FROM `item`, `contact`,
606 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
607 WHERE `item`.`contact-id` = %d
608 AND `i`.`id` = `item`.`parent`
609 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
610 AND `type`!='activity'
611 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
612 ORDER BY `created` DESC
614 intval($user_info['id'])
617 if (count($lastwall)>0){
618 $lastwall = $lastwall[0];
620 $in_reply_to_status_id = '';
621 $in_reply_to_user_id = '';
622 $in_reply_to_screen_name = '';
623 if ($lastwall['parent']!=$lastwall['id']) {
624 $in_reply_to_status_id=$lastwall['parent'];
625 $in_reply_to_user_id = $lastwall['reply_uid'];
626 $in_reply_to_screen_name = $lastwall['reply_author'];
628 $status_info = array(
629 'text' => html2plain(bbcode($lastwall['body']), 0),
630 'truncated' => false,
631 'created_at' => api_date($lastwall['created']),
632 'in_reply_to_status_id' => $in_reply_to_status_id,
633 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
634 'id' => $lastwall['contact-id'],
635 'in_reply_to_user_id' => $in_reply_to_user_id,
636 'in_reply_to_screen_name' => $in_reply_to_screen_name,
638 'favorited' => false,
639 'coordinates' => $lastwall['coord'],
640 'place' => $lastwall['location'],
643 $status_info['user'] = $user_info;
645 return api_apply_template("status", $type, array('$status' => $status_info));
654 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
655 * The author's most recent status will be returned inline.
656 * http://developer.twitter.com/doc/get/users/show
658 function api_users_show(&$a, $type){
659 $user_info = api_get_user($a);
660 // get last public wall message
661 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
662 FROM `item`, `contact`,
663 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
664 WHERE `item`.`contact-id` = %d
665 AND `i`.`id` = `item`.`parent`
666 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
667 AND `type`!='activity'
668 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
669 ORDER BY `created` DESC
671 intval($user_info['id'])
674 if (count($lastwall)>0){
675 $lastwall = $lastwall[0];
677 $in_reply_to_status_id = '';
678 $in_reply_to_user_id = '';
679 $in_reply_to_screen_name = '';
680 if ($lastwall['parent']!=$lastwall['id']) {
681 $in_reply_to_status_id=$lastwall['parent'];
682 $in_reply_to_user_id = $lastwall['reply_uid'];
683 $in_reply_to_screen_name = $lastwall['reply_author'];
685 $user_info['status'] = array(
686 'created_at' => api_date($lastwall['created']),
687 'id' => $lastwall['contact-id'],
688 'text' => html2plain(bbcode($lastwall['body']), 0),
689 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
690 'truncated' => false,
691 'in_reply_to_status_id' => $in_reply_to_status_id,
692 'in_reply_to_user_id' => $in_reply_to_user_id,
693 'favorited' => false,
694 'in_reply_to_screen_name' => $in_reply_to_screen_name,
696 'coordinates' => $lastwall['coord'],
697 'place' => $lastwall['location'],
701 return api_apply_template("user", $type, array('$user' => $user_info));
704 api_register_func('api/users/show','api_users_show');
708 * http://developer.twitter.com/doc/get/statuses/home_timeline
710 * TODO: Optional parameters
711 * TODO: Add reply info
713 function api_statuses_home_timeline(&$a, $type){
714 if (local_user()===false) return false;
716 $user_info = api_get_user($a);
717 // get last newtork messages
721 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
722 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
723 if ($page<0) $page=0;
724 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
725 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
726 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
727 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
729 $start = $page*$count;
731 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
735 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
736 if ($exclude_replies > 0)
737 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
739 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
740 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
741 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
742 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
743 FROM `item`, `contact`
744 WHERE `item`.`uid` = %d
745 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
746 AND `contact`.`id` = `item`.`contact-id`
747 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
750 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
751 intval($user_info['uid']),
753 intval($start), intval($count)
756 $ret = api_format_items($r,$user_info);
758 // We aren't going to try to figure out at the item, group, and page
759 // level which items you've seen and which you haven't. If you're looking
760 // at the network timeline just mark everything seen.
762 $r = q("UPDATE `item` SET `unseen` = 0
763 WHERE `unseen` = 1 AND `uid` = %d",
764 intval($user_info['uid'])
768 $data = array('$statuses' => $ret);
772 $data = api_rss_extra($a, $data, $user_info);
775 $as = api_format_as($a, $ret, $user_info);
776 $as['title'] = $a->config['sitename']." Home Timeline";
777 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
782 return api_apply_template("timeline", $type, $data);
784 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
785 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
787 function api_statuses_public_timeline(&$a, $type){
788 if (local_user()===false) return false;
790 $user_info = api_get_user($a);
791 // get last newtork messages
795 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
796 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
797 if ($page<0) $page=0;
798 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
799 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
800 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
802 $start = $page*$count;
804 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
807 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
809 /*$r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
810 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
811 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
812 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
813 FROM `item`, `contact`
814 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
815 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
816 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
817 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
818 AND `contact`.`id` = `item`.`contact-id`
819 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
822 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
824 intval($start), intval($count)
826 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
827 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
828 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
829 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
830 `user`.`nickname`, `user`.`hidewall`
831 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
832 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
833 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
834 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
835 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
836 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
837 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
840 ORDER BY `received` DESC LIMIT %d, %d ",
845 $ret = api_format_items($r,$user_info);
848 $data = array('$statuses' => $ret);
852 $data = api_rss_extra($a, $data, $user_info);
855 $as = api_format_as($a, $ret, $user_info);
856 $as['title'] = $a->config['sitename']." Public Timeline";
857 $as['link']['url'] = $a->get_baseurl()."/";
862 return api_apply_template("timeline", $type, $data);
864 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
869 function api_statuses_show(&$a, $type){
870 if (local_user()===false) return false;
872 $user_info = api_get_user($a);
875 $id = intval($a->argv[3]);
877 logger('API: api_statuses_show: '.$id);
879 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
880 $conversation = (x($_REQUEST,'conversation')?1:0);
884 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
886 $sql_extra .= " AND `item`.`id` = %d";
888 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
889 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
890 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
891 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
892 FROM `item`, `contact`
893 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
894 AND `contact`.`id` = `item`.`contact-id`
895 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
900 $ret = api_format_items($r,$user_info);
903 $data = array('$statuses' => $ret);
904 return api_apply_template("timeline", $type, $data);
906 $data = array('$status' => $ret[0]);
910 $data = api_rss_extra($a, $data, $user_info);
912 return api_apply_template("status", $type, $data);
915 api_register_func('api/statuses/show','api_statuses_show', true);
921 function api_statuses_repeat(&$a, $type){
922 if (local_user()===false) return false;
924 $user_info = api_get_user($a);
927 $id = intval($a->argv[3]);
929 logger('API: api_statuses_repeat: '.$id);
931 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
933 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
934 `contact`.`name`, `contact`.`photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
935 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
936 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
937 FROM `item`, `contact`
938 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
939 AND `contact`.`id` = `item`.`contact-id`
940 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
946 if ($r[0]['body'] != "") {
947 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
948 $_REQUEST['profile_uid'] = local_user();
949 $_REQUEST['type'] = 'wall';
950 $_REQUEST['api_source'] = true;
952 require_once('mod/item.php');
961 return api_apply_template('test', $type, array('$ok' => $ok));
963 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
968 function api_statuses_destroy(&$a, $type){
969 if (local_user()===false) return false;
971 $user_info = api_get_user($a);
974 $id = intval($a->argv[3]);
976 logger('API: api_statuses_destroy: '.$id);
978 require_once('include/items.php');
979 drop_item($id, false);
986 return api_apply_template('test', $type, array('$ok' => $ok));
988 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
992 * http://developer.twitter.com/doc/get/statuses/mentions
995 function api_statuses_mentions(&$a, $type){
996 if (local_user()===false) return false;
998 $user_info = api_get_user($a);
999 // get last newtork messages
1003 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1004 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1005 if ($page<0) $page=0;
1006 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1007 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1008 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1010 $start = $page*$count;
1012 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1014 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1015 $myurl = substr($myurl,strpos($myurl,'://')+3);
1016 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1017 $diasp_url = str_replace('/profile/','/u/',$myurl);
1019 if (get_config('system','use_fulltext_engine'))
1020 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where (MATCH(`author-link`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(`tag`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(tag) AGAINST ('".'"%s"'."' in boolean mode))) ",
1021 dbesc(protect_sprintf($myurl)),
1022 dbesc(protect_sprintf($myurl)),
1023 dbesc(protect_sprintf($diasp_url))
1026 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where ( `author-link` like '%s' or `tag` like '%s' or tag like '%s' )) ",
1027 dbesc(protect_sprintf('%' . $myurl)),
1028 dbesc(protect_sprintf('%' . $myurl . ']%')),
1029 dbesc(protect_sprintf('%' . $diasp_url . ']%'))
1033 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1035 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1036 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1037 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1038 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1039 FROM `item`, `contact`
1040 WHERE `item`.`uid` = %d
1041 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1042 AND `contact`.`id` = `item`.`contact-id`
1043 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1046 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1047 intval($user_info['uid']),
1049 intval($start), intval($count)
1052 $ret = api_format_items($r,$user_info);
1055 $data = array('$statuses' => $ret);
1059 $data = api_rss_extra($a, $data, $user_info);
1062 $as = api_format_as($a, $ret, $user_info);
1063 $as["title"] = $a->config['sitename']." Mentions";
1064 $as['link']['url'] = $a->get_baseurl()."/";
1069 return api_apply_template("timeline", $type, $data);
1071 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1072 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1075 function api_statuses_user_timeline(&$a, $type){
1076 if (local_user()===false) return false;
1078 $user_info = api_get_user($a);
1079 // get last newtork messages
1082 logger("api_statuses_user_timeline: local_user: ". local_user() .
1083 "\nuser_info: ".print_r($user_info, true) .
1084 "\n_REQUEST: ".print_r($_REQUEST, true),
1088 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1089 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1090 if ($page<0) $page=0;
1091 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1092 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1093 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1095 $start = $page*$count;
1098 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1099 if ($exclude_replies > 0) $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1101 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1102 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1103 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1104 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1105 FROM `item`, `contact`
1106 WHERE `item`.`uid` = %d
1107 AND `item`.`contact-id` = %d
1108 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1109 AND `contact`.`id` = `item`.`contact-id`
1110 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1113 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1114 intval(local_user()),
1115 intval($user_info['id']),
1117 intval($start), intval($count)
1120 $ret = api_format_items($r,$user_info);
1123 $data = array('$statuses' => $ret);
1127 $data = api_rss_extra($a, $data, $user_info);
1130 return api_apply_template("timeline", $type, $data);
1133 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1136 function api_favorites(&$a, $type){
1137 if (local_user()===false) return false;
1139 $user_info = api_get_user($a);
1140 // in friendica starred item are private
1141 // return favorites only for self
1142 logger('api_favorites: self:' . $user_info['self']);
1144 if ($user_info['self']==0) {
1150 $count = (x($_GET,'count')?$_GET['count']:20);
1151 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1152 if ($page<0) $page=0;
1154 $start = $page*$count;
1156 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1157 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1158 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1159 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1160 FROM `item`, `contact`
1161 WHERE `item`.`uid` = %d
1162 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1163 AND `item`.`starred` = 1
1164 AND `contact`.`id` = `item`.`contact-id`
1165 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1167 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1168 intval($user_info['uid']),
1169 intval($start), intval($count)
1172 $ret = api_format_items($r,$user_info);
1176 $data = array('$statuses' => $ret);
1180 $data = api_rss_extra($a, $data, $user_info);
1183 return api_apply_template("timeline", $type, $data);
1186 api_register_func('api/favorites','api_favorites', true);
1188 function api_format_as($a, $ret, $user_info) {
1191 $as['title'] = $a->config['sitename']." Public Timeline";
1193 foreach ($ret as $item) {
1194 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1195 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1196 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1197 $avatar[0]["rel"] = "avatar";
1198 $avatar[0]["type"] = "";
1199 $avatar[0]["width"] = 96;
1200 $avatar[0]["height"] = 96;
1201 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1202 $avatar[1]["rel"] = "avatar";
1203 $avatar[1]["type"] = "";
1204 $avatar[1]["width"] = 48;
1205 $avatar[1]["height"] = 48;
1206 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1207 $avatar[2]["rel"] = "avatar";
1208 $avatar[2]["type"] = "";
1209 $avatar[2]["width"] = 24;
1210 $avatar[2]["height"] = 24;
1211 $singleitem["actor"]["avatarLinks"] = $avatar;
1213 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1214 $singleitem["actor"]["image"]["rel"] = "avatar";
1215 $singleitem["actor"]["image"]["type"] = "";
1216 $singleitem["actor"]["image"]["width"] = 96;
1217 $singleitem["actor"]["image"]["height"] = 96;
1218 $singleitem["actor"]["type"] = "person";
1219 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1220 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1221 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1222 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1223 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1224 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1225 $singleitem["actor"]["contact"]["addresses"] = "";
1227 $singleitem["body"] = $item["text"];
1228 $singleitem["object"]["displayName"] = $item["text"];
1229 $singleitem["object"]["id"] = $item["url"];
1230 $singleitem["object"]["type"] = "note";
1231 $singleitem["object"]["url"] = $item["url"];
1232 //$singleitem["context"] =;
1233 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1234 $singleitem["provider"]["objectType"] = "service";
1235 $singleitem["provider"]["displayName"] = "Test";
1236 $singleitem["provider"]["url"] = "http://test.tld";
1237 $singleitem["title"] = $item["text"];
1238 $singleitem["verb"] = "post";
1239 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1240 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1241 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1242 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1243 //$singleitem["original"] = $item;
1244 $items[] = $singleitem;
1246 $as['items'] = $items;
1247 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1248 $as['link']['rel'] = "alternate";
1249 $as['link']['type'] = "text/html";
1253 function api_format_messages($item, $recipient, $sender) {
1254 // standard meta information
1256 'id' => $item['id'],
1257 'created_at' => api_date($item['created']),
1258 'sender_id' => $sender['id'] ,
1259 'sender_screen_name' => $sender['screen_name'],
1260 'sender' => $sender,
1261 'recipient_id' => $recipient['id'],
1262 'recipient_screen_name' => $recipient['screen_name'],
1263 'recipient' => $recipient,
1266 //don't send title to regular StatusNET requests to avoid confusing these apps
1267 if (x($_GET, 'getText')) {
1268 $ret['title'] = $item['title'] ;
1269 if ($_GET["getText"] == "html") {
1270 $ret['text'] = bbcode($item['body']);
1272 elseif ($_GET["getText"] == "plain") {
1273 $ret['text'] = html2plain(bbcode($item['body']), 0);
1277 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body']), 0);
1279 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1280 unset($ret['sender']);
1281 unset($ret['recipient']);
1287 function api_format_items($r,$user_info) {
1289 //logger('api_format_items: ' . print_r($r,true));
1291 //logger('api_format_items: ' . print_r($user_info,true));
1296 foreach($r as $item) {
1297 localize_item($item);
1298 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
1300 if ($item['parent']!=$item['id']) {
1301 $r = q("select id from item where parent=%s and id<%s order by id desc limit 1",
1302 intval($item['parent']), intval($item['id']));
1304 $in_reply_to_status_id = $r[0]['id'];
1306 $in_reply_to_status_id = $item['parent'];
1308 $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact
1309 where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id));
1311 $in_reply_to_screen_name = $r[0]['author-name'];
1312 $in_reply_to_user_id = $r[0]['contact-id'];
1315 $in_reply_to_screen_name = '';
1316 $in_reply_to_user_id = 0;
1317 $in_reply_to_status_id = 0;
1320 // Workaround for ostatus messages where the title is identically to the body
1321 $statusbody = trim(html2plain(bbcode($item['body']), 0));
1322 $statustitle = trim($item['title']);
1324 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1325 $statustext = trim($statusbody);
1327 $statustext = trim($statustitle."\n\n".$statusbody);
1329 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1330 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1333 'text' => $statustext,
1334 'truncated' => False,
1335 'created_at'=> api_date($item['created']),
1336 'in_reply_to_status_id' => $in_reply_to_status_id,
1337 'source' => (($item['app']) ? $item['app'] : 'web'),
1338 'id' => intval($item['id']),
1339 'in_reply_to_user_id' => $in_reply_to_user_id,
1340 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1342 'favorited' => $item['starred'] ? true : false,
1343 'user' => $status_user ,
1344 'statusnet_html' => trim(bbcode($item['body'])),
1345 'statusnet_conversation_id' => $item['parent'],
1348 // Seesmic doesn't like the following content
1349 if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1351 'updated' => api_date($item['edited']),
1352 'published' => api_date($item['created']),
1353 'message_id' => $item['uri'],
1354 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1355 'coordinates' => $item['coord'],
1356 'place' => $item['location'],
1357 'contributors' => '',
1358 'annotations' => '',
1360 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1361 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1362 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1363 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1366 $status = array_merge($status, $status2);
1375 function api_account_rate_limit_status(&$a,$type) {
1378 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1379 'remaining_hits' => (string) 150,
1380 'hourly_limit' => (string) 150,
1381 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1384 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1386 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1389 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1391 function api_help_test(&$a,$type) {
1398 return api_apply_template('test', $type, array('$ok' => $ok));
1401 api_register_func('api/help/test','api_help_test',true);
1404 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1405 * This function is deprecated by Twitter
1406 * returns: json, xml
1408 function api_statuses_f(&$a, $type, $qtype) {
1409 if (local_user()===false) return false;
1410 $user_info = api_get_user($a);
1413 // friends and followers only for self
1414 if ($user_info['self']==0){
1418 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1419 /* this is to stop Hotot to load friends multiple times
1420 * I'm not sure if I'm missing return something or
1421 * is a bug in hotot. Workaround, meantime
1425 return array('$users' => $ret);*/
1429 if($qtype == 'friends')
1430 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1431 if($qtype == 'followers')
1432 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1434 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1435 intval(local_user())
1439 foreach($r as $cid){
1440 $ret[] = api_get_user($a, $cid['id']);
1444 return array('$users' => $ret);
1447 function api_statuses_friends(&$a, $type){
1448 $data = api_statuses_f($a,$type,"friends");
1449 if ($data===false) return false;
1450 return api_apply_template("friends", $type, $data);
1452 function api_statuses_followers(&$a, $type){
1453 $data = api_statuses_f($a,$type,"followers");
1454 if ($data===false) return false;
1455 return api_apply_template("friends", $type, $data);
1457 api_register_func('api/statuses/friends','api_statuses_friends',true);
1458 api_register_func('api/statuses/followers','api_statuses_followers',true);
1465 function api_statusnet_config(&$a,$type) {
1466 $name = $a->config['sitename'];
1467 $server = $a->get_hostname();
1468 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1469 $email = $a->config['admin_email'];
1470 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1471 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1472 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1473 if($a->config['api_import_size'])
1474 $texlimit = string($a->config['api_import_size']);
1475 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1476 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1479 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1480 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1481 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1482 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1483 'shorturllength' => '30',
1484 'friendica' => array(
1485 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1486 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1487 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1488 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1493 return api_apply_template('config', $type, array('$config' => $config));
1496 api_register_func('api/statusnet/config','api_statusnet_config',false);
1498 function api_statusnet_version(&$a,$type) {
1502 if($type === 'xml') {
1503 header("Content-type: application/xml");
1504 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1507 elseif($type === 'json') {
1508 header("Content-type: application/json");
1513 api_register_func('api/statusnet/version','api_statusnet_version',false);
1516 function api_ff_ids(&$a,$type,$qtype) {
1520 if($qtype == 'friends')
1521 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1522 if($qtype == 'followers')
1523 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1526 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1527 intval(local_user())
1531 if($type === 'xml') {
1532 header("Content-type: application/xml");
1533 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1535 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1536 echo '</ids>' . "\r\n";
1539 elseif($type === 'json') {
1541 header("Content-type: application/json");
1542 foreach($r as $rr) $ret[] = $rr['id'];
1543 echo json_encode($ret);
1549 function api_friends_ids(&$a,$type) {
1550 api_ff_ids($a,$type,'friends');
1552 function api_followers_ids(&$a,$type) {
1553 api_ff_ids($a,$type,'followers');
1555 api_register_func('api/friends/ids','api_friends_ids',true);
1556 api_register_func('api/followers/ids','api_followers_ids',true);
1559 function api_direct_messages_new(&$a, $type) {
1560 if (local_user()===false) return false;
1562 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1564 $sender = api_get_user($a);
1566 require_once("include/message.php");
1568 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1569 intval(local_user()),
1570 dbesc($_POST['screen_name']));
1572 $recipient = api_get_user($a, $r[0]['id']);
1575 if (x($_REQUEST,'replyto')) {
1576 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1577 intval(local_user()),
1578 intval($_REQUEST['replyto']));
1579 $replyto = $r[0]['parent-uri'];
1580 $sub = $r[0]['title'];
1583 if (x($_REQUEST,'title')) {
1584 $sub = $_REQUEST['title'];
1587 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1591 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1594 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1595 $ret = api_format_messages($r[0], $recipient, $sender);
1598 $ret = array("error"=>$id);
1601 $data = Array('$messages'=>$ret);
1606 $data = api_rss_extra($a, $data, $user_info);
1609 return api_apply_template("direct_messages", $type, $data);
1612 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1614 function api_direct_messages_box(&$a, $type, $box) {
1615 if (local_user()===false) return false;
1617 $user_info = api_get_user($a);
1620 $count = (x($_GET,'count')?$_GET['count']:20);
1621 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1622 if ($page<0) $page=0;
1624 $start = $page*$count;
1626 $profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1627 if ($box=="sentbox") {
1628 $sql_extra = "`from-url`='".dbesc( $profile_url )."'";
1630 elseif ($box=="conversation") {
1631 $sql_extra = "`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1633 elseif ($box=="all") {
1634 $sql_extra = "true";
1636 elseif ($box=="inbox") {
1637 $sql_extra = "`from-url`!='".dbesc( $profile_url )."'";
1640 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1641 intval(local_user()),
1642 intval($start), intval($count)
1646 foreach($r as $item) {
1647 if ($box == "inbox" || $item['from-url'] != $profile_url){
1648 $recipient = $user_info;
1649 $sender = api_get_user($a,$item['contact-id']);
1651 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1652 $recipient = api_get_user($a,$item['contact-id']);
1653 $sender = $user_info;
1656 $ret[]=api_format_messages($item, $recipient, $sender);
1660 $data = array('$messages' => $ret);
1664 $data = api_rss_extra($a, $data, $user_info);
1667 return api_apply_template("direct_messages", $type, $data);
1671 function api_direct_messages_sentbox(&$a, $type){
1672 return api_direct_messages_box($a, $type, "sentbox");
1674 function api_direct_messages_inbox(&$a, $type){
1675 return api_direct_messages_box($a, $type, "inbox");
1677 function api_direct_messages_all(&$a, $type){
1678 return api_direct_messages_box($a, $type, "all");
1680 function api_direct_messages_conversation(&$a, $type){
1681 return api_direct_messages_box($a, $type, "conversation");
1683 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1684 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1685 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1686 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1690 function api_oauth_request_token(&$a, $type){
1692 $oauth = new FKOAuth1();
1693 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1694 }catch(Exception $e){
1695 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1700 function api_oauth_access_token(&$a, $type){
1702 $oauth = new FKOAuth1();
1703 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1704 }catch(Exception $e){
1705 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1711 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1712 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1715 Not implemented by now:
1719 statuses/retweets_of_me
1724 account/update_location
1725 account/update_profile_background_image
1726 account/update_profile_image
1730 Not implemented in status.net:
1731 statuses/retweeted_to_me
1732 statuses/retweeted_by_me
1733 direct_messages/destroy
1735 account/update_delivery_device
1736 notifications/follow