3 - Automatically detect if incoming data is HTML or BBCode
5 require_once("include/bbcode.php");
6 require_once("include/datetime.php");
7 require_once("include/conversation.php");
8 require_once("include/oauth.php");
9 require_once("include/html2plain.php");
19 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
20 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
21 // into a page, and visitors will post something without noticing it).
22 // Instead, use this function.
23 if ($_SESSION["allow_api"])
29 function api_date($str){
30 //Wed May 23 06:01:13 +0000 2007
31 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
35 function api_register_func($path, $func, $auth=false){
37 $API[$path] = array('func'=>$func, 'auth'=>$auth);
39 // Workaround for hotot
40 $path = str_replace("api/", "api/1.1/", $path);
41 $API[$path] = array('func'=>$func, 'auth'=>$auth);
48 function api_login(&$a){
51 $oauth = new FKOAuth1();
52 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
53 if (!is_null($token)){
54 $oauth->loginUser($token->uid);
55 call_hooks('logged_in', $a->user);
58 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
60 logger(__file__.__line__.__function__."\n".$e);
61 //die(__file__.__line__.__function__."<pre>".$e); die();
66 // workaround for HTTP-auth in CGI mode
67 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
68 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
69 if(strlen($userpass)) {
70 list($name, $password) = explode(':', $userpass);
71 $_SERVER['PHP_AUTH_USER'] = $name;
72 $_SERVER['PHP_AUTH_PW'] = $password;
76 if (!isset($_SERVER['PHP_AUTH_USER'])) {
77 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
78 header('WWW-Authenticate: Basic realm="Friendica"');
79 header('HTTP/1.0 401 Unauthorized');
80 die((api_error($a, 'json', "This api requires login")));
82 //die('This api requires login');
85 $user = $_SERVER['PHP_AUTH_USER'];
86 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
90 * next code from mod/auth.php. needs better solution
93 // process normal login request
95 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
96 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
104 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
105 header('WWW-Authenticate: Basic realm="Friendica"');
106 header('HTTP/1.0 401 Unauthorized');
107 die('This api requires login');
110 require_once('include/security.php');
111 authenticate_success($record); $_SESSION["allow_api"] = true;
113 call_hooks('logged_in', $a->user);
117 /**************************
118 * MAIN API ENTRY POINT *
119 **************************/
120 function api_call(&$a){
121 GLOBAL $API, $called_api;
126 foreach ($API as $p=>$info){
127 if (strpos($a->query_string, $p)===0){
128 $called_api= explode("/",$p);
129 //unset($_SERVER['PHP_AUTH_USER']);
130 if ($info['auth']===true && api_user()===false) {
134 load_contact_links(api_user());
136 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
137 logger('API parameters: ' . print_r($_REQUEST,true));
139 if (strpos($a->query_string, ".xml")>0) $type="xml";
140 if (strpos($a->query_string, ".json")>0) $type="json";
141 if (strpos($a->query_string, ".rss")>0) $type="rss";
142 if (strpos($a->query_string, ".atom")>0) $type="atom";
143 if (strpos($a->query_string, ".as")>0) $type="as";
145 $r = call_user_func($info['func'], $a, $type);
146 if ($r===false) return;
150 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
151 header ("Content-Type: text/xml");
152 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
155 header ("Content-Type: application/json");
157 return json_encode($rr);
160 header ("Content-Type: application/rss+xml");
161 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
164 header ("Content-Type: application/atom+xml");
165 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
168 //header ("Content-Type: application/json");
170 // return json_encode($rr);
171 return json_encode($r);
175 //echo "<pre>"; var_dump($r); die();
178 header("HTTP/1.1 404 Not Found");
179 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
180 return(api_error($a, $type, "not implemented"));
184 function api_error(&$a, $type, $error) {
185 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
188 header ("Content-Type: text/xml");
189 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
192 header ("Content-Type: application/json");
193 return json_encode(array('error' => $error, 'request' => $a->query_string));
196 header ("Content-Type: application/rss+xml");
197 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
200 header ("Content-Type: application/atom+xml");
201 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
209 function api_rss_extra(&$a, $arr, $user_info){
210 if (is_null($user_info)) $user_info = api_get_user($a);
211 $arr['$user'] = $user_info;
212 $arr['$rss'] = array(
213 'alternate' => $user_info['url'],
214 'self' => $a->get_baseurl(). "/". $a->query_string,
215 'base' => $a->get_baseurl(),
216 'updated' => api_date(null),
217 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
218 'language' => $user_info['language'],
219 'logo' => $a->get_baseurl()."/images/friendica-32.png",
227 * Unique contact to contact url.
229 function api_unique_id_to_url($id){
230 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
233 return ($r[0]["url"]);
239 * Returns user info array.
241 function api_get_user(&$a, $contact_id = Null, $type = "json"){
248 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
250 // Searching for contact URL
251 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
252 $user = dbesc(normalise_link($contact_id));
254 $extra_query = "AND `contact`.`nurl` = '%s' ";
255 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
258 // Searching for unique contact id
259 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
260 $user = dbesc(api_unique_id_to_url($contact_id));
263 die(api_error($a, $type, t("User not found.")));
266 $extra_query = "AND `contact`.`nurl` = '%s' ";
267 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
270 if(is_null($user) && x($_GET, 'user_id')) {
271 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
274 die(api_error($a, $type, t("User not found.")));
277 $extra_query = "AND `contact`.`nurl` = '%s' ";
278 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
280 if(is_null($user) && x($_GET, 'screen_name')) {
281 $user = dbesc($_GET['screen_name']);
283 $extra_query = "AND `contact`.`nick` = '%s' ";
284 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
287 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
288 $argid = count($called_api);
289 list($user, $null) = explode(".",$a->argv[$argid]);
290 if(is_numeric($user)){
291 $user = dbesc(api_unique_id_to_url($user));
297 $extra_query = "AND `contact`.`nurl` = '%s' ";
298 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
300 $user = dbesc($user);
302 $extra_query = "AND `contact`.`nick` = '%s' ";
303 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
307 logger("api_get_user: user ".$user, LOGGER_DEBUG);
310 if (api_user()===false) {
311 api_login($a); return False;
313 $user = $_SESSION['uid'];
314 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
319 logger('api_user: ' . $extra_query . ', user: ' . $user);
321 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
327 // Selecting the id by priority, friendica first
328 api_best_nickname($uinfo);
330 // if the contact wasn't found, fetch it from the unique contacts
331 if (count($uinfo)==0) {
335 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
337 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
340 // If no nick where given, extract it from the address
341 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
342 $r[0]['nick'] = api_get_nick($r[0]["url"]);
346 'id_str' => (string) $r[0]["id"],
347 'name' => $r[0]["name"],
348 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
350 'description' => NULL,
351 'profile_image_url' => $r[0]["avatar"],
352 'profile_image_url_https' => $r[0]["avatar"],
353 'url' => $r[0]["url"],
354 'protected' => false,
355 'followers_count' => 0,
356 'friends_count' => 0,
357 'created_at' => api_date(0),
358 'favourites_count' => 0,
360 'time_zone' => 'UTC',
361 'statuses_count' => 0,
362 'following' => false,
364 'statusnet_blocking' => false,
365 'notifications' => false,
366 'statusnet_profile_url' => $r[0]["url"],
375 die(api_error($a, $type, t("User not found.")));
379 if($uinfo[0]['self']) {
380 $usr = q("select * from user where uid = %d limit 1",
383 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
387 // count public wall messages
388 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
391 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
392 intval($uinfo[0]['uid'])
394 $countitms = $r[0]['count'];
397 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
398 WHERE `contact-id` = %d
399 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
400 intval($uinfo[0]['id'])
402 $countitms = $r[0]['count'];
406 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
407 WHERE `uid` = %d AND `rel` IN ( %d, %d )
408 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
409 intval($uinfo[0]['uid']),
410 intval(CONTACT_IS_SHARING),
411 intval(CONTACT_IS_FRIEND)
413 $countfriends = $r[0]['count'];
415 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
416 WHERE `uid` = %d AND `rel` IN ( %d, %d )
417 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
418 intval($uinfo[0]['uid']),
419 intval(CONTACT_IS_FOLLOWER),
420 intval(CONTACT_IS_FRIEND)
422 $countfollowers = $r[0]['count'];
424 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
425 intval($uinfo[0]['uid'])
427 $starred = $r[0]['count'];
430 if(! $uinfo[0]['self']) {
436 // Add a nick if it isn't present there
437 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
438 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
439 //if ($uinfo[0]['nick'] != "")
440 // q("UPDATE contact SET nick = '%s' WHERE id = %d",
441 // dbesc($uinfo[0]['nick']), intval($uinfo[0]["id"]));
444 // Fetching unique id
445 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
447 // If not there, then add it
448 if (count($r) == 0) {
449 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
450 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
452 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
455 require_once('include/contact_selectors.php');
456 $network_name = network_to_name($uinfo[0]['network']);
459 'id' => intval($r[0]['id']),
460 'id_str' => (string) intval($r[0]['id']),
461 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
462 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
463 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
464 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
465 'profile_image_url' => $uinfo[0]['micro'],
466 'profile_image_url_https' => $uinfo[0]['micro'],
467 'url' => $uinfo[0]['url'],
468 'protected' => false,
469 'followers_count' => intval($countfollowers),
470 'friends_count' => intval($countfriends),
471 'created_at' => api_date($uinfo[0]['created']),
472 'favourites_count' => intval($starred),
474 'time_zone' => 'UTC',
475 'statuses_count' => intval($countitms),
476 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
478 'statusnet_blocking' => false,
479 'notifications' => false,
480 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
481 'uid' => intval($uinfo[0]['uid']),
482 'cid' => intval($uinfo[0]['cid']),
483 'self' => $uinfo[0]['self'],
484 'network' => $uinfo[0]['network'],
491 function api_item_get_user(&$a, $item) {
493 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
494 dbesc(normalise_link($item['author-link'])));
496 if (count($author) == 0) {
497 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
498 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
500 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
501 dbesc(normalise_link($item['author-link'])));
502 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
503 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
504 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
507 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
508 dbesc(normalise_link($item['owner-link'])));
510 if (count($owner) == 0) {
511 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
512 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
514 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
515 dbesc(normalise_link($item['owner-link'])));
516 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
517 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
518 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
521 // Comments in threads may appear as wall-to-wall postings.
522 // So only take the owner at the top posting.
523 if ($item["id"] == $item["parent"])
524 $status_user = api_get_user($a,$item["owner-link"]);
526 $status_user = api_get_user($a,$item["author-link"]);
528 $status_user["protected"] = (($item["allow_cid"] != "") OR
529 ($item["allow_gid"] != "") OR
530 ($item["deny_cid"] != "") OR
531 ($item["deny_gid"] != ""));
533 return ($status_user);
538 * load api $templatename for $type and replace $data array
540 function api_apply_template($templatename, $type, $data){
548 $data = array_xmlify($data);
549 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
551 header ("Content-Type: text/xml");
552 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
555 $ret = replace_macros($tpl, $data);
570 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
571 * returns a 401 status code and an error message if not.
572 * http://developer.twitter.com/doc/get/account/verify_credentials
574 function api_account_verify_credentials(&$a, $type){
575 if (api_user()===false) return false;
577 unset($_REQUEST["user_id"]);
578 unset($_GET["user_id"]);
580 unset($_REQUEST["screen_name"]);
581 unset($_GET["screen_name"]);
583 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
585 $user_info = api_get_user($a);
587 // "verified" isn't used here in the standard
588 unset($user_info["verified"]);
590 // - Adding last status
592 $user_info["status"] = api_status_show($a,"raw");
593 if (!count($user_info["status"]))
594 unset($user_info["status"]);
596 unset($user_info["status"]["user"]);
599 // "uid" and "self" are only needed for some internal stuff, so remove it from here
600 unset($user_info["uid"]);
601 unset($user_info["self"]);
603 return api_apply_template("user", $type, array('$user' => $user_info));
606 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
610 * get data from $_POST or $_GET
612 function requestdata($k){
613 if (isset($_POST[$k])){
616 if (isset($_GET[$k])){
622 /*Waitman Gobble Mod*/
623 function api_statuses_mediap(&$a, $type) {
624 if (api_user()===false) {
625 logger('api_statuses_update: no user');
628 $user_info = api_get_user($a);
630 $_REQUEST['type'] = 'wall';
631 $_REQUEST['profile_uid'] = api_user();
632 $_REQUEST['api_source'] = true;
633 $txt = requestdata('status');
634 //$txt = urldecode(requestdata('status'));
636 require_once('library/HTMLPurifier.auto.php');
637 require_once('include/html2bbcode.php');
639 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
640 $txt = html2bb_video($txt);
641 $config = HTMLPurifier_Config::createDefault();
642 $config->set('Cache.DefinitionImpl', null);
643 $purifier = new HTMLPurifier($config);
644 $txt = $purifier->purify($txt);
646 $txt = html2bbcode($txt);
648 $a->argv[1]=$user_info['screen_name']; //should be set to username?
650 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
651 require_once('mod/wall_upload.php');
652 $bebop = wall_upload_post($a);
654 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
655 $_REQUEST['body']=$txt."\n\n".$bebop;
656 require_once('mod/item.php');
659 // this should output the last post (the one we just posted).
660 return api_status_show($a,$type);
662 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
663 /*Waitman Gobble Mod*/
666 function api_statuses_update(&$a, $type) {
667 if (api_user()===false) {
668 logger('api_statuses_update: no user');
671 $user_info = api_get_user($a);
673 // convert $_POST array items to the form we use for web posts.
675 // logger('api_post: ' . print_r($_POST,true));
677 if(requestdata('htmlstatus')) {
678 require_once('library/HTMLPurifier.auto.php');
679 require_once('include/html2bbcode.php');
681 $txt = requestdata('htmlstatus');
682 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
684 $txt = html2bb_video($txt);
686 $config = HTMLPurifier_Config::createDefault();
687 $config->set('Cache.DefinitionImpl', null);
690 $purifier = new HTMLPurifier($config);
691 $txt = $purifier->purify($txt);
693 $_REQUEST['body'] = html2bbcode($txt);
698 $_REQUEST['body'] = requestdata('status');
700 $_REQUEST['title'] = requestdata('title');
702 $parent = requestdata('in_reply_to_status_id');
703 if(ctype_digit($parent))
704 $_REQUEST['parent'] = $parent;
706 $_REQUEST['parent_uri'] = $parent;
708 if(requestdata('lat') && requestdata('long'))
709 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
710 $_REQUEST['profile_uid'] = api_user();
713 $_REQUEST['type'] = 'net-comment';
715 $_REQUEST['type'] = 'wall';
716 if(x($_FILES,'media')) {
717 // upload the image if we have one
718 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
719 require_once('mod/wall_upload.php');
720 $media = wall_upload_post($a);
722 $_REQUEST['body'] .= "\n\n".$media;
726 // set this so that the item_post() function is quiet and doesn't redirect or emit json
728 $_REQUEST['api_source'] = true;
730 // call out normal post function
732 require_once('mod/item.php');
735 // this should output the last post (the one we just posted).
736 return api_status_show($a,$type);
738 api_register_func('api/statuses/update','api_statuses_update', true);
739 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
742 function api_status_show(&$a, $type){
743 $user_info = api_get_user($a);
745 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
747 // get last public wall message
748 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
749 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
750 WHERE `item`.`contact-id` = %d
751 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
752 AND `i`.`id` = `item`.`parent`
753 AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
754 AND `item`.`type`!='activity'
755 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
756 ORDER BY `item`.`created` DESC
758 intval($user_info['cid']),
759 dbesc($user_info['url']),
760 dbesc(normalise_link($user_info['url'])),
761 dbesc($user_info['url']),
762 dbesc(normalise_link($user_info['url']))
765 if (count($lastwall)>0){
766 $lastwall = $lastwall[0];
768 $in_reply_to_status_id = NULL;
769 $in_reply_to_user_id = NULL;
770 $in_reply_to_status_id_str = NULL;
771 $in_reply_to_user_id_str = NULL;
772 $in_reply_to_screen_name = NULL;
773 if ($lastwall['parent']!=$lastwall['id']) {
774 $in_reply_to_status_id= intval($lastwall['parent']);
775 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
776 //$in_reply_to_user_id = $lastwall['reply_uid'];
777 //$in_reply_to_screen_name = $lastwall['reply_author'];
779 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
781 if ($r[0]['nick'] == "")
782 $r[0]['nick'] = api_get_nick($r[0]["url"]);
784 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
785 $in_reply_to_user_id = intval($r[0]['id']);
786 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
790 $status_info = array(
791 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
792 'truncated' => false,
793 'created_at' => api_date($lastwall['created']),
794 'in_reply_to_status_id' => $in_reply_to_status_id,
795 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
796 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
797 'id' => intval($lastwall['id']),
798 'id_str' => (string) $lastwall['id'],
799 'in_reply_to_user_id' => $in_reply_to_user_id,
800 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
801 'in_reply_to_screen_name' => $in_reply_to_screen_name,
803 'favorited' => false,
805 'user' => $user_info,
806 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
807 'statusnet_conversation_id' => $lastwall['parent'],
810 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
811 if (count($entities) > 0)
812 $status_info['entities'] = $entities;
814 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
815 $status_info["source"] = network_to_name($lastwall['item_network']);
816 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
817 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
819 // "uid" and "self" are only needed for some internal stuff, so remove it from here
820 unset($status_info["user"]["uid"]);
821 unset($status_info["user"]["self"]);
825 return($status_info);
827 return api_apply_template("status", $type, array('$status' => $status_info));
836 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
837 * The author's most recent status will be returned inline.
838 * http://developer.twitter.com/doc/get/users/show
840 function api_users_show(&$a, $type){
841 $user_info = api_get_user($a);
843 $lastwall = q("SELECT `item`.*
844 FROM `item`, `contact`
845 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d
846 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
847 AND `contact`.`id`=`item`.`contact-id`
848 AND `type`!='activity'
849 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
850 ORDER BY `created` DESC
853 intval($user_info['cid']),
854 dbesc($user_info['url']),
855 dbesc(normalise_link($user_info['url'])),
856 dbesc($user_info['url']),
857 dbesc(normalise_link($user_info['url']))
859 //print_r($user_info);
860 if (count($lastwall)>0){
861 $lastwall = $lastwall[0];
863 $in_reply_to_status_id = NULL;
864 $in_reply_to_user_id = NULL;
865 $in_reply_to_status_id_str = NULL;
866 $in_reply_to_user_id_str = NULL;
867 $in_reply_to_screen_name = NULL;
868 if ($lastwall['parent']!=$lastwall['id']) {
869 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
870 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
871 if (count($reply)>0) {
872 $in_reply_to_status_id = intval($lastwall['parent']);
873 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
875 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
877 if ($r[0]['nick'] == "")
878 $r[0]['nick'] = api_get_nick($r[0]["url"]);
880 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
881 $in_reply_to_user_id = intval($r[0]['id']);
882 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
886 $user_info['status'] = array(
887 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
888 'truncated' => false,
889 'created_at' => api_date($lastwall['created']),
890 'in_reply_to_status_id' => $in_reply_to_status_id,
891 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
892 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
893 'id' => intval($lastwall['contact-id']),
894 'id_str' => (string) $lastwall['contact-id'],
895 'in_reply_to_user_id' => $in_reply_to_user_id,
896 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
897 'in_reply_to_screen_name' => $in_reply_to_screen_name,
899 'favorited' => false,
900 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
901 'statusnet_conversation_id' => $lastwall['parent'],
904 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
905 if (count($entities) > 0)
906 $user_info['entities'] = $entities;
908 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
909 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
910 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
911 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
915 // "uid" and "self" are only needed for some internal stuff, so remove it from here
916 unset($user_info["uid"]);
917 unset($user_info["self"]);
919 return api_apply_template("user", $type, array('$user' => $user_info));
922 api_register_func('api/users/show','api_users_show');
926 * http://developer.twitter.com/doc/get/statuses/home_timeline
928 * TODO: Optional parameters
929 * TODO: Add reply info
931 function api_statuses_home_timeline(&$a, $type){
932 if (api_user()===false) return false;
934 unset($_REQUEST["user_id"]);
935 unset($_GET["user_id"]);
937 unset($_REQUEST["screen_name"]);
938 unset($_GET["screen_name"]);
940 $user_info = api_get_user($a);
941 // get last newtork messages
945 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
946 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
947 if ($page<0) $page=0;
948 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
949 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
950 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
951 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
952 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
954 $start = $page*$count;
958 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
959 if ($exclude_replies > 0)
960 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
961 if ($conversation_id > 0)
962 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
964 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
965 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
966 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
967 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
968 FROM `item`, `contact`
969 WHERE `item`.`uid` = %d
970 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
971 AND `contact`.`id` = `item`.`contact-id`
972 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
975 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
976 //intval($user_info['uid']),
979 intval($start), intval($count)
982 $ret = api_format_items($r,$user_info);
984 // We aren't going to try to figure out at the item, group, and page
985 // level which items you've seen and which you haven't. If you're looking
986 // at the network timeline just mark everything seen.
988 $r = q("UPDATE `item` SET `unseen` = 0
989 WHERE `unseen` = 1 AND `uid` = %d",
990 //intval($user_info['uid'])
995 $data = array('$statuses' => $ret);
999 $data = api_rss_extra($a, $data, $user_info);
1002 $as = api_format_as($a, $ret, $user_info);
1003 $as['title'] = $a->config['sitename']." Home Timeline";
1004 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1009 return api_apply_template("timeline", $type, $data);
1011 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1012 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1014 function api_statuses_public_timeline(&$a, $type){
1015 if (api_user()===false) return false;
1017 $user_info = api_get_user($a);
1018 // get last newtork messages
1022 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1023 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1024 if ($page<0) $page=0;
1025 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1026 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1027 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1028 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1029 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1031 $start = $page*$count;
1034 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1035 if ($exclude_replies > 0)
1036 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1037 if ($conversation_id > 0)
1038 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1040 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1041 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1042 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1043 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1044 `user`.`nickname`, `user`.`hidewall`
1045 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1046 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1047 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1048 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1049 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1050 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1051 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1054 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1059 $ret = api_format_items($r,$user_info);
1062 $data = array('$statuses' => $ret);
1066 $data = api_rss_extra($a, $data, $user_info);
1069 $as = api_format_as($a, $ret, $user_info);
1070 $as['title'] = $a->config['sitename']." Public Timeline";
1071 $as['link']['url'] = $a->get_baseurl()."/";
1076 return api_apply_template("timeline", $type, $data);
1078 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1083 function api_statuses_show(&$a, $type){
1084 if (api_user()===false) return false;
1086 $user_info = api_get_user($a);
1089 $id = intval($a->argv[3]);
1092 $id = intval($_REQUEST["id"]);
1096 $id = intval($a->argv[4]);
1098 logger('API: api_statuses_show: '.$id);
1100 $conversation = (x($_REQUEST,'conversation')?1:0);
1104 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1106 $sql_extra .= " AND `item`.`id` = %d";
1108 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1109 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1110 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1111 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1112 FROM `item`, `contact`
1113 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1114 AND `contact`.`id` = `item`.`contact-id`
1115 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1121 die(api_error($a, $type, t("There is no status with this id.")));
1123 $ret = api_format_items($r,$user_info);
1125 if ($conversation) {
1126 $data = array('$statuses' => $ret);
1127 return api_apply_template("timeline", $type, $data);
1129 $data = array('$status' => $ret[0]);
1133 $data = api_rss_extra($a, $data, $user_info);
1135 return api_apply_template("status", $type, $data);
1138 api_register_func('api/statuses/show','api_statuses_show', true);
1144 function api_conversation_show(&$a, $type){
1145 if (api_user()===false) return false;
1147 $user_info = api_get_user($a);
1150 $id = intval($a->argv[3]);
1151 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1152 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1153 if ($page<0) $page=0;
1154 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1155 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1157 $start = $page*$count;
1160 $id = intval($_REQUEST["id"]);
1164 $id = intval($a->argv[4]);
1166 logger('API: api_conversation_show: '.$id);
1171 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1173 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1174 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1175 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1176 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1177 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1178 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1179 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1180 AND `item`.`uid` = %d AND `contact`.`id` = `item`.`contact-id`
1181 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1182 AND `item`.`id`>%d $sql_extra
1183 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1184 intval($id), intval(api_user()),
1186 intval($start), intval($count)
1190 die(api_error($a, $type, t("There is no conversation with this id.")));
1192 $ret = api_format_items($r,$user_info);
1194 $data = array('$statuses' => $ret);
1195 return api_apply_template("timeline", $type, $data);
1197 api_register_func('api/conversation/show','api_conversation_show', true);
1203 function api_statuses_repeat(&$a, $type){
1206 if (api_user()===false) return false;
1208 $user_info = api_get_user($a);
1211 $id = intval($a->argv[3]);
1214 $id = intval($_REQUEST["id"]);
1218 $id = intval($a->argv[4]);
1220 logger('API: api_statuses_repeat: '.$id);
1222 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1223 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1224 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1225 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1226 FROM `item`, `contact`
1227 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1228 AND `contact`.`id` = `item`.`contact-id`
1229 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1231 AND `item`.`id`=%d",
1235 if ($r[0]['body'] != "") {
1236 if (!intval(get_config('system','old_share'))) {
1237 if (strpos($r[0]['body'], "[/share]") !== false) {
1238 $pos = strpos($r[0]['body'], "[share");
1239 $post = substr($r[0]['body'], $pos);
1241 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1242 "' profile='".$r[0]['author-link'].
1243 "' avatar='".$r[0]['author-avatar'].
1244 "' link='".$r[0]['plink']."']";
1245 $post .= $r[0]['body'];
1246 $post .= "[/share]";
1248 $_REQUEST['body'] = $post;
1250 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1252 $_REQUEST['profile_uid'] = api_user();
1253 $_REQUEST['type'] = 'wall';
1254 $_REQUEST['api_source'] = true;
1256 require_once('mod/item.php');
1260 // this should output the last post (the one we just posted).
1262 return(api_status_show($a,$type));
1264 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1269 function api_statuses_destroy(&$a, $type){
1270 if (api_user()===false) return false;
1272 $user_info = api_get_user($a);
1275 $id = intval($a->argv[3]);
1278 $id = intval($_REQUEST["id"]);
1282 $id = intval($a->argv[4]);
1284 logger('API: api_statuses_destroy: '.$id);
1286 $ret = api_statuses_show($a, $type);
1288 require_once('include/items.php');
1289 drop_item($id, false);
1293 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1297 * http://developer.twitter.com/doc/get/statuses/mentions
1300 function api_statuses_mentions(&$a, $type){
1301 if (api_user()===false) return false;
1303 unset($_REQUEST["user_id"]);
1304 unset($_GET["user_id"]);
1306 unset($_REQUEST["screen_name"]);
1307 unset($_GET["screen_name"]);
1309 $user_info = api_get_user($a);
1310 // get last newtork messages
1314 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1315 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1316 if ($page<0) $page=0;
1317 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1318 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1319 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1321 $start = $page*$count;
1323 // Ugly code - should be changed
1324 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1325 $myurl = substr($myurl,strpos($myurl,'://')+3);
1326 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1327 $myurl = str_replace('www.','',$myurl);
1328 $diasp_url = str_replace('/profile/','/u/',$myurl);
1330 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1331 dbesc(protect_sprintf($myurl)),
1332 dbesc(protect_sprintf($myurl))
1336 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1338 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1339 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1340 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1341 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1342 FROM `item`, `contact`
1343 WHERE `item`.`uid` = %d
1344 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1345 AND `contact`.`id` = `item`.`contact-id`
1346 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1349 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1350 //intval($user_info['uid']),
1353 intval($start), intval($count)
1356 $ret = api_format_items($r,$user_info);
1359 $data = array('$statuses' => $ret);
1363 $data = api_rss_extra($a, $data, $user_info);
1366 $as = api_format_as($a, $ret, $user_info);
1367 $as["title"] = $a->config['sitename']." Mentions";
1368 $as['link']['url'] = $a->get_baseurl()."/";
1373 return api_apply_template("timeline", $type, $data);
1375 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1376 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1379 function api_statuses_user_timeline(&$a, $type){
1380 if (api_user()===false) return false;
1382 $user_info = api_get_user($a);
1383 // get last network messages
1385 logger("api_statuses_user_timeline: api_user: ". api_user() .
1386 "\nuser_info: ".print_r($user_info, true) .
1387 "\n_REQUEST: ".print_r($_REQUEST, true),
1391 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1392 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1393 if ($page<0) $page=0;
1394 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1395 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1396 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1397 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1399 $start = $page*$count;
1402 if ($user_info['self']==1)
1403 $sql_extra .= " AND `item`.`wall` = 1 ";
1405 if ($exclude_replies > 0)
1406 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1407 if ($conversation_id > 0)
1408 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1410 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1411 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1412 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1413 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1414 FROM `item`, `contact`
1415 WHERE `item`.`uid` = %d
1416 AND `item`.`contact-id` = %d
1417 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1418 AND `contact`.`id` = `item`.`contact-id`
1419 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1422 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1424 intval($user_info['cid']),
1426 intval($start), intval($count)
1429 $ret = api_format_items($r,$user_info, true);
1431 $data = array('$statuses' => $ret);
1435 $data = api_rss_extra($a, $data, $user_info);
1438 return api_apply_template("timeline", $type, $data);
1441 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1444 function api_favorites(&$a, $type){
1447 if (api_user()===false) return false;
1449 $called_api= array();
1451 $user_info = api_get_user($a);
1453 // in friendica starred item are private
1454 // return favorites only for self
1455 logger('api_favorites: self:' . $user_info['self']);
1457 if ($user_info['self']==0) {
1463 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1464 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1465 $count = (x($_GET,'count')?$_GET['count']:20);
1466 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1467 if ($page<0) $page=0;
1469 $start = $page*$count;
1472 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1474 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1475 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1476 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1477 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1478 FROM `item`, `contact`
1479 WHERE `item`.`uid` = %d
1480 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1481 AND `item`.`starred` = 1
1482 AND `contact`.`id` = `item`.`contact-id`
1483 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1486 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1487 //intval($user_info['uid']),
1490 intval($start), intval($count)
1493 $ret = api_format_items($r,$user_info);
1497 $data = array('$statuses' => $ret);
1501 $data = api_rss_extra($a, $data, $user_info);
1504 return api_apply_template("timeline", $type, $data);
1507 api_register_func('api/favorites','api_favorites', true);
1509 function api_format_as($a, $ret, $user_info) {
1512 $as['title'] = $a->config['sitename']." Public Timeline";
1514 foreach ($ret as $item) {
1515 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1516 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1517 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1518 $avatar[0]["rel"] = "avatar";
1519 $avatar[0]["type"] = "";
1520 $avatar[0]["width"] = 96;
1521 $avatar[0]["height"] = 96;
1522 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1523 $avatar[1]["rel"] = "avatar";
1524 $avatar[1]["type"] = "";
1525 $avatar[1]["width"] = 48;
1526 $avatar[1]["height"] = 48;
1527 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1528 $avatar[2]["rel"] = "avatar";
1529 $avatar[2]["type"] = "";
1530 $avatar[2]["width"] = 24;
1531 $avatar[2]["height"] = 24;
1532 $singleitem["actor"]["avatarLinks"] = $avatar;
1534 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1535 $singleitem["actor"]["image"]["rel"] = "avatar";
1536 $singleitem["actor"]["image"]["type"] = "";
1537 $singleitem["actor"]["image"]["width"] = 96;
1538 $singleitem["actor"]["image"]["height"] = 96;
1539 $singleitem["actor"]["type"] = "person";
1540 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1541 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1542 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1543 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1544 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1545 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1546 $singleitem["actor"]["contact"]["addresses"] = "";
1548 $singleitem["body"] = $item["text"];
1549 $singleitem["object"]["displayName"] = $item["text"];
1550 $singleitem["object"]["id"] = $item["url"];
1551 $singleitem["object"]["type"] = "note";
1552 $singleitem["object"]["url"] = $item["url"];
1553 //$singleitem["context"] =;
1554 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1555 $singleitem["provider"]["objectType"] = "service";
1556 $singleitem["provider"]["displayName"] = "Test";
1557 $singleitem["provider"]["url"] = "http://test.tld";
1558 $singleitem["title"] = $item["text"];
1559 $singleitem["verb"] = "post";
1560 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1561 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1562 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1563 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1564 //$singleitem["original"] = $item;
1565 $items[] = $singleitem;
1567 $as['items'] = $items;
1568 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1569 $as['link']['rel'] = "alternate";
1570 $as['link']['type'] = "text/html";
1574 function api_format_messages($item, $recipient, $sender) {
1575 // standard meta information
1577 'id' => $item['id'],
1578 'sender_id' => $sender['id'] ,
1580 'recipient_id' => $recipient['id'],
1581 'created_at' => api_date($item['created']),
1582 'sender_screen_name' => $sender['screen_name'],
1583 'recipient_screen_name' => $recipient['screen_name'],
1584 'sender' => $sender,
1585 'recipient' => $recipient,
1588 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1589 unset($ret["sender"]["uid"]);
1590 unset($ret["sender"]["self"]);
1591 unset($ret["recipient"]["uid"]);
1592 unset($ret["recipient"]["self"]);
1594 //don't send title to regular StatusNET requests to avoid confusing these apps
1595 if (x($_GET, 'getText')) {
1596 $ret['title'] = $item['title'] ;
1597 if ($_GET["getText"] == "html") {
1598 $ret['text'] = bbcode($item['body'], false, false);
1600 elseif ($_GET["getText"] == "plain") {
1601 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1602 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1606 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1608 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1609 unset($ret['sender']);
1610 unset($ret['recipient']);
1616 function api_get_entitities($text, $bbcode) {
1619 * Links at the first character of the post
1620 * different sizes of pictures
1621 * caching picture data (using the id for that?) (See privacy_image_cache)
1624 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1626 if ($include_entities != "true")
1629 $bbcode = bb_CleanPictureLinks($bbcode);
1631 // Change pure links in text to bbcode uris
1632 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1634 $entities = array();
1635 $entities["hashtags"] = array();
1636 $entities["symbols"] = array();
1637 $entities["urls"] = array();
1638 $entities["user_mentions"] = array();
1640 $URLSearchString = "^\[\]";
1642 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1644 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1645 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1646 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1648 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1649 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1650 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1652 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1653 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1654 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1656 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1658 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1659 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1661 $ordered_urls = array();
1662 foreach ($urls[1] AS $id=>$url) {
1663 //$start = strpos($text, $url, $offset);
1664 $start = iconv_strpos($text, $url, 0, "UTF-8");
1665 if (!($start === false))
1666 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1669 ksort($ordered_urls);
1672 //foreach ($urls[1] AS $id=>$url) {
1673 foreach ($ordered_urls AS $url) {
1674 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1675 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1676 $display_url = $url["title"];
1678 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1679 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1681 if (strlen($display_url) > 26)
1682 $display_url = substr($display_url, 0, 25)."…";
1685 //$start = strpos($text, $url, $offset);
1686 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1687 if (!($start === false)) {
1688 $entities["urls"][] = array("url" => $url["url"],
1689 "expanded_url" => $url["url"],
1690 "display_url" => $display_url,
1691 "indices" => array($start, $start+strlen($url["url"])));
1692 $offset = $start + 1;
1696 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1697 $ordered_images = array();
1698 foreach ($images[1] AS $image) {
1699 //$start = strpos($text, $url, $offset);
1700 $start = iconv_strpos($text, $image, 0, "UTF-8");
1701 if (!($start === false))
1702 $ordered_images[$start] = $image;
1704 //$entities["media"] = array();
1707 foreach ($ordered_images AS $url) {
1708 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1709 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1711 if (strlen($display_url) > 26)
1712 $display_url = substr($display_url, 0, 25)."…";
1714 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1715 if (!($start === false)) {
1717 $img_str = fetch_url($url,true, $redirects, 10);
1718 $image = @imagecreatefromstring($img_str);
1720 $entities["media"][] = array(
1722 "id_str" => (string)$start+1,
1723 "indices" => array($start, $start+strlen($url)),
1724 "media_url" => $url,
1725 "media_url_https" => $url,
1727 "display_url" => $display_url,
1728 "expanded_url" => $url,
1730 "sizes" => array("medium" => array(
1731 "w" => imagesx($image),
1732 "h" => imagesy($image),
1733 "resize" => "fit")));
1735 $offset = $start + 1;
1742 function api_format_items($r,$user_info, $filter_user = false) {
1747 foreach($r as $item) {
1748 api_share_as_retweet($a, api_user(), $item);
1750 localize_item($item);
1751 $status_user = api_item_get_user($a,$item);
1753 // Look if the posts are matching if they should be filtered by user id
1754 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1757 if ($item['thr-parent'] != $item['uri']) {
1758 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1760 dbesc($item['thr-parent']));
1762 $in_reply_to_status_id = intval($r[0]['id']);
1764 $in_reply_to_status_id = intval($item['parent']);
1766 $in_reply_to_status_id_str = (string) intval($item['parent']);
1768 $in_reply_to_screen_name = NULL;
1769 $in_reply_to_user_id = NULL;
1770 $in_reply_to_user_id_str = NULL;
1772 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1774 intval($in_reply_to_status_id));
1776 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1779 if ($r[0]['nick'] == "")
1780 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1782 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1783 $in_reply_to_user_id = intval($r[0]['id']);
1784 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1788 $in_reply_to_screen_name = NULL;
1789 $in_reply_to_user_id = NULL;
1790 $in_reply_to_status_id = NULL;
1791 $in_reply_to_user_id_str = NULL;
1792 $in_reply_to_status_id_str = NULL;
1795 // Workaround for ostatus messages where the title is identically to the body
1796 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1797 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1798 $statusbody = trim(html2plain($html, 0));
1800 $statustitle = trim($item['title']);
1802 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1803 $statustext = trim($statusbody);
1805 $statustext = trim($statustitle."\n\n".$statusbody);
1807 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1808 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1811 'text' => $statustext,
1812 'truncated' => False,
1813 'created_at'=> api_date($item['created']),
1814 'in_reply_to_status_id' => $in_reply_to_status_id,
1815 'in_reply_to_status_id_str' => $in_reply_to_status_id,
1816 'source' => (($item['app']) ? $item['app'] : 'web'),
1817 'id' => intval($item['id']),
1818 'id_str' => (string) intval($item['id']),
1819 'in_reply_to_user_id' => $in_reply_to_user_id,
1820 'in_reply_to_user_id_str' => $in_reply_to_user_id,
1821 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1823 'favorited' => $item['starred'] ? true : false,
1824 //'attachments' => array(),
1825 'user' => $status_user ,
1826 //'entities' => NULL,
1827 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1828 'statusnet_conversation_id' => $item['parent'],
1831 $entities = api_get_entitities($status['text'], $item['body']);
1832 if (count($entities) > 0)
1833 $status['entities'] = $entities;
1835 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1836 $status["source"] = network_to_name($item['item_network']);
1837 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1838 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1841 // Retweets are only valid for top postings
1842 // It doesn't work reliable with the link if its a feed
1843 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1845 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1847 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1848 $retweeted_status = $status;
1849 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1851 $status["retweeted_status"] = $retweeted_status;
1854 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1855 unset($status["user"]["uid"]);
1856 unset($status["user"]["self"]);
1858 // 'geo' => array('type' => 'Point',
1859 // 'coordinates' => array((float) $notice->lat,
1860 // (float) $notice->lon));
1862 // Seesmic doesn't like the following content
1863 // completely disabled to make friendica totally compatible to the statusnet API
1864 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1866 'updated' => api_date($item['edited']),
1867 'published' => api_date($item['created']),
1868 'message_id' => $item['uri'],
1869 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1870 'coordinates' => $item['coord'],
1871 'place' => $item['location'],
1872 'contributors' => '',
1873 'annotations' => '',
1875 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1876 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1877 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1878 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1881 $status = array_merge($status, $status2);
1890 function api_account_rate_limit_status(&$a,$type) {
1893 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1894 'remaining_hits' => (string) 150,
1895 'hourly_limit' => (string) 150,
1896 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1899 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1901 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1904 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1906 function api_help_test(&$a,$type) {
1913 return api_apply_template('test', $type, array("$ok" => $ok));
1916 api_register_func('api/help/test','api_help_test',false);
1918 function api_lists(&$a,$type) {
1923 api_register_func('api/lists','api_lists',true);
1925 function api_lists_list(&$a,$type) {
1930 api_register_func('api/lists/list','api_lists_list',true);
1933 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1934 * This function is deprecated by Twitter
1935 * returns: json, xml
1937 function api_statuses_f(&$a, $type, $qtype) {
1938 if (api_user()===false) return false;
1939 $user_info = api_get_user($a);
1941 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1942 /* this is to stop Hotot to load friends multiple times
1943 * I'm not sure if I'm missing return something or
1944 * is a bug in hotot. Workaround, meantime
1948 return array('$users' => $ret);*/
1952 if($qtype == 'friends')
1953 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1954 if($qtype == 'followers')
1955 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1957 // friends and followers only for self
1958 if ($user_info['self'] == 0)
1959 $sql_extra = " AND false ";
1961 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1966 foreach($r as $cid){
1967 $user = api_get_user($a, $cid['nurl']);
1968 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1969 unset($user["uid"]);
1970 unset($user["self"]);
1976 return array('$users' => $ret);
1979 function api_statuses_friends(&$a, $type){
1980 $data = api_statuses_f($a,$type,"friends");
1981 if ($data===false) return false;
1982 return api_apply_template("friends", $type, $data);
1984 function api_statuses_followers(&$a, $type){
1985 $data = api_statuses_f($a,$type,"followers");
1986 if ($data===false) return false;
1987 return api_apply_template("friends", $type, $data);
1989 api_register_func('api/statuses/friends','api_statuses_friends',true);
1990 api_register_func('api/statuses/followers','api_statuses_followers',true);
1997 function api_statusnet_config(&$a,$type) {
1998 $name = $a->config['sitename'];
1999 $server = $a->get_hostname();
2000 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2001 $email = $a->config['admin_email'];
2002 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2003 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2004 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2005 if($a->config['api_import_size'])
2006 $texlimit = string($a->config['api_import_size']);
2007 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2008 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2011 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2012 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2013 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2014 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2015 'shorturllength' => '30',
2016 'friendica' => array(
2017 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2018 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2019 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2020 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2025 return api_apply_template('config', $type, array('$config' => $config));
2028 api_register_func('api/statusnet/config','api_statusnet_config',false);
2030 function api_statusnet_version(&$a,$type) {
2034 if($type === 'xml') {
2035 header("Content-type: application/xml");
2036 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2039 elseif($type === 'json') {
2040 header("Content-type: application/json");
2045 api_register_func('api/statusnet/version','api_statusnet_version',false);
2048 function api_ff_ids(&$a,$type,$qtype) {
2052 $user_info = api_get_user($a);
2054 if($qtype == 'friends')
2055 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2056 if($qtype == 'followers')
2057 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2059 if (!$user_info["self"])
2060 $sql_extra = " AND false ";
2062 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2064 $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",
2070 if($type === 'xml') {
2071 header("Content-type: application/xml");
2072 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2074 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2075 echo '</ids>' . "\r\n";
2078 elseif($type === 'json') {
2080 header("Content-type: application/json");
2085 $ret[] = intval($rr['id']);
2087 echo json_encode($ret);
2093 function api_friends_ids(&$a,$type) {
2094 api_ff_ids($a,$type,'friends');
2096 function api_followers_ids(&$a,$type) {
2097 api_ff_ids($a,$type,'followers');
2099 api_register_func('api/friends/ids','api_friends_ids',true);
2100 api_register_func('api/followers/ids','api_followers_ids',true);
2103 function api_direct_messages_new(&$a, $type) {
2104 if (api_user()===false) return false;
2106 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2108 $sender = api_get_user($a);
2110 require_once("include/message.php");
2112 if ($_POST['screen_name']) {
2113 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2115 dbesc($_POST['screen_name']));
2117 // Selecting the id by priority, friendica first
2118 api_best_nickname($r);
2120 $recipient = api_get_user($a, $r[0]['nurl']);
2122 $recipient = api_get_user($a, $_POST['user_id']);
2126 if (x($_REQUEST,'replyto')) {
2127 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2129 intval($_REQUEST['replyto']));
2130 $replyto = $r[0]['parent-uri'];
2131 $sub = $r[0]['title'];
2134 if (x($_REQUEST,'title')) {
2135 $sub = $_REQUEST['title'];
2138 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2142 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2145 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2146 $ret = api_format_messages($r[0], $recipient, $sender);
2149 $ret = array("error"=>$id);
2152 $data = Array('$messages'=>$ret);
2157 $data = api_rss_extra($a, $data, $user_info);
2160 return api_apply_template("direct_messages", $type, $data);
2163 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2165 function api_direct_messages_box(&$a, $type, $box) {
2166 if (api_user()===false) return false;
2168 unset($_REQUEST["user_id"]);
2169 unset($_GET["user_id"]);
2171 unset($_REQUEST["screen_name"]);
2172 unset($_GET["screen_name"]);
2174 $user_info = api_get_user($a);
2177 $count = (x($_GET,'count')?$_GET['count']:20);
2178 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2179 if ($page<0) $page=0;
2181 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2182 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2184 $start = $page*$count;
2186 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2187 $profile_url = $user_info["url"];
2189 if ($box=="sentbox") {
2190 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2192 elseif ($box=="conversation") {
2193 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2195 elseif ($box=="all") {
2196 $sql_extra = "true";
2198 elseif ($box=="inbox") {
2199 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2203 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2205 $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`.`id` DESC LIMIT %d,%d",
2208 intval($start), intval($count)
2212 foreach($r as $item) {
2213 if ($box == "inbox" || $item['from-url'] != $profile_url){
2214 $recipient = $user_info;
2215 $sender = api_get_user($a,normalise_link($item['contact-url']));
2217 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2218 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2219 $sender = $user_info;
2223 $ret[]=api_format_messages($item, $recipient, $sender);
2227 $data = array('$messages' => $ret);
2231 $data = api_rss_extra($a, $data, $user_info);
2234 return api_apply_template("direct_messages", $type, $data);
2238 function api_direct_messages_sentbox(&$a, $type){
2239 return api_direct_messages_box($a, $type, "sentbox");
2241 function api_direct_messages_inbox(&$a, $type){
2242 return api_direct_messages_box($a, $type, "inbox");
2244 function api_direct_messages_all(&$a, $type){
2245 return api_direct_messages_box($a, $type, "all");
2247 function api_direct_messages_conversation(&$a, $type){
2248 return api_direct_messages_box($a, $type, "conversation");
2250 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2251 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2252 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2253 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2257 function api_oauth_request_token(&$a, $type){
2259 $oauth = new FKOAuth1();
2260 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2261 }catch(Exception $e){
2262 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2267 function api_oauth_access_token(&$a, $type){
2269 $oauth = new FKOAuth1();
2270 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2271 }catch(Exception $e){
2272 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2278 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2279 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2281 function api_share_as_retweet($a, $uid, &$item) {
2282 $body = trim($item["body"]);
2284 // Skip if it isn't a pure repeated messages
2285 // Does it start with a share?
2286 if (strpos($body, "[share") > 0)
2289 // Does it end with a share?
2290 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2293 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2294 // Skip if there is no shared message in there
2295 if ($body == $attributes)
2299 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2300 if ($matches[1] != "")
2301 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2303 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2304 if ($matches[1] != "")
2305 $author = $matches[1];
2308 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2309 if ($matches[1] != "")
2310 $profile = $matches[1];
2312 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2313 if ($matches[1] != "")
2314 $profile = $matches[1];
2317 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2318 if ($matches[1] != "")
2319 $avatar = $matches[1];
2321 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2322 if ($matches[1] != "")
2323 $avatar = $matches[1];
2325 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2327 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2330 $item["body"] = $shared_body;
2331 $item["author-name"] = $author;
2332 $item["author-link"] = $profile;
2333 $item["author-avatar"] = $avatar;
2339 function api_get_nick($profile) {
2341 - remove trailing jung from profile url
2342 - pump.io check has to check the website
2347 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2348 if ($friendica != $profile)
2352 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2353 if ($diaspora != $profile)
2358 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2359 if ($twitter != $profile)
2365 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2366 if ($StatusnetHost != $profile) {
2367 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2368 if ($StatusnetUser != $profile) {
2369 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2370 $user = json_decode($UserData);
2372 $nick = $user->screen_name;
2377 // To-Do: look at the page if its really a pumpio site
2378 //if (!$nick == "") {
2379 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2380 // if ($pumpio != $profile)
2382 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2387 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2388 dbesc($nick), dbesc(normalise_link($profile)));
2395 function api_clean_plain_items($Text) {
2396 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2398 $Text = bb_CleanPictureLinks($Text);
2400 if ($include_entities == "true") {
2401 $URLSearchString = "^\[\]";
2403 $Text = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$Text);
2404 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2407 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2411 function api_cleanup_share($shared) {
2412 if ($shared[2] != "type-link")
2415 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2421 if (isset($bookmark[2][0]))
2422 $title = $bookmark[2][0];
2424 if (isset($bookmark[1][0]))
2425 $link = $bookmark[1][0];
2427 if (strpos($shared[1],$title) !== false)
2430 if (strpos($shared[1],$link) !== false)
2433 $text = trim($shared[1]);
2435 //if (strlen($text) < strlen($title))
2436 if (($text == "") AND ($title != ""))
2437 $text .= "\n\n".trim($title);
2440 $text .= "\n".trim($link);
2442 return(trim($text));
2445 function api_best_nickname(&$contacts) {
2446 $best_contact = array();
2448 if (count($contact) == 0)
2451 foreach ($contacts AS $contact)
2452 if ($contact["network"] == "") {
2453 $contact["network"] = "dfrn";
2454 $best_contact = array($contact);
2457 if (sizeof($best_contact) == 0)
2458 foreach ($contacts AS $contact)
2459 if ($contact["network"] == "dfrn")
2460 $best_contact = array($contact);
2462 if (sizeof($best_contact) == 0)
2463 foreach ($contacts AS $contact)
2464 if ($contact["network"] == "dspr")
2465 $best_contact = array($contact);
2467 if (sizeof($best_contact) == 0)
2468 foreach ($contacts AS $contact)
2469 if ($contact["network"] == "stat")
2470 $best_contact = array($contact);
2472 if (sizeof($best_contact) == 0)
2473 foreach ($contacts AS $contact)
2474 if ($contact["network"] == "pump")
2475 $best_contact = array($contact);
2477 if (sizeof($best_contact) == 0)
2478 foreach ($contacts AS $contact)
2479 if ($contact["network"] == "twit")
2480 $best_contact = array($contact);
2482 if (sizeof($best_contact) == 1)
2483 $contacts = $best_contact;
2485 $contacts = array($contacts[0]);
2489 Not implemented by now:
2493 statuses/retweets_of_me
2498 account/update_location
2499 account/update_profile_background_image
2500 account/update_profile_image
2504 Not implemented in status.net:
2505 statuses/retweeted_to_me
2506 statuses/retweeted_by_me
2507 direct_messages/destroy
2509 account/update_delivery_device
2510 notifications/follow