3 - Detecting shared items and transfer them as retweeted items
4 - Automatically detect if incoming data is HTML or BBCode
5 - search for usernames should first search friendica, then the other open networks, then the closed ones
7 require_once("include/bbcode.php");
8 require_once("include/datetime.php");
9 require_once("include/conversation.php");
10 require_once("include/oauth.php");
11 require_once("include/html2plain.php");
21 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
22 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
23 // into a page, and visitors will post something without noticing it).
24 // Instead, use this function.
25 if ($_SESSION["allow_api"])
31 function api_date($str){
32 //Wed May 23 06:01:13 +0000 2007
33 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
37 function api_register_func($path, $func, $auth=false){
39 $API[$path] = array('func'=>$func,
47 function api_login(&$a){
50 $oauth = new FKOAuth1();
51 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
52 if (!is_null($token)){
53 $oauth->loginUser($token->uid);
54 call_hooks('logged_in', $a->user);
57 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
59 logger(__file__.__line__.__function__."\n".$e);
60 //die(__file__.__line__.__function__."<pre>".$e); die();
65 // workaround for HTTP-auth in CGI mode
66 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
67 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
68 if(strlen($userpass)) {
69 list($name, $password) = explode(':', $userpass);
70 $_SERVER['PHP_AUTH_USER'] = $name;
71 $_SERVER['PHP_AUTH_PW'] = $password;
75 if (!isset($_SERVER['PHP_AUTH_USER'])) {
76 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
77 header('WWW-Authenticate: Basic realm="Friendica"');
78 header('HTTP/1.0 401 Unauthorized');
79 die((api_error($a, 'json', "This api requires login")));
81 //die('This api requires login');
84 $user = $_SERVER['PHP_AUTH_USER'];
85 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
89 * next code from mod/auth.php. needs better solution
92 // process normal login request
94 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
95 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
103 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
104 header('WWW-Authenticate: Basic realm="Friendica"');
105 header('HTTP/1.0 401 Unauthorized');
106 die('This api requires login');
109 require_once('include/security.php');
110 authenticate_success($record); $_SESSION["allow_api"] = true;
112 call_hooks('logged_in', $a->user);
116 /**************************
117 * MAIN API ENTRY POINT *
118 **************************/
119 function api_call(&$a){
120 GLOBAL $API, $called_api;
125 foreach ($API as $p=>$info){
126 if (strpos($a->query_string, $p)===0){
127 $called_api= explode("/",$p);
128 //unset($_SERVER['PHP_AUTH_USER']);
129 if ($info['auth']===true && api_user()===false) {
133 load_contact_links(api_user());
135 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
136 logger('API parameters: ' . print_r($_REQUEST,true));
138 if (strpos($a->query_string, ".xml")>0) $type="xml";
139 if (strpos($a->query_string, ".json")>0) $type="json";
140 if (strpos($a->query_string, ".rss")>0) $type="rss";
141 if (strpos($a->query_string, ".atom")>0) $type="atom";
142 if (strpos($a->query_string, ".as")>0) $type="as";
144 $r = call_user_func($info['func'], $a, $type);
145 if ($r===false) return;
149 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
150 header ("Content-Type: text/xml");
151 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
154 header ("Content-Type: application/json");
156 return json_encode($rr);
159 header ("Content-Type: application/rss+xml");
160 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
163 header ("Content-Type: application/atom+xml");
164 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
167 //header ("Content-Type: application/json");
169 // return json_encode($rr);
170 return json_encode($r);
174 //echo "<pre>"; var_dump($r); die();
177 header("HTTP/1.1 404 Not Found");
178 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
179 return(api_error($a, $type, "not implemented"));
183 function api_error(&$a, $type, $error) {
184 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
187 header ("Content-Type: text/xml");
188 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
191 header ("Content-Type: application/json");
192 return json_encode(array('error' => $error, 'request' => $a->query_string));
195 header ("Content-Type: application/rss+xml");
196 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
199 header ("Content-Type: application/atom+xml");
200 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
208 function api_rss_extra(&$a, $arr, $user_info){
209 if (is_null($user_info)) $user_info = api_get_user($a);
210 $arr['$user'] = $user_info;
211 $arr['$rss'] = array(
212 'alternate' => $user_info['url'],
213 'self' => $a->get_baseurl(). "/". $a->query_string,
214 'base' => $a->get_baseurl(),
215 'updated' => api_date(null),
216 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
217 'language' => $user_info['language'],
218 'logo' => $a->get_baseurl()."/images/friendica-32.png",
226 * Unique contact to contact url.
228 function api_unique_id_to_url($id){
229 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
232 return ($r[0]["url"]);
238 * Returns user info array.
240 function api_get_user(&$a, $contact_id = Null, $type = "json"){
247 // Searching for contact URL
248 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
249 $user = dbesc(normalise_link($contact_id));
251 $extra_query = "AND `contact`.`nurl` = '%s' ";
252 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
255 // Searching for unique contact id
256 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
257 $user = dbesc(api_unique_id_to_url($contact_id));
260 die(api_error($a, $type, t("User not found.")));
263 $extra_query = "AND `contact`.`nurl` = '%s' ";
264 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
267 if(is_null($user) && x($_GET, 'user_id')) {
268 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
271 die(api_error($a, $type, t("User not found.")));
274 $extra_query = "AND `contact`.`nurl` = '%s' ";
275 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
277 if(is_null($user) && x($_GET, 'screen_name')) {
278 $user = dbesc($_GET['screen_name']);
280 $extra_query = "AND `contact`.`nick` = '%s' ";
281 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
284 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
285 $argid = count($called_api);
286 list($user, $null) = explode(".",$a->argv[$argid]);
287 if(is_numeric($user)){
288 $user = dbesc(api_unique_id_to_url($user));
294 $extra_query = "AND `contact`.`nurl` = '%s' ";
295 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
297 $user = dbesc($user);
299 $extra_query = "AND `contact`.`nick` = '%s' ";
300 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
305 if (api_user()===false) {
306 api_login($a); return False;
308 $user = $_SESSION['uid'];
309 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
314 logger('api_user: ' . $extra_query . ', user: ' . $user);
316 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
322 // if the contact wasn't found, fetch it from the unique contacts
323 if (count($uinfo)==0) {
327 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
329 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
334 'name' => $r[0]["name"],
335 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
337 'description' => NULL,
338 'profile_image_url' => $r[0]["avatar"],
339 'profile_image_url_https' => $r[0]["avatar"],
340 'url' => $r[0]["url"],
341 'protected' => false,
342 'followers_count' => 0,
343 'friends_count' => 0,
344 'created_at' => api_date(0),
345 'favourites_count' => 0,
347 'time_zone' => 'UTC',
348 'statuses_count' => 0,
349 'following' => false,
351 'statusnet_blocking' => false,
352 'notifications' => false,
353 'statusnet_profile_url' => $r[0]["url"],
361 die(api_error($a, $type, t("User not found.")));
365 if($uinfo[0]['self']) {
366 $usr = q("select * from user where uid = %d limit 1",
369 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
373 // count public wall messages
374 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
377 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
378 intval($uinfo[0]['uid'])
380 $countitms = $r[0]['count'];
383 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
384 WHERE `contact-id` = %d
385 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
386 intval($uinfo[0]['id'])
388 $countitms = $r[0]['count'];
392 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
393 WHERE `uid` = %d AND `rel` IN ( %d, %d )
394 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
395 intval($uinfo[0]['uid']),
396 intval(CONTACT_IS_SHARING),
397 intval(CONTACT_IS_FRIEND)
399 $countfriends = $r[0]['count'];
401 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
402 WHERE `uid` = %d AND `rel` IN ( %d, %d )
403 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
404 intval($uinfo[0]['uid']),
405 intval(CONTACT_IS_FOLLOWER),
406 intval(CONTACT_IS_FRIEND)
408 $countfollowers = $r[0]['count'];
410 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
411 intval($uinfo[0]['uid'])
413 $starred = $r[0]['count'];
416 if(! $uinfo[0]['self']) {
422 // Fetching unique id
423 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
425 // If not there, then add it
426 if (count($r) == 0) {
427 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
428 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
430 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
434 'id' => intval($r[0]['id']),
435 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
436 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
437 'location' => ($usr) ? $usr[0]['default-location'] : NULL,
438 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
439 'profile_image_url' => $uinfo[0]['micro'],
440 'profile_image_url_https' => $uinfo[0]['micro'],
441 'url' => $uinfo[0]['url'],
442 'protected' => false,
443 'followers_count' => intval($countfollowers),
444 'friends_count' => intval($countfriends),
445 'created_at' => api_date($uinfo[0]['name-date']),
446 'favourites_count' => intval($starred),
447 'utc_offset' => "0", // To-Do
448 'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
449 'statuses_count' => intval($countitms),
450 'following' => true, //#XXX: fix me
451 'verified' => true, //#XXX: fix me
452 'statusnet_blocking' => false,
453 'notifications' => false,
454 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
455 'uid' => intval($uinfo[0]['uid']),
456 'cid' => intval($uinfo[0]['cid']),
457 'self' => $uinfo[0]['self'],
464 function api_item_get_user(&$a, $item) {
466 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
467 dbesc(normalise_link($item['author-link'])));
469 if (count($author) == 0) {
470 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
471 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
473 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
474 dbesc(normalise_link($item['author-link'])));
475 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
476 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
477 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
480 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
481 dbesc(normalise_link($item['owner-link'])));
483 if (count($owner) == 0) {
484 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
485 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
487 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
488 dbesc(normalise_link($item['owner-link'])));
489 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
490 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
491 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
494 // Comments in threads may appear as wall-to-wall postings.
495 // So only take the owner at the top posting.
496 if ($item["id"] == $item["parent"])
497 return api_get_user($a,$item["owner-link"]);
499 return api_get_user($a,$item["author-link"]);
504 * load api $templatename for $type and replace $data array
506 function api_apply_template($templatename, $type, $data){
514 $data = array_xmlify($data);
515 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
517 header ("Content-Type: text/xml");
518 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
521 $ret = replace_macros($tpl, $data);
535 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
536 * returns a 401 status code and an error message if not.
537 * http://developer.twitter.com/doc/get/account/verify_credentials
539 function api_account_verify_credentials(&$a, $type){
540 if (api_user()===false) return false;
542 unset($_REQUEST["user_id"]);
543 unset($_GET["user_id"]);
545 $user_info = api_get_user($a);
547 // "verified" isn't used here in the standard
548 unset($user_info["verified"]);
550 // - Adding last status
551 $user_info["status"] = api_status_show($a,"raw");
552 if (!count($user_info["status"]))
553 unset($user_info["status"]);
555 unset($user_info["status"]["user"]);
557 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
558 unset($user_info["cid"]);
559 unset($user_info["uid"]);
560 unset($user_info["self"]);
562 return api_apply_template("user", $type, array('$user' => $user_info));
565 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
569 * get data from $_POST or $_GET
571 function requestdata($k){
572 if (isset($_POST[$k])){
575 if (isset($_GET[$k])){
581 /*Waitman Gobble Mod*/
582 function api_statuses_mediap(&$a, $type) {
583 if (api_user()===false) {
584 logger('api_statuses_update: no user');
587 $user_info = api_get_user($a);
589 $_REQUEST['type'] = 'wall';
590 $_REQUEST['profile_uid'] = api_user();
591 $_REQUEST['api_source'] = true;
592 $txt = requestdata('status');
593 //$txt = urldecode(requestdata('status'));
595 require_once('library/HTMLPurifier.auto.php');
596 require_once('include/html2bbcode.php');
598 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
599 $txt = html2bb_video($txt);
600 $config = HTMLPurifier_Config::createDefault();
601 $config->set('Cache.DefinitionImpl', null);
602 $purifier = new HTMLPurifier($config);
603 $txt = $purifier->purify($txt);
605 $txt = html2bbcode($txt);
607 $a->argv[1]=$user_info['screen_name']; //should be set to username?
609 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
610 require_once('mod/wall_upload.php');
611 $bebop = wall_upload_post($a);
613 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
614 $_REQUEST['body']=$txt."\n\n".$bebop;
615 require_once('mod/item.php');
618 // this should output the last post (the one we just posted).
619 return api_status_show($a,$type);
621 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
622 /*Waitman Gobble Mod*/
625 function api_statuses_update(&$a, $type) {
626 if (api_user()===false) {
627 logger('api_statuses_update: no user');
630 $user_info = api_get_user($a);
632 // convert $_POST array items to the form we use for web posts.
634 // logger('api_post: ' . print_r($_POST,true));
636 if(requestdata('htmlstatus')) {
637 require_once('library/HTMLPurifier.auto.php');
638 require_once('include/html2bbcode.php');
640 $txt = requestdata('htmlstatus');
641 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
643 $txt = html2bb_video($txt);
645 $config = HTMLPurifier_Config::createDefault();
646 $config->set('Cache.DefinitionImpl', null);
649 $purifier = new HTMLPurifier($config);
650 $txt = $purifier->purify($txt);
652 $_REQUEST['body'] = html2bbcode($txt);
657 $_REQUEST['body'] = requestdata('status');
659 $_REQUEST['title'] = requestdata('title');
661 $parent = requestdata('in_reply_to_status_id');
662 if(ctype_digit($parent))
663 $_REQUEST['parent'] = $parent;
665 $_REQUEST['parent_uri'] = $parent;
667 if(requestdata('lat') && requestdata('long'))
668 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
669 $_REQUEST['profile_uid'] = api_user();
672 $_REQUEST['type'] = 'net-comment';
674 $_REQUEST['type'] = 'wall';
675 if(x($_FILES,'media')) {
676 // upload the image if we have one
677 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
678 require_once('mod/wall_upload.php');
679 $media = wall_upload_post($a);
681 $_REQUEST['body'] .= "\n\n".$media;
685 // set this so that the item_post() function is quiet and doesn't redirect or emit json
687 $_REQUEST['api_source'] = true;
689 // call out normal post function
691 require_once('mod/item.php');
694 // this should output the last post (the one we just posted).
695 return api_status_show($a,$type);
697 api_register_func('api/statuses/update','api_statuses_update', true);
700 function api_status_show(&$a, $type){
701 $user_info = api_get_user($a);
702 // get last public wall message
703 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
704 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
705 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
706 AND `i`.`id` = `item`.`parent`
707 AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
708 AND `item`.`type`!='activity'
709 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
710 ORDER BY `item`.`created` DESC
712 intval($user_info['cid']),
713 dbesc($user_info['url'])
716 if (count($lastwall)>0){
717 $lastwall = $lastwall[0];
719 $in_reply_to_status_id = NULL;
720 $in_reply_to_user_id = NULL;
721 $in_reply_to_screen_name = NULL;
722 if ($lastwall['parent']!=$lastwall['id']) {
723 $in_reply_to_status_id=$lastwall['parent'];
724 //$in_reply_to_user_id = $lastwall['reply_uid'];
725 //$in_reply_to_screen_name = $lastwall['reply_author'];
727 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
729 $in_reply_to_screen_name = $r[0]['name'];
730 $in_reply_to_user_id = $r[0]['id'];
733 $status_info = array(
734 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
735 'truncated' => false,
736 'created_at' => api_date($lastwall['created']),
737 'in_reply_to_status_id' => $in_reply_to_status_id,
738 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
739 'id' => $lastwall['id'],
740 'in_reply_to_user_id' => $in_reply_to_user_id,
741 'in_reply_to_screen_name' => $in_reply_to_screen_name,
743 'favorited' => false,
745 'user' => $user_info,
746 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
747 'statusnet_conversation_id' => $lastwall['parent'],
750 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
751 $status_info["source"] = network_to_name($lastwall['item_network']);
752 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
753 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
755 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
756 unset($status_info["user"]["cid"]);
757 unset($status_info["user"]["uid"]);
758 unset($status_info["user"]["self"]);
762 return($status_info);
764 return api_apply_template("status", $type, array('$status' => $status_info));
773 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
774 * The author's most recent status will be returned inline.
775 * http://developer.twitter.com/doc/get/users/show
777 function api_users_show(&$a, $type){
778 $user_info = api_get_user($a);
780 $lastwall = q("SELECT `item`.*
781 FROM `item`, `contact`
782 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
783 AND `contact`.`id`=`item`.`contact-id`
784 AND `type`!='activity'
785 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
786 ORDER BY `created` DESC
788 intval($user_info['cid']),
789 dbesc($user_info['url'])
792 if (count($lastwall)>0){
793 $lastwall = $lastwall[0];
795 $in_reply_to_status_id = NULL;
796 $in_reply_to_user_id = NULL;
797 $in_reply_to_screen_name = NULL;
798 if ($lastwall['parent']!=$lastwall['id']) {
799 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
800 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
801 if (count($reply)>0) {
802 $in_reply_to_status_id=$lastwall['parent'];
803 //$in_reply_to_user_id = $reply[0]['reply_uid'];
804 //$in_reply_to_screen_name = $reply[0]['reply_author'];
805 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
807 $in_reply_to_screen_name = $r[0]['name'];
808 $in_reply_to_user_id = $r[0]['id'];
812 $user_info['status'] = array(
813 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
814 'truncated' => false,
815 'created_at' => api_date($lastwall['created']),
816 'in_reply_to_status_id' => $in_reply_to_status_id,
817 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
818 'id' => $lastwall['contact-id'],
819 'in_reply_to_user_id' => $in_reply_to_user_id,
820 'in_reply_to_screen_name' => $in_reply_to_screen_name,
822 'favorited' => false,
823 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
824 'statusnet_conversation_id' => $lastwall['parent'],
827 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
828 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
829 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
830 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
834 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
835 unset($user_info["cid"]);
836 unset($user_info["uid"]);
837 unset($user_info["self"]);
839 return api_apply_template("user", $type, array('$user' => $user_info));
842 api_register_func('api/users/show','api_users_show');
846 * http://developer.twitter.com/doc/get/statuses/home_timeline
848 * TODO: Optional parameters
849 * TODO: Add reply info
851 function api_statuses_home_timeline(&$a, $type){
852 if (api_user()===false) return false;
854 unset($_REQUEST["user_id"]);
855 unset($_GET["user_id"]);
857 $user_info = api_get_user($a);
858 // get last newtork messages
862 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
863 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
864 if ($page<0) $page=0;
865 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
866 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
867 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
868 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
869 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
871 $start = $page*$count;
873 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
877 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
878 if ($exclude_replies > 0)
879 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
880 if ($conversation_id > 0)
881 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
883 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
884 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
885 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
886 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
887 FROM `item`, `contact`
888 WHERE `item`.`uid` = %d
889 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
890 AND `contact`.`id` = `item`.`contact-id`
891 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
894 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
895 //intval($user_info['uid']),
898 intval($start), intval($count)
901 $ret = api_format_items($r,$user_info);
903 // We aren't going to try to figure out at the item, group, and page
904 // level which items you've seen and which you haven't. If you're looking
905 // at the network timeline just mark everything seen.
907 $r = q("UPDATE `item` SET `unseen` = 0
908 WHERE `unseen` = 1 AND `uid` = %d",
909 //intval($user_info['uid'])
914 $data = array('$statuses' => $ret);
918 $data = api_rss_extra($a, $data, $user_info);
921 $as = api_format_as($a, $ret, $user_info);
922 $as['title'] = $a->config['sitename']." Home Timeline";
923 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
928 return api_apply_template("timeline", $type, $data);
930 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
931 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
933 function api_statuses_public_timeline(&$a, $type){
934 if (api_user()===false) return false;
936 $user_info = api_get_user($a);
937 // get last newtork messages
941 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
942 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
943 if ($page<0) $page=0;
944 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
945 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
946 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
947 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
948 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
950 $start = $page*$count;
952 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
955 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
956 if ($exclude_replies > 0)
957 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
958 if ($conversation_id > 0)
959 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
961 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
962 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
963 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
964 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
965 `user`.`nickname`, `user`.`hidewall`
966 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
967 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
968 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
969 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
970 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
971 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
972 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
975 ORDER BY `received` DESC LIMIT %d, %d ",
980 $ret = api_format_items($r,$user_info);
983 $data = array('$statuses' => $ret);
987 $data = api_rss_extra($a, $data, $user_info);
990 $as = api_format_as($a, $ret, $user_info);
991 $as['title'] = $a->config['sitename']." Public Timeline";
992 $as['link']['url'] = $a->get_baseurl()."/";
997 return api_apply_template("timeline", $type, $data);
999 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1004 function api_statuses_show(&$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_show: '.$id);
1017 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1018 $conversation = (x($_REQUEST,'conversation')?1:0);
1022 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1024 $sql_extra .= " AND `item`.`id` = %d";
1026 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1027 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1028 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1029 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1030 FROM `item`, `contact`
1031 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1032 AND `contact`.`id` = `item`.`contact-id`
1033 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1039 die(api_error($a, $type, t("There is no status with this id.")));
1041 $ret = api_format_items($r,$user_info);
1043 if ($conversation) {
1044 $data = array('$statuses' => $ret);
1045 return api_apply_template("timeline", $type, $data);
1047 $data = array('$status' => $ret[0]);
1051 $data = api_rss_extra($a, $data, $user_info);
1053 return api_apply_template("status", $type, $data);
1056 api_register_func('api/statuses/show','api_statuses_show', true);
1062 function api_statuses_repeat(&$a, $type){
1063 if (api_user()===false) return false;
1065 $user_info = api_get_user($a);
1068 $id = intval($a->argv[3]);
1071 $id = intval($_REQUEST["id"]);
1073 logger('API: api_statuses_repeat: '.$id);
1075 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1077 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1078 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1079 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1080 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1081 FROM `item`, `contact`
1082 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1083 AND `contact`.`id` = `item`.`contact-id`
1084 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1086 AND `item`.`id`=%d",
1090 if ($r[0]['body'] != "") {
1091 if (!intval(get_config('system','old_share'))) {
1092 $post = "[share author='".str_replace("'", "'", $r[0]['reply_author']).
1093 "' profile='".$r[0]['reply_url'].
1094 "' avatar='".$r[0]['reply_photo'].
1095 "' link='".$r[0]['plink']."']";
1097 $post .= $r[0]['body'];
1098 $post .= "[/share]";
1099 $_REQUEST['body'] = $post;
1101 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1103 $_REQUEST['profile_uid'] = api_user();
1104 $_REQUEST['type'] = 'wall';
1105 $_REQUEST['api_source'] = true;
1107 require_once('mod/item.php');
1116 return api_apply_template('test', $type, array('$ok' => $ok));
1118 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1123 function api_statuses_destroy(&$a, $type){
1124 if (api_user()===false) return false;
1126 $user_info = api_get_user($a);
1129 $id = intval($a->argv[3]);
1132 $id = intval($_REQUEST["id"]);
1134 logger('API: api_statuses_destroy: '.$id);
1136 require_once('include/items.php');
1137 drop_item($id, false);
1144 return api_apply_template('test', $type, array('$ok' => $ok));
1146 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1150 * http://developer.twitter.com/doc/get/statuses/mentions
1153 function api_statuses_mentions(&$a, $type){
1154 if (api_user()===false) return false;
1156 unset($_REQUEST["user_id"]);
1157 unset($_GET["user_id"]);
1159 $user_info = api_get_user($a);
1160 // get last newtork messages
1164 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1165 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1166 if ($page<0) $page=0;
1167 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1168 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1169 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1171 $start = $page*$count;
1173 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1175 // Ugly code - should be changed
1176 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1177 $myurl = substr($myurl,strpos($myurl,'://')+3);
1178 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1179 $myurl = str_replace('www.','',$myurl);
1180 $diasp_url = str_replace('/profile/','/u/',$myurl);
1182 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1183 dbesc(protect_sprintf($myurl)),
1184 dbesc(protect_sprintf($myurl))
1188 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1190 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1191 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1192 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1193 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1194 FROM `item`, `contact`
1195 WHERE `item`.`uid` = %d
1196 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1197 AND `contact`.`id` = `item`.`contact-id`
1198 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1201 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1202 //intval($user_info['uid']),
1205 intval($start), intval($count)
1208 $ret = api_format_items($r,$user_info);
1211 $data = array('$statuses' => $ret);
1215 $data = api_rss_extra($a, $data, $user_info);
1218 $as = api_format_as($a, $ret, $user_info);
1219 $as["title"] = $a->config['sitename']." Mentions";
1220 $as['link']['url'] = $a->get_baseurl()."/";
1225 return api_apply_template("timeline", $type, $data);
1227 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1228 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1231 function api_statuses_user_timeline(&$a, $type){
1232 if (api_user()===false) return false;
1234 $user_info = api_get_user($a);
1235 // get last network messages
1237 logger("api_statuses_user_timeline: api_user: ". api_user() .
1238 "\nuser_info: ".print_r($user_info, true) .
1239 "\n_REQUEST: ".print_r($_REQUEST, true),
1243 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1244 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1245 if ($page<0) $page=0;
1246 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1247 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1248 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1249 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1251 $start = $page*$count;
1254 if ($user_info['self']==1)
1255 $sql_extra .= " AND `item`.`wall` = 1 ";
1257 if ($exclude_replies > 0)
1258 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1259 if ($conversation_id > 0)
1260 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1262 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1263 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1264 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1265 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1266 FROM `item`, `contact`
1267 WHERE `item`.`uid` = %d
1268 AND `item`.`contact-id` = %d
1269 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1270 AND `contact`.`id` = `item`.`contact-id`
1271 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1274 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1276 intval($user_info['cid']),
1278 intval($start), intval($count)
1281 $ret = api_format_items($r,$user_info, true);
1283 $data = array('$statuses' => $ret);
1287 $data = api_rss_extra($a, $data, $user_info);
1290 return api_apply_template("timeline", $type, $data);
1293 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1296 function api_favorites(&$a, $type){
1299 if (api_user()===false) return false;
1301 $called_api= array();
1303 $user_info = api_get_user($a);
1305 // in friendica starred item are private
1306 // return favorites only for self
1307 logger('api_favorites: self:' . $user_info['self']);
1309 if ($user_info['self']==0) {
1314 $count = (x($_GET,'count')?$_GET['count']:20);
1315 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1316 if ($page<0) $page=0;
1318 $start = $page*$count;
1320 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1321 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1322 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1323 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1324 FROM `item`, `contact`
1325 WHERE `item`.`uid` = %d
1326 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1327 AND `item`.`starred` = 1
1328 AND `contact`.`id` = `item`.`contact-id`
1329 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1331 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1332 //intval($user_info['uid']),
1334 intval($start), intval($count)
1337 $ret = api_format_items($r,$user_info);
1341 $data = array('$statuses' => $ret);
1345 $data = api_rss_extra($a, $data, $user_info);
1348 return api_apply_template("timeline", $type, $data);
1351 api_register_func('api/favorites','api_favorites', true);
1353 function api_format_as($a, $ret, $user_info) {
1356 $as['title'] = $a->config['sitename']." Public Timeline";
1358 foreach ($ret as $item) {
1359 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1360 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1361 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1362 $avatar[0]["rel"] = "avatar";
1363 $avatar[0]["type"] = "";
1364 $avatar[0]["width"] = 96;
1365 $avatar[0]["height"] = 96;
1366 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1367 $avatar[1]["rel"] = "avatar";
1368 $avatar[1]["type"] = "";
1369 $avatar[1]["width"] = 48;
1370 $avatar[1]["height"] = 48;
1371 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1372 $avatar[2]["rel"] = "avatar";
1373 $avatar[2]["type"] = "";
1374 $avatar[2]["width"] = 24;
1375 $avatar[2]["height"] = 24;
1376 $singleitem["actor"]["avatarLinks"] = $avatar;
1378 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1379 $singleitem["actor"]["image"]["rel"] = "avatar";
1380 $singleitem["actor"]["image"]["type"] = "";
1381 $singleitem["actor"]["image"]["width"] = 96;
1382 $singleitem["actor"]["image"]["height"] = 96;
1383 $singleitem["actor"]["type"] = "person";
1384 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1385 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1386 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1387 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1388 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1389 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1390 $singleitem["actor"]["contact"]["addresses"] = "";
1392 $singleitem["body"] = $item["text"];
1393 $singleitem["object"]["displayName"] = $item["text"];
1394 $singleitem["object"]["id"] = $item["url"];
1395 $singleitem["object"]["type"] = "note";
1396 $singleitem["object"]["url"] = $item["url"];
1397 //$singleitem["context"] =;
1398 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1399 $singleitem["provider"]["objectType"] = "service";
1400 $singleitem["provider"]["displayName"] = "Test";
1401 $singleitem["provider"]["url"] = "http://test.tld";
1402 $singleitem["title"] = $item["text"];
1403 $singleitem["verb"] = "post";
1404 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1405 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1406 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1407 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1408 //$singleitem["original"] = $item;
1409 $items[] = $singleitem;
1411 $as['items'] = $items;
1412 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1413 $as['link']['rel'] = "alternate";
1414 $as['link']['type'] = "text/html";
1418 function api_format_messages($item, $recipient, $sender) {
1419 // standard meta information
1421 'id' => $item['id'],
1422 'sender_id' => $sender['id'] ,
1424 'recipient_id' => $recipient['id'],
1425 'created_at' => api_date($item['created']),
1426 'sender_screen_name' => $sender['screen_name'],
1427 'recipient_screen_name' => $recipient['screen_name'],
1428 'sender' => $sender,
1429 'recipient' => $recipient,
1432 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1433 unset($ret["sender"]["cid"]);
1434 unset($ret["sender"]["uid"]);
1435 unset($ret["sender"]["self"]);
1436 unset($ret["recipient"]["cid"]);
1437 unset($ret["recipient"]["uid"]);
1438 unset($ret["recipient"]["self"]);
1440 //don't send title to regular StatusNET requests to avoid confusing these apps
1441 if (x($_GET, 'getText')) {
1442 $ret['title'] = $item['title'] ;
1443 if ($_GET["getText"] == "html") {
1444 $ret['text'] = bbcode($item['body'], false, false);
1446 elseif ($_GET["getText"] == "plain") {
1447 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1448 $ret['text'] = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1452 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body'], false, false, 2), 0);
1454 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1455 unset($ret['sender']);
1456 unset($ret['recipient']);
1462 function api_format_items($r,$user_info, $filter_user = false) {
1467 foreach($r as $item) {
1468 localize_item($item);
1469 $status_user = api_item_get_user($a,$item);
1471 // Look if the posts are matching if they should be filtered by user id
1472 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1475 if ($item['thr-parent'] != $item['uri']) {
1476 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1478 dbesc($item['thr-parent']));
1480 $in_reply_to_status_id = $r[0]['id'];
1482 $in_reply_to_status_id = $item['parent'];
1484 $in_reply_to_screen_name = NULL;
1485 $in_reply_to_user_id = NULL;
1487 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1489 intval($in_reply_to_status_id));
1491 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1494 $in_reply_to_screen_name = $r[0]['name'];
1495 $in_reply_to_user_id = $r[0]['id'];
1499 $in_reply_to_screen_name = NULL;
1500 $in_reply_to_user_id = NULL;
1501 $in_reply_to_status_id = NULL;
1504 // Workaround for ostatus messages where the title is identically to the body
1505 $statusbody = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1507 $statustitle = trim($item['title']);
1509 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1510 $statustext = trim($statusbody);
1512 $statustext = trim($statustitle."\n\n".$statusbody);
1514 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1515 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1518 'text' => $statustext,
1519 'truncated' => False,
1520 'created_at'=> api_date($item['created']),
1521 'in_reply_to_status_id' => $in_reply_to_status_id,
1522 'source' => (($item['app']) ? $item['app'] : 'web'),
1523 'id' => intval($item['id']),
1524 'in_reply_to_user_id' => $in_reply_to_user_id,
1525 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1527 'favorited' => $item['starred'] ? true : false,
1528 //'attachments' => array(),
1529 'user' => $status_user ,
1530 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1531 'statusnet_conversation_id' => $item['parent'],
1534 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1535 $status["source"] = network_to_name($item['item_network']);
1536 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1537 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1540 // Retweets are only valid for top postings
1541 if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1542 $retweeted_status = $status;
1543 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1545 $status["retweeted_status"] = $retweeted_status;
1548 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1549 unset($status["user"]["cid"]);
1550 unset($status["user"]["uid"]);
1551 unset($status["user"]["self"]);
1553 // 'geo' => array('type' => 'Point',
1554 // 'coordinates' => array((float) $notice->lat,
1555 // (float) $notice->lon));
1557 // Seesmic doesn't like the following content
1558 // completely disabled to make friendica totally compatible to the statusnet API
1559 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1561 'updated' => api_date($item['edited']),
1562 'published' => api_date($item['created']),
1563 'message_id' => $item['uri'],
1564 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1565 'coordinates' => $item['coord'],
1566 'place' => $item['location'],
1567 'contributors' => '',
1568 'annotations' => '',
1570 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1571 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1572 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1573 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1576 $status = array_merge($status, $status2);
1585 function api_account_rate_limit_status(&$a,$type) {
1588 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1589 'remaining_hits' => (string) 150,
1590 'hourly_limit' => (string) 150,
1591 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1594 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1596 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1599 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1601 function api_help_test(&$a,$type) {
1608 return api_apply_template('test', $type, array('$ok' => $ok));
1611 api_register_func('api/help/test','api_help_test',false);
1614 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1615 * This function is deprecated by Twitter
1616 * returns: json, xml
1618 function api_statuses_f(&$a, $type, $qtype) {
1619 if (api_user()===false) return false;
1620 $user_info = api_get_user($a);
1623 // friends and followers only for self
1624 if ($user_info['self']==0){
1628 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1629 /* this is to stop Hotot to load friends multiple times
1630 * I'm not sure if I'm missing return something or
1631 * is a bug in hotot. Workaround, meantime
1635 return array('$users' => $ret);*/
1639 if($qtype == 'friends')
1640 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1641 if($qtype == 'followers')
1642 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1644 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1649 foreach($r as $cid){
1650 $user = api_get_user($a, $cid['id']);
1651 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1652 unset($user["cid"]);
1653 unset($user["uid"]);
1654 unset($user["self"]);
1661 return array('$users' => $ret);
1664 function api_statuses_friends(&$a, $type){
1665 $data = api_statuses_f($a,$type,"friends");
1666 if ($data===false) return false;
1667 return api_apply_template("friends", $type, $data);
1669 function api_statuses_followers(&$a, $type){
1670 $data = api_statuses_f($a,$type,"followers");
1671 if ($data===false) return false;
1672 return api_apply_template("friends", $type, $data);
1674 api_register_func('api/statuses/friends','api_statuses_friends',true);
1675 api_register_func('api/statuses/followers','api_statuses_followers',true);
1682 function api_statusnet_config(&$a,$type) {
1683 $name = $a->config['sitename'];
1684 $server = $a->get_hostname();
1685 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1686 $email = $a->config['admin_email'];
1687 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1688 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1689 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1690 if($a->config['api_import_size'])
1691 $texlimit = string($a->config['api_import_size']);
1692 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1693 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1696 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1697 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1698 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1699 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1700 'shorturllength' => '30',
1701 'friendica' => array(
1702 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1703 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1704 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1705 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1710 return api_apply_template('config', $type, array('$config' => $config));
1713 api_register_func('api/statusnet/config','api_statusnet_config',false);
1715 function api_statusnet_version(&$a,$type) {
1719 if($type === 'xml') {
1720 header("Content-type: application/xml");
1721 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1724 elseif($type === 'json') {
1725 header("Content-type: application/json");
1730 api_register_func('api/statusnet/version','api_statusnet_version',false);
1733 function api_ff_ids(&$a,$type,$qtype) {
1737 if($qtype == 'friends')
1738 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1739 if($qtype == 'followers')
1740 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1743 $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",
1749 if($type === 'xml') {
1750 header("Content-type: application/xml");
1751 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1753 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1754 echo '</ids>' . "\r\n";
1757 elseif($type === 'json') {
1759 header("Content-type: application/json");
1760 foreach($r as $rr) $ret[] = $rr['id'];
1761 echo json_encode($ret);
1767 function api_friends_ids(&$a,$type) {
1768 api_ff_ids($a,$type,'friends');
1770 function api_followers_ids(&$a,$type) {
1771 api_ff_ids($a,$type,'followers');
1773 api_register_func('api/friends/ids','api_friends_ids',true);
1774 api_register_func('api/followers/ids','api_followers_ids',true);
1777 function api_direct_messages_new(&$a, $type) {
1778 if (api_user()===false) return false;
1780 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
1782 $sender = api_get_user($a);
1784 require_once("include/message.php");
1786 if ($_POST['screen_name']) {
1787 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1789 dbesc($_POST['screen_name']));
1791 $recipient = api_get_user($a, $r[0]['nurl']);
1793 $recipient = api_get_user($a, $_POST['user_id']);
1797 if (x($_REQUEST,'replyto')) {
1798 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1800 intval($_REQUEST['replyto']));
1801 $replyto = $r[0]['parent-uri'];
1802 $sub = $r[0]['title'];
1805 if (x($_REQUEST,'title')) {
1806 $sub = $_REQUEST['title'];
1809 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1813 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
1816 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1817 $ret = api_format_messages($r[0], $recipient, $sender);
1820 $ret = array("error"=>$id);
1823 $data = Array('$messages'=>$ret);
1828 $data = api_rss_extra($a, $data, $user_info);
1831 return api_apply_template("direct_messages", $type, $data);
1834 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1836 function api_direct_messages_box(&$a, $type, $box) {
1837 if (api_user()===false) return false;
1839 unset($_REQUEST["user_id"]);
1840 unset($_GET["user_id"]);
1842 $user_info = api_get_user($a);
1845 $count = (x($_GET,'count')?$_GET['count']:20);
1846 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1847 if ($page<0) $page=0;
1849 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1851 $start = $page*$count;
1853 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1854 $profile_url = $user_info["url"];
1856 if ($box=="sentbox") {
1857 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
1859 elseif ($box=="conversation") {
1860 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1862 elseif ($box=="all") {
1863 $sql_extra = "true";
1865 elseif ($box=="inbox") {
1866 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
1869 $r = q("SELECT `mail`.*, `contact`.`nurl` AS `contact-url` FROM `mail`,`contact` WHERE `mail`.`contact-id` = `contact`.`id` AND `mail`.`uid`=%d AND $sql_extra AND `mail`.`id` > %d ORDER BY `mail`.`created` DESC LIMIT %d,%d",
1872 intval($start), intval($count)
1876 foreach($r as $item) {
1877 if ($box == "inbox" || $item['from-url'] != $profile_url){
1878 $recipient = $user_info;
1879 $sender = api_get_user($a,normalise_link($item['contact-url']));
1881 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1882 $recipient = api_get_user($a,normalise_link($item['contact-url']));
1883 $sender = $user_info;
1887 $ret[]=api_format_messages($item, $recipient, $sender);
1891 $data = array('$messages' => $ret);
1895 $data = api_rss_extra($a, $data, $user_info);
1898 return api_apply_template("direct_messages", $type, $data);
1902 function api_direct_messages_sentbox(&$a, $type){
1903 return api_direct_messages_box($a, $type, "sentbox");
1905 function api_direct_messages_inbox(&$a, $type){
1906 return api_direct_messages_box($a, $type, "inbox");
1908 function api_direct_messages_all(&$a, $type){
1909 return api_direct_messages_box($a, $type, "all");
1911 function api_direct_messages_conversation(&$a, $type){
1912 return api_direct_messages_box($a, $type, "conversation");
1914 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1915 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1916 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1917 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1921 function api_oauth_request_token(&$a, $type){
1923 $oauth = new FKOAuth1();
1924 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1925 }catch(Exception $e){
1926 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1931 function api_oauth_access_token(&$a, $type){
1933 $oauth = new FKOAuth1();
1934 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1935 }catch(Exception $e){
1936 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1942 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1943 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1946 Not implemented by now:
1950 statuses/retweets_of_me
1955 account/update_location
1956 account/update_profile_background_image
1957 account/update_profile_image
1961 Not implemented in status.net:
1962 statuses/retweeted_to_me
1963 statuses/retweeted_by_me
1964 direct_messages/destroy
1966 account/update_delivery_device
1967 notifications/follow