2 require_once("include/bbcode.php");
3 require_once("include/datetime.php");
4 require_once("include/conversation.php");
5 require_once("include/oauth.php");
6 require_once("include/html2plain.php");
16 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
17 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
18 // into a page, and visitors will post something without noticing it).
19 // Instead, use this function.
20 if ($_SESSION["allow_api"])
26 function api_date($str){
27 //Wed May 23 06:01:13 +0000 2007
28 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
32 function api_register_func($path, $func, $auth=false){
34 $API[$path] = array('func'=>$func,
42 function api_login(&$a){
45 $oauth = new FKOAuth1();
46 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
47 if (!is_null($token)){
48 $oauth->loginUser($token->uid);
49 call_hooks('logged_in', $a->user);
52 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
54 logger(__file__.__line__.__function__."\n".$e);
55 //die(__file__.__line__.__function__."<pre>".$e); die();
60 // workaround for HTTP-auth in CGI mode
61 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
62 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
63 if(strlen($userpass)) {
64 list($name, $password) = explode(':', $userpass);
65 $_SERVER['PHP_AUTH_USER'] = $name;
66 $_SERVER['PHP_AUTH_PW'] = $password;
70 if (!isset($_SERVER['PHP_AUTH_USER'])) {
71 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
72 header('WWW-Authenticate: Basic realm="Friendica"');
73 header('HTTP/1.0 401 Unauthorized');
74 die('This api requires login');
77 $user = $_SERVER['PHP_AUTH_USER'];
78 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
82 * next code from mod/auth.php. needs better solution
85 // process normal login request
87 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
88 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
96 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
97 header('WWW-Authenticate: Basic realm="Friendica"');
98 header('HTTP/1.0 401 Unauthorized');
99 die('This api requires login');
102 require_once('include/security.php');
103 authenticate_success($record); $_SESSION["allow_api"] = true;
105 call_hooks('logged_in', $a->user);
109 /**************************
110 * MAIN API ENTRY POINT *
111 **************************/
112 function api_call(&$a){
113 GLOBAL $API, $called_api;
118 foreach ($API as $p=>$info){
119 if (strpos($a->query_string, $p)===0){
120 $called_api= explode("/",$p);
121 //unset($_SERVER['PHP_AUTH_USER']);
122 if ($info['auth']===true && api_user()===false) {
126 load_contact_links(api_user());
128 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
129 logger('API parameters: ' . print_r($_REQUEST,true));
131 if (strpos($a->query_string, ".xml")>0) $type="xml";
132 if (strpos($a->query_string, ".json")>0) $type="json";
133 if (strpos($a->query_string, ".rss")>0) $type="rss";
134 if (strpos($a->query_string, ".atom")>0) $type="atom";
135 if (strpos($a->query_string, ".as")>0) $type="as";
137 $r = call_user_func($info['func'], $a, $type);
138 if ($r===false) return;
142 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
143 header ("Content-Type: text/xml");
144 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
147 //header ("Content-Type: application/json");
149 return json_encode($rr);
152 header ("Content-Type: application/rss+xml");
153 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
156 header ("Content-Type: application/atom+xml");
157 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
160 //header ("Content-Type: application/json");
162 // return json_encode($rr);
163 return json_encode($r);
167 //echo "<pre>"; var_dump($r); die();
170 header("HTTP/1.1 404 Not Found");
171 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
172 $r = '<status><error>not implemented</error></status>';
175 header ("Content-Type: text/xml");
176 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
179 header ("Content-Type: application/json");
180 return json_encode(array('error' => 'not implemented'));
183 header ("Content-Type: application/rss+xml");
184 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
187 header ("Content-Type: application/atom+xml");
188 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
196 function api_rss_extra(&$a, $arr, $user_info){
197 if (is_null($user_info)) $user_info = api_get_user($a);
198 $arr['$user'] = $user_info;
199 $arr['$rss'] = array(
200 'alternate' => $user_info['url'],
201 'self' => $a->get_baseurl(). "/". $a->query_string,
202 'base' => $a->get_baseurl(),
203 'updated' => api_date(null),
204 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
205 'language' => $user_info['language'],
206 'logo' => $a->get_baseurl()."/images/friendica-32.png",
213 * Returns user info array.
215 function api_get_user(&$a, $contact_id = Null){
221 if(!is_null($contact_id)){
223 $extra_query = "AND `contact`.`id` = %d ";
226 if(is_null($user) && x($_GET, 'user_id')) {
227 $user = intval($_GET['user_id']);
228 $extra_query = "AND `contact`.`id` = %d ";
230 if(is_null($user) && x($_GET, 'screen_name')) {
231 $user = dbesc($_GET['screen_name']);
232 $extra_query = "AND `contact`.`nick` = '%s' ";
233 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
237 if (is_null($user) && $a->argc > (count($called_api)-1)){
238 $argid = count($called_api);
239 list($user, $null) = explode(".",$a->argv[$argid]);
240 if(is_numeric($user)){
241 $user = intval($user);
242 $extra_query = "AND `contact`.`id` = %d ";
244 $user = dbesc($user);
245 $extra_query = "AND `contact`.`nick` = '%s' ";
246 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
251 if (api_user()===false) {
252 api_login($a); return False;
254 $user = $_SESSION['uid'];
255 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
260 logger('api_user: ' . $extra_query . ', user: ' . $user);
262 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
267 if (count($uinfo)==0) {
271 if($uinfo[0]['self']) {
272 $usr = q("select * from user where uid = %d limit 1",
275 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
279 // count public wall messages
280 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
283 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
284 intval($uinfo[0]['uid'])
286 $countitms = $r[0]['count'];
289 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
290 WHERE `contact-id` = %d
291 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
292 intval($uinfo[0]['id'])
294 $countitms = $r[0]['count'];
298 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
299 WHERE `uid` = %d AND `rel` IN ( %d, %d )
300 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
301 intval($uinfo[0]['uid']),
302 intval(CONTACT_IS_SHARING),
303 intval(CONTACT_IS_FRIEND)
305 $countfriends = $r[0]['count'];
307 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
308 WHERE `uid` = %d AND `rel` IN ( %d, %d )
309 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
310 intval($uinfo[0]['uid']),
311 intval(CONTACT_IS_FOLLOWER),
312 intval(CONTACT_IS_FRIEND)
314 $countfollowers = $r[0]['count'];
316 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
317 intval($uinfo[0]['uid'])
319 $starred = $r[0]['count'];
322 if(! $uinfo[0]['self']) {
329 'id' => intval($uinfo[0]['cid']),
330 'self' => intval($uinfo[0]['self']),
331 'uid' => intval($uinfo[0]['uid']),
332 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
333 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
334 'location' => ($usr) ? $usr[0]['default-location'] : '',
335 'profile_image_url' => $uinfo[0]['micro'],
336 'url' => $uinfo[0]['url'],
337 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
338 'protected' => false,
339 'friends_count' => intval($countfriends),
340 'created_at' => api_date($uinfo[0]['name-date']),
341 'utc_offset' => "+00:00",
342 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
343 'geo_enabled' => false,
344 'statuses_count' => intval($countitms), #XXX: fix me
345 'lang' => 'en', #XXX: fix me
346 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
347 'followers_count' => intval($countfollowers),
348 'favourites_count' => intval($starred),
349 'contributors_enabled' => false,
350 'follow_request_sent' => true,
351 'profile_background_color' => 'cfe8f6',
352 'profile_text_color' => '000000',
353 'profile_link_color' => 'FF8500',
354 'profile_sidebar_fill_color' =>'AD0066',
355 'profile_sidebar_border_color' => 'AD0066',
356 'profile_background_image_url' => '',
357 'profile_background_tile' => false,
358 'profile_use_background_image' => false,
359 'notifications' => false,
360 'following' => '', #XXX: fix me
361 'verified' => true, #XXX: fix me
369 function api_item_get_user(&$a, $item) {
372 // The author is our direct contact, in a conversation with us.
373 if(link_compare($item['url'],$item['author-link'])) {
374 return api_get_user($a,$item['cid']);
377 // The author may be a contact of ours, but is replying to somebody else.
378 // Figure out if we know him/her.
379 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
380 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
381 return api_get_user($a,$a->contacts[$normalised]['id']);
383 // We don't know this person directly.
385 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
386 $name=str_replace(")","",$name);
394 // Generating a random ID
395 if (is_null($usercache[$nick]) or !array_key_exists($nick, $usercache))
396 $usercache[$nick] = mt_rand(2000000, 2100000);
399 'id' => $usercache[$nick],
401 'screen_name' => $nick,
402 'location' => '', //$uinfo[0]['default-location'],
404 'profile_image_url' => $item['author-avatar'],
405 'url' => $item['author-link'],
406 'protected' => false, #
407 'followers_count' => 0,
408 'friends_count' => 0,
410 'favourites_count' => 0,
411 'utc_offset' => 0, #XXX: fix me
412 'time_zone' => '', //$uinfo[0]['timezone'],
413 'statuses_count' => 0,
415 'statusnet_blocking' => false,
416 'notifications' => false,
419 'geo_enabled' => false,
420 'lang' => 'en', #XXX: fix me
421 'contributors_enabled' => false,
422 'follow_request_sent' => false,
423 'profile_background_color' => 'cfe8f6',
424 'profile_text_color' => '000000',
425 'profile_link_color' => 'FF8500',
426 'profile_sidebar_fill_color' =>'AD0066',
427 'profile_sidebar_border_color' => 'AD0066',
428 'profile_background_image_url' => '',
429 'profile_background_tile' => false,
430 'profile_use_background_image' => false,
431 'verified' => true, #XXX: fix me
432 'followers' => '', #XXX: fix me
441 * load api $templatename for $type and replace $data array
443 function api_apply_template($templatename, $type, $data){
451 $data = array_xmlify($data);
452 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
454 header ("Content-Type: text/xml");
455 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
458 $ret = replace_macros($tpl, $data);
472 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
473 * returns a 401 status code and an error message if not.
474 * http://developer.twitter.com/doc/get/account/verify_credentials
476 function api_account_verify_credentials(&$a, $type){
477 if (api_user()===false) return false;
478 $user_info = api_get_user($a);
480 return api_apply_template("user", $type, array('$user' => $user_info));
483 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
487 * get data from $_POST or $_GET
489 function requestdata($k){
490 if (isset($_POST[$k])){
493 if (isset($_GET[$k])){
499 /*Waitman Gobble Mod*/
500 function api_statuses_mediap(&$a, $type) {
501 if (api_user()===false) {
502 logger('api_statuses_update: no user');
505 $user_info = api_get_user($a);
507 $_REQUEST['type'] = 'wall';
508 $_REQUEST['profile_uid'] = api_user();
509 $_REQUEST['api_source'] = true;
510 $txt = requestdata('status');
511 //$txt = urldecode(requestdata('status'));
513 require_once('library/HTMLPurifier.auto.php');
514 require_once('include/html2bbcode.php');
516 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
517 $txt = html2bb_video($txt);
518 $config = HTMLPurifier_Config::createDefault();
519 $config->set('Cache.DefinitionImpl', null);
520 $purifier = new HTMLPurifier($config);
521 $txt = $purifier->purify($txt);
523 $txt = html2bbcode($txt);
525 $a->argv[1]=$user_info['screen_name']; //should be set to username?
527 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
528 require_once('mod/wall_upload.php');
529 $bebop = wall_upload_post($a);
531 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
532 $_REQUEST['body']=$txt."\n\n".$bebop;
533 require_once('mod/item.php');
536 // this should output the last post (the one we just posted).
537 return api_status_show($a,$type);
539 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
540 /*Waitman Gobble Mod*/
543 function api_statuses_update(&$a, $type) {
544 if (api_user()===false) {
545 logger('api_statuses_update: no user');
548 $user_info = api_get_user($a);
550 // convert $_POST array items to the form we use for web posts.
552 // logger('api_post: ' . print_r($_POST,true));
554 if(requestdata('htmlstatus')) {
555 require_once('library/HTMLPurifier.auto.php');
556 require_once('include/html2bbcode.php');
558 $txt = requestdata('htmlstatus');
559 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
561 $txt = html2bb_video($txt);
563 $config = HTMLPurifier_Config::createDefault();
564 $config->set('Cache.DefinitionImpl', null);
567 $purifier = new HTMLPurifier($config);
568 $txt = $purifier->purify($txt);
570 $_REQUEST['body'] = html2bbcode($txt);
575 $_REQUEST['body'] = requestdata('status');
576 //$_REQUEST['body'] = urldecode(requestdata('status'));
578 $_REQUEST['title'] = requestdata('title');
580 $parent = requestdata('in_reply_to_status_id');
581 if(ctype_digit($parent))
582 $_REQUEST['parent'] = $parent;
584 $_REQUEST['parent_uri'] = $parent;
586 if(requestdata('lat') && requestdata('long'))
587 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
588 $_REQUEST['profile_uid'] = api_user();
591 $_REQUEST['type'] = 'net-comment';
593 $_REQUEST['type'] = 'wall';
594 if(x($_FILES,'media')) {
595 // upload the image if we have one
596 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
597 require_once('mod/wall_upload.php');
598 $media = wall_upload_post($a);
600 $_REQUEST['body'] .= "\n\n".$media;
604 // set this so that the item_post() function is quiet and doesn't redirect or emit json
606 $_REQUEST['api_source'] = true;
608 // call out normal post function
610 require_once('mod/item.php');
613 // this should output the last post (the one we just posted).
614 return api_status_show($a,$type);
616 api_register_func('api/statuses/update','api_statuses_update', true);
619 function api_status_show(&$a, $type){
620 $user_info = api_get_user($a);
621 // get last public wall message
622 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
623 FROM `item`, `contact`,
624 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
625 WHERE `item`.`contact-id` = %d
626 AND `i`.`id` = `item`.`parent`
627 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
628 AND `type`!='activity'
629 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
630 ORDER BY `created` DESC
632 intval($user_info['id'])
635 if (count($lastwall)>0){
636 $lastwall = $lastwall[0];
638 $in_reply_to_status_id = '';
639 $in_reply_to_user_id = '';
640 $in_reply_to_screen_name = '';
641 if ($lastwall['parent']!=$lastwall['id']) {
642 $in_reply_to_status_id=$lastwall['parent'];
643 $in_reply_to_user_id = $lastwall['reply_uid'];
644 $in_reply_to_screen_name = $lastwall['reply_author'];
646 $status_info = array(
647 'text' => html2plain(bbcode($lastwall['body'], false, false, true), 0),
648 'truncated' => false,
649 'created_at' => api_date($lastwall['created']),
650 'in_reply_to_status_id' => $in_reply_to_status_id,
651 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
652 'id' => $lastwall['contact-id'],
653 'in_reply_to_user_id' => $in_reply_to_user_id,
654 'in_reply_to_screen_name' => $in_reply_to_screen_name,
656 'favorited' => false,
657 'coordinates' => $lastwall['coord'],
658 'place' => $lastwall['location'],
661 $status_info['user'] = $user_info;
663 return api_apply_template("status", $type, array('$status' => $status_info));
672 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
673 * The author's most recent status will be returned inline.
674 * http://developer.twitter.com/doc/get/users/show
676 function api_users_show(&$a, $type){
677 $user_info = api_get_user($a);
678 // get last public wall message
679 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
680 FROM `item`, `contact`,
681 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
682 WHERE `item`.`contact-id` = %d
683 AND `i`.`id` = `item`.`parent`
684 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
685 AND `type`!='activity'
686 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
687 ORDER BY `created` DESC
689 intval($user_info['id'])
692 if (count($lastwall)>0){
693 $lastwall = $lastwall[0];
695 $in_reply_to_status_id = '';
696 $in_reply_to_user_id = '';
697 $in_reply_to_screen_name = '';
698 if ($lastwall['parent']!=$lastwall['id']) {
699 $in_reply_to_status_id=$lastwall['parent'];
700 $in_reply_to_user_id = $lastwall['reply_uid'];
701 $in_reply_to_screen_name = $lastwall['reply_author'];
703 $user_info['status'] = array(
704 'created_at' => api_date($lastwall['created']),
705 'id' => $lastwall['contact-id'],
706 'text' => html2plain(bbcode($lastwall['body'], false, false, true), 0),
707 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
708 'truncated' => false,
709 'in_reply_to_status_id' => $in_reply_to_status_id,
710 'in_reply_to_user_id' => $in_reply_to_user_id,
711 'favorited' => false,
712 'in_reply_to_screen_name' => $in_reply_to_screen_name,
714 'coordinates' => $lastwall['coord'],
715 'place' => $lastwall['location'],
719 return api_apply_template("user", $type, array('$user' => $user_info));
722 api_register_func('api/users/show','api_users_show');
726 * http://developer.twitter.com/doc/get/statuses/home_timeline
728 * TODO: Optional parameters
729 * TODO: Add reply info
731 function api_statuses_home_timeline(&$a, $type){
732 if (api_user()===false) return false;
734 $user_info = api_get_user($a);
735 // get last newtork messages
739 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
740 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
741 if ($page<0) $page=0;
742 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
743 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
744 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
745 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
746 $parent_id = (x($_REQUEST,'parent_id')?$_REQUEST['parent_id']:0);
748 $start = $page*$count;
750 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
754 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
755 if ($exclude_replies > 0)
756 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
758 $sql_extra .= ' AND `item`.`parent` = '.intval($parent_id);
760 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
761 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
762 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
763 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
764 FROM `item`, `contact`
765 WHERE `item`.`uid` = %d
766 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
767 AND `contact`.`id` = `item`.`contact-id`
768 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
771 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
772 intval($user_info['uid']),
774 intval($start), intval($count)
777 $ret = api_format_items($r,$user_info);
779 // We aren't going to try to figure out at the item, group, and page
780 // level which items you've seen and which you haven't. If you're looking
781 // at the network timeline just mark everything seen.
783 $r = q("UPDATE `item` SET `unseen` = 0
784 WHERE `unseen` = 1 AND `uid` = %d",
785 intval($user_info['uid'])
789 $data = array('$statuses' => $ret);
793 $data = api_rss_extra($a, $data, $user_info);
796 $as = api_format_as($a, $ret, $user_info);
797 $as['title'] = $a->config['sitename']." Home Timeline";
798 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
803 return api_apply_template("timeline", $type, $data);
805 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
806 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
808 function api_statuses_public_timeline(&$a, $type){
809 if (api_user()===false) return false;
811 $user_info = api_get_user($a);
812 // get last newtork messages
816 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
817 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
818 if ($page<0) $page=0;
819 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
820 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
821 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
822 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
823 $parent_id = (x($_REQUEST,'parent_id')?$_REQUEST['parent_id']:0);
825 $start = $page*$count;
827 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
830 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
831 if ($exclude_replies > 0)
832 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
834 $sql_extra .= ' AND `item`.`parent` = '.intval($parent_id);
836 /*$r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
837 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
838 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
839 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
840 FROM `item`, `contact`
841 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
842 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
843 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
844 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
845 AND `contact`.`id` = `item`.`contact-id`
846 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
849 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
851 intval($start), intval($count)
853 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
854 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
855 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
856 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
857 `user`.`nickname`, `user`.`hidewall`
858 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
859 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
860 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
861 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
862 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
863 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
864 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
867 ORDER BY `received` DESC LIMIT %d, %d ",
872 $ret = api_format_items($r,$user_info);
875 $data = array('$statuses' => $ret);
879 $data = api_rss_extra($a, $data, $user_info);
882 $as = api_format_as($a, $ret, $user_info);
883 $as['title'] = $a->config['sitename']." Public Timeline";
884 $as['link']['url'] = $a->get_baseurl()."/";
889 return api_apply_template("timeline", $type, $data);
891 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
896 function api_statuses_show(&$a, $type){
897 if (api_user()===false) return false;
899 $user_info = api_get_user($a);
902 $id = intval($a->argv[3]);
904 logger('API: api_statuses_show: '.$id);
906 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
907 $conversation = (x($_REQUEST,'conversation')?1:0);
911 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
913 $sql_extra .= " AND `item`.`id` = %d";
915 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
916 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
917 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
918 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
919 FROM `item`, `contact`
920 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
921 AND `contact`.`id` = `item`.`contact-id`
922 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
927 $ret = api_format_items($r,$user_info);
930 $data = array('$statuses' => $ret);
931 return api_apply_template("timeline", $type, $data);
933 $data = array('$status' => $ret[0]);
937 $data = api_rss_extra($a, $data, $user_info);
939 return api_apply_template("status", $type, $data);
942 api_register_func('api/statuses/show','api_statuses_show', true);
948 function api_statuses_repeat(&$a, $type){
949 if (api_user()===false) return false;
951 $user_info = api_get_user($a);
954 $id = intval($a->argv[3]);
956 logger('API: api_statuses_repeat: '.$id);
958 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
960 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
961 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
962 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
963 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
964 FROM `item`, `contact`
965 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
966 AND `contact`.`id` = `item`.`contact-id`
967 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
973 if ($r[0]['body'] != "") {
974 if (intval(get_config('system','new_share'))) {
975 $post = "[share author='".str_replace("'", "'", $r[0]['reply_author']).
976 "' profile='".$r[0]['reply_url'].
977 "' avatar='".$r[0]['reply_photo'].
978 "' link='".$r[0]['plink']."']";
980 $post .= $r[0]['body'];
982 $_REQUEST['body'] = $post;
984 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
986 $_REQUEST['profile_uid'] = api_user();
987 $_REQUEST['type'] = 'wall';
988 $_REQUEST['api_source'] = true;
990 require_once('mod/item.php');
999 return api_apply_template('test', $type, array('$ok' => $ok));
1001 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1006 function api_statuses_destroy(&$a, $type){
1007 if (api_user()===false) return false;
1009 $user_info = api_get_user($a);
1012 $id = intval($a->argv[3]);
1014 logger('API: api_statuses_destroy: '.$id);
1016 require_once('include/items.php');
1017 drop_item($id, false);
1024 return api_apply_template('test', $type, array('$ok' => $ok));
1026 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1030 * http://developer.twitter.com/doc/get/statuses/mentions
1033 function api_statuses_mentions(&$a, $type){
1034 if (api_user()===false) return false;
1036 $user_info = api_get_user($a);
1037 // get last newtork messages
1041 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1042 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1043 if ($page<0) $page=0;
1044 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1045 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1046 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1048 $start = $page*$count;
1050 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1052 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1053 $myurl = substr($myurl,strpos($myurl,'://')+3);
1054 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1055 $myurl = str_replace('www.','',$myurl);
1056 $diasp_url = str_replace('/profile/','/u/',$myurl);
1058 /* if (get_config('system','use_fulltext_engine'))
1059 $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))) ",
1060 dbesc(protect_sprintf($myurl)),
1061 dbesc(protect_sprintf($myurl)),
1062 dbesc(protect_sprintf($diasp_url))
1065 $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' )) ",
1066 dbesc(protect_sprintf('%' . $myurl)),
1067 dbesc(protect_sprintf('%' . $myurl . ']%')),
1068 dbesc(protect_sprintf('%' . $diasp_url . ']%'))
1071 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1072 dbesc(protect_sprintf($myurl)),
1073 dbesc(protect_sprintf($myurl))
1077 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1079 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1080 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1081 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1082 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1083 FROM `item`, `contact`
1084 WHERE `item`.`uid` = %d
1085 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1086 AND `contact`.`id` = `item`.`contact-id`
1087 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1090 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1091 intval($user_info['uid']),
1093 intval($start), intval($count)
1096 $ret = api_format_items($r,$user_info);
1099 $data = array('$statuses' => $ret);
1103 $data = api_rss_extra($a, $data, $user_info);
1106 $as = api_format_as($a, $ret, $user_info);
1107 $as["title"] = $a->config['sitename']." Mentions";
1108 $as['link']['url'] = $a->get_baseurl()."/";
1113 return api_apply_template("timeline", $type, $data);
1115 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1116 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1119 function api_statuses_user_timeline(&$a, $type){
1120 if (api_user()===false) return false;
1122 $user_info = api_get_user($a);
1123 // get last newtork messages
1126 logger("api_statuses_user_timeline: api_user: ". api_user() .
1127 "\nuser_info: ".print_r($user_info, true) .
1128 "\n_REQUEST: ".print_r($_REQUEST, true),
1132 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1133 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1134 if ($page<0) $page=0;
1135 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1136 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1137 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1138 $parent_id = (x($_REQUEST,'parent_id')?$_REQUEST['parent_id']:0);
1140 $start = $page*$count;
1143 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1145 if ($exclude_replies > 0)
1146 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1148 $sql_extra .= ' AND `item`.`parent` = '.intval($parent_id);
1150 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1151 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1152 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1153 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1154 FROM `item`, `contact`
1155 WHERE `item`.`uid` = %d
1156 AND `item`.`contact-id` = %d
1157 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1158 AND `contact`.`id` = `item`.`contact-id`
1159 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1162 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1164 intval($user_info['id']),
1166 intval($start), intval($count)
1169 $ret = api_format_items($r,$user_info);
1172 $data = array('$statuses' => $ret);
1176 $data = api_rss_extra($a, $data, $user_info);
1179 return api_apply_template("timeline", $type, $data);
1182 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1185 function api_favorites(&$a, $type){
1186 if (api_user()===false) return false;
1188 $user_info = api_get_user($a);
1189 // in friendica starred item are private
1190 // return favorites only for self
1191 logger('api_favorites: self:' . $user_info['self']);
1193 if ($user_info['self']==0) {
1199 $count = (x($_GET,'count')?$_GET['count']:20);
1200 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1201 if ($page<0) $page=0;
1203 $start = $page*$count;
1205 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1206 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1207 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1208 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1209 FROM `item`, `contact`
1210 WHERE `item`.`uid` = %d
1211 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1212 AND `item`.`starred` = 1
1213 AND `contact`.`id` = `item`.`contact-id`
1214 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1216 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1217 intval($user_info['uid']),
1218 intval($start), intval($count)
1221 $ret = api_format_items($r,$user_info);
1225 $data = array('$statuses' => $ret);
1229 $data = api_rss_extra($a, $data, $user_info);
1232 return api_apply_template("timeline", $type, $data);
1235 api_register_func('api/favorites','api_favorites', true);
1237 function api_format_as($a, $ret, $user_info) {
1240 $as['title'] = $a->config['sitename']." Public Timeline";
1242 foreach ($ret as $item) {
1243 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1244 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1245 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1246 $avatar[0]["rel"] = "avatar";
1247 $avatar[0]["type"] = "";
1248 $avatar[0]["width"] = 96;
1249 $avatar[0]["height"] = 96;
1250 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1251 $avatar[1]["rel"] = "avatar";
1252 $avatar[1]["type"] = "";
1253 $avatar[1]["width"] = 48;
1254 $avatar[1]["height"] = 48;
1255 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1256 $avatar[2]["rel"] = "avatar";
1257 $avatar[2]["type"] = "";
1258 $avatar[2]["width"] = 24;
1259 $avatar[2]["height"] = 24;
1260 $singleitem["actor"]["avatarLinks"] = $avatar;
1262 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1263 $singleitem["actor"]["image"]["rel"] = "avatar";
1264 $singleitem["actor"]["image"]["type"] = "";
1265 $singleitem["actor"]["image"]["width"] = 96;
1266 $singleitem["actor"]["image"]["height"] = 96;
1267 $singleitem["actor"]["type"] = "person";
1268 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1269 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1270 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1271 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1272 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1273 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1274 $singleitem["actor"]["contact"]["addresses"] = "";
1276 $singleitem["body"] = $item["text"];
1277 $singleitem["object"]["displayName"] = $item["text"];
1278 $singleitem["object"]["id"] = $item["url"];
1279 $singleitem["object"]["type"] = "note";
1280 $singleitem["object"]["url"] = $item["url"];
1281 //$singleitem["context"] =;
1282 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1283 $singleitem["provider"]["objectType"] = "service";
1284 $singleitem["provider"]["displayName"] = "Test";
1285 $singleitem["provider"]["url"] = "http://test.tld";
1286 $singleitem["title"] = $item["text"];
1287 $singleitem["verb"] = "post";
1288 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1289 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1290 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1291 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1292 //$singleitem["original"] = $item;
1293 $items[] = $singleitem;
1295 $as['items'] = $items;
1296 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1297 $as['link']['rel'] = "alternate";
1298 $as['link']['type'] = "text/html";
1302 function api_format_messages($item, $recipient, $sender) {
1303 // standard meta information
1305 'id' => $item['id'],
1306 'created_at' => api_date($item['created']),
1307 'sender_id' => $sender['id'] ,
1308 'sender_screen_name' => $sender['screen_name'],
1309 'sender' => $sender,
1310 'recipient_id' => $recipient['id'],
1311 'recipient_screen_name' => $recipient['screen_name'],
1312 'recipient' => $recipient,
1315 //don't send title to regular StatusNET requests to avoid confusing these apps
1316 if (x($_GET, 'getText')) {
1317 $ret['title'] = $item['title'] ;
1318 if ($_GET["getText"] == "html") {
1319 $ret['text'] = bbcode($item['body']);
1321 elseif ($_GET["getText"] == "plain") {
1322 $ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1326 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body'], false, false, true), 0);
1328 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1329 unset($ret['sender']);
1330 unset($ret['recipient']);
1336 function api_format_items($r,$user_info) {
1338 //logger('api_format_items: ' . print_r($r,true));
1340 //logger('api_format_items: ' . print_r($user_info,true));
1345 foreach($r as $item) {
1346 localize_item($item);
1347 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
1349 if ($item['parent']!=$item['id']) {
1350 $r = q("select id from item where parent=%s and id<%s order by id desc limit 1",
1351 intval($item['parent']), intval($item['id']));
1353 $in_reply_to_status_id = $r[0]['id'];
1355 $in_reply_to_status_id = $item['parent'];
1357 $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact
1358 where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id));
1360 $in_reply_to_screen_name = $r[0]['author-name'];
1361 $in_reply_to_user_id = $r[0]['contact-id'];
1364 $in_reply_to_screen_name = '';
1365 $in_reply_to_user_id = 0;
1366 $in_reply_to_status_id = 0;
1369 // Workaround for ostatus messages where the title is identically to the body
1370 $statusbody = trim(html2plain(bbcode($item['body'], false, false, true), 0));
1371 $statustitle = trim($item['title']);
1373 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1374 $statustext = trim($statusbody);
1376 $statustext = trim($statustitle."\n\n".$statusbody);
1378 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1379 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1382 'text' => $statustext,
1383 'truncated' => False,
1384 'created_at'=> api_date($item['created']),
1385 'in_reply_to_status_id' => $in_reply_to_status_id,
1386 'source' => (($item['app']) ? $item['app'] : 'web'),
1387 'id' => intval($item['id']),
1388 'in_reply_to_user_id' => $in_reply_to_user_id,
1389 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1391 'favorited' => $item['starred'] ? true : false,
1392 'user' => $status_user ,
1393 'statusnet_html' => trim(bbcode($item['body'])),
1394 'statusnet_conversation_id' => $item['parent'],
1397 // Seesmic doesn't like the following content
1398 if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1400 'updated' => api_date($item['edited']),
1401 'published' => api_date($item['created']),
1402 'message_id' => $item['uri'],
1403 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1404 'coordinates' => $item['coord'],
1405 'place' => $item['location'],
1406 'contributors' => '',
1407 'annotations' => '',
1409 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1410 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1411 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1412 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1415 $status = array_merge($status, $status2);
1424 function api_account_rate_limit_status(&$a,$type) {
1427 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1428 'remaining_hits' => (string) 150,
1429 'hourly_limit' => (string) 150,
1430 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1433 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1435 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1438 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1440 function api_help_test(&$a,$type) {
1447 return api_apply_template('test', $type, array('$ok' => $ok));
1450 api_register_func('api/help/test','api_help_test',false);
1453 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1454 * This function is deprecated by Twitter
1455 * returns: json, xml
1457 function api_statuses_f(&$a, $type, $qtype) {
1458 if (api_user()===false) return false;
1459 $user_info = api_get_user($a);
1462 // friends and followers only for self
1463 if ($user_info['self']==0){
1467 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1468 /* this is to stop Hotot to load friends multiple times
1469 * I'm not sure if I'm missing return something or
1470 * is a bug in hotot. Workaround, meantime
1474 return array('$users' => $ret);*/
1478 if($qtype == 'friends')
1479 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1480 if($qtype == 'followers')
1481 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1483 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1488 foreach($r as $cid){
1489 $ret[] = api_get_user($a, $cid['id']);
1493 return array('$users' => $ret);
1496 function api_statuses_friends(&$a, $type){
1497 $data = api_statuses_f($a,$type,"friends");
1498 if ($data===false) return false;
1499 return api_apply_template("friends", $type, $data);
1501 function api_statuses_followers(&$a, $type){
1502 $data = api_statuses_f($a,$type,"followers");
1503 if ($data===false) return false;
1504 return api_apply_template("friends", $type, $data);
1506 api_register_func('api/statuses/friends','api_statuses_friends',true);
1507 api_register_func('api/statuses/followers','api_statuses_followers',true);
1514 function api_statusnet_config(&$a,$type) {
1515 $name = $a->config['sitename'];
1516 $server = $a->get_hostname();
1517 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1518 $email = $a->config['admin_email'];
1519 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1520 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1521 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1522 if($a->config['api_import_size'])
1523 $texlimit = string($a->config['api_import_size']);
1524 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1525 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1528 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1529 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1530 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1531 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1532 'shorturllength' => '30',
1533 'friendica' => array(
1534 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1535 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1536 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1537 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1542 return api_apply_template('config', $type, array('$config' => $config));
1545 api_register_func('api/statusnet/config','api_statusnet_config',false);
1547 function api_statusnet_version(&$a,$type) {
1551 if($type === 'xml') {
1552 header("Content-type: application/xml");
1553 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1556 elseif($type === 'json') {
1557 header("Content-type: application/json");
1562 api_register_func('api/statusnet/version','api_statusnet_version',false);
1565 function api_ff_ids(&$a,$type,$qtype) {
1569 if($qtype == 'friends')
1570 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1571 if($qtype == 'followers')
1572 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1575 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1580 if($type === 'xml') {
1581 header("Content-type: application/xml");
1582 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1584 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1585 echo '</ids>' . "\r\n";
1588 elseif($type === 'json') {
1590 header("Content-type: application/json");
1591 foreach($r as $rr) $ret[] = $rr['id'];
1592 echo json_encode($ret);
1598 function api_friends_ids(&$a,$type) {
1599 api_ff_ids($a,$type,'friends');
1601 function api_followers_ids(&$a,$type) {
1602 api_ff_ids($a,$type,'followers');
1604 api_register_func('api/friends/ids','api_friends_ids',true);
1605 api_register_func('api/followers/ids','api_followers_ids',true);
1608 function api_direct_messages_new(&$a, $type) {
1609 if (api_user()===false) return false;
1611 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1613 $sender = api_get_user($a);
1615 require_once("include/message.php");
1617 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1619 dbesc($_POST['screen_name']));
1621 $recipient = api_get_user($a, $r[0]['id']);
1624 if (x($_REQUEST,'replyto')) {
1625 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1627 intval($_REQUEST['replyto']));
1628 $replyto = $r[0]['parent-uri'];
1629 $sub = $r[0]['title'];
1632 if (x($_REQUEST,'title')) {
1633 $sub = $_REQUEST['title'];
1636 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1640 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1643 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1644 $ret = api_format_messages($r[0], $recipient, $sender);
1647 $ret = array("error"=>$id);
1650 $data = Array('$messages'=>$ret);
1655 $data = api_rss_extra($a, $data, $user_info);
1658 return api_apply_template("direct_messages", $type, $data);
1661 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1663 function api_direct_messages_box(&$a, $type, $box) {
1664 if (api_user()===false) return false;
1666 $user_info = api_get_user($a);
1669 $count = (x($_GET,'count')?$_GET['count']:20);
1670 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1671 if ($page<0) $page=0;
1673 $start = $page*$count;
1675 $profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1676 if ($box=="sentbox") {
1677 $sql_extra = "`from-url`='".dbesc( $profile_url )."'";
1679 elseif ($box=="conversation") {
1680 $sql_extra = "`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1682 elseif ($box=="all") {
1683 $sql_extra = "true";
1685 elseif ($box=="inbox") {
1686 $sql_extra = "`from-url`!='".dbesc( $profile_url )."'";
1689 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1691 intval($start), intval($count)
1695 foreach($r as $item) {
1696 if ($box == "inbox" || $item['from-url'] != $profile_url){
1697 $recipient = $user_info;
1698 $sender = api_get_user($a,$item['contact-id']);
1700 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1701 $recipient = api_get_user($a,$item['contact-id']);
1702 $sender = $user_info;
1705 $ret[]=api_format_messages($item, $recipient, $sender);
1709 $data = array('$messages' => $ret);
1713 $data = api_rss_extra($a, $data, $user_info);
1716 return api_apply_template("direct_messages", $type, $data);
1720 function api_direct_messages_sentbox(&$a, $type){
1721 return api_direct_messages_box($a, $type, "sentbox");
1723 function api_direct_messages_inbox(&$a, $type){
1724 return api_direct_messages_box($a, $type, "inbox");
1726 function api_direct_messages_all(&$a, $type){
1727 return api_direct_messages_box($a, $type, "all");
1729 function api_direct_messages_conversation(&$a, $type){
1730 return api_direct_messages_box($a, $type, "conversation");
1732 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1733 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1734 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1735 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1739 function api_oauth_request_token(&$a, $type){
1741 $oauth = new FKOAuth1();
1742 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1743 }catch(Exception $e){
1744 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1749 function api_oauth_access_token(&$a, $type){
1751 $oauth = new FKOAuth1();
1752 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1753 }catch(Exception $e){
1754 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1760 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1761 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1764 Not implemented by now:
1768 statuses/retweets_of_me
1773 account/update_location
1774 account/update_profile_background_image
1775 account/update_profile_image
1779 Not implemented in status.net:
1780 statuses/retweeted_to_me
1781 statuses/retweeted_by_me
1782 direct_messages/destroy
1784 account/update_delivery_device
1785 notifications/follow