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 // call out normal post function
731 require_once('mod/item.php');
734 // this should output the last post (the one we just posted).
735 return api_status_show($a,$type);
737 api_register_func('api/statuses/update','api_statuses_update', true);
738 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
741 function api_status_show(&$a, $type){
742 $user_info = api_get_user($a);
744 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
746 // get last public wall message
747 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
748 FROM `item`, `item` as `i`
749 WHERE `item`.`contact-id` = %d
750 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
751 AND `i`.`id` = `item`.`parent`
752 AND `item`.`type`!='activity'
753 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
754 ORDER BY `item`.`created` DESC
756 intval($user_info['cid']),
757 dbesc($user_info['url']),
758 dbesc(normalise_link($user_info['url'])),
759 dbesc($user_info['url']),
760 dbesc(normalise_link($user_info['url']))
763 if (count($lastwall)>0){
764 $lastwall = $lastwall[0];
766 $in_reply_to_status_id = NULL;
767 $in_reply_to_user_id = NULL;
768 $in_reply_to_status_id_str = NULL;
769 $in_reply_to_user_id_str = NULL;
770 $in_reply_to_screen_name = NULL;
771 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
772 $in_reply_to_status_id= intval($lastwall['parent']);
773 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
775 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
777 if ($r[0]['nick'] == "")
778 $r[0]['nick'] = api_get_nick($r[0]["url"]);
780 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
781 $in_reply_to_user_id = intval($r[0]['id']);
782 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
786 // There seems to be situation, where both fields are identical:
787 // https://github.com/friendica/friendica/issues/1010
788 // This is a bugfix for that.
789 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
790 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
791 $in_reply_to_status_id = NULL;
792 $in_reply_to_user_id = NULL;
793 $in_reply_to_status_id_str = NULL;
794 $in_reply_to_user_id_str = NULL;
795 $in_reply_to_screen_name = NULL;
798 $status_info = array(
799 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
800 'truncated' => false,
801 'created_at' => api_date($lastwall['created']),
802 'in_reply_to_status_id' => $in_reply_to_status_id,
803 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
804 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
805 'id' => intval($lastwall['id']),
806 'id_str' => (string) $lastwall['id'],
807 'in_reply_to_user_id' => $in_reply_to_user_id,
808 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
809 'in_reply_to_screen_name' => $in_reply_to_screen_name,
811 'favorited' => false,
813 'user' => $user_info,
814 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
815 'statusnet_conversation_id' => $lastwall['parent'],
818 if ($lastwall['title'] != "")
819 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
821 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
822 if (count($entities) > 0)
823 $status_info['entities'] = $entities;
825 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
826 $status_info["source"] = network_to_name($lastwall['item_network']);
827 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
828 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
830 // "uid" and "self" are only needed for some internal stuff, so remove it from here
831 unset($status_info["user"]["uid"]);
832 unset($status_info["user"]["self"]);
836 return($status_info);
838 return api_apply_template("status", $type, array('$status' => $status_info));
847 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
848 * The author's most recent status will be returned inline.
849 * http://developer.twitter.com/doc/get/users/show
851 function api_users_show(&$a, $type){
852 $user_info = api_get_user($a);
854 $lastwall = q("SELECT `item`.*
855 FROM `item`, `contact`
856 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
857 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
858 AND `contact`.`id`=`item`.`contact-id`
859 AND `type`!='activity'
860 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
861 ORDER BY `created` DESC
864 dbesc(ACTIVITY_POST),
865 intval($user_info['cid']),
866 dbesc($user_info['url']),
867 dbesc(normalise_link($user_info['url'])),
868 dbesc($user_info['url']),
869 dbesc(normalise_link($user_info['url']))
871 if (count($lastwall)>0){
872 $lastwall = $lastwall[0];
874 $in_reply_to_status_id = NULL;
875 $in_reply_to_user_id = NULL;
876 $in_reply_to_status_id_str = NULL;
877 $in_reply_to_user_id_str = NULL;
878 $in_reply_to_screen_name = NULL;
879 if ($lastwall['parent']!=$lastwall['id']) {
880 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
881 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
882 if (count($reply)>0) {
883 $in_reply_to_status_id = intval($lastwall['parent']);
884 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
886 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
888 if ($r[0]['nick'] == "")
889 $r[0]['nick'] = api_get_nick($r[0]["url"]);
891 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
892 $in_reply_to_user_id = intval($r[0]['id']);
893 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
897 $user_info['status'] = array(
898 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
899 'truncated' => false,
900 'created_at' => api_date($lastwall['created']),
901 'in_reply_to_status_id' => $in_reply_to_status_id,
902 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
903 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
904 'id' => intval($lastwall['contact-id']),
905 'id_str' => (string) $lastwall['contact-id'],
906 'in_reply_to_user_id' => $in_reply_to_user_id,
907 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
908 'in_reply_to_screen_name' => $in_reply_to_screen_name,
910 'favorited' => false,
911 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
912 'statusnet_conversation_id' => $lastwall['parent'],
915 if ($lastwall['title'] != "")
916 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
918 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
919 if (count($entities) > 0)
920 $user_info['entities'] = $entities;
922 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
923 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
924 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
925 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
929 // "uid" and "self" are only needed for some internal stuff, so remove it from here
930 unset($user_info["uid"]);
931 unset($user_info["self"]);
933 return api_apply_template("user", $type, array('$user' => $user_info));
936 api_register_func('api/users/show','api_users_show');
939 function api_users_search(&$a, $type) {
940 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
944 if (isset($_GET["q"])) {
945 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
947 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
950 foreach ($r AS $user) {
951 $user_info = api_get_user($a, $user["id"]);
952 //echo print_r($user_info, true)."\n";
953 $userdata = api_apply_template("user", $type, array('user' => $user_info));
954 $userlist[] = $userdata["user"];
956 $userlist = array("users" => $userlist);
958 die(api_error($a, $type, t("User not found.")));
960 die(api_error($a, $type, t("User not found.")));
965 api_register_func('api/users/search','api_users_search');
969 * http://developer.twitter.com/doc/get/statuses/home_timeline
971 * TODO: Optional parameters
972 * TODO: Add reply info
974 function api_statuses_home_timeline(&$a, $type){
975 if (api_user()===false) return false;
977 unset($_REQUEST["user_id"]);
978 unset($_GET["user_id"]);
980 unset($_REQUEST["screen_name"]);
981 unset($_GET["screen_name"]);
983 $user_info = api_get_user($a);
984 // get last newtork messages
988 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
989 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
990 if ($page<0) $page=0;
991 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
992 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
993 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
994 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
995 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
997 $start = $page*$count;
1001 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1002 if ($exclude_replies > 0)
1003 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1004 if ($conversation_id > 0)
1005 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1007 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1008 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1009 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1010 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1011 FROM `item`, `contact`
1012 WHERE `item`.`uid` = %d AND `verb` = '%s'
1013 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1014 AND `contact`.`id` = `item`.`contact-id`
1015 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1018 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1020 dbesc(ACTIVITY_POST),
1022 intval($start), intval($count)
1025 $ret = api_format_items($r,$user_info);
1027 // We aren't going to try to figure out at the item, group, and page
1028 // level which items you've seen and which you haven't. If you're looking
1029 // at the network timeline just mark everything seen.
1031 $r = q("UPDATE `item` SET `unseen` = 0
1032 WHERE `unseen` = 1 AND `uid` = %d",
1033 //intval($user_info['uid'])
1038 $data = array('$statuses' => $ret);
1042 $data = api_rss_extra($a, $data, $user_info);
1045 $as = api_format_as($a, $ret, $user_info);
1046 $as['title'] = $a->config['sitename']." Home Timeline";
1047 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1052 return api_apply_template("timeline", $type, $data);
1054 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1055 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1057 function api_statuses_public_timeline(&$a, $type){
1058 if (api_user()===false) return false;
1060 $user_info = api_get_user($a);
1061 // get last newtork messages
1065 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1066 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1067 if ($page<0) $page=0;
1068 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1069 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1070 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1071 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1072 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1074 $start = $page*$count;
1077 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1078 if ($exclude_replies > 0)
1079 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1080 if ($conversation_id > 0)
1081 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1083 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1084 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1085 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1086 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1087 `user`.`nickname`, `user`.`hidewall`
1088 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1089 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1090 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1091 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1092 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1093 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1094 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1097 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1098 dbesc(ACTIVITY_POST),
1103 $ret = api_format_items($r,$user_info);
1106 $data = array('$statuses' => $ret);
1110 $data = api_rss_extra($a, $data, $user_info);
1113 $as = api_format_as($a, $ret, $user_info);
1114 $as['title'] = $a->config['sitename']." Public Timeline";
1115 $as['link']['url'] = $a->get_baseurl()."/";
1120 return api_apply_template("timeline", $type, $data);
1122 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1127 function api_statuses_show(&$a, $type){
1128 if (api_user()===false) return false;
1130 $user_info = api_get_user($a);
1133 $id = intval($a->argv[3]);
1136 $id = intval($_REQUEST["id"]);
1140 $id = intval($a->argv[4]);
1142 logger('API: api_statuses_show: '.$id);
1144 $conversation = (x($_REQUEST,'conversation')?1:0);
1148 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1150 $sql_extra .= " AND `item`.`id` = %d";
1152 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1153 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1154 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1155 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1156 FROM `item`, `contact`
1157 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1158 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1159 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1162 dbesc(ACTIVITY_POST),
1167 die(api_error($a, $type, t("There is no status with this id.")));
1169 $ret = api_format_items($r,$user_info);
1171 if ($conversation) {
1172 $data = array('$statuses' => $ret);
1173 return api_apply_template("timeline", $type, $data);
1175 $data = array('$status' => $ret[0]);
1179 $data = api_rss_extra($a, $data, $user_info);
1181 return api_apply_template("status", $type, $data);
1184 api_register_func('api/statuses/show','api_statuses_show', true);
1190 function api_conversation_show(&$a, $type){
1191 if (api_user()===false) return false;
1193 $user_info = api_get_user($a);
1196 $id = intval($a->argv[3]);
1197 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1198 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1199 if ($page<0) $page=0;
1200 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1201 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1203 $start = $page*$count;
1206 $id = intval($_REQUEST["id"]);
1210 $id = intval($a->argv[4]);
1212 logger('API: api_conversation_show: '.$id);
1217 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1219 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1220 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1221 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1222 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1223 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1224 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1225 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1226 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1227 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1228 AND `item`.`id`>%d $sql_extra
1229 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1230 intval($id), intval(api_user()),
1231 dbesc(ACTIVITY_POST),
1233 intval($start), intval($count)
1237 die(api_error($a, $type, t("There is no conversation with this id.")));
1239 $ret = api_format_items($r,$user_info);
1241 $data = array('$statuses' => $ret);
1242 return api_apply_template("timeline", $type, $data);
1244 api_register_func('api/conversation/show','api_conversation_show', true);
1250 function api_statuses_repeat(&$a, $type){
1253 if (api_user()===false) return false;
1255 $user_info = api_get_user($a);
1258 $id = intval($a->argv[3]);
1261 $id = intval($_REQUEST["id"]);
1265 $id = intval($a->argv[4]);
1267 logger('API: api_statuses_repeat: '.$id);
1269 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1270 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1271 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1272 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1273 FROM `item`, `contact`
1274 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1275 AND `contact`.`id` = `item`.`contact-id`
1276 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1278 AND `item`.`id`=%d",
1282 if ($r[0]['body'] != "") {
1283 if (!intval(get_config('system','old_share'))) {
1284 if (strpos($r[0]['body'], "[/share]") !== false) {
1285 $pos = strpos($r[0]['body'], "[share");
1286 $post = substr($r[0]['body'], $pos);
1288 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1289 "' profile='".$r[0]['author-link'].
1290 "' avatar='".$r[0]['author-avatar'].
1291 "' link='".$r[0]['plink']."']";
1292 $post .= $r[0]['body'];
1293 $post .= "[/share]";
1295 $_REQUEST['body'] = $post;
1297 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1299 $_REQUEST['profile_uid'] = api_user();
1300 $_REQUEST['type'] = 'wall';
1301 $_REQUEST['api_source'] = true;
1303 require_once('mod/item.php');
1307 // this should output the last post (the one we just posted).
1309 return(api_status_show($a,$type));
1311 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1316 function api_statuses_destroy(&$a, $type){
1317 if (api_user()===false) return false;
1319 $user_info = api_get_user($a);
1322 $id = intval($a->argv[3]);
1325 $id = intval($_REQUEST["id"]);
1329 $id = intval($a->argv[4]);
1331 logger('API: api_statuses_destroy: '.$id);
1333 $ret = api_statuses_show($a, $type);
1335 require_once('include/items.php');
1336 drop_item($id, false);
1340 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1344 * http://developer.twitter.com/doc/get/statuses/mentions
1347 function api_statuses_mentions(&$a, $type){
1348 if (api_user()===false) return false;
1350 unset($_REQUEST["user_id"]);
1351 unset($_GET["user_id"]);
1353 unset($_REQUEST["screen_name"]);
1354 unset($_GET["screen_name"]);
1356 $user_info = api_get_user($a);
1357 // get last newtork messages
1361 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1362 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1363 if ($page<0) $page=0;
1364 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1365 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1366 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1368 $start = $page*$count;
1370 // Ugly code - should be changed
1371 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1372 $myurl = substr($myurl,strpos($myurl,'://')+3);
1373 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1374 $myurl = str_replace('www.','',$myurl);
1375 $diasp_url = str_replace('/profile/','/u/',$myurl);
1378 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1380 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1381 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1382 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1383 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1384 FROM `item`, `contact`
1385 WHERE `item`.`uid` = %d AND `verb` = '%s'
1386 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1387 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1388 AND `contact`.`id` = `item`.`contact-id`
1389 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1390 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention`)
1393 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1395 dbesc(ACTIVITY_POST),
1396 dbesc(protect_sprintf($myurl)),
1397 dbesc(protect_sprintf($myurl)),
1400 intval($start), intval($count)
1403 $ret = api_format_items($r,$user_info);
1406 $data = array('$statuses' => $ret);
1410 $data = api_rss_extra($a, $data, $user_info);
1413 $as = api_format_as($a, $ret, $user_info);
1414 $as["title"] = $a->config['sitename']." Mentions";
1415 $as['link']['url'] = $a->get_baseurl()."/";
1420 return api_apply_template("timeline", $type, $data);
1422 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1423 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1426 function api_statuses_user_timeline(&$a, $type){
1427 if (api_user()===false) return false;
1429 $user_info = api_get_user($a);
1430 // get last network messages
1432 logger("api_statuses_user_timeline: api_user: ". api_user() .
1433 "\nuser_info: ".print_r($user_info, true) .
1434 "\n_REQUEST: ".print_r($_REQUEST, true),
1438 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1439 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1440 if ($page<0) $page=0;
1441 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1442 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1443 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1444 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1446 $start = $page*$count;
1449 if ($user_info['self']==1)
1450 $sql_extra .= " AND `item`.`wall` = 1 ";
1452 if ($exclude_replies > 0)
1453 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1454 if ($conversation_id > 0)
1455 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1457 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1458 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1459 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1460 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1461 FROM `item`, `contact`
1462 WHERE `item`.`uid` = %d AND `verb` = '%s'
1463 AND `item`.`contact-id` = %d
1464 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1465 AND `contact`.`id` = `item`.`contact-id`
1466 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1469 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1471 dbesc(ACTIVITY_POST),
1472 intval($user_info['cid']),
1474 intval($start), intval($count)
1477 $ret = api_format_items($r,$user_info, true);
1479 $data = array('$statuses' => $ret);
1483 $data = api_rss_extra($a, $data, $user_info);
1486 return api_apply_template("timeline", $type, $data);
1489 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1492 function api_favorites(&$a, $type){
1495 if (api_user()===false) return false;
1497 $called_api= array();
1499 $user_info = api_get_user($a);
1501 // in friendica starred item are private
1502 // return favorites only for self
1503 logger('api_favorites: self:' . $user_info['self']);
1505 if ($user_info['self']==0) {
1511 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1512 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1513 $count = (x($_GET,'count')?$_GET['count']:20);
1514 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1515 if ($page<0) $page=0;
1517 $start = $page*$count;
1520 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1522 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1523 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1524 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1525 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1526 FROM `item`, `contact`
1527 WHERE `item`.`uid` = %d AND `verb` = '%s'
1528 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1529 AND `item`.`starred` = 1
1530 AND `contact`.`id` = `item`.`contact-id`
1531 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1534 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1536 dbesc(ACTIVITY_POST),
1538 intval($start), intval($count)
1541 $ret = api_format_items($r,$user_info);
1545 $data = array('$statuses' => $ret);
1549 $data = api_rss_extra($a, $data, $user_info);
1552 return api_apply_template("timeline", $type, $data);
1555 api_register_func('api/favorites','api_favorites', true);
1557 function api_format_as($a, $ret, $user_info) {
1560 $as['title'] = $a->config['sitename']." Public Timeline";
1562 foreach ($ret as $item) {
1563 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1564 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1565 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1566 $avatar[0]["rel"] = "avatar";
1567 $avatar[0]["type"] = "";
1568 $avatar[0]["width"] = 96;
1569 $avatar[0]["height"] = 96;
1570 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1571 $avatar[1]["rel"] = "avatar";
1572 $avatar[1]["type"] = "";
1573 $avatar[1]["width"] = 48;
1574 $avatar[1]["height"] = 48;
1575 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1576 $avatar[2]["rel"] = "avatar";
1577 $avatar[2]["type"] = "";
1578 $avatar[2]["width"] = 24;
1579 $avatar[2]["height"] = 24;
1580 $singleitem["actor"]["avatarLinks"] = $avatar;
1582 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1583 $singleitem["actor"]["image"]["rel"] = "avatar";
1584 $singleitem["actor"]["image"]["type"] = "";
1585 $singleitem["actor"]["image"]["width"] = 96;
1586 $singleitem["actor"]["image"]["height"] = 96;
1587 $singleitem["actor"]["type"] = "person";
1588 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1589 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1590 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1591 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1592 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1593 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1594 $singleitem["actor"]["contact"]["addresses"] = "";
1596 $singleitem["body"] = $item["text"];
1597 $singleitem["object"]["displayName"] = $item["text"];
1598 $singleitem["object"]["id"] = $item["url"];
1599 $singleitem["object"]["type"] = "note";
1600 $singleitem["object"]["url"] = $item["url"];
1601 //$singleitem["context"] =;
1602 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1603 $singleitem["provider"]["objectType"] = "service";
1604 $singleitem["provider"]["displayName"] = "Test";
1605 $singleitem["provider"]["url"] = "http://test.tld";
1606 $singleitem["title"] = $item["text"];
1607 $singleitem["verb"] = "post";
1608 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1609 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1610 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1611 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1612 //$singleitem["original"] = $item;
1613 $items[] = $singleitem;
1615 $as['items'] = $items;
1616 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1617 $as['link']['rel'] = "alternate";
1618 $as['link']['type'] = "text/html";
1622 function api_format_messages($item, $recipient, $sender) {
1623 // standard meta information
1625 'id' => $item['id'],
1626 'sender_id' => $sender['id'] ,
1628 'recipient_id' => $recipient['id'],
1629 'created_at' => api_date($item['created']),
1630 'sender_screen_name' => $sender['screen_name'],
1631 'recipient_screen_name' => $recipient['screen_name'],
1632 'sender' => $sender,
1633 'recipient' => $recipient,
1636 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1637 unset($ret["sender"]["uid"]);
1638 unset($ret["sender"]["self"]);
1639 unset($ret["recipient"]["uid"]);
1640 unset($ret["recipient"]["self"]);
1642 //don't send title to regular StatusNET requests to avoid confusing these apps
1643 if (x($_GET, 'getText')) {
1644 $ret['title'] = $item['title'] ;
1645 if ($_GET["getText"] == "html") {
1646 $ret['text'] = bbcode($item['body'], false, false);
1648 elseif ($_GET["getText"] == "plain") {
1649 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1650 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1654 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1656 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1657 unset($ret['sender']);
1658 unset($ret['recipient']);
1664 function api_get_entitities(&$text, $bbcode) {
1667 * Links at the first character of the post
1672 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1674 if ($include_entities != "true") {
1675 require_once("mod/proxy.php");
1677 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1679 foreach ($images[1] AS $image) {
1680 $replace = proxy_url($image);
1681 $text = str_replace($image, $replace, $text);
1686 $bbcode = bb_CleanPictureLinks($bbcode);
1688 // Change pure links in text to bbcode uris
1689 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1691 $entities = array();
1692 $entities["hashtags"] = array();
1693 $entities["symbols"] = array();
1694 $entities["urls"] = array();
1695 $entities["user_mentions"] = array();
1697 $URLSearchString = "^\[\]";
1699 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1701 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1702 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1703 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1705 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1706 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1707 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1709 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1710 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1711 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1713 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1715 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1716 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1718 $ordered_urls = array();
1719 foreach ($urls[1] AS $id=>$url) {
1720 //$start = strpos($text, $url, $offset);
1721 $start = iconv_strpos($text, $url, 0, "UTF-8");
1722 if (!($start === false))
1723 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1726 ksort($ordered_urls);
1729 //foreach ($urls[1] AS $id=>$url) {
1730 foreach ($ordered_urls AS $url) {
1731 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1732 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1733 $display_url = $url["title"];
1735 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1736 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1738 if (strlen($display_url) > 26)
1739 $display_url = substr($display_url, 0, 25)."…";
1742 //$start = strpos($text, $url, $offset);
1743 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1744 if (!($start === false)) {
1745 $entities["urls"][] = array("url" => $url["url"],
1746 "expanded_url" => $url["url"],
1747 "display_url" => $display_url,
1748 "indices" => array($start, $start+strlen($url["url"])));
1749 $offset = $start + 1;
1753 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1754 $ordered_images = array();
1755 foreach ($images[1] AS $image) {
1756 //$start = strpos($text, $url, $offset);
1757 $start = iconv_strpos($text, $image, 0, "UTF-8");
1758 if (!($start === false))
1759 $ordered_images[$start] = $image;
1761 //$entities["media"] = array();
1764 foreach ($ordered_images AS $url) {
1765 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1766 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1768 if (strlen($display_url) > 26)
1769 $display_url = substr($display_url, 0, 25)."…";
1771 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1772 if (!($start === false)) {
1773 require_once("include/Photo.php");
1774 $image = get_photo_info($url);
1776 // If image cache is activated, then use the following sizes:
1777 // thumb (150), small (340), medium (600) and large (1024)
1778 if (!get_config("system", "proxy_disabled")) {
1779 require_once("mod/proxy.php");
1780 $media_url = proxy_url($url);
1783 $scale = scale_image($image[0], $image[1], 150);
1784 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1786 if (($image[0] > 150) OR ($image[1] > 150)) {
1787 $scale = scale_image($image[0], $image[1], 340);
1788 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1791 $scale = scale_image($image[0], $image[1], 600);
1792 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1794 if (($image[0] > 600) OR ($image[1] > 600)) {
1795 $scale = scale_image($image[0], $image[1], 1024);
1796 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1800 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1803 $entities["media"][] = array(
1805 "id_str" => (string)$start+1,
1806 "indices" => array($start, $start+strlen($url)),
1807 "media_url" => normalise_link($media_url),
1808 "media_url_https" => $media_url,
1810 "display_url" => $display_url,
1811 "expanded_url" => $url,
1815 $offset = $start + 1;
1822 function api_format_items($r,$user_info, $filter_user = false) {
1827 foreach($r as $item) {
1828 api_share_as_retweet($a, api_user(), $item);
1830 localize_item($item);
1831 $status_user = api_item_get_user($a,$item);
1833 // Look if the posts are matching if they should be filtered by user id
1834 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1837 if ($item['thr-parent'] != $item['uri']) {
1838 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1840 dbesc($item['thr-parent']));
1842 $in_reply_to_status_id = intval($r[0]['id']);
1844 $in_reply_to_status_id = intval($item['parent']);
1846 $in_reply_to_status_id_str = (string) intval($item['parent']);
1848 $in_reply_to_screen_name = NULL;
1849 $in_reply_to_user_id = NULL;
1850 $in_reply_to_user_id_str = NULL;
1852 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1854 intval($in_reply_to_status_id));
1856 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1859 if ($r[0]['nick'] == "")
1860 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1862 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1863 $in_reply_to_user_id = intval($r[0]['id']);
1864 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1868 $in_reply_to_screen_name = NULL;
1869 $in_reply_to_user_id = NULL;
1870 $in_reply_to_status_id = NULL;
1871 $in_reply_to_user_id_str = NULL;
1872 $in_reply_to_status_id_str = NULL;
1875 // Workaround for ostatus messages where the title is identically to the body
1876 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1877 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1878 $statusbody = trim(html2plain($html, 0));
1880 $statustitle = trim($item['title']);
1882 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1883 $statustext = trim($statusbody);
1885 $statustext = trim($statustitle."\n\n".$statusbody);
1887 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1888 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1891 'text' => $statustext,
1892 'truncated' => False,
1893 'created_at'=> api_date($item['created']),
1894 'in_reply_to_status_id' => $in_reply_to_status_id,
1895 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1896 'source' => (($item['app']) ? $item['app'] : 'web'),
1897 'id' => intval($item['id']),
1898 'id_str' => (string) intval($item['id']),
1899 'in_reply_to_user_id' => $in_reply_to_user_id,
1900 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1901 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1903 'favorited' => $item['starred'] ? true : false,
1904 //'attachments' => array(),
1905 'user' => $status_user ,
1906 //'entities' => NULL,
1907 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1908 'statusnet_conversation_id' => $item['parent'],
1911 if ($item['title'] != "")
1912 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
1914 $entities = api_get_entitities($status['text'], $item['body']);
1915 if (count($entities) > 0)
1916 $status['entities'] = $entities;
1918 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1919 $status["source"] = network_to_name($item['item_network']);
1920 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1921 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1924 // Retweets are only valid for top postings
1925 // It doesn't work reliable with the link if its a feed
1926 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1928 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1930 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1931 $retweeted_status = $status;
1932 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1934 $status["retweeted_status"] = $retweeted_status;
1937 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1938 unset($status["user"]["uid"]);
1939 unset($status["user"]["self"]);
1941 // 'geo' => array('type' => 'Point',
1942 // 'coordinates' => array((float) $notice->lat,
1943 // (float) $notice->lon));
1951 function api_account_rate_limit_status(&$a,$type) {
1954 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1955 'remaining_hits' => (string) 150,
1956 'hourly_limit' => (string) 150,
1957 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1960 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1962 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1965 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1967 function api_help_test(&$a,$type) {
1974 return api_apply_template('test', $type, array("$ok" => $ok));
1977 api_register_func('api/help/test','api_help_test',false);
1979 function api_lists(&$a,$type) {
1984 api_register_func('api/lists','api_lists',true);
1986 function api_lists_list(&$a,$type) {
1991 api_register_func('api/lists/list','api_lists_list',true);
1994 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1995 * This function is deprecated by Twitter
1996 * returns: json, xml
1998 function api_statuses_f(&$a, $type, $qtype) {
1999 if (api_user()===false) return false;
2000 $user_info = api_get_user($a);
2002 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2003 /* this is to stop Hotot to load friends multiple times
2004 * I'm not sure if I'm missing return something or
2005 * is a bug in hotot. Workaround, meantime
2009 return array('$users' => $ret);*/
2013 if($qtype == 'friends')
2014 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2015 if($qtype == 'followers')
2016 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2018 // friends and followers only for self
2019 if ($user_info['self'] == 0)
2020 $sql_extra = " AND false ";
2022 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2027 foreach($r as $cid){
2028 $user = api_get_user($a, $cid['nurl']);
2029 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2030 unset($user["uid"]);
2031 unset($user["self"]);
2037 return array('$users' => $ret);
2040 function api_statuses_friends(&$a, $type){
2041 $data = api_statuses_f($a,$type,"friends");
2042 if ($data===false) return false;
2043 return api_apply_template("friends", $type, $data);
2045 function api_statuses_followers(&$a, $type){
2046 $data = api_statuses_f($a,$type,"followers");
2047 if ($data===false) return false;
2048 return api_apply_template("friends", $type, $data);
2050 api_register_func('api/statuses/friends','api_statuses_friends',true);
2051 api_register_func('api/statuses/followers','api_statuses_followers',true);
2058 function api_statusnet_config(&$a,$type) {
2059 $name = $a->config['sitename'];
2060 $server = $a->get_hostname();
2061 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2062 $email = $a->config['admin_email'];
2063 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2064 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2065 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2066 if($a->config['api_import_size'])
2067 $texlimit = string($a->config['api_import_size']);
2068 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2069 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2072 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2073 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2074 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2075 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2076 'shorturllength' => '30',
2077 'friendica' => array(
2078 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2079 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2080 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2081 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2086 return api_apply_template('config', $type, array('$config' => $config));
2089 api_register_func('api/statusnet/config','api_statusnet_config',false);
2091 function api_statusnet_version(&$a,$type) {
2095 if($type === 'xml') {
2096 header("Content-type: application/xml");
2097 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2100 elseif($type === 'json') {
2101 header("Content-type: application/json");
2106 api_register_func('api/statusnet/version','api_statusnet_version',false);
2109 function api_ff_ids(&$a,$type,$qtype) {
2113 $user_info = api_get_user($a);
2115 if($qtype == 'friends')
2116 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2117 if($qtype == 'followers')
2118 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2120 if (!$user_info["self"])
2121 $sql_extra = " AND false ";
2123 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2125 $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",
2131 if($type === 'xml') {
2132 header("Content-type: application/xml");
2133 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2135 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2136 echo '</ids>' . "\r\n";
2139 elseif($type === 'json') {
2141 header("Content-type: application/json");
2146 $ret[] = intval($rr['id']);
2148 echo json_encode($ret);
2154 function api_friends_ids(&$a,$type) {
2155 api_ff_ids($a,$type,'friends');
2157 function api_followers_ids(&$a,$type) {
2158 api_ff_ids($a,$type,'followers');
2160 api_register_func('api/friends/ids','api_friends_ids',true);
2161 api_register_func('api/followers/ids','api_followers_ids',true);
2164 function api_direct_messages_new(&$a, $type) {
2165 if (api_user()===false) return false;
2167 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2169 $sender = api_get_user($a);
2171 require_once("include/message.php");
2173 if ($_POST['screen_name']) {
2174 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2176 dbesc($_POST['screen_name']));
2178 // Selecting the id by priority, friendica first
2179 api_best_nickname($r);
2181 $recipient = api_get_user($a, $r[0]['nurl']);
2183 $recipient = api_get_user($a, $_POST['user_id']);
2187 if (x($_REQUEST,'replyto')) {
2188 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2190 intval($_REQUEST['replyto']));
2191 $replyto = $r[0]['parent-uri'];
2192 $sub = $r[0]['title'];
2195 if (x($_REQUEST,'title')) {
2196 $sub = $_REQUEST['title'];
2199 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2203 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2206 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2207 $ret = api_format_messages($r[0], $recipient, $sender);
2210 $ret = array("error"=>$id);
2213 $data = Array('$messages'=>$ret);
2218 $data = api_rss_extra($a, $data, $user_info);
2221 return api_apply_template("direct_messages", $type, $data);
2224 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2226 function api_direct_messages_box(&$a, $type, $box) {
2227 if (api_user()===false) return false;
2229 unset($_REQUEST["user_id"]);
2230 unset($_GET["user_id"]);
2232 unset($_REQUEST["screen_name"]);
2233 unset($_GET["screen_name"]);
2235 $user_info = api_get_user($a);
2238 $count = (x($_GET,'count')?$_GET['count']:20);
2239 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2240 if ($page<0) $page=0;
2242 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2243 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2245 $start = $page*$count;
2247 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2248 $profile_url = $user_info["url"];
2250 if ($box=="sentbox") {
2251 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2253 elseif ($box=="conversation") {
2254 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2256 elseif ($box=="all") {
2257 $sql_extra = "true";
2259 elseif ($box=="inbox") {
2260 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2264 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2266 $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",
2269 intval($start), intval($count)
2273 foreach($r as $item) {
2274 if ($box == "inbox" || $item['from-url'] != $profile_url){
2275 $recipient = $user_info;
2276 $sender = api_get_user($a,normalise_link($item['contact-url']));
2278 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2279 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2280 $sender = $user_info;
2284 $ret[]=api_format_messages($item, $recipient, $sender);
2288 $data = array('$messages' => $ret);
2292 $data = api_rss_extra($a, $data, $user_info);
2295 return api_apply_template("direct_messages", $type, $data);
2299 function api_direct_messages_sentbox(&$a, $type){
2300 return api_direct_messages_box($a, $type, "sentbox");
2302 function api_direct_messages_inbox(&$a, $type){
2303 return api_direct_messages_box($a, $type, "inbox");
2305 function api_direct_messages_all(&$a, $type){
2306 return api_direct_messages_box($a, $type, "all");
2308 function api_direct_messages_conversation(&$a, $type){
2309 return api_direct_messages_box($a, $type, "conversation");
2311 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2312 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2313 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2314 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2318 function api_oauth_request_token(&$a, $type){
2320 $oauth = new FKOAuth1();
2321 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2322 }catch(Exception $e){
2323 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2328 function api_oauth_access_token(&$a, $type){
2330 $oauth = new FKOAuth1();
2331 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2332 }catch(Exception $e){
2333 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2339 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2340 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2343 function api_fr_photos_list(&$a,$type) {
2344 if (api_user()===false) return false;
2345 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2346 intval(local_user())
2351 $ret[] = $rr['resource-id'];
2352 header("Content-type: application/json");
2353 echo json_encode($ret);
2358 function api_fr_photo_detail(&$a,$type) {
2359 if (api_user()===false) return false;
2360 if(! $_REQUEST['photo_id']) return false;
2361 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2362 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2363 intval(local_user()),
2364 dbesc($_REQUEST['photo_id']),
2368 header("Content-type: application/json");
2369 $r[0]['data'] = base64_encode($r[0]['data']);
2370 echo json_encode($r[0]);
2376 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2377 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2384 function api_share_as_retweet($a, $uid, &$item) {
2385 $body = trim($item["body"]);
2387 // Skip if it isn't a pure repeated messages
2388 // Does it start with a share?
2389 if (strpos($body, "[share") > 0)
2392 // Does it end with a share?
2393 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2396 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2397 // Skip if there is no shared message in there
2398 if ($body == $attributes)
2402 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2403 if ($matches[1] != "")
2404 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2406 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2407 if ($matches[1] != "")
2408 $author = $matches[1];
2411 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2412 if ($matches[1] != "")
2413 $profile = $matches[1];
2415 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2416 if ($matches[1] != "")
2417 $profile = $matches[1];
2420 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2421 if ($matches[1] != "")
2422 $avatar = $matches[1];
2424 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2425 if ($matches[1] != "")
2426 $avatar = $matches[1];
2428 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2430 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2433 $item["body"] = $shared_body;
2434 $item["author-name"] = $author;
2435 $item["author-link"] = $profile;
2436 $item["author-avatar"] = $avatar;
2442 function api_get_nick($profile) {
2444 - remove trailing jung from profile url
2445 - pump.io check has to check the website
2450 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2451 if ($friendica != $profile)
2455 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2456 if ($diaspora != $profile)
2461 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2462 if ($twitter != $profile)
2468 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2469 if ($StatusnetHost != $profile) {
2470 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2471 if ($StatusnetUser != $profile) {
2472 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2473 $user = json_decode($UserData);
2475 $nick = $user->screen_name;
2480 // To-Do: look at the page if its really a pumpio site
2481 //if (!$nick == "") {
2482 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2483 // if ($pumpio != $profile)
2485 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2490 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2491 dbesc($nick), dbesc(normalise_link($profile)));
2498 function api_clean_plain_items($Text) {
2499 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2501 $Text = bb_CleanPictureLinks($Text);
2503 $URLSearchString = "^\[\]";
2505 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2507 if ($include_entities == "true") {
2508 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2511 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2515 function api_cleanup_share($shared) {
2516 if ($shared[2] != "type-link")
2519 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2525 if (isset($bookmark[2][0]))
2526 $title = $bookmark[2][0];
2528 if (isset($bookmark[1][0]))
2529 $link = $bookmark[1][0];
2531 if (strpos($shared[1],$title) !== false)
2534 if (strpos($shared[1],$link) !== false)
2537 $text = trim($shared[1]);
2539 //if (strlen($text) < strlen($title))
2540 if (($text == "") AND ($title != ""))
2541 $text .= "\n\n".trim($title);
2544 $text .= "\n".trim($link);
2546 return(trim($text));
2549 function api_best_nickname(&$contacts) {
2550 $best_contact = array();
2552 if (count($contact) == 0)
2555 foreach ($contacts AS $contact)
2556 if ($contact["network"] == "") {
2557 $contact["network"] = "dfrn";
2558 $best_contact = array($contact);
2561 if (sizeof($best_contact) == 0)
2562 foreach ($contacts AS $contact)
2563 if ($contact["network"] == "dfrn")
2564 $best_contact = array($contact);
2566 if (sizeof($best_contact) == 0)
2567 foreach ($contacts AS $contact)
2568 if ($contact["network"] == "dspr")
2569 $best_contact = array($contact);
2571 if (sizeof($best_contact) == 0)
2572 foreach ($contacts AS $contact)
2573 if ($contact["network"] == "stat")
2574 $best_contact = array($contact);
2576 if (sizeof($best_contact) == 0)
2577 foreach ($contacts AS $contact)
2578 if ($contact["network"] == "pump")
2579 $best_contact = array($contact);
2581 if (sizeof($best_contact) == 0)
2582 foreach ($contacts AS $contact)
2583 if ($contact["network"] == "twit")
2584 $best_contact = array($contact);
2586 if (sizeof($best_contact) == 1)
2587 $contacts = $best_contact;
2589 $contacts = array($contacts[0]);
2593 Not implemented by now:
2597 statuses/retweets_of_me
2602 account/update_location
2603 account/update_profile_background_image
2604 account/update_profile_image
2608 Not implemented in status.net:
2609 statuses/retweeted_to_me
2610 statuses/retweeted_by_me
2611 direct_messages/destroy
2613 account/update_delivery_device
2614 notifications/follow