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 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
388 // count public wall messages
389 $r = q("SELECT count(*) as `count` FROM `item`
392 intval($uinfo[0]['uid'])
394 $countitms = $r[0]['count'];
397 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
398 $r = q("SELECT count(*) as `count` FROM `item`
399 WHERE `contact-id` = %d",
400 intval($uinfo[0]['id'])
402 $countitms = $r[0]['count'];
406 $r = q("SELECT count(*) 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(*) 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(*) 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"]);
441 // Fetching unique id
442 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
444 // If not there, then add it
445 if (count($r) == 0) {
446 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
447 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
449 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
452 require_once('include/contact_selectors.php');
453 $network_name = network_to_name($uinfo[0]['network']);
456 'id' => intval($r[0]['id']),
457 'id_str' => (string) intval($r[0]['id']),
458 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
459 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
460 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
461 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
462 'profile_image_url' => $uinfo[0]['micro'],
463 'profile_image_url_https' => $uinfo[0]['micro'],
464 'url' => $uinfo[0]['url'],
465 'protected' => false,
466 'followers_count' => intval($countfollowers),
467 'friends_count' => intval($countfriends),
468 'created_at' => api_date($uinfo[0]['created']),
469 'favourites_count' => intval($starred),
471 'time_zone' => 'UTC',
472 'statuses_count' => intval($countitms),
473 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
475 'statusnet_blocking' => false,
476 'notifications' => false,
477 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
478 'uid' => intval($uinfo[0]['uid']),
479 'cid' => intval($uinfo[0]['cid']),
480 'self' => $uinfo[0]['self'],
481 'network' => $uinfo[0]['network'],
488 function api_item_get_user(&$a, $item) {
490 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
491 dbesc(normalise_link($item['author-link'])));
493 if (count($author) == 0) {
494 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
495 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
497 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
498 dbesc(normalise_link($item['author-link'])));
499 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
500 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
501 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
504 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
505 dbesc(normalise_link($item['owner-link'])));
507 if (count($owner) == 0) {
508 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
509 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
511 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
512 dbesc(normalise_link($item['owner-link'])));
513 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
514 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
515 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
518 // Comments in threads may appear as wall-to-wall postings.
519 // So only take the owner at the top posting.
520 if ($item["id"] == $item["parent"])
521 $status_user = api_get_user($a,$item["owner-link"]);
523 $status_user = api_get_user($a,$item["author-link"]);
525 $status_user["protected"] = (($item["allow_cid"] != "") OR
526 ($item["allow_gid"] != "") OR
527 ($item["deny_cid"] != "") OR
528 ($item["deny_gid"] != "") OR
531 return ($status_user);
536 * load api $templatename for $type and replace $data array
538 function api_apply_template($templatename, $type, $data){
546 $data = array_xmlify($data);
547 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
549 header ("Content-Type: text/xml");
550 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
553 $ret = replace_macros($tpl, $data);
568 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
569 * returns a 401 status code and an error message if not.
570 * http://developer.twitter.com/doc/get/account/verify_credentials
572 function api_account_verify_credentials(&$a, $type){
573 if (api_user()===false) return false;
575 unset($_REQUEST["user_id"]);
576 unset($_GET["user_id"]);
578 unset($_REQUEST["screen_name"]);
579 unset($_GET["screen_name"]);
581 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
583 $user_info = api_get_user($a);
585 // "verified" isn't used here in the standard
586 unset($user_info["verified"]);
588 // - Adding last status
590 $user_info["status"] = api_status_show($a,"raw");
591 if (!count($user_info["status"]))
592 unset($user_info["status"]);
594 unset($user_info["status"]["user"]);
597 // "uid" and "self" are only needed for some internal stuff, so remove it from here
598 unset($user_info["uid"]);
599 unset($user_info["self"]);
601 return api_apply_template("user", $type, array('$user' => $user_info));
604 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
608 * get data from $_POST or $_GET
610 function requestdata($k){
611 if (isset($_POST[$k])){
614 if (isset($_GET[$k])){
620 /*Waitman Gobble Mod*/
621 function api_statuses_mediap(&$a, $type) {
622 if (api_user()===false) {
623 logger('api_statuses_update: no user');
626 $user_info = api_get_user($a);
628 $_REQUEST['type'] = 'wall';
629 $_REQUEST['profile_uid'] = api_user();
630 $_REQUEST['api_source'] = true;
631 $txt = requestdata('status');
632 //$txt = urldecode(requestdata('status'));
634 require_once('library/HTMLPurifier.auto.php');
635 require_once('include/html2bbcode.php');
637 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
638 $txt = html2bb_video($txt);
639 $config = HTMLPurifier_Config::createDefault();
640 $config->set('Cache.DefinitionImpl', null);
641 $purifier = new HTMLPurifier($config);
642 $txt = $purifier->purify($txt);
644 $txt = html2bbcode($txt);
646 $a->argv[1]=$user_info['screen_name']; //should be set to username?
648 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
649 require_once('mod/wall_upload.php');
650 $bebop = wall_upload_post($a);
652 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
653 $_REQUEST['body']=$txt."\n\n".$bebop;
654 require_once('mod/item.php');
657 // this should output the last post (the one we just posted).
658 return api_status_show($a,$type);
660 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
661 /*Waitman Gobble Mod*/
664 function api_statuses_update(&$a, $type) {
665 if (api_user()===false) {
666 logger('api_statuses_update: no user');
669 $user_info = api_get_user($a);
671 // convert $_POST array items to the form we use for web posts.
673 // logger('api_post: ' . print_r($_POST,true));
675 if(requestdata('htmlstatus')) {
676 require_once('library/HTMLPurifier.auto.php');
677 require_once('include/html2bbcode.php');
679 $txt = requestdata('htmlstatus');
680 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
682 $txt = html2bb_video($txt);
684 $config = HTMLPurifier_Config::createDefault();
685 $config->set('Cache.DefinitionImpl', null);
688 $purifier = new HTMLPurifier($config);
689 $txt = $purifier->purify($txt);
691 $_REQUEST['body'] = html2bbcode($txt);
696 $_REQUEST['body'] = requestdata('status');
698 $_REQUEST['title'] = requestdata('title');
700 $parent = requestdata('in_reply_to_status_id');
701 if(ctype_digit($parent))
702 $_REQUEST['parent'] = $parent;
704 $_REQUEST['parent_uri'] = $parent;
706 if(requestdata('lat') && requestdata('long'))
707 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
708 $_REQUEST['profile_uid'] = api_user();
711 $_REQUEST['type'] = 'net-comment';
713 $_REQUEST['type'] = 'wall';
714 if(x($_FILES,'media')) {
715 // upload the image if we have one
716 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
717 require_once('mod/wall_upload.php');
718 $media = wall_upload_post($a);
720 $_REQUEST['body'] .= "\n\n".$media;
724 // set this so that the item_post() function is quiet and doesn't redirect or emit json
726 $_REQUEST['api_source'] = true;
728 // call out normal post function
730 require_once('mod/item.php');
733 // this should output the last post (the one we just posted).
734 return api_status_show($a,$type);
736 api_register_func('api/statuses/update','api_statuses_update', true);
737 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
740 function api_status_show(&$a, $type){
741 $user_info = api_get_user($a);
743 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
745 // get last public wall message
746 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
747 FROM `item`, `item` as `i`
748 WHERE `item`.`contact-id` = %d
749 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
750 AND `i`.`id` = `item`.`parent`
751 AND `item`.`type`!='activity'
752 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
753 ORDER BY `item`.`created` DESC
755 intval($user_info['cid']),
756 dbesc($user_info['url']),
757 dbesc(normalise_link($user_info['url'])),
758 dbesc($user_info['url']),
759 dbesc(normalise_link($user_info['url']))
762 if (count($lastwall)>0){
763 $lastwall = $lastwall[0];
765 $in_reply_to_status_id = NULL;
766 $in_reply_to_user_id = NULL;
767 $in_reply_to_status_id_str = NULL;
768 $in_reply_to_user_id_str = NULL;
769 $in_reply_to_screen_name = NULL;
770 if ($lastwall['parent']!=$lastwall['id']) {
771 $in_reply_to_status_id= intval($lastwall['parent']);
772 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
774 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
776 if ($r[0]['nick'] == "")
777 $r[0]['nick'] = api_get_nick($r[0]["url"]);
779 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
780 $in_reply_to_user_id = intval($r[0]['id']);
781 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
785 $status_info = array(
786 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
787 'truncated' => false,
788 'created_at' => api_date($lastwall['created']),
789 'in_reply_to_status_id' => $in_reply_to_status_id,
790 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
791 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
792 'id' => intval($lastwall['id']),
793 'id_str' => (string) $lastwall['id'],
794 'in_reply_to_user_id' => $in_reply_to_user_id,
795 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
796 'in_reply_to_screen_name' => $in_reply_to_screen_name,
798 'favorited' => false,
800 'user' => $user_info,
801 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
802 'statusnet_conversation_id' => $lastwall['parent'],
805 if ($lastwall['title'] != "")
806 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
808 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
809 if (count($entities) > 0)
810 $status_info['entities'] = $entities;
812 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
813 $status_info["source"] = network_to_name($lastwall['item_network']);
814 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
815 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
817 // "uid" and "self" are only needed for some internal stuff, so remove it from here
818 unset($status_info["user"]["uid"]);
819 unset($status_info["user"]["self"]);
823 return($status_info);
825 return api_apply_template("status", $type, array('$status' => $status_info));
834 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
835 * The author's most recent status will be returned inline.
836 * http://developer.twitter.com/doc/get/users/show
838 function api_users_show(&$a, $type){
839 $user_info = api_get_user($a);
841 $lastwall = q("SELECT `item`.*
842 FROM `item`, `contact`
843 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
844 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
845 AND `contact`.`id`=`item`.`contact-id`
846 AND `type`!='activity'
847 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
848 ORDER BY `created` DESC
851 dbesc(ACTIVITY_POST),
852 intval($user_info['cid']),
853 dbesc($user_info['url']),
854 dbesc(normalise_link($user_info['url'])),
855 dbesc($user_info['url']),
856 dbesc(normalise_link($user_info['url']))
858 if (count($lastwall)>0){
859 $lastwall = $lastwall[0];
861 $in_reply_to_status_id = NULL;
862 $in_reply_to_user_id = NULL;
863 $in_reply_to_status_id_str = NULL;
864 $in_reply_to_user_id_str = NULL;
865 $in_reply_to_screen_name = NULL;
866 if ($lastwall['parent']!=$lastwall['id']) {
867 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
868 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
869 if (count($reply)>0) {
870 $in_reply_to_status_id = intval($lastwall['parent']);
871 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
873 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
875 if ($r[0]['nick'] == "")
876 $r[0]['nick'] = api_get_nick($r[0]["url"]);
878 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
879 $in_reply_to_user_id = intval($r[0]['id']);
880 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
884 $user_info['status'] = array(
885 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
886 'truncated' => false,
887 'created_at' => api_date($lastwall['created']),
888 'in_reply_to_status_id' => $in_reply_to_status_id,
889 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
890 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
891 'id' => intval($lastwall['contact-id']),
892 'id_str' => (string) $lastwall['contact-id'],
893 'in_reply_to_user_id' => $in_reply_to_user_id,
894 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
895 'in_reply_to_screen_name' => $in_reply_to_screen_name,
897 'favorited' => false,
898 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
899 'statusnet_conversation_id' => $lastwall['parent'],
902 if ($lastwall['title'] != "")
903 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
905 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
906 if (count($entities) > 0)
907 $user_info['entities'] = $entities;
909 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
910 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
911 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
912 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
916 // "uid" and "self" are only needed for some internal stuff, so remove it from here
917 unset($user_info["uid"]);
918 unset($user_info["self"]);
920 return api_apply_template("user", $type, array('$user' => $user_info));
923 api_register_func('api/users/show','api_users_show');
927 * http://developer.twitter.com/doc/get/statuses/home_timeline
929 * TODO: Optional parameters
930 * TODO: Add reply info
932 function api_statuses_home_timeline(&$a, $type){
933 if (api_user()===false) return false;
935 unset($_REQUEST["user_id"]);
936 unset($_GET["user_id"]);
938 unset($_REQUEST["screen_name"]);
939 unset($_GET["screen_name"]);
941 $user_info = api_get_user($a);
942 // get last newtork messages
946 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
947 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
948 if ($page<0) $page=0;
949 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
950 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
951 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
952 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
953 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
955 $start = $page*$count;
959 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
960 if ($exclude_replies > 0)
961 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
962 if ($conversation_id > 0)
963 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
965 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
966 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
967 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
968 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
969 FROM `item`, `contact`
970 WHERE `item`.`uid` = %d AND `verb` = '%s'
971 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
972 AND `contact`.`id` = `item`.`contact-id`
973 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
976 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
978 dbesc(ACTIVITY_POST),
980 intval($start), intval($count)
983 $ret = api_format_items($r,$user_info);
985 // We aren't going to try to figure out at the item, group, and page
986 // level which items you've seen and which you haven't. If you're looking
987 // at the network timeline just mark everything seen.
989 $r = q("UPDATE `item` SET `unseen` = 0
990 WHERE `unseen` = 1 AND `uid` = %d",
991 //intval($user_info['uid'])
996 $data = array('$statuses' => $ret);
1000 $data = api_rss_extra($a, $data, $user_info);
1003 $as = api_format_as($a, $ret, $user_info);
1004 $as['title'] = $a->config['sitename']." Home Timeline";
1005 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1010 return api_apply_template("timeline", $type, $data);
1012 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1013 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1015 function api_statuses_public_timeline(&$a, $type){
1016 if (api_user()===false) return false;
1018 $user_info = api_get_user($a);
1019 // get last newtork messages
1023 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1024 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1025 if ($page<0) $page=0;
1026 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1027 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1028 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1029 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1030 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1032 $start = $page*$count;
1035 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1036 if ($exclude_replies > 0)
1037 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1038 if ($conversation_id > 0)
1039 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1041 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1042 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1043 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1044 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1045 `user`.`nickname`, `user`.`hidewall`
1046 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1047 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1048 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1049 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1050 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1051 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1052 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1055 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1056 dbesc(ACTIVITY_POST),
1061 $ret = api_format_items($r,$user_info);
1064 $data = array('$statuses' => $ret);
1068 $data = api_rss_extra($a, $data, $user_info);
1071 $as = api_format_as($a, $ret, $user_info);
1072 $as['title'] = $a->config['sitename']." Public Timeline";
1073 $as['link']['url'] = $a->get_baseurl()."/";
1078 return api_apply_template("timeline", $type, $data);
1080 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1085 function api_statuses_show(&$a, $type){
1086 if (api_user()===false) return false;
1088 $user_info = api_get_user($a);
1091 $id = intval($a->argv[3]);
1094 $id = intval($_REQUEST["id"]);
1098 $id = intval($a->argv[4]);
1100 logger('API: api_statuses_show: '.$id);
1102 $conversation = (x($_REQUEST,'conversation')?1:0);
1106 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1108 $sql_extra .= " AND `item`.`id` = %d";
1110 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1111 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1112 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1113 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1114 FROM `item`, `contact`
1115 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1116 AND `contact`.`id` = `item`.`contact-id`
1117 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1123 die(api_error($a, $type, t("There is no status with this id.")));
1125 $ret = api_format_items($r,$user_info);
1127 if ($conversation) {
1128 $data = array('$statuses' => $ret);
1129 return api_apply_template("timeline", $type, $data);
1131 $data = array('$status' => $ret[0]);
1135 $data = api_rss_extra($a, $data, $user_info);
1137 return api_apply_template("status", $type, $data);
1140 api_register_func('api/statuses/show','api_statuses_show', true);
1146 function api_conversation_show(&$a, $type){
1147 if (api_user()===false) return false;
1149 $user_info = api_get_user($a);
1152 $id = intval($a->argv[3]);
1153 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1154 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1155 if ($page<0) $page=0;
1156 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1157 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1159 $start = $page*$count;
1162 $id = intval($_REQUEST["id"]);
1166 $id = intval($a->argv[4]);
1168 logger('API: api_conversation_show: '.$id);
1173 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1175 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1176 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1177 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1178 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1179 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1180 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1181 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1182 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1183 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1184 AND `item`.`id`>%d $sql_extra
1185 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1186 intval($id), intval(api_user()),
1187 dbesc(ACTIVITY_POST),
1189 intval($start), intval($count)
1193 die(api_error($a, $type, t("There is no conversation with this id.")));
1195 $ret = api_format_items($r,$user_info);
1197 $data = array('$statuses' => $ret);
1198 return api_apply_template("timeline", $type, $data);
1200 api_register_func('api/conversation/show','api_conversation_show', true);
1206 function api_statuses_repeat(&$a, $type){
1209 if (api_user()===false) return false;
1211 $user_info = api_get_user($a);
1214 $id = intval($a->argv[3]);
1217 $id = intval($_REQUEST["id"]);
1221 $id = intval($a->argv[4]);
1223 logger('API: api_statuses_repeat: '.$id);
1225 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1226 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1227 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1228 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1229 FROM `item`, `contact`
1230 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1231 AND `contact`.`id` = `item`.`contact-id`
1232 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1234 AND `item`.`id`=%d",
1238 if ($r[0]['body'] != "") {
1239 if (!intval(get_config('system','old_share'))) {
1240 if (strpos($r[0]['body'], "[/share]") !== false) {
1241 $pos = strpos($r[0]['body'], "[share");
1242 $post = substr($r[0]['body'], $pos);
1244 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1245 "' profile='".$r[0]['author-link'].
1246 "' avatar='".$r[0]['author-avatar'].
1247 "' link='".$r[0]['plink']."']";
1248 $post .= $r[0]['body'];
1249 $post .= "[/share]";
1251 $_REQUEST['body'] = $post;
1253 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1255 $_REQUEST['profile_uid'] = api_user();
1256 $_REQUEST['type'] = 'wall';
1257 $_REQUEST['api_source'] = true;
1259 require_once('mod/item.php');
1263 // this should output the last post (the one we just posted).
1265 return(api_status_show($a,$type));
1267 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1272 function api_statuses_destroy(&$a, $type){
1273 if (api_user()===false) return false;
1275 $user_info = api_get_user($a);
1278 $id = intval($a->argv[3]);
1281 $id = intval($_REQUEST["id"]);
1285 $id = intval($a->argv[4]);
1287 logger('API: api_statuses_destroy: '.$id);
1289 $ret = api_statuses_show($a, $type);
1291 require_once('include/items.php');
1292 drop_item($id, false);
1296 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1300 * http://developer.twitter.com/doc/get/statuses/mentions
1303 function api_statuses_mentions(&$a, $type){
1304 if (api_user()===false) return false;
1306 unset($_REQUEST["user_id"]);
1307 unset($_GET["user_id"]);
1309 unset($_REQUEST["screen_name"]);
1310 unset($_GET["screen_name"]);
1312 $user_info = api_get_user($a);
1313 // get last newtork messages
1317 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1318 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1319 if ($page<0) $page=0;
1320 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1321 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1322 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1324 $start = $page*$count;
1326 // Ugly code - should be changed
1327 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1328 $myurl = substr($myurl,strpos($myurl,'://')+3);
1329 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1330 $myurl = str_replace('www.','',$myurl);
1331 $diasp_url = str_replace('/profile/','/u/',$myurl);
1334 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1336 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1337 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1338 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1339 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1340 FROM `item`, `contact`
1341 WHERE `item`.`uid` = %d AND `verb` = '%s'
1342 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1343 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1344 AND `contact`.`id` = `item`.`contact-id`
1345 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1346 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention`)
1349 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1351 dbesc(ACTIVITY_POST),
1352 dbesc(protect_sprintf($myurl)),
1353 dbesc(protect_sprintf($myurl)),
1356 intval($start), intval($count)
1359 $ret = api_format_items($r,$user_info);
1362 $data = array('$statuses' => $ret);
1366 $data = api_rss_extra($a, $data, $user_info);
1369 $as = api_format_as($a, $ret, $user_info);
1370 $as["title"] = $a->config['sitename']." Mentions";
1371 $as['link']['url'] = $a->get_baseurl()."/";
1376 return api_apply_template("timeline", $type, $data);
1378 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1379 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1382 function api_statuses_user_timeline(&$a, $type){
1383 if (api_user()===false) return false;
1385 $user_info = api_get_user($a);
1386 // get last network messages
1388 logger("api_statuses_user_timeline: api_user: ". api_user() .
1389 "\nuser_info: ".print_r($user_info, true) .
1390 "\n_REQUEST: ".print_r($_REQUEST, true),
1394 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1395 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1396 if ($page<0) $page=0;
1397 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1398 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1399 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1400 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1402 $start = $page*$count;
1405 if ($user_info['self']==1)
1406 $sql_extra .= " AND `item`.`wall` = 1 ";
1408 if ($exclude_replies > 0)
1409 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1410 if ($conversation_id > 0)
1411 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1413 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1414 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1415 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1416 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1417 FROM `item`, `contact`
1418 WHERE `item`.`uid` = %d AND `verb` = '%s'
1419 AND `item`.`contact-id` = %d
1420 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1421 AND `contact`.`id` = `item`.`contact-id`
1422 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1425 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1427 dbesc(ACTIVITY_POST),
1428 intval($user_info['cid']),
1430 intval($start), intval($count)
1433 $ret = api_format_items($r,$user_info, true);
1435 $data = array('$statuses' => $ret);
1439 $data = api_rss_extra($a, $data, $user_info);
1442 return api_apply_template("timeline", $type, $data);
1445 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1448 function api_favorites(&$a, $type){
1451 if (api_user()===false) return false;
1453 $called_api= array();
1455 $user_info = api_get_user($a);
1457 // in friendica starred item are private
1458 // return favorites only for self
1459 logger('api_favorites: self:' . $user_info['self']);
1461 if ($user_info['self']==0) {
1467 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1468 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1469 $count = (x($_GET,'count')?$_GET['count']:20);
1470 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1471 if ($page<0) $page=0;
1473 $start = $page*$count;
1476 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1478 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1479 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1480 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1481 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1482 FROM `item`, `contact`
1483 WHERE `item`.`uid` = %d AND `verb` = '%s'
1484 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1485 AND `item`.`starred` = 1
1486 AND `contact`.`id` = `item`.`contact-id`
1487 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1490 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1492 dbesc(ACTIVITY_POST),
1494 intval($start), intval($count)
1497 $ret = api_format_items($r,$user_info);
1501 $data = array('$statuses' => $ret);
1505 $data = api_rss_extra($a, $data, $user_info);
1508 return api_apply_template("timeline", $type, $data);
1511 api_register_func('api/favorites','api_favorites', true);
1513 function api_format_as($a, $ret, $user_info) {
1516 $as['title'] = $a->config['sitename']." Public Timeline";
1518 foreach ($ret as $item) {
1519 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1520 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1521 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1522 $avatar[0]["rel"] = "avatar";
1523 $avatar[0]["type"] = "";
1524 $avatar[0]["width"] = 96;
1525 $avatar[0]["height"] = 96;
1526 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1527 $avatar[1]["rel"] = "avatar";
1528 $avatar[1]["type"] = "";
1529 $avatar[1]["width"] = 48;
1530 $avatar[1]["height"] = 48;
1531 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1532 $avatar[2]["rel"] = "avatar";
1533 $avatar[2]["type"] = "";
1534 $avatar[2]["width"] = 24;
1535 $avatar[2]["height"] = 24;
1536 $singleitem["actor"]["avatarLinks"] = $avatar;
1538 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1539 $singleitem["actor"]["image"]["rel"] = "avatar";
1540 $singleitem["actor"]["image"]["type"] = "";
1541 $singleitem["actor"]["image"]["width"] = 96;
1542 $singleitem["actor"]["image"]["height"] = 96;
1543 $singleitem["actor"]["type"] = "person";
1544 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1545 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1546 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1547 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1548 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1549 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1550 $singleitem["actor"]["contact"]["addresses"] = "";
1552 $singleitem["body"] = $item["text"];
1553 $singleitem["object"]["displayName"] = $item["text"];
1554 $singleitem["object"]["id"] = $item["url"];
1555 $singleitem["object"]["type"] = "note";
1556 $singleitem["object"]["url"] = $item["url"];
1557 //$singleitem["context"] =;
1558 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1559 $singleitem["provider"]["objectType"] = "service";
1560 $singleitem["provider"]["displayName"] = "Test";
1561 $singleitem["provider"]["url"] = "http://test.tld";
1562 $singleitem["title"] = $item["text"];
1563 $singleitem["verb"] = "post";
1564 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1565 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1566 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1567 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1568 //$singleitem["original"] = $item;
1569 $items[] = $singleitem;
1571 $as['items'] = $items;
1572 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1573 $as['link']['rel'] = "alternate";
1574 $as['link']['type'] = "text/html";
1578 function api_format_messages($item, $recipient, $sender) {
1579 // standard meta information
1581 'id' => $item['id'],
1582 'sender_id' => $sender['id'] ,
1584 'recipient_id' => $recipient['id'],
1585 'created_at' => api_date($item['created']),
1586 'sender_screen_name' => $sender['screen_name'],
1587 'recipient_screen_name' => $recipient['screen_name'],
1588 'sender' => $sender,
1589 'recipient' => $recipient,
1592 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1593 unset($ret["sender"]["uid"]);
1594 unset($ret["sender"]["self"]);
1595 unset($ret["recipient"]["uid"]);
1596 unset($ret["recipient"]["self"]);
1598 //don't send title to regular StatusNET requests to avoid confusing these apps
1599 if (x($_GET, 'getText')) {
1600 $ret['title'] = $item['title'] ;
1601 if ($_GET["getText"] == "html") {
1602 $ret['text'] = bbcode($item['body'], false, false);
1604 elseif ($_GET["getText"] == "plain") {
1605 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1606 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1610 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1612 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1613 unset($ret['sender']);
1614 unset($ret['recipient']);
1620 function api_get_entitities($text, $bbcode) {
1623 * Links at the first character of the post
1624 * different sizes of pictures
1625 * caching picture data (using the id for that?) (See privacy_image_cache)
1628 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1630 if ($include_entities != "true")
1633 $bbcode = bb_CleanPictureLinks($bbcode);
1635 // Change pure links in text to bbcode uris
1636 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1638 $entities = array();
1639 $entities["hashtags"] = array();
1640 $entities["symbols"] = array();
1641 $entities["urls"] = array();
1642 $entities["user_mentions"] = array();
1644 $URLSearchString = "^\[\]";
1646 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1648 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1649 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1650 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1652 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1653 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1654 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1656 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1657 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1658 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1660 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1662 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1663 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1665 $ordered_urls = array();
1666 foreach ($urls[1] AS $id=>$url) {
1667 //$start = strpos($text, $url, $offset);
1668 $start = iconv_strpos($text, $url, 0, "UTF-8");
1669 if (!($start === false))
1670 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1673 ksort($ordered_urls);
1676 //foreach ($urls[1] AS $id=>$url) {
1677 foreach ($ordered_urls AS $url) {
1678 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1679 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1680 $display_url = $url["title"];
1682 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1683 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1685 if (strlen($display_url) > 26)
1686 $display_url = substr($display_url, 0, 25)."…";
1689 //$start = strpos($text, $url, $offset);
1690 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1691 if (!($start === false)) {
1692 $entities["urls"][] = array("url" => $url["url"],
1693 "expanded_url" => $url["url"],
1694 "display_url" => $display_url,
1695 "indices" => array($start, $start+strlen($url["url"])));
1696 $offset = $start + 1;
1700 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1701 $ordered_images = array();
1702 foreach ($images[1] AS $image) {
1703 //$start = strpos($text, $url, $offset);
1704 $start = iconv_strpos($text, $image, 0, "UTF-8");
1705 if (!($start === false))
1706 $ordered_images[$start] = $image;
1708 //$entities["media"] = array();
1711 foreach ($ordered_images AS $url) {
1712 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1713 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1715 if (strlen($display_url) > 26)
1716 $display_url = substr($display_url, 0, 25)."…";
1718 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1719 if (!($start === false)) {
1721 $img_str = fetch_url($url,true, $redirects, 10);
1722 $image = @imagecreatefromstring($img_str);
1724 $entities["media"][] = array(
1726 "id_str" => (string)$start+1,
1727 "indices" => array($start, $start+strlen($url)),
1728 "media_url" => $url,
1729 "media_url_https" => $url,
1731 "display_url" => $display_url,
1732 "expanded_url" => $url,
1734 "sizes" => array("medium" => array(
1735 "w" => imagesx($image),
1736 "h" => imagesy($image),
1737 "resize" => "fit")));
1739 $offset = $start + 1;
1746 function api_format_items($r,$user_info, $filter_user = false) {
1751 foreach($r as $item) {
1752 api_share_as_retweet($a, api_user(), $item);
1754 localize_item($item);
1755 $status_user = api_item_get_user($a,$item);
1757 // Look if the posts are matching if they should be filtered by user id
1758 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1761 if ($item['thr-parent'] != $item['uri']) {
1762 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1764 dbesc($item['thr-parent']));
1766 $in_reply_to_status_id = intval($r[0]['id']);
1768 $in_reply_to_status_id = intval($item['parent']);
1770 $in_reply_to_status_id_str = (string) intval($item['parent']);
1772 $in_reply_to_screen_name = NULL;
1773 $in_reply_to_user_id = NULL;
1774 $in_reply_to_user_id_str = NULL;
1776 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1778 intval($in_reply_to_status_id));
1780 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1783 if ($r[0]['nick'] == "")
1784 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1786 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1787 $in_reply_to_user_id = intval($r[0]['id']);
1788 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1792 $in_reply_to_screen_name = NULL;
1793 $in_reply_to_user_id = NULL;
1794 $in_reply_to_status_id = NULL;
1795 $in_reply_to_user_id_str = NULL;
1796 $in_reply_to_status_id_str = NULL;
1799 // Workaround for ostatus messages where the title is identically to the body
1800 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1801 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1802 $statusbody = trim(html2plain($html, 0));
1804 $statustitle = trim($item['title']);
1806 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1807 $statustext = trim($statusbody);
1809 $statustext = trim($statustitle."\n\n".$statusbody);
1811 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1812 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1815 'text' => $statustext,
1816 'truncated' => False,
1817 'created_at'=> api_date($item['created']),
1818 'in_reply_to_status_id' => $in_reply_to_status_id,
1819 'in_reply_to_status_id_str' => $in_reply_to_status_id,
1820 'source' => (($item['app']) ? $item['app'] : 'web'),
1821 'id' => intval($item['id']),
1822 'id_str' => (string) intval($item['id']),
1823 'in_reply_to_user_id' => $in_reply_to_user_id,
1824 'in_reply_to_user_id_str' => $in_reply_to_user_id,
1825 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1827 'favorited' => $item['starred'] ? true : false,
1828 //'attachments' => array(),
1829 'user' => $status_user ,
1830 //'entities' => NULL,
1831 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1832 'statusnet_conversation_id' => $item['parent'],
1835 if ($item['title'] != "")
1836 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
1838 $entities = api_get_entitities($status['text'], $item['body']);
1839 if (count($entities) > 0)
1840 $status['entities'] = $entities;
1842 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1843 $status["source"] = network_to_name($item['item_network']);
1844 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1845 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1848 // Retweets are only valid for top postings
1849 // It doesn't work reliable with the link if its a feed
1850 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1852 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1854 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1855 $retweeted_status = $status;
1856 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1858 $status["retweeted_status"] = $retweeted_status;
1861 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1862 unset($status["user"]["uid"]);
1863 unset($status["user"]["self"]);
1865 // 'geo' => array('type' => 'Point',
1866 // 'coordinates' => array((float) $notice->lat,
1867 // (float) $notice->lon));
1875 function api_account_rate_limit_status(&$a,$type) {
1878 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1879 'remaining_hits' => (string) 150,
1880 'hourly_limit' => (string) 150,
1881 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1884 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1886 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1889 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1891 function api_help_test(&$a,$type) {
1898 return api_apply_template('test', $type, array("$ok" => $ok));
1901 api_register_func('api/help/test','api_help_test',false);
1903 function api_lists(&$a,$type) {
1908 api_register_func('api/lists','api_lists',true);
1910 function api_lists_list(&$a,$type) {
1915 api_register_func('api/lists/list','api_lists_list',true);
1918 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1919 * This function is deprecated by Twitter
1920 * returns: json, xml
1922 function api_statuses_f(&$a, $type, $qtype) {
1923 if (api_user()===false) return false;
1924 $user_info = api_get_user($a);
1926 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1927 /* this is to stop Hotot to load friends multiple times
1928 * I'm not sure if I'm missing return something or
1929 * is a bug in hotot. Workaround, meantime
1933 return array('$users' => $ret);*/
1937 if($qtype == 'friends')
1938 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1939 if($qtype == 'followers')
1940 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1942 // friends and followers only for self
1943 if ($user_info['self'] == 0)
1944 $sql_extra = " AND false ";
1946 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1951 foreach($r as $cid){
1952 $user = api_get_user($a, $cid['nurl']);
1953 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1954 unset($user["uid"]);
1955 unset($user["self"]);
1961 return array('$users' => $ret);
1964 function api_statuses_friends(&$a, $type){
1965 $data = api_statuses_f($a,$type,"friends");
1966 if ($data===false) return false;
1967 return api_apply_template("friends", $type, $data);
1969 function api_statuses_followers(&$a, $type){
1970 $data = api_statuses_f($a,$type,"followers");
1971 if ($data===false) return false;
1972 return api_apply_template("friends", $type, $data);
1974 api_register_func('api/statuses/friends','api_statuses_friends',true);
1975 api_register_func('api/statuses/followers','api_statuses_followers',true);
1982 function api_statusnet_config(&$a,$type) {
1983 $name = $a->config['sitename'];
1984 $server = $a->get_hostname();
1985 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1986 $email = $a->config['admin_email'];
1987 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1988 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1989 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1990 if($a->config['api_import_size'])
1991 $texlimit = string($a->config['api_import_size']);
1992 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1993 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1996 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1997 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1998 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1999 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2000 'shorturllength' => '30',
2001 'friendica' => array(
2002 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2003 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2004 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2005 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2010 return api_apply_template('config', $type, array('$config' => $config));
2013 api_register_func('api/statusnet/config','api_statusnet_config',false);
2015 function api_statusnet_version(&$a,$type) {
2019 if($type === 'xml') {
2020 header("Content-type: application/xml");
2021 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2024 elseif($type === 'json') {
2025 header("Content-type: application/json");
2030 api_register_func('api/statusnet/version','api_statusnet_version',false);
2033 function api_ff_ids(&$a,$type,$qtype) {
2037 $user_info = api_get_user($a);
2039 if($qtype == 'friends')
2040 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2041 if($qtype == 'followers')
2042 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2044 if (!$user_info["self"])
2045 $sql_extra = " AND false ";
2047 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2049 $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",
2055 if($type === 'xml') {
2056 header("Content-type: application/xml");
2057 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2059 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2060 echo '</ids>' . "\r\n";
2063 elseif($type === 'json') {
2065 header("Content-type: application/json");
2070 $ret[] = intval($rr['id']);
2072 echo json_encode($ret);
2078 function api_friends_ids(&$a,$type) {
2079 api_ff_ids($a,$type,'friends');
2081 function api_followers_ids(&$a,$type) {
2082 api_ff_ids($a,$type,'followers');
2084 api_register_func('api/friends/ids','api_friends_ids',true);
2085 api_register_func('api/followers/ids','api_followers_ids',true);
2088 function api_direct_messages_new(&$a, $type) {
2089 if (api_user()===false) return false;
2091 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2093 $sender = api_get_user($a);
2095 require_once("include/message.php");
2097 if ($_POST['screen_name']) {
2098 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2100 dbesc($_POST['screen_name']));
2102 // Selecting the id by priority, friendica first
2103 api_best_nickname($r);
2105 $recipient = api_get_user($a, $r[0]['nurl']);
2107 $recipient = api_get_user($a, $_POST['user_id']);
2111 if (x($_REQUEST,'replyto')) {
2112 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2114 intval($_REQUEST['replyto']));
2115 $replyto = $r[0]['parent-uri'];
2116 $sub = $r[0]['title'];
2119 if (x($_REQUEST,'title')) {
2120 $sub = $_REQUEST['title'];
2123 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2127 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2130 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2131 $ret = api_format_messages($r[0], $recipient, $sender);
2134 $ret = array("error"=>$id);
2137 $data = Array('$messages'=>$ret);
2142 $data = api_rss_extra($a, $data, $user_info);
2145 return api_apply_template("direct_messages", $type, $data);
2148 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2150 function api_direct_messages_box(&$a, $type, $box) {
2151 if (api_user()===false) return false;
2153 unset($_REQUEST["user_id"]);
2154 unset($_GET["user_id"]);
2156 unset($_REQUEST["screen_name"]);
2157 unset($_GET["screen_name"]);
2159 $user_info = api_get_user($a);
2162 $count = (x($_GET,'count')?$_GET['count']:20);
2163 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2164 if ($page<0) $page=0;
2166 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2167 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2169 $start = $page*$count;
2171 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2172 $profile_url = $user_info["url"];
2174 if ($box=="sentbox") {
2175 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2177 elseif ($box=="conversation") {
2178 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2180 elseif ($box=="all") {
2181 $sql_extra = "true";
2183 elseif ($box=="inbox") {
2184 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2188 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2190 $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",
2193 intval($start), intval($count)
2197 foreach($r as $item) {
2198 if ($box == "inbox" || $item['from-url'] != $profile_url){
2199 $recipient = $user_info;
2200 $sender = api_get_user($a,normalise_link($item['contact-url']));
2202 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2203 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2204 $sender = $user_info;
2208 $ret[]=api_format_messages($item, $recipient, $sender);
2212 $data = array('$messages' => $ret);
2216 $data = api_rss_extra($a, $data, $user_info);
2219 return api_apply_template("direct_messages", $type, $data);
2223 function api_direct_messages_sentbox(&$a, $type){
2224 return api_direct_messages_box($a, $type, "sentbox");
2226 function api_direct_messages_inbox(&$a, $type){
2227 return api_direct_messages_box($a, $type, "inbox");
2229 function api_direct_messages_all(&$a, $type){
2230 return api_direct_messages_box($a, $type, "all");
2232 function api_direct_messages_conversation(&$a, $type){
2233 return api_direct_messages_box($a, $type, "conversation");
2235 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2236 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2237 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2238 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2242 function api_oauth_request_token(&$a, $type){
2244 $oauth = new FKOAuth1();
2245 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2246 }catch(Exception $e){
2247 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2252 function api_oauth_access_token(&$a, $type){
2254 $oauth = new FKOAuth1();
2255 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2256 }catch(Exception $e){
2257 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2263 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2264 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2266 function api_share_as_retweet($a, $uid, &$item) {
2267 $body = trim($item["body"]);
2269 // Skip if it isn't a pure repeated messages
2270 // Does it start with a share?
2271 if (strpos($body, "[share") > 0)
2274 // Does it end with a share?
2275 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2278 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2279 // Skip if there is no shared message in there
2280 if ($body == $attributes)
2284 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2285 if ($matches[1] != "")
2286 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2288 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2289 if ($matches[1] != "")
2290 $author = $matches[1];
2293 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2294 if ($matches[1] != "")
2295 $profile = $matches[1];
2297 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2298 if ($matches[1] != "")
2299 $profile = $matches[1];
2302 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2303 if ($matches[1] != "")
2304 $avatar = $matches[1];
2306 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2307 if ($matches[1] != "")
2308 $avatar = $matches[1];
2310 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2312 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2315 $item["body"] = $shared_body;
2316 $item["author-name"] = $author;
2317 $item["author-link"] = $profile;
2318 $item["author-avatar"] = $avatar;
2324 function api_get_nick($profile) {
2326 - remove trailing jung from profile url
2327 - pump.io check has to check the website
2332 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2333 if ($friendica != $profile)
2337 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2338 if ($diaspora != $profile)
2343 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2344 if ($twitter != $profile)
2350 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2351 if ($StatusnetHost != $profile) {
2352 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2353 if ($StatusnetUser != $profile) {
2354 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2355 $user = json_decode($UserData);
2357 $nick = $user->screen_name;
2362 // To-Do: look at the page if its really a pumpio site
2363 //if (!$nick == "") {
2364 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2365 // if ($pumpio != $profile)
2367 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2372 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2373 dbesc($nick), dbesc(normalise_link($profile)));
2380 function api_clean_plain_items($Text) {
2381 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2383 $Text = bb_CleanPictureLinks($Text);
2385 $URLSearchString = "^\[\]";
2387 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2389 if ($include_entities == "true") {
2390 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2393 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2397 function api_cleanup_share($shared) {
2398 if ($shared[2] != "type-link")
2401 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2407 if (isset($bookmark[2][0]))
2408 $title = $bookmark[2][0];
2410 if (isset($bookmark[1][0]))
2411 $link = $bookmark[1][0];
2413 if (strpos($shared[1],$title) !== false)
2416 if (strpos($shared[1],$link) !== false)
2419 $text = trim($shared[1]);
2421 //if (strlen($text) < strlen($title))
2422 if (($text == "") AND ($title != ""))
2423 $text .= "\n\n".trim($title);
2426 $text .= "\n".trim($link);
2428 return(trim($text));
2431 function api_best_nickname(&$contacts) {
2432 $best_contact = array();
2434 if (count($contact) == 0)
2437 foreach ($contacts AS $contact)
2438 if ($contact["network"] == "") {
2439 $contact["network"] = "dfrn";
2440 $best_contact = array($contact);
2443 if (sizeof($best_contact) == 0)
2444 foreach ($contacts AS $contact)
2445 if ($contact["network"] == "dfrn")
2446 $best_contact = array($contact);
2448 if (sizeof($best_contact) == 0)
2449 foreach ($contacts AS $contact)
2450 if ($contact["network"] == "dspr")
2451 $best_contact = array($contact);
2453 if (sizeof($best_contact) == 0)
2454 foreach ($contacts AS $contact)
2455 if ($contact["network"] == "stat")
2456 $best_contact = array($contact);
2458 if (sizeof($best_contact) == 0)
2459 foreach ($contacts AS $contact)
2460 if ($contact["network"] == "pump")
2461 $best_contact = array($contact);
2463 if (sizeof($best_contact) == 0)
2464 foreach ($contacts AS $contact)
2465 if ($contact["network"] == "twit")
2466 $best_contact = array($contact);
2468 if (sizeof($best_contact) == 1)
2469 $contacts = $best_contact;
2471 $contacts = array($contacts[0]);
2475 Not implemented by now:
2479 statuses/retweets_of_me
2484 account/update_location
2485 account/update_profile_background_image
2486 account/update_profile_image
2490 Not implemented in status.net:
2491 statuses/retweeted_to_me
2492 statuses/retweeted_by_me
2493 direct_messages/destroy
2495 account/update_delivery_device
2496 notifications/follow