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",
214 * Unique contact to to contact url.
216 function api_unique_id_to_url($id){
217 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
220 return ($r[0]["url"]);
226 * Returns user info array.
228 function api_get_user(&$a, $contact_id = Null){
235 // Searching for contact URL
236 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
237 $user = dbesc(normalise_link($contact_id));
239 $extra_query = "AND `contact`.`nurl` = '%s' ";
240 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
243 // Searching for unique contact id
244 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
245 $user = dbesc(api_unique_id_to_url($contact_id));
251 $extra_query = "AND `contact`.`nurl` = '%s' ";
252 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
255 if(is_null($user) && x($_GET, 'user_id')) {
256 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
262 $extra_query = "AND `contact`.`nurl` = '%s' ";
263 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
265 if(is_null($user) && x($_GET, 'screen_name')) {
266 $user = dbesc($_GET['screen_name']);
268 $extra_query = "AND `contact`.`nick` = '%s' ";
269 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
272 if (is_null($user) && $a->argc > (count($called_api)-1)){
273 $argid = count($called_api);
274 list($user, $null) = explode(".",$a->argv[$argid]);
275 if(is_numeric($user)){
276 $user = dbesc(api_unique_id_to_url($user));
282 $extra_query = "AND `contact`.`nurl` = '%s' ";
283 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
285 $user = dbesc($user);
287 $extra_query = "AND `contact`.`nick` = '%s' ";
288 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
293 if (api_user()===false) {
294 api_login($a); return False;
296 $user = $_SESSION['uid'];
297 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
302 logger('api_user: ' . $extra_query . ', user: ' . $user);
304 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
310 // if the contact wasn't found, fetch it from the unique contacts
311 if (count($uinfo)==0) {
315 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
317 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
322 'name' => $r[0]["name"],
323 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
325 'description' => NULL,
326 'profile_image_url' => $r[0]["avatar"],
327 'url' => $r[0]["url"],
328 'protected' => false,
329 'followers_count' => 0,
330 'friends_count' => 0,
332 'favourites_count' => 0,
334 'time_zone' => 'UTC',
335 'statuses_count' => 0,
337 'statusnet_blocking' => false,
338 'notifications' => false,
339 'statusnet_profile_url' => $r[0]["url"],
351 if($uinfo[0]['self']) {
352 $usr = q("select * from user where uid = %d limit 1",
355 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
359 // count public wall messages
360 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
363 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
364 intval($uinfo[0]['uid'])
366 $countitms = $r[0]['count'];
369 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
370 WHERE `contact-id` = %d
371 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
372 intval($uinfo[0]['id'])
374 $countitms = $r[0]['count'];
378 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
379 WHERE `uid` = %d AND `rel` IN ( %d, %d )
380 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
381 intval($uinfo[0]['uid']),
382 intval(CONTACT_IS_SHARING),
383 intval(CONTACT_IS_FRIEND)
385 $countfriends = $r[0]['count'];
387 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
388 WHERE `uid` = %d AND `rel` IN ( %d, %d )
389 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
390 intval($uinfo[0]['uid']),
391 intval(CONTACT_IS_FOLLOWER),
392 intval(CONTACT_IS_FRIEND)
394 $countfollowers = $r[0]['count'];
396 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
397 intval($uinfo[0]['uid'])
399 $starred = $r[0]['count'];
402 if(! $uinfo[0]['self']) {
408 // Fetching unique id
409 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
411 // If not there, then add it
412 if (count($r) == 0) {
413 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
414 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
416 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
420 'id' => intval($r[0]['id']),
421 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
422 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
423 'location' => ($usr) ? $usr[0]['default-location'] : NULL,
424 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
425 'profile_image_url' => $uinfo[0]['micro'],
426 'url' => $uinfo[0]['url'],
427 'protected' => false,
428 'followers_count' => intval($countfollowers),
429 'friends_count' => intval($countfriends),
430 'created_at' => api_date($uinfo[0]['name-date']),
431 'favourites_count' => intval($starred),
432 'utc_offset' => "0", // To-Do
433 'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
434 'statuses_count' => intval($countitms),
435 'following' => true, //#XXX: fix me
436 'verified' => true, //#XXX: fix me
437 'statusnet_blocking' => false,
438 'notifications' => false,
439 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
440 'uid' => intval($uinfo[0]['uid']),
441 'cid' => intval($uinfo[0]['cid']),
442 'self' => $uinfo[0]['self'],
449 function api_item_get_user(&$a, $item) {
451 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
452 dbesc(normalise_link($item['author-link'])));
454 if (count($author) == 0) {
455 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
456 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
458 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
459 dbesc(normalise_link($item['author-link'])));
462 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
463 dbesc(normalise_link($item['owner-link'])));
465 if (count($owner) == 0) {
466 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
467 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
469 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
470 dbesc(normalise_link($item['owner-link'])));
473 // Comments in threads may appear as wall-to-wall postings.
474 // So only take the owner at the top posting.
475 if ($item["id"] == $item["parent"])
476 return api_get_user($a,$item["owner-link"]);
478 return api_get_user($a,$item["author-link"]);
483 * load api $templatename for $type and replace $data array
485 function api_apply_template($templatename, $type, $data){
493 $data = array_xmlify($data);
494 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
496 header ("Content-Type: text/xml");
497 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
500 $ret = replace_macros($tpl, $data);
514 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
515 * returns a 401 status code and an error message if not.
516 * http://developer.twitter.com/doc/get/account/verify_credentials
518 function api_account_verify_credentials(&$a, $type){
519 if (api_user()===false) return false;
520 $user_info = api_get_user($a);
522 return api_apply_template("user", $type, array('$user' => $user_info));
525 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
529 * get data from $_POST or $_GET
531 function requestdata($k){
532 if (isset($_POST[$k])){
535 if (isset($_GET[$k])){
541 /*Waitman Gobble Mod*/
542 function api_statuses_mediap(&$a, $type) {
543 if (api_user()===false) {
544 logger('api_statuses_update: no user');
547 $user_info = api_get_user($a);
549 $_REQUEST['type'] = 'wall';
550 $_REQUEST['profile_uid'] = api_user();
551 $_REQUEST['api_source'] = true;
552 $txt = requestdata('status');
553 //$txt = urldecode(requestdata('status'));
555 require_once('library/HTMLPurifier.auto.php');
556 require_once('include/html2bbcode.php');
558 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
559 $txt = html2bb_video($txt);
560 $config = HTMLPurifier_Config::createDefault();
561 $config->set('Cache.DefinitionImpl', null);
562 $purifier = new HTMLPurifier($config);
563 $txt = $purifier->purify($txt);
565 $txt = html2bbcode($txt);
567 $a->argv[1]=$user_info['screen_name']; //should be set to username?
569 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
570 require_once('mod/wall_upload.php');
571 $bebop = wall_upload_post($a);
573 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
574 $_REQUEST['body']=$txt."\n\n".$bebop;
575 require_once('mod/item.php');
578 // this should output the last post (the one we just posted).
579 return api_status_show($a,$type);
581 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
582 /*Waitman Gobble Mod*/
585 function api_statuses_update(&$a, $type) {
586 if (api_user()===false) {
587 logger('api_statuses_update: no user');
590 $user_info = api_get_user($a);
592 // convert $_POST array items to the form we use for web posts.
594 // logger('api_post: ' . print_r($_POST,true));
596 if(requestdata('htmlstatus')) {
597 require_once('library/HTMLPurifier.auto.php');
598 require_once('include/html2bbcode.php');
600 $txt = requestdata('htmlstatus');
601 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
603 $txt = html2bb_video($txt);
605 $config = HTMLPurifier_Config::createDefault();
606 $config->set('Cache.DefinitionImpl', null);
609 $purifier = new HTMLPurifier($config);
610 $txt = $purifier->purify($txt);
612 $_REQUEST['body'] = html2bbcode($txt);
617 $_REQUEST['body'] = requestdata('status');
619 $_REQUEST['title'] = requestdata('title');
621 $parent = requestdata('in_reply_to_status_id');
622 if(ctype_digit($parent))
623 $_REQUEST['parent'] = $parent;
625 $_REQUEST['parent_uri'] = $parent;
627 if(requestdata('lat') && requestdata('long'))
628 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
629 $_REQUEST['profile_uid'] = api_user();
632 $_REQUEST['type'] = 'net-comment';
634 $_REQUEST['type'] = 'wall';
635 if(x($_FILES,'media')) {
636 // upload the image if we have one
637 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
638 require_once('mod/wall_upload.php');
639 $media = wall_upload_post($a);
641 $_REQUEST['body'] .= "\n\n".$media;
645 // set this so that the item_post() function is quiet and doesn't redirect or emit json
647 $_REQUEST['api_source'] = true;
649 // call out normal post function
651 require_once('mod/item.php');
654 // this should output the last post (the one we just posted).
655 return api_status_show($a,$type);
657 api_register_func('api/statuses/update','api_statuses_update', true);
660 function api_status_show(&$a, $type){
661 $user_info = api_get_user($a);
662 // get last public wall message
663 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
664 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
665 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
666 AND `i`.`id` = `item`.`parent`
667 AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
668 AND `item`.`type`!='activity'
669 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
670 ORDER BY `item`.`created` DESC
672 intval($user_info['cid']),
673 dbesc($user_info['url'])
676 if (count($lastwall)>0){
677 $lastwall = $lastwall[0];
679 $in_reply_to_status_id = NULL;
680 $in_reply_to_user_id = NULL;
681 $in_reply_to_screen_name = NULL;
682 if ($lastwall['parent']!=$lastwall['id']) {
683 $in_reply_to_status_id=$lastwall['parent'];
684 //$in_reply_to_user_id = $lastwall['reply_uid'];
685 //$in_reply_to_screen_name = $lastwall['reply_author'];
687 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
689 $in_reply_to_screen_name = $r[0]['name'];
690 $in_reply_to_user_id = $r[0]['id'];
693 $status_info = array(
694 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
695 'truncated' => false,
696 'created_at' => api_date($lastwall['created']),
697 'in_reply_to_status_id' => $in_reply_to_status_id,
698 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
699 'id' => $lastwall['id'],
700 'in_reply_to_user_id' => $in_reply_to_user_id,
701 'in_reply_to_screen_name' => $in_reply_to_screen_name,
703 'favorited' => false,
704 'user' => $user_info,
705 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
706 'statusnet_conversation_id' => $lastwall['parent'],
707 //'coordinates' => $lastwall['coord'],
708 //'place' => $lastwall['location'],
709 //'contributors' => ''
712 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
713 unset($status_info["user"]["cid"]);
714 unset($status_info["user"]["uid"]);
715 unset($status_info["user"]["self"]);
718 return api_apply_template("status", $type, array('$status' => $status_info));
727 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
728 * The author's most recent status will be returned inline.
729 * http://developer.twitter.com/doc/get/users/show
731 function api_users_show(&$a, $type){
732 $user_info = api_get_user($a);
734 $lastwall = q("SELECT `item`.*
735 FROM `item`, `contact`
736 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
737 AND `contact`.`id`=`item`.`contact-id`
738 AND `type`!='activity'
739 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
740 ORDER BY `created` DESC
742 intval($user_info['cid']),
743 dbesc($user_info['url'])
746 if (count($lastwall)>0){
747 $lastwall = $lastwall[0];
749 $in_reply_to_status_id = NULL;
750 $in_reply_to_user_id = NULL;
751 $in_reply_to_screen_name = NULL;
752 if ($lastwall['parent']!=$lastwall['id']) {
753 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
754 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
755 if (count($reply)>0) {
756 $in_reply_to_status_id=$lastwall['parent'];
757 //$in_reply_to_user_id = $reply[0]['reply_uid'];
758 //$in_reply_to_screen_name = $reply[0]['reply_author'];
759 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
761 $in_reply_to_screen_name = $r[0]['name'];
762 $in_reply_to_user_id = $r[0]['id'];
766 $user_info['status'] = array(
767 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
768 'truncated' => false,
769 'created_at' => api_date($lastwall['created']),
770 'in_reply_to_status_id' => $in_reply_to_status_id,
771 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
772 'id' => $lastwall['contact-id'],
773 'in_reply_to_user_id' => $in_reply_to_user_id,
774 'in_reply_to_screen_name' => $in_reply_to_screen_name,
776 'favorited' => false,
777 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
778 'statusnet_conversation_id' => $lastwall['parent'],
782 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
783 unset($user_info["cid"]);
784 unset($user_info["uid"]);
785 unset($user_info["self"]);
787 return api_apply_template("user", $type, array('$user' => $user_info));
790 api_register_func('api/users/show','api_users_show');
794 * http://developer.twitter.com/doc/get/statuses/home_timeline
796 * TODO: Optional parameters
797 * TODO: Add reply info
799 function api_statuses_home_timeline(&$a, $type){
800 if (api_user()===false) return false;
802 $user_info = api_get_user($a);
803 // get last newtork messages
807 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
808 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
809 if ($page<0) $page=0;
810 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
811 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
812 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
813 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
814 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
816 $start = $page*$count;
818 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
822 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
823 if ($exclude_replies > 0)
824 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
825 if ($conversation_id > 0)
826 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
828 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
829 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
830 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
831 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
832 FROM `item`, `contact`
833 WHERE `item`.`uid` = %d
834 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
835 AND `contact`.`id` = `item`.`contact-id`
836 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
839 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
840 //intval($user_info['uid']),
843 intval($start), intval($count)
846 $ret = api_format_items($r,$user_info);
848 // We aren't going to try to figure out at the item, group, and page
849 // level which items you've seen and which you haven't. If you're looking
850 // at the network timeline just mark everything seen.
852 $r = q("UPDATE `item` SET `unseen` = 0
853 WHERE `unseen` = 1 AND `uid` = %d",
854 //intval($user_info['uid'])
859 $data = array('$statuses' => $ret);
863 $data = api_rss_extra($a, $data, $user_info);
866 $as = api_format_as($a, $ret, $user_info);
867 $as['title'] = $a->config['sitename']." Home Timeline";
868 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
873 return api_apply_template("timeline", $type, $data);
875 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
876 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
878 function api_statuses_public_timeline(&$a, $type){
879 if (api_user()===false) return false;
881 $user_info = api_get_user($a);
882 // get last newtork messages
886 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
887 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
888 if ($page<0) $page=0;
889 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
890 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
891 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
892 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
893 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
895 $start = $page*$count;
897 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
900 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
901 if ($exclude_replies > 0)
902 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
903 if ($conversation_id > 0)
904 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
906 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
907 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
908 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
909 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
910 `user`.`nickname`, `user`.`hidewall`
911 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
912 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
913 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
914 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
915 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
916 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
917 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
920 ORDER BY `received` DESC LIMIT %d, %d ",
925 $ret = api_format_items($r,$user_info);
928 $data = array('$statuses' => $ret);
932 $data = api_rss_extra($a, $data, $user_info);
935 $as = api_format_as($a, $ret, $user_info);
936 $as['title'] = $a->config['sitename']." Public Timeline";
937 $as['link']['url'] = $a->get_baseurl()."/";
942 return api_apply_template("timeline", $type, $data);
944 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
949 function api_statuses_show(&$a, $type){
950 if (api_user()===false) return false;
952 $user_info = api_get_user($a);
955 $id = intval($a->argv[3]);
958 $id = intval($_REQUEST["id"]);
960 logger('API: api_statuses_show: '.$id);
962 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
963 $conversation = (x($_REQUEST,'conversation')?1:0);
967 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
969 $sql_extra .= " AND `item`.`id` = %d";
971 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
972 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
973 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
974 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
975 FROM `item`, `contact`
976 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
977 AND `contact`.`id` = `item`.`contact-id`
978 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
983 $ret = api_format_items($r,$user_info);
986 $data = array('$statuses' => $ret);
987 return api_apply_template("timeline", $type, $data);
989 $data = array('$status' => $ret[0]);
993 $data = api_rss_extra($a, $data, $user_info);
995 return api_apply_template("status", $type, $data);
998 api_register_func('api/statuses/show','api_statuses_show', true);
1004 function api_statuses_repeat(&$a, $type){
1005 if (api_user()===false) return false;
1007 $user_info = api_get_user($a);
1010 $id = intval($a->argv[3]);
1013 $id = intval($_REQUEST["id"]);
1015 logger('API: api_statuses_repeat: '.$id);
1017 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1019 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
1020 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1021 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1022 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1023 FROM `item`, `contact`
1024 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1025 AND `contact`.`id` = `item`.`contact-id`
1026 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1028 AND `item`.`id`=%d",
1032 if ($r[0]['body'] != "") {
1033 if (!intval(get_config('system','old_share'))) {
1034 $post = "[share author='".str_replace("'", "'", $r[0]['reply_author']).
1035 "' profile='".$r[0]['reply_url'].
1036 "' avatar='".$r[0]['reply_photo'].
1037 "' link='".$r[0]['plink']."']";
1039 $post .= $r[0]['body'];
1040 $post .= "[/share]";
1041 $_REQUEST['body'] = $post;
1043 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1045 $_REQUEST['profile_uid'] = api_user();
1046 $_REQUEST['type'] = 'wall';
1047 $_REQUEST['api_source'] = true;
1049 require_once('mod/item.php');
1058 return api_apply_template('test', $type, array('$ok' => $ok));
1060 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1065 function api_statuses_destroy(&$a, $type){
1066 if (api_user()===false) return false;
1068 $user_info = api_get_user($a);
1071 $id = intval($a->argv[3]);
1074 $id = intval($_REQUEST["id"]);
1076 logger('API: api_statuses_destroy: '.$id);
1078 require_once('include/items.php');
1079 drop_item($id, false);
1086 return api_apply_template('test', $type, array('$ok' => $ok));
1088 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1092 * http://developer.twitter.com/doc/get/statuses/mentions
1095 function api_statuses_mentions(&$a, $type){
1096 if (api_user()===false) return false;
1098 $user_info = api_get_user($a);
1099 // get last newtork messages
1103 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1104 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1105 if ($page<0) $page=0;
1106 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1107 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1108 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1110 $start = $page*$count;
1112 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1114 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1115 $myurl = substr($myurl,strpos($myurl,'://')+3);
1116 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1117 $myurl = str_replace('www.','',$myurl);
1118 $diasp_url = str_replace('/profile/','/u/',$myurl);
1120 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1121 dbesc(protect_sprintf($myurl)),
1122 dbesc(protect_sprintf($myurl))
1126 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1128 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1129 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1130 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1131 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1132 FROM `item`, `contact`
1133 WHERE `item`.`uid` = %d
1134 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1135 AND `contact`.`id` = `item`.`contact-id`
1136 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1139 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1140 //intval($user_info['uid']),
1143 intval($start), intval($count)
1146 $ret = api_format_items($r,$user_info);
1149 $data = array('$statuses' => $ret);
1153 $data = api_rss_extra($a, $data, $user_info);
1156 $as = api_format_as($a, $ret, $user_info);
1157 $as["title"] = $a->config['sitename']." Mentions";
1158 $as['link']['url'] = $a->get_baseurl()."/";
1163 return api_apply_template("timeline", $type, $data);
1165 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1166 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1169 function api_statuses_user_timeline(&$a, $type){
1170 if (api_user()===false) return false;
1172 $user_info = api_get_user($a);
1173 // get last network messages
1175 logger("api_statuses_user_timeline: api_user: ". api_user() .
1176 "\nuser_info: ".print_r($user_info, true) .
1177 "\n_REQUEST: ".print_r($_REQUEST, true),
1181 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1182 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1183 if ($page<0) $page=0;
1184 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1185 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1186 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1187 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1189 $start = $page*$count;
1192 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1194 if ($exclude_replies > 0)
1195 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1196 if ($conversation_id > 0)
1197 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1199 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1200 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1201 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1202 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1203 FROM `item`, `contact`
1204 WHERE `item`.`uid` = %d
1205 AND `item`.`contact-id` = %d
1206 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1207 AND `contact`.`id` = `item`.`contact-id`
1208 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1211 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1213 intval($user_info['cid']),
1215 intval($start), intval($count)
1218 $ret = api_format_items($r,$user_info, true);
1220 $data = array('$statuses' => $ret);
1224 $data = api_rss_extra($a, $data, $user_info);
1227 return api_apply_template("timeline", $type, $data);
1230 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1233 function api_favorites(&$a, $type){
1234 if (api_user()===false) return false;
1236 $user_info = api_get_user($a);
1237 // in friendica starred item are private
1238 // return favorites only for self
1239 logger('api_favorites: self:' . $user_info['self']);
1241 if ($user_info['self']==0) {
1247 $count = (x($_GET,'count')?$_GET['count']:20);
1248 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1249 if ($page<0) $page=0;
1251 $start = $page*$count;
1253 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1254 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1255 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1256 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1257 FROM `item`, `contact`
1258 WHERE `item`.`uid` = %d
1259 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1260 AND `item`.`starred` = 1
1261 AND `contact`.`id` = `item`.`contact-id`
1262 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1264 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1265 //intval($user_info['uid']),
1267 intval($start), intval($count)
1270 $ret = api_format_items($r,$user_info);
1274 $data = array('$statuses' => $ret);
1278 $data = api_rss_extra($a, $data, $user_info);
1281 return api_apply_template("timeline", $type, $data);
1284 api_register_func('api/favorites','api_favorites', true);
1286 function api_format_as($a, $ret, $user_info) {
1289 $as['title'] = $a->config['sitename']." Public Timeline";
1291 foreach ($ret as $item) {
1292 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1293 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1294 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1295 $avatar[0]["rel"] = "avatar";
1296 $avatar[0]["type"] = "";
1297 $avatar[0]["width"] = 96;
1298 $avatar[0]["height"] = 96;
1299 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1300 $avatar[1]["rel"] = "avatar";
1301 $avatar[1]["type"] = "";
1302 $avatar[1]["width"] = 48;
1303 $avatar[1]["height"] = 48;
1304 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1305 $avatar[2]["rel"] = "avatar";
1306 $avatar[2]["type"] = "";
1307 $avatar[2]["width"] = 24;
1308 $avatar[2]["height"] = 24;
1309 $singleitem["actor"]["avatarLinks"] = $avatar;
1311 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1312 $singleitem["actor"]["image"]["rel"] = "avatar";
1313 $singleitem["actor"]["image"]["type"] = "";
1314 $singleitem["actor"]["image"]["width"] = 96;
1315 $singleitem["actor"]["image"]["height"] = 96;
1316 $singleitem["actor"]["type"] = "person";
1317 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1318 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1319 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1320 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1321 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1322 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1323 $singleitem["actor"]["contact"]["addresses"] = "";
1325 $singleitem["body"] = $item["text"];
1326 $singleitem["object"]["displayName"] = $item["text"];
1327 $singleitem["object"]["id"] = $item["url"];
1328 $singleitem["object"]["type"] = "note";
1329 $singleitem["object"]["url"] = $item["url"];
1330 //$singleitem["context"] =;
1331 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1332 $singleitem["provider"]["objectType"] = "service";
1333 $singleitem["provider"]["displayName"] = "Test";
1334 $singleitem["provider"]["url"] = "http://test.tld";
1335 $singleitem["title"] = $item["text"];
1336 $singleitem["verb"] = "post";
1337 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1338 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1339 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1340 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1341 //$singleitem["original"] = $item;
1342 $items[] = $singleitem;
1344 $as['items'] = $items;
1345 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1346 $as['link']['rel'] = "alternate";
1347 $as['link']['type'] = "text/html";
1351 function api_format_messages($item, $recipient, $sender) {
1352 // standard meta information
1354 'id' => $item['id'],
1355 'sender_id' => $sender['id'] ,
1357 'recipient_id' => $recipient['id'],
1358 'created_at' => api_date($item['created']),
1359 'sender_screen_name' => $sender['screen_name'],
1360 'recipient_screen_name' => $recipient['screen_name'],
1361 'sender' => $sender,
1362 'recipient' => $recipient,
1365 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1366 unset($ret["sender"]["cid"]);
1367 unset($ret["sender"]["uid"]);
1368 unset($ret["sender"]["self"]);
1369 unset($ret["recipient"]["cid"]);
1370 unset($ret["recipient"]["uid"]);
1371 unset($ret["recipient"]["self"]);
1373 //don't send title to regular StatusNET requests to avoid confusing these apps
1374 if (x($_GET, 'getText')) {
1375 $ret['title'] = $item['title'] ;
1376 if ($_GET["getText"] == "html") {
1377 $ret['text'] = bbcode($item['body'], false, false);
1379 elseif ($_GET["getText"] == "plain") {
1380 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1381 $ret['text'] = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1385 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body'], false, false, 2), 0);
1387 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1388 unset($ret['sender']);
1389 unset($ret['recipient']);
1395 function api_format_items($r,$user_info, $filter_user = false) {
1400 foreach($r as $item) {
1401 localize_item($item);
1402 $status_user = api_item_get_user($a,$item);
1404 // Look if the posts are matching if they should be filtered by user id
1405 // To-Do: Fix for wall-to-wall-posts
1406 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1409 if ($item['thr-parent'] != $item['uri']) {
1410 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1412 dbesc($item['thr-parent']));
1414 $in_reply_to_status_id = $r[0]['id'];
1416 $in_reply_to_status_id = $item['parent'];
1418 $in_reply_to_screen_name = NULL;
1419 $in_reply_to_user_id = NULL;
1421 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1423 intval($in_reply_to_status_id));
1425 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1428 $in_reply_to_screen_name = $r[0]['name'];
1429 $in_reply_to_user_id = $r[0]['id'];
1433 $in_reply_to_screen_name = NULL;
1434 $in_reply_to_user_id = NULL;
1435 $in_reply_to_status_id = NULL;
1438 // Workaround for ostatus messages where the title is identically to the body
1439 $statusbody = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1441 $statustitle = trim($item['title']);
1443 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1444 $statustext = trim($statusbody);
1446 $statustext = trim($statustitle."\n\n".$statusbody);
1448 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1449 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1452 'text' => $statustext,
1453 'truncated' => False,
1454 'created_at'=> api_date($item['created']),
1455 'in_reply_to_status_id' => $in_reply_to_status_id,
1456 'source' => (($item['app']) ? $item['app'] : 'web'),
1457 'id' => intval($item['id']),
1458 'in_reply_to_user_id' => $in_reply_to_user_id,
1459 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1461 'favorited' => $item['starred'] ? true : false,
1462 'attachments' => array(),
1463 'user' => $status_user ,
1464 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1465 'statusnet_conversation_id' => $item['parent'],
1468 // Retweets are only valid for top postings
1469 if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1470 $retweeted_status = $status;
1471 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1473 $status["retweeted_status"] = $retweeted_status;
1476 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1477 unset($status["user"]["cid"]);
1478 unset($status["user"]["uid"]);
1479 unset($status["user"]["self"]);
1481 // 'geo' => array('type' => 'Point',
1482 // 'coordinates' => array((float) $notice->lat,
1483 // (float) $notice->lon));
1485 // Seesmic doesn't like the following content
1486 // completely disabled to make friendica totally compatible to the statusnet API
1487 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1489 'updated' => api_date($item['edited']),
1490 'published' => api_date($item['created']),
1491 'message_id' => $item['uri'],
1492 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1493 'coordinates' => $item['coord'],
1494 'place' => $item['location'],
1495 'contributors' => '',
1496 'annotations' => '',
1498 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1499 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1500 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1501 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1504 $status = array_merge($status, $status2);
1513 function api_account_rate_limit_status(&$a,$type) {
1516 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1517 'remaining_hits' => (string) 150,
1518 'hourly_limit' => (string) 150,
1519 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1522 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1524 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1527 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1529 function api_help_test(&$a,$type) {
1536 return api_apply_template('test', $type, array('$ok' => $ok));
1539 api_register_func('api/help/test','api_help_test',false);
1542 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1543 * This function is deprecated by Twitter
1544 * returns: json, xml
1546 function api_statuses_f(&$a, $type, $qtype) {
1547 if (api_user()===false) return false;
1548 $user_info = api_get_user($a);
1551 // friends and followers only for self
1552 if ($user_info['self']==0){
1556 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1557 /* this is to stop Hotot to load friends multiple times
1558 * I'm not sure if I'm missing return something or
1559 * is a bug in hotot. Workaround, meantime
1563 return array('$users' => $ret);*/
1567 if($qtype == 'friends')
1568 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1569 if($qtype == 'followers')
1570 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1572 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1577 foreach($r as $cid){
1578 $user = api_get_user($a, $cid['id']);
1579 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1580 unset($user["cid"]);
1581 unset($user["uid"]);
1582 unset($user["self"]);
1589 return array('$users' => $ret);
1592 function api_statuses_friends(&$a, $type){
1593 $data = api_statuses_f($a,$type,"friends");
1594 if ($data===false) return false;
1595 return api_apply_template("friends", $type, $data);
1597 function api_statuses_followers(&$a, $type){
1598 $data = api_statuses_f($a,$type,"followers");
1599 if ($data===false) return false;
1600 return api_apply_template("friends", $type, $data);
1602 api_register_func('api/statuses/friends','api_statuses_friends',true);
1603 api_register_func('api/statuses/followers','api_statuses_followers',true);
1610 function api_statusnet_config(&$a,$type) {
1611 $name = $a->config['sitename'];
1612 $server = $a->get_hostname();
1613 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1614 $email = $a->config['admin_email'];
1615 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1616 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1617 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1618 if($a->config['api_import_size'])
1619 $texlimit = string($a->config['api_import_size']);
1620 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1621 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1624 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1625 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1626 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1627 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1628 'shorturllength' => '30',
1629 'friendica' => array(
1630 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1631 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1632 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1633 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1638 return api_apply_template('config', $type, array('$config' => $config));
1641 api_register_func('api/statusnet/config','api_statusnet_config',false);
1643 function api_statusnet_version(&$a,$type) {
1647 if($type === 'xml') {
1648 header("Content-type: application/xml");
1649 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1652 elseif($type === 'json') {
1653 header("Content-type: application/json");
1658 api_register_func('api/statusnet/version','api_statusnet_version',false);
1661 function api_ff_ids(&$a,$type,$qtype) {
1665 if($qtype == 'friends')
1666 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1667 if($qtype == 'followers')
1668 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1671 $r = q("SELECT unique_contacts.id FROM contact, unique_contacts WHERE contact.nurl = unique_contacts.url AND `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1677 if($type === 'xml') {
1678 header("Content-type: application/xml");
1679 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1681 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1682 echo '</ids>' . "\r\n";
1685 elseif($type === 'json') {
1687 header("Content-type: application/json");
1688 foreach($r as $rr) $ret[] = $rr['id'];
1689 echo json_encode($ret);
1695 function api_friends_ids(&$a,$type) {
1696 api_ff_ids($a,$type,'friends');
1698 function api_followers_ids(&$a,$type) {
1699 api_ff_ids($a,$type,'followers');
1701 api_register_func('api/friends/ids','api_friends_ids',true);
1702 api_register_func('api/followers/ids','api_followers_ids',true);
1705 function api_direct_messages_new(&$a, $type) {
1706 if (api_user()===false) return false;
1708 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1710 $sender = api_get_user($a);
1712 require_once("include/message.php");
1714 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1716 dbesc($_POST['screen_name']));
1718 $recipient = api_get_user($a, $r[0]['id']);
1721 if (x($_REQUEST,'replyto')) {
1722 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1724 intval($_REQUEST['replyto']));
1725 $replyto = $r[0]['parent-uri'];
1726 $sub = $r[0]['title'];
1729 if (x($_REQUEST,'title')) {
1730 $sub = $_REQUEST['title'];
1733 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1737 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1740 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1741 $ret = api_format_messages($r[0], $recipient, $sender);
1744 $ret = array("error"=>$id);
1747 $data = Array('$messages'=>$ret);
1752 $data = api_rss_extra($a, $data, $user_info);
1755 return api_apply_template("direct_messages", $type, $data);
1758 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1760 function api_direct_messages_box(&$a, $type, $box) {
1761 if (api_user()===false) return false;
1763 $user_info = api_get_user($a);
1766 $count = (x($_GET,'count')?$_GET['count']:20);
1767 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1768 if ($page<0) $page=0;
1770 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1772 $start = $page*$count;
1774 $profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1775 if ($box=="sentbox") {
1776 $sql_extra = "`from-url`='".dbesc( $profile_url )."'";
1778 elseif ($box=="conversation") {
1779 $sql_extra = "`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1781 elseif ($box=="all") {
1782 $sql_extra = "true";
1784 elseif ($box=="inbox") {
1785 $sql_extra = "`from-url`!='".dbesc( $profile_url )."'";
1788 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra AND id > %d ORDER BY created DESC LIMIT %d,%d",
1791 intval($start), intval($count)
1795 foreach($r as $item) {
1796 if ($box == "inbox" || $item['from-url'] != $profile_url){
1797 $recipient = $user_info;
1798 $sender = api_get_user($a,$item['contact-id']);
1800 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1801 $recipient = api_get_user($a,$item['contact-id']);
1802 $sender = $user_info;
1805 $ret[]=api_format_messages($item, $recipient, $sender);
1809 $data = array('$messages' => $ret);
1813 $data = api_rss_extra($a, $data, $user_info);
1816 return api_apply_template("direct_messages", $type, $data);
1820 function api_direct_messages_sentbox(&$a, $type){
1821 return api_direct_messages_box($a, $type, "sentbox");
1823 function api_direct_messages_inbox(&$a, $type){
1824 return api_direct_messages_box($a, $type, "inbox");
1826 function api_direct_messages_all(&$a, $type){
1827 return api_direct_messages_box($a, $type, "all");
1829 function api_direct_messages_conversation(&$a, $type){
1830 return api_direct_messages_box($a, $type, "conversation");
1832 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1833 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1834 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1835 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1839 function api_oauth_request_token(&$a, $type){
1841 $oauth = new FKOAuth1();
1842 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1843 }catch(Exception $e){
1844 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1849 function api_oauth_access_token(&$a, $type){
1851 $oauth = new FKOAuth1();
1852 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1853 }catch(Exception $e){
1854 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1860 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1861 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1866 - renewing of unique contacts
1867 - support of repeated items
1873 Not implemented by now:
1877 statuses/retweets_of_me
1882 account/update_location
1883 account/update_profile_background_image
1884 account/update_profile_image
1888 Not implemented in status.net:
1889 statuses/retweeted_to_me
1890 statuses/retweeted_by_me
1891 direct_messages/destroy
1893 account/update_delivery_device
1894 notifications/follow