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;
125 foreach ($API as $p=>$info){
126 if (strpos($a->query_string, $p)===0){
127 $called_api= explode("/",$p);
128 //unset($_SERVER['PHP_AUTH_USER']);
129 if ($info['auth']===true && api_user()===false) {
133 load_contact_links(api_user());
135 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
136 logger('API parameters: ' . print_r($_REQUEST,true));
138 if (strpos($a->query_string, ".xml")>0) $type="xml";
139 if (strpos($a->query_string, ".json")>0) $type="json";
140 if (strpos($a->query_string, ".rss")>0) $type="rss";
141 if (strpos($a->query_string, ".atom")>0) $type="atom";
142 if (strpos($a->query_string, ".as")>0) $type="as";
144 $r = call_user_func($info['func'], $a, $type);
145 if ($r===false) return;
149 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
150 header ("Content-Type: text/xml");
151 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
154 header ("Content-Type: application/json");
156 return json_encode($rr);
159 header ("Content-Type: application/rss+xml");
160 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
163 header ("Content-Type: application/atom+xml");
164 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
167 //header ("Content-Type: application/json");
169 // return json_encode($rr);
170 return json_encode($r);
174 //echo "<pre>"; var_dump($r); die();
177 header("HTTP/1.1 404 Not Found");
178 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
179 return(api_error($a, $type, "not implemented"));
183 function api_error(&$a, $type, $error) {
184 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
187 header ("Content-Type: text/xml");
188 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
191 header ("Content-Type: application/json");
192 return json_encode(array('error' => $error, 'request' => $a->query_string));
195 header ("Content-Type: application/rss+xml");
196 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
199 header ("Content-Type: application/atom+xml");
200 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
208 function api_rss_extra(&$a, $arr, $user_info){
209 if (is_null($user_info)) $user_info = api_get_user($a);
210 $arr['$user'] = $user_info;
211 $arr['$rss'] = array(
212 'alternate' => $user_info['url'],
213 'self' => $a->get_baseurl(). "/". $a->query_string,
214 'base' => $a->get_baseurl(),
215 'updated' => api_date(null),
216 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
217 'language' => $user_info['language'],
218 'logo' => $a->get_baseurl()."/images/friendica-32.png",
226 * Unique contact to contact url.
228 function api_unique_id_to_url($id){
229 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
232 return ($r[0]["url"]);
238 * Returns user info array.
240 function api_get_user(&$a, $contact_id = Null, $type = "json"){
247 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
249 // Searching for contact URL
250 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
251 $user = dbesc(normalise_link($contact_id));
253 $extra_query = "AND `contact`.`nurl` = '%s' ";
254 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
257 // Searching for unique contact id
258 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
259 $user = dbesc(api_unique_id_to_url($contact_id));
262 die(api_error($a, $type, t("User not found.")));
265 $extra_query = "AND `contact`.`nurl` = '%s' ";
266 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
269 if(is_null($user) && x($_GET, 'user_id')) {
270 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
273 die(api_error($a, $type, t("User not found.")));
276 $extra_query = "AND `contact`.`nurl` = '%s' ";
277 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
279 if(is_null($user) && x($_GET, 'screen_name')) {
280 $user = dbesc($_GET['screen_name']);
282 $extra_query = "AND `contact`.`nick` = '%s' ";
283 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
286 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
287 $argid = count($called_api);
288 list($user, $null) = explode(".",$a->argv[$argid]);
289 if(is_numeric($user)){
290 $user = dbesc(api_unique_id_to_url($user));
296 $extra_query = "AND `contact`.`nurl` = '%s' ";
297 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
299 $user = dbesc($user);
301 $extra_query = "AND `contact`.`nick` = '%s' ";
302 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
306 logger("api_get_user: user ".$user, LOGGER_DEBUG);
309 if (api_user()===false) {
310 api_login($a); return False;
312 $user = $_SESSION['uid'];
313 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
318 logger('api_user: ' . $extra_query . ', user: ' . $user);
320 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
326 // Selecting the id by priority, friendica first
327 api_best_nickname($uinfo);
329 // if the contact wasn't found, fetch it from the unique contacts
330 if (count($uinfo)==0) {
334 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
336 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
339 // If no nick where given, extract it from the address
340 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
341 $r[0]['nick'] = api_get_nick($r[0]["url"]);
345 'id_str' => (string) $r[0]["id"],
346 'name' => $r[0]["name"],
347 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
349 'description' => NULL,
350 'profile_image_url' => $r[0]["avatar"],
351 'profile_image_url_https' => $r[0]["avatar"],
352 'url' => $r[0]["url"],
353 'protected' => false,
354 'followers_count' => 0,
355 'friends_count' => 0,
356 'created_at' => api_date(0),
357 'favourites_count' => 0,
359 'time_zone' => 'UTC',
360 'statuses_count' => 0,
361 'following' => false,
363 'statusnet_blocking' => false,
364 'notifications' => false,
365 'statusnet_profile_url' => $r[0]["url"],
374 die(api_error($a, $type, t("User not found.")));
378 if($uinfo[0]['self']) {
379 $usr = q("select * from user where uid = %d limit 1",
382 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
386 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
387 // count public wall messages
388 $r = q("SELECT count(*) as `count` FROM `item`
391 intval($uinfo[0]['uid'])
393 $countitms = $r[0]['count'];
396 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
397 $r = q("SELECT count(*) as `count` FROM `item`
398 WHERE `contact-id` = %d",
399 intval($uinfo[0]['id'])
401 $countitms = $r[0]['count'];
405 $r = q("SELECT count(*) as `count` FROM `contact`
406 WHERE `uid` = %d AND `rel` IN ( %d, %d )
407 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
408 intval($uinfo[0]['uid']),
409 intval(CONTACT_IS_SHARING),
410 intval(CONTACT_IS_FRIEND)
412 $countfriends = $r[0]['count'];
414 $r = q("SELECT count(*) as `count` FROM `contact`
415 WHERE `uid` = %d AND `rel` IN ( %d, %d )
416 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
417 intval($uinfo[0]['uid']),
418 intval(CONTACT_IS_FOLLOWER),
419 intval(CONTACT_IS_FRIEND)
421 $countfollowers = $r[0]['count'];
423 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
424 intval($uinfo[0]['uid'])
426 $starred = $r[0]['count'];
429 if(! $uinfo[0]['self']) {
435 // Add a nick if it isn't present there
436 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
437 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
440 // Fetching unique id
441 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
443 // If not there, then add it
444 if (count($r) == 0) {
445 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
446 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
448 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
451 require_once('include/contact_selectors.php');
452 $network_name = network_to_name($uinfo[0]['network']);
455 'id' => intval($r[0]['id']),
456 'id_str' => (string) intval($r[0]['id']),
457 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
458 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
459 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
460 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
461 'profile_image_url' => $uinfo[0]['micro'],
462 'profile_image_url_https' => $uinfo[0]['micro'],
463 'url' => $uinfo[0]['url'],
464 'protected' => false,
465 'followers_count' => intval($countfollowers),
466 'friends_count' => intval($countfriends),
467 'created_at' => api_date($uinfo[0]['created']),
468 'favourites_count' => intval($starred),
470 'time_zone' => 'UTC',
471 'statuses_count' => intval($countitms),
472 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
474 'statusnet_blocking' => false,
475 'notifications' => false,
476 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
477 'uid' => intval($uinfo[0]['uid']),
478 'cid' => intval($uinfo[0]['cid']),
479 'self' => $uinfo[0]['self'],
480 'network' => $uinfo[0]['network'],
487 function api_item_get_user(&$a, $item) {
489 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
490 dbesc(normalise_link($item['author-link'])));
492 if (count($author) == 0) {
493 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
494 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
496 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
497 dbesc(normalise_link($item['author-link'])));
498 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
499 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
500 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
503 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
504 dbesc(normalise_link($item['owner-link'])));
506 if (count($owner) == 0) {
507 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
508 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
510 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
511 dbesc(normalise_link($item['owner-link'])));
512 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
513 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
514 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
517 // Comments in threads may appear as wall-to-wall postings.
518 // So only take the owner at the top posting.
519 if ($item["id"] == $item["parent"])
520 $status_user = api_get_user($a,$item["owner-link"]);
522 $status_user = api_get_user($a,$item["author-link"]);
524 $status_user["protected"] = (($item["allow_cid"] != "") OR
525 ($item["allow_gid"] != "") OR
526 ($item["deny_cid"] != "") OR
527 ($item["deny_gid"] != "") OR
530 return ($status_user);
535 * load api $templatename for $type and replace $data array
537 function api_apply_template($templatename, $type, $data){
545 $data = array_xmlify($data);
546 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
548 header ("Content-Type: text/xml");
549 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
552 $ret = replace_macros($tpl, $data);
567 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
568 * returns a 401 status code and an error message if not.
569 * http://developer.twitter.com/doc/get/account/verify_credentials
571 function api_account_verify_credentials(&$a, $type){
572 if (api_user()===false) return false;
574 unset($_REQUEST["user_id"]);
575 unset($_GET["user_id"]);
577 unset($_REQUEST["screen_name"]);
578 unset($_GET["screen_name"]);
580 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
582 $user_info = api_get_user($a);
584 // "verified" isn't used here in the standard
585 unset($user_info["verified"]);
587 // - Adding last status
589 $user_info["status"] = api_status_show($a,"raw");
590 if (!count($user_info["status"]))
591 unset($user_info["status"]);
593 unset($user_info["status"]["user"]);
596 // "uid" and "self" are only needed for some internal stuff, so remove it from here
597 unset($user_info["uid"]);
598 unset($user_info["self"]);
600 return api_apply_template("user", $type, array('$user' => $user_info));
603 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
607 * get data from $_POST or $_GET
609 function requestdata($k){
610 if (isset($_POST[$k])){
613 if (isset($_GET[$k])){
619 /*Waitman Gobble Mod*/
620 function api_statuses_mediap(&$a, $type) {
621 if (api_user()===false) {
622 logger('api_statuses_update: no user');
625 $user_info = api_get_user($a);
627 $_REQUEST['type'] = 'wall';
628 $_REQUEST['profile_uid'] = api_user();
629 $_REQUEST['api_source'] = true;
630 $txt = requestdata('status');
631 //$txt = urldecode(requestdata('status'));
633 require_once('library/HTMLPurifier.auto.php');
634 require_once('include/html2bbcode.php');
636 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
637 $txt = html2bb_video($txt);
638 $config = HTMLPurifier_Config::createDefault();
639 $config->set('Cache.DefinitionImpl', null);
640 $purifier = new HTMLPurifier($config);
641 $txt = $purifier->purify($txt);
643 $txt = html2bbcode($txt);
645 $a->argv[1]=$user_info['screen_name']; //should be set to username?
647 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
648 require_once('mod/wall_upload.php');
649 $bebop = wall_upload_post($a);
651 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
652 $_REQUEST['body']=$txt."\n\n".$bebop;
653 require_once('mod/item.php');
656 // this should output the last post (the one we just posted).
657 return api_status_show($a,$type);
659 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
660 /*Waitman Gobble Mod*/
663 function api_statuses_update(&$a, $type) {
664 if (api_user()===false) {
665 logger('api_statuses_update: no user');
668 $user_info = api_get_user($a);
670 // convert $_POST array items to the form we use for web posts.
672 // logger('api_post: ' . print_r($_POST,true));
674 if(requestdata('htmlstatus')) {
675 require_once('library/HTMLPurifier.auto.php');
676 require_once('include/html2bbcode.php');
678 $txt = requestdata('htmlstatus');
679 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
681 $txt = html2bb_video($txt);
683 $config = HTMLPurifier_Config::createDefault();
684 $config->set('Cache.DefinitionImpl', null);
687 $purifier = new HTMLPurifier($config);
688 $txt = $purifier->purify($txt);
690 $_REQUEST['body'] = html2bbcode($txt);
695 $_REQUEST['body'] = requestdata('status');
697 $_REQUEST['title'] = requestdata('title');
699 $parent = requestdata('in_reply_to_status_id');
700 if(ctype_digit($parent))
701 $_REQUEST['parent'] = $parent;
703 $_REQUEST['parent_uri'] = $parent;
705 if(requestdata('lat') && requestdata('long'))
706 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
707 $_REQUEST['profile_uid'] = api_user();
710 $_REQUEST['type'] = 'net-comment';
712 // logger("api_statuses_update: upload ".print_r($_FILES, true)." ".print_r($_POST, true)." ".print_r($_GET, true), LOGGER_DEBUG);
714 $_REQUEST['type'] = 'wall';
715 if(x($_FILES,'media')) {
716 // upload the image if we have one
717 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
718 require_once('mod/wall_upload.php');
719 $media = wall_upload_post($a);
721 $_REQUEST['body'] .= "\n\n".$media;
725 // set this so that the item_post() function is quiet and doesn't redirect or emit json
727 $_REQUEST['api_source'] = true;
729 if (!isset($_REQUEST["source"]) OR ($_REQUEST["source"] == ""))
730 $_REQUEST["source"] = "api";
732 // call out normal post function
734 require_once('mod/item.php');
737 // this should output the last post (the one we just posted).
738 return api_status_show($a,$type);
740 api_register_func('api/statuses/update','api_statuses_update', true);
741 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
744 function api_status_show(&$a, $type){
745 $user_info = api_get_user($a);
747 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
749 // get last public wall message
750 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
751 FROM `item`, `item` as `i`
752 WHERE `item`.`contact-id` = %d
753 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
754 AND `i`.`id` = `item`.`parent`
755 AND `item`.`type`!='activity'
756 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
757 ORDER BY `item`.`created` DESC
759 intval($user_info['cid']),
760 dbesc($user_info['url']),
761 dbesc(normalise_link($user_info['url'])),
762 dbesc($user_info['url']),
763 dbesc(normalise_link($user_info['url']))
766 if (count($lastwall)>0){
767 $lastwall = $lastwall[0];
769 $in_reply_to_status_id = NULL;
770 $in_reply_to_user_id = NULL;
771 $in_reply_to_status_id_str = NULL;
772 $in_reply_to_user_id_str = NULL;
773 $in_reply_to_screen_name = NULL;
774 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
775 $in_reply_to_status_id= intval($lastwall['parent']);
776 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
778 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
780 if ($r[0]['nick'] == "")
781 $r[0]['nick'] = api_get_nick($r[0]["url"]);
783 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
784 $in_reply_to_user_id = intval($r[0]['id']);
785 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
789 // There seems to be situation, where both fields are identical:
790 // https://github.com/friendica/friendica/issues/1010
791 // This is a bugfix for that.
792 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
793 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
794 $in_reply_to_status_id = NULL;
795 $in_reply_to_user_id = NULL;
796 $in_reply_to_status_id_str = NULL;
797 $in_reply_to_user_id_str = NULL;
798 $in_reply_to_screen_name = NULL;
801 $status_info = array(
802 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
803 'truncated' => false,
804 'created_at' => api_date($lastwall['created']),
805 'in_reply_to_status_id' => $in_reply_to_status_id,
806 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
807 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
808 'id' => intval($lastwall['id']),
809 'id_str' => (string) $lastwall['id'],
810 'in_reply_to_user_id' => $in_reply_to_user_id,
811 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
812 'in_reply_to_screen_name' => $in_reply_to_screen_name,
814 'favorited' => false,
816 'user' => $user_info,
817 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
818 'statusnet_conversation_id' => $lastwall['parent'],
821 if ($lastwall['title'] != "")
822 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
824 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
825 if (count($entities) > 0)
826 $status_info['entities'] = $entities;
828 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
829 $status_info["source"] = network_to_name($lastwall['item_network']);
830 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
831 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
833 // "uid" and "self" are only needed for some internal stuff, so remove it from here
834 unset($status_info["user"]["uid"]);
835 unset($status_info["user"]["self"]);
839 return($status_info);
841 return api_apply_template("status", $type, array('$status' => $status_info));
850 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
851 * The author's most recent status will be returned inline.
852 * http://developer.twitter.com/doc/get/users/show
854 function api_users_show(&$a, $type){
855 $user_info = api_get_user($a);
857 $lastwall = q("SELECT `item`.*
858 FROM `item`, `contact`
859 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
860 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
861 AND `contact`.`id`=`item`.`contact-id`
862 AND `type`!='activity'
863 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
864 ORDER BY `created` DESC
867 dbesc(ACTIVITY_POST),
868 intval($user_info['cid']),
869 dbesc($user_info['url']),
870 dbesc(normalise_link($user_info['url'])),
871 dbesc($user_info['url']),
872 dbesc(normalise_link($user_info['url']))
874 if (count($lastwall)>0){
875 $lastwall = $lastwall[0];
877 $in_reply_to_status_id = NULL;
878 $in_reply_to_user_id = NULL;
879 $in_reply_to_status_id_str = NULL;
880 $in_reply_to_user_id_str = NULL;
881 $in_reply_to_screen_name = NULL;
882 if ($lastwall['parent']!=$lastwall['id']) {
883 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
884 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
885 if (count($reply)>0) {
886 $in_reply_to_status_id = intval($lastwall['parent']);
887 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
889 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
891 if ($r[0]['nick'] == "")
892 $r[0]['nick'] = api_get_nick($r[0]["url"]);
894 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
895 $in_reply_to_user_id = intval($r[0]['id']);
896 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
900 $user_info['status'] = array(
901 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
902 'truncated' => false,
903 'created_at' => api_date($lastwall['created']),
904 'in_reply_to_status_id' => $in_reply_to_status_id,
905 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
906 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
907 'id' => intval($lastwall['contact-id']),
908 'id_str' => (string) $lastwall['contact-id'],
909 'in_reply_to_user_id' => $in_reply_to_user_id,
910 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
911 'in_reply_to_screen_name' => $in_reply_to_screen_name,
913 'favorited' => false,
914 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
915 'statusnet_conversation_id' => $lastwall['parent'],
918 if ($lastwall['title'] != "")
919 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
921 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
922 if (count($entities) > 0)
923 $user_info['entities'] = $entities;
925 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
926 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
927 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
928 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
932 // "uid" and "self" are only needed for some internal stuff, so remove it from here
933 unset($user_info["uid"]);
934 unset($user_info["self"]);
936 return api_apply_template("user", $type, array('$user' => $user_info));
939 api_register_func('api/users/show','api_users_show');
942 function api_users_search(&$a, $type) {
943 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
947 if (isset($_GET["q"])) {
948 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
950 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
953 foreach ($r AS $user) {
954 $user_info = api_get_user($a, $user["id"]);
955 //echo print_r($user_info, true)."\n";
956 $userdata = api_apply_template("user", $type, array('user' => $user_info));
957 $userlist[] = $userdata["user"];
959 $userlist = array("users" => $userlist);
961 die(api_error($a, $type, t("User not found.")));
963 die(api_error($a, $type, t("User not found.")));
968 api_register_func('api/users/search','api_users_search');
972 * http://developer.twitter.com/doc/get/statuses/home_timeline
974 * TODO: Optional parameters
975 * TODO: Add reply info
977 function api_statuses_home_timeline(&$a, $type){
978 if (api_user()===false) return false;
980 unset($_REQUEST["user_id"]);
981 unset($_GET["user_id"]);
983 unset($_REQUEST["screen_name"]);
984 unset($_GET["screen_name"]);
986 $user_info = api_get_user($a);
987 // get last newtork messages
991 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
992 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
993 if ($page<0) $page=0;
994 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
995 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
996 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
997 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
998 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1000 $start = $page*$count;
1004 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1005 if ($exclude_replies > 0)
1006 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1007 if ($conversation_id > 0)
1008 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1010 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1011 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1012 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1013 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1014 FROM `item`, `contact`
1015 WHERE `item`.`uid` = %d AND `verb` = '%s'
1016 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1017 AND `contact`.`id` = `item`.`contact-id`
1018 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1021 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1023 dbesc(ACTIVITY_POST),
1025 intval($start), intval($count)
1028 $ret = api_format_items($r,$user_info);
1030 // We aren't going to try to figure out at the item, group, and page
1031 // level which items you've seen and which you haven't. If you're looking
1032 // at the network timeline just mark everything seen.
1034 $r = q("UPDATE `item` SET `unseen` = 0
1035 WHERE `unseen` = 1 AND `uid` = %d",
1036 //intval($user_info['uid'])
1041 $data = array('$statuses' => $ret);
1045 $data = api_rss_extra($a, $data, $user_info);
1048 $as = api_format_as($a, $ret, $user_info);
1049 $as['title'] = $a->config['sitename']." Home Timeline";
1050 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1055 return api_apply_template("timeline", $type, $data);
1057 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1058 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1060 function api_statuses_public_timeline(&$a, $type){
1061 if (api_user()===false) return false;
1063 $user_info = api_get_user($a);
1064 // get last newtork messages
1068 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1069 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1070 if ($page<0) $page=0;
1071 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1072 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1073 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1074 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1075 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1077 $start = $page*$count;
1080 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1081 if ($exclude_replies > 0)
1082 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1083 if ($conversation_id > 0)
1084 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1086 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1087 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1088 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1089 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1090 `user`.`nickname`, `user`.`hidewall`
1091 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1092 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1093 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1094 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1095 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1096 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1097 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1100 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1101 dbesc(ACTIVITY_POST),
1106 $ret = api_format_items($r,$user_info);
1109 $data = array('$statuses' => $ret);
1113 $data = api_rss_extra($a, $data, $user_info);
1116 $as = api_format_as($a, $ret, $user_info);
1117 $as['title'] = $a->config['sitename']." Public Timeline";
1118 $as['link']['url'] = $a->get_baseurl()."/";
1123 return api_apply_template("timeline", $type, $data);
1125 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1130 function api_statuses_show(&$a, $type){
1131 if (api_user()===false) return false;
1133 $user_info = api_get_user($a);
1136 $id = intval($a->argv[3]);
1139 $id = intval($_REQUEST["id"]);
1143 $id = intval($a->argv[4]);
1145 logger('API: api_statuses_show: '.$id);
1147 $conversation = (x($_REQUEST,'conversation')?1:0);
1151 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1153 $sql_extra .= " AND `item`.`id` = %d";
1155 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1156 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1157 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1158 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1159 FROM `item`, `contact`
1160 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1161 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1162 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1165 dbesc(ACTIVITY_POST),
1170 die(api_error($a, $type, t("There is no status with this id.")));
1172 $ret = api_format_items($r,$user_info);
1174 if ($conversation) {
1175 $data = array('$statuses' => $ret);
1176 return api_apply_template("timeline", $type, $data);
1178 $data = array('$status' => $ret[0]);
1182 $data = api_rss_extra($a, $data, $user_info);
1184 return api_apply_template("status", $type, $data);
1187 api_register_func('api/statuses/show','api_statuses_show', true);
1193 function api_conversation_show(&$a, $type){
1194 if (api_user()===false) return false;
1196 $user_info = api_get_user($a);
1199 $id = intval($a->argv[3]);
1200 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1201 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1202 if ($page<0) $page=0;
1203 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1204 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1206 $start = $page*$count;
1209 $id = intval($_REQUEST["id"]);
1213 $id = intval($a->argv[4]);
1215 logger('API: api_conversation_show: '.$id);
1220 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1222 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1223 `contact`.`name`, `contact`.`photo`, `contact`.`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` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1227 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1228 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1229 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1230 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1231 AND `item`.`id`>%d $sql_extra
1232 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1233 intval($id), intval(api_user()),
1234 dbesc(ACTIVITY_POST),
1236 intval($start), intval($count)
1240 die(api_error($a, $type, t("There is no conversation with this id.")));
1242 $ret = api_format_items($r,$user_info);
1244 $data = array('$statuses' => $ret);
1245 return api_apply_template("timeline", $type, $data);
1247 api_register_func('api/conversation/show','api_conversation_show', true);
1253 function api_statuses_repeat(&$a, $type){
1256 if (api_user()===false) return false;
1258 $user_info = api_get_user($a);
1261 $id = intval($a->argv[3]);
1264 $id = intval($_REQUEST["id"]);
1268 $id = intval($a->argv[4]);
1270 logger('API: api_statuses_repeat: '.$id);
1272 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1273 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1274 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1275 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1276 FROM `item`, `contact`
1277 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1278 AND `contact`.`id` = `item`.`contact-id`
1279 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1281 AND `item`.`id`=%d",
1285 if ($r[0]['body'] != "") {
1286 if (!intval(get_config('system','old_share'))) {
1287 if (strpos($r[0]['body'], "[/share]") !== false) {
1288 $pos = strpos($r[0]['body'], "[share");
1289 $post = substr($r[0]['body'], $pos);
1291 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1292 "' profile='".$r[0]['author-link'].
1293 "' avatar='".$r[0]['author-avatar'].
1294 "' link='".$r[0]['plink']."']";
1295 $post .= $r[0]['body'];
1296 $post .= "[/share]";
1298 $_REQUEST['body'] = $post;
1300 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1302 $_REQUEST['profile_uid'] = api_user();
1303 $_REQUEST['type'] = 'wall';
1304 $_REQUEST['api_source'] = true;
1306 if (!isset($_REQUEST["source"]) OR ($_REQUEST["source"] == ""))
1307 $_REQUEST["source"] = "api";
1309 require_once('mod/item.php');
1313 // this should output the last post (the one we just posted).
1315 return(api_status_show($a,$type));
1317 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1322 function api_statuses_destroy(&$a, $type){
1323 if (api_user()===false) return false;
1325 $user_info = api_get_user($a);
1328 $id = intval($a->argv[3]);
1331 $id = intval($_REQUEST["id"]);
1335 $id = intval($a->argv[4]);
1337 logger('API: api_statuses_destroy: '.$id);
1339 $ret = api_statuses_show($a, $type);
1341 require_once('include/items.php');
1342 drop_item($id, false);
1346 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1350 * http://developer.twitter.com/doc/get/statuses/mentions
1353 function api_statuses_mentions(&$a, $type){
1354 if (api_user()===false) return false;
1356 unset($_REQUEST["user_id"]);
1357 unset($_GET["user_id"]);
1359 unset($_REQUEST["screen_name"]);
1360 unset($_GET["screen_name"]);
1362 $user_info = api_get_user($a);
1363 // get last newtork messages
1367 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1368 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1369 if ($page<0) $page=0;
1370 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1371 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1372 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1374 $start = $page*$count;
1376 // Ugly code - should be changed
1377 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1378 $myurl = substr($myurl,strpos($myurl,'://')+3);
1379 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1380 $myurl = str_replace('www.','',$myurl);
1381 $diasp_url = str_replace('/profile/','/u/',$myurl);
1384 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1386 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1387 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1388 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1389 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1390 FROM `item`, `contact`
1391 WHERE `item`.`uid` = %d AND `verb` = '%s'
1392 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1393 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1394 AND `contact`.`id` = `item`.`contact-id`
1395 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1396 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention`)
1399 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1401 dbesc(ACTIVITY_POST),
1402 dbesc(protect_sprintf($myurl)),
1403 dbesc(protect_sprintf($myurl)),
1406 intval($start), intval($count)
1409 $ret = api_format_items($r,$user_info);
1412 $data = array('$statuses' => $ret);
1416 $data = api_rss_extra($a, $data, $user_info);
1419 $as = api_format_as($a, $ret, $user_info);
1420 $as["title"] = $a->config['sitename']." Mentions";
1421 $as['link']['url'] = $a->get_baseurl()."/";
1426 return api_apply_template("timeline", $type, $data);
1428 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1429 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1432 function api_statuses_user_timeline(&$a, $type){
1433 if (api_user()===false) return false;
1435 $user_info = api_get_user($a);
1436 // get last network messages
1438 logger("api_statuses_user_timeline: api_user: ". api_user() .
1439 "\nuser_info: ".print_r($user_info, true) .
1440 "\n_REQUEST: ".print_r($_REQUEST, true),
1444 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1445 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1446 if ($page<0) $page=0;
1447 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1448 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1449 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1450 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1452 $start = $page*$count;
1455 if ($user_info['self']==1)
1456 $sql_extra .= " AND `item`.`wall` = 1 ";
1458 if ($exclude_replies > 0)
1459 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1460 if ($conversation_id > 0)
1461 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1463 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1464 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1465 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1466 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1467 FROM `item`, `contact`
1468 WHERE `item`.`uid` = %d AND `verb` = '%s'
1469 AND `item`.`contact-id` = %d
1470 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1471 AND `contact`.`id` = `item`.`contact-id`
1472 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1475 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1477 dbesc(ACTIVITY_POST),
1478 intval($user_info['cid']),
1480 intval($start), intval($count)
1483 $ret = api_format_items($r,$user_info, true);
1485 $data = array('$statuses' => $ret);
1489 $data = api_rss_extra($a, $data, $user_info);
1492 return api_apply_template("timeline", $type, $data);
1495 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1498 function api_favorites(&$a, $type){
1501 if (api_user()===false) return false;
1503 $called_api= array();
1505 $user_info = api_get_user($a);
1507 // in friendica starred item are private
1508 // return favorites only for self
1509 logger('api_favorites: self:' . $user_info['self']);
1511 if ($user_info['self']==0) {
1517 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1518 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1519 $count = (x($_GET,'count')?$_GET['count']:20);
1520 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1521 if ($page<0) $page=0;
1523 $start = $page*$count;
1526 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1528 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1529 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1530 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1531 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1532 FROM `item`, `contact`
1533 WHERE `item`.`uid` = %d AND `verb` = '%s'
1534 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1535 AND `item`.`starred` = 1
1536 AND `contact`.`id` = `item`.`contact-id`
1537 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1540 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1542 dbesc(ACTIVITY_POST),
1544 intval($start), intval($count)
1547 $ret = api_format_items($r,$user_info);
1551 $data = array('$statuses' => $ret);
1555 $data = api_rss_extra($a, $data, $user_info);
1558 return api_apply_template("timeline", $type, $data);
1561 api_register_func('api/favorites','api_favorites', true);
1563 function api_format_as($a, $ret, $user_info) {
1566 $as['title'] = $a->config['sitename']." Public Timeline";
1568 foreach ($ret as $item) {
1569 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1570 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1571 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1572 $avatar[0]["rel"] = "avatar";
1573 $avatar[0]["type"] = "";
1574 $avatar[0]["width"] = 96;
1575 $avatar[0]["height"] = 96;
1576 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1577 $avatar[1]["rel"] = "avatar";
1578 $avatar[1]["type"] = "";
1579 $avatar[1]["width"] = 48;
1580 $avatar[1]["height"] = 48;
1581 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1582 $avatar[2]["rel"] = "avatar";
1583 $avatar[2]["type"] = "";
1584 $avatar[2]["width"] = 24;
1585 $avatar[2]["height"] = 24;
1586 $singleitem["actor"]["avatarLinks"] = $avatar;
1588 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1589 $singleitem["actor"]["image"]["rel"] = "avatar";
1590 $singleitem["actor"]["image"]["type"] = "";
1591 $singleitem["actor"]["image"]["width"] = 96;
1592 $singleitem["actor"]["image"]["height"] = 96;
1593 $singleitem["actor"]["type"] = "person";
1594 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1595 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1596 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1597 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1598 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1599 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1600 $singleitem["actor"]["contact"]["addresses"] = "";
1602 $singleitem["body"] = $item["text"];
1603 $singleitem["object"]["displayName"] = $item["text"];
1604 $singleitem["object"]["id"] = $item["url"];
1605 $singleitem["object"]["type"] = "note";
1606 $singleitem["object"]["url"] = $item["url"];
1607 //$singleitem["context"] =;
1608 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1609 $singleitem["provider"]["objectType"] = "service";
1610 $singleitem["provider"]["displayName"] = "Test";
1611 $singleitem["provider"]["url"] = "http://test.tld";
1612 $singleitem["title"] = $item["text"];
1613 $singleitem["verb"] = "post";
1614 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1615 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1616 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1617 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1618 //$singleitem["original"] = $item;
1619 $items[] = $singleitem;
1621 $as['items'] = $items;
1622 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1623 $as['link']['rel'] = "alternate";
1624 $as['link']['type'] = "text/html";
1628 function api_format_messages($item, $recipient, $sender) {
1629 // standard meta information
1631 'id' => $item['id'],
1632 'sender_id' => $sender['id'] ,
1634 'recipient_id' => $recipient['id'],
1635 'created_at' => api_date($item['created']),
1636 'sender_screen_name' => $sender['screen_name'],
1637 'recipient_screen_name' => $recipient['screen_name'],
1638 'sender' => $sender,
1639 'recipient' => $recipient,
1642 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1643 unset($ret["sender"]["uid"]);
1644 unset($ret["sender"]["self"]);
1645 unset($ret["recipient"]["uid"]);
1646 unset($ret["recipient"]["self"]);
1648 //don't send title to regular StatusNET requests to avoid confusing these apps
1649 if (x($_GET, 'getText')) {
1650 $ret['title'] = $item['title'] ;
1651 if ($_GET["getText"] == "html") {
1652 $ret['text'] = bbcode($item['body'], false, false);
1654 elseif ($_GET["getText"] == "plain") {
1655 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1656 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1660 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1662 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1663 unset($ret['sender']);
1664 unset($ret['recipient']);
1670 function api_get_entitities(&$text, $bbcode) {
1673 * Links at the first character of the post
1678 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1680 if ($include_entities != "true") {
1681 require_once("mod/proxy.php");
1683 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1685 foreach ($images[1] AS $image) {
1686 $replace = proxy_url($image);
1687 $text = str_replace($image, $replace, $text);
1692 $bbcode = bb_CleanPictureLinks($bbcode);
1694 // Change pure links in text to bbcode uris
1695 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1697 $entities = array();
1698 $entities["hashtags"] = array();
1699 $entities["symbols"] = array();
1700 $entities["urls"] = array();
1701 $entities["user_mentions"] = array();
1703 $URLSearchString = "^\[\]";
1705 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1707 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1708 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1709 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1711 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1712 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1713 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1715 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1716 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1717 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1719 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1721 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1722 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1724 $ordered_urls = array();
1725 foreach ($urls[1] AS $id=>$url) {
1726 //$start = strpos($text, $url, $offset);
1727 $start = iconv_strpos($text, $url, 0, "UTF-8");
1728 if (!($start === false))
1729 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1732 ksort($ordered_urls);
1735 //foreach ($urls[1] AS $id=>$url) {
1736 foreach ($ordered_urls AS $url) {
1737 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1738 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1739 $display_url = $url["title"];
1741 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1742 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1744 if (strlen($display_url) > 26)
1745 $display_url = substr($display_url, 0, 25)."…";
1748 //$start = strpos($text, $url, $offset);
1749 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1750 if (!($start === false)) {
1751 $entities["urls"][] = array("url" => $url["url"],
1752 "expanded_url" => $url["url"],
1753 "display_url" => $display_url,
1754 "indices" => array($start, $start+strlen($url["url"])));
1755 $offset = $start + 1;
1759 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1760 $ordered_images = array();
1761 foreach ($images[1] AS $image) {
1762 //$start = strpos($text, $url, $offset);
1763 $start = iconv_strpos($text, $image, 0, "UTF-8");
1764 if (!($start === false))
1765 $ordered_images[$start] = $image;
1767 //$entities["media"] = array();
1770 foreach ($ordered_images AS $url) {
1771 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1772 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1774 if (strlen($display_url) > 26)
1775 $display_url = substr($display_url, 0, 25)."…";
1777 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1778 if (!($start === false)) {
1779 require_once("include/Photo.php");
1780 $image = get_photo_info($url);
1782 // If image cache is activated, then use the following sizes:
1783 // thumb (150), small (340), medium (600) and large (1024)
1784 if (!get_config("system", "proxy_disabled")) {
1785 require_once("mod/proxy.php");
1786 $media_url = proxy_url($url);
1789 $scale = scale_image($image[0], $image[1], 150);
1790 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1792 if (($image[0] > 150) OR ($image[1] > 150)) {
1793 $scale = scale_image($image[0], $image[1], 340);
1794 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1797 $scale = scale_image($image[0], $image[1], 600);
1798 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1800 if (($image[0] > 600) OR ($image[1] > 600)) {
1801 $scale = scale_image($image[0], $image[1], 1024);
1802 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1806 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1809 $entities["media"][] = array(
1811 "id_str" => (string)$start+1,
1812 "indices" => array($start, $start+strlen($url)),
1813 "media_url" => normalise_link($media_url),
1814 "media_url_https" => $media_url,
1816 "display_url" => $display_url,
1817 "expanded_url" => $url,
1821 $offset = $start + 1;
1828 function api_format_items($r,$user_info, $filter_user = false) {
1833 foreach($r as $item) {
1834 api_share_as_retweet($a, api_user(), $item);
1836 localize_item($item);
1837 $status_user = api_item_get_user($a,$item);
1839 // Look if the posts are matching if they should be filtered by user id
1840 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1843 if ($item['thr-parent'] != $item['uri']) {
1844 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1846 dbesc($item['thr-parent']));
1848 $in_reply_to_status_id = intval($r[0]['id']);
1850 $in_reply_to_status_id = intval($item['parent']);
1852 $in_reply_to_status_id_str = (string) intval($item['parent']);
1854 $in_reply_to_screen_name = NULL;
1855 $in_reply_to_user_id = NULL;
1856 $in_reply_to_user_id_str = NULL;
1858 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1860 intval($in_reply_to_status_id));
1862 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1865 if ($r[0]['nick'] == "")
1866 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1868 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1869 $in_reply_to_user_id = intval($r[0]['id']);
1870 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1874 $in_reply_to_screen_name = NULL;
1875 $in_reply_to_user_id = NULL;
1876 $in_reply_to_status_id = NULL;
1877 $in_reply_to_user_id_str = NULL;
1878 $in_reply_to_status_id_str = NULL;
1881 // Workaround for ostatus messages where the title is identically to the body
1882 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1883 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1884 $statusbody = trim(html2plain($html, 0));
1886 $statustitle = trim($item['title']);
1888 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1889 $statustext = trim($statusbody);
1891 $statustext = trim($statustitle."\n\n".$statusbody);
1893 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1894 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1897 'text' => $statustext,
1898 'truncated' => False,
1899 'created_at'=> api_date($item['created']),
1900 'in_reply_to_status_id' => $in_reply_to_status_id,
1901 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1902 'source' => (($item['app']) ? $item['app'] : 'web'),
1903 'id' => intval($item['id']),
1904 'id_str' => (string) intval($item['id']),
1905 'in_reply_to_user_id' => $in_reply_to_user_id,
1906 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1907 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1909 'favorited' => $item['starred'] ? true : false,
1910 //'attachments' => array(),
1911 'user' => $status_user ,
1912 //'entities' => NULL,
1913 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1914 'statusnet_conversation_id' => $item['parent'],
1917 if ($item['title'] != "")
1918 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
1920 $entities = api_get_entitities($status['text'], $item['body']);
1921 if (count($entities) > 0)
1922 $status['entities'] = $entities;
1924 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1925 $status["source"] = network_to_name($item['item_network']);
1926 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1927 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1930 // Retweets are only valid for top postings
1931 // It doesn't work reliable with the link if its a feed
1932 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1934 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1936 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1937 $retweeted_status = $status;
1938 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1940 $status["retweeted_status"] = $retweeted_status;
1943 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1944 unset($status["user"]["uid"]);
1945 unset($status["user"]["self"]);
1947 // 'geo' => array('type' => 'Point',
1948 // 'coordinates' => array((float) $notice->lat,
1949 // (float) $notice->lon));
1957 function api_account_rate_limit_status(&$a,$type) {
1960 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1961 'remaining_hits' => (string) 150,
1962 'hourly_limit' => (string) 150,
1963 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1966 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1968 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1971 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1973 function api_help_test(&$a,$type) {
1980 return api_apply_template('test', $type, array("$ok" => $ok));
1983 api_register_func('api/help/test','api_help_test',false);
1985 function api_lists(&$a,$type) {
1990 api_register_func('api/lists','api_lists',true);
1992 function api_lists_list(&$a,$type) {
1997 api_register_func('api/lists/list','api_lists_list',true);
2000 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2001 * This function is deprecated by Twitter
2002 * returns: json, xml
2004 function api_statuses_f(&$a, $type, $qtype) {
2005 if (api_user()===false) return false;
2006 $user_info = api_get_user($a);
2008 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2009 /* this is to stop Hotot to load friends multiple times
2010 * I'm not sure if I'm missing return something or
2011 * is a bug in hotot. Workaround, meantime
2015 return array('$users' => $ret);*/
2019 if($qtype == 'friends')
2020 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2021 if($qtype == 'followers')
2022 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2024 // friends and followers only for self
2025 if ($user_info['self'] == 0)
2026 $sql_extra = " AND false ";
2028 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2033 foreach($r as $cid){
2034 $user = api_get_user($a, $cid['nurl']);
2035 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2036 unset($user["uid"]);
2037 unset($user["self"]);
2043 return array('$users' => $ret);
2046 function api_statuses_friends(&$a, $type){
2047 $data = api_statuses_f($a,$type,"friends");
2048 if ($data===false) return false;
2049 return api_apply_template("friends", $type, $data);
2051 function api_statuses_followers(&$a, $type){
2052 $data = api_statuses_f($a,$type,"followers");
2053 if ($data===false) return false;
2054 return api_apply_template("friends", $type, $data);
2056 api_register_func('api/statuses/friends','api_statuses_friends',true);
2057 api_register_func('api/statuses/followers','api_statuses_followers',true);
2064 function api_statusnet_config(&$a,$type) {
2065 $name = $a->config['sitename'];
2066 $server = $a->get_hostname();
2067 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2068 $email = $a->config['admin_email'];
2069 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2070 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2071 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2072 if($a->config['api_import_size'])
2073 $texlimit = string($a->config['api_import_size']);
2074 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2075 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2078 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2079 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2080 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2081 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2082 'shorturllength' => '30',
2083 'friendica' => array(
2084 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2085 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2086 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2087 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2092 return api_apply_template('config', $type, array('$config' => $config));
2095 api_register_func('api/statusnet/config','api_statusnet_config',false);
2097 function api_statusnet_version(&$a,$type) {
2101 if($type === 'xml') {
2102 header("Content-type: application/xml");
2103 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2106 elseif($type === 'json') {
2107 header("Content-type: application/json");
2112 api_register_func('api/statusnet/version','api_statusnet_version',false);
2115 function api_ff_ids(&$a,$type,$qtype) {
2119 $user_info = api_get_user($a);
2121 if($qtype == 'friends')
2122 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2123 if($qtype == 'followers')
2124 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2126 if (!$user_info["self"])
2127 $sql_extra = " AND false ";
2129 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2131 $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",
2137 if($type === 'xml') {
2138 header("Content-type: application/xml");
2139 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2141 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2142 echo '</ids>' . "\r\n";
2145 elseif($type === 'json') {
2147 header("Content-type: application/json");
2152 $ret[] = intval($rr['id']);
2154 echo json_encode($ret);
2160 function api_friends_ids(&$a,$type) {
2161 api_ff_ids($a,$type,'friends');
2163 function api_followers_ids(&$a,$type) {
2164 api_ff_ids($a,$type,'followers');
2166 api_register_func('api/friends/ids','api_friends_ids',true);
2167 api_register_func('api/followers/ids','api_followers_ids',true);
2170 function api_direct_messages_new(&$a, $type) {
2171 if (api_user()===false) return false;
2173 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2175 $sender = api_get_user($a);
2177 require_once("include/message.php");
2179 if ($_POST['screen_name']) {
2180 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2182 dbesc($_POST['screen_name']));
2184 // Selecting the id by priority, friendica first
2185 api_best_nickname($r);
2187 $recipient = api_get_user($a, $r[0]['nurl']);
2189 $recipient = api_get_user($a, $_POST['user_id']);
2193 if (x($_REQUEST,'replyto')) {
2194 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2196 intval($_REQUEST['replyto']));
2197 $replyto = $r[0]['parent-uri'];
2198 $sub = $r[0]['title'];
2201 if (x($_REQUEST,'title')) {
2202 $sub = $_REQUEST['title'];
2205 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2209 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2212 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2213 $ret = api_format_messages($r[0], $recipient, $sender);
2216 $ret = array("error"=>$id);
2219 $data = Array('$messages'=>$ret);
2224 $data = api_rss_extra($a, $data, $user_info);
2227 return api_apply_template("direct_messages", $type, $data);
2230 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2232 function api_direct_messages_box(&$a, $type, $box) {
2233 if (api_user()===false) return false;
2235 unset($_REQUEST["user_id"]);
2236 unset($_GET["user_id"]);
2238 unset($_REQUEST["screen_name"]);
2239 unset($_GET["screen_name"]);
2241 $user_info = api_get_user($a);
2244 $count = (x($_GET,'count')?$_GET['count']:20);
2245 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2246 if ($page<0) $page=0;
2248 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2249 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2251 $start = $page*$count;
2253 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2254 $profile_url = $user_info["url"];
2256 if ($box=="sentbox") {
2257 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2259 elseif ($box=="conversation") {
2260 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2262 elseif ($box=="all") {
2263 $sql_extra = "true";
2265 elseif ($box=="inbox") {
2266 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2270 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2272 $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",
2275 intval($start), intval($count)
2279 foreach($r as $item) {
2280 if ($box == "inbox" || $item['from-url'] != $profile_url){
2281 $recipient = $user_info;
2282 $sender = api_get_user($a,normalise_link($item['contact-url']));
2284 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2285 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2286 $sender = $user_info;
2290 $ret[]=api_format_messages($item, $recipient, $sender);
2294 $data = array('$messages' => $ret);
2298 $data = api_rss_extra($a, $data, $user_info);
2301 return api_apply_template("direct_messages", $type, $data);
2305 function api_direct_messages_sentbox(&$a, $type){
2306 return api_direct_messages_box($a, $type, "sentbox");
2308 function api_direct_messages_inbox(&$a, $type){
2309 return api_direct_messages_box($a, $type, "inbox");
2311 function api_direct_messages_all(&$a, $type){
2312 return api_direct_messages_box($a, $type, "all");
2314 function api_direct_messages_conversation(&$a, $type){
2315 return api_direct_messages_box($a, $type, "conversation");
2317 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2318 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2319 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2320 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2324 function api_oauth_request_token(&$a, $type){
2326 $oauth = new FKOAuth1();
2327 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2328 }catch(Exception $e){
2329 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2334 function api_oauth_access_token(&$a, $type){
2336 $oauth = new FKOAuth1();
2337 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2338 }catch(Exception $e){
2339 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2345 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2346 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2349 function api_fr_photos_list(&$a,$type) {
2350 if (api_user()===false) return false;
2351 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2352 intval(local_user())
2357 $ret[] = $rr['resource-id'];
2358 header("Content-type: application/json");
2359 echo json_encode($ret);
2364 function api_fr_photo_detail(&$a,$type) {
2365 if (api_user()===false) return false;
2366 if(! $_REQUEST['photo_id']) return false;
2367 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2368 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2369 intval(local_user()),
2370 dbesc($_REQUEST['photo_id']),
2374 header("Content-type: application/json");
2375 $r[0]['data'] = base64_encode($r[0]['data']);
2376 echo json_encode($r[0]);
2382 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2383 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2390 function api_share_as_retweet($a, $uid, &$item) {
2391 $body = trim($item["body"]);
2393 // Skip if it isn't a pure repeated messages
2394 // Does it start with a share?
2395 if (strpos($body, "[share") > 0)
2398 // Does it end with a share?
2399 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2402 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2403 // Skip if there is no shared message in there
2404 if ($body == $attributes)
2408 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2409 if ($matches[1] != "")
2410 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2412 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2413 if ($matches[1] != "")
2414 $author = $matches[1];
2417 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2418 if ($matches[1] != "")
2419 $profile = $matches[1];
2421 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2422 if ($matches[1] != "")
2423 $profile = $matches[1];
2426 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2427 if ($matches[1] != "")
2428 $avatar = $matches[1];
2430 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2431 if ($matches[1] != "")
2432 $avatar = $matches[1];
2434 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2436 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2439 $item["body"] = $shared_body;
2440 $item["author-name"] = $author;
2441 $item["author-link"] = $profile;
2442 $item["author-avatar"] = $avatar;
2448 function api_get_nick($profile) {
2450 - remove trailing jung from profile url
2451 - pump.io check has to check the website
2456 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2457 if ($friendica != $profile)
2461 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2462 if ($diaspora != $profile)
2467 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2468 if ($twitter != $profile)
2474 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2475 if ($StatusnetHost != $profile) {
2476 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2477 if ($StatusnetUser != $profile) {
2478 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2479 $user = json_decode($UserData);
2481 $nick = $user->screen_name;
2486 // To-Do: look at the page if its really a pumpio site
2487 //if (!$nick == "") {
2488 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2489 // if ($pumpio != $profile)
2491 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2496 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2497 dbesc($nick), dbesc(normalise_link($profile)));
2504 function api_clean_plain_items($Text) {
2505 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2507 $Text = bb_CleanPictureLinks($Text);
2509 $URLSearchString = "^\[\]";
2511 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2513 if ($include_entities == "true") {
2514 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2517 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2521 function api_cleanup_share($shared) {
2522 if ($shared[2] != "type-link")
2525 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2531 if (isset($bookmark[2][0]))
2532 $title = $bookmark[2][0];
2534 if (isset($bookmark[1][0]))
2535 $link = $bookmark[1][0];
2537 if (strpos($shared[1],$title) !== false)
2540 if (strpos($shared[1],$link) !== false)
2543 $text = trim($shared[1]);
2545 //if (strlen($text) < strlen($title))
2546 if (($text == "") AND ($title != ""))
2547 $text .= "\n\n".trim($title);
2550 $text .= "\n".trim($link);
2552 return(trim($text));
2555 function api_best_nickname(&$contacts) {
2556 $best_contact = array();
2558 if (count($contact) == 0)
2561 foreach ($contacts AS $contact)
2562 if ($contact["network"] == "") {
2563 $contact["network"] = "dfrn";
2564 $best_contact = array($contact);
2567 if (sizeof($best_contact) == 0)
2568 foreach ($contacts AS $contact)
2569 if ($contact["network"] == "dfrn")
2570 $best_contact = array($contact);
2572 if (sizeof($best_contact) == 0)
2573 foreach ($contacts AS $contact)
2574 if ($contact["network"] == "dspr")
2575 $best_contact = array($contact);
2577 if (sizeof($best_contact) == 0)
2578 foreach ($contacts AS $contact)
2579 if ($contact["network"] == "stat")
2580 $best_contact = array($contact);
2582 if (sizeof($best_contact) == 0)
2583 foreach ($contacts AS $contact)
2584 if ($contact["network"] == "pump")
2585 $best_contact = array($contact);
2587 if (sizeof($best_contact) == 0)
2588 foreach ($contacts AS $contact)
2589 if ($contact["network"] == "twit")
2590 $best_contact = array($contact);
2592 if (sizeof($best_contact) == 1)
2593 $contacts = $best_contact;
2595 $contacts = array($contacts[0]);
2599 Not implemented by now:
2603 statuses/retweets_of_me
2608 account/update_location
2609 account/update_profile_background_image
2610 account/update_profile_image
2614 Not implemented in status.net:
2615 statuses/retweeted_to_me
2616 statuses/retweeted_by_me
2617 direct_messages/destroy
2619 account/update_delivery_device
2620 notifications/follow