2 require_once("include/bbcode.php");
3 require_once("include/datetime.php");
4 require_once("include/conversation.php");
5 require_once("include/oauth.php");
6 require_once("include/html2plain.php");
16 // It is not sufficient to use local_user() to check whether someone is allowed to use the API,
17 // because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
18 // into a page, and visitors will post something without noticing it).
19 // Instead, use this function.
20 if ($_SESSION["allow_api"])
26 function api_date($str){
27 //Wed May 23 06:01:13 +0000 2007
28 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
32 function api_register_func($path, $func, $auth=false){
34 $API[$path] = array('func'=>$func,
42 function api_login(&$a){
45 $oauth = new FKOAuth1();
46 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
47 if (!is_null($token)){
48 $oauth->loginUser($token->uid);
49 call_hooks('logged_in', $a->user);
52 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
54 logger(__file__.__line__.__function__."\n".$e);
55 //die(__file__.__line__.__function__."<pre>".$e); die();
60 // workaround for HTTP-auth in CGI mode
61 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
62 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
63 if(strlen($userpass)) {
64 list($name, $password) = explode(':', $userpass);
65 $_SERVER['PHP_AUTH_USER'] = $name;
66 $_SERVER['PHP_AUTH_PW'] = $password;
70 if (!isset($_SERVER['PHP_AUTH_USER'])) {
71 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
72 header('WWW-Authenticate: Basic realm="Friendica"');
73 header('HTTP/1.0 401 Unauthorized');
74 die((api_error(&$a, 'json', "This api requires login")));
76 //die('This api requires login');
79 $user = $_SERVER['PHP_AUTH_USER'];
80 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
84 * next code from mod/auth.php. needs better solution
87 // process normal login request
89 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
90 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `account_removed` = 0 AND `verified` = 1 LIMIT 1",
98 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
99 header('WWW-Authenticate: Basic realm="Friendica"');
100 header('HTTP/1.0 401 Unauthorized');
101 die('This api requires login');
104 require_once('include/security.php');
105 authenticate_success($record); $_SESSION["allow_api"] = true;
107 call_hooks('logged_in', $a->user);
111 /**************************
112 * MAIN API ENTRY POINT *
113 **************************/
114 function api_call(&$a){
115 GLOBAL $API, $called_api;
120 foreach ($API as $p=>$info){
121 if (strpos($a->query_string, $p)===0){
122 $called_api= explode("/",$p);
123 //unset($_SERVER['PHP_AUTH_USER']);
124 if ($info['auth']===true && api_user()===false) {
128 load_contact_links(api_user());
130 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
131 logger('API parameters: ' . print_r($_REQUEST,true));
133 if (strpos($a->query_string, ".xml")>0) $type="xml";
134 if (strpos($a->query_string, ".json")>0) $type="json";
135 if (strpos($a->query_string, ".rss")>0) $type="rss";
136 if (strpos($a->query_string, ".atom")>0) $type="atom";
137 if (strpos($a->query_string, ".as")>0) $type="as";
139 $r = call_user_func($info['func'], $a, $type);
140 if ($r===false) return;
144 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
145 header ("Content-Type: text/xml");
146 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
149 header ("Content-Type: application/json");
151 return json_encode($rr);
154 header ("Content-Type: application/rss+xml");
155 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
158 header ("Content-Type: application/atom+xml");
159 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
162 //header ("Content-Type: application/json");
164 // return json_encode($rr);
165 return json_encode($r);
169 //echo "<pre>"; var_dump($r); die();
172 header("HTTP/1.1 404 Not Found");
173 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
174 return(api_error(&$a, $type, "not implemented"));
178 function api_error(&$a, $type, $error) {
179 $r = "<status><error>".$error."</error><request>".$a->query_string."</request></status>";
182 header ("Content-Type: text/xml");
183 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
186 header ("Content-Type: application/json");
187 return json_encode(array('error' => $error, 'request' => $a->query_string));
190 header ("Content-Type: application/rss+xml");
191 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
194 header ("Content-Type: application/atom+xml");
195 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
203 function api_rss_extra(&$a, $arr, $user_info){
204 if (is_null($user_info)) $user_info = api_get_user($a);
205 $arr['$user'] = $user_info;
206 $arr['$rss'] = array(
207 'alternate' => $user_info['url'],
208 'self' => $a->get_baseurl(). "/". $a->query_string,
209 'base' => $a->get_baseurl(),
210 'updated' => api_date(null),
211 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
212 'language' => $user_info['language'],
213 'logo' => $a->get_baseurl()."/images/friendica-32.png",
221 * Unique contact to contact url.
223 function api_unique_id_to_url($id){
224 $r = q("SELECT url FROM unique_contacts WHERE id=%d LIMIT 1",
227 return ($r[0]["url"]);
233 * Returns user info array.
235 function api_get_user(&$a, $contact_id = Null, $type = "json"){
242 // Searching for contact URL
243 if(!is_null($contact_id) AND (intval($contact_id) == 0)){
244 $user = dbesc(normalise_link($contact_id));
246 $extra_query = "AND `contact`.`nurl` = '%s' ";
247 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
250 // Searching for unique contact id
251 if(!is_null($contact_id) AND (intval($contact_id) != 0)){
252 $user = dbesc(api_unique_id_to_url($contact_id));
255 die(api_error($a, $type, t("User not found.")));
258 $extra_query = "AND `contact`.`nurl` = '%s' ";
259 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
262 if(is_null($user) && x($_GET, 'user_id')) {
263 $user = dbesc(api_unique_id_to_url($_GET['user_id']));
266 die(api_error($a, $type, t("User not found.")));
269 $extra_query = "AND `contact`.`nurl` = '%s' ";
270 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
272 if(is_null($user) && x($_GET, 'screen_name')) {
273 $user = dbesc($_GET['screen_name']);
275 $extra_query = "AND `contact`.`nick` = '%s' ";
276 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
279 if (is_null($user) && $a->argc > (count($called_api)-1)){
280 $argid = count($called_api);
281 list($user, $null) = explode(".",$a->argv[$argid]);
282 if(is_numeric($user)){
283 $user = dbesc(api_unique_id_to_url($user));
289 $extra_query = "AND `contact`.`nurl` = '%s' ";
290 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
292 $user = dbesc($user);
294 $extra_query = "AND `contact`.`nick` = '%s' ";
295 if (api_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(api_user());
300 if (api_user()===false) {
301 api_login($a); return False;
303 $user = $_SESSION['uid'];
304 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
309 logger('api_user: ' . $extra_query . ', user: ' . $user);
311 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
317 // if the contact wasn't found, fetch it from the unique contacts
318 if (count($uinfo)==0) {
322 $r = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1", $url);
324 $r = q("SELECT * FROM unique_contacts WHERE nick='%s' LIMIT 1", $nick);
329 'name' => $r[0]["name"],
330 'screen_name' => (($r[0]['nick']) ? $r[0]['nick'] : $r[0]['name']),
332 'description' => NULL,
333 'profile_image_url' => $r[0]["avatar"],
334 'profile_image_url_https' => $r[0]["avatar"],
335 'url' => $r[0]["url"],
336 'protected' => false,
337 'followers_count' => 0,
338 'friends_count' => 0,
339 'created_at' => api_date(0),
340 'favourites_count' => 0,
342 'time_zone' => 'UTC',
343 'statuses_count' => 0,
344 'following' => false,
346 'statusnet_blocking' => false,
347 'notifications' => false,
348 'statusnet_profile_url' => $r[0]["url"],
356 die(api_error($a, $type, t("User not found.")));
360 if($uinfo[0]['self']) {
361 $usr = q("select * from user where uid = %d limit 1",
364 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
368 // count public wall messages
369 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
372 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
373 intval($uinfo[0]['uid'])
375 $countitms = $r[0]['count'];
378 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
379 WHERE `contact-id` = %d
380 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
381 intval($uinfo[0]['id'])
383 $countitms = $r[0]['count'];
387 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
388 WHERE `uid` = %d AND `rel` IN ( %d, %d )
389 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
390 intval($uinfo[0]['uid']),
391 intval(CONTACT_IS_SHARING),
392 intval(CONTACT_IS_FRIEND)
394 $countfriends = $r[0]['count'];
396 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
397 WHERE `uid` = %d AND `rel` IN ( %d, %d )
398 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
399 intval($uinfo[0]['uid']),
400 intval(CONTACT_IS_FOLLOWER),
401 intval(CONTACT_IS_FRIEND)
403 $countfollowers = $r[0]['count'];
405 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
406 intval($uinfo[0]['uid'])
408 $starred = $r[0]['count'];
411 if(! $uinfo[0]['self']) {
417 // Fetching unique id
418 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
420 // If not there, then add it
421 if (count($r) == 0) {
422 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
423 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
425 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
429 'id' => intval($r[0]['id']),
430 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
431 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
432 'location' => ($usr) ? $usr[0]['default-location'] : NULL,
433 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
434 'profile_image_url' => $uinfo[0]['micro'],
435 'profile_image_url_https' => $uinfo[0]['micro'],
436 'url' => $uinfo[0]['url'],
437 'protected' => false,
438 'followers_count' => intval($countfollowers),
439 'friends_count' => intval($countfriends),
440 'created_at' => api_date($uinfo[0]['name-date']),
441 'favourites_count' => intval($starred),
442 'utc_offset' => "0", // To-Do
443 'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
444 'statuses_count' => intval($countitms),
445 'following' => true, //#XXX: fix me
446 'verified' => true, //#XXX: fix me
447 'statusnet_blocking' => false,
448 'notifications' => false,
449 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
450 'uid' => intval($uinfo[0]['uid']),
451 'cid' => intval($uinfo[0]['cid']),
452 'self' => $uinfo[0]['self'],
459 function api_item_get_user(&$a, $item) {
461 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
462 dbesc(normalise_link($item['author-link'])));
464 if (count($author) == 0) {
465 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
466 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
468 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
469 dbesc(normalise_link($item['author-link'])));
470 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
471 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
472 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
475 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
476 dbesc(normalise_link($item['owner-link'])));
478 if (count($owner) == 0) {
479 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
480 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
482 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
483 dbesc(normalise_link($item['owner-link'])));
484 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
485 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
486 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
489 // Comments in threads may appear as wall-to-wall postings.
490 // So only take the owner at the top posting.
491 if ($item["id"] == $item["parent"])
492 return api_get_user($a,$item["owner-link"]);
494 return api_get_user($a,$item["author-link"]);
499 * load api $templatename for $type and replace $data array
501 function api_apply_template($templatename, $type, $data){
509 $data = array_xmlify($data);
510 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
512 header ("Content-Type: text/xml");
513 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
516 $ret = replace_macros($tpl, $data);
530 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
531 * returns a 401 status code and an error message if not.
532 * http://developer.twitter.com/doc/get/account/verify_credentials
534 function api_account_verify_credentials(&$a, $type){
535 if (api_user()===false) return false;
536 $user_info = api_get_user($a);
538 // "verified" isn't used here in the standard
539 unset($user_info["verified"]);
541 // - Adding last status
542 $user_info["status"] = api_status_show($a,"raw");
543 unset($user_info["status"]["user"]);
545 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
546 unset($user_info["cid"]);
547 unset($user_info["uid"]);
548 unset($user_info["self"]);
550 return api_apply_template("user", $type, array('$user' => $user_info));
553 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
557 * get data from $_POST or $_GET
559 function requestdata($k){
560 if (isset($_POST[$k])){
563 if (isset($_GET[$k])){
569 /*Waitman Gobble Mod*/
570 function api_statuses_mediap(&$a, $type) {
571 if (api_user()===false) {
572 logger('api_statuses_update: no user');
575 $user_info = api_get_user($a);
577 $_REQUEST['type'] = 'wall';
578 $_REQUEST['profile_uid'] = api_user();
579 $_REQUEST['api_source'] = true;
580 $txt = requestdata('status');
581 //$txt = urldecode(requestdata('status'));
583 require_once('library/HTMLPurifier.auto.php');
584 require_once('include/html2bbcode.php');
586 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
587 $txt = html2bb_video($txt);
588 $config = HTMLPurifier_Config::createDefault();
589 $config->set('Cache.DefinitionImpl', null);
590 $purifier = new HTMLPurifier($config);
591 $txt = $purifier->purify($txt);
593 $txt = html2bbcode($txt);
595 $a->argv[1]=$user_info['screen_name']; //should be set to username?
597 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
598 require_once('mod/wall_upload.php');
599 $bebop = wall_upload_post($a);
601 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
602 $_REQUEST['body']=$txt."\n\n".$bebop;
603 require_once('mod/item.php');
606 // this should output the last post (the one we just posted).
607 return api_status_show($a,$type);
609 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
610 /*Waitman Gobble Mod*/
613 function api_statuses_update(&$a, $type) {
614 if (api_user()===false) {
615 logger('api_statuses_update: no user');
618 $user_info = api_get_user($a);
620 // convert $_POST array items to the form we use for web posts.
622 // logger('api_post: ' . print_r($_POST,true));
624 if(requestdata('htmlstatus')) {
625 require_once('library/HTMLPurifier.auto.php');
626 require_once('include/html2bbcode.php');
628 $txt = requestdata('htmlstatus');
629 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
631 $txt = html2bb_video($txt);
633 $config = HTMLPurifier_Config::createDefault();
634 $config->set('Cache.DefinitionImpl', null);
637 $purifier = new HTMLPurifier($config);
638 $txt = $purifier->purify($txt);
640 $_REQUEST['body'] = html2bbcode($txt);
645 $_REQUEST['body'] = requestdata('status');
647 $_REQUEST['title'] = requestdata('title');
649 $parent = requestdata('in_reply_to_status_id');
650 if(ctype_digit($parent))
651 $_REQUEST['parent'] = $parent;
653 $_REQUEST['parent_uri'] = $parent;
655 if(requestdata('lat') && requestdata('long'))
656 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
657 $_REQUEST['profile_uid'] = api_user();
660 $_REQUEST['type'] = 'net-comment';
662 $_REQUEST['type'] = 'wall';
663 if(x($_FILES,'media')) {
664 // upload the image if we have one
665 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
666 require_once('mod/wall_upload.php');
667 $media = wall_upload_post($a);
669 $_REQUEST['body'] .= "\n\n".$media;
673 // set this so that the item_post() function is quiet and doesn't redirect or emit json
675 $_REQUEST['api_source'] = true;
677 // call out normal post function
679 require_once('mod/item.php');
682 // this should output the last post (the one we just posted).
683 return api_status_show($a,$type);
685 api_register_func('api/statuses/update','api_statuses_update', true);
688 function api_status_show(&$a, $type){
689 $user_info = api_get_user($a);
690 // get last public wall message
691 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
692 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
693 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
694 AND `i`.`id` = `item`.`parent`
695 AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
696 AND `item`.`type`!='activity'
697 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
698 ORDER BY `item`.`created` DESC
700 intval($user_info['cid']),
701 dbesc($user_info['url'])
704 if (count($lastwall)>0){
705 $lastwall = $lastwall[0];
707 $in_reply_to_status_id = NULL;
708 $in_reply_to_user_id = NULL;
709 $in_reply_to_screen_name = NULL;
710 if ($lastwall['parent']!=$lastwall['id']) {
711 $in_reply_to_status_id=$lastwall['parent'];
712 //$in_reply_to_user_id = $lastwall['reply_uid'];
713 //$in_reply_to_screen_name = $lastwall['reply_author'];
715 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
717 $in_reply_to_screen_name = $r[0]['name'];
718 $in_reply_to_user_id = $r[0]['id'];
721 $status_info = array(
722 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
723 'truncated' => false,
724 'created_at' => api_date($lastwall['created']),
725 'in_reply_to_status_id' => $in_reply_to_status_id,
726 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
727 'id' => $lastwall['id'],
728 'in_reply_to_user_id' => $in_reply_to_user_id,
729 'in_reply_to_screen_name' => $in_reply_to_screen_name,
731 'favorited' => false,
733 'user' => $user_info,
734 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
735 'statusnet_conversation_id' => $lastwall['parent'],
738 if (($lastwall['item_network'] != "") AND ($status["source"] == 'web'))
739 $status_info["source"] = network_to_name($lastwall['item_network']);
740 elseif (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $status_info["source"]))
741 $status_info["source"] = trim($status_info["source"].' ('.network_to_name($lastwall['item_network']).')');
743 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
744 unset($status_info["user"]["cid"]);
745 unset($status_info["user"]["uid"]);
746 unset($status_info["user"]["self"]);
750 return($status_info);
752 return api_apply_template("status", $type, array('$status' => $status_info));
761 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
762 * The author's most recent status will be returned inline.
763 * http://developer.twitter.com/doc/get/users/show
765 function api_users_show(&$a, $type){
766 $user_info = api_get_user($a);
768 $lastwall = q("SELECT `item`.*
769 FROM `item`, `contact`
770 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
771 AND `contact`.`id`=`item`.`contact-id`
772 AND `type`!='activity'
773 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
774 ORDER BY `created` DESC
776 intval($user_info['cid']),
777 dbesc($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_screen_name = NULL;
786 if ($lastwall['parent']!=$lastwall['id']) {
787 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
788 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
789 if (count($reply)>0) {
790 $in_reply_to_status_id=$lastwall['parent'];
791 //$in_reply_to_user_id = $reply[0]['reply_uid'];
792 //$in_reply_to_screen_name = $reply[0]['reply_author'];
793 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
795 $in_reply_to_screen_name = $r[0]['name'];
796 $in_reply_to_user_id = $r[0]['id'];
800 $user_info['status'] = array(
801 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
802 'truncated' => false,
803 'created_at' => api_date($lastwall['created']),
804 'in_reply_to_status_id' => $in_reply_to_status_id,
805 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
806 'id' => $lastwall['contact-id'],
807 'in_reply_to_user_id' => $in_reply_to_user_id,
808 'in_reply_to_screen_name' => $in_reply_to_screen_name,
810 'favorited' => false,
811 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
812 'statusnet_conversation_id' => $lastwall['parent'],
815 if (($lastwall['item_network'] != "") AND ($user_info["status"]["source"] == 'web'))
816 $user_info["status"]["source"] = network_to_name($lastwall['item_network']);
817 if (($lastwall['item_network'] != "") AND (network_to_name($lastwall['item_network']) != $user_info["status"]["source"]))
818 $user_info["status"]["source"] = trim($user_info["status"]["source"].' ('.network_to_name($lastwall['item_network']).')');
822 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
823 unset($user_info["cid"]);
824 unset($user_info["uid"]);
825 unset($user_info["self"]);
827 return api_apply_template("user", $type, array('$user' => $user_info));
830 api_register_func('api/users/show','api_users_show');
834 * http://developer.twitter.com/doc/get/statuses/home_timeline
836 * TODO: Optional parameters
837 * TODO: Add reply info
839 function api_statuses_home_timeline(&$a, $type){
840 if (api_user()===false) return false;
842 $user_info = api_get_user($a);
843 // get last newtork messages
847 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
848 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
849 if ($page<0) $page=0;
850 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
851 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
852 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
853 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
854 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
856 $start = $page*$count;
858 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
862 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
863 if ($exclude_replies > 0)
864 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
865 if ($conversation_id > 0)
866 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
868 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
869 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
870 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
871 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
872 FROM `item`, `contact`
873 WHERE `item`.`uid` = %d
874 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
875 AND `contact`.`id` = `item`.`contact-id`
876 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
879 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
880 //intval($user_info['uid']),
883 intval($start), intval($count)
886 $ret = api_format_items($r,$user_info);
888 // We aren't going to try to figure out at the item, group, and page
889 // level which items you've seen and which you haven't. If you're looking
890 // at the network timeline just mark everything seen.
892 $r = q("UPDATE `item` SET `unseen` = 0
893 WHERE `unseen` = 1 AND `uid` = %d",
894 //intval($user_info['uid'])
899 $data = array('$statuses' => $ret);
903 $data = api_rss_extra($a, $data, $user_info);
906 $as = api_format_as($a, $ret, $user_info);
907 $as['title'] = $a->config['sitename']." Home Timeline";
908 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
913 return api_apply_template("timeline", $type, $data);
915 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
916 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
918 function api_statuses_public_timeline(&$a, $type){
919 if (api_user()===false) return false;
921 $user_info = api_get_user($a);
922 // get last newtork messages
926 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
927 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
928 if ($page<0) $page=0;
929 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
930 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
931 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
932 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
933 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
935 $start = $page*$count;
937 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
940 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
941 if ($exclude_replies > 0)
942 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
943 if ($conversation_id > 0)
944 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
946 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
947 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
948 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
949 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
950 `user`.`nickname`, `user`.`hidewall`
951 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
952 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
953 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
954 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
955 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
956 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
957 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
960 ORDER BY `received` DESC LIMIT %d, %d ",
965 $ret = api_format_items($r,$user_info);
968 $data = array('$statuses' => $ret);
972 $data = api_rss_extra($a, $data, $user_info);
975 $as = api_format_as($a, $ret, $user_info);
976 $as['title'] = $a->config['sitename']." Public Timeline";
977 $as['link']['url'] = $a->get_baseurl()."/";
982 return api_apply_template("timeline", $type, $data);
984 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
989 function api_statuses_show(&$a, $type){
990 if (api_user()===false) return false;
992 $user_info = api_get_user($a);
995 $id = intval($a->argv[3]);
998 $id = intval($_REQUEST["id"]);
1000 logger('API: api_statuses_show: '.$id);
1002 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1003 $conversation = (x($_REQUEST,'conversation')?1:0);
1007 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
1009 $sql_extra .= " AND `item`.`id` = %d";
1011 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1012 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1013 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1014 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1015 FROM `item`, `contact`
1016 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1017 AND `contact`.`id` = `item`.`contact-id`
1018 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1024 die(api_error($a, $type, t("There is no status with this id.")));
1026 $ret = api_format_items($r,$user_info);
1028 if ($conversation) {
1029 $data = array('$statuses' => $ret);
1030 return api_apply_template("timeline", $type, $data);
1032 $data = array('$status' => $ret[0]);
1036 $data = api_rss_extra($a, $data, $user_info);
1038 return api_apply_template("status", $type, $data);
1041 api_register_func('api/statuses/show','api_statuses_show', true);
1047 function api_statuses_repeat(&$a, $type){
1048 if (api_user()===false) return false;
1050 $user_info = api_get_user($a);
1053 $id = intval($a->argv[3]);
1056 $id = intval($_REQUEST["id"]);
1058 logger('API: api_statuses_repeat: '.$id);
1060 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1062 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`, `contact`.`nick` as `reply_author`,
1063 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1064 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1065 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1066 FROM `item`, `contact`
1067 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1068 AND `contact`.`id` = `item`.`contact-id`
1069 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1071 AND `item`.`id`=%d",
1075 if ($r[0]['body'] != "") {
1076 if (!intval(get_config('system','old_share'))) {
1077 $post = "[share author='".str_replace("'", "'", $r[0]['reply_author']).
1078 "' profile='".$r[0]['reply_url'].
1079 "' avatar='".$r[0]['reply_photo'].
1080 "' link='".$r[0]['plink']."']";
1082 $post .= $r[0]['body'];
1083 $post .= "[/share]";
1084 $_REQUEST['body'] = $post;
1086 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1088 $_REQUEST['profile_uid'] = api_user();
1089 $_REQUEST['type'] = 'wall';
1090 $_REQUEST['api_source'] = true;
1092 require_once('mod/item.php');
1101 return api_apply_template('test', $type, array('$ok' => $ok));
1103 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1108 function api_statuses_destroy(&$a, $type){
1109 if (api_user()===false) return false;
1111 $user_info = api_get_user($a);
1114 $id = intval($a->argv[3]);
1117 $id = intval($_REQUEST["id"]);
1119 logger('API: api_statuses_destroy: '.$id);
1121 require_once('include/items.php');
1122 drop_item($id, false);
1129 return api_apply_template('test', $type, array('$ok' => $ok));
1131 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1135 * http://developer.twitter.com/doc/get/statuses/mentions
1138 function api_statuses_mentions(&$a, $type){
1139 if (api_user()===false) return false;
1141 $user_info = api_get_user($a);
1142 // get last newtork messages
1146 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1147 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1148 if ($page<0) $page=0;
1149 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1150 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1151 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1153 $start = $page*$count;
1155 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1157 // Ugly code - should be changed
1158 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1159 $myurl = substr($myurl,strpos($myurl,'://')+3);
1160 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1161 $myurl = str_replace('www.','',$myurl);
1162 $diasp_url = str_replace('/profile/','/u/',$myurl);
1164 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1165 dbesc(protect_sprintf($myurl)),
1166 dbesc(protect_sprintf($myurl))
1170 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1172 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1173 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1174 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1175 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1176 FROM `item`, `contact`
1177 WHERE `item`.`uid` = %d
1178 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1179 AND `contact`.`id` = `item`.`contact-id`
1180 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1183 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1184 //intval($user_info['uid']),
1187 intval($start), intval($count)
1190 $ret = api_format_items($r,$user_info);
1193 $data = array('$statuses' => $ret);
1197 $data = api_rss_extra($a, $data, $user_info);
1200 $as = api_format_as($a, $ret, $user_info);
1201 $as["title"] = $a->config['sitename']." Mentions";
1202 $as['link']['url'] = $a->get_baseurl()."/";
1207 return api_apply_template("timeline", $type, $data);
1209 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1210 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1213 function api_statuses_user_timeline(&$a, $type){
1214 if (api_user()===false) return false;
1216 $user_info = api_get_user($a);
1217 // get last network messages
1219 logger("api_statuses_user_timeline: api_user: ". api_user() .
1220 "\nuser_info: ".print_r($user_info, true) .
1221 "\n_REQUEST: ".print_r($_REQUEST, true),
1225 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1226 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1227 if ($page<0) $page=0;
1228 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1229 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1230 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1231 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1233 $start = $page*$count;
1236 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1238 if ($exclude_replies > 0)
1239 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1240 if ($conversation_id > 0)
1241 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1243 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1244 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1245 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1246 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1247 FROM `item`, `contact`
1248 WHERE `item`.`uid` = %d
1249 AND `item`.`contact-id` = %d
1250 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1251 AND `contact`.`id` = `item`.`contact-id`
1252 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1255 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1257 intval($user_info['cid']),
1259 intval($start), intval($count)
1262 $ret = api_format_items($r,$user_info, true);
1264 $data = array('$statuses' => $ret);
1268 $data = api_rss_extra($a, $data, $user_info);
1271 return api_apply_template("timeline", $type, $data);
1274 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1277 function api_favorites(&$a, $type){
1278 if (api_user()===false) return false;
1280 $user_info = api_get_user($a);
1281 // in friendica starred item are private
1282 // return favorites only for self
1283 logger('api_favorites: self:' . $user_info['self']);
1285 if ($user_info['self']==0) {
1291 $count = (x($_GET,'count')?$_GET['count']:20);
1292 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1293 if ($page<0) $page=0;
1295 $start = $page*$count;
1297 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `item`.`network` AS `item_network`,
1298 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1299 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1300 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1301 FROM `item`, `contact`
1302 WHERE `item`.`uid` = %d
1303 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1304 AND `item`.`starred` = 1
1305 AND `contact`.`id` = `item`.`contact-id`
1306 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1308 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1309 //intval($user_info['uid']),
1311 intval($start), intval($count)
1314 $ret = api_format_items($r,$user_info);
1318 $data = array('$statuses' => $ret);
1322 $data = api_rss_extra($a, $data, $user_info);
1325 return api_apply_template("timeline", $type, $data);
1328 api_register_func('api/favorites','api_favorites', true);
1330 function api_format_as($a, $ret, $user_info) {
1333 $as['title'] = $a->config['sitename']." Public Timeline";
1335 foreach ($ret as $item) {
1336 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1337 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1338 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1339 $avatar[0]["rel"] = "avatar";
1340 $avatar[0]["type"] = "";
1341 $avatar[0]["width"] = 96;
1342 $avatar[0]["height"] = 96;
1343 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1344 $avatar[1]["rel"] = "avatar";
1345 $avatar[1]["type"] = "";
1346 $avatar[1]["width"] = 48;
1347 $avatar[1]["height"] = 48;
1348 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1349 $avatar[2]["rel"] = "avatar";
1350 $avatar[2]["type"] = "";
1351 $avatar[2]["width"] = 24;
1352 $avatar[2]["height"] = 24;
1353 $singleitem["actor"]["avatarLinks"] = $avatar;
1355 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1356 $singleitem["actor"]["image"]["rel"] = "avatar";
1357 $singleitem["actor"]["image"]["type"] = "";
1358 $singleitem["actor"]["image"]["width"] = 96;
1359 $singleitem["actor"]["image"]["height"] = 96;
1360 $singleitem["actor"]["type"] = "person";
1361 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1362 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1363 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1364 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1365 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1366 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1367 $singleitem["actor"]["contact"]["addresses"] = "";
1369 $singleitem["body"] = $item["text"];
1370 $singleitem["object"]["displayName"] = $item["text"];
1371 $singleitem["object"]["id"] = $item["url"];
1372 $singleitem["object"]["type"] = "note";
1373 $singleitem["object"]["url"] = $item["url"];
1374 //$singleitem["context"] =;
1375 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1376 $singleitem["provider"]["objectType"] = "service";
1377 $singleitem["provider"]["displayName"] = "Test";
1378 $singleitem["provider"]["url"] = "http://test.tld";
1379 $singleitem["title"] = $item["text"];
1380 $singleitem["verb"] = "post";
1381 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1382 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1383 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1384 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1385 //$singleitem["original"] = $item;
1386 $items[] = $singleitem;
1388 $as['items'] = $items;
1389 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1390 $as['link']['rel'] = "alternate";
1391 $as['link']['type'] = "text/html";
1395 function api_format_messages($item, $recipient, $sender) {
1396 // standard meta information
1398 'id' => $item['id'],
1399 'sender_id' => $sender['id'] ,
1401 'recipient_id' => $recipient['id'],
1402 'created_at' => api_date($item['created']),
1403 'sender_screen_name' => $sender['screen_name'],
1404 'recipient_screen_name' => $recipient['screen_name'],
1405 'sender' => $sender,
1406 'recipient' => $recipient,
1409 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1410 unset($ret["sender"]["cid"]);
1411 unset($ret["sender"]["uid"]);
1412 unset($ret["sender"]["self"]);
1413 unset($ret["recipient"]["cid"]);
1414 unset($ret["recipient"]["uid"]);
1415 unset($ret["recipient"]["self"]);
1417 //don't send title to regular StatusNET requests to avoid confusing these apps
1418 if (x($_GET, 'getText')) {
1419 $ret['title'] = $item['title'] ;
1420 if ($_GET["getText"] == "html") {
1421 $ret['text'] = bbcode($item['body'], false, false);
1423 elseif ($_GET["getText"] == "plain") {
1424 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1425 $ret['text'] = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1429 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body'], false, false, 2), 0);
1431 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1432 unset($ret['sender']);
1433 unset($ret['recipient']);
1439 function api_format_items($r,$user_info, $filter_user = false) {
1444 foreach($r as $item) {
1445 localize_item($item);
1446 $status_user = api_item_get_user($a,$item);
1448 // Look if the posts are matching if they should be filtered by user id
1449 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1452 if ($item['thr-parent'] != $item['uri']) {
1453 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1455 dbesc($item['thr-parent']));
1457 $in_reply_to_status_id = $r[0]['id'];
1459 $in_reply_to_status_id = $item['parent'];
1461 $in_reply_to_screen_name = NULL;
1462 $in_reply_to_user_id = NULL;
1464 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1466 intval($in_reply_to_status_id));
1468 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1471 $in_reply_to_screen_name = $r[0]['name'];
1472 $in_reply_to_user_id = $r[0]['id'];
1476 $in_reply_to_screen_name = NULL;
1477 $in_reply_to_user_id = NULL;
1478 $in_reply_to_status_id = NULL;
1481 // Workaround for ostatus messages where the title is identically to the body
1482 $statusbody = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1484 $statustitle = trim($item['title']);
1486 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1487 $statustext = trim($statusbody);
1489 $statustext = trim($statustitle."\n\n".$statusbody);
1491 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1492 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1495 'text' => $statustext,
1496 'truncated' => False,
1497 'created_at'=> api_date($item['created']),
1498 'in_reply_to_status_id' => $in_reply_to_status_id,
1499 'source' => (($item['app']) ? $item['app'] : 'web'),
1500 'id' => intval($item['id']),
1501 'in_reply_to_user_id' => $in_reply_to_user_id,
1502 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1504 'favorited' => $item['starred'] ? true : false,
1505 //'attachments' => array(),
1506 'user' => $status_user ,
1507 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1508 'statusnet_conversation_id' => $item['parent'],
1511 if (($item['item_network'] != "") AND ($status["source"] == 'web'))
1512 $status["source"] = network_to_name($item['item_network']);
1513 else if (($item['item_network'] != "") AND (network_to_name($item['item_network']) != $status["source"]))
1514 $status["source"] = trim($status["source"].' ('.network_to_name($item['item_network']).')');
1517 // Retweets are only valid for top postings
1518 if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1519 $retweeted_status = $status;
1520 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1522 $status["retweeted_status"] = $retweeted_status;
1525 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1526 unset($status["user"]["cid"]);
1527 unset($status["user"]["uid"]);
1528 unset($status["user"]["self"]);
1530 // 'geo' => array('type' => 'Point',
1531 // 'coordinates' => array((float) $notice->lat,
1532 // (float) $notice->lon));
1534 // Seesmic doesn't like the following content
1535 // completely disabled to make friendica totally compatible to the statusnet API
1536 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1538 'updated' => api_date($item['edited']),
1539 'published' => api_date($item['created']),
1540 'message_id' => $item['uri'],
1541 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1542 'coordinates' => $item['coord'],
1543 'place' => $item['location'],
1544 'contributors' => '',
1545 'annotations' => '',
1547 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1548 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1549 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1550 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1553 $status = array_merge($status, $status2);
1562 function api_account_rate_limit_status(&$a,$type) {
1565 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1566 'remaining_hits' => (string) 150,
1567 'hourly_limit' => (string) 150,
1568 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1571 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1573 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1576 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1578 function api_help_test(&$a,$type) {
1585 return api_apply_template('test', $type, array('$ok' => $ok));
1588 api_register_func('api/help/test','api_help_test',false);
1591 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1592 * This function is deprecated by Twitter
1593 * returns: json, xml
1595 function api_statuses_f(&$a, $type, $qtype) {
1596 if (api_user()===false) return false;
1597 $user_info = api_get_user($a);
1600 // friends and followers only for self
1601 if ($user_info['self']==0){
1605 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1606 /* this is to stop Hotot to load friends multiple times
1607 * I'm not sure if I'm missing return something or
1608 * is a bug in hotot. Workaround, meantime
1612 return array('$users' => $ret);*/
1616 if($qtype == 'friends')
1617 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1618 if($qtype == 'followers')
1619 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1621 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1626 foreach($r as $cid){
1627 $user = api_get_user($a, $cid['id']);
1628 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1629 unset($user["cid"]);
1630 unset($user["uid"]);
1631 unset($user["self"]);
1638 return array('$users' => $ret);
1641 function api_statuses_friends(&$a, $type){
1642 $data = api_statuses_f($a,$type,"friends");
1643 if ($data===false) return false;
1644 return api_apply_template("friends", $type, $data);
1646 function api_statuses_followers(&$a, $type){
1647 $data = api_statuses_f($a,$type,"followers");
1648 if ($data===false) return false;
1649 return api_apply_template("friends", $type, $data);
1651 api_register_func('api/statuses/friends','api_statuses_friends',true);
1652 api_register_func('api/statuses/followers','api_statuses_followers',true);
1659 function api_statusnet_config(&$a,$type) {
1660 $name = $a->config['sitename'];
1661 $server = $a->get_hostname();
1662 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1663 $email = $a->config['admin_email'];
1664 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1665 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1666 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1667 if($a->config['api_import_size'])
1668 $texlimit = string($a->config['api_import_size']);
1669 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1670 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1673 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1674 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1675 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1676 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1677 'shorturllength' => '30',
1678 'friendica' => array(
1679 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1680 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1681 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1682 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1687 return api_apply_template('config', $type, array('$config' => $config));
1690 api_register_func('api/statusnet/config','api_statusnet_config',false);
1692 function api_statusnet_version(&$a,$type) {
1696 if($type === 'xml') {
1697 header("Content-type: application/xml");
1698 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1701 elseif($type === 'json') {
1702 header("Content-type: application/json");
1707 api_register_func('api/statusnet/version','api_statusnet_version',false);
1710 function api_ff_ids(&$a,$type,$qtype) {
1714 if($qtype == 'friends')
1715 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1716 if($qtype == 'followers')
1717 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1720 $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",
1726 if($type === 'xml') {
1727 header("Content-type: application/xml");
1728 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1730 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1731 echo '</ids>' . "\r\n";
1734 elseif($type === 'json') {
1736 header("Content-type: application/json");
1737 foreach($r as $rr) $ret[] = $rr['id'];
1738 echo json_encode($ret);
1744 function api_friends_ids(&$a,$type) {
1745 api_ff_ids($a,$type,'friends');
1747 function api_followers_ids(&$a,$type) {
1748 api_ff_ids($a,$type,'followers');
1750 api_register_func('api/friends/ids','api_friends_ids',true);
1751 api_register_func('api/followers/ids','api_followers_ids',true);
1754 function api_direct_messages_new(&$a, $type) {
1755 if (api_user()===false) return false;
1757 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1759 $sender = api_get_user($a);
1761 require_once("include/message.php");
1763 $r = q("SELECT `id`, `nurl` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1765 dbesc($_POST['screen_name']));
1767 $recipient = api_get_user($a, $r[0]['nurl']);
1770 if (x($_REQUEST,'replyto')) {
1771 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1773 intval($_REQUEST['replyto']));
1774 $replyto = $r[0]['parent-uri'];
1775 $sub = $r[0]['title'];
1778 if (x($_REQUEST,'title')) {
1779 $sub = $_REQUEST['title'];
1782 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1786 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1789 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1790 $ret = api_format_messages($r[0], $recipient, $sender);
1793 $ret = array("error"=>$id);
1796 $data = Array('$messages'=>$ret);
1801 $data = api_rss_extra($a, $data, $user_info);
1804 return api_apply_template("direct_messages", $type, $data);
1807 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1809 function api_direct_messages_box(&$a, $type, $box) {
1810 if (api_user()===false) return false;
1812 $user_info = api_get_user($a);
1815 $count = (x($_GET,'count')?$_GET['count']:20);
1816 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1817 if ($page<0) $page=0;
1819 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1821 $start = $page*$count;
1823 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1824 $profile_url = $user_info["url"];
1826 if ($box=="sentbox") {
1827 $sql_extra = "`mail`.`from-url`='".dbesc( $profile_url )."'";
1829 elseif ($box=="conversation") {
1830 $sql_extra = "`mail`.`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1832 elseif ($box=="all") {
1833 $sql_extra = "true";
1835 elseif ($box=="inbox") {
1836 $sql_extra = "`mail`.`from-url`!='".dbesc( $profile_url )."'";
1839 $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`.`created` DESC LIMIT %d,%d",
1842 intval($start), intval($count)
1846 foreach($r as $item) {
1847 if ($box == "inbox" || $item['from-url'] != $profile_url){
1848 $recipient = $user_info;
1849 $sender = api_get_user($a,normalise_link($item['contact-url']));
1851 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1852 $recipient = api_get_user($a,normalise_link($item['contact-url']));
1853 $sender = $user_info;
1857 $ret[]=api_format_messages($item, $recipient, $sender);
1861 $data = array('$messages' => $ret);
1865 $data = api_rss_extra($a, $data, $user_info);
1868 return api_apply_template("direct_messages", $type, $data);
1872 function api_direct_messages_sentbox(&$a, $type){
1873 return api_direct_messages_box($a, $type, "sentbox");
1875 function api_direct_messages_inbox(&$a, $type){
1876 return api_direct_messages_box($a, $type, "inbox");
1878 function api_direct_messages_all(&$a, $type){
1879 return api_direct_messages_box($a, $type, "all");
1881 function api_direct_messages_conversation(&$a, $type){
1882 return api_direct_messages_box($a, $type, "conversation");
1884 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1885 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1886 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1887 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1891 function api_oauth_request_token(&$a, $type){
1893 $oauth = new FKOAuth1();
1894 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1895 }catch(Exception $e){
1896 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1901 function api_oauth_access_token(&$a, $type){
1903 $oauth = new FKOAuth1();
1904 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1905 }catch(Exception $e){
1906 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1912 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1913 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1916 Not implemented by now:
1920 statuses/retweets_of_me
1925 account/update_location
1926 account/update_profile_background_image
1927 account/update_profile_image
1931 Not implemented in status.net:
1932 statuses/retweeted_to_me
1933 statuses/retweeted_by_me
1934 direct_messages/destroy
1936 account/update_delivery_device
1937 notifications/follow