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);
759 $data = array('$statuses' => $ret);
763 $data = api_rss_extra($a, $data, $user_info);
766 $as = api_format_as($a, $ret, $user_info);
767 $as['title'] = $a->config['sitename']." Home Timeline";
768 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
773 return api_apply_template("timeline", $type, $data);
775 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
776 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
778 function api_statuses_public_timeline(&$a, $type){
779 if (local_user()===false) return false;
781 $user_info = api_get_user($a);
782 // get last newtork messages
786 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
787 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
788 if ($page<0) $page=0;
789 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
790 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
791 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
793 $start = $page*$count;
795 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
798 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
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`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
806 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
807 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
808 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
809 AND `contact`.`id` = `item`.`contact-id`
810 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
813 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
815 intval($start), intval($count)
817 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
818 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
819 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
820 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
821 `user`.`nickname`, `user`.`hidewall`
822 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
823 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
824 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
825 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
826 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
827 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
828 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
831 ORDER BY `received` DESC LIMIT %d, %d ",
836 $ret = api_format_items($r,$user_info);
839 $data = array('$statuses' => $ret);
843 $data = api_rss_extra($a, $data, $user_info);
846 $as = api_format_as($a, $ret, $user_info);
847 $as['title'] = $a->config['sitename']." Public Timeline";
848 $as['link']['url'] = $a->get_baseurl()."/";
853 return api_apply_template("timeline", $type, $data);
855 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
860 function api_statuses_show(&$a, $type){
861 if (local_user()===false) return false;
863 $user_info = api_get_user($a);
866 $id = intval($a->argv[3]);
868 logger('API: api_statuses_show: '.$id);
870 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
871 $conversation = (x($_REQUEST,'conversation')?1:0);
875 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
877 $sql_extra .= " AND `item`.`id` = %d";
879 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
880 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
881 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
882 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
883 FROM `item`, `contact`
884 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
885 AND `contact`.`id` = `item`.`contact-id`
886 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
891 $ret = api_format_items($r,$user_info);
894 $data = array('$statuses' => $ret);
895 return api_apply_template("timeline", $type, $data);
897 $data = array('$status' => $ret[0]);
901 $data = api_rss_extra($a, $data, $user_info);
903 return api_apply_template("status", $type, $data);
906 api_register_func('api/statuses/show','api_statuses_show', true);
912 function api_statuses_repeat(&$a, $type){
913 if (local_user()===false) return false;
915 $user_info = api_get_user($a);
918 $id = intval($a->argv[3]);
920 logger('API: api_statuses_repeat: '.$id);
922 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
924 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
925 `contact`.`name`, `contact`.`photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
926 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
927 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
928 FROM `item`, `contact`
929 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
930 AND `contact`.`id` = `item`.`contact-id`
931 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
937 if ($r[0]['body'] != "") {
938 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
939 $_REQUEST['profile_uid'] = local_user();
940 $_REQUEST['type'] = 'wall';
941 $_REQUEST['api_source'] = true;
943 require_once('mod/item.php');
952 return api_apply_template('test', $type, array('$ok' => $ok));
954 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
959 function api_statuses_destroy(&$a, $type){
960 if (local_user()===false) return false;
962 $user_info = api_get_user($a);
965 $id = intval($a->argv[3]);
967 logger('API: api_statuses_destroy: '.$id);
969 require_once('include/items.php');
970 drop_item($id, false);
977 return api_apply_template('test', $type, array('$ok' => $ok));
979 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
983 * http://developer.twitter.com/doc/get/statuses/mentions
986 function api_statuses_mentions(&$a, $type){
987 if (local_user()===false) return false;
989 $user_info = api_get_user($a);
990 // get last newtork messages
994 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
995 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
996 if ($page<0) $page=0;
997 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
998 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
999 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1001 $start = $page*$count;
1003 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1005 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1006 $myurl = substr($myurl,strpos($myurl,'://')+3);
1007 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1008 $diasp_url = str_replace('/profile/','/u/',$myurl);
1010 if (get_config('system','use_fulltext_engine'))
1011 $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))) ",
1012 dbesc(protect_sprintf($myurl)),
1013 dbesc(protect_sprintf($myurl)),
1014 dbesc(protect_sprintf($diasp_url))
1017 $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' )) ",
1018 dbesc(protect_sprintf('%' . $myurl)),
1019 dbesc(protect_sprintf('%' . $myurl . ']%')),
1020 dbesc(protect_sprintf('%' . $diasp_url . ']%'))
1024 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1026 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1027 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1028 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1029 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1030 FROM `item`, `contact`
1031 WHERE `item`.`uid` = %d
1032 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1033 AND `contact`.`id` = `item`.`contact-id`
1034 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1037 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1038 intval($user_info['uid']),
1040 intval($start), intval($count)
1043 $ret = api_format_items($r,$user_info);
1046 $data = array('$statuses' => $ret);
1050 $data = api_rss_extra($a, $data, $user_info);
1053 $as = api_format_as($a, $ret, $user_info);
1054 $as["title"] = $a->config['sitename']." Mentions";
1055 $as['link']['url'] = $a->get_baseurl()."/";
1060 return api_apply_template("timeline", $type, $data);
1062 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1063 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1066 function api_statuses_user_timeline(&$a, $type){
1067 if (local_user()===false) return false;
1069 $user_info = api_get_user($a);
1070 // get last newtork messages
1073 logger("api_statuses_user_timeline: local_user: ". local_user() .
1074 "\nuser_info: ".print_r($user_info, true) .
1075 "\n_REQUEST: ".print_r($_REQUEST, true),
1079 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1080 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1081 if ($page<0) $page=0;
1082 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1083 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1084 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1086 $start = $page*$count;
1089 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1090 if ($exclude_replies > 0) $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1092 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1093 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1094 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1095 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1096 FROM `item`, `contact`
1097 WHERE `item`.`uid` = %d
1098 AND `item`.`contact-id` = %d
1099 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1100 AND `contact`.`id` = `item`.`contact-id`
1101 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1104 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1105 intval(local_user()),
1106 intval($user_info['id']),
1108 intval($start), intval($count)
1111 $ret = api_format_items($r,$user_info);
1114 $data = array('$statuses' => $ret);
1118 $data = api_rss_extra($a, $data, $user_info);
1121 return api_apply_template("timeline", $type, $data);
1124 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1127 function api_favorites(&$a, $type){
1128 if (local_user()===false) return false;
1130 $user_info = api_get_user($a);
1131 // in friendica starred item are private
1132 // return favorites only for self
1133 logger('api_favorites: self:' . $user_info['self']);
1135 if ($user_info['self']==0) {
1141 $count = (x($_GET,'count')?$_GET['count']:20);
1142 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1143 if ($page<0) $page=0;
1145 $start = $page*$count;
1147 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1148 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1149 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1150 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1151 FROM `item`, `contact`
1152 WHERE `item`.`uid` = %d
1153 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1154 AND `item`.`starred` = 1
1155 AND `contact`.`id` = `item`.`contact-id`
1156 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1158 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1159 intval($user_info['uid']),
1160 intval($start), intval($count)
1163 $ret = api_format_items($r,$user_info);
1167 $data = array('$statuses' => $ret);
1171 $data = api_rss_extra($a, $data, $user_info);
1174 return api_apply_template("timeline", $type, $data);
1177 api_register_func('api/favorites','api_favorites', true);
1179 function api_format_as($a, $ret, $user_info) {
1182 $as['title'] = $a->config['sitename']." Public Timeline";
1184 foreach ($ret as $item) {
1185 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1186 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1187 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1188 $avatar[0]["rel"] = "avatar";
1189 $avatar[0]["type"] = "";
1190 $avatar[0]["width"] = 96;
1191 $avatar[0]["height"] = 96;
1192 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1193 $avatar[1]["rel"] = "avatar";
1194 $avatar[1]["type"] = "";
1195 $avatar[1]["width"] = 48;
1196 $avatar[1]["height"] = 48;
1197 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1198 $avatar[2]["rel"] = "avatar";
1199 $avatar[2]["type"] = "";
1200 $avatar[2]["width"] = 24;
1201 $avatar[2]["height"] = 24;
1202 $singleitem["actor"]["avatarLinks"] = $avatar;
1204 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1205 $singleitem["actor"]["image"]["rel"] = "avatar";
1206 $singleitem["actor"]["image"]["type"] = "";
1207 $singleitem["actor"]["image"]["width"] = 96;
1208 $singleitem["actor"]["image"]["height"] = 96;
1209 $singleitem["actor"]["type"] = "person";
1210 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1211 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1212 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1213 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1214 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1215 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1216 $singleitem["actor"]["contact"]["addresses"] = "";
1218 $singleitem["body"] = $item["text"];
1219 $singleitem["object"]["displayName"] = $item["text"];
1220 $singleitem["object"]["id"] = $item["url"];
1221 $singleitem["object"]["type"] = "note";
1222 $singleitem["object"]["url"] = $item["url"];
1223 //$singleitem["context"] =;
1224 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1225 $singleitem["provider"]["objectType"] = "service";
1226 $singleitem["provider"]["displayName"] = "Test";
1227 $singleitem["provider"]["url"] = "http://test.tld";
1228 $singleitem["title"] = $item["text"];
1229 $singleitem["verb"] = "post";
1230 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1231 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1232 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1233 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1234 //$singleitem["original"] = $item;
1235 $items[] = $singleitem;
1237 $as['items'] = $items;
1238 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1239 $as['link']['rel'] = "alternate";
1240 $as['link']['type'] = "text/html";
1244 function api_format_messages($item, $recipient, $sender) {
1245 // standard meta information
1247 'id' => $item['id'],
1248 'created_at' => api_date($item['created']),
1249 'sender_id' => $sender['id'] ,
1250 'sender_screen_name' => $sender['screen_name'],
1251 'sender' => $sender,
1252 'recipient_id' => $recipient['id'],
1253 'recipient_screen_name' => $recipient['screen_name'],
1254 'recipient' => $recipient,
1257 //don't send title to regular StatusNET requests to avoid confusing these apps
1258 if (x($_GET, 'getText')) {
1259 $ret['title'] = $item['title'] ;
1260 if ($_GET["getText"] == "html") {
1261 $ret['text'] = bbcode($item['body']);
1263 elseif ($_GET["getText"] == "plain") {
1264 $ret['text'] = html2plain(bbcode($item['body']), 0);
1268 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body']), 0);
1270 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1271 unset($ret['sender']);
1272 unset($ret['recipient']);
1278 function api_format_items($r,$user_info) {
1280 //logger('api_format_items: ' . print_r($r,true));
1282 //logger('api_format_items: ' . print_r($user_info,true));
1287 foreach($r as $item) {
1288 localize_item($item);
1289 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
1291 if ($item['parent']!=$item['id']) {
1292 $r = q("select id from item where parent=%s and id<%s order by id desc limit 1",
1293 intval($item['parent']), intval($item['id']));
1295 $in_reply_to_status_id = $r[0]['id'];
1297 $in_reply_to_status_id = $item['parent'];
1299 $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact
1300 where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id));
1302 $in_reply_to_screen_name = $r[0]['author-name'];
1303 $in_reply_to_user_id = $r[0]['contact-id'];
1306 $in_reply_to_screen_name = '';
1307 $in_reply_to_user_id = 0;
1308 $in_reply_to_status_id = 0;
1311 // Workaround for ostatus messages where the title is identically to the body
1312 $statusbody = trim(html2plain(bbcode($item['body']), 0));
1313 $statustitle = trim($item['title']);
1315 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1316 $statustext = trim($statusbody);
1318 $statustext = trim($statustitle."\n\n".$statusbody);
1320 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1321 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1324 'text' => $statustext,
1325 'truncated' => False,
1326 'created_at'=> api_date($item['created']),
1327 'in_reply_to_status_id' => $in_reply_to_status_id,
1328 'source' => (($item['app']) ? $item['app'] : 'web'),
1329 'id' => intval($item['id']),
1330 'in_reply_to_user_id' => $in_reply_to_user_id,
1331 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1333 'favorited' => $item['starred'] ? true : false,
1334 'user' => $status_user ,
1335 'statusnet_html' => trim(bbcode($item['body'])),
1336 'statusnet_conversation_id' => $item['parent'],
1339 // Seesmic doesn't like the following content
1340 if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1342 'updated' => api_date($item['edited']),
1343 'published' => api_date($item['created']),
1344 'message_id' => $item['uri'],
1345 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1346 'coordinates' => $item['coord'],
1347 'place' => $item['location'],
1348 'contributors' => '',
1349 'annotations' => '',
1351 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1352 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1353 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1354 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1357 $status = array_merge($status, $status2);
1366 function api_account_rate_limit_status(&$a,$type) {
1369 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1370 'remaining_hits' => (string) 150,
1371 'hourly_limit' => (string) 150,
1372 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1375 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1377 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1380 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1382 function api_help_test(&$a,$type) {
1389 return api_apply_template('test', $type, array('$ok' => $ok));
1392 api_register_func('api/help/test','api_help_test',true);
1395 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1396 * This function is deprecated by Twitter
1397 * returns: json, xml
1399 function api_statuses_f(&$a, $type, $qtype) {
1400 if (local_user()===false) return false;
1401 $user_info = api_get_user($a);
1404 // friends and followers only for self
1405 if ($user_info['self']==0){
1409 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1410 /* this is to stop Hotot to load friends multiple times
1411 * I'm not sure if I'm missing return something or
1412 * is a bug in hotot. Workaround, meantime
1416 return array('$users' => $ret);*/
1420 if($qtype == 'friends')
1421 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1422 if($qtype == 'followers')
1423 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1425 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1426 intval(local_user())
1430 foreach($r as $cid){
1431 $ret[] = api_get_user($a, $cid['id']);
1435 return array('$users' => $ret);
1438 function api_statuses_friends(&$a, $type){
1439 $data = api_statuses_f($a,$type,"friends");
1440 if ($data===false) return false;
1441 return api_apply_template("friends", $type, $data);
1443 function api_statuses_followers(&$a, $type){
1444 $data = api_statuses_f($a,$type,"followers");
1445 if ($data===false) return false;
1446 return api_apply_template("friends", $type, $data);
1448 api_register_func('api/statuses/friends','api_statuses_friends',true);
1449 api_register_func('api/statuses/followers','api_statuses_followers',true);
1456 function api_statusnet_config(&$a,$type) {
1457 $name = $a->config['sitename'];
1458 $server = $a->get_hostname();
1459 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1460 $email = $a->config['admin_email'];
1461 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1462 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1463 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1464 if($a->config['api_import_size'])
1465 $texlimit = string($a->config['api_import_size']);
1466 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1467 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1470 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1471 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1472 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1473 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1474 'shorturllength' => '30',
1475 'friendica' => array(
1476 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1477 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1478 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1479 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1484 return api_apply_template('config', $type, array('$config' => $config));
1487 api_register_func('api/statusnet/config','api_statusnet_config',false);
1489 function api_statusnet_version(&$a,$type) {
1493 if($type === 'xml') {
1494 header("Content-type: application/xml");
1495 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1498 elseif($type === 'json') {
1499 header("Content-type: application/json");
1504 api_register_func('api/statusnet/version','api_statusnet_version',false);
1507 function api_ff_ids(&$a,$type,$qtype) {
1511 if($qtype == 'friends')
1512 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1513 if($qtype == 'followers')
1514 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1517 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1518 intval(local_user())
1522 if($type === 'xml') {
1523 header("Content-type: application/xml");
1524 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1526 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1527 echo '</ids>' . "\r\n";
1530 elseif($type === 'json') {
1532 header("Content-type: application/json");
1533 foreach($r as $rr) $ret[] = $rr['id'];
1534 echo json_encode($ret);
1540 function api_friends_ids(&$a,$type) {
1541 api_ff_ids($a,$type,'friends');
1543 function api_followers_ids(&$a,$type) {
1544 api_ff_ids($a,$type,'followers');
1546 api_register_func('api/friends/ids','api_friends_ids',true);
1547 api_register_func('api/followers/ids','api_followers_ids',true);
1550 function api_direct_messages_new(&$a, $type) {
1551 if (local_user()===false) return false;
1553 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1555 $sender = api_get_user($a);
1557 require_once("include/message.php");
1559 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1560 intval(local_user()),
1561 dbesc($_POST['screen_name']));
1563 $recipient = api_get_user($a, $r[0]['id']);
1566 if (x($_REQUEST,'replyto')) {
1567 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1568 intval(local_user()),
1569 intval($_REQUEST['replyto']));
1570 $replyto = $r[0]['parent-uri'];
1571 $sub = $r[0]['title'];
1574 if (x($_REQUEST,'title')) {
1575 $sub = $_REQUEST['title'];
1578 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1582 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1585 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1586 $ret = api_format_messages($r[0], $recipient, $sender);
1589 $ret = array("error"=>$id);
1592 $data = Array('$messages'=>$ret);
1597 $data = api_rss_extra($a, $data, $user_info);
1600 return api_apply_template("direct_messages", $type, $data);
1603 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1605 function api_direct_messages_box(&$a, $type, $box) {
1606 if (local_user()===false) return false;
1608 $user_info = api_get_user($a);
1611 $count = (x($_GET,'count')?$_GET['count']:20);
1612 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1613 if ($page<0) $page=0;
1615 $start = $page*$count;
1617 $profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1618 if ($box=="sentbox") {
1619 $sql_extra = "`from-url`='".dbesc( $profile_url )."'";
1621 elseif ($box=="conversation") {
1622 $sql_extra = "`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1624 elseif ($box=="all") {
1625 $sql_extra = "true";
1627 elseif ($box=="inbox") {
1628 $sql_extra = "`from-url`!='".dbesc( $profile_url )."'";
1631 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1632 intval(local_user()),
1633 intval($start), intval($count)
1637 foreach($r as $item) {
1638 if ($box == "inbox" || $item['from-url'] != $profile_url){
1639 $recipient = $user_info;
1640 $sender = api_get_user($a,$item['contact-id']);
1642 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1643 $recipient = api_get_user($a,$item['contact-id']);
1644 $sender = $user_info;
1647 $ret[]=api_format_messages($item, $recipient, $sender);
1651 $data = array('$messages' => $ret);
1655 $data = api_rss_extra($a, $data, $user_info);
1658 return api_apply_template("direct_messages", $type, $data);
1662 function api_direct_messages_sentbox(&$a, $type){
1663 return api_direct_messages_box($a, $type, "sentbox");
1665 function api_direct_messages_inbox(&$a, $type){
1666 return api_direct_messages_box($a, $type, "inbox");
1668 function api_direct_messages_all(&$a, $type){
1669 return api_direct_messages_box($a, $type, "all");
1671 function api_direct_messages_conversation(&$a, $type){
1672 return api_direct_messages_box($a, $type, "conversation");
1674 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1675 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1676 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1677 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1681 function api_oauth_request_token(&$a, $type){
1683 $oauth = new FKOAuth1();
1684 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1685 }catch(Exception $e){
1686 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1691 function api_oauth_access_token(&$a, $type){
1693 $oauth = new FKOAuth1();
1694 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1695 }catch(Exception $e){
1696 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1702 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1703 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1706 Not implemented by now:
1710 statuses/retweets_of_me
1715 account/update_location
1716 account/update_profile_background_image
1717 account/update_profile_image
1721 Not implemented in status.net:
1722 statuses/retweeted_to_me
1723 statuses/retweeted_by_me
1724 direct_messages/destroy
1726 account/update_delivery_device
1727 notifications/follow