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 $json = json_encode($rr);
170 if ($_GET['callback'])
171 $json = $_GET['callback']."(".$json.")";
175 header ("Content-Type: application/rss+xml");
176 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
179 header ("Content-Type: application/atom+xml");
180 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
183 //header ("Content-Type: application/json");
185 // return json_encode($rr);
186 return json_encode($r);
190 //echo "<pre>"; var_dump($r); die();
193 header("HTTP/1.1 404 Not Found");
194 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
195 return(api_error($a, $type, "not implemented"));
199 function api_error(&$a, $type, $error) {
200 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
203 header ("Content-Type: text/xml");
204 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
207 header ("Content-Type: application/json");
208 return json_encode(array('error' => $error, 'request' => $a->query_string));
211 header ("Content-Type: application/rss+xml");
212 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
215 header ("Content-Type: application/atom+xml");
216 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
224 function api_rss_extra(&$a, $arr, $user_info){
225 if (is_null($user_info)) $user_info = api_get_user($a);
226 $arr['$user'] = $user_info;
227 $arr['$rss'] = array(
228 'alternate' => $user_info['url'],
229 'self' => $a->get_baseurl(). "/". $a->query_string,
230 'base' => $a->get_baseurl(),
231 'updated' => api_date(null),
232 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
233 'language' => $user_info['language'],
234 'logo' => $a->get_baseurl()."/images/friendica-32.png",
242 * Unique contact to contact url.
244 function api_unique_id_to_url($id){
245 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
248 return ($r[0]["url"]);
254 * Returns user info array.
256 function api_get_user(&$a, $contact_id = Null, $type = "json"){
263 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
265 // Searching for contact URL
266 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
267 $user = dbesc(normalise_link($contact_id));
269 $extra_query = "AND `contact`.`nurl` = '%s' ";
270 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
273 // Searching for unique contact id
274 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
275 $user = dbesc(api_unique_id_to_url($contact_id));
278 die(api_error($a, $type, t("User not found.")));
281 $extra_query = "AND `contact`.`nurl` = '%s' ";
282 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
285 if(is_null($user) && x($_GET, 'user_id')) {
286 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
289 die(api_error($a, $type, t("User not found.")));
292 $extra_query = "AND `contact`.`nurl` = '%s' ";
293 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
295 if(is_null($user) && x($_GET, 'screen_name')) {
296 $user = dbesc($_GET['screen_name']);
298 $extra_query = "AND `contact`.`nick` = '%s' ";
299 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
302 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
303 $argid = count($called_api);
304 list($user, $null) = explode(".",$a->argv[$argid]);
305 if(is_numeric($user)){
306 $user = dbesc(api_unique_id_to_url($user));
312 $extra_query = "AND `contact`.`nurl` = '%s' ";
313 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
315 $user = dbesc($user);
317 $extra_query = "AND `contact`.`nick` = '%s' ";
318 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
322 logger("api_get_user: user ".$user, LOGGER_DEBUG);
325 if (api_user()===false) {
326 api_login($a); return False;
328 $user = $_SESSION['uid'];
329 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
334 logger('api_user: ' . $extra_query . ', user: ' . $user);
336 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
342 // Selecting the id by priority, friendica first
343 api_best_nickname($uinfo);
345 // if the contact wasn't found, fetch it from the unique contacts
346 if (count($uinfo)==0) {
350 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
352 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
355 // If no nick where given, extract it from the address
356 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
357 $r[0]['nick'] = api_get_nick($r[0]["url"]);
361 'id_str' => (string) $r[0]["id"],
362 'name' => $r[0]["name"],
363 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
365 'description' => NULL,
366 'profile_image_url' => $r[0]["avatar"],
367 'profile_image_url_https' => $r[0]["avatar"],
368 'url' => $r[0]["url"],
369 'protected' => false,
370 'followers_count' => 0,
371 'friends_count' => 0,
372 'created_at' => api_date(0),
373 'favourites_count' => 0,
375 'time_zone' => 'UTC',
376 'statuses_count' => 0,
377 'following' => false,
379 'statusnet_blocking' => false,
380 'notifications' => false,
381 'statusnet_profile_url' => $r[0]["url"],
390 die(api_error($a, $type, t("User not found.")));
394 if($uinfo[0]['self']) {
395 $usr = q("select * from user where uid = %d limit 1",
398 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
402 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
403 // count public wall messages
404 $r = q("SELECT count(*) as `count` FROM `item`
407 intval($uinfo[0]['uid'])
409 $countitms = $r[0]['count'];
412 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
413 $r = q("SELECT count(*) as `count` FROM `item`
414 WHERE `contact-id` = %d",
415 intval($uinfo[0]['id'])
417 $countitms = $r[0]['count'];
421 $r = q("SELECT count(*) as `count` FROM `contact`
422 WHERE `uid` = %d AND `rel` IN ( %d, %d )
423 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
424 intval($uinfo[0]['uid']),
425 intval(CONTACT_IS_SHARING),
426 intval(CONTACT_IS_FRIEND)
428 $countfriends = $r[0]['count'];
430 $r = q("SELECT count(*) as `count` FROM `contact`
431 WHERE `uid` = %d AND `rel` IN ( %d, %d )
432 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
433 intval($uinfo[0]['uid']),
434 intval(CONTACT_IS_FOLLOWER),
435 intval(CONTACT_IS_FRIEND)
437 $countfollowers = $r[0]['count'];
439 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
440 intval($uinfo[0]['uid'])
442 $starred = $r[0]['count'];
445 if(! $uinfo[0]['self']) {
451 // Add a nick if it isn't present there
452 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
453 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
456 // Fetching unique id
457 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
459 // If not there, then add it
460 if (count($r) == 0) {
461 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
462 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
464 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
467 require_once('include/contact_selectors.php');
468 $network_name = network_to_name($uinfo[0]['network']);
471 'id' => intval($r[0]['id']),
472 'id_str' => (string) intval($r[0]['id']),
473 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
474 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
475 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
476 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
477 'profile_image_url' => $uinfo[0]['micro'],
478 'profile_image_url_https' => $uinfo[0]['micro'],
479 'url' => $uinfo[0]['url'],
480 'protected' => false,
481 'followers_count' => intval($countfollowers),
482 'friends_count' => intval($countfriends),
483 'created_at' => api_date($uinfo[0]['created']),
484 'favourites_count' => intval($starred),
486 'time_zone' => 'UTC',
487 'statuses_count' => intval($countitms),
488 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
490 'statusnet_blocking' => false,
491 'notifications' => false,
492 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
493 'uid' => intval($uinfo[0]['uid']),
494 'cid' => intval($uinfo[0]['cid']),
495 'self' => $uinfo[0]['self'],
496 'network' => $uinfo[0]['network'],
503 function api_item_get_user(&$a, $item) {
505 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
506 dbesc(normalise_link($item['author-link'])));
508 if (count($author) == 0) {
509 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
510 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
512 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
513 dbesc(normalise_link($item['author-link'])));
514 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
515 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
516 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
519 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
520 dbesc(normalise_link($item['owner-link'])));
522 if (count($owner) == 0) {
523 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
524 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
526 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
527 dbesc(normalise_link($item['owner-link'])));
528 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
529 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
530 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
533 // Comments in threads may appear as wall-to-wall postings.
534 // So only take the owner at the top posting.
535 if ($item["id"] == $item["parent"])
536 $status_user = api_get_user($a,$item["owner-link"]);
538 $status_user = api_get_user($a,$item["author-link"]);
540 $status_user["protected"] = (($item["allow_cid"] != "") OR
541 ($item["allow_gid"] != "") OR
542 ($item["deny_cid"] != "") OR
543 ($item["deny_gid"] != "") OR
546 return ($status_user);
551 * load api $templatename for $type and replace $data array
553 function api_apply_template($templatename, $type, $data){
561 $data = array_xmlify($data);
562 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
564 header ("Content-Type: text/xml");
565 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
568 $ret = replace_macros($tpl, $data);
583 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
584 * returns a 401 status code and an error message if not.
585 * http://developer.twitter.com/doc/get/account/verify_credentials
587 function api_account_verify_credentials(&$a, $type){
588 if (api_user()===false) return false;
590 unset($_REQUEST["user_id"]);
591 unset($_GET["user_id"]);
593 unset($_REQUEST["screen_name"]);
594 unset($_GET["screen_name"]);
596 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
598 $user_info = api_get_user($a);
600 // "verified" isn't used here in the standard
601 unset($user_info["verified"]);
603 // - Adding last status
605 $user_info["status"] = api_status_show($a,"raw");
606 if (!count($user_info["status"]))
607 unset($user_info["status"]);
609 unset($user_info["status"]["user"]);
612 // "uid" and "self" are only needed for some internal stuff, so remove it from here
613 unset($user_info["uid"]);
614 unset($user_info["self"]);
616 return api_apply_template("user", $type, array('$user' => $user_info));
619 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
623 * get data from $_POST or $_GET
625 function requestdata($k){
626 if (isset($_POST[$k])){
629 if (isset($_GET[$k])){
635 /*Waitman Gobble Mod*/
636 function api_statuses_mediap(&$a, $type) {
637 if (api_user()===false) {
638 logger('api_statuses_update: no user');
641 $user_info = api_get_user($a);
643 $_REQUEST['type'] = 'wall';
644 $_REQUEST['profile_uid'] = api_user();
645 $_REQUEST['api_source'] = true;
646 $txt = requestdata('status');
647 //$txt = urldecode(requestdata('status'));
649 require_once('library/HTMLPurifier.auto.php');
650 require_once('include/html2bbcode.php');
652 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
653 $txt = html2bb_video($txt);
654 $config = HTMLPurifier_Config::createDefault();
655 $config->set('Cache.DefinitionImpl', null);
656 $purifier = new HTMLPurifier($config);
657 $txt = $purifier->purify($txt);
659 $txt = html2bbcode($txt);
661 $a->argv[1]=$user_info['screen_name']; //should be set to username?
663 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
664 require_once('mod/wall_upload.php');
665 $bebop = wall_upload_post($a);
667 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
668 $_REQUEST['body']=$txt."\n\n".$bebop;
669 require_once('mod/item.php');
672 // this should output the last post (the one we just posted).
673 return api_status_show($a,$type);
675 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
676 /*Waitman Gobble Mod*/
679 function api_statuses_update(&$a, $type) {
680 if (api_user()===false) {
681 logger('api_statuses_update: no user');
684 $user_info = api_get_user($a);
686 // convert $_POST array items to the form we use for web posts.
688 // logger('api_post: ' . print_r($_POST,true));
690 if(requestdata('htmlstatus')) {
691 require_once('library/HTMLPurifier.auto.php');
692 require_once('include/html2bbcode.php');
694 $txt = requestdata('htmlstatus');
695 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
697 $txt = html2bb_video($txt);
699 $config = HTMLPurifier_Config::createDefault();
700 $config->set('Cache.DefinitionImpl', null);
703 $purifier = new HTMLPurifier($config);
704 $txt = $purifier->purify($txt);
706 $_REQUEST['body'] = html2bbcode($txt);
711 $_REQUEST['body'] = requestdata('status');
713 $_REQUEST['title'] = requestdata('title');
715 $parent = requestdata('in_reply_to_status_id');
716 if(ctype_digit($parent))
717 $_REQUEST['parent'] = $parent;
719 $_REQUEST['parent_uri'] = $parent;
721 if(requestdata('lat') && requestdata('long'))
722 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
723 $_REQUEST['profile_uid'] = api_user();
726 $_REQUEST['type'] = 'net-comment';
728 $_REQUEST['type'] = 'wall';
729 if(x($_FILES,'media')) {
730 // upload the image if we have one
731 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
732 require_once('mod/wall_upload.php');
733 $media = wall_upload_post($a);
735 $_REQUEST['body'] .= "\n\n".$media;
739 // set this so that the item_post() function is quiet and doesn't redirect or emit json
741 $_REQUEST['api_source'] = true;
743 if (!x($_REQUEST, "source"))
744 $_REQUEST["source"] = api_source();
746 // call out normal post function
748 require_once('mod/item.php');
751 // this should output the last post (the one we just posted).
752 return api_status_show($a,$type);
754 api_register_func('api/statuses/update','api_statuses_update', true);
755 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
758 function api_status_show(&$a, $type){
759 $user_info = api_get_user($a);
761 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
763 // get last public wall message
764 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
765 FROM `item`, `item` as `i`
766 WHERE `item`.`contact-id` = %d
767 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
768 AND `i`.`id` = `item`.`parent`
769 AND `item`.`type`!='activity'
770 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
771 ORDER BY `item`.`created` DESC
773 intval($user_info['cid']),
774 dbesc($user_info['url']),
775 dbesc(normalise_link($user_info['url'])),
776 dbesc($user_info['url']),
777 dbesc(normalise_link($user_info['url']))
780 if (count($lastwall)>0){
781 $lastwall = $lastwall[0];
783 $in_reply_to_status_id = NULL;
784 $in_reply_to_user_id = NULL;
785 $in_reply_to_status_id_str = NULL;
786 $in_reply_to_user_id_str = NULL;
787 $in_reply_to_screen_name = NULL;
788 if (intval($lastwall['parent']) != intval($lastwall['id'])) {
789 $in_reply_to_status_id= intval($lastwall['parent']);
790 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
792 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
794 if ($r[0]['nick'] == "")
795 $r[0]['nick'] = api_get_nick($r[0]["url"]);
797 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
798 $in_reply_to_user_id = intval($r[0]['id']);
799 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
803 // There seems to be situation, where both fields are identical:
804 // https://github.com/friendica/friendica/issues/1010
805 // This is a bugfix for that.
806 if (intval($in_reply_to_status_id) == intval($lastwall['id'])) {
807 logger('api_status_show: this message should never appear: id: '.$lastwall['id'].' similar to reply-to: '.$in_reply_to_status_id, LOGGER_DEBUG);
808 $in_reply_to_status_id = NULL;
809 $in_reply_to_user_id = NULL;
810 $in_reply_to_status_id_str = NULL;
811 $in_reply_to_user_id_str = NULL;
812 $in_reply_to_screen_name = NULL;
815 $status_info = array(
816 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
817 'truncated' => false,
818 'created_at' => api_date($lastwall['created']),
819 'in_reply_to_status_id' => $in_reply_to_status_id,
820 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
821 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
822 'id' => intval($lastwall['id']),
823 'id_str' => (string) $lastwall['id'],
824 'in_reply_to_user_id' => $in_reply_to_user_id,
825 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
826 'in_reply_to_screen_name' => $in_reply_to_screen_name,
828 'favorited' => false,
830 'user' => $user_info,
831 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
832 'statusnet_conversation_id' => $lastwall['parent'],
835 if ($lastwall['title'] != "")
836 $status_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$status_info['statusnet_html'];
838 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
839 if (count($entities) > 0)
840 $status_info['entities'] = $entities;
842 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
843 $status_info["source"] = network_to_name($lastwall['item_network']);
844 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
845 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
847 // "uid" and "self" are only needed for some internal stuff, so remove it from here
848 unset($status_info["user"]["uid"]);
849 unset($status_info["user"]["self"]);
853 return($status_info);
855 return api_apply_template("status", $type, array('$status' => $status_info));
864 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
865 * The author's most recent status will be returned inline.
866 * http://developer.twitter.com/doc/get/users/show
868 function api_users_show(&$a, $type){
869 $user_info = api_get_user($a);
871 $lastwall = q("SELECT `item`.*
872 FROM `item`, `contact`
873 WHERE `item`.`uid` = %d AND `verb` = '%s' AND `item`.`contact-id` = %d
874 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
875 AND `contact`.`id`=`item`.`contact-id`
876 AND `type`!='activity'
877 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
878 ORDER BY `created` DESC
881 dbesc(ACTIVITY_POST),
882 intval($user_info['cid']),
883 dbesc($user_info['url']),
884 dbesc(normalise_link($user_info['url'])),
885 dbesc($user_info['url']),
886 dbesc(normalise_link($user_info['url']))
888 if (count($lastwall)>0){
889 $lastwall = $lastwall[0];
891 $in_reply_to_status_id = NULL;
892 $in_reply_to_user_id = NULL;
893 $in_reply_to_status_id_str = NULL;
894 $in_reply_to_user_id_str = NULL;
895 $in_reply_to_screen_name = NULL;
896 if ($lastwall['parent']!=$lastwall['id']) {
897 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
898 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
899 if (count($reply)>0) {
900 $in_reply_to_status_id = intval($lastwall['parent']);
901 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
903 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
905 if ($r[0]['nick'] == "")
906 $r[0]['nick'] = api_get_nick($r[0]["url"]);
908 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
909 $in_reply_to_user_id = intval($r[0]['id']);
910 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
914 $user_info['status'] = array(
915 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
916 'truncated' => false,
917 'created_at' => api_date($lastwall['created']),
918 'in_reply_to_status_id' => $in_reply_to_status_id,
919 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
920 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
921 'id' => intval($lastwall['contact-id']),
922 'id_str' => (string) $lastwall['contact-id'],
923 'in_reply_to_user_id' => $in_reply_to_user_id,
924 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
925 'in_reply_to_screen_name' => $in_reply_to_screen_name,
927 'favorited' => false,
928 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
929 'statusnet_conversation_id' => $lastwall['parent'],
932 if ($lastwall['title'] != "")
933 $user_info['statusnet_html'] = "<h4>".bbcode($lastwall['title'])."</h4>\n".$user_info['statusnet_html'];
935 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
936 if (count($entities) > 0)
937 $user_info['entities'] = $entities;
939 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
940 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
941 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
942 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
946 // "uid" and "self" are only needed for some internal stuff, so remove it from here
947 unset($user_info["uid"]);
948 unset($user_info["self"]);
950 return api_apply_template("user", $type, array('$user' => $user_info));
953 api_register_func('api/users/show','api_users_show');
956 function api_users_search(&$a, $type) {
957 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
961 if (isset($_GET["q"])) {
962 $r = q("SELECT id FROM unique_contacts WHERE name='%s'", dbesc($_GET["q"]));
964 $r = q("SELECT id FROM unique_contacts WHERE nick='%s'", dbesc($_GET["q"]));
967 foreach ($r AS $user) {
968 $user_info = api_get_user($a, $user["id"]);
969 //echo print_r($user_info, true)."\n";
970 $userdata = api_apply_template("user", $type, array('user' => $user_info));
971 $userlist[] = $userdata["user"];
973 $userlist = array("users" => $userlist);
975 die(api_error($a, $type, t("User not found.")));
977 die(api_error($a, $type, t("User not found.")));
982 api_register_func('api/users/search','api_users_search');
986 * http://developer.twitter.com/doc/get/statuses/home_timeline
988 * TODO: Optional parameters
989 * TODO: Add reply info
991 function api_statuses_home_timeline(&$a, $type){
992 if (api_user()===false) return false;
994 unset($_REQUEST["user_id"]);
995 unset($_GET["user_id"]);
997 unset($_REQUEST["screen_name"]);
998 unset($_GET["screen_name"]);
1000 $user_info = api_get_user($a);
1001 // get last newtork messages
1005 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1006 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1007 if ($page<0) $page=0;
1008 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1009 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1010 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1011 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1012 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1014 $start = $page*$count;
1018 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1019 if ($exclude_replies > 0)
1020 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1021 if ($conversation_id > 0)
1022 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1024 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1025 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1026 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1027 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1028 FROM `item`, `contact`
1029 WHERE `item`.`uid` = %d AND `verb` = '%s'
1030 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1031 AND `contact`.`id` = `item`.`contact-id`
1032 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1035 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1037 dbesc(ACTIVITY_POST),
1039 intval($start), intval($count)
1042 $ret = api_format_items($r,$user_info);
1044 // We aren't going to try to figure out at the item, group, and page
1045 // level which items you've seen and which you haven't. If you're looking
1046 // at the network timeline just mark everything seen.
1048 $r = q("UPDATE `item` SET `unseen` = 0
1049 WHERE `unseen` = 1 AND `uid` = %d",
1050 //intval($user_info['uid'])
1055 $data = array('$statuses' => $ret);
1059 $data = api_rss_extra($a, $data, $user_info);
1062 $as = api_format_as($a, $ret, $user_info);
1063 $as['title'] = $a->config['sitename']." Home Timeline";
1064 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1069 return api_apply_template("timeline", $type, $data);
1071 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1072 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1074 function api_statuses_public_timeline(&$a, $type){
1075 if (api_user()===false) return false;
1077 $user_info = api_get_user($a);
1078 // get last newtork messages
1082 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1083 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1084 if ($page<0) $page=0;
1085 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1086 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1087 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1088 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1089 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1091 $start = $page*$count;
1094 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1095 if ($exclude_replies > 0)
1096 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1097 if ($conversation_id > 0)
1098 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1100 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1101 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1102 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1103 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1104 `user`.`nickname`, `user`.`hidewall`
1105 FROM `item` STRAIGHT_JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1106 STRAIGHT_JOIN `user` ON `user`.`uid` = `item`.`uid`
1107 WHERE `verb` = '%s' AND `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1108 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1109 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1110 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1111 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1114 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1115 dbesc(ACTIVITY_POST),
1120 $ret = api_format_items($r,$user_info);
1123 $data = array('$statuses' => $ret);
1127 $data = api_rss_extra($a, $data, $user_info);
1130 $as = api_format_as($a, $ret, $user_info);
1131 $as['title'] = $a->config['sitename']." Public Timeline";
1132 $as['link']['url'] = $a->get_baseurl()."/";
1137 return api_apply_template("timeline", $type, $data);
1139 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1144 function api_statuses_show(&$a, $type){
1145 if (api_user()===false) return false;
1147 $user_info = api_get_user($a);
1150 $id = intval($a->argv[3]);
1153 $id = intval($_REQUEST["id"]);
1157 $id = intval($a->argv[4]);
1159 logger('API: api_statuses_show: '.$id);
1161 $conversation = (x($_REQUEST,'conversation')?1:0);
1165 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1167 $sql_extra .= " AND `item`.`id` = %d";
1169 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1170 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1171 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1172 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1173 FROM `item`, `contact`
1174 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1175 AND `contact`.`id` = `item`.`contact-id` AND `item`.`uid` = %d AND `item`.`verb` = '%s'
1176 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1179 dbesc(ACTIVITY_POST),
1184 die(api_error($a, $type, t("There is no status with this id.")));
1186 $ret = api_format_items($r,$user_info);
1188 if ($conversation) {
1189 $data = array('$statuses' => $ret);
1190 return api_apply_template("timeline", $type, $data);
1192 $data = array('$status' => $ret[0]);
1196 $data = api_rss_extra($a, $data, $user_info);
1198 return api_apply_template("status", $type, $data);
1201 api_register_func('api/statuses/show','api_statuses_show', true);
1207 function api_conversation_show(&$a, $type){
1208 if (api_user()===false) return false;
1210 $user_info = api_get_user($a);
1213 $id = intval($a->argv[3]);
1214 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1215 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1216 if ($page<0) $page=0;
1217 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1218 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1220 $start = $page*$count;
1223 $id = intval($_REQUEST["id"]);
1227 $id = intval($a->argv[4]);
1229 logger('API: api_conversation_show: '.$id);
1234 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1236 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1237 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1238 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1239 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1240 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1241 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1242 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1243 AND `item`.`uid` = %d AND `item`.`verb` = '%s' AND `contact`.`id` = `item`.`contact-id`
1244 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1245 AND `item`.`id`>%d $sql_extra
1246 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1247 intval($id), intval(api_user()),
1248 dbesc(ACTIVITY_POST),
1250 intval($start), intval($count)
1254 die(api_error($a, $type, t("There is no conversation with this id.")));
1256 $ret = api_format_items($r,$user_info);
1258 $data = array('$statuses' => $ret);
1259 return api_apply_template("timeline", $type, $data);
1261 api_register_func('api/conversation/show','api_conversation_show', true);
1267 function api_statuses_repeat(&$a, $type){
1270 if (api_user()===false) return false;
1272 $user_info = api_get_user($a);
1275 $id = intval($a->argv[3]);
1278 $id = intval($_REQUEST["id"]);
1282 $id = intval($a->argv[4]);
1284 logger('API: api_statuses_repeat: '.$id);
1286 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1287 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1288 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1289 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1290 FROM `item`, `contact`
1291 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1292 AND `contact`.`id` = `item`.`contact-id`
1293 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1295 AND `item`.`id`=%d",
1299 if ($r[0]['body'] != "") {
1300 if (!intval(get_config('system','old_share'))) {
1301 if (strpos($r[0]['body'], "[/share]") !== false) {
1302 $pos = strpos($r[0]['body'], "[share");
1303 $post = substr($r[0]['body'], $pos);
1305 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1306 "' profile='".$r[0]['author-link'].
1307 "' avatar='".$r[0]['author-avatar'].
1308 "' link='".$r[0]['plink']."']";
1309 $post .= $r[0]['body'];
1310 $post .= "[/share]";
1312 $_REQUEST['body'] = $post;
1314 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1316 $_REQUEST['profile_uid'] = api_user();
1317 $_REQUEST['type'] = 'wall';
1318 $_REQUEST['api_source'] = true;
1320 if (!x($_REQUEST, "source"))
1321 $_REQUEST["source"] = api_source();
1323 require_once('mod/item.php');
1327 // this should output the last post (the one we just posted).
1329 return(api_status_show($a,$type));
1331 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1336 function api_statuses_destroy(&$a, $type){
1337 if (api_user()===false) return false;
1339 $user_info = api_get_user($a);
1342 $id = intval($a->argv[3]);
1345 $id = intval($_REQUEST["id"]);
1349 $id = intval($a->argv[4]);
1351 logger('API: api_statuses_destroy: '.$id);
1353 $ret = api_statuses_show($a, $type);
1355 require_once('include/items.php');
1356 drop_item($id, false);
1360 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1364 * http://developer.twitter.com/doc/get/statuses/mentions
1367 function api_statuses_mentions(&$a, $type){
1368 if (api_user()===false) return false;
1370 unset($_REQUEST["user_id"]);
1371 unset($_GET["user_id"]);
1373 unset($_REQUEST["screen_name"]);
1374 unset($_GET["screen_name"]);
1376 $user_info = api_get_user($a);
1377 // get last newtork messages
1381 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1382 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1383 if ($page<0) $page=0;
1384 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1385 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1386 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1388 $start = $page*$count;
1390 // Ugly code - should be changed
1391 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1392 $myurl = substr($myurl,strpos($myurl,'://')+3);
1393 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1394 $myurl = str_replace('www.','',$myurl);
1395 $diasp_url = str_replace('/profile/','/u/',$myurl);
1398 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1400 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1401 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1402 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1403 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1404 FROM `item`, `contact`
1405 WHERE `item`.`uid` = %d AND `verb` = '%s'
1406 AND NOT (`item`.`author-link` IN ('https://%s', 'http://%s'))
1407 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1408 AND `contact`.`id` = `item`.`contact-id`
1409 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1410 AND `item`.`parent` IN (SELECT `iid` from thread where uid = %d AND `mention` AND !`ignored`)
1413 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1415 dbesc(ACTIVITY_POST),
1416 dbesc(protect_sprintf($myurl)),
1417 dbesc(protect_sprintf($myurl)),
1420 intval($start), intval($count)
1423 $ret = api_format_items($r,$user_info);
1426 $data = array('$statuses' => $ret);
1430 $data = api_rss_extra($a, $data, $user_info);
1433 $as = api_format_as($a, $ret, $user_info);
1434 $as["title"] = $a->config['sitename']." Mentions";
1435 $as['link']['url'] = $a->get_baseurl()."/";
1440 return api_apply_template("timeline", $type, $data);
1442 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1443 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1446 function api_statuses_user_timeline(&$a, $type){
1447 if (api_user()===false) return false;
1449 $user_info = api_get_user($a);
1450 // get last network messages
1452 logger("api_statuses_user_timeline: api_user: ". api_user() .
1453 "\nuser_info: ".print_r($user_info, true) .
1454 "\n_REQUEST: ".print_r($_REQUEST, true),
1458 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1459 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1460 if ($page<0) $page=0;
1461 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1462 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1463 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1464 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1466 $start = $page*$count;
1469 if ($user_info['self']==1)
1470 $sql_extra .= " AND `item`.`wall` = 1 ";
1472 if ($exclude_replies > 0)
1473 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1474 if ($conversation_id > 0)
1475 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1477 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1478 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1479 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1480 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1481 FROM `item`, `contact`
1482 WHERE `item`.`uid` = %d AND `verb` = '%s'
1483 AND `item`.`contact-id` = %d
1484 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1485 AND `contact`.`id` = `item`.`contact-id`
1486 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1489 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1491 dbesc(ACTIVITY_POST),
1492 intval($user_info['cid']),
1494 intval($start), intval($count)
1497 $ret = api_format_items($r,$user_info, true);
1499 $data = array('$statuses' => $ret);
1503 $data = api_rss_extra($a, $data, $user_info);
1506 return api_apply_template("timeline", $type, $data);
1509 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1512 function api_favorites(&$a, $type){
1515 if (api_user()===false) return false;
1517 $called_api= array();
1519 $user_info = api_get_user($a);
1521 // in friendica starred item are private
1522 // return favorites only for self
1523 logger('api_favorites: self:' . $user_info['self']);
1525 if ($user_info['self']==0) {
1531 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1532 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1533 $count = (x($_GET,'count')?$_GET['count']:20);
1534 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1535 if ($page<0) $page=0;
1537 $start = $page*$count;
1540 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1542 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1543 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1544 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1545 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1546 FROM `item`, `contact`
1547 WHERE `item`.`uid` = %d AND `verb` = '%s'
1548 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1549 AND `item`.`starred` = 1
1550 AND `contact`.`id` = `item`.`contact-id`
1551 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1554 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1556 dbesc(ACTIVITY_POST),
1558 intval($start), intval($count)
1561 $ret = api_format_items($r,$user_info);
1565 $data = array('$statuses' => $ret);
1569 $data = api_rss_extra($a, $data, $user_info);
1572 return api_apply_template("timeline", $type, $data);
1575 api_register_func('api/favorites','api_favorites', true);
1577 function api_format_as($a, $ret, $user_info) {
1580 $as['title'] = $a->config['sitename']." Public Timeline";
1582 foreach ($ret as $item) {
1583 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1584 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1585 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1586 $avatar[0]["rel"] = "avatar";
1587 $avatar[0]["type"] = "";
1588 $avatar[0]["width"] = 96;
1589 $avatar[0]["height"] = 96;
1590 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1591 $avatar[1]["rel"] = "avatar";
1592 $avatar[1]["type"] = "";
1593 $avatar[1]["width"] = 48;
1594 $avatar[1]["height"] = 48;
1595 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1596 $avatar[2]["rel"] = "avatar";
1597 $avatar[2]["type"] = "";
1598 $avatar[2]["width"] = 24;
1599 $avatar[2]["height"] = 24;
1600 $singleitem["actor"]["avatarLinks"] = $avatar;
1602 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1603 $singleitem["actor"]["image"]["rel"] = "avatar";
1604 $singleitem["actor"]["image"]["type"] = "";
1605 $singleitem["actor"]["image"]["width"] = 96;
1606 $singleitem["actor"]["image"]["height"] = 96;
1607 $singleitem["actor"]["type"] = "person";
1608 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1609 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1610 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1611 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1612 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1613 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1614 $singleitem["actor"]["contact"]["addresses"] = "";
1616 $singleitem["body"] = $item["text"];
1617 $singleitem["object"]["displayName"] = $item["text"];
1618 $singleitem["object"]["id"] = $item["url"];
1619 $singleitem["object"]["type"] = "note";
1620 $singleitem["object"]["url"] = $item["url"];
1621 //$singleitem["context"] =;
1622 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1623 $singleitem["provider"]["objectType"] = "service";
1624 $singleitem["provider"]["displayName"] = "Test";
1625 $singleitem["provider"]["url"] = "http://test.tld";
1626 $singleitem["title"] = $item["text"];
1627 $singleitem["verb"] = "post";
1628 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1629 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1630 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1631 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1632 //$singleitem["original"] = $item;
1633 $items[] = $singleitem;
1635 $as['items'] = $items;
1636 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1637 $as['link']['rel'] = "alternate";
1638 $as['link']['type'] = "text/html";
1642 function api_format_messages($item, $recipient, $sender) {
1643 // standard meta information
1645 'id' => $item['id'],
1646 'sender_id' => $sender['id'] ,
1648 'recipient_id' => $recipient['id'],
1649 'created_at' => api_date($item['created']),
1650 'sender_screen_name' => $sender['screen_name'],
1651 'recipient_screen_name' => $recipient['screen_name'],
1652 'sender' => $sender,
1653 'recipient' => $recipient,
1656 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1657 unset($ret["sender"]["uid"]);
1658 unset($ret["sender"]["self"]);
1659 unset($ret["recipient"]["uid"]);
1660 unset($ret["recipient"]["self"]);
1662 //don't send title to regular StatusNET requests to avoid confusing these apps
1663 if (x($_GET, 'getText')) {
1664 $ret['title'] = $item['title'] ;
1665 if ($_GET["getText"] == "html") {
1666 $ret['text'] = bbcode($item['body'], false, false);
1668 elseif ($_GET["getText"] == "plain") {
1669 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1670 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1674 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1676 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1677 unset($ret['sender']);
1678 unset($ret['recipient']);
1684 function api_get_entitities(&$text, $bbcode) {
1687 * Links at the first character of the post
1692 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1694 if ($include_entities != "true") {
1695 require_once("mod/proxy.php");
1697 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1699 foreach ($images[1] AS $image) {
1700 $replace = proxy_url($image);
1701 $text = str_replace($image, $replace, $text);
1706 $bbcode = bb_CleanPictureLinks($bbcode);
1708 // Change pure links in text to bbcode uris
1709 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1711 $entities = array();
1712 $entities["hashtags"] = array();
1713 $entities["symbols"] = array();
1714 $entities["urls"] = array();
1715 $entities["user_mentions"] = array();
1717 $URLSearchString = "^\[\]";
1719 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1721 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1722 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1723 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1725 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1726 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1727 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1729 $bbcode = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1730 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1731 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1733 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1735 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1736 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1738 $ordered_urls = array();
1739 foreach ($urls[1] AS $id=>$url) {
1740 //$start = strpos($text, $url, $offset);
1741 $start = iconv_strpos($text, $url, 0, "UTF-8");
1742 if (!($start === false))
1743 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1746 ksort($ordered_urls);
1749 //foreach ($urls[1] AS $id=>$url) {
1750 foreach ($ordered_urls AS $url) {
1751 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1752 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1753 $display_url = $url["title"];
1755 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1756 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1758 if (strlen($display_url) > 26)
1759 $display_url = substr($display_url, 0, 25)."…";
1762 //$start = strpos($text, $url, $offset);
1763 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1764 if (!($start === false)) {
1765 $entities["urls"][] = array("url" => $url["url"],
1766 "expanded_url" => $url["url"],
1767 "display_url" => $display_url,
1768 "indices" => array($start, $start+strlen($url["url"])));
1769 $offset = $start + 1;
1773 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1774 $ordered_images = array();
1775 foreach ($images[1] AS $image) {
1776 //$start = strpos($text, $url, $offset);
1777 $start = iconv_strpos($text, $image, 0, "UTF-8");
1778 if (!($start === false))
1779 $ordered_images[$start] = $image;
1781 //$entities["media"] = array();
1784 foreach ($ordered_images AS $url) {
1785 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1786 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1788 if (strlen($display_url) > 26)
1789 $display_url = substr($display_url, 0, 25)."…";
1791 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1792 if (!($start === false)) {
1793 require_once("include/Photo.php");
1794 $image = get_photo_info($url);
1796 // If image cache is activated, then use the following sizes:
1797 // thumb (150), small (340), medium (600) and large (1024)
1798 if (!get_config("system", "proxy_disabled")) {
1799 require_once("mod/proxy.php");
1800 $media_url = proxy_url($url);
1803 $scale = scale_image($image[0], $image[1], 150);
1804 $sizes["thumb"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1806 if (($image[0] > 150) OR ($image[1] > 150)) {
1807 $scale = scale_image($image[0], $image[1], 340);
1808 $sizes["small"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1811 $scale = scale_image($image[0], $image[1], 600);
1812 $sizes["medium"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1814 if (($image[0] > 600) OR ($image[1] > 600)) {
1815 $scale = scale_image($image[0], $image[1], 1024);
1816 $sizes["large"] = array("w" => $scale["width"], "h" => $scale["height"], "resize" => "fit");
1820 $sizes["medium"] = array("w" => $image[0], "h" => $image[1], "resize" => "fit");
1823 $entities["media"][] = array(
1825 "id_str" => (string)$start+1,
1826 "indices" => array($start, $start+strlen($url)),
1827 "media_url" => normalise_link($media_url),
1828 "media_url_https" => $media_url,
1830 "display_url" => $display_url,
1831 "expanded_url" => $url,
1835 $offset = $start + 1;
1841 function api_format_items_embeded_images($item, $text){
1843 $text = preg_replace_callback(
1844 "|data:image/([^;]+)[^=]+=*|m",
1845 function($match) use ($a, $item) {
1846 return $a->get_baseurl()."/display/".$item['guid'];
1852 function api_format_items($r,$user_info, $filter_user = false) {
1857 foreach($r as $item) {
1858 api_share_as_retweet($a, api_user(), $item);
1860 localize_item($item);
1861 $status_user = api_item_get_user($a,$item);
1863 // Look if the posts are matching if they should be filtered by user id
1864 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1867 if ($item['thr-parent'] != $item['uri']) {
1868 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1870 dbesc($item['thr-parent']));
1872 $in_reply_to_status_id = intval($r[0]['id']);
1874 $in_reply_to_status_id = intval($item['parent']);
1876 $in_reply_to_status_id_str = (string) intval($item['parent']);
1878 $in_reply_to_screen_name = NULL;
1879 $in_reply_to_user_id = NULL;
1880 $in_reply_to_user_id_str = NULL;
1882 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1884 intval($in_reply_to_status_id));
1886 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1889 if ($r[0]['nick'] == "")
1890 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1892 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1893 $in_reply_to_user_id = intval($r[0]['id']);
1894 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1898 $in_reply_to_screen_name = NULL;
1899 $in_reply_to_user_id = NULL;
1900 $in_reply_to_status_id = NULL;
1901 $in_reply_to_user_id_str = NULL;
1902 $in_reply_to_status_id_str = NULL;
1905 // Workaround for ostatus messages where the title is identically to the body
1906 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1907 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1908 $statusbody = trim(html2plain($html, 0));
1910 // handle data: images
1911 $statusbody = api_format_items_embeded_images($item,$statusbody);
1913 $statustitle = trim($item['title']);
1915 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1916 $statustext = trim($statusbody);
1918 $statustext = trim($statustitle."\n\n".$statusbody);
1920 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1921 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1923 $statushtml = trim(bbcode($item['body'], false, false));
1927 'text' => $statustext,
1928 'truncated' => False,
1929 'created_at'=> api_date($item['created']),
1930 'in_reply_to_status_id' => $in_reply_to_status_id,
1931 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
1932 'source' => (($item['app']) ? $item['app'] : 'web'),
1933 'id' => intval($item['id']),
1934 'id_str' => (string) intval($item['id']),
1935 'in_reply_to_user_id' => $in_reply_to_user_id,
1936 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
1937 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1939 'favorited' => $item['starred'] ? true : false,
1940 //'attachments' => array(),
1941 'user' => $status_user ,
1942 //'entities' => NULL,
1943 'statusnet_html' => $statushtml,
1944 'statusnet_conversation_id' => $item['parent'],
1947 if ($item['title'] != "")
1948 $status['statusnet_html'] = "<h4>".bbcode($item['title'])."</h4>\n".$status['statusnet_html'];
1950 $entities = api_get_entitities($status['text'], $item['body']);
1951 if (count($entities) > 0)
1952 $status['entities'] = $entities;
1954 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1955 $status["source"] = network_to_name($item['item_network']);
1956 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1957 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1960 // Retweets are only valid for top postings
1961 // It doesn't work reliable with the link if its a feed
1962 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1964 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1966 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1967 $retweeted_status = $status;
1968 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1970 $status["retweeted_status"] = $retweeted_status;
1973 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1974 unset($status["user"]["uid"]);
1975 unset($status["user"]["self"]);
1977 // 'geo' => array('type' => 'Point',
1978 // 'coordinates' => array((float) $notice->lat,
1979 // (float) $notice->lon));
1987 function api_account_rate_limit_status(&$a,$type) {
1990 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1991 'remaining_hits' => (string) 150,
1992 'hourly_limit' => (string) 150,
1993 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1996 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1998 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
2001 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
2003 function api_help_test(&$a,$type) {
2010 return api_apply_template('test', $type, array("$ok" => $ok));
2013 api_register_func('api/help/test','api_help_test',false);
2015 function api_lists(&$a,$type) {
2020 api_register_func('api/lists','api_lists',true);
2022 function api_lists_list(&$a,$type) {
2027 api_register_func('api/lists/list','api_lists_list',true);
2030 * https://dev.twitter.com/docs/api/1/get/statuses/friends
2031 * This function is deprecated by Twitter
2032 * returns: json, xml
2034 function api_statuses_f(&$a, $type, $qtype) {
2035 if (api_user()===false) return false;
2036 $user_info = api_get_user($a);
2038 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
2039 /* this is to stop Hotot to load friends multiple times
2040 * I'm not sure if I'm missing return something or
2041 * is a bug in hotot. Workaround, meantime
2045 return array('$users' => $ret);*/
2049 if($qtype == 'friends')
2050 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2051 if($qtype == 'followers')
2052 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2054 // friends and followers only for self
2055 if ($user_info['self'] == 0)
2056 $sql_extra = " AND false ";
2058 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
2063 foreach($r as $cid){
2064 $user = api_get_user($a, $cid['nurl']);
2065 // "uid" and "self" are only needed for some internal stuff, so remove it from here
2066 unset($user["uid"]);
2067 unset($user["self"]);
2073 return array('$users' => $ret);
2076 function api_statuses_friends(&$a, $type){
2077 $data = api_statuses_f($a,$type,"friends");
2078 if ($data===false) return false;
2079 return api_apply_template("friends", $type, $data);
2081 function api_statuses_followers(&$a, $type){
2082 $data = api_statuses_f($a,$type,"followers");
2083 if ($data===false) return false;
2084 return api_apply_template("friends", $type, $data);
2086 api_register_func('api/statuses/friends','api_statuses_friends',true);
2087 api_register_func('api/statuses/followers','api_statuses_followers',true);
2094 function api_statusnet_config(&$a,$type) {
2095 $name = $a->config['sitename'];
2096 $server = $a->get_hostname();
2097 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2098 $email = $a->config['admin_email'];
2099 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2100 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2101 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2102 if($a->config['api_import_size'])
2103 $texlimit = string($a->config['api_import_size']);
2104 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2105 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2108 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2109 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2110 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2111 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2112 'shorturllength' => '30',
2113 'friendica' => array(
2114 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2115 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2116 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2117 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2122 return api_apply_template('config', $type, array('$config' => $config));
2125 api_register_func('api/statusnet/config','api_statusnet_config',false);
2127 function api_statusnet_version(&$a,$type) {
2131 if($type === 'xml') {
2132 header("Content-type: application/xml");
2133 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2136 elseif($type === 'json') {
2137 header("Content-type: application/json");
2142 api_register_func('api/statusnet/version','api_statusnet_version',false);
2145 function api_ff_ids(&$a,$type,$qtype) {
2149 $user_info = api_get_user($a);
2151 if($qtype == 'friends')
2152 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2153 if($qtype == 'followers')
2154 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2156 if (!$user_info["self"])
2157 $sql_extra = " AND false ";
2159 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2161 $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",
2167 if($type === 'xml') {
2168 header("Content-type: application/xml");
2169 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2171 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2172 echo '</ids>' . "\r\n";
2175 elseif($type === 'json') {
2177 header("Content-type: application/json");
2182 $ret[] = intval($rr['id']);
2184 echo json_encode($ret);
2190 function api_friends_ids(&$a,$type) {
2191 api_ff_ids($a,$type,'friends');
2193 function api_followers_ids(&$a,$type) {
2194 api_ff_ids($a,$type,'followers');
2196 api_register_func('api/friends/ids','api_friends_ids',true);
2197 api_register_func('api/followers/ids','api_followers_ids',true);
2200 function api_direct_messages_new(&$a, $type) {
2201 if (api_user()===false) return false;
2203 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2205 $sender = api_get_user($a);
2207 require_once("include/message.php");
2209 if ($_POST['screen_name']) {
2210 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2212 dbesc($_POST['screen_name']));
2214 // Selecting the id by priority, friendica first
2215 api_best_nickname($r);
2217 $recipient = api_get_user($a, $r[0]['nurl']);
2219 $recipient = api_get_user($a, $_POST['user_id']);
2223 if (x($_REQUEST,'replyto')) {
2224 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2226 intval($_REQUEST['replyto']));
2227 $replyto = $r[0]['parent-uri'];
2228 $sub = $r[0]['title'];
2231 if (x($_REQUEST,'title')) {
2232 $sub = $_REQUEST['title'];
2235 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2239 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2242 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2243 $ret = api_format_messages($r[0], $recipient, $sender);
2246 $ret = array("error"=>$id);
2249 $data = Array('$messages'=>$ret);
2254 $data = api_rss_extra($a, $data, $user_info);
2257 return api_apply_template("direct_messages", $type, $data);
2260 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2262 function api_direct_messages_box(&$a, $type, $box) {
2263 if (api_user()===false) return false;
2267 $count = (x($_GET,'count')?$_GET['count']:20);
2268 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2269 if ($page<0) $page=0;
2271 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2272 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2274 $user_id = (x($_REQUEST,'user_id')?$_REQUEST['user_id']:"");
2275 $screen_name = (x($_REQUEST,'screen_name')?$_REQUEST['screen_name']:"");
2278 unset($_REQUEST["user_id"]);
2279 unset($_GET["user_id"]);
2281 unset($_REQUEST["screen_name"]);
2282 unset($_GET["screen_name"]);
2284 $user_info = api_get_user($a);
2285 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2286 $profile_url = $user_info["url"];
2290 $start = $page*$count;
2293 if ($box=="sentbox") {
2294 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2296 elseif ($box=="conversation") {
2297 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2299 elseif ($box=="all") {
2300 $sql_extra = "true";
2302 elseif ($box=="inbox") {
2303 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2307 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2309 if ($user_id !="") {
2310 $sql_extra .= ' AND `mail`.`contact-id` = ' . intval($user_id);
2312 elseif($screen_name !=""){
2313 $sql_extra .= " AND `contact`.`nick` = '" . dbesc($screen_name). "'";
2316 $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",
2319 intval($start), intval($count)
2324 foreach($r as $item) {
2325 if ($box == "inbox" || $item['from-url'] != $profile_url){
2326 $recipient = $user_info;
2327 $sender = api_get_user($a,normalise_link($item['contact-url']));
2329 elseif ($box == "sentbox" || $item['from-url'] == $profile_url){
2330 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2331 $sender = $user_info;
2334 $ret[]=api_format_messages($item, $recipient, $sender);
2338 $data = array('$messages' => $ret);
2342 $data = api_rss_extra($a, $data, $user_info);
2345 return api_apply_template("direct_messages", $type, $data);
2349 function api_direct_messages_sentbox(&$a, $type){
2350 return api_direct_messages_box($a, $type, "sentbox");
2352 function api_direct_messages_inbox(&$a, $type){
2353 return api_direct_messages_box($a, $type, "inbox");
2355 function api_direct_messages_all(&$a, $type){
2356 return api_direct_messages_box($a, $type, "all");
2358 function api_direct_messages_conversation(&$a, $type){
2359 return api_direct_messages_box($a, $type, "conversation");
2361 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2362 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2363 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2364 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2368 function api_oauth_request_token(&$a, $type){
2370 $oauth = new FKOAuth1();
2371 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2372 }catch(Exception $e){
2373 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2378 function api_oauth_access_token(&$a, $type){
2380 $oauth = new FKOAuth1();
2381 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2382 }catch(Exception $e){
2383 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2389 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2390 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2393 function api_fr_photos_list(&$a,$type) {
2394 if (api_user()===false) return false;
2395 $r = q("select distinct `resource-id` from photo where uid = %d and album != 'Contact Photos' ",
2396 intval(local_user())
2401 $ret[] = $rr['resource-id'];
2402 header("Content-type: application/json");
2403 echo json_encode($ret);
2408 function api_fr_photo_detail(&$a,$type) {
2409 if (api_user()===false) return false;
2410 if(! $_REQUEST['photo_id']) return false;
2411 $scale = ((array_key_exists('scale',$_REQUEST)) ? intval($_REQUEST['scale']) : 0);
2412 $r = q("select * from photo where uid = %d and `resource-id` = '%s' and scale = %d limit 1",
2413 intval(local_user()),
2414 dbesc($_REQUEST['photo_id']),
2418 header("Content-type: application/json");
2419 $r[0]['data'] = base64_encode($r[0]['data']);
2420 echo json_encode($r[0]);
2426 api_register_func('api/friendica/photos/list', 'api_fr_photos_list', true);
2427 api_register_func('api/friendica/photo', 'api_fr_photo_detail', true);
2431 function api_share_as_retweet($a, $uid, &$item) {
2432 $body = trim($item["body"]);
2434 // Skip if it isn't a pure repeated messages
2435 // Does it start with a share?
2436 if (strpos($body, "[share") > 0)
2439 // Does it end with a share?
2440 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2443 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2444 // Skip if there is no shared message in there
2445 if ($body == $attributes)
2449 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2450 if ($matches[1] != "")
2451 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2453 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2454 if ($matches[1] != "")
2455 $author = $matches[1];
2458 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2459 if ($matches[1] != "")
2460 $profile = $matches[1];
2462 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2463 if ($matches[1] != "")
2464 $profile = $matches[1];
2467 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2468 if ($matches[1] != "")
2469 $avatar = $matches[1];
2471 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2472 if ($matches[1] != "")
2473 $avatar = $matches[1];
2475 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2477 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2480 $item["body"] = $shared_body;
2481 $item["author-name"] = $author;
2482 $item["author-link"] = $profile;
2483 $item["author-avatar"] = $avatar;
2489 function api_get_nick($profile) {
2491 - remove trailing jung from profile url
2492 - pump.io check has to check the website
2497 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2498 if ($friendica != $profile)
2502 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2503 if ($diaspora != $profile)
2508 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2509 if ($twitter != $profile)
2515 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2516 if ($StatusnetHost != $profile) {
2517 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2518 if ($StatusnetUser != $profile) {
2519 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2520 $user = json_decode($UserData);
2522 $nick = $user->screen_name;
2527 // To-Do: look at the page if its really a pumpio site
2528 //if (!$nick == "") {
2529 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2530 // if ($pumpio != $profile)
2532 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2537 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2538 dbesc($nick), dbesc(normalise_link($profile)));
2545 function api_clean_plain_items($Text) {
2546 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2548 $Text = bb_CleanPictureLinks($Text);
2550 $URLSearchString = "^\[\]";
2552 $Text = preg_replace("/([!#@])\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'$1$3',$Text);
2554 if ($include_entities == "true") {
2555 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2558 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2562 function api_cleanup_share($shared) {
2563 if ($shared[2] != "type-link")
2566 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2572 if (isset($bookmark[2][0]))
2573 $title = $bookmark[2][0];
2575 if (isset($bookmark[1][0]))
2576 $link = $bookmark[1][0];
2578 if (strpos($shared[1],$title) !== false)
2581 if (strpos($shared[1],$link) !== false)
2584 $text = trim($shared[1]);
2586 //if (strlen($text) < strlen($title))
2587 if (($text == "") AND ($title != ""))
2588 $text .= "\n\n".trim($title);
2591 $text .= "\n".trim($link);
2593 return(trim($text));
2596 function api_best_nickname(&$contacts) {
2597 $best_contact = array();
2599 if (count($contact) == 0)
2602 foreach ($contacts AS $contact)
2603 if ($contact["network"] == "") {
2604 $contact["network"] = "dfrn";
2605 $best_contact = array($contact);
2608 if (sizeof($best_contact) == 0)
2609 foreach ($contacts AS $contact)
2610 if ($contact["network"] == "dfrn")
2611 $best_contact = array($contact);
2613 if (sizeof($best_contact) == 0)
2614 foreach ($contacts AS $contact)
2615 if ($contact["network"] == "dspr")
2616 $best_contact = array($contact);
2618 if (sizeof($best_contact) == 0)
2619 foreach ($contacts AS $contact)
2620 if ($contact["network"] == "stat")
2621 $best_contact = array($contact);
2623 if (sizeof($best_contact) == 0)
2624 foreach ($contacts AS $contact)
2625 if ($contact["network"] == "pump")
2626 $best_contact = array($contact);
2628 if (sizeof($best_contact) == 0)
2629 foreach ($contacts AS $contact)
2630 if ($contact["network"] == "twit")
2631 $best_contact = array($contact);
2633 if (sizeof($best_contact) == 1)
2634 $contacts = $best_contact;
2636 $contacts = array($contacts[0]);
2640 Not implemented by now:
2644 statuses/retweets_of_me
2649 account/update_location
2650 account/update_profile_background_image
2651 account/update_profile_image
2655 Not implemented in status.net:
2656 statuses/retweeted_to_me
2657 statuses/retweeted_by_me
2658 direct_messages/destroy
2660 account/update_delivery_device
2661 notifications/follow