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_source() {
30 if (requestdata('source'))
31 return (requestdata('source'));
33 // Support for known clients that doesn't send a source name
34 if (strstr($_SERVER['HTTP_USER_AGENT'], "Twidere"))
37 logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
42 function api_date($str){
43 //Wed May 23 06:01:13 +0000 2007
44 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
48 function api_register_func($path, $func, $auth=false){
50 $API[$path] = array('func'=>$func, 'auth'=>$auth);
52 // Workaround for hotot
53 $path = str_replace("api/", "api/1.1/", $path);
54 $API[$path] = array('func'=>$func, 'auth'=>$auth);
61 function api_login(&$a){
64 $oauth = new FKOAuth1();
65 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
66 if (!is_null($token)){
67 $oauth->loginUser($token->uid);
68 call_hooks('logged_in', $a->user);
71 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
73 logger(__file__.__line__.__function__."\n".$e);
74 //die(__file__.__line__.__function__."<pre>".$e); die();
79 // workaround for HTTP-auth in CGI mode
80 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
81 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
82 if(strlen($userpass)) {
83 list($name, $password) = explode(':', $userpass);
84 $_SERVER['PHP_AUTH_USER'] = $name;
85 $_SERVER['PHP_AUTH_PW'] = $password;
89 if (!isset($_SERVER['PHP_AUTH_USER'])) {
90 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
91 header('WWW-Authenticate: Basic realm="Friendica"');
92 header('HTTP/1.0 401 Unauthorized');
93 die((api_error($a, 'json', "This api requires login")));
95 //die('This api requires login');
98 $user = $_SERVER['PHP_AUTH_USER'];
99 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
103 * next code from mod/auth.php. needs better solution
106 // process normal login request
108 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
109 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
117 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
118 header('WWW-Authenticate: Basic realm="Friendica"');
119 header('HTTP/1.0 401 Unauthorized');
120 die('This api requires login');
123 require_once('include/security.php');
124 authenticate_success($record); $_SESSION["allow_api"] = true;
126 call_hooks('logged_in', $a->user);
130 /**************************
131 * MAIN API ENTRY POINT *
132 **************************/
133 function api_call(&$a){
134 GLOBAL $API, $called_api;
138 foreach ($API as $p=>$info){
139 if (strpos($a->query_string, $p)===0){
140 $called_api= explode("/",$p);
141 //unset($_SERVER['PHP_AUTH_USER']);
142 if ($info['auth']===true && api_user()===false) {
146 load_contact_links(api_user());
148 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
149 logger('API parameters: ' . print_r($_REQUEST,true));
151 if (strpos($a->query_string, ".xml")>0) $type="xml";
152 if (strpos($a->query_string, ".json")>0) $type="json";
153 if (strpos($a->query_string, ".rss")>0) $type="rss";
154 if (strpos($a->query_string, ".atom")>0) $type="atom";
155 if (strpos($a->query_string, ".as")>0) $type="as";
157 $r = call_user_func($info['func'], $a, $type);
158 if ($r===false) return;
162 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
163 header ("Content-Type: text/xml");
164 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
167 header ("Content-Type: application/json");
169 return json_encode($rr);
172 header ("Content-Type: application/rss+xml");
173 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
176 header ("Content-Type: application/atom+xml");
177 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
180 //header ("Content-Type: application/json");
182 // return json_encode($rr);
183 return json_encode($r);
187 //echo "<pre>"; var_dump($r); die();
190 header("HTTP/1.1 404 Not Found");
191 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
192 return(api_error($a, $type, "not implemented"));
196 function api_error(&$a, $type, $error) {
197 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
200 header ("Content-Type: text/xml");
201 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
204 header ("Content-Type: application/json");
205 return json_encode(array('error' => $error, 'request' => $a->query_string));
208 header ("Content-Type: application/rss+xml");
209 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
212 header ("Content-Type: application/atom+xml");
213 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
221 function api_rss_extra(&$a, $arr, $user_info){
222 if (is_null($user_info)) $user_info = api_get_user($a);
223 $arr['$user'] = $user_info;
224 $arr['$rss'] = array(
225 'alternate' => $user_info['url'],
226 'self' => $a->get_baseurl(). "/". $a->query_string,
227 'base' => $a->get_baseurl(),
228 'updated' => api_date(null),
229 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
230 'language' => $user_info['language'],
231 'logo' => $a->get_baseurl()."/images/friendica-32.png",
239 * Unique contact to contact url.
241 function api_unique_id_to_url($id){
242 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
245 return ($r[0]["url"]);
251 * Returns user info array.
253 function api_get_user(&$a, $contact_id = Null, $type = "json"){
260 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
262 // Searching for contact URL
263 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
264 $user = dbesc(normalise_link($contact_id));
266 $extra_query = "AND `contact`.`nurl` = '%s' ";
267 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
270 // Searching for unique contact id
271 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
272 $user = dbesc(api_unique_id_to_url($contact_id));
275 die(api_error($a, $type, t("User not found.")));
278 $extra_query = "AND `contact`.`nurl` = '%s' ";
279 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
282 if(is_null($user) && x($_GET, 'user_id')) {
283 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
286 die(api_error($a, $type, t("User not found.")));
289 $extra_query = "AND `contact`.`nurl` = '%s' ";
290 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
292 if(is_null($user) && x($_GET, 'screen_name')) {
293 $user = dbesc($_GET['screen_name']);
295 $extra_query = "AND `contact`.`nick` = '%s' ";
296 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
299 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
300 $argid = count($called_api);
301 list($user, $null) = explode(".",$a->argv[$argid]);
302 if(is_numeric($user)){
303 $user = dbesc(api_unique_id_to_url($user));
309 $extra_query = "AND `contact`.`nurl` = '%s' ";
310 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
312 $user = dbesc($user);
314 $extra_query = "AND `contact`.`nick` = '%s' ";
315 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
319 logger("api_get_user: user ".$user, LOGGER_DEBUG);
322 if (api_user()===false) {
323 api_login($a); return False;
325 $user = $_SESSION['uid'];
326 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
331 logger('api_user: ' . $extra_query . ', user: ' . $user);
333 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
339 // Selecting the id by priority, friendica first
340 api_best_nickname($uinfo);
342 // if the contact wasn't found, fetch it from the unique contacts
343 if (count($uinfo)==0) {
347 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
349 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
352 // If no nick where given, extract it from the address
353 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
354 $r[0]['nick'] = api_get_nick($r[0]["url"]);
358 'id_str' => (string) $r[0]["id"],
359 'name' => $r[0]["name"],
360 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
362 'description' => NULL,
363 'profile_image_url' => $r[0]["avatar"],
364 'profile_image_url_https' => $r[0]["avatar"],
365 'url' => $r[0]["url"],
366 'protected' => false,
367 'followers_count' => 0,
368 'friends_count' => 0,
369 'created_at' => api_date(0),
370 'favourites_count' => 0,
372 'time_zone' => 'UTC',
373 'statuses_count' => 0,
374 'following' => false,
376 'statusnet_blocking' => false,
377 'notifications' => false,
378 'statusnet_profile_url' => $r[0]["url"],
387 die(api_error($a, $type, t("User not found.")));
391 if($uinfo[0]['self']) {
392 $usr = q("select * from user where uid = %d limit 1",
395 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
399 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
400 // count public wall messages
401 $r = q("SELECT count(*) as `count` FROM `item`
404 intval($uinfo[0]['uid'])
406 $countitms = $r[0]['count'];
409 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
410 $r = q("SELECT count(*) as `count` FROM `item`
411 WHERE `contact-id` = %d",
412 intval($uinfo[0]['id'])
414 $countitms = $r[0]['count'];
418 $r = q("SELECT count(*) as `count` FROM `contact`
419 WHERE `uid` = %d AND `rel` IN ( %d, %d )
420 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
421 intval($uinfo[0]['uid']),
422 intval(CONTACT_IS_SHARING),
423 intval(CONTACT_IS_FRIEND)
425 $countfriends = $r[0]['count'];
427 $r = q("SELECT count(*) as `count` FROM `contact`
428 WHERE `uid` = %d AND `rel` IN ( %d, %d )
429 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
430 intval($uinfo[0]['uid']),
431 intval(CONTACT_IS_FOLLOWER),
432 intval(CONTACT_IS_FRIEND)
434 $countfollowers = $r[0]['count'];
436 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
437 intval($uinfo[0]['uid'])
439 $starred = $r[0]['count'];
442 if(! $uinfo[0]['self']) {
448 // Add a nick if it isn't present there
449 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
450 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
453 // Fetching unique id
454 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
456 // If not there, then add it
457 if (count($r) == 0) {
458 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
459 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
461 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
464 require_once('include/contact_selectors.php');
465 $network_name = network_to_name($uinfo[0]['network']);
468 'id' => intval($r[0]['id']),
469 'id_str' => (string) intval($r[0]['id']),
470 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
471 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
472 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
473 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
474 'profile_image_url' => $uinfo[0]['micro'],
475 'profile_image_url_https' => $uinfo[0]['micro'],
476 'url' => $uinfo[0]['url'],
477 'protected' => false,
478 'followers_count' => intval($countfollowers),
479 'friends_count' => intval($countfriends),
480 'created_at' => api_date($uinfo[0]['created']),
481 'favourites_count' => intval($starred),
483 'time_zone' => 'UTC',
484 'statuses_count' => intval($countitms),
485 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
487 'statusnet_blocking' => false,
488 'notifications' => false,
489 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
490 'uid' => intval($uinfo[0]['uid']),
491 'cid' => intval($uinfo[0]['cid']),
492 'self' => $uinfo[0]['self'],
493 'network' => $uinfo[0]['network'],
500 function api_item_get_user(&$a, $item) {
502 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
503 dbesc(normalise_link($item['author-link'])));
505 if (count($author) == 0) {
506 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
507 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
509 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
510 dbesc(normalise_link($item['author-link'])));
511 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
512 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
513 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
516 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
517 dbesc(normalise_link($item['owner-link'])));
519 if (count($owner) == 0) {
520 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
521 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
523 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
524 dbesc(normalise_link($item['owner-link'])));
525 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
526 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
527 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
530 // Comments in threads may appear as wall-to-wall postings.
531 // So only take the owner at the top posting.
532 if ($item["id"] == $item["parent"])
533 $status_user = api_get_user($a,$item["owner-link"]);
535 $status_user = api_get_user($a,$item["author-link"]);
537 $status_user["protected"] = (($item["allow_cid"] != "") OR
538 ($item["allow_gid"] != "") OR
539 ($item["deny_cid"] != "") OR
540 ($item["deny_gid"] != "") OR
543 return ($status_user);
548 * load api $templatename for $type and replace $data array
550 function api_apply_template($templatename, $type, $data){
558 $data = array_xmlify($data);
559 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
561 header ("Content-Type: text/xml");
562 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
565 $ret = replace_macros($tpl, $data);
580 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
581 * returns a 401 status code and an error message if not.
582 * http://developer.twitter.com/doc/get/account/verify_credentials
584 function api_account_verify_credentials(&$a, $type){
585 if (api_user()===false) return false;
587 unset($_REQUEST["user_id"]);
588 unset($_GET["user_id"]);
590 unset($_REQUEST["screen_name"]);
591 unset($_GET["screen_name"]);
593 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
595 $user_info = api_get_user($a);
597 // "verified" isn't used here in the standard
598 unset($user_info["verified"]);
600 // - Adding last status
602 $user_info["status"] = api_status_show($a,"raw");
603 if (!count($user_info["status"]))
604 unset($user_info["status"]);
606 unset($user_info["status"]["user"]);
609 // "uid" and "self" are only needed for some internal stuff, so remove it from here
610 unset($user_info["uid"]);
611 unset($user_info["self"]);
613 return api_apply_template("user", $type, array('$user' => $user_info));
616 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
620 * get data from $_POST or $_GET
622 function requestdata($k){
623 if (isset($_POST[$k])){
626 if (isset($_GET[$k])){
632 /*Waitman Gobble Mod*/
633 function api_statuses_mediap(&$a, $type) {
634 if (api_user()===false) {
635 logger('api_statuses_update: no user');
638 $user_info = api_get_user($a);
640 $_REQUEST['type'] = 'wall';
641 $_REQUEST['profile_uid'] = api_user();
642 $_REQUEST['api_source'] = true;
643 $txt = requestdata('status');
644 //$txt = urldecode(requestdata('status'));
646 require_once('library/HTMLPurifier.auto.php');
647 require_once('include/html2bbcode.php');
649 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
650 $txt = html2bb_video($txt);
651 $config = HTMLPurifier_Config::createDefault();
652 $config->set('Cache.DefinitionImpl', null);
653 $purifier = new HTMLPurifier($config);
654 $txt = $purifier->purify($txt);
656 $txt = html2bbcode($txt);
658 $a->argv[1]=$user_info['screen_name']; //should be set to username?
660 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
661 require_once('mod/wall_upload.php');
662 $bebop = wall_upload_post($a);
664 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
665 $_REQUEST['body']=$txt."\n\n".$bebop;
666 require_once('mod/item.php');
669 // this should output the last post (the one we just posted).
670 return api_status_show($a,$type);
672 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
673 /*Waitman Gobble Mod*/
676 function api_statuses_update(&$a, $type) {
677 if (api_user()===false) {
678 logger('api_statuses_update: no user');
681 $user_info = api_get_user($a);
683 // convert $_POST array items to the form we use for web posts.
685 // logger('api_post: ' . print_r($_POST,true));
687 if(requestdata('htmlstatus')) {
688 require_once('library/HTMLPurifier.auto.php');
689 require_once('include/html2bbcode.php');
691 $txt = requestdata('htmlstatus');
692 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
694 $txt = html2bb_video($txt);
696 $config = HTMLPurifier_Config::createDefault();
697 $config->set('Cache.DefinitionImpl', null);
700 $purifier = new HTMLPurifier($config);
701 $txt = $purifier->purify($txt);
703 $_REQUEST['body'] = html2bbcode($txt);
708 $_REQUEST['body'] = requestdata('status');
710 $_REQUEST['title'] = requestdata('title');
712 $parent = requestdata('in_reply_to_status_id');
713 if(ctype_digit($parent))
714 $_REQUEST['parent'] = $parent;
716 $_REQUEST['parent_uri'] = $parent;
718 if(requestdata('lat') && requestdata('long'))
719 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
720 $_REQUEST['profile_uid'] = api_user();
723 $_REQUEST['type'] = 'net-comment';
725 $_REQUEST['type'] = 'wall';
726 if(x($_FILES,'media')) {
727 // upload the image if we have one
728 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
729 require_once('mod/wall_upload.php');
730 $media = wall_upload_post($a);
732 $_REQUEST['body'] .= "\n\n".$media;
736 // set this so that the item_post() function is quiet and doesn't redirect or emit json
738 $_REQUEST['api_source'] = true;
740 if (!x($_REQUEST, "source"))
741 $_REQUEST["source"] = api_source();
743 // call out normal post function
745 require_once('mod/item.php');
748 // this should output the last post (the one we just posted).
749 return api_status_show($a,$type);
751 api_register_func('api/statuses/update','api_statuses_update', true);
752 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
755 function api_status_show(&$a, $type){
756 $user_info = api_get_user($a);
758 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
760 // get last public wall message
761 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
762 FROM `item`, `item` as `i`
763 WHERE `item`.`contact-id` = %d
764 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
765 AND `i`.`id` = `item`.`parent`
766 AND `item`.`type`!='activity'
767 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
768 ORDER BY `item`.`created` DESC
770 intval($user_info['cid']),
771 dbesc($user_info['url']),
772 dbesc(normalise_link($user_info['url'])),
773 dbesc($user_info['url']),
774 dbesc(normalise_link($user_info['url']))
777 if (count($lastwall)>0){
778 $lastwall = $lastwall[0];
780 $in_reply_to_status_id = NULL;
781 $in_reply_to_user_id = NULL;
782 $in_reply_to_status_id_str = NULL;
783 $in_reply_to_user_id_str = NULL;
784 $in_reply_to_screen_name = NULL;
785 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
786 $in_reply_to_status_id= intval($lastwall['parent']);
787 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
789 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
791 if ($r[0]['nick'] == "")
792 $r[0]['nick'] = api_get_nick($r[0]["url"]);
794 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
795 $in_reply_to_user_id = intval($r[0]['id']);
796 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
800 // There seems to be situation, where both fields are identical:
801 // https://github.com/friendica/friendica/issues/1010
802 // This is a bugfix for that.
803 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
804 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
805 $in_reply_to_status_id = NULL;
806 $in_reply_to_user_id = NULL;
807 $in_reply_to_status_id_str = NULL;
808 $in_reply_to_user_id_str = NULL;
809 $in_reply_to_screen_name = NULL;
812 $status_info = array(
813 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
814 'truncated' => false,
815 'created_at' => api_date($lastwall['created']),
816 'in_reply_to_status_id' => $in_reply_to_status_id,
817 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
818 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
819 'id' => intval($lastwall['id']),
820 'id_str' => (string) $lastwall['id'],
821 'in_reply_to_user_id' => $in_reply_to_user_id,
822 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
823 'in_reply_to_screen_name' => $in_reply_to_screen_name,
825 'favorited' => false,
827 'user' => $user_info,
828 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
829 'statusnet_conversation_id' => $lastwall['parent'],
832 if ($lastwall['title'] != "")
833 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
835 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
836 if (count($entities) > 0)
837 $status_info['entities'] = $entities;
839 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
840 $status_info["source"] = network_to_name($lastwall['item_network']);
841 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
842 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
844 // "uid" and "self" are only needed for some internal stuff, so remove it from here
845 unset($status_info["user"]["uid"]);
846 unset($status_info["user"]["self"]);
850 return($status_info);
852 return api_apply_template("status", $type, array('$status' => $status_info));
861 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
862 * The author's most recent status will be returned inline.
863 * http://developer.twitter.com/doc/get/users/show
865 function api_users_show(&$a, $type){
866 $user_info = api_get_user($a);
868 $lastwall = q("SELECT `item`.*
869 FROM `item`, `contact`
870 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
871 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
872 AND `contact`.`id`=`item`.`contact-id`
873 AND `type`!='activity'
874 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
875 ORDER BY `created` DESC
878 dbesc(ACTIVITY_POST),
879 intval($user_info['cid']),
880 dbesc($user_info['url']),
881 dbesc(normalise_link($user_info['url'])),
882 dbesc($user_info['url']),
883 dbesc(normalise_link($user_info['url']))
885 if (count($lastwall)>0){
886 $lastwall = $lastwall[0];
888 $in_reply_to_status_id = NULL;
889 $in_reply_to_user_id = NULL;
890 $in_reply_to_status_id_str = NULL;
891 $in_reply_to_user_id_str = NULL;
892 $in_reply_to_screen_name = NULL;
893 if ($lastwall['parent']!=$lastwall['id']) {
894 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
895 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
896 if (count($reply)>0) {
897 $in_reply_to_status_id = intval($lastwall['parent']);
898 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
900 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
902 if ($r[0]['nick'] == "")
903 $r[0]['nick'] = api_get_nick($r[0]["url"]);
905 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
906 $in_reply_to_user_id = intval($r[0]['id']);
907 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
911 $user_info['status'] = array(
912 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
913 'truncated' => false,
914 'created_at' => api_date($lastwall['created']),
915 'in_reply_to_status_id' => $in_reply_to_status_id,
916 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
917 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
918 'id' => intval($lastwall['contact-id']),
919 'id_str' => (string) $lastwall['contact-id'],
920 'in_reply_to_user_id' => $in_reply_to_user_id,
921 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
922 'in_reply_to_screen_name' => $in_reply_to_screen_name,
924 'favorited' => false,
925 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
926 'statusnet_conversation_id' => $lastwall['parent'],
929 if ($lastwall['title'] != "")
930 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
932 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
933 if (count($entities) > 0)
934 $user_info['entities'] = $entities;
936 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
937 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
938 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
939 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
943 // "uid" and "self" are only needed for some internal stuff, so remove it from here
944 unset($user_info["uid"]);
945 unset($user_info["self"]);
947 return api_apply_template("user", $type, array('$user' => $user_info));
950 api_register_func('api/users/show','api_users_show');
953 function api_users_search(&$a, $type) {
954 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
958 if (isset($_GET["q"])) {
959 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
961 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
964 foreach ($r AS $user) {
965 $user_info = api_get_user($a, $user["id"]);
966 //echo print_r($user_info, true)."\n";
967 $userdata = api_apply_template("user", $type, array('user' => $user_info));
968 $userlist[] = $userdata["user"];
970 $userlist = array("users" => $userlist);
972 die(api_error($a, $type, t("User not found.")));
974 die(api_error($a, $type, t("User not found.")));
979 api_register_func('api/users/search','api_users_search');
983 * http://developer.twitter.com/doc/get/statuses/home_timeline
985 * TODO: Optional parameters
986 * TODO: Add reply info
988 function api_statuses_home_timeline(&$a, $type){
989 if (api_user()===false) return false;
991 unset($_REQUEST["user_id"]);
992 unset($_GET["user_id"]);
994 unset($_REQUEST["screen_name"]);
995 unset($_GET["screen_name"]);
997 $user_info = api_get_user($a);
998 // get last newtork messages
1002 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1003 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1004 if ($page<0) $page=0;
1005 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1006 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1007 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1008 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1009 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1011 $start = $page*$count;
1015 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1016 if ($exclude_replies > 0)
1017 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1018 if ($conversation_id > 0)
1019 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1021 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1022 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1023 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1024 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1025 FROM `item`, `contact`
1026 WHERE `item`.`uid` = %d AND `verb` = '%s'
1027 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1028 AND `contact`.`id` = `item`.`contact-id`
1029 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1032 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1034 dbesc(ACTIVITY_POST),
1036 intval($start), intval($count)
1039 $ret = api_format_items($r,$user_info);
1041 // We aren't going to try to figure out at the item, group, and page
1042 // level which items you've seen and which you haven't. If you're looking
1043 // at the network timeline just mark everything seen.
1045 $r = q("UPDATE `item` SET `unseen` = 0
1046 WHERE `unseen` = 1 AND `uid` = %d",
1047 //intval($user_info['uid'])
1052 $data = array('$statuses' => $ret);
1056 $data = api_rss_extra($a, $data, $user_info);
1059 $as = api_format_as($a, $ret, $user_info);
1060 $as['title'] = $a->config['sitename']." Home Timeline";
1061 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1066 return api_apply_template("timeline", $type, $data);
1068 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1069 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1071 function api_statuses_public_timeline(&$a, $type){
1072 if (api_user()===false) return false;
1074 $user_info = api_get_user($a);
1075 // get last newtork messages
1079 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1080 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1081 if ($page<0) $page=0;
1082 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1083 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1084 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1085 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1086 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1088 $start = $page*$count;
1091 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1092 if ($exclude_replies > 0)
1093 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1094 if ($conversation_id > 0)
1095 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1097 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1098 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1099 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1100 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1101 `user`.`nickname`, `user`.`hidewall`
1102 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1103 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1104 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1105 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1106 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1107 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1108 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1111 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1112 dbesc(ACTIVITY_POST),
1117 $ret = api_format_items($r,$user_info);
1120 $data = array('$statuses' => $ret);
1124 $data = api_rss_extra($a, $data, $user_info);
1127 $as = api_format_as($a, $ret, $user_info);
1128 $as['title'] = $a->config['sitename']." Public Timeline";
1129 $as['link']['url'] = $a->get_baseurl()."/";
1134 return api_apply_template("timeline", $type, $data);
1136 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1141 function api_statuses_show(&$a, $type){
1142 if (api_user()===false) return false;
1144 $user_info = api_get_user($a);
1147 $id = intval($a->argv[3]);
1150 $id = intval($_REQUEST["id"]);
1154 $id = intval($a->argv[4]);
1156 logger('API: api_statuses_show: '.$id);
1158 $conversation = (x($_REQUEST,'conversation')?1:0);
1162 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1164 $sql_extra .= " AND `item`.`id` = %d";
1166 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1167 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1168 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1169 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1170 FROM `item`, `contact`
1171 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1172 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1173 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1176 dbesc(ACTIVITY_POST),
1181 die(api_error($a, $type, t("There is no status with this id.")));
1183 $ret = api_format_items($r,$user_info);
1185 if ($conversation) {
1186 $data = array('$statuses' => $ret);
1187 return api_apply_template("timeline", $type, $data);
1189 $data = array('$status' => $ret[0]);
1193 $data = api_rss_extra($a, $data, $user_info);
1195 return api_apply_template("status", $type, $data);
1198 api_register_func('api/statuses/show','api_statuses_show', true);
1204 function api_conversation_show(&$a, $type){
1205 if (api_user()===false) return false;
1207 $user_info = api_get_user($a);
1210 $id = intval($a->argv[3]);
1211 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1212 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1213 if ($page<0) $page=0;
1214 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1215 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1217 $start = $page*$count;
1220 $id = intval($_REQUEST["id"]);
1224 $id = intval($a->argv[4]);
1226 logger('API: api_conversation_show: '.$id);
1231 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1233 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1234 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1235 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1236 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1237 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1238 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1239 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1240 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1241 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1242 AND `item`.`id`>%d $sql_extra
1243 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1244 intval($id), intval(api_user()),
1245 dbesc(ACTIVITY_POST),
1247 intval($start), intval($count)
1251 die(api_error($a, $type, t("There is no conversation with this id.")));
1253 $ret = api_format_items($r,$user_info);
1255 $data = array('$statuses' => $ret);
1256 return api_apply_template("timeline", $type, $data);
1258 api_register_func('api/conversation/show','api_conversation_show', true);
1264 function api_statuses_repeat(&$a, $type){
1267 if (api_user()===false) return false;
1269 $user_info = api_get_user($a);
1272 $id = intval($a->argv[3]);
1275 $id = intval($_REQUEST["id"]);
1279 $id = intval($a->argv[4]);
1281 logger('API: api_statuses_repeat: '.$id);
1283 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1284 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1285 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1286 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1287 FROM `item`, `contact`
1288 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1289 AND `contact`.`id` = `item`.`contact-id`
1290 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1292 AND `item`.`id`=%d",
1296 if ($r[0]['body'] != "") {
1297 if (!intval(get_config('system','old_share'))) {
1298 if (strpos($r[0]['body'], "[/share]") !== false) {
1299 $pos = strpos($r[0]['body'], "[share");
1300 $post = substr($r[0]['body'], $pos);
1302 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1303 "' profile='".$r[0]['author-link'].
1304 "' avatar='".$r[0]['author-avatar'].
1305 "' link='".$r[0]['plink']."']";
1306 $post .= $r[0]['body'];
1307 $post .= "[/share]";
1309 $_REQUEST['body'] = $post;
1311 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1313 $_REQUEST['profile_uid'] = api_user();
1314 $_REQUEST['type'] = 'wall';
1315 $_REQUEST['api_source'] = true;
1317 if (!x($_REQUEST, "source"))
1318 $_REQUEST["source"] = api_source();
1320 require_once('mod/item.php');
1324 // this should output the last post (the one we just posted).
1326 return(api_status_show($a,$type));
1328 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1333 function api_statuses_destroy(&$a, $type){
1334 if (api_user()===false) return false;
1336 $user_info = api_get_user($a);
1339 $id = intval($a->argv[3]);
1342 $id = intval($_REQUEST["id"]);
1346 $id = intval($a->argv[4]);
1348 logger('API: api_statuses_destroy: '.$id);
1350 $ret = api_statuses_show($a, $type);
1352 require_once('include/items.php');
1353 drop_item($id, false);
1357 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1361 * http://developer.twitter.com/doc/get/statuses/mentions
1364 function api_statuses_mentions(&$a, $type){
1365 if (api_user()===false) return false;
1367 unset($_REQUEST["user_id"]);
1368 unset($_GET["user_id"]);
1370 unset($_REQUEST["screen_name"]);
1371 unset($_GET["screen_name"]);
1373 $user_info = api_get_user($a);
1374 // get last newtork messages
1378 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1379 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1380 if ($page<0) $page=0;
1381 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1382 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1383 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1385 $start = $page*$count;
1387 // Ugly code - should be changed
1388 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1389 $myurl = substr($myurl,strpos($myurl,'://')+3);
1390 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1391 $myurl = str_replace('www.','',$myurl);
1392 $diasp_url = str_replace('/profile/','/u/',$myurl);
1395 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1397 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1398 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1399 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1400 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1401 FROM `item`, `contact`
1402 WHERE `item`.`uid` = %d AND `verb` = '%s'
1403 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1404 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1405 AND `contact`.`id` = `item`.`contact-id`
1406 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1407 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention`)
1410 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1412 dbesc(ACTIVITY_POST),
1413 dbesc(protect_sprintf($myurl)),
1414 dbesc(protect_sprintf($myurl)),
1417 intval($start), intval($count)
1420 $ret = api_format_items($r,$user_info);
1423 $data = array('$statuses' => $ret);
1427 $data = api_rss_extra($a, $data, $user_info);
1430 $as = api_format_as($a, $ret, $user_info);
1431 $as["title"] = $a->config['sitename']." Mentions";
1432 $as['link']['url'] = $a->get_baseurl()."/";
1437 return api_apply_template("timeline", $type, $data);
1439 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1440 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1443 function api_statuses_user_timeline(&$a, $type){
1444 if (api_user()===false) return false;
1446 $user_info = api_get_user($a);
1447 // get last network messages
1449 logger("api_statuses_user_timeline: api_user: ". api_user() .
1450 "\nuser_info: ".print_r($user_info, true) .
1451 "\n_REQUEST: ".print_r($_REQUEST, true),
1455 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1456 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1457 if ($page<0) $page=0;
1458 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1459 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1460 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1461 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1463 $start = $page*$count;
1466 if ($user_info['self']==1)
1467 $sql_extra .= " AND `item`.`wall` = 1 ";
1469 if ($exclude_replies > 0)
1470 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1471 if ($conversation_id > 0)
1472 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1474 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1475 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1476 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1477 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1478 FROM `item`, `contact`
1479 WHERE `item`.`uid` = %d AND `verb` = '%s'
1480 AND `item`.`contact-id` = %d
1481 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1482 AND `contact`.`id` = `item`.`contact-id`
1483 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1486 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1488 dbesc(ACTIVITY_POST),
1489 intval($user_info['cid']),
1491 intval($start), intval($count)
1494 $ret = api_format_items($r,$user_info, true);
1496 $data = array('$statuses' => $ret);
1500 $data = api_rss_extra($a, $data, $user_info);
1503 return api_apply_template("timeline", $type, $data);
1506 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1509 function api_favorites(&$a, $type){
1512 if (api_user()===false) return false;
1514 $called_api= array();
1516 $user_info = api_get_user($a);
1518 // in friendica starred item are private
1519 // return favorites only for self
1520 logger('api_favorites: self:' . $user_info['self']);
1522 if ($user_info['self']==0) {
1528 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1529 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1530 $count = (x($_GET,'count')?$_GET['count']:20);
1531 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1532 if ($page<0) $page=0;
1534 $start = $page*$count;
1537 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1539 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1540 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1541 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1542 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1543 FROM `item`, `contact`
1544 WHERE `item`.`uid` = %d AND `verb` = '%s'
1545 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1546 AND `item`.`starred` = 1
1547 AND `contact`.`id` = `item`.`contact-id`
1548 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1551 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1553 dbesc(ACTIVITY_POST),
1555 intval($start), intval($count)
1558 $ret = api_format_items($r,$user_info);
1562 $data = array('$statuses' => $ret);
1566 $data = api_rss_extra($a, $data, $user_info);
1569 return api_apply_template("timeline", $type, $data);
1572 api_register_func('api/favorites','api_favorites', true);
1574 function api_format_as($a, $ret, $user_info) {
1577 $as['title'] = $a->config['sitename']." Public Timeline";
1579 foreach ($ret as $item) {
1580 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1581 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1582 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1583 $avatar[0]["rel"] = "avatar";
1584 $avatar[0]["type"] = "";
1585 $avatar[0]["width"] = 96;
1586 $avatar[0]["height"] = 96;
1587 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1588 $avatar[1]["rel"] = "avatar";
1589 $avatar[1]["type"] = "";
1590 $avatar[1]["width"] = 48;
1591 $avatar[1]["height"] = 48;
1592 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1593 $avatar[2]["rel"] = "avatar";
1594 $avatar[2]["type"] = "";
1595 $avatar[2]["width"] = 24;
1596 $avatar[2]["height"] = 24;
1597 $singleitem["actor"]["avatarLinks"] = $avatar;
1599 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1600 $singleitem["actor"]["image"]["rel"] = "avatar";
1601 $singleitem["actor"]["image"]["type"] = "";
1602 $singleitem["actor"]["image"]["width"] = 96;
1603 $singleitem["actor"]["image"]["height"] = 96;
1604 $singleitem["actor"]["type"] = "person";
1605 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1606 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1607 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1608 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1609 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1610 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1611 $singleitem["actor"]["contact"]["addresses"] = "";
1613 $singleitem["body"] = $item["text"];
1614 $singleitem["object"]["displayName"] = $item["text"];
1615 $singleitem["object"]["id"] = $item["url"];
1616 $singleitem["object"]["type"] = "note";
1617 $singleitem["object"]["url"] = $item["url"];
1618 //$singleitem["context"] =;
1619 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1620 $singleitem["provider"]["objectType"] = "service";
1621 $singleitem["provider"]["displayName"] = "Test";
1622 $singleitem["provider"]["url"] = "http://test.tld";
1623 $singleitem["title"] = $item["text"];
1624 $singleitem["verb"] = "post";
1625 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1626 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1627 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1628 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1629 //$singleitem["original"] = $item;
1630 $items[] = $singleitem;
1632 $as['items'] = $items;
1633 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1634 $as['link']['rel'] = "alternate";
1635 $as['link']['type'] = "text/html";
1639 function api_format_messages($item, $recipient, $sender) {
1640 // standard meta information
1642 'id' => $item['id'],
1643 'sender_id' => $sender['id'] ,
1645 'recipient_id' => $recipient['id'],
1646 'created_at' => api_date($item['created']),
1647 'sender_screen_name' => $sender['screen_name'],
1648 'recipient_screen_name' => $recipient['screen_name'],
1649 'sender' => $sender,
1650 'recipient' => $recipient,
1653 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1654 unset($ret["sender"]["uid"]);
1655 unset($ret["sender"]["self"]);
1656 unset($ret["recipient"]["uid"]);
1657 unset($ret["recipient"]["self"]);
1659 //don't send title to regular StatusNET requests to avoid confusing these apps
1660 if (x($_GET, 'getText')) {
1661 $ret['title'] = $item['title'] ;
1662 if ($_GET["getText"] == "html") {
1663 $ret['text'] = bbcode($item['body'], false, false);
1665 elseif ($_GET["getText"] == "plain") {
1666 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1667 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1671 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1673 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1674 unset($ret['sender']);
1675 unset($ret['recipient']);
1681 function api_get_entitities(&$text, $bbcode) {
1684 * Links at the first character of the post
1689 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1691 if ($include_entities != "true") {
1692 require_once("mod/proxy.php");
1694 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1696 foreach ($images[1] AS $image) {
1697 $replace = proxy_url($image);
1698 $text = str_replace($image, $replace, $text);
1703 $bbcode = bb_CleanPictureLinks($bbcode);
1705 // Change pure links in text to bbcode uris
1706 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1708 $entities = array();
1709 $entities["hashtags"] = array();
1710 $entities["symbols"] = array();
1711 $entities["urls"] = array();
1712 $entities["user_mentions"] = array();
1714 $URLSearchString = "^\[\]";
1716 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1718 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1719 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1720 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1722 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1723 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1724 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1726 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1727 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1728 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1730 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1732 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1733 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1735 $ordered_urls = array();
1736 foreach ($urls[1] AS $id=>$url) {
1737 //$start = strpos($text, $url, $offset);
1738 $start = iconv_strpos($text, $url, 0, "UTF-8");
1739 if (!($start === false))
1740 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1743 ksort($ordered_urls);
1746 //foreach ($urls[1] AS $id=>$url) {
1747 foreach ($ordered_urls AS $url) {
1748 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1749 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1750 $display_url = $url["title"];
1752 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1753 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1755 if (strlen($display_url) > 26)
1756 $display_url = substr($display_url, 0, 25)."…";
1759 //$start = strpos($text, $url, $offset);
1760 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1761 if (!($start === false)) {
1762 $entities["urls"][] = array("url" => $url["url"],
1763 "expanded_url" => $url["url"],
1764 "display_url" => $display_url,
1765 "indices" => array($start, $start+strlen($url["url"])));
1766 $offset = $start + 1;
1770 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1771 $ordered_images = array();
1772 foreach ($images[1] AS $image) {
1773 //$start = strpos($text, $url, $offset);
1774 $start = iconv_strpos($text, $image, 0, "UTF-8");
1775 if (!($start === false))
1776 $ordered_images[$start] = $image;
1778 //$entities["media"] = array();
1781 foreach ($ordered_images AS $url) {
1782 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1783 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1785 if (strlen($display_url) > 26)
1786 $display_url = substr($display_url, 0, 25)."…";
1788 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1789 if (!($start === false)) {
1790 require_once("include/Photo.php");
1791 $image = get_photo_info($url);
1793 // If image cache is activated, then use the following sizes:
1794 // thumb (150), small (340), medium (600) and large (1024)
1795 if (!get_config("system", "proxy_disabled")) {
1796 require_once("mod/proxy.php");
1797 $media_url = proxy_url($url);
1800 $scale = scale_image($image[0], $image[1], 150);
1801 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1803 if (($image[0] > 150) OR ($image[1] > 150)) {
1804 $scale = scale_image($image[0], $image[1], 340);
1805 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1808 $scale = scale_image($image[0], $image[1], 600);
1809 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1811 if (($image[0] > 600) OR ($image[1] > 600)) {
1812 $scale = scale_image($image[0], $image[1], 1024);
1813 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1817 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1820 $entities["media"][] = array(
1822 "id_str" => (string)$start+1,
1823 "indices" => array($start, $start+strlen($url)),
1824 "media_url" => normalise_link($media_url),
1825 "media_url_https" => $media_url,
1827 "display_url" => $display_url,
1828 "expanded_url" => $url,
1832 $offset = $start + 1;
1839 function api_format_items($r,$user_info, $filter_user = false) {
1844 foreach($r as $item) {
1845 api_share_as_retweet($a, api_user(), $item);
1847 localize_item($item);
1848 $status_user = api_item_get_user($a,$item);
1850 // Look if the posts are matching if they should be filtered by user id
1851 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1854 if ($item['thr-parent'] != $item['uri']) {
1855 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1857 dbesc($item['thr-parent']));
1859 $in_reply_to_status_id = intval($r[0]['id']);
1861 $in_reply_to_status_id = intval($item['parent']);
1863 $in_reply_to_status_id_str = (string) intval($item['parent']);
1865 $in_reply_to_screen_name = NULL;
1866 $in_reply_to_user_id = NULL;
1867 $in_reply_to_user_id_str = NULL;
1869 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1871 intval($in_reply_to_status_id));
1873 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1876 if ($r[0]['nick'] == "")
1877 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1879 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1880 $in_reply_to_user_id = intval($r[0]['id']);
1881 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1885 $in_reply_to_screen_name = NULL;
1886 $in_reply_to_user_id = NULL;
1887 $in_reply_to_status_id = NULL;
1888 $in_reply_to_user_id_str = NULL;
1889 $in_reply_to_status_id_str = NULL;
1892 // Workaround for ostatus messages where the title is identically to the body
1893 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1894 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1895 $statusbody = trim(html2plain($html, 0));
1897 $statustitle = trim($item['title']);
1899 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1900 $statustext = trim($statusbody);
1902 $statustext = trim($statustitle."\n\n".$statusbody);
1904 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1905 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1908 'text' => $statustext,
1909 'truncated' => False,
1910 'created_at'=> api_date($item['created']),
1911 'in_reply_to_status_id' => $in_reply_to_status_id,
1912 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1913 'source' => (($item['app']) ? $item['app'] : 'web'),
1914 'id' => intval($item['id']),
1915 'id_str' => (string) intval($item['id']),
1916 'in_reply_to_user_id' => $in_reply_to_user_id,
1917 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1918 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1920 'favorited' => $item['starred'] ? true : false,
1921 //'attachments' => array(),
1922 'user' => $status_user ,
1923 //'entities' => NULL,
1924 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1925 'statusnet_conversation_id' => $item['parent'],
1928 if ($item['title'] != "")
1929 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
1931 $entities = api_get_entitities($status['text'], $item['body']);
1932 if (count($entities) > 0)
1933 $status['entities'] = $entities;
1935 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1936 $status["source"] = network_to_name($item['item_network']);
1937 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1938 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1941 // Retweets are only valid for top postings
1942 // It doesn't work reliable with the link if its a feed
1943 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1945 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1947 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1948 $retweeted_status = $status;
1949 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1951 $status["retweeted_status"] = $retweeted_status;
1954 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1955 unset($status["user"]["uid"]);
1956 unset($status["user"]["self"]);
1958 // 'geo' => array('type' => 'Point',
1959 // 'coordinates' => array((float) $notice->lat,
1960 // (float) $notice->lon));
1968 function api_account_rate_limit_status(&$a,$type) {
1971 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1972 'remaining_hits' => (string) 150,
1973 'hourly_limit' => (string) 150,
1974 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1977 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1979 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1982 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1984 function api_help_test(&$a,$type) {
1991 return api_apply_template('test', $type, array("$ok" => $ok));
1994 api_register_func('api/help/test','api_help_test',false);
1996 function api_lists(&$a,$type) {
2001 api_register_func('api/lists','api_lists',true);
2003 function api_lists_list(&$a,$type) {
2008 api_register_func('api/lists/list','api_lists_list',true);
2011 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2012 * This function is deprecated by Twitter
2013 * returns: json, xml
2015 function api_statuses_f(&$a, $type, $qtype) {
2016 if (api_user()===false) return false;
2017 $user_info = api_get_user($a);
2019 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2020 /* this is to stop Hotot to load friends multiple times
2021 * I'm not sure if I'm missing return something or
2022 * is a bug in hotot. Workaround, meantime
2026 return array('$users' => $ret);*/
2030 if($qtype == 'friends')
2031 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2032 if($qtype == 'followers')
2033 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2035 // friends and followers only for self
2036 if ($user_info['self'] == 0)
2037 $sql_extra = " AND false ";
2039 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2044 foreach($r as $cid){
2045 $user = api_get_user($a, $cid['nurl']);
2046 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2047 unset($user["uid"]);
2048 unset($user["self"]);
2054 return array('$users' => $ret);
2057 function api_statuses_friends(&$a, $type){
2058 $data = api_statuses_f($a,$type,"friends");
2059 if ($data===false) return false;
2060 return api_apply_template("friends", $type, $data);
2062 function api_statuses_followers(&$a, $type){
2063 $data = api_statuses_f($a,$type,"followers");
2064 if ($data===false) return false;
2065 return api_apply_template("friends", $type, $data);
2067 api_register_func('api/statuses/friends','api_statuses_friends',true);
2068 api_register_func('api/statuses/followers','api_statuses_followers',true);
2075 function api_statusnet_config(&$a,$type) {
2076 $name = $a->config['sitename'];
2077 $server = $a->get_hostname();
2078 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2079 $email = $a->config['admin_email'];
2080 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2081 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2082 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2083 if($a->config['api_import_size'])
2084 $texlimit = string($a->config['api_import_size']);
2085 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2086 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2089 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2090 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2091 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2092 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2093 'shorturllength' => '30',
2094 'friendica' => array(
2095 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2096 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2097 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2098 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2103 return api_apply_template('config', $type, array('$config' => $config));
2106 api_register_func('api/statusnet/config','api_statusnet_config',false);
2108 function api_statusnet_version(&$a,$type) {
2112 if($type === 'xml') {
2113 header("Content-type: application/xml");
2114 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2117 elseif($type === 'json') {
2118 header("Content-type: application/json");
2123 api_register_func('api/statusnet/version','api_statusnet_version',false);
2126 function api_ff_ids(&$a,$type,$qtype) {
2130 $user_info = api_get_user($a);
2132 if($qtype == 'friends')
2133 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2134 if($qtype == 'followers')
2135 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2137 if (!$user_info["self"])
2138 $sql_extra = " AND false ";
2140 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2142 $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",
2148 if($type === 'xml') {
2149 header("Content-type: application/xml");
2150 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2152 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2153 echo '</ids>' . "\r\n";
2156 elseif($type === 'json') {
2158 header("Content-type: application/json");
2163 $ret[] = intval($rr['id']);
2165 echo json_encode($ret);
2171 function api_friends_ids(&$a,$type) {
2172 api_ff_ids($a,$type,'friends');
2174 function api_followers_ids(&$a,$type) {
2175 api_ff_ids($a,$type,'followers');
2177 api_register_func('api/friends/ids','api_friends_ids',true);
2178 api_register_func('api/followers/ids','api_followers_ids',true);
2181 function api_direct_messages_new(&$a, $type) {
2182 if (api_user()===false) return false;
2184 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2186 $sender = api_get_user($a);
2188 require_once("include/message.php");
2190 if ($_POST['screen_name']) {
2191 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2193 dbesc($_POST['screen_name']));
2195 // Selecting the id by priority, friendica first
2196 api_best_nickname($r);
2198 $recipient = api_get_user($a, $r[0]['nurl']);
2200 $recipient = api_get_user($a, $_POST['user_id']);
2204 if (x($_REQUEST,'replyto')) {
2205 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2207 intval($_REQUEST['replyto']));
2208 $replyto = $r[0]['parent-uri'];
2209 $sub = $r[0]['title'];
2212 if (x($_REQUEST,'title')) {
2213 $sub = $_REQUEST['title'];
2216 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2220 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2223 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2224 $ret = api_format_messages($r[0], $recipient, $sender);
2227 $ret = array("error"=>$id);
2230 $data = Array('$messages'=>$ret);
2235 $data = api_rss_extra($a, $data, $user_info);
2238 return api_apply_template("direct_messages", $type, $data);
2241 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2243 function api_direct_messages_box(&$a, $type, $box) {
2244 if (api_user()===false) return false;
2246 unset($_REQUEST["user_id"]);
2247 unset($_GET["user_id"]);
2249 unset($_REQUEST["screen_name"]);
2250 unset($_GET["screen_name"]);
2252 $user_info = api_get_user($a);
2255 $count = (x($_GET,'count')?$_GET['count']:20);
2256 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2257 if ($page<0) $page=0;
2259 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2260 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2262 $start = $page*$count;
2264 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2265 $profile_url = $user_info["url"];
2267 if ($box=="sentbox") {
2268 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2270 elseif ($box=="conversation") {
2271 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2273 elseif ($box=="all") {
2274 $sql_extra = "true";
2276 elseif ($box=="inbox") {
2277 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2281 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2283 $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",
2286 intval($start), intval($count)
2290 foreach($r as $item) {
2291 if ($box == "inbox" || $item['from-url'] != $profile_url){
2292 $recipient = $user_info;
2293 $sender = api_get_user($a,normalise_link($item['contact-url']));
2295 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2296 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2297 $sender = $user_info;
2301 $ret[]=api_format_messages($item, $recipient, $sender);
2305 $data = array('$messages' => $ret);
2309 $data = api_rss_extra($a, $data, $user_info);
2312 return api_apply_template("direct_messages", $type, $data);
2316 function api_direct_messages_sentbox(&$a, $type){
2317 return api_direct_messages_box($a, $type, "sentbox");
2319 function api_direct_messages_inbox(&$a, $type){
2320 return api_direct_messages_box($a, $type, "inbox");
2322 function api_direct_messages_all(&$a, $type){
2323 return api_direct_messages_box($a, $type, "all");
2325 function api_direct_messages_conversation(&$a, $type){
2326 return api_direct_messages_box($a, $type, "conversation");
2328 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2329 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2330 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2331 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2335 function api_oauth_request_token(&$a, $type){
2337 $oauth = new FKOAuth1();
2338 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2339 }catch(Exception $e){
2340 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2345 function api_oauth_access_token(&$a, $type){
2347 $oauth = new FKOAuth1();
2348 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2349 }catch(Exception $e){
2350 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2356 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2357 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2360 function api_fr_photos_list(&$a,$type) {
2361 if (api_user()===false) return false;
2362 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2363 intval(local_user())
2368 $ret[] = $rr['resource-id'];
2369 header("Content-type: application/json");
2370 echo json_encode($ret);
2375 function api_fr_photo_detail(&$a,$type) {
2376 if (api_user()===false) return false;
2377 if(! $_REQUEST['photo_id']) return false;
2378 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2379 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2380 intval(local_user()),
2381 dbesc($_REQUEST['photo_id']),
2385 header("Content-type: application/json");
2386 $r[0]['data'] = base64_encode($r[0]['data']);
2387 echo json_encode($r[0]);
2393 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2394 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2401 function api_share_as_retweet($a, $uid, &$item) {
2402 $body = trim($item["body"]);
2404 // Skip if it isn't a pure repeated messages
2405 // Does it start with a share?
2406 if (strpos($body, "[share") > 0)
2409 // Does it end with a share?
2410 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2413 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2414 // Skip if there is no shared message in there
2415 if ($body == $attributes)
2419 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2420 if ($matches[1] != "")
2421 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2423 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2424 if ($matches[1] != "")
2425 $author = $matches[1];
2428 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2429 if ($matches[1] != "")
2430 $profile = $matches[1];
2432 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2433 if ($matches[1] != "")
2434 $profile = $matches[1];
2437 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2438 if ($matches[1] != "")
2439 $avatar = $matches[1];
2441 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2442 if ($matches[1] != "")
2443 $avatar = $matches[1];
2445 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2447 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2450 $item["body"] = $shared_body;
2451 $item["author-name"] = $author;
2452 $item["author-link"] = $profile;
2453 $item["author-avatar"] = $avatar;
2459 function api_get_nick($profile) {
2461 - remove trailing jung from profile url
2462 - pump.io check has to check the website
2467 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2468 if ($friendica != $profile)
2472 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2473 if ($diaspora != $profile)
2478 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2479 if ($twitter != $profile)
2485 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2486 if ($StatusnetHost != $profile) {
2487 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2488 if ($StatusnetUser != $profile) {
2489 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2490 $user = json_decode($UserData);
2492 $nick = $user->screen_name;
2497 // To-Do: look at the page if its really a pumpio site
2498 //if (!$nick == "") {
2499 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2500 // if ($pumpio != $profile)
2502 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2507 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2508 dbesc($nick), dbesc(normalise_link($profile)));
2515 function api_clean_plain_items($Text) {
2516 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2518 $Text = bb_CleanPictureLinks($Text);
2520 $URLSearchString = "^\[\]";
2522 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2524 if ($include_entities == "true") {
2525 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2528 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2532 function api_cleanup_share($shared) {
2533 if ($shared[2] != "type-link")
2536 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2542 if (isset($bookmark[2][0]))
2543 $title = $bookmark[2][0];
2545 if (isset($bookmark[1][0]))
2546 $link = $bookmark[1][0];
2548 if (strpos($shared[1],$title) !== false)
2551 if (strpos($shared[1],$link) !== false)
2554 $text = trim($shared[1]);
2556 //if (strlen($text) < strlen($title))
2557 if (($text == "") AND ($title != ""))
2558 $text .= "\n\n".trim($title);
2561 $text .= "\n".trim($link);
2563 return(trim($text));
2566 function api_best_nickname(&$contacts) {
2567 $best_contact = array();
2569 if (count($contact) == 0)
2572 foreach ($contacts AS $contact)
2573 if ($contact["network"] == "") {
2574 $contact["network"] = "dfrn";
2575 $best_contact = array($contact);
2578 if (sizeof($best_contact) == 0)
2579 foreach ($contacts AS $contact)
2580 if ($contact["network"] == "dfrn")
2581 $best_contact = array($contact);
2583 if (sizeof($best_contact) == 0)
2584 foreach ($contacts AS $contact)
2585 if ($contact["network"] == "dspr")
2586 $best_contact = array($contact);
2588 if (sizeof($best_contact) == 0)
2589 foreach ($contacts AS $contact)
2590 if ($contact["network"] == "stat")
2591 $best_contact = array($contact);
2593 if (sizeof($best_contact) == 0)
2594 foreach ($contacts AS $contact)
2595 if ($contact["network"] == "pump")
2596 $best_contact = array($contact);
2598 if (sizeof($best_contact) == 0)
2599 foreach ($contacts AS $contact)
2600 if ($contact["network"] == "twit")
2601 $best_contact = array($contact);
2603 if (sizeof($best_contact) == 1)
2604 $contacts = $best_contact;
2606 $contacts = array($contacts[0]);
2610 Not implemented by now:
2614 statuses/retweets_of_me
2619 account/update_location
2620 account/update_profile_background_image
2621 account/update_profile_image
2625 Not implemented in status.net:
2626 statuses/retweeted_to_me
2627 statuses/retweeted_by_me
2628 direct_messages/destroy
2630 account/update_delivery_device
2631 notifications/follow