3 - Automatically detect if incoming data is HTML or BBCode
4 - search for usernames should first search friendica, then the other open networks, then the closed ones
6 require_once("include/bbcode.php");
7 require_once("include/datetime.php");
8 require_once("include/conversation.php");
9 require_once("include/oauth.php");
10 require_once("include/html2plain.php");
20 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
21 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
22 // into a page, and visitors will post something without noticing it).
23 // Instead, use this function.
24 if ($_SESSION["allow_api"])
30 function api_date($str){
31 //Wed May 23 06:01:13 +0000 2007
32 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
36 function api_register_func($path, $func, $auth=false){
38 $API[$path] = array('func'=>$func,
46 function api_login(&$a){
49 $oauth = new FKOAuth1();
50 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
51 if (!is_null($token)){
52 $oauth->loginUser($token->uid);
53 call_hooks('logged_in', $a->user);
56 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
58 logger(__file__.__line__.__function__."\n".$e);
59 //die(__file__.__line__.__function__."<pre>".$e); die();
64 // workaround for HTTP-auth in CGI mode
65 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
66 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
67 if(strlen($userpass)) {
68 list($name, $password) = explode(':', $userpass);
69 $_SERVER['PHP_AUTH_USER'] = $name;
70 $_SERVER['PHP_AUTH_PW'] = $password;
74 if (!isset($_SERVER['PHP_AUTH_USER'])) {
75 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
76 header('WWW-Authenticate: Basic realm="Friendica"');
77 header('HTTP/1.0 401 Unauthorized');
78 die((api_error(&$a, 'json', "This api requires login")));
80 //die('This api requires login');
83 $user = $_SERVER['PHP_AUTH_USER'];
84 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
88 * next code from mod/auth.php. needs better solution
91 // process normal login request
93 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
94 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
102 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
103 header('WWW-Authenticate: Basic realm="Friendica"');
104 header('HTTP/1.0 401 Unauthorized');
105 die('This api requires login');
108 require_once('include/security.php');
109 authenticate_success($record); $_SESSION["allow_api"] = true;
111 call_hooks('logged_in', $a->user);
115 /**************************
116 * MAIN API ENTRY POINT *
117 **************************/
118 function api_call(&$a){
119 GLOBAL $API, $called_api;
124 foreach ($API as $p=>$info){
125 if (strpos($a->query_string, $p)===0){
126 $called_api= explode("/",$p);
127 //unset($_SERVER['PHP_AUTH_USER']);
128 if ($info['auth']===true && api_user()===false) {
132 load_contact_links(api_user());
134 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
135 logger('API parameters: ' . print_r($_REQUEST,true));
137 if (strpos($a->query_string, ".xml")>0) $type="xml";
138 if (strpos($a->query_string, ".json")>0) $type="json";
139 if (strpos($a->query_string, ".rss")>0) $type="rss";
140 if (strpos($a->query_string, ".atom")>0) $type="atom";
141 if (strpos($a->query_string, ".as")>0) $type="as";
143 $r = call_user_func($info['func'], $a, $type);
144 if ($r===false) return;
148 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
149 header ("Content-Type: text/xml");
150 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
153 header ("Content-Type: application/json");
155 return json_encode($rr);
158 header ("Content-Type: application/rss+xml");
159 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
162 header ("Content-Type: application/atom+xml");
163 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
166 //header ("Content-Type: application/json");
168 // return json_encode($rr);
169 return json_encode($r);
173 //echo "<pre>"; var_dump($r); die();
176 header("HTTP/1.1 404 Not Found");
177 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
178 return(api_error(&$a, $type, "not implemented"));
182 function api_error(&$a, $type, $error) {
183 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
186 header ("Content-Type: text/xml");
187 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
190 header ("Content-Type: application/json");
191 return json_encode(array('error' => $error, 'request' => $a->query_string));
194 header ("Content-Type: application/rss+xml");
195 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
198 header ("Content-Type: application/atom+xml");
199 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
207 function api_rss_extra(&$a, $arr, $user_info){
208 if (is_null($user_info)) $user_info = api_get_user($a);
209 $arr['$user'] = $user_info;
210 $arr['$rss'] = array(
211 'alternate' => $user_info['url'],
212 'self' => $a->get_baseurl(). "/". $a->query_string,
213 'base' => $a->get_baseurl(),
214 'updated' => api_date(null),
215 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
216 'language' => $user_info['language'],
217 'logo' => $a->get_baseurl()."/images/friendica-32.png",
225 * Unique contact to contact url.
227 function api_unique_id_to_url($id){
228 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
231 return ($r[0]["url"]);
237 * Returns user info array.
239 function api_get_user(&$a, $contact_id = Null, $type = "json"){
246 // Searching for contact URL
247 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
248 $user = dbesc(normalise_link($contact_id));
250 $extra_query = "AND `contact`.`nurl` = '%s' ";
251 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
254 // Searching for unique contact id
255 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
256 $user = dbesc(api_unique_id_to_url($contact_id));
259 die(api_error($a, $type, t("User not found.")));
262 $extra_query = "AND `contact`.`nurl` = '%s' ";
263 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
266 if(is_null($user) && x($_GET, 'user_id')) {
267 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
270 die(api_error($a, $type, t("User not found.")));
273 $extra_query = "AND `contact`.`nurl` = '%s' ";
274 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
276 if(is_null($user) && x($_GET, 'screen_name')) {
277 $user = dbesc($_GET['screen_name']);
279 $extra_query = "AND `contact`.`nick` = '%s' ";
280 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
283 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
284 $argid = count($called_api);
285 list($user, $null) = explode(".",$a->argv[$argid]);
286 if(is_numeric($user)){
287 $user = dbesc(api_unique_id_to_url($user));
293 $extra_query = "AND `contact`.`nurl` = '%s' ";
294 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
296 $user = dbesc($user);
298 $extra_query = "AND `contact`.`nick` = '%s' ";
299 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
304 if (api_user()===false) {
305 api_login($a); return False;
307 $user = $_SESSION['uid'];
308 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
313 logger('api_user: ' . $extra_query . ', user: ' . $user);
315 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
321 // if the contact wasn't found, fetch it from the unique contacts
322 if (count($uinfo)==0) {
326 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
328 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
331 // If no nick where given, extract it from the address
332 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
333 $r[0]['nick'] = api_get_nick($r[0]["url"]);
337 'name' => $r[0]["name"],
338 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
340 'description' => NULL,
341 'profile_image_url' => $r[0]["avatar"],
342 'profile_image_url_https' => $r[0]["avatar"],
343 'url' => $r[0]["url"],
344 'protected' => false,
345 'followers_count' => 0,
346 'friends_count' => 0,
347 'created_at' => api_date(0),
348 'favourites_count' => 0,
350 'time_zone' => 'UTC',
351 'statuses_count' => 0,
352 'following' => false,
354 'statusnet_blocking' => false,
355 'notifications' => false,
356 'statusnet_profile_url' => $r[0]["url"],
364 die(api_error($a, $type, t("User not found.")));
368 if($uinfo[0]['self']) {
369 $usr = q("select * from user where uid = %d limit 1",
372 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
376 // count public wall messages
377 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
380 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
381 intval($uinfo[0]['uid'])
383 $countitms = $r[0]['count'];
386 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
387 WHERE `contact-id` = %d
388 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
389 intval($uinfo[0]['id'])
391 $countitms = $r[0]['count'];
395 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
396 WHERE `uid` = %d AND `rel` IN ( %d, %d )
397 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
398 intval($uinfo[0]['uid']),
399 intval(CONTACT_IS_SHARING),
400 intval(CONTACT_IS_FRIEND)
402 $countfriends = $r[0]['count'];
404 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
405 WHERE `uid` = %d AND `rel` IN ( %d, %d )
406 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
407 intval($uinfo[0]['uid']),
408 intval(CONTACT_IS_FOLLOWER),
409 intval(CONTACT_IS_FRIEND)
411 $countfollowers = $r[0]['count'];
413 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
414 intval($uinfo[0]['uid'])
416 $starred = $r[0]['count'];
419 if(! $uinfo[0]['self']) {
425 // Add a nick if it isn't present there
426 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
427 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
428 //if ($uinfo[0]['nick'] != "")
429 // q("UPDATE contact SET nick = '%s' WHERE id = %d",
430 // dbesc($uinfo[0]['nick']), intval($uinfo[0]["id"]));
433 // Fetching unique id
434 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
436 // If not there, then add it
437 if (count($r) == 0) {
438 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
439 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
441 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
445 'id' => intval($r[0]['id']),
446 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
447 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
448 'location' => ($usr) ? $usr[0]['default-location'] : NULL,
449 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
450 'profile_image_url' => $uinfo[0]['micro'],
451 'profile_image_url_https' => $uinfo[0]['micro'],
452 'url' => $uinfo[0]['url'],
453 'protected' => false,
454 'followers_count' => intval($countfollowers),
455 'friends_count' => intval($countfriends),
456 'created_at' => api_date($uinfo[0]['name-date']),
457 'favourites_count' => intval($starred),
458 'utc_offset' => "0", // To-Do
459 'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
460 'statuses_count' => intval($countitms),
461 'following' => true, //#XXX: fix me
462 'verified' => true, //#XXX: fix me
463 'statusnet_blocking' => false,
464 'notifications' => false,
465 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
466 'uid' => intval($uinfo[0]['uid']),
467 'cid' => intval($uinfo[0]['cid']),
468 'self' => $uinfo[0]['self'],
475 function api_item_get_user(&$a, $item) {
477 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
478 dbesc(normalise_link($item['author-link'])));
480 if (count($author) == 0) {
481 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
482 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
484 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
485 dbesc(normalise_link($item['author-link'])));
486 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
487 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
488 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
491 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
492 dbesc(normalise_link($item['owner-link'])));
494 if (count($owner) == 0) {
495 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
496 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
498 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
499 dbesc(normalise_link($item['owner-link'])));
500 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
501 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
502 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
505 // Comments in threads may appear as wall-to-wall postings.
506 // So only take the owner at the top posting.
507 if ($item["id"] == $item["parent"])
508 return api_get_user($a,$item["owner-link"]);
510 return api_get_user($a,$item["author-link"]);
515 * load api $templatename for $type and replace $data array
517 function api_apply_template($templatename, $type, $data){
525 $data = array_xmlify($data);
526 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
528 header ("Content-Type: text/xml");
529 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
532 $ret = replace_macros($tpl, $data);
546 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
547 * returns a 401 status code and an error message if not.
548 * http://developer.twitter.com/doc/get/account/verify_credentials
550 function api_account_verify_credentials(&$a, $type){
551 if (api_user()===false) return false;
553 unset($_REQUEST["user_id"]);
554 unset($_GET["user_id"]);
556 $user_info = api_get_user($a);
558 // "verified" isn't used here in the standard
559 unset($user_info["verified"]);
561 // - Adding last status
562 $user_info["status"] = api_status_show($a,"raw");
563 if (!count($user_info["status"]))
564 unset($user_info["status"]);
566 unset($user_info["status"]["user"]);
568 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
569 unset($user_info["cid"]);
570 unset($user_info["uid"]);
571 unset($user_info["self"]);
573 return api_apply_template("user", $type, array('$user' => $user_info));
576 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
580 * get data from $_POST or $_GET
582 function requestdata($k){
583 if (isset($_POST[$k])){
586 if (isset($_GET[$k])){
592 /*Waitman Gobble Mod*/
593 function api_statuses_mediap(&$a, $type) {
594 if (api_user()===false) {
595 logger('api_statuses_update: no user');
598 $user_info = api_get_user($a);
600 $_REQUEST['type'] = 'wall';
601 $_REQUEST['profile_uid'] = api_user();
602 $_REQUEST['api_source'] = true;
603 $txt = requestdata('status');
604 //$txt = urldecode(requestdata('status'));
606 require_once('library/HTMLPurifier.auto.php');
607 require_once('include/html2bbcode.php');
609 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
610 $txt = html2bb_video($txt);
611 $config = HTMLPurifier_Config::createDefault();
612 $config->set('Cache.DefinitionImpl', null);
613 $purifier = new HTMLPurifier($config);
614 $txt = $purifier->purify($txt);
616 $txt = html2bbcode($txt);
618 $a->argv[1]=$user_info['screen_name']; //should be set to username?
620 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
621 require_once('mod/wall_upload.php');
622 $bebop = wall_upload_post($a);
624 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
625 $_REQUEST['body']=$txt."\n\n".$bebop;
626 require_once('mod/item.php');
629 // this should output the last post (the one we just posted).
630 return api_status_show($a,$type);
632 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
633 /*Waitman Gobble Mod*/
636 function api_statuses_update(&$a, $type) {
637 if (api_user()===false) {
638 logger('api_statuses_update: no user');
641 $user_info = api_get_user($a);
643 // convert $_POST array items to the form we use for web posts.
645 // logger('api_post: ' . print_r($_POST,true));
647 if(requestdata('htmlstatus')) {
648 require_once('library/HTMLPurifier.auto.php');
649 require_once('include/html2bbcode.php');
651 $txt = requestdata('htmlstatus');
652 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
654 $txt = html2bb_video($txt);
656 $config = HTMLPurifier_Config::createDefault();
657 $config->set('Cache.DefinitionImpl', null);
660 $purifier = new HTMLPurifier($config);
661 $txt = $purifier->purify($txt);
663 $_REQUEST['body'] = html2bbcode($txt);
668 $_REQUEST['body'] = requestdata('status');
670 $_REQUEST['title'] = requestdata('title');
672 $parent = requestdata('in_reply_to_status_id');
673 if(ctype_digit($parent))
674 $_REQUEST['parent'] = $parent;
676 $_REQUEST['parent_uri'] = $parent;
678 if(requestdata('lat') && requestdata('long'))
679 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
680 $_REQUEST['profile_uid'] = api_user();
683 $_REQUEST['type'] = 'net-comment';
685 $_REQUEST['type'] = 'wall';
686 if(x($_FILES,'media')) {
687 // upload the image if we have one
688 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
689 require_once('mod/wall_upload.php');
690 $media = wall_upload_post($a);
692 $_REQUEST['body'] .= "\n\n".$media;
696 // set this so that the item_post() function is quiet and doesn't redirect or emit json
698 $_REQUEST['api_source'] = true;
700 // call out normal post function
702 require_once('mod/item.php');
705 // this should output the last post (the one we just posted).
706 return api_status_show($a,$type);
708 api_register_func('api/statuses/update','api_statuses_update', true);
711 function api_status_show(&$a, $type){
712 $user_info = api_get_user($a);
713 // get last public wall message
714 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
715 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
716 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
717 AND `i`.`id` = `item`.`parent`
718 AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
719 AND `item`.`type`!='activity'
720 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
721 ORDER BY `item`.`created` DESC
723 intval($user_info['cid']),
724 dbesc($user_info['url'])
727 if (count($lastwall)>0){
728 $lastwall = $lastwall[0];
730 $in_reply_to_status_id = NULL;
731 $in_reply_to_user_id = NULL;
732 $in_reply_to_screen_name = NULL;
733 if ($lastwall['parent']!=$lastwall['id']) {
734 $in_reply_to_status_id=$lastwall['parent'];
735 //$in_reply_to_user_id = $lastwall['reply_uid'];
736 //$in_reply_to_screen_name = $lastwall['reply_author'];
738 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
740 if ($r[0]['nick'] == "")
741 $r[0]['nick'] = api_get_nick($r[0]["url"]);
743 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
744 $in_reply_to_user_id = $r[0]['id'];
747 $status_info = array(
748 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
749 'truncated' => false,
750 'created_at' => api_date($lastwall['created']),
751 'in_reply_to_status_id' => $in_reply_to_status_id,
752 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
753 'id' => $lastwall['id'],
754 'in_reply_to_user_id' => $in_reply_to_user_id,
755 'in_reply_to_screen_name' => $in_reply_to_screen_name,
757 'favorited' => false,
759 'user' => $user_info,
760 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
761 'statusnet_conversation_id' => $lastwall['parent'],
764 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
765 $status_info["source"] = network_to_name($lastwall['item_network']);
766 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
767 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
769 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
770 unset($status_info["user"]["cid"]);
771 unset($status_info["user"]["uid"]);
772 unset($status_info["user"]["self"]);
776 return($status_info);
778 return api_apply_template("status", $type, array('$status' => $status_info));
787 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
788 * The author's most recent status will be returned inline.
789 * http://developer.twitter.com/doc/get/users/show
791 function api_users_show(&$a, $type){
792 $user_info = api_get_user($a);
794 $lastwall = q("SELECT `item`.*
795 FROM `item`, `contact`
796 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
797 AND `contact`.`id`=`item`.`contact-id`
798 AND `type`!='activity'
799 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
800 ORDER BY `created` DESC
802 intval($user_info['cid']),
803 dbesc($user_info['url'])
806 if (count($lastwall)>0){
807 $lastwall = $lastwall[0];
809 $in_reply_to_status_id = NULL;
810 $in_reply_to_user_id = NULL;
811 $in_reply_to_screen_name = NULL;
812 if ($lastwall['parent']!=$lastwall['id']) {
813 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
814 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
815 if (count($reply)>0) {
816 $in_reply_to_status_id=$lastwall['parent'];
817 //$in_reply_to_user_id = $reply[0]['reply_uid'];
818 //$in_reply_to_screen_name = $reply[0]['reply_author'];
819 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
821 if ($r[0]['nick'] == "")
822 $r[0]['nick'] = api_get_nick($r[0]["url"]);
824 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
825 $in_reply_to_user_id = $r[0]['id'];
829 $user_info['status'] = array(
830 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
831 'truncated' => false,
832 'created_at' => api_date($lastwall['created']),
833 'in_reply_to_status_id' => $in_reply_to_status_id,
834 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
835 'id' => $lastwall['contact-id'],
836 'in_reply_to_user_id' => $in_reply_to_user_id,
837 'in_reply_to_screen_name' => $in_reply_to_screen_name,
839 'favorited' => false,
840 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
841 'statusnet_conversation_id' => $lastwall['parent'],
844 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
845 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
846 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
847 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
851 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
852 unset($user_info["cid"]);
853 unset($user_info["uid"]);
854 unset($user_info["self"]);
856 return api_apply_template("user", $type, array('$user' => $user_info));
859 api_register_func('api/users/show','api_users_show');
863 * http://developer.twitter.com/doc/get/statuses/home_timeline
865 * TODO: Optional parameters
866 * TODO: Add reply info
868 function api_statuses_home_timeline(&$a, $type){
869 if (api_user()===false) return false;
871 unset($_REQUEST["user_id"]);
872 unset($_GET["user_id"]);
874 $user_info = api_get_user($a);
875 // get last newtork messages
879 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
880 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
881 if ($page<0) $page=0;
882 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
883 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
884 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
885 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
886 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
888 $start = $page*$count;
890 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
894 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
895 if ($exclude_replies > 0)
896 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
897 if ($conversation_id > 0)
898 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
900 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
901 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
902 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
903 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
904 FROM `item`, `contact`
905 WHERE `item`.`uid` = %d
906 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
907 AND `contact`.`id` = `item`.`contact-id`
908 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
911 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
912 //intval($user_info['uid']),
915 intval($start), intval($count)
918 $ret = api_format_items($r,$user_info);
920 // We aren't going to try to figure out at the item, group, and page
921 // level which items you've seen and which you haven't. If you're looking
922 // at the network timeline just mark everything seen.
924 $r = q("UPDATE `item` SET `unseen` = 0
925 WHERE `unseen` = 1 AND `uid` = %d",
926 //intval($user_info['uid'])
931 $data = array('$statuses' => $ret);
935 $data = api_rss_extra($a, $data, $user_info);
938 $as = api_format_as($a, $ret, $user_info);
939 $as['title'] = $a->config['sitename']." Home Timeline";
940 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
945 return api_apply_template("timeline", $type, $data);
947 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
948 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
950 function api_statuses_public_timeline(&$a, $type){
951 if (api_user()===false) return false;
953 $user_info = api_get_user($a);
954 // get last newtork messages
958 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
959 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
960 if ($page<0) $page=0;
961 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
962 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
963 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
964 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
965 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
967 $start = $page*$count;
969 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
972 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
973 if ($exclude_replies > 0)
974 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
975 if ($conversation_id > 0)
976 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
978 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
979 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
980 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
981 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
982 `user`.`nickname`, `user`.`hidewall`
983 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
984 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
985 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
986 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
987 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
988 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
989 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
992 ORDER BY `received` DESC LIMIT %d, %d ",
997 $ret = api_format_items($r,$user_info);
1000 $data = array('$statuses' => $ret);
1004 $data = api_rss_extra($a, $data, $user_info);
1007 $as = api_format_as($a, $ret, $user_info);
1008 $as['title'] = $a->config['sitename']." Public Timeline";
1009 $as['link']['url'] = $a->get_baseurl()."/";
1014 return api_apply_template("timeline", $type, $data);
1016 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1021 function api_statuses_show(&$a, $type){
1022 if (api_user()===false) return false;
1024 $user_info = api_get_user($a);
1027 $id = intval($a->argv[3]);
1030 $id = intval($_REQUEST["id"]);
1032 logger('API: api_statuses_show: '.$id);
1034 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1035 $conversation = (x($_REQUEST,'conversation')?1:0);
1039 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1041 $sql_extra .= " AND `item`.`id` = %d";
1043 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1044 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1045 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1046 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1047 FROM `item`, `contact`
1048 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1049 AND `contact`.`id` = `item`.`contact-id`
1050 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1056 die(api_error($a, $type, t("There is no status with this id.")));
1058 $ret = api_format_items($r,$user_info);
1060 if ($conversation) {
1061 $data = array('$statuses' => $ret);
1062 return api_apply_template("timeline", $type, $data);
1064 $data = array('$status' => $ret[0]);
1068 $data = api_rss_extra($a, $data, $user_info);
1070 return api_apply_template("status", $type, $data);
1073 api_register_func('api/statuses/show','api_statuses_show', true);
1079 function api_statuses_repeat(&$a, $type){
1080 if (api_user()===false) return false;
1082 $user_info = api_get_user($a);
1085 $id = intval($a->argv[3]);
1088 $id = intval($_REQUEST["id"]);
1090 logger('API: api_statuses_repeat: '.$id);
1092 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1094 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1095 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1096 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1097 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1098 FROM `item`, `contact`
1099 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1100 AND `contact`.`id` = `item`.`contact-id`
1101 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1103 AND `item`.`id`=%d",
1107 if ($r[0]['body'] != "") {
1108 if (!intval(get_config('system','old_share'))) {
1109 $post = "[share author='".str_replace("'", "'", $r[0]['reply_author']).
1110 "' profile='".$r[0]['reply_url'].
1111 "' avatar='".$r[0]['reply_photo'].
1112 "' link='".$r[0]['plink']."']";
1114 $post .= $r[0]['body'];
1115 $post .= "[/share]";
1116 $_REQUEST['body'] = $post;
1118 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1120 $_REQUEST['profile_uid'] = api_user();
1121 $_REQUEST['type'] = 'wall';
1122 $_REQUEST['api_source'] = true;
1124 require_once('mod/item.php');
1133 return api_apply_template('test', $type, array('$ok' => $ok));
1135 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1140 function api_statuses_destroy(&$a, $type){
1141 if (api_user()===false) return false;
1143 $user_info = api_get_user($a);
1146 $id = intval($a->argv[3]);
1149 $id = intval($_REQUEST["id"]);
1151 logger('API: api_statuses_destroy: '.$id);
1153 require_once('include/items.php');
1154 drop_item($id, false);
1161 return api_apply_template('test', $type, array('$ok' => $ok));
1163 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1167 * http://developer.twitter.com/doc/get/statuses/mentions
1170 function api_statuses_mentions(&$a, $type){
1171 if (api_user()===false) return false;
1173 unset($_REQUEST["user_id"]);
1174 unset($_GET["user_id"]);
1176 $user_info = api_get_user($a);
1177 // get last newtork messages
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 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1186 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1188 $start = $page*$count;
1190 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1192 // Ugly code - should be changed
1193 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1194 $myurl = substr($myurl,strpos($myurl,'://')+3);
1195 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1196 $myurl = str_replace('www.','',$myurl);
1197 $diasp_url = str_replace('/profile/','/u/',$myurl);
1199 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1200 dbesc(protect_sprintf($myurl)),
1201 dbesc(protect_sprintf($myurl))
1205 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1207 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1208 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1209 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1210 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1211 FROM `item`, `contact`
1212 WHERE `item`.`uid` = %d
1213 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1214 AND `contact`.`id` = `item`.`contact-id`
1215 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1218 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1219 //intval($user_info['uid']),
1222 intval($start), intval($count)
1225 $ret = api_format_items($r,$user_info);
1228 $data = array('$statuses' => $ret);
1232 $data = api_rss_extra($a, $data, $user_info);
1235 $as = api_format_as($a, $ret, $user_info);
1236 $as["title"] = $a->config['sitename']." Mentions";
1237 $as['link']['url'] = $a->get_baseurl()."/";
1242 return api_apply_template("timeline", $type, $data);
1244 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1245 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1248 function api_statuses_user_timeline(&$a, $type){
1249 if (api_user()===false) return false;
1251 $user_info = api_get_user($a);
1252 // get last network messages
1254 logger("api_statuses_user_timeline: api_user: ". api_user() .
1255 "\nuser_info: ".print_r($user_info, true) .
1256 "\n_REQUEST: ".print_r($_REQUEST, true),
1260 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1261 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1262 if ($page<0) $page=0;
1263 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1264 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1265 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1266 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1268 $start = $page*$count;
1271 if ($user_info['self']==1)
1272 $sql_extra .= " AND `item`.`wall` = 1 ";
1274 if ($exclude_replies > 0)
1275 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1276 if ($conversation_id > 0)
1277 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1279 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1280 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1281 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1282 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1283 FROM `item`, `contact`
1284 WHERE `item`.`uid` = %d
1285 AND `item`.`contact-id` = %d
1286 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1287 AND `contact`.`id` = `item`.`contact-id`
1288 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1291 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1293 intval($user_info['cid']),
1295 intval($start), intval($count)
1298 $ret = api_format_items($r,$user_info, true);
1300 $data = array('$statuses' => $ret);
1304 $data = api_rss_extra($a, $data, $user_info);
1307 return api_apply_template("timeline", $type, $data);
1310 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1313 function api_favorites(&$a, $type){
1316 if (api_user()===false) return false;
1318 $called_api= array();
1320 $user_info = api_get_user($a);
1322 // in friendica starred item are private
1323 // return favorites only for self
1324 logger('api_favorites: self:' . $user_info['self']);
1326 if ($user_info['self']==0) {
1331 $count = (x($_GET,'count')?$_GET['count']:20);
1332 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1333 if ($page<0) $page=0;
1335 $start = $page*$count;
1337 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1338 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1339 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1340 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1341 FROM `item`, `contact`
1342 WHERE `item`.`uid` = %d
1343 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1344 AND `item`.`starred` = 1
1345 AND `contact`.`id` = `item`.`contact-id`
1346 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1348 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1349 //intval($user_info['uid']),
1351 intval($start), intval($count)
1354 $ret = api_format_items($r,$user_info);
1358 $data = array('$statuses' => $ret);
1362 $data = api_rss_extra($a, $data, $user_info);
1365 return api_apply_template("timeline", $type, $data);
1368 api_register_func('api/favorites','api_favorites', true);
1370 function api_format_as($a, $ret, $user_info) {
1373 $as['title'] = $a->config['sitename']." Public Timeline";
1375 foreach ($ret as $item) {
1376 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1377 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1378 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1379 $avatar[0]["rel"] = "avatar";
1380 $avatar[0]["type"] = "";
1381 $avatar[0]["width"] = 96;
1382 $avatar[0]["height"] = 96;
1383 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1384 $avatar[1]["rel"] = "avatar";
1385 $avatar[1]["type"] = "";
1386 $avatar[1]["width"] = 48;
1387 $avatar[1]["height"] = 48;
1388 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1389 $avatar[2]["rel"] = "avatar";
1390 $avatar[2]["type"] = "";
1391 $avatar[2]["width"] = 24;
1392 $avatar[2]["height"] = 24;
1393 $singleitem["actor"]["avatarLinks"] = $avatar;
1395 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1396 $singleitem["actor"]["image"]["rel"] = "avatar";
1397 $singleitem["actor"]["image"]["type"] = "";
1398 $singleitem["actor"]["image"]["width"] = 96;
1399 $singleitem["actor"]["image"]["height"] = 96;
1400 $singleitem["actor"]["type"] = "person";
1401 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1402 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1403 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1404 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1405 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1406 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1407 $singleitem["actor"]["contact"]["addresses"] = "";
1409 $singleitem["body"] = $item["text"];
1410 $singleitem["object"]["displayName"] = $item["text"];
1411 $singleitem["object"]["id"] = $item["url"];
1412 $singleitem["object"]["type"] = "note";
1413 $singleitem["object"]["url"] = $item["url"];
1414 //$singleitem["context"] =;
1415 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1416 $singleitem["provider"]["objectType"] = "service";
1417 $singleitem["provider"]["displayName"] = "Test";
1418 $singleitem["provider"]["url"] = "http://test.tld";
1419 $singleitem["title"] = $item["text"];
1420 $singleitem["verb"] = "post";
1421 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1422 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1423 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1424 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1425 //$singleitem["original"] = $item;
1426 $items[] = $singleitem;
1428 $as['items'] = $items;
1429 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1430 $as['link']['rel'] = "alternate";
1431 $as['link']['type'] = "text/html";
1435 function api_format_messages($item, $recipient, $sender) {
1436 // standard meta information
1438 'id' => $item['id'],
1439 'sender_id' => $sender['id'] ,
1441 'recipient_id' => $recipient['id'],
1442 'created_at' => api_date($item['created']),
1443 'sender_screen_name' => $sender['screen_name'],
1444 'recipient_screen_name' => $recipient['screen_name'],
1445 'sender' => $sender,
1446 'recipient' => $recipient,
1449 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1450 unset($ret["sender"]["cid"]);
1451 unset($ret["sender"]["uid"]);
1452 unset($ret["sender"]["self"]);
1453 unset($ret["recipient"]["cid"]);
1454 unset($ret["recipient"]["uid"]);
1455 unset($ret["recipient"]["self"]);
1457 //don't send title to regular StatusNET requests to avoid confusing these apps
1458 if (x($_GET, 'getText')) {
1459 $ret['title'] = $item['title'] ;
1460 if ($_GET["getText"] == "html") {
1461 $ret['text'] = bbcode($item['body'], false, false);
1463 elseif ($_GET["getText"] == "plain") {
1464 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1465 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1469 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1471 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1472 unset($ret['sender']);
1473 unset($ret['recipient']);
1479 function api_format_items($r,$user_info, $filter_user = false) {
1484 foreach($r as $item) {
1485 api_share_as_retweet($a, api_user(), $item);
1487 localize_item($item);
1488 $status_user = api_item_get_user($a,$item);
1490 // Look if the posts are matching if they should be filtered by user id
1491 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1494 if ($item['thr-parent'] != $item['uri']) {
1495 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1497 dbesc($item['thr-parent']));
1499 $in_reply_to_status_id = $r[0]['id'];
1501 $in_reply_to_status_id = $item['parent'];
1503 $in_reply_to_screen_name = NULL;
1504 $in_reply_to_user_id = NULL;
1506 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1508 intval($in_reply_to_status_id));
1510 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1513 if ($r[0]['nick'] == "")
1514 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1516 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1517 $in_reply_to_user_id = $r[0]['id'];
1521 $in_reply_to_screen_name = NULL;
1522 $in_reply_to_user_id = NULL;
1523 $in_reply_to_status_id = NULL;
1526 // Workaround for ostatus messages where the title is identically to the body
1527 $statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1529 $statustitle = trim($item['title']);
1531 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1532 $statustext = trim($statusbody);
1534 $statustext = trim($statustitle."\n\n".$statusbody);
1536 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1537 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1540 'text' => $statustext,
1541 'truncated' => False,
1542 'created_at'=> api_date($item['created']),
1543 'in_reply_to_status_id' => $in_reply_to_status_id,
1544 'source' => (($item['app']) ? $item['app'] : 'web'),
1545 'id' => intval($item['id']),
1546 'in_reply_to_user_id' => $in_reply_to_user_id,
1547 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1549 'favorited' => $item['starred'] ? true : false,
1550 //'attachments' => array(),
1551 'user' => $status_user ,
1552 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1553 'statusnet_conversation_id' => $item['parent'],
1556 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1557 $status["source"] = network_to_name($item['item_network']);
1558 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1559 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1562 // Retweets are only valid for top postings
1563 if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1564 $retweeted_status = $status;
1565 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1567 $status["retweeted_status"] = $retweeted_status;
1570 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1571 unset($status["user"]["cid"]);
1572 unset($status["user"]["uid"]);
1573 unset($status["user"]["self"]);
1575 // 'geo' => array('type' => 'Point',
1576 // 'coordinates' => array((float) $notice->lat,
1577 // (float) $notice->lon));
1579 // Seesmic doesn't like the following content
1580 // completely disabled to make friendica totally compatible to the statusnet API
1581 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1583 'updated' => api_date($item['edited']),
1584 'published' => api_date($item['created']),
1585 'message_id' => $item['uri'],
1586 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1587 'coordinates' => $item['coord'],
1588 'place' => $item['location'],
1589 'contributors' => '',
1590 'annotations' => '',
1592 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1593 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1594 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1595 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1598 $status = array_merge($status, $status2);
1607 function api_account_rate_limit_status(&$a,$type) {
1610 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1611 'remaining_hits' => (string) 150,
1612 'hourly_limit' => (string) 150,
1613 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1616 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1618 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1621 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1623 function api_help_test(&$a,$type) {
1630 return api_apply_template('test', $type, array('$ok' => $ok));
1633 api_register_func('api/help/test','api_help_test',false);
1636 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1637 * This function is deprecated by Twitter
1638 * returns: json, xml
1640 function api_statuses_f(&$a, $type, $qtype) {
1641 if (api_user()===false) return false;
1642 $user_info = api_get_user($a);
1645 // friends and followers only for self
1646 if ($user_info['self']==0){
1650 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1651 /* this is to stop Hotot to load friends multiple times
1652 * I'm not sure if I'm missing return something or
1653 * is a bug in hotot. Workaround, meantime
1657 return array('$users' => $ret);*/
1661 if($qtype == 'friends')
1662 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1663 if($qtype == 'followers')
1664 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1666 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1671 foreach($r as $cid){
1672 $user = api_get_user($a, $cid['id']);
1673 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1674 unset($user["cid"]);
1675 unset($user["uid"]);
1676 unset($user["self"]);
1683 return array('$users' => $ret);
1686 function api_statuses_friends(&$a, $type){
1687 $data = api_statuses_f($a,$type,"friends");
1688 if ($data===false) return false;
1689 return api_apply_template("friends", $type, $data);
1691 function api_statuses_followers(&$a, $type){
1692 $data = api_statuses_f($a,$type,"followers");
1693 if ($data===false) return false;
1694 return api_apply_template("friends", $type, $data);
1696 api_register_func('api/statuses/friends','api_statuses_friends',true);
1697 api_register_func('api/statuses/followers','api_statuses_followers',true);
1704 function api_statusnet_config(&$a,$type) {
1705 $name = $a->config['sitename'];
1706 $server = $a->get_hostname();
1707 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1708 $email = $a->config['admin_email'];
1709 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1710 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1711 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1712 if($a->config['api_import_size'])
1713 $texlimit = string($a->config['api_import_size']);
1714 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1715 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1718 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1719 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1720 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1721 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1722 'shorturllength' => '30',
1723 'friendica' => array(
1724 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1725 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1726 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1727 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1732 return api_apply_template('config', $type, array('$config' => $config));
1735 api_register_func('api/statusnet/config','api_statusnet_config',false);
1737 function api_statusnet_version(&$a,$type) {
1741 if($type === 'xml') {
1742 header("Content-type: application/xml");
1743 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1746 elseif($type === 'json') {
1747 header("Content-type: application/json");
1752 api_register_func('api/statusnet/version','api_statusnet_version',false);
1755 function api_ff_ids(&$a,$type,$qtype) {
1759 if($qtype == 'friends')
1760 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1761 if($qtype == 'followers')
1762 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1765 $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",
1771 if($type === 'xml') {
1772 header("Content-type: application/xml");
1773 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1775 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1776 echo '</ids>' . "\r\n";
1779 elseif($type === 'json') {
1781 header("Content-type: application/json");
1782 foreach($r as $rr) $ret[] = $rr['id'];
1783 echo json_encode($ret);
1789 function api_friends_ids(&$a,$type) {
1790 api_ff_ids($a,$type,'friends');
1792 function api_followers_ids(&$a,$type) {
1793 api_ff_ids($a,$type,'followers');
1795 api_register_func('api/friends/ids','api_friends_ids',true);
1796 api_register_func('api/followers/ids','api_followers_ids',true);
1799 function api_direct_messages_new(&$a, $type) {
1800 if (api_user()===false) return false;
1802 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
1804 $sender = api_get_user($a);
1806 require_once("include/message.php");
1808 if ($_POST['screen_name']) {
1809 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1811 dbesc($_POST['screen_name']));
1813 $recipient = api_get_user($a, $r[0]['nurl']);
1815 $recipient = api_get_user($a, $_POST['user_id']);
1819 if (x($_REQUEST,'replyto')) {
1820 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1822 intval($_REQUEST['replyto']));
1823 $replyto = $r[0]['parent-uri'];
1824 $sub = $r[0]['title'];
1827 if (x($_REQUEST,'title')) {
1828 $sub = $_REQUEST['title'];
1831 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1835 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
1838 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1839 $ret = api_format_messages($r[0], $recipient, $sender);
1842 $ret = array("error"=>$id);
1845 $data = Array('$messages'=>$ret);
1850 $data = api_rss_extra($a, $data, $user_info);
1853 return api_apply_template("direct_messages", $type, $data);
1856 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1858 function api_direct_messages_box(&$a, $type, $box) {
1859 if (api_user()===false) return false;
1861 unset($_REQUEST["user_id"]);
1862 unset($_GET["user_id"]);
1864 $user_info = api_get_user($a);
1867 $count = (x($_GET,'count')?$_GET['count']:20);
1868 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1869 if ($page<0) $page=0;
1871 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1873 $start = $page*$count;
1875 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1876 $profile_url = $user_info["url"];
1878 if ($box=="sentbox") {
1879 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
1881 elseif ($box=="conversation") {
1882 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1884 elseif ($box=="all") {
1885 $sql_extra = "true";
1887 elseif ($box=="inbox") {
1888 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
1891 $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",
1894 intval($start), intval($count)
1898 foreach($r as $item) {
1899 if ($box == "inbox" || $item['from-url'] != $profile_url){
1900 $recipient = $user_info;
1901 $sender = api_get_user($a,normalise_link($item['contact-url']));
1903 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1904 $recipient = api_get_user($a,normalise_link($item['contact-url']));
1905 $sender = $user_info;
1909 $ret[]=api_format_messages($item, $recipient, $sender);
1913 $data = array('$messages' => $ret);
1917 $data = api_rss_extra($a, $data, $user_info);
1920 return api_apply_template("direct_messages", $type, $data);
1924 function api_direct_messages_sentbox(&$a, $type){
1925 return api_direct_messages_box($a, $type, "sentbox");
1927 function api_direct_messages_inbox(&$a, $type){
1928 return api_direct_messages_box($a, $type, "inbox");
1930 function api_direct_messages_all(&$a, $type){
1931 return api_direct_messages_box($a, $type, "all");
1933 function api_direct_messages_conversation(&$a, $type){
1934 return api_direct_messages_box($a, $type, "conversation");
1936 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1937 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1938 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1939 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1943 function api_oauth_request_token(&$a, $type){
1945 $oauth = new FKOAuth1();
1946 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1947 }catch(Exception $e){
1948 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1953 function api_oauth_access_token(&$a, $type){
1955 $oauth = new FKOAuth1();
1956 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1957 }catch(Exception $e){
1958 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1964 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1965 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1967 function api_share_as_retweet($a, $uid, &$item) {
1968 $body = trim($item["body"]);
1970 // Skip if it isn't a pure repeated messages
1971 // Does it start with a share?
1972 if (strpos($body, "[share") > 0)
1975 // Does it end with a share?
1976 if (strlen($body) > (strrpos($body, "[/share]") + 8))
1979 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
1980 // Skip if there is no shared message in there
1981 if ($body == $attributes)
1985 preg_match("/author='(.*?)'/ism", $attributes, $matches);
1986 if ($matches[1] != "")
1987 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
1989 preg_match('/author="(.*?)"/ism', $attributes, $matches);
1990 if ($matches[1] != "")
1991 $author = $matches[1];
1994 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
1995 if ($matches[1] != "")
1996 $profile = $matches[1];
1998 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
1999 if ($matches[1] != "")
2000 $profile = $matches[1];
2003 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2004 if ($matches[1] != "")
2005 $avatar = $matches[1];
2007 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2008 if ($matches[1] != "")
2009 $avatar = $matches[1];
2011 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2013 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2016 $item["body"] = $shared_body;
2017 $item["author-name"] = $author;
2018 $item["author-link"] = $profile;
2019 $item["author-avatar"] = $avatar;
2025 function api_get_nick($profile) {
2027 - remove trailing jung from profile url
2028 - pump.io check has to check the websitr
2033 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2034 if ($friendica != $profile)
2038 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2039 if ($diaspora != $profile)
2044 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2045 if ($twitter != $profile)
2051 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2052 if ($StatusnetHost != $profile) {
2053 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2054 if ($StatusnetUser != $profile) {
2055 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2056 $user = json_decode($UserData);
2058 $nick = $user->screen_name;
2063 // To-Do: look at the page if its really a pumpio site
2064 //if (!$nick == "") {
2065 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2066 // if ($pumpio != $profile)
2068 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2073 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2074 dbesc($nick), dbesc(normalise_link($profile)));
2081 function api_clean_plain_items($Text) {
2082 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2086 function api_cleanup_share($shared) {
2087 if ($shared[2] != "type-link")
2090 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2096 if (isset($bookmark[2][0]))
2097 $title = $bookmark[2][0];
2099 if (isset($bookmark[1][0]))
2100 $link = $bookmark[1][0];
2102 if (strpos($shared[1],$title) !== false)
2105 if (strpos($shared[1],$link) !== false)
2108 $text = trim($shared[1]);
2110 //if (strlen($text) < strlen($title))
2111 if (($text == "") AND ($title != ""))
2112 $text .= "\n\n".trim($title);
2115 $text .= "\n".trim($link);
2117 return(trim($text));
2121 Not implemented by now:
2125 statuses/retweets_of_me
2130 account/update_location
2131 account/update_profile_background_image
2132 account/update_profile_image
2136 Not implemented in status.net:
2137 statuses/retweeted_to_me
2138 statuses/retweeted_by_me
2139 direct_messages/destroy
2141 account/update_delivery_device
2142 notifications/follow