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 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 'url' => $r[0]["url"],
335 'protected' => false,
336 'followers_count' => 0,
337 'friends_count' => 0,
339 'favourites_count' => 0,
341 'time_zone' => 'UTC',
342 'statuses_count' => 0,
344 'statusnet_blocking' => false,
345 'notifications' => false,
346 'statusnet_profile_url' => $r[0]["url"],
354 die(api_error($a, $type, t("User not found.")));
358 if($uinfo[0]['self']) {
359 $usr = q("select * from user where uid = %d limit 1",
362 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
366 // count public wall messages
367 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
370 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
371 intval($uinfo[0]['uid'])
373 $countitms = $r[0]['count'];
376 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
377 WHERE `contact-id` = %d
378 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
379 intval($uinfo[0]['id'])
381 $countitms = $r[0]['count'];
385 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
386 WHERE `uid` = %d AND `rel` IN ( %d, %d )
387 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
388 intval($uinfo[0]['uid']),
389 intval(CONTACT_IS_SHARING),
390 intval(CONTACT_IS_FRIEND)
392 $countfriends = $r[0]['count'];
394 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
395 WHERE `uid` = %d AND `rel` IN ( %d, %d )
396 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
397 intval($uinfo[0]['uid']),
398 intval(CONTACT_IS_FOLLOWER),
399 intval(CONTACT_IS_FRIEND)
401 $countfollowers = $r[0]['count'];
403 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
404 intval($uinfo[0]['uid'])
406 $starred = $r[0]['count'];
409 if(! $uinfo[0]['self']) {
415 // Fetching unique id
416 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
418 // If not there, then add it
419 if (count($r) == 0) {
420 q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
421 dbesc(normalise_link($uinfo[0]['url'])), dbesc($uinfo[0]['name']),dbesc($uinfo[0]['nick']), dbesc($uinfo[0]['micro']));
423 $r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1", dbesc(normalise_link($uinfo[0]['url'])));
427 'id' => intval($r[0]['id']),
428 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
429 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
430 'location' => ($usr) ? $usr[0]['default-location'] : NULL,
431 'description' => (($profile) ? $profile[0]['pdesc'] : NULL),
432 'profile_image_url' => $uinfo[0]['micro'],
433 'url' => $uinfo[0]['url'],
434 'protected' => false,
435 'followers_count' => intval($countfollowers),
436 'friends_count' => intval($countfriends),
437 'created_at' => api_date($uinfo[0]['name-date']),
438 'favourites_count' => intval($starred),
439 'utc_offset' => "0", // To-Do
440 'time_zone' => 'UTC', // To-Do $uinfo[0]['timezone'],
441 'statuses_count' => intval($countitms),
442 'following' => true, //#XXX: fix me
443 'verified' => true, //#XXX: fix me
444 'statusnet_blocking' => false,
445 'notifications' => false,
446 'statusnet_profile_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
447 'uid' => intval($uinfo[0]['uid']),
448 'cid' => intval($uinfo[0]['cid']),
449 'self' => $uinfo[0]['self'],
456 function api_item_get_user(&$a, $item) {
458 $author = q("SELECT * FROM unique_contacts WHERE url='%s' LIMIT 1",
459 dbesc(normalise_link($item['author-link'])));
461 if (count($author) == 0) {
462 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
463 dbesc(normalise_link($item["author-link"])), dbesc($item["author-name"]), dbesc($item["author-avatar"]));
465 $author = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
466 dbesc(normalise_link($item['author-link'])));
467 } else if ($item["author-link"].$item["author-name"] != $author[0]["url"].$author[0]["name"]) {
468 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
469 dbesc($item["author-name"]), dbesc($item["author-avatar"]), dbesc(normalise_link($item["author-link"])));
472 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
473 dbesc(normalise_link($item['owner-link'])));
475 if (count($owner) == 0) {
476 q("INSERT INTO unique_contacts (url, name, avatar) VALUES ('%s', '%s', '%s')",
477 dbesc(normalise_link($item["owner-link"])), dbesc($item["owner-name"]), dbesc($item["owner-avatar"]));
479 $owner = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
480 dbesc(normalise_link($item['owner-link'])));
481 } else if ($item["owner-link"].$item["owner-name"] != $owner[0]["url"].$owner[0]["name"]) {
482 q("UPDATE unique_contacts SET name = '%s', avatar = '%s' WHERE url = '%s'",
483 dbesc($item["owner-name"]), dbesc($item["owner-avatar"]), dbesc(normalise_link($item["owner-link"])));
486 // Comments in threads may appear as wall-to-wall postings.
487 // So only take the owner at the top posting.
488 if ($item["id"] == $item["parent"])
489 return api_get_user($a,$item["owner-link"]);
491 return api_get_user($a,$item["author-link"]);
496 * load api $templatename for $type and replace $data array
498 function api_apply_template($templatename, $type, $data){
506 $data = array_xmlify($data);
507 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
509 header ("Content-Type: text/xml");
510 echo '<?xml version="1.0" encoding="UTF-8"?>'."\n".'<status><error>not implemented</error></status>';
513 $ret = replace_macros($tpl, $data);
527 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
528 * returns a 401 status code and an error message if not.
529 * http://developer.twitter.com/doc/get/account/verify_credentials
531 function api_account_verify_credentials(&$a, $type){
532 if (api_user()===false) return false;
533 $user_info = api_get_user($a);
535 // "verified" isn't used here in the standard
536 unset($user_info["verified"]);
538 // - Adding last status
539 $user_info["status"] = api_status_show($a,"raw");
540 unset($user_info["status"]["user"]);
542 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
543 unset($user_info["cid"]);
544 unset($user_info["uid"]);
545 unset($user_info["self"]);
547 return api_apply_template("user", $type, array('$user' => $user_info));
550 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
554 * get data from $_POST or $_GET
556 function requestdata($k){
557 if (isset($_POST[$k])){
560 if (isset($_GET[$k])){
566 /*Waitman Gobble Mod*/
567 function api_statuses_mediap(&$a, $type) {
568 if (api_user()===false) {
569 logger('api_statuses_update: no user');
572 $user_info = api_get_user($a);
574 $_REQUEST['type'] = 'wall';
575 $_REQUEST['profile_uid'] = api_user();
576 $_REQUEST['api_source'] = true;
577 $txt = requestdata('status');
578 //$txt = urldecode(requestdata('status'));
580 require_once('library/HTMLPurifier.auto.php');
581 require_once('include/html2bbcode.php');
583 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
584 $txt = html2bb_video($txt);
585 $config = HTMLPurifier_Config::createDefault();
586 $config->set('Cache.DefinitionImpl', null);
587 $purifier = new HTMLPurifier($config);
588 $txt = $purifier->purify($txt);
590 $txt = html2bbcode($txt);
592 $a->argv[1]=$user_info['screen_name']; //should be set to username?
594 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
595 require_once('mod/wall_upload.php');
596 $bebop = wall_upload_post($a);
598 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
599 $_REQUEST['body']=$txt."\n\n".$bebop;
600 require_once('mod/item.php');
603 // this should output the last post (the one we just posted).
604 return api_status_show($a,$type);
606 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
607 /*Waitman Gobble Mod*/
610 function api_statuses_update(&$a, $type) {
611 if (api_user()===false) {
612 logger('api_statuses_update: no user');
615 $user_info = api_get_user($a);
617 // convert $_POST array items to the form we use for web posts.
619 // logger('api_post: ' . print_r($_POST,true));
621 if(requestdata('htmlstatus')) {
622 require_once('library/HTMLPurifier.auto.php');
623 require_once('include/html2bbcode.php');
625 $txt = requestdata('htmlstatus');
626 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
628 $txt = html2bb_video($txt);
630 $config = HTMLPurifier_Config::createDefault();
631 $config->set('Cache.DefinitionImpl', null);
634 $purifier = new HTMLPurifier($config);
635 $txt = $purifier->purify($txt);
637 $_REQUEST['body'] = html2bbcode($txt);
642 $_REQUEST['body'] = requestdata('status');
644 $_REQUEST['title'] = requestdata('title');
646 $parent = requestdata('in_reply_to_status_id');
647 if(ctype_digit($parent))
648 $_REQUEST['parent'] = $parent;
650 $_REQUEST['parent_uri'] = $parent;
652 if(requestdata('lat') && requestdata('long'))
653 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
654 $_REQUEST['profile_uid'] = api_user();
657 $_REQUEST['type'] = 'net-comment';
659 $_REQUEST['type'] = 'wall';
660 if(x($_FILES,'media')) {
661 // upload the image if we have one
662 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
663 require_once('mod/wall_upload.php');
664 $media = wall_upload_post($a);
666 $_REQUEST['body'] .= "\n\n".$media;
670 // set this so that the item_post() function is quiet and doesn't redirect or emit json
672 $_REQUEST['api_source'] = true;
674 // call out normal post function
676 require_once('mod/item.php');
679 // this should output the last post (the one we just posted).
680 return api_status_show($a,$type);
682 api_register_func('api/statuses/update','api_statuses_update', true);
685 function api_status_show(&$a, $type){
686 $user_info = api_get_user($a);
687 // get last public wall message
688 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `c`.`nick` as `reply_author`, `i`.`author-link` AS `item-author`
689 FROM `item`, `contact`, `item` as `i`, `contact` as `c`
690 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
691 AND `i`.`id` = `item`.`parent`
692 AND `contact`.`id`=`item`.`contact-id` AND `c`.`id`=`i`.`contact-id` AND `contact`.`self`=1
693 AND `item`.`type`!='activity'
694 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
695 ORDER BY `item`.`created` DESC
697 intval($user_info['cid']),
698 dbesc($user_info['url'])
701 if (count($lastwall)>0){
702 $lastwall = $lastwall[0];
704 $in_reply_to_status_id = NULL;
705 $in_reply_to_user_id = NULL;
706 $in_reply_to_screen_name = NULL;
707 if ($lastwall['parent']!=$lastwall['id']) {
708 $in_reply_to_status_id=$lastwall['parent'];
709 //$in_reply_to_user_id = $lastwall['reply_uid'];
710 //$in_reply_to_screen_name = $lastwall['reply_author'];
712 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($lastwall['item-author'])));
714 $in_reply_to_screen_name = $r[0]['name'];
715 $in_reply_to_user_id = $r[0]['id'];
718 $status_info = array(
719 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
720 'truncated' => false,
721 'created_at' => api_date($lastwall['created']),
722 'in_reply_to_status_id' => $in_reply_to_status_id,
723 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
724 'id' => $lastwall['id'],
725 'in_reply_to_user_id' => $in_reply_to_user_id,
726 'in_reply_to_screen_name' => $in_reply_to_screen_name,
728 'favorited' => false,
730 'user' => $user_info,
731 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
732 'statusnet_conversation_id' => $lastwall['parent'],
735 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
736 unset($status_info["user"]["cid"]);
737 unset($status_info["user"]["uid"]);
738 unset($status_info["user"]["self"]);
742 return($status_info);
744 return api_apply_template("status", $type, array('$status' => $status_info));
753 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
754 * The author's most recent status will be returned inline.
755 * http://developer.twitter.com/doc/get/users/show
757 function api_users_show(&$a, $type){
758 $user_info = api_get_user($a);
760 $lastwall = q("SELECT `item`.*
761 FROM `item`, `contact`
762 WHERE `item`.`contact-id` = %d AND `item`.`owner-link` = '%s'
763 AND `contact`.`id`=`item`.`contact-id`
764 AND `type`!='activity'
765 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
766 ORDER BY `created` DESC
768 intval($user_info['cid']),
769 dbesc($user_info['url'])
772 if (count($lastwall)>0){
773 $lastwall = $lastwall[0];
775 $in_reply_to_status_id = NULL;
776 $in_reply_to_user_id = NULL;
777 $in_reply_to_screen_name = NULL;
778 if ($lastwall['parent']!=$lastwall['id']) {
779 $reply = q("SELECT `item`.`id`, `item`.`contact-id` as `reply_uid`, `contact`.`nick` as `reply_author`, `item`.`author-link` AS `item-author`
780 FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id` AND `item`.`id` = %d", intval($lastwall['parent']));
781 if (count($reply)>0) {
782 $in_reply_to_status_id=$lastwall['parent'];
783 //$in_reply_to_user_id = $reply[0]['reply_uid'];
784 //$in_reply_to_screen_name = $reply[0]['reply_author'];
785 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($reply[0]['item-author'])));
787 $in_reply_to_screen_name = $r[0]['name'];
788 $in_reply_to_user_id = $r[0]['id'];
792 $user_info['status'] = array(
793 'text' => trim(html2plain(bbcode($lastwall['body'], false, false, 2), 0)),
794 'truncated' => false,
795 'created_at' => api_date($lastwall['created']),
796 'in_reply_to_status_id' => $in_reply_to_status_id,
797 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
798 'id' => $lastwall['contact-id'],
799 'in_reply_to_user_id' => $in_reply_to_user_id,
800 'in_reply_to_screen_name' => $in_reply_to_screen_name,
802 'favorited' => false,
803 'statusnet_html' => trim(bbcode($lastwall['body'], false, false)),
804 'statusnet_conversation_id' => $lastwall['parent'],
808 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
809 unset($user_info["cid"]);
810 unset($user_info["uid"]);
811 unset($user_info["self"]);
813 return api_apply_template("user", $type, array('$user' => $user_info));
816 api_register_func('api/users/show','api_users_show');
820 * http://developer.twitter.com/doc/get/statuses/home_timeline
822 * TODO: Optional parameters
823 * TODO: Add reply info
825 function api_statuses_home_timeline(&$a, $type){
826 if (api_user()===false) return false;
828 $user_info = api_get_user($a);
829 // get last newtork messages
833 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
834 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
835 if ($page<0) $page=0;
836 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
837 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
838 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
839 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
840 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
842 $start = $page*$count;
844 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
848 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
849 if ($exclude_replies > 0)
850 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
851 if ($conversation_id > 0)
852 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
854 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
855 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
856 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
857 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
858 FROM `item`, `contact`
859 WHERE `item`.`uid` = %d
860 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
861 AND `contact`.`id` = `item`.`contact-id`
862 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
865 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
866 //intval($user_info['uid']),
869 intval($start), intval($count)
872 $ret = api_format_items($r,$user_info);
874 // We aren't going to try to figure out at the item, group, and page
875 // level which items you've seen and which you haven't. If you're looking
876 // at the network timeline just mark everything seen.
878 $r = q("UPDATE `item` SET `unseen` = 0
879 WHERE `unseen` = 1 AND `uid` = %d",
880 //intval($user_info['uid'])
885 $data = array('$statuses' => $ret);
889 $data = api_rss_extra($a, $data, $user_info);
892 $as = api_format_as($a, $ret, $user_info);
893 $as['title'] = $a->config['sitename']." Home Timeline";
894 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
899 return api_apply_template("timeline", $type, $data);
901 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
902 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
904 function api_statuses_public_timeline(&$a, $type){
905 if (api_user()===false) return false;
907 $user_info = api_get_user($a);
908 // get last newtork messages
912 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
913 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
914 if ($page<0) $page=0;
915 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
916 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
917 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
918 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
919 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
921 $start = $page*$count;
923 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
926 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
927 if ($exclude_replies > 0)
928 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
929 if ($conversation_id > 0)
930 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
932 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
933 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
934 `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
935 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
936 `user`.`nickname`, `user`.`hidewall`
937 FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
938 LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
939 WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
940 AND `item`.`allow_cid` = '' AND `item`.`allow_gid` = ''
941 AND `item`.`deny_cid` = '' AND `item`.`deny_gid` = ''
942 AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
943 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
946 ORDER BY `received` DESC LIMIT %d, %d ",
951 $ret = api_format_items($r,$user_info);
954 $data = array('$statuses' => $ret);
958 $data = api_rss_extra($a, $data, $user_info);
961 $as = api_format_as($a, $ret, $user_info);
962 $as['title'] = $a->config['sitename']." Public Timeline";
963 $as['link']['url'] = $a->get_baseurl()."/";
968 return api_apply_template("timeline", $type, $data);
970 api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
975 function api_statuses_show(&$a, $type){
976 if (api_user()===false) return false;
978 $user_info = api_get_user($a);
981 $id = intval($a->argv[3]);
984 $id = intval($_REQUEST["id"]);
986 logger('API: api_statuses_show: '.$id);
988 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
989 $conversation = (x($_REQUEST,'conversation')?1:0);
993 $sql_extra .= " AND `item`.`parent` = %d ORDER BY `received` ASC ";
995 $sql_extra .= " AND `item`.`id` = %d";
997 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
998 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
999 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1000 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1001 FROM `item`, `contact`
1002 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1003 AND `contact`.`id` = `item`.`contact-id`
1004 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1010 die(api_error($a, $type, t("There is no status with this id.")));
1012 $ret = api_format_items($r,$user_info);
1014 if ($conversation) {
1015 $data = array('$statuses' => $ret);
1016 return api_apply_template("timeline", $type, $data);
1018 $data = array('$status' => $ret[0]);
1022 $data = api_rss_extra($a, $data, $user_info);
1024 return api_apply_template("status", $type, $data);
1027 api_register_func('api/statuses/show','api_statuses_show', true);
1033 function api_statuses_repeat(&$a, $type){
1034 if (api_user()===false) return false;
1036 $user_info = api_get_user($a);
1039 $id = intval($a->argv[3]);
1042 $id = intval($_REQUEST["id"]);
1044 logger('API: api_statuses_repeat: '.$id);
1046 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1048 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
1049 `contact`.`name`, `contact`.`photo` as `reply_photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
1050 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1051 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1052 FROM `item`, `contact`
1053 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1054 AND `contact`.`id` = `item`.`contact-id`
1055 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1057 AND `item`.`id`=%d",
1061 if ($r[0]['body'] != "") {
1062 if (!intval(get_config('system','old_share'))) {
1063 $post = "[share author='".str_replace("'", "'", $r[0]['reply_author']).
1064 "' profile='".$r[0]['reply_url'].
1065 "' avatar='".$r[0]['reply_photo'].
1066 "' link='".$r[0]['plink']."']";
1068 $post .= $r[0]['body'];
1069 $post .= "[/share]";
1070 $_REQUEST['body'] = $post;
1072 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
1074 $_REQUEST['profile_uid'] = api_user();
1075 $_REQUEST['type'] = 'wall';
1076 $_REQUEST['api_source'] = true;
1078 require_once('mod/item.php');
1087 return api_apply_template('test', $type, array('$ok' => $ok));
1089 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
1094 function api_statuses_destroy(&$a, $type){
1095 if (api_user()===false) return false;
1097 $user_info = api_get_user($a);
1100 $id = intval($a->argv[3]);
1103 $id = intval($_REQUEST["id"]);
1105 logger('API: api_statuses_destroy: '.$id);
1107 require_once('include/items.php');
1108 drop_item($id, false);
1115 return api_apply_template('test', $type, array('$ok' => $ok));
1117 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
1121 * http://developer.twitter.com/doc/get/statuses/mentions
1124 function api_statuses_mentions(&$a, $type){
1125 if (api_user()===false) return false;
1127 $user_info = api_get_user($a);
1128 // get last newtork messages
1132 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1133 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1134 if ($page<0) $page=0;
1135 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1136 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
1137 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1139 $start = $page*$count;
1141 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1143 // Ugly code - should be changed
1144 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1145 $myurl = substr($myurl,strpos($myurl,'://')+3);
1146 //$myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1147 $myurl = str_replace('www.','',$myurl);
1148 $diasp_url = str_replace('/profile/','/u/',$myurl);
1150 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where `author-link` IN ('https://%s', 'http://%s') OR `mention`)",
1151 dbesc(protect_sprintf($myurl)),
1152 dbesc(protect_sprintf($myurl))
1156 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1158 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1159 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1160 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1161 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1162 FROM `item`, `contact`
1163 WHERE `item`.`uid` = %d
1164 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1165 AND `contact`.`id` = `item`.`contact-id`
1166 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1169 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1170 //intval($user_info['uid']),
1173 intval($start), intval($count)
1176 $ret = api_format_items($r,$user_info);
1179 $data = array('$statuses' => $ret);
1183 $data = api_rss_extra($a, $data, $user_info);
1186 $as = api_format_as($a, $ret, $user_info);
1187 $as["title"] = $a->config['sitename']." Mentions";
1188 $as['link']['url'] = $a->get_baseurl()."/";
1193 return api_apply_template("timeline", $type, $data);
1195 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1196 api_register_func('api/statuses/replies','api_statuses_mentions', true);
1199 function api_statuses_user_timeline(&$a, $type){
1200 if (api_user()===false) return false;
1202 $user_info = api_get_user($a);
1203 // get last network messages
1205 logger("api_statuses_user_timeline: api_user: ". api_user() .
1206 "\nuser_info: ".print_r($user_info, true) .
1207 "\n_REQUEST: ".print_r($_REQUEST, true),
1211 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1212 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1213 if ($page<0) $page=0;
1214 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1215 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1216 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1217 $conversation_id = (x($_REQUEST,'conversation_id')?$_REQUEST['conversation_id']:0);
1219 $start = $page*$count;
1222 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1224 if ($exclude_replies > 0)
1225 $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1226 if ($conversation_id > 0)
1227 $sql_extra .= ' AND `item`.`parent` = '.intval($conversation_id);
1229 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1230 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1231 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1232 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1233 FROM `item`, `contact`
1234 WHERE `item`.`uid` = %d
1235 AND `item`.`contact-id` = %d
1236 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1237 AND `contact`.`id` = `item`.`contact-id`
1238 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1241 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1243 intval($user_info['cid']),
1245 intval($start), intval($count)
1248 $ret = api_format_items($r,$user_info, true);
1250 $data = array('$statuses' => $ret);
1254 $data = api_rss_extra($a, $data, $user_info);
1257 return api_apply_template("timeline", $type, $data);
1260 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1263 function api_favorites(&$a, $type){
1264 if (api_user()===false) return false;
1266 $user_info = api_get_user($a);
1267 // in friendica starred item are private
1268 // return favorites only for self
1269 logger('api_favorites: self:' . $user_info['self']);
1271 if ($user_info['self']==0) {
1277 $count = (x($_GET,'count')?$_GET['count']:20);
1278 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1279 if ($page<0) $page=0;
1281 $start = $page*$count;
1283 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1284 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1285 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1286 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1287 FROM `item`, `contact`
1288 WHERE `item`.`uid` = %d
1289 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1290 AND `item`.`starred` = 1
1291 AND `contact`.`id` = `item`.`contact-id`
1292 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1294 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1295 //intval($user_info['uid']),
1297 intval($start), intval($count)
1300 $ret = api_format_items($r,$user_info);
1304 $data = array('$statuses' => $ret);
1308 $data = api_rss_extra($a, $data, $user_info);
1311 return api_apply_template("timeline", $type, $data);
1314 api_register_func('api/favorites','api_favorites', true);
1316 function api_format_as($a, $ret, $user_info) {
1319 $as['title'] = $a->config['sitename']." Public Timeline";
1321 foreach ($ret as $item) {
1322 $singleitem["actor"]["displayName"] = $item["user"]["name"];
1323 $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1324 $avatar[0]["url"] = $item["user"]["profile_image_url"];
1325 $avatar[0]["rel"] = "avatar";
1326 $avatar[0]["type"] = "";
1327 $avatar[0]["width"] = 96;
1328 $avatar[0]["height"] = 96;
1329 $avatar[1]["url"] = $item["user"]["profile_image_url"];
1330 $avatar[1]["rel"] = "avatar";
1331 $avatar[1]["type"] = "";
1332 $avatar[1]["width"] = 48;
1333 $avatar[1]["height"] = 48;
1334 $avatar[2]["url"] = $item["user"]["profile_image_url"];
1335 $avatar[2]["rel"] = "avatar";
1336 $avatar[2]["type"] = "";
1337 $avatar[2]["width"] = 24;
1338 $avatar[2]["height"] = 24;
1339 $singleitem["actor"]["avatarLinks"] = $avatar;
1341 $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1342 $singleitem["actor"]["image"]["rel"] = "avatar";
1343 $singleitem["actor"]["image"]["type"] = "";
1344 $singleitem["actor"]["image"]["width"] = 96;
1345 $singleitem["actor"]["image"]["height"] = 96;
1346 $singleitem["actor"]["type"] = "person";
1347 $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1348 $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1349 $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1350 $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1351 $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1352 $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1353 $singleitem["actor"]["contact"]["addresses"] = "";
1355 $singleitem["body"] = $item["text"];
1356 $singleitem["object"]["displayName"] = $item["text"];
1357 $singleitem["object"]["id"] = $item["url"];
1358 $singleitem["object"]["type"] = "note";
1359 $singleitem["object"]["url"] = $item["url"];
1360 //$singleitem["context"] =;
1361 $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1362 $singleitem["provider"]["objectType"] = "service";
1363 $singleitem["provider"]["displayName"] = "Test";
1364 $singleitem["provider"]["url"] = "http://test.tld";
1365 $singleitem["title"] = $item["text"];
1366 $singleitem["verb"] = "post";
1367 $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1368 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1369 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1370 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1371 //$singleitem["original"] = $item;
1372 $items[] = $singleitem;
1374 $as['items'] = $items;
1375 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1376 $as['link']['rel'] = "alternate";
1377 $as['link']['type'] = "text/html";
1381 function api_format_messages($item, $recipient, $sender) {
1382 // standard meta information
1384 'id' => $item['id'],
1385 'sender_id' => $sender['id'] ,
1387 'recipient_id' => $recipient['id'],
1388 'created_at' => api_date($item['created']),
1389 'sender_screen_name' => $sender['screen_name'],
1390 'recipient_screen_name' => $recipient['screen_name'],
1391 'sender' => $sender,
1392 'recipient' => $recipient,
1395 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1396 unset($ret["sender"]["cid"]);
1397 unset($ret["sender"]["uid"]);
1398 unset($ret["sender"]["self"]);
1399 unset($ret["recipient"]["cid"]);
1400 unset($ret["recipient"]["uid"]);
1401 unset($ret["recipient"]["self"]);
1403 //don't send title to regular StatusNET requests to avoid confusing these apps
1404 if (x($_GET, 'getText')) {
1405 $ret['title'] = $item['title'] ;
1406 if ($_GET["getText"] == "html") {
1407 $ret['text'] = bbcode($item['body'], false, false);
1409 elseif ($_GET["getText"] == "plain") {
1410 //$ret['text'] = html2plain(bbcode($item['body'], false, false, true), 0);
1411 $ret['text'] = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1415 $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body'], false, false, 2), 0);
1417 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1418 unset($ret['sender']);
1419 unset($ret['recipient']);
1425 function api_format_items($r,$user_info, $filter_user = false) {
1430 foreach($r as $item) {
1431 localize_item($item);
1432 $status_user = api_item_get_user($a,$item);
1434 // Look if the posts are matching if they should be filtered by user id
1435 if ($filter_user AND ($status_user["id"] != $user_info["id"]))
1438 if ($item['thr-parent'] != $item['uri']) {
1439 $r = q("SELECT id FROM item WHERE uid=%d AND uri='%s' LIMIT 1",
1441 dbesc($item['thr-parent']));
1443 $in_reply_to_status_id = $r[0]['id'];
1445 $in_reply_to_status_id = $item['parent'];
1447 $in_reply_to_screen_name = NULL;
1448 $in_reply_to_user_id = NULL;
1450 $r = q("SELECT `author-link` FROM item WHERE uid=%d AND id=%d LIMIT 1",
1452 intval($in_reply_to_status_id));
1454 $r = q("SELECT * FROM unique_contacts WHERE `url` = '%s'", dbesc(normalise_link($r[0]['author-link'])));
1457 $in_reply_to_screen_name = $r[0]['name'];
1458 $in_reply_to_user_id = $r[0]['id'];
1462 $in_reply_to_screen_name = NULL;
1463 $in_reply_to_user_id = NULL;
1464 $in_reply_to_status_id = NULL;
1467 // Workaround for ostatus messages where the title is identically to the body
1468 $statusbody = trim(html2plain(bbcode($item['body'], false, false, 2), 0));
1470 $statustitle = trim($item['title']);
1472 if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1473 $statustext = trim($statusbody);
1475 $statustext = trim($statustitle."\n\n".$statusbody);
1477 if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1478 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1481 'text' => $statustext,
1482 'truncated' => False,
1483 'created_at'=> api_date($item['created']),
1484 'in_reply_to_status_id' => $in_reply_to_status_id,
1485 'source' => (($item['app']) ? $item['app'] : 'web'),
1486 'id' => intval($item['id']),
1487 'in_reply_to_user_id' => $in_reply_to_user_id,
1488 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1490 'favorited' => $item['starred'] ? true : false,
1491 //'attachments' => array(),
1492 'user' => $status_user ,
1493 'statusnet_html' => trim(bbcode($item['body'], false, false)),
1494 'statusnet_conversation_id' => $item['parent'],
1497 // Retweets are only valid for top postings
1498 if (($item['owner-link'] != $item['author-link']) AND ($item["id"] == $item["parent"])) {
1499 $retweeted_status = $status;
1500 $retweeted_status["user"] = api_get_user($a,$item["author-link"]);
1502 $status["retweeted_status"] = $retweeted_status;
1505 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1506 unset($status["user"]["cid"]);
1507 unset($status["user"]["uid"]);
1508 unset($status["user"]["self"]);
1510 // 'geo' => array('type' => 'Point',
1511 // 'coordinates' => array((float) $notice->lat,
1512 // (float) $notice->lon));
1514 // Seesmic doesn't like the following content
1515 // completely disabled to make friendica totally compatible to the statusnet API
1516 /*if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1518 'updated' => api_date($item['edited']),
1519 'published' => api_date($item['created']),
1520 'message_id' => $item['uri'],
1521 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1522 'coordinates' => $item['coord'],
1523 'place' => $item['location'],
1524 'contributors' => '',
1525 'annotations' => '',
1527 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1528 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1529 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1530 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1533 $status = array_merge($status, $status2);
1542 function api_account_rate_limit_status(&$a,$type) {
1545 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1546 'remaining_hits' => (string) 150,
1547 'hourly_limit' => (string) 150,
1548 'reset_time' => api_date(datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME)),
1551 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1553 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1556 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1558 function api_help_test(&$a,$type) {
1565 return api_apply_template('test', $type, array('$ok' => $ok));
1568 api_register_func('api/help/test','api_help_test',false);
1571 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1572 * This function is deprecated by Twitter
1573 * returns: json, xml
1575 function api_statuses_f(&$a, $type, $qtype) {
1576 if (api_user()===false) return false;
1577 $user_info = api_get_user($a);
1580 // friends and followers only for self
1581 if ($user_info['self']==0){
1585 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1586 /* this is to stop Hotot to load friends multiple times
1587 * I'm not sure if I'm missing return something or
1588 * is a bug in hotot. Workaround, meantime
1592 return array('$users' => $ret);*/
1596 if($qtype == 'friends')
1597 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1598 if($qtype == 'followers')
1599 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1601 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1606 foreach($r as $cid){
1607 $user = api_get_user($a, $cid['id']);
1608 // "cid", "uid" and "self" are only needed for some internal stuff, so remove it from here
1609 unset($user["cid"]);
1610 unset($user["uid"]);
1611 unset($user["self"]);
1618 return array('$users' => $ret);
1621 function api_statuses_friends(&$a, $type){
1622 $data = api_statuses_f($a,$type,"friends");
1623 if ($data===false) return false;
1624 return api_apply_template("friends", $type, $data);
1626 function api_statuses_followers(&$a, $type){
1627 $data = api_statuses_f($a,$type,"followers");
1628 if ($data===false) return false;
1629 return api_apply_template("friends", $type, $data);
1631 api_register_func('api/statuses/friends','api_statuses_friends',true);
1632 api_register_func('api/statuses/followers','api_statuses_followers',true);
1639 function api_statusnet_config(&$a,$type) {
1640 $name = $a->config['sitename'];
1641 $server = $a->get_hostname();
1642 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1643 $email = $a->config['admin_email'];
1644 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1645 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1646 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1647 if($a->config['api_import_size'])
1648 $texlimit = string($a->config['api_import_size']);
1649 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1650 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1653 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1654 'logo' => $logo, 'fancy' => true, 'language' => 'en', 'email' => $email, 'broughtby' => '',
1655 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => false,
1656 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1657 'shorturllength' => '30',
1658 'friendica' => array(
1659 'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1660 'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1661 'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1662 'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1667 return api_apply_template('config', $type, array('$config' => $config));
1670 api_register_func('api/statusnet/config','api_statusnet_config',false);
1672 function api_statusnet_version(&$a,$type) {
1676 if($type === 'xml') {
1677 header("Content-type: application/xml");
1678 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1681 elseif($type === 'json') {
1682 header("Content-type: application/json");
1687 api_register_func('api/statusnet/version','api_statusnet_version',false);
1690 function api_ff_ids(&$a,$type,$qtype) {
1694 if($qtype == 'friends')
1695 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1696 if($qtype == 'followers')
1697 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1700 $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",
1706 if($type === 'xml') {
1707 header("Content-type: application/xml");
1708 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1710 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1711 echo '</ids>' . "\r\n";
1714 elseif($type === 'json') {
1716 header("Content-type: application/json");
1717 foreach($r as $rr) $ret[] = $rr['id'];
1718 echo json_encode($ret);
1724 function api_friends_ids(&$a,$type) {
1725 api_ff_ids($a,$type,'friends');
1727 function api_followers_ids(&$a,$type) {
1728 api_ff_ids($a,$type,'followers');
1730 api_register_func('api/friends/ids','api_friends_ids',true);
1731 api_register_func('api/followers/ids','api_followers_ids',true);
1734 function api_direct_messages_new(&$a, $type) {
1735 if (api_user()===false) return false;
1737 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1739 $sender = api_get_user($a);
1741 require_once("include/message.php");
1743 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1745 dbesc($_POST['screen_name']));
1747 $recipient = api_get_user($a, $r[0]['id']);
1750 if (x($_REQUEST,'replyto')) {
1751 $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1753 intval($_REQUEST['replyto']));
1754 $replyto = $r[0]['parent-uri'];
1755 $sub = $r[0]['title'];
1758 if (x($_REQUEST,'title')) {
1759 $sub = $_REQUEST['title'];
1762 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1766 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1769 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1770 $ret = api_format_messages($r[0], $recipient, $sender);
1773 $ret = array("error"=>$id);
1776 $data = Array('$messages'=>$ret);
1781 $data = api_rss_extra($a, $data, $user_info);
1784 return api_apply_template("direct_messages", $type, $data);
1787 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1789 function api_direct_messages_box(&$a, $type, $box) {
1790 if (api_user()===false) return false;
1792 $user_info = api_get_user($a);
1795 $count = (x($_GET,'count')?$_GET['count']:20);
1796 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1797 if ($page<0) $page=0;
1799 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1801 $start = $page*$count;
1803 //$profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1804 $profile_url = $user_info["url"];
1806 if ($box=="sentbox") {
1807 $sql_extra = "`from-url`='".dbesc( $profile_url )."'";
1809 elseif ($box=="conversation") {
1810 $sql_extra = "`parent-uri`='".dbesc( $_GET["uri"] ) ."'";
1812 elseif ($box=="all") {
1813 $sql_extra = "true";
1815 elseif ($box=="inbox") {
1816 $sql_extra = "`from-url`!='".dbesc( $profile_url )."'";
1819 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra AND id > %d ORDER BY created DESC LIMIT %d,%d",
1822 intval($start), intval($count)
1826 foreach($r as $item) {
1827 if ($box == "inbox" || $item['from-url'] != $profile_url){
1828 $recipient = $user_info;
1829 $sender = api_get_user($a,$item['contact-id']);
1831 elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1832 $recipient = api_get_user($a,$item['contact-id']);
1833 $sender = $user_info;
1836 $ret[]=api_format_messages($item, $recipient, $sender);
1840 $data = array('$messages' => $ret);
1844 $data = api_rss_extra($a, $data, $user_info);
1847 return api_apply_template("direct_messages", $type, $data);
1851 function api_direct_messages_sentbox(&$a, $type){
1852 return api_direct_messages_box($a, $type, "sentbox");
1854 function api_direct_messages_inbox(&$a, $type){
1855 return api_direct_messages_box($a, $type, "inbox");
1857 function api_direct_messages_all(&$a, $type){
1858 return api_direct_messages_box($a, $type, "all");
1860 function api_direct_messages_conversation(&$a, $type){
1861 return api_direct_messages_box($a, $type, "conversation");
1863 api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1864 api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1865 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1866 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1870 function api_oauth_request_token(&$a, $type){
1872 $oauth = new FKOAuth1();
1873 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1874 }catch(Exception $e){
1875 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1880 function api_oauth_access_token(&$a, $type){
1882 $oauth = new FKOAuth1();
1883 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1884 }catch(Exception $e){
1885 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1891 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1892 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1895 Not implemented by now:
1899 statuses/retweets_of_me
1904 account/update_location
1905 account/update_profile_background_image
1906 account/update_profile_image
1910 Not implemented in status.net:
1911 statuses/retweeted_to_me
1912 statuses/retweeted_by_me
1913 direct_messages/destroy
1915 account/update_delivery_device
1916 notifications/follow