3 - Automatically detect if incoming data is HTML or BBCode
5 require_once("include/bbcode.php");
6 require_once("include/datetime.php");
7 require_once("include/conversation.php");
8 require_once("include/oauth.php");
9 require_once("include/html2plain.php");
19 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
20 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
21 // into a page, and visitors will post something without noticing it).
22 // Instead, use this function.
23 if ($_SESSION["allow_api"])
29 function api_date($str){
30 //Wed May 23 06:01:13 +0000 2007
31 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
35 function api_register_func($path, $func, $auth=false){
37 $API[$path] = array('func'=>$func, 'auth'=>$auth);
39 // Workaround for hotot
40 $path = str_replace("api/", "api/1.1/", $path);
41 $API[$path] = array('func'=>$func, 'auth'=>$auth);
48 function api_login(&$a){
51 $oauth = new FKOAuth1();
52 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
53 if (!is_null($token)){
54 $oauth->loginUser($token->uid);
55 call_hooks('logged_in', $a->user);
58 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
60 logger(__file__.__line__.__function__."\n".$e);
61 //die(__file__.__line__.__function__."<pre>".$e); die();
66 // workaround for HTTP-auth in CGI mode
67 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
68 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
69 if(strlen($userpass)) {
70 list($name, $password) = explode(':', $userpass);
71 $_SERVER['PHP_AUTH_USER'] = $name;
72 $_SERVER['PHP_AUTH_PW'] = $password;
76 if (!isset($_SERVER['PHP_AUTH_USER'])) {
77 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
78 header('WWW-Authenticate: Basic realm="Friendica"');
79 header('HTTP/1.0 401 Unauthorized');
80 die((api_error($a, 'json', "This api requires login")));
82 //die('This api requires login');
85 $user = $_SERVER['PHP_AUTH_USER'];
86 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
90 * next code from mod/auth.php. needs better solution
93 // process normal login request
95 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
96 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
104 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
105 header('WWW-Authenticate: Basic realm="Friendica"');
106 header('HTTP/1.0 401 Unauthorized');
107 die('This api requires login');
110 require_once('include/security.php');
111 authenticate_success($record); $_SESSION["allow_api"] = true;
113 call_hooks('logged_in', $a->user);
117 /**************************
118 * MAIN API ENTRY POINT *
119 **************************/
120 function api_call(&$a){
121 GLOBAL $API, $called_api;
126 foreach ($API as $p=>$info){
127 if (strpos($a->query_string, $p)===0){
128 $called_api= explode("/",$p);
129 //unset($_SERVER['PHP_AUTH_USER']);
130 if ($info['auth']===true && api_user()===false) {
134 load_contact_links(api_user());
136 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
137 logger('API parameters: ' . print_r($_REQUEST,true));
139 if (strpos($a->query_string, ".xml")>0) $type="xml";
140 if (strpos($a->query_string, ".json")>0) $type="json";
141 if (strpos($a->query_string, ".rss")>0) $type="rss";
142 if (strpos($a->query_string, ".atom")>0) $type="atom";
143 if (strpos($a->query_string, ".as")>0) $type="as";
145 $r = call_user_func($info['func'], $a, $type);
146 if ($r===false) return;
150 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
151 header ("Content-Type: text/xml");
152 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
155 header ("Content-Type: application/json");
157 return json_encode($rr);
160 header ("Content-Type: application/rss+xml");
161 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
164 header ("Content-Type: application/atom+xml");
165 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
168 //header ("Content-Type: application/json");
170 // return json_encode($rr);
171 return json_encode($r);
175 //echo "<pre>"; var_dump($r); die();
178 header("HTTP/1.1 404 Not Found");
179 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
180 return(api_error($a, $type, "not implemented"));
184 function api_error(&$a, $type, $error) {
185 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
188 header ("Content-Type: text/xml");
189 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
192 header ("Content-Type: application/json");
193 return json_encode(array('error' => $error, 'request' => $a->query_string));
196 header ("Content-Type: application/rss+xml");
197 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
200 header ("Content-Type: application/atom+xml");
201 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
209 function api_rss_extra(&$a, $arr, $user_info){
210 if (is_null($user_info)) $user_info = api_get_user($a);
211 $arr['$user'] = $user_info;
212 $arr['$rss'] = array(
213 'alternate' => $user_info['url'],
214 'self' => $a->get_baseurl(). "/". $a->query_string,
215 'base' => $a->get_baseurl(),
216 'updated' => api_date(null),
217 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
218 'language' => $user_info['language'],
219 'logo' => $a->get_baseurl()."/images/friendica-32.png",
227 * Unique contact to contact url.
229 function api_unique_id_to_url($id){
230 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
233 return ($r[0]["url"]);
239 * Returns user info array.
241 function api_get_user(&$a, $contact_id = Null, $type = "json"){
248 logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
250 // Searching for contact URL
251 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
252 $user = dbesc(normalise_link($contact_id));
254 $extra_query = "AND `contact`.`nurl` = '%s' ";
255 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
258 // Searching for unique contact id
259 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
260 $user = dbesc(api_unique_id_to_url($contact_id));
263 die(api_error($a, $type, t("User not found.")));
266 $extra_query = "AND `contact`.`nurl` = '%s' ";
267 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
270 if(is_null($user) && x($_GET, 'user_id')) {
271 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
274 die(api_error($a, $type, t("User not found.")));
277 $extra_query = "AND `contact`.`nurl` = '%s' ";
278 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
280 if(is_null($user) && x($_GET, 'screen_name')) {
281 $user = dbesc($_GET['screen_name']);
283 $extra_query = "AND `contact`.`nick` = '%s' ";
284 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
287 if (is_null($user) AND ($a->argc > (count($called_api)-1)) AND (count($called_api) > 0)){
288 $argid = count($called_api);
289 list($user, $null) = explode(".",$a->argv[$argid]);
290 if(is_numeric($user)){
291 $user = dbesc(api_unique_id_to_url($user));
297 $extra_query = "AND `contact`.`nurl` = '%s' ";
298 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
300 $user = dbesc($user);
302 $extra_query = "AND `contact`.`nick` = '%s' ";
303 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
307 logger("api_get_user: user ".$user, LOGGER_DEBUG);
310 if (api_user()===false) {
311 api_login($a); return False;
313 $user = $_SESSION['uid'];
314 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
319 logger('api_user: ' . $extra_query . ', user: ' . $user);
321 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
327 // Selecting the id by priority, friendica first
328 api_best_nickname($uinfo);
330 // if the contact wasn't found, fetch it from the unique contacts
331 if (count($uinfo)==0) {
335 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
337 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
340 // If no nick where given, extract it from the address
341 if (($r[0]['nick'] == "") OR ($r[0]['name'] == $r[0]['nick']))
342 $r[0]['nick'] = api_get_nick($r[0]["url"]);
346 'id_str' => (string) $r[0]["id"],
347 'name' => $r[0]["name"],
348 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
350 'description' => NULL,
351 'profile_image_url' => $r[0]["avatar"],
352 'profile_image_url_https' => $r[0]["avatar"],
353 'url' => $r[0]["url"],
354 'protected' => false,
355 'followers_count' => 0,
356 'friends_count' => 0,
357 'created_at' => api_date(0),
358 'favourites_count' => 0,
360 'time_zone' => 'UTC',
361 'statuses_count' => 0,
362 'following' => false,
364 'statusnet_blocking' => false,
365 'notifications' => false,
366 'statusnet_profile_url' => $r[0]["url"],
375 die(api_error($a, $type, t("User not found.")));
379 if($uinfo[0]['self']) {
380 $usr = q("select * from user where uid = %d limit 1",
383 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
387 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
388 // count public wall messages
389 $r = q("SELECT count(*) as `count` FROM `item`
392 intval($uinfo[0]['uid'])
394 $countitms = $r[0]['count'];
397 //AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
398 $r = q("SELECT count(*) as `count` FROM `item`
399 WHERE `contact-id` = %d",
400 intval($uinfo[0]['id'])
402 $countitms = $r[0]['count'];
406 $r = q("SELECT count(*) as `count` FROM `contact`
407 WHERE `uid` = %d AND `rel` IN ( %d, %d )
408 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
409 intval($uinfo[0]['uid']),
410 intval(CONTACT_IS_SHARING),
411 intval(CONTACT_IS_FRIEND)
413 $countfriends = $r[0]['count'];
415 $r = q("SELECT count(*) as `count` FROM `contact`
416 WHERE `uid` = %d AND `rel` IN ( %d, %d )
417 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
418 intval($uinfo[0]['uid']),
419 intval(CONTACT_IS_FOLLOWER),
420 intval(CONTACT_IS_FRIEND)
422 $countfollowers = $r[0]['count'];
424 $r = q("SELECT count(*) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
425 intval($uinfo[0]['uid'])
427 $starred = $r[0]['count'];
430 if(! $uinfo[0]['self']) {
436 // Add a nick if it isn't present there
437 if (($uinfo[0]['nick'] == "") OR ($uinfo[0]['name'] == $uinfo[0]['nick'])) {
438 $uinfo[0]['nick'] = api_get_nick($uinfo[0]["url"]);
439 //if ($uinfo[0]['nick'] != "")
440 // q("UPDATE contact SET nick = '%s' WHERE id = %d",
441 // dbesc($uinfo[0]['nick']), intval($uinfo[0]["id"]));
444 // Fetching unique id
445 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
447 // If not there, then add it
448 if (count($r) == 0) {
449 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
450 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
452 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
455 require_once('include/contact_selectors.php');
456 $network_name = network_to_name($uinfo[0]['network']);
459 'id' => intval($r[0]['id']),
460 'id_str' => (string) intval($r[0]['id']),
461 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
462 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
463 'location' => ($usr) ? $usr[0]['default-location'] : $network_name,
464 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
465 'profile_image_url' => $uinfo[0]['micro'],
466 'profile_image_url_https' => $uinfo[0]['micro'],
467 'url' => $uinfo[0]['url'],
468 'protected' => false,
469 'followers_count' => intval($countfollowers),
470 'friends_count' => intval($countfriends),
471 'created_at' => api_date($uinfo[0]['created']),
472 'favourites_count' => intval($starred),
474 'time_zone' => 'UTC',
475 'statuses_count' => intval($countitms),
476 'following' => (($uinfo[0]['rel'] == CONTACT_IS_FOLLOWER) OR ($uinfo[0]['rel'] == CONTACT_IS_FRIEND)),
478 'statusnet_blocking' => false,
479 'notifications' => false,
480 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
481 'uid' => intval($uinfo[0]['uid']),
482 'cid' => intval($uinfo[0]['cid']),
483 'self' => $uinfo[0]['self'],
484 'network' => $uinfo[0]['network'],
491 function api_item_get_user(&$a, $item) {
493 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
494 dbesc(normalise_link($item['author-link'])));
496 if (count($author) == 0) {
497 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
498 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
500 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
501 dbesc(normalise_link($item['author-link'])));
502 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
503 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
504 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
507 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
508 dbesc(normalise_link($item['owner-link'])));
510 if (count($owner) == 0) {
511 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
512 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
514 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
515 dbesc(normalise_link($item['owner-link'])));
516 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
517 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
518 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
521 // Comments in threads may appear as wall-to-wall postings.
522 // So only take the owner at the top posting.
523 if ($item["id"] == $item["parent"])
524 $status_user = api_get_user($a,$item["owner-link"]);
526 $status_user = api_get_user($a,$item["author-link"]);
528 $status_user["protected"] = (($item["allow_cid"] != "") OR
529 ($item["allow_gid"] != "") OR
530 ($item["deny_cid"] != "") OR
531 ($item["deny_gid"] != "") OR
534 return ($status_user);
539 * load api $templatename for $type and replace $data array
541 function api_apply_template($templatename, $type, $data){
549 $data = array_xmlify($data);
550 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
552 header ("Content-Type: text/xml");
553 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
556 $ret = replace_macros($tpl, $data);
571 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
572 * returns a 401 status code and an error message if not.
573 * http://developer.twitter.com/doc/get/account/verify_credentials
575 function api_account_verify_credentials(&$a, $type){
576 if (api_user()===false) return false;
578 unset($_REQUEST["user_id"]);
579 unset($_GET["user_id"]);
581 unset($_REQUEST["screen_name"]);
582 unset($_GET["screen_name"]);
584 $skip_status = (x($_REQUEST,'skip_status')?$_REQUEST['skip_status']:false);
586 $user_info = api_get_user($a);
588 // "verified" isn't used here in the standard
589 unset($user_info["verified"]);
591 // - Adding last status
593 $user_info["status"] = api_status_show($a,"raw");
594 if (!count($user_info["status"]))
595 unset($user_info["status"]);
597 unset($user_info["status"]["user"]);
600 // "uid" and "self" are only needed for some internal stuff, so remove it from here
601 unset($user_info["uid"]);
602 unset($user_info["self"]);
604 return api_apply_template("user", $type, array('$user' => $user_info));
607 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
611 * get data from $_POST or $_GET
613 function requestdata($k){
614 if (isset($_POST[$k])){
617 if (isset($_GET[$k])){
623 /*Waitman Gobble Mod*/
624 function api_statuses_mediap(&$a, $type) {
625 if (api_user()===false) {
626 logger('api_statuses_update: no user');
629 $user_info = api_get_user($a);
631 $_REQUEST['type'] = 'wall';
632 $_REQUEST['profile_uid'] = api_user();
633 $_REQUEST['api_source'] = true;
634 $txt = requestdata('status');
635 //$txt = urldecode(requestdata('status'));
637 require_once('library/HTMLPurifier.auto.php');
638 require_once('include/html2bbcode.php');
640 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
641 $txt = html2bb_video($txt);
642 $config = HTMLPurifier_Config::createDefault();
643 $config->set('Cache.DefinitionImpl', null);
644 $purifier = new HTMLPurifier($config);
645 $txt = $purifier->purify($txt);
647 $txt = html2bbcode($txt);
649 $a->argv[1]=$user_info['screen_name']; //should be set to username?
651 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
652 require_once('mod/wall_upload.php');
653 $bebop = wall_upload_post($a);
655 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
656 $_REQUEST['body']=$txt."\n\n".$bebop;
657 require_once('mod/item.php');
660 // this should output the last post (the one we just posted).
661 return api_status_show($a,$type);
663 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
664 /*Waitman Gobble Mod*/
667 function api_statuses_update(&$a, $type) {
668 if (api_user()===false) {
669 logger('api_statuses_update: no user');
672 $user_info = api_get_user($a);
674 // convert $_POST array items to the form we use for web posts.
676 // logger('api_post: ' . print_r($_POST,true));
678 if(requestdata('htmlstatus')) {
679 require_once('library/HTMLPurifier.auto.php');
680 require_once('include/html2bbcode.php');
682 $txt = requestdata('htmlstatus');
683 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
685 $txt = html2bb_video($txt);
687 $config = HTMLPurifier_Config::createDefault();
688 $config->set('Cache.DefinitionImpl', null);
691 $purifier = new HTMLPurifier($config);
692 $txt = $purifier->purify($txt);
694 $_REQUEST['body'] = html2bbcode($txt);
699 $_REQUEST['body'] = requestdata('status');
701 $_REQUEST['title'] = requestdata('title');
703 $parent = requestdata('in_reply_to_status_id');
704 if(ctype_digit($parent))
705 $_REQUEST['parent'] = $parent;
707 $_REQUEST['parent_uri'] = $parent;
709 if(requestdata('lat') && requestdata('long'))
710 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
711 $_REQUEST['profile_uid'] = api_user();
714 $_REQUEST['type'] = 'net-comment';
716 $_REQUEST['type'] = 'wall';
717 if(x($_FILES,'media')) {
718 // upload the image if we have one
719 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
720 require_once('mod/wall_upload.php');
721 $media = wall_upload_post($a);
723 $_REQUEST['body'] .= "\n\n".$media;
727 // set this so that the item_post() function is quiet and doesn't redirect or emit json
729 $_REQUEST['api_source'] = true;
731 // call out normal post function
733 require_once('mod/item.php');
736 // this should output the last post (the one we just posted).
737 return api_status_show($a,$type);
739 api_register_func('api/statuses/update','api_statuses_update', true);
740 api_register_func('api/statuses/update_with_media','api_statuses_update', true);
743 function api_status_show(&$a, $type){
744 $user_info = api_get_user($a);
746 logger('api_status_show: user_info: '.print_r($user_info, true), LOGGER_DEBUG);
748 // get last public wall message
749 //$lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
750 // FROM `item`, `contact`, `item` as `i`, `contact` as `c`
751 // WHERE `item`.`contact-id` = %d
752 // AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
753 // AND `i`.`id` = `item`.`parent`
754 // AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
755 // AND `item`.`type`!='activity'
756 // AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
757 // ORDER BY `item`.`created` DESC
759 // intval($user_info['cid']),
760 // dbesc($user_info['url']),
761 // dbesc(normalise_link($user_info['url'])),
762 // dbesc($user_info['url']),
763 // dbesc(normalise_link($user_info['url']))
765 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`author-link` AS `item-author`
766 FROM `item`, `item` as `i`
767 WHERE `item`.`contact-id` = %d
768 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
769 AND `i`.`id` = `item`.`parent`
770 AND `item`.`type`!='activity'
771 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
772 ORDER BY `item`.`created` DESC
774 intval($user_info['cid']),
775 dbesc($user_info['url']),
776 dbesc(normalise_link($user_info['url'])),
777 dbesc($user_info['url']),
778 dbesc(normalise_link($user_info['url']))
781 if (count($lastwall)>0){
782 $lastwall = $lastwall[0];
784 $in_reply_to_status_id = NULL;
785 $in_reply_to_user_id = NULL;
786 $in_reply_to_status_id_str = NULL;
787 $in_reply_to_user_id_str = NULL;
788 $in_reply_to_screen_name = NULL;
789 if ($lastwall['parent']!=$lastwall['id']) {
790 $in_reply_to_status_id= intval($lastwall['parent']);
791 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
793 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
795 if ($r[0]['nick'] == "")
796 $r[0]['nick'] = api_get_nick($r[0]["url"]);
798 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
799 $in_reply_to_user_id = intval($r[0]['id']);
800 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
804 $status_info = array(
805 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
806 'truncated' => false,
807 'created_at' => api_date($lastwall['created']),
808 'in_reply_to_status_id' => $in_reply_to_status_id,
809 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
810 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
811 'id' => intval($lastwall['id']),
812 'id_str' => (string) $lastwall['id'],
813 'in_reply_to_user_id' => $in_reply_to_user_id,
814 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
815 'in_reply_to_screen_name' => $in_reply_to_screen_name,
817 'favorited' => false,
819 'user' => $user_info,
820 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
821 'statusnet_conversation_id' => $lastwall['parent'],
824 $entities = api_get_entitities($status_info['text'], $lastwall['body']);
825 if (count($entities) > 0)
826 $status_info['entities'] = $entities;
828 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
829 $status_info["source"] = network_to_name($lastwall['item_network']);
830 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
831 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
833 // "uid" and "self" are only needed for some internal stuff, so remove it from here
834 unset($status_info["user"]["uid"]);
835 unset($status_info["user"]["self"]);
839 return($status_info);
841 return api_apply_template("status", $type, array('$status' => $status_info));
850 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
851 * The author's most recent status will be returned inline.
852 * http://developer.twitter.com/doc/get/users/show
854 function api_users_show(&$a, $type){
855 $user_info = api_get_user($a);
857 $lastwall = q("SELECT `item`.*
858 FROM `item`, `contact`
859 WHERE `item`.`uid` = %d AND `item`.`contact-id` = %d
860 AND ((`item`.`author-link` IN ('%s', '%s')) OR (`item`.`owner-link` IN ('%s', '%s')))
861 AND `contact`.`id`=`item`.`contact-id`
862 AND `type`!='activity'
863 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
864 ORDER BY `created` DESC
867 intval($user_info['cid']),
868 dbesc($user_info['url']),
869 dbesc(normalise_link($user_info['url'])),
870 dbesc($user_info['url']),
871 dbesc(normalise_link($user_info['url']))
873 //print_r($user_info);
874 if (count($lastwall)>0){
875 $lastwall = $lastwall[0];
877 $in_reply_to_status_id = NULL;
878 $in_reply_to_user_id = NULL;
879 $in_reply_to_status_id_str = NULL;
880 $in_reply_to_user_id_str = NULL;
881 $in_reply_to_screen_name = NULL;
882 if ($lastwall['parent']!=$lastwall['id']) {
883 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
884 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
885 if (count($reply)>0) {
886 $in_reply_to_status_id = intval($lastwall['parent']);
887 $in_reply_to_status_id_str = (string) intval($lastwall['parent']);
889 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
891 if ($r[0]['nick'] == "")
892 $r[0]['nick'] = api_get_nick($r[0]["url"]);
894 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
895 $in_reply_to_user_id = intval($r[0]['id']);
896 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
900 $user_info['status'] = array(
901 'text' => trim(html2plain(bbcode(api_clean_plain_items($lastwall['body']), false, false, 2, true), 0)),
902 'truncated' => false,
903 'created_at' => api_date($lastwall['created']),
904 'in_reply_to_status_id' => $in_reply_to_status_id,
905 'in_reply_to_status_id_str' => $in_reply_to_status_id_str,
906 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
907 'id' => intval($lastwall['contact-id']),
908 'id_str' => (string) $lastwall['contact-id'],
909 'in_reply_to_user_id' => $in_reply_to_user_id,
910 'in_reply_to_user_id_str' => $in_reply_to_user_id_str,
911 'in_reply_to_screen_name' => $in_reply_to_screen_name,
913 'favorited' => false,
914 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
915 'statusnet_conversation_id' => $lastwall['parent'],
918 $entities = api_get_entitities($user_info['text'], $lastwall['body']);
919 if (count($entities) > 0)
920 $user_info['entities'] = $entities;
922 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
923 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
924 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
925 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
929 // "uid" and "self" are only needed for some internal stuff, so remove it from here
930 unset($user_info["uid"]);
931 unset($user_info["self"]);
933 return api_apply_template("user", $type, array('$user' => $user_info));
936 api_register_func('api/users/show','api_users_show');
940 * http://developer.twitter.com/doc/get/statuses/home_timeline
942 * TODO: Optional parameters
943 * TODO: Add reply info
945 function api_statuses_home_timeline(&$a, $type){
946 if (api_user()===false) return false;
948 unset($_REQUEST["user_id"]);
949 unset($_GET["user_id"]);
951 unset($_REQUEST["screen_name"]);
952 unset($_GET["screen_name"]);
954 $user_info = api_get_user($a);
955 // get last newtork messages
959 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
960 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
961 if ($page<0) $page=0;
962 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
963 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
964 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
965 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
966 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
968 $start = $page*$count;
972 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
973 if ($exclude_replies > 0)
974 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
975 if ($conversation_id > 0)
976 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
978 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
979 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
980 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
981 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
982 FROM `item`, `contact`
983 WHERE `item`.`uid` = %d
984 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
985 AND `contact`.`id` = `item`.`contact-id`
986 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
989 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
990 //intval($user_info['uid']),
993 intval($start), intval($count)
996 $ret = api_format_items($r,$user_info);
998 // We aren't going to try to figure out at the item, group, and page
999 // level which items you've seen and which you haven't. If you're looking
1000 // at the network timeline just mark everything seen.
1002 $r = q("UPDATE `item` SET `unseen` = 0
1003 WHERE `unseen` = 1 AND `uid` = %d",
1004 //intval($user_info['uid'])
1009 $data = array('$statuses' => $ret);
1013 $data = api_rss_extra($a, $data, $user_info);
1016 $as = api_format_as($a, $ret, $user_info);
1017 $as['title'] = $a->config['sitename']." Home Timeline";
1018 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1023 return api_apply_template("timeline", $type, $data);
1025 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
1026 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
1028 function api_statuses_public_timeline(&$a, $type){
1029 if (api_user()===false) return false;
1031 $user_info = api_get_user($a);
1032 // get last newtork messages
1036 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1037 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1038 if ($page<0) $page=0;
1039 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1040 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1041 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1042 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1043 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1045 $start = $page*$count;
1048 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
1049 if ($exclude_replies > 0)
1050 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1051 if ($conversation_id > 0)
1052 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1054 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1055 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1056 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
1057 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
1058 `user`.`nickname`, `user`.`hidewall`
1059 FROM `item` INNER JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
1060 INNER JOIN `user` ON `user`.`uid` = `item`.`uid`
1061 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
1062 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
1063 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
1064 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
1065 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1068 ORDER BY `item`.`id` DESC LIMIT %d, %d ",
1073 $ret = api_format_items($r,$user_info);
1076 $data = array('$statuses' => $ret);
1080 $data = api_rss_extra($a, $data, $user_info);
1083 $as = api_format_as($a, $ret, $user_info);
1084 $as['title'] = $a->config['sitename']." Public Timeline";
1085 $as['link']['url'] = $a->get_baseurl()."/";
1090 return api_apply_template("timeline", $type, $data);
1092 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
1097 function api_statuses_show(&$a, $type){
1098 if (api_user()===false) return false;
1100 $user_info = api_get_user($a);
1103 $id = intval($a->argv[3]);
1106 $id = intval($_REQUEST["id"]);
1110 $id = intval($a->argv[4]);
1112 logger('API: api_statuses_show: '.$id);
1114 $conversation = (x($_REQUEST,'conversation')?1:0);
1118 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1120 $sql_extra .= " AND `item`.`id` = %d";
1122 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1123 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1124 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1125 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1126 FROM `item`, `contact`
1127 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1128 AND `contact`.`id` = `item`.`contact-id`
1129 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1135 die(api_error($a, $type, t("There is no status with this id.")));
1137 $ret = api_format_items($r,$user_info);
1139 if ($conversation) {
1140 $data = array('$statuses' => $ret);
1141 return api_apply_template("timeline", $type, $data);
1143 $data = array('$status' => $ret[0]);
1147 $data = api_rss_extra($a, $data, $user_info);
1149 return api_apply_template("status", $type, $data);
1152 api_register_func('api/statuses/show','api_statuses_show', true);
1158 function api_conversation_show(&$a, $type){
1159 if (api_user()===false) return false;
1161 $user_info = api_get_user($a);
1164 $id = intval($a->argv[3]);
1165 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1166 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1167 if ($page<0) $page=0;
1168 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1169 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1171 $start = $page*$count;
1174 $id = intval($_REQUEST["id"]);
1178 $id = intval($a->argv[4]);
1180 logger('API: api_conversation_show: '.$id);
1185 $sql_extra = ' AND `item`.`id` <= '.intval($max_id);
1187 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1188 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1189 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1190 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1191 FROM `item` INNER JOIN (SELECT `uri`,`parent` FROM `item` WHERE `id` = %d) AS `temp1`
1192 ON (`item`.`thr-parent` = `temp1`.`uri` AND `item`.`parent` = `temp1`.`parent`), `contact`
1193 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1194 AND `item`.`uid` = %d AND `contact`.`id` = `item`.`contact-id`
1195 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1196 AND `item`.`id`>%d $sql_extra
1197 ORDER BY `item`.`id` DESC LIMIT %d ,%d",
1198 intval($id), intval(api_user()),
1200 intval($start), intval($count)
1204 die(api_error($a, $type, t("There is no conversation with this id.")));
1206 $ret = api_format_items($r,$user_info);
1208 $data = array('$statuses' => $ret);
1209 return api_apply_template("timeline", $type, $data);
1211 api_register_func('api/conversation/show','api_conversation_show', true);
1217 function api_statuses_repeat(&$a, $type){
1220 if (api_user()===false) return false;
1222 $user_info = api_get_user($a);
1225 $id = intval($a->argv[3]);
1228 $id = intval($_REQUEST["id"]);
1232 $id = intval($a->argv[4]);
1234 logger('API: api_statuses_repeat: '.$id);
1236 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1237 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_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`, `contact`
1241 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1242 AND `contact`.`id` = `item`.`contact-id`
1243 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1245 AND `item`.`id`=%d",
1249 if ($r[0]['body'] != "") {
1250 if (!intval(get_config('system','old_share'))) {
1251 if (strpos($r[0]['body'], "[/share]") !== false) {
1252 $pos = strpos($r[0]['body'], "[share");
1253 $post = substr($r[0]['body'], $pos);
1255 $post = "[share author='".str_replace("'", "'", $r[0]['author-name']).
1256 "' profile='".$r[0]['author-link'].
1257 "' avatar='".$r[0]['author-avatar'].
1258 "' link='".$r[0]['plink']."']";
1259 $post .= $r[0]['body'];
1260 $post .= "[/share]";
1262 $_REQUEST['body'] = $post;
1264 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1266 $_REQUEST['profile_uid'] = api_user();
1267 $_REQUEST['type'] = 'wall';
1268 $_REQUEST['api_source'] = true;
1270 require_once('mod/item.php');
1274 // this should output the last post (the one we just posted).
1276 return(api_status_show($a,$type));
1278 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1283 function api_statuses_destroy(&$a, $type){
1284 if (api_user()===false) return false;
1286 $user_info = api_get_user($a);
1289 $id = intval($a->argv[3]);
1292 $id = intval($_REQUEST["id"]);
1296 $id = intval($a->argv[4]);
1298 logger('API: api_statuses_destroy: '.$id);
1300 $ret = api_statuses_show($a, $type);
1302 require_once('include/items.php');
1303 drop_item($id, false);
1307 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1311 * http://developer.twitter.com/doc/get/statuses/mentions
1314 function api_statuses_mentions(&$a, $type){
1315 if (api_user()===false) return false;
1317 unset($_REQUEST["user_id"]);
1318 unset($_GET["user_id"]);
1320 unset($_REQUEST["screen_name"]);
1321 unset($_GET["screen_name"]);
1323 $user_info = api_get_user($a);
1324 // get last newtork messages
1328 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1329 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1330 if ($page<0) $page=0;
1331 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1332 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1333 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1335 $start = $page*$count;
1337 // Ugly code - should be changed
1338 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1339 $myurl = substr($myurl,strpos($myurl,'://')+3);
1340 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1341 $myurl = str_replace('www.','',$myurl);
1342 $diasp_url = str_replace('/profile/','/u/',$myurl);
1344 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1345 dbesc(protect_sprintf($myurl)),
1346 dbesc(protect_sprintf($myurl))
1350 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1352 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1353 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1354 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1355 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1356 FROM `item`, `contact`
1357 WHERE `item`.`uid` = %d
1358 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1359 AND `contact`.`id` = `item`.`contact-id`
1360 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1363 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1364 //intval($user_info['uid']),
1367 intval($start), intval($count)
1370 $ret = api_format_items($r,$user_info);
1373 $data = array('$statuses' => $ret);
1377 $data = api_rss_extra($a, $data, $user_info);
1380 $as = api_format_as($a, $ret, $user_info);
1381 $as["title"] = $a->config['sitename']." Mentions";
1382 $as['link']['url'] = $a->get_baseurl()."/";
1387 return api_apply_template("timeline", $type, $data);
1389 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1390 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1393 function api_statuses_user_timeline(&$a, $type){
1394 if (api_user()===false) return false;
1396 $user_info = api_get_user($a);
1397 // get last network messages
1399 logger("api_statuses_user_timeline: api_user: ". api_user() .
1400 "\nuser_info: ".print_r($user_info, true) .
1401 "\n_REQUEST: ".print_r($_REQUEST, true),
1405 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1406 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1407 if ($page<0) $page=0;
1408 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1409 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1410 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1411 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1413 $start = $page*$count;
1416 if ($user_info['self']==1)
1417 $sql_extra .= " AND `item`.`wall` = 1 ";
1419 if ($exclude_replies > 0)
1420 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1421 if ($conversation_id > 0)
1422 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1424 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1425 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1426 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1427 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1428 FROM `item`, `contact`
1429 WHERE `item`.`uid` = %d
1430 AND `item`.`contact-id` = %d
1431 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1432 AND `contact`.`id` = `item`.`contact-id`
1433 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1436 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1438 intval($user_info['cid']),
1440 intval($start), intval($count)
1443 $ret = api_format_items($r,$user_info, true);
1445 $data = array('$statuses' => $ret);
1449 $data = api_rss_extra($a, $data, $user_info);
1452 return api_apply_template("timeline", $type, $data);
1455 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1458 function api_favorites(&$a, $type){
1461 if (api_user()===false) return false;
1463 $called_api= array();
1465 $user_info = api_get_user($a);
1467 // in friendica starred item are private
1468 // return favorites only for self
1469 logger('api_favorites: self:' . $user_info['self']);
1471 if ($user_info['self']==0) {
1477 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1478 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1479 $count = (x($_GET,'count')?$_GET['count']:20);
1480 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1481 if ($page<0) $page=0;
1483 $start = $page*$count;
1486 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1488 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1489 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1490 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1491 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1492 FROM `item`, `contact`
1493 WHERE `item`.`uid` = %d
1494 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1495 AND `item`.`starred` = 1
1496 AND `contact`.`id` = `item`.`contact-id`
1497 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1500 ORDER BY `item`.`id` DESC LIMIT %d ,%d ",
1501 //intval($user_info['uid']),
1504 intval($start), intval($count)
1507 $ret = api_format_items($r,$user_info);
1511 $data = array('$statuses' => $ret);
1515 $data = api_rss_extra($a, $data, $user_info);
1518 return api_apply_template("timeline", $type, $data);
1521 api_register_func('api/favorites','api_favorites', true);
1523 function api_format_as($a, $ret, $user_info) {
1526 $as['title'] = $a->config['sitename']." Public Timeline";
1528 foreach ($ret as $item) {
1529 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1530 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1531 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1532 $avatar[0]["rel"] = "avatar";
1533 $avatar[0]["type"] = "";
1534 $avatar[0]["width"] = 96;
1535 $avatar[0]["height"] = 96;
1536 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1537 $avatar[1]["rel"] = "avatar";
1538 $avatar[1]["type"] = "";
1539 $avatar[1]["width"] = 48;
1540 $avatar[1]["height"] = 48;
1541 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1542 $avatar[2]["rel"] = "avatar";
1543 $avatar[2]["type"] = "";
1544 $avatar[2]["width"] = 24;
1545 $avatar[2]["height"] = 24;
1546 $singleitem["actor"]["avatarLinks"] = $avatar;
1548 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1549 $singleitem["actor"]["image"]["rel"] = "avatar";
1550 $singleitem["actor"]["image"]["type"] = "";
1551 $singleitem["actor"]["image"]["width"] = 96;
1552 $singleitem["actor"]["image"]["height"] = 96;
1553 $singleitem["actor"]["type"] = "person";
1554 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1555 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1556 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1557 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1558 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1559 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1560 $singleitem["actor"]["contact"]["addresses"] = "";
1562 $singleitem["body"] = $item["text"];
1563 $singleitem["object"]["displayName"] = $item["text"];
1564 $singleitem["object"]["id"] = $item["url"];
1565 $singleitem["object"]["type"] = "note";
1566 $singleitem["object"]["url"] = $item["url"];
1567 //$singleitem["context"] =;
1568 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1569 $singleitem["provider"]["objectType"] = "service";
1570 $singleitem["provider"]["displayName"] = "Test";
1571 $singleitem["provider"]["url"] = "http://test.tld";
1572 $singleitem["title"] = $item["text"];
1573 $singleitem["verb"] = "post";
1574 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1575 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1576 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1577 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1578 //$singleitem["original"] = $item;
1579 $items[] = $singleitem;
1581 $as['items'] = $items;
1582 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1583 $as['link']['rel'] = "alternate";
1584 $as['link']['type'] = "text/html";
1588 function api_format_messages($item, $recipient, $sender) {
1589 // standard meta information
1591 'id' => $item['id'],
1592 'sender_id' => $sender['id'] ,
1594 'recipient_id' => $recipient['id'],
1595 'created_at' => api_date($item['created']),
1596 'sender_screen_name' => $sender['screen_name'],
1597 'recipient_screen_name' => $recipient['screen_name'],
1598 'sender' => $sender,
1599 'recipient' => $recipient,
1602 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1603 unset($ret["sender"]["uid"]);
1604 unset($ret["sender"]["self"]);
1605 unset($ret["recipient"]["uid"]);
1606 unset($ret["recipient"]["self"]);
1608 //don't send title to regular StatusNET requests to avoid confusing these apps
1609 if (x($_GET, 'getText')) {
1610 $ret['title'] = $item['title'] ;
1611 if ($_GET["getText"] == "html") {
1612 $ret['text'] = bbcode($item['body'], false, false);
1614 elseif ($_GET["getText"] == "plain") {
1615 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1616 $ret['text'] = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0));
1620 $ret['text'] = $item['title']."\n".html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 2, true), 0);
1622 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1623 unset($ret['sender']);
1624 unset($ret['recipient']);
1630 function api_get_entitities($text, $bbcode) {
1633 * Links at the first character of the post
1634 * different sizes of pictures
1635 * caching picture data (using the id for that?) (See privacy_image_cache)
1638 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
1640 if ($include_entities != "true")
1643 $bbcode = bb_CleanPictureLinks($bbcode);
1645 // Change pure links in text to bbcode uris
1646 $bbcode = preg_replace("/([^\]\='".'"'."]|^)(https?\:\/\/[a-zA-Z0-9\:\/\-\?\&\;\.\=\_\~\#\%\$\!\+\,]+)/ism", '$1[url=$2]$2[/url]', $bbcode);
1648 $entities = array();
1649 $entities["hashtags"] = array();
1650 $entities["symbols"] = array();
1651 $entities["urls"] = array();
1652 $entities["user_mentions"] = array();
1654 $URLSearchString = "^\[\]";
1656 $bbcode = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$bbcode);
1658 $bbcode = preg_replace("/\[bookmark\=([$URLSearchString]*)\](.*?)\[\/bookmark\]/ism",'[url=$1]$2[/url]',$bbcode);
1659 //$bbcode = preg_replace("/\[url\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$bbcode);
1660 $bbcode = preg_replace("/\[video\](.*?)\[\/video\]/ism",'[url=$1]$1[/url]',$bbcode);
1662 $bbcode = preg_replace("/\[youtube\]([A-Za-z0-9\-_=]+)(.*?)\[\/youtube\]/ism",
1663 '[url=https://www.youtube.com/watch?v=$1]https://www.youtube.com/watch?v=$1[/url]', $bbcode);
1664 $bbcode = preg_replace("/\[youtube\](.*?)\[\/youtube\]/ism",'[url=$1]$1[/url]',$bbcode);
1666 $Text = preg_replace("/\[vimeo\]([0-9]+)(.*?)\[\/vimeo\]/ism",
1667 '[url=https://vimeo.com/$1]https://vimeo.com/$1[/url]', $bbcode);
1668 $bbcode = preg_replace("/\[vimeo\](.*?)\[\/vimeo\]/ism",'[url=$1]$1[/url]',$bbcode);
1670 $bbcode = preg_replace("/\[img\=([0-9]*)x([0-9]*)\](.*?)\[\/img\]/ism", '[img]$3[/img]', $bbcode);
1672 //preg_match_all("/\[url\]([$URLSearchString]*)\[\/url\]/ism", $bbcode, $urls1);
1673 preg_match_all("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism", $bbcode, $urls);
1675 $ordered_urls = array();
1676 foreach ($urls[1] AS $id=>$url) {
1677 //$start = strpos($text, $url, $offset);
1678 $start = iconv_strpos($text, $url, 0, "UTF-8");
1679 if (!($start === false))
1680 $ordered_urls[$start] = array("url" => $url, "title" => $urls[2][$id]);
1683 ksort($ordered_urls);
1686 //foreach ($urls[1] AS $id=>$url) {
1687 foreach ($ordered_urls AS $url) {
1688 if ((substr($url["title"], 0, 7) != "http://") AND (substr($url["title"], 0, 8) != "https://") AND
1689 !strpos($url["title"], "http://") AND !strpos($url["title"], "https://"))
1690 $display_url = $url["title"];
1692 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url["url"]);
1693 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1695 if (strlen($display_url) > 26)
1696 $display_url = substr($display_url, 0, 25)."…";
1699 //$start = strpos($text, $url, $offset);
1700 $start = iconv_strpos($text, $url["url"], $offset, "UTF-8");
1701 if (!($start === false)) {
1702 $entities["urls"][] = array("url" => $url["url"],
1703 "expanded_url" => $url["url"],
1704 "display_url" => $display_url,
1705 "indices" => array($start, $start+strlen($url["url"])));
1706 $offset = $start + 1;
1710 preg_match_all("/\[img](.*?)\[\/img\]/ism", $bbcode, $images);
1711 $ordered_images = array();
1712 foreach ($images[1] AS $image) {
1713 //$start = strpos($text, $url, $offset);
1714 $start = iconv_strpos($text, $image, 0, "UTF-8");
1715 if (!($start === false))
1716 $ordered_images[$start] = $image;
1718 //$entities["media"] = array();
1721 foreach ($ordered_images AS $url) {
1722 $display_url = str_replace(array("http://www.", "https://www."), array("", ""), $url);
1723 $display_url = str_replace(array("http://", "https://"), array("", ""), $display_url);
1725 if (strlen($display_url) > 26)
1726 $display_url = substr($display_url, 0, 25)."…";
1728 $start = iconv_strpos($text, $url, $offset, "UTF-8");
1729 if (!($start === false)) {
1731 $img_str = fetch_url($url,true, $redirects, 10);
1732 $image = @imagecreatefromstring($img_str);
1734 $entities["media"][] = array(
1736 "id_str" => (string)$start+1,
1737 "indices" => array($start, $start+strlen($url)),
1738 "media_url" => $url,
1739 "media_url_https" => $url,
1741 "display_url" => $display_url,
1742 "expanded_url" => $url,
1744 "sizes" => array("medium" => array(
1745 "w" => imagesx($image),
1746 "h" => imagesy($image),
1747 "resize" => "fit")));
1749 $offset = $start + 1;
1756 function api_format_items($r,$user_info, $filter_user = false) {
1761 foreach($r as $item) {
1762 api_share_as_retweet($a, api_user(), $item);
1764 localize_item($item);
1765 $status_user = api_item_get_user($a,$item);
1767 // Look if the posts are matching if they should be filtered by user id
1768 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1771 if ($item['thr-parent'] != $item['uri']) {
1772 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1774 dbesc($item['thr-parent']));
1776 $in_reply_to_status_id = intval($r[0]['id']);
1778 $in_reply_to_status_id = intval($item['parent']);
1780 $in_reply_to_status_id_str = (string) intval($item['parent']);
1782 $in_reply_to_screen_name = NULL;
1783 $in_reply_to_user_id = NULL;
1784 $in_reply_to_user_id_str = NULL;
1786 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1788 intval($in_reply_to_status_id));
1790 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1793 if ($r[0]['nick'] == "")
1794 $r[0]['nick'] = api_get_nick($r[0]["url"]);
1796 $in_reply_to_screen_name = (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']);
1797 $in_reply_to_user_id = intval($r[0]['id']);
1798 $in_reply_to_user_id_str = (string) intval($r[0]['id']);
1802 $in_reply_to_screen_name = NULL;
1803 $in_reply_to_user_id = NULL;
1804 $in_reply_to_status_id = NULL;
1805 $in_reply_to_user_id_str = NULL;
1806 $in_reply_to_status_id_str = NULL;
1809 // Workaround for ostatus messages where the title is identically to the body
1810 //$statusbody = trim(html2plain(bbcode(api_clean_plain_items($item['body']), false, false, 5, true), 0));
1811 $html = bbcode(api_clean_plain_items($item['body']), false, false, 2, true);
1812 $statusbody = trim(html2plain($html, 0));
1814 $statustitle = trim($item['title']);
1816 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1817 $statustext = trim($statusbody);
1819 $statustext = trim($statustitle."\n\n".$statusbody);
1821 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1822 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1825 'text' => $statustext,
1826 'truncated' => False,
1827 'created_at'=> api_date($item['created']),
1828 'in_reply_to_status_id' => $in_reply_to_status_id,
1829 'in_reply_to_status_id_str' => $in_reply_to_status_id,
1830 'source' => (($item['app']) ? $item['app'] : 'web'),
1831 'id' => intval($item['id']),
1832 'id_str' => (string) intval($item['id']),
1833 'in_reply_to_user_id' => $in_reply_to_user_id,
1834 'in_reply_to_user_id_str' => $in_reply_to_user_id,
1835 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1837 'favorited' => $item['starred'] ? true : false,
1838 //'attachments' => array(),
1839 'user' => $status_user ,
1840 //'entities' => NULL,
1841 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1842 'statusnet_conversation_id' => $item['parent'],
1845 $entities = api_get_entitities($status['text'], $item['body']);
1846 if (count($entities) > 0)
1847 $status['entities'] = $entities;
1849 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1850 $status["source"] = network_to_name($item['item_network']);
1851 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1852 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1855 // Retweets are only valid for top postings
1856 // It doesn't work reliable with the link if its a feed
1857 $IsRetweet = ($item['owner-link'] != $item['author-link']);
1859 $IsRetweet = (($item['owner-name'] != $item['author-name']) OR ($item['owner-avatar'] != $item['author-avatar']));
1861 if ($IsRetweet AND ($item["id"] == $item["parent"])) {
1862 $retweeted_status = $status;
1863 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1865 $status["retweeted_status"] = $retweeted_status;
1868 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1869 unset($status["user"]["uid"]);
1870 unset($status["user"]["self"]);
1872 // 'geo' => array('type' => 'Point',
1873 // 'coordinates' => array((float) $notice->lat,
1874 // (float) $notice->lon));
1876 // Seesmic doesn't like the following content
1877 // completely disabled to make friendica totally compatible to the statusnet API
1878 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1880 'updated' => api_date($item['edited']),
1881 'published' => api_date($item['created']),
1882 'message_id' => $item['uri'],
1883 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1884 'coordinates' => $item['coord'],
1885 'place' => $item['location'],
1886 'contributors' => '',
1887 'annotations' => '',
1889 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1890 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1891 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1892 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1895 $status = array_merge($status, $status2);
1904 function api_account_rate_limit_status(&$a,$type) {
1907 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1908 'remaining_hits' => (string) 150,
1909 'hourly_limit' => (string) 150,
1910 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1913 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1915 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1918 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1920 function api_help_test(&$a,$type) {
1927 return api_apply_template('test', $type, array("$ok" => $ok));
1930 api_register_func('api/help/test','api_help_test',false);
1932 function api_lists(&$a,$type) {
1937 api_register_func('api/lists','api_lists',true);
1939 function api_lists_list(&$a,$type) {
1944 api_register_func('api/lists/list','api_lists_list',true);
1947 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1948 * This function is deprecated by Twitter
1949 * returns: json, xml
1951 function api_statuses_f(&$a, $type, $qtype) {
1952 if (api_user()===false) return false;
1953 $user_info = api_get_user($a);
1955 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1956 /* this is to stop Hotot to load friends multiple times
1957 * I'm not sure if I'm missing return something or
1958 * is a bug in hotot. Workaround, meantime
1962 return array('$users' => $ret);*/
1966 if($qtype == 'friends')
1967 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1968 if($qtype == 'followers')
1969 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1971 // friends and followers only for self
1972 if ($user_info['self'] == 0)
1973 $sql_extra = " AND false ";
1975 $r = q("SELECT `nurl` FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1980 foreach($r as $cid){
1981 $user = api_get_user($a, $cid['nurl']);
1982 // "uid" and "self" are only needed for some internal stuff, so remove it from here
1983 unset($user["uid"]);
1984 unset($user["self"]);
1990 return array('$users' => $ret);
1993 function api_statuses_friends(&$a, $type){
1994 $data = api_statuses_f($a,$type,"friends");
1995 if ($data===false) return false;
1996 return api_apply_template("friends", $type, $data);
1998 function api_statuses_followers(&$a, $type){
1999 $data = api_statuses_f($a,$type,"followers");
2000 if ($data===false) return false;
2001 return api_apply_template("friends", $type, $data);
2003 api_register_func('api/statuses/friends','api_statuses_friends',true);
2004 api_register_func('api/statuses/followers','api_statuses_followers',true);
2011 function api_statusnet_config(&$a,$type) {
2012 $name = $a->config['sitename'];
2013 $server = $a->get_hostname();
2014 $logo = $a->get_baseurl() . '/images/friendica-64.png';
2015 $email = $a->config['admin_email'];
2016 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
2017 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
2018 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
2019 if($a->config['api_import_size'])
2020 $texlimit = string($a->config['api_import_size']);
2021 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
2022 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
2025 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
2026 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
2027 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
2028 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
2029 'shorturllength' => '30',
2030 'friendica' => array(
2031 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
2032 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
2033 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
2034 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
2039 return api_apply_template('config', $type, array('$config' => $config));
2042 api_register_func('api/statusnet/config','api_statusnet_config',false);
2044 function api_statusnet_version(&$a,$type) {
2048 if($type === 'xml') {
2049 header("Content-type: application/xml");
2050 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
2053 elseif($type === 'json') {
2054 header("Content-type: application/json");
2059 api_register_func('api/statusnet/version','api_statusnet_version',false);
2062 function api_ff_ids(&$a,$type,$qtype) {
2066 $user_info = api_get_user($a);
2068 if($qtype == 'friends')
2069 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
2070 if($qtype == 'followers')
2071 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
2073 if (!$user_info["self"])
2074 $sql_extra = " AND false ";
2076 $stringify_ids = (x($_REQUEST,'stringify_ids')?$_REQUEST['stringify_ids']:false);
2078 $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",
2084 if($type === 'xml') {
2085 header("Content-type: application/xml");
2086 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
2088 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
2089 echo '</ids>' . "\r\n";
2092 elseif($type === 'json') {
2094 header("Content-type: application/json");
2099 $ret[] = intval($rr['id']);
2101 echo json_encode($ret);
2107 function api_friends_ids(&$a,$type) {
2108 api_ff_ids($a,$type,'friends');
2110 function api_followers_ids(&$a,$type) {
2111 api_ff_ids($a,$type,'followers');
2113 api_register_func('api/friends/ids','api_friends_ids',true);
2114 api_register_func('api/followers/ids','api_followers_ids',true);
2117 function api_direct_messages_new(&$a, $type) {
2118 if (api_user()===false) return false;
2120 if (!x($_POST, "text") OR (!x($_POST,"screen_name") AND !x($_POST,"user_id"))) return;
2122 $sender = api_get_user($a);
2124 require_once("include/message.php");
2126 if ($_POST['screen_name']) {
2127 $r = q("SELECT `id`, `nurl`, `network` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
2129 dbesc($_POST['screen_name']));
2131 // Selecting the id by priority, friendica first
2132 api_best_nickname($r);
2134 $recipient = api_get_user($a, $r[0]['nurl']);
2136 $recipient = api_get_user($a, $_POST['user_id']);
2140 if (x($_REQUEST,'replyto')) {
2141 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
2143 intval($_REQUEST['replyto']));
2144 $replyto = $r[0]['parent-uri'];
2145 $sub = $r[0]['title'];
2148 if (x($_REQUEST,'title')) {
2149 $sub = $_REQUEST['title'];
2152 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
2156 $id = send_message($recipient['cid'], $_POST['text'], $sub, $replyto);
2159 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
2160 $ret = api_format_messages($r[0], $recipient, $sender);
2163 $ret = array("error"=>$id);
2166 $data = Array('$messages'=>$ret);
2171 $data = api_rss_extra($a, $data, $user_info);
2174 return api_apply_template("direct_messages", $type, $data);
2177 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
2179 function api_direct_messages_box(&$a, $type, $box) {
2180 if (api_user()===false) return false;
2182 unset($_REQUEST["user_id"]);
2183 unset($_GET["user_id"]);
2185 unset($_REQUEST["screen_name"]);
2186 unset($_GET["screen_name"]);
2188 $user_info = api_get_user($a);
2191 $count = (x($_GET,'count')?$_GET['count']:20);
2192 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
2193 if ($page<0) $page=0;
2195 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
2196 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
2198 $start = $page*$count;
2200 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
2201 $profile_url = $user_info["url"];
2203 if ($box=="sentbox") {
2204 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
2206 elseif ($box=="conversation") {
2207 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
2209 elseif ($box=="all") {
2210 $sql_extra = "true";
2212 elseif ($box=="inbox") {
2213 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
2217 $sql_extra .= ' AND `mail`.`id` <= '.intval($max_id);
2219 $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",
2222 intval($start), intval($count)
2226 foreach($r as $item) {
2227 if ($box == "inbox" || $item['from-url'] != $profile_url){
2228 $recipient = $user_info;
2229 $sender = api_get_user($a,normalise_link($item['contact-url']));
2231 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
2232 $recipient = api_get_user($a,normalise_link($item['contact-url']));
2233 $sender = $user_info;
2237 $ret[]=api_format_messages($item, $recipient, $sender);
2241 $data = array('$messages' => $ret);
2245 $data = api_rss_extra($a, $data, $user_info);
2248 return api_apply_template("direct_messages", $type, $data);
2252 function api_direct_messages_sentbox(&$a, $type){
2253 return api_direct_messages_box($a, $type, "sentbox");
2255 function api_direct_messages_inbox(&$a, $type){
2256 return api_direct_messages_box($a, $type, "inbox");
2258 function api_direct_messages_all(&$a, $type){
2259 return api_direct_messages_box($a, $type, "all");
2261 function api_direct_messages_conversation(&$a, $type){
2262 return api_direct_messages_box($a, $type, "conversation");
2264 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
2265 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
2266 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
2267 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
2271 function api_oauth_request_token(&$a, $type){
2273 $oauth = new FKOAuth1();
2274 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
2275 }catch(Exception $e){
2276 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2281 function api_oauth_access_token(&$a, $type){
2283 $oauth = new FKOAuth1();
2284 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
2285 }catch(Exception $e){
2286 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
2292 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
2293 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
2295 function api_share_as_retweet($a, $uid, &$item) {
2296 $body = trim($item["body"]);
2298 // Skip if it isn't a pure repeated messages
2299 // Does it start with a share?
2300 if (strpos($body, "[share") > 0)
2303 // Does it end with a share?
2304 if (strlen($body) > (strrpos($body, "[/share]") + 8))
2307 $attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
2308 // Skip if there is no shared message in there
2309 if ($body == $attributes)
2313 preg_match("/author='(.*?)'/ism", $attributes, $matches);
2314 if ($matches[1] != "")
2315 $author = html_entity_decode($matches[1],ENT_QUOTES,'UTF-8');
2317 preg_match('/author="(.*?)"/ism', $attributes, $matches);
2318 if ($matches[1] != "")
2319 $author = $matches[1];
2322 preg_match("/profile='(.*?)'/ism", $attributes, $matches);
2323 if ($matches[1] != "")
2324 $profile = $matches[1];
2326 preg_match('/profile="(.*?)"/ism', $attributes, $matches);
2327 if ($matches[1] != "")
2328 $profile = $matches[1];
2331 preg_match("/avatar='(.*?)'/ism", $attributes, $matches);
2332 if ($matches[1] != "")
2333 $avatar = $matches[1];
2335 preg_match('/avatar="(.*?)"/ism', $attributes, $matches);
2336 if ($matches[1] != "")
2337 $avatar = $matches[1];
2339 $shared_body = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$2",$body);
2341 if (($shared_body == "") OR ($profile == "") OR ($author == "") OR ($avatar == ""))
2344 $item["body"] = $shared_body;
2345 $item["author-name"] = $author;
2346 $item["author-link"] = $profile;
2347 $item["author-avatar"] = $avatar;
2353 function api_get_nick($profile) {
2355 - remove trailing jung from profile url
2356 - pump.io check has to check the website
2361 $friendica = preg_replace("=https?://(.*)/profile/(.*)=ism", "$2", $profile);
2362 if ($friendica != $profile)
2366 $diaspora = preg_replace("=https?://(.*)/u/(.*)=ism", "$2", $profile);
2367 if ($diaspora != $profile)
2372 $twitter = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $profile);
2373 if ($twitter != $profile)
2379 $StatusnetHost = preg_replace("=https?://(.*)/user/(.*)=ism", "$1", $profile);
2380 if ($StatusnetHost != $profile) {
2381 $StatusnetUser = preg_replace("=https?://(.*)/user/(.*)=ism", "$2", $profile);
2382 if ($StatusnetUser != $profile) {
2383 $UserData = fetch_url("http://".$StatusnetHost."/api/users/show.json?user_id=".$StatusnetUser);
2384 $user = json_decode($UserData);
2386 $nick = $user->screen_name;
2391 // To-Do: look at the page if its really a pumpio site
2392 //if (!$nick == "") {
2393 // $pumpio = preg_replace("=https?://(.*)/(.*)/=ism", "$2", $profile."/");
2394 // if ($pumpio != $profile)
2396 // <div class="media" id="profile-block" data-profile-id="acct:kabniel@microca.st">
2401 q("UPDATE unique_contacts SET nick = '%s' WHERE url = '%s'",
2402 dbesc($nick), dbesc(normalise_link($profile)));
2409 function api_clean_plain_items($Text) {
2410 $include_entities = strtolower(x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:"false");
2412 $Text = bb_CleanPictureLinks($Text);
2414 if ($include_entities == "true") {
2415 $URLSearchString = "^\[\]";
2417 $Text = preg_replace("/#\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'#$2',$Text);
2418 $Text = preg_replace("/\[url\=([$URLSearchString]*)\](.*?)\[\/url\]/ism",'[url=$1]$1[/url]',$Text);
2421 $Text = preg_replace_callback("((.*?)\[class=(.*?)\](.*?)\[\/class\])ism","api_cleanup_share",$Text);
2425 function api_cleanup_share($shared) {
2426 if ($shared[2] != "type-link")
2429 if (!preg_match_all("/\[bookmark\=([^\]]*)\](.*?)\[\/bookmark\]/ism",$shared[3], $bookmark))
2435 if (isset($bookmark[2][0]))
2436 $title = $bookmark[2][0];
2438 if (isset($bookmark[1][0]))
2439 $link = $bookmark[1][0];
2441 if (strpos($shared[1],$title) !== false)
2444 if (strpos($shared[1],$link) !== false)
2447 $text = trim($shared[1]);
2449 //if (strlen($text) < strlen($title))
2450 if (($text == "") AND ($title != ""))
2451 $text .= "\n\n".trim($title);
2454 $text .= "\n".trim($link);
2456 return(trim($text));
2459 function api_best_nickname(&$contacts) {
2460 $best_contact = array();
2462 if (count($contact) == 0)
2465 foreach ($contacts AS $contact)
2466 if ($contact["network"] == "") {
2467 $contact["network"] = "dfrn";
2468 $best_contact = array($contact);
2471 if (sizeof($best_contact) == 0)
2472 foreach ($contacts AS $contact)
2473 if ($contact["network"] == "dfrn")
2474 $best_contact = array($contact);
2476 if (sizeof($best_contact) == 0)
2477 foreach ($contacts AS $contact)
2478 if ($contact["network"] == "dspr")
2479 $best_contact = array($contact);
2481 if (sizeof($best_contact) == 0)
2482 foreach ($contacts AS $contact)
2483 if ($contact["network"] == "stat")
2484 $best_contact = array($contact);
2486 if (sizeof($best_contact) == 0)
2487 foreach ($contacts AS $contact)
2488 if ($contact["network"] == "pump")
2489 $best_contact = array($contact);
2491 if (sizeof($best_contact) == 0)
2492 foreach ($contacts AS $contact)
2493 if ($contact["network"] == "twit")
2494 $best_contact = array($contact);
2496 if (sizeof($best_contact) == 1)
2497 $contacts = $best_contact;
2499 $contacts = array($contacts[0]);
2503 Not implemented by now:
2507 statuses/retweets_of_me
2512 account/update_location
2513 account/update_profile_background_image
2514 account/update_profile_image
2518 Not implemented in status.net:
2519 statuses/retweeted_to_me
2520 statuses/retweeted_by_me
2521 direct_messages/destroy
2523 account/update_delivery_device
2524 notifications/follow