2 require_once("bbcode.php");
3 require_once("datetime.php");
4 require_once("conversation.php");
5 require_once("oauth.php");
6 require_once("html2plain.php");
15 function api_date($str){
16 //Wed May 23 06:01:13 +0000 2007
17 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
21 function api_register_func($path, $func, $auth=false){
23 $API[$path] = array('func'=>$func,
31 function api_login(&$a){
34 $oauth = new FKOAuth1();
35 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
36 if (!is_null($token)){
37 $oauth->loginUser($token->uid);
38 call_hooks('logged_in', $a->user);
41 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
43 logger(__file__.__line__.__function__."\n".$e);
44 //die(__file__.__line__.__function__."<pre>".$e); die();
49 // workaround for HTTP-auth in CGI mode
50 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
51 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
52 if(strlen($userpass)) {
53 list($name, $password) = explode(':', $userpass);
54 $_SERVER['PHP_AUTH_USER'] = $name;
55 $_SERVER['PHP_AUTH_PW'] = $password;
59 if (!isset($_SERVER['PHP_AUTH_USER'])) {
60 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
61 header('WWW-Authenticate: Basic realm="Friendica"');
62 header('HTTP/1.0 401 Unauthorized');
63 die('This api requires login');
66 $user = $_SERVER['PHP_AUTH_USER'];
67 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
71 * next code from mod/auth.php. needs better solution
74 // process normal login request
76 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
77 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
85 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
86 header('WWW-Authenticate: Basic realm="Friendica"');
87 header('HTTP/1.0 401 Unauthorized');
88 die('This api requires login');
91 require_once('include/security.php');
92 authenticate_success($record);
94 call_hooks('logged_in', $a->user);
98 /**************************
99 * MAIN API ENTRY POINT *
100 **************************/
101 function api_call(&$a){
102 GLOBAL $API, $called_api;
107 foreach ($API as $p=>$info){
108 if (strpos($a->query_string, $p)===0){
109 $called_api= explode("/",$p);
110 //unset($_SERVER['PHP_AUTH_USER']);
111 if ($info['auth']===true && local_user()===false) {
115 load_contact_links(local_user());
117 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
118 logger('API parameters: ' . print_r($_REQUEST,true));
120 if (strpos($a->query_string, ".xml")>0) $type="xml";
121 if (strpos($a->query_string, ".json")>0) $type="json";
122 if (strpos($a->query_string, ".rss")>0) $type="rss";
123 if (strpos($a->query_string, ".atom")>0) $type="atom";
125 $r = call_user_func($info['func'], $a, $type);
126 if ($r===false) return;
130 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
131 header ("Content-Type: text/xml");
132 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
135 //header ("Content-Type: application/json");
137 return json_encode($rr);
140 header ("Content-Type: application/rss+xml");
141 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
144 header ("Content-Type: application/atom+xml");
145 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
149 //echo "<pre>"; var_dump($r); die();
152 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
153 $r = '<status><error>not implemented</error></status>';
156 header ("Content-Type: text/xml");
157 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
160 header ("Content-Type: application/json");
161 return json_encode(array('error' => 'not implemented'));
164 header ("Content-Type: application/rss+xml");
165 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
168 header ("Content-Type: application/atom+xml");
169 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
177 function api_rss_extra(&$a, $arr, $user_info){
178 if (is_null($user_info)) $user_info = api_get_user($a);
179 $arr['$user'] = $user_info;
180 $arr['$rss'] = array(
181 'alternate' => $user_info['url'],
182 'self' => $a->get_baseurl(). "/". $a->query_string,
183 'base' => $a->get_baseurl(),
184 'updated' => api_date(null),
185 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
186 'language' => $user_info['language'],
187 'logo' => $a->get_baseurl()."/images/friendica-32.png",
194 * Returns user info array.
196 function api_get_user(&$a, $contact_id = Null){
202 if(!is_null($contact_id)){
204 $extra_query = "AND `contact`.`id` = %d ";
207 if(is_null($user) && x($_GET, 'user_id')) {
208 $user = intval($_GET['user_id']);
209 $extra_query = "AND `contact`.`id` = %d ";
211 if(is_null($user) && x($_GET, 'screen_name')) {
212 $user = dbesc($_GET['screen_name']);
213 $extra_query = "AND `contact`.`nick` = '%s' ";
214 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
218 if (is_null($user) && $a->argc > (count($called_api)-1)){
219 $argid = count($called_api);
220 list($user, $null) = explode(".",$a->argv[$argid]);
221 if(is_numeric($user)){
222 $user = intval($user);
223 $extra_query = "AND `contact`.`id` = %d ";
225 $user = dbesc($user);
226 $extra_query = "AND `contact`.`nick` = '%s' ";
227 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
232 if (local_user()===false) {
233 api_login($a); return False;
235 $user = $_SESSION['uid'];
236 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
241 logger('api_user: ' . $extra_query . ' ' , $user);
243 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
248 if (count($uinfo)==0) {
252 if($uinfo[0]['self']) {
253 $usr = q("select * from user where uid = %d limit 1",
256 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
260 // count public wall messages
261 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
264 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
265 intval($uinfo[0]['uid'])
267 $countitms = $r[0]['count'];
270 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
271 WHERE `contact-id` = %d
272 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
273 intval($uinfo[0]['id'])
275 $countitms = $r[0]['count'];
279 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
280 WHERE `uid` = %d AND `rel` IN ( %d, %d )
281 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
282 intval($uinfo[0]['uid']),
283 intval(CONTACT_IS_SHARING),
284 intval(CONTACT_IS_FRIEND)
286 $countfriends = $r[0]['count'];
288 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
289 WHERE `uid` = %d AND `rel` IN ( %d, %d )
290 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
291 intval($uinfo[0]['uid']),
292 intval(CONTACT_IS_FOLLOWER),
293 intval(CONTACT_IS_FRIEND)
295 $countfollowers = $r[0]['count'];
297 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
298 intval($uinfo[0]['uid'])
300 $starred = $r[0]['count'];
303 if(! $uinfo[0]['self']) {
310 'id' => intval($uinfo[0]['cid']),
311 'self' => intval($uinfo[0]['self']),
312 'uid' => intval($uinfo[0]['uid']),
313 'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
314 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
315 'location' => ($usr) ? $usr[0]['default-location'] : '',
316 'profile_image_url' => $uinfo[0]['micro'],
317 'url' => $uinfo[0]['url'],
318 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
319 'protected' => false,
320 'friends_count' => intval($countfriends),
321 'created_at' => api_date($uinfo[0]['name-date']),
322 'utc_offset' => "+00:00",
323 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
324 'geo_enabled' => false,
325 'statuses_count' => intval($countitms), #XXX: fix me
326 'lang' => 'en', #XXX: fix me
327 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
328 'followers_count' => intval($countfollowers),
329 'favourites_count' => intval($starred),
330 'contributors_enabled' => false,
331 'follow_request_sent' => true,
332 'profile_background_color' => 'cfe8f6',
333 'profile_text_color' => '000000',
334 'profile_link_color' => 'FF8500',
335 'profile_sidebar_fill_color' =>'AD0066',
336 'profile_sidebar_border_color' => 'AD0066',
337 'profile_background_image_url' => '',
338 'profile_background_tile' => false,
339 'profile_use_background_image' => false,
340 'notifications' => false,
341 'following' => '', #XXX: fix me
342 'verified' => true, #XXX: fix me
350 function api_item_get_user(&$a, $item) {
353 // The author is our direct contact, in a conversation with us.
354 if(link_compare($item['url'],$item['author-link'])) {
355 return api_get_user($a,$item['cid']);
358 // The author may be a contact of ours, but is replying to somebody else.
359 // Figure out if we know him/her.
360 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
361 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
362 return api_get_user($a,$a->contacts[$normalised]['id']);
364 // We don't know this person directly.
366 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
367 $name=str_replace(")","",$name);
375 // Generating a random ID
376 if (!array_key_exists($nick, $usercache))
377 $usercache[$nick] = mt_rand(2000000, 2100000);
380 'id' => $usercache[$nick],
382 'screen_name' => $nick,
383 'location' => '', //$uinfo[0]['default-location'],
385 'profile_image_url' => $item['author-avatar'],
386 'url' => $item['author-link'],
387 'protected' => false, #
388 'followers_count' => 0,
389 'friends_count' => 0,
391 'favourites_count' => 0,
392 'utc_offset' => 0, #XXX: fix me
393 'time_zone' => '', //$uinfo[0]['timezone'],
394 'statuses_count' => 0,
396 'statusnet_blocking' => false,
397 'notifications' => false,
400 'geo_enabled' => false,
401 'lang' => 'en', #XXX: fix me
402 'contributors_enabled' => false,
403 'follow_request_sent' => false,
404 'profile_background_color' => 'cfe8f6',
405 'profile_text_color' => '000000',
406 'profile_link_color' => 'FF8500',
407 'profile_sidebar_fill_color' =>'AD0066',
408 'profile_sidebar_border_color' => 'AD0066',
409 'profile_background_image_url' => '',
410 'profile_background_tile' => false,
411 'profile_use_background_image' => false,
412 'verified' => true, #XXX: fix me
413 'followers' => '', #XXX: fix me
422 * load api $templatename for $type and replace $data array
424 function api_apply_template($templatename, $type, $data){
432 $data = array_xmlify($data);
433 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
434 $ret = replace_macros($tpl, $data);
448 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
449 * returns a 401 status code and an error message if not.
450 * http://developer.twitter.com/doc/get/account/verify_credentials
452 function api_account_verify_credentials(&$a, $type){
453 if (local_user()===false) return false;
454 $user_info = api_get_user($a);
456 return api_apply_template("user", $type, array('$user' => $user_info));
459 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
463 * get data from $_POST or $_GET
465 function requestdata($k){
466 if (isset($_POST[$k])){
469 if (isset($_GET[$k])){
475 /*Waitman Gobble Mod*/
476 function api_statuses_mediap(&$a, $type) {
477 if (local_user()===false) {
478 logger('api_statuses_update: no user');
481 $user_info = api_get_user($a);
483 $_REQUEST['type'] = 'wall';
484 $_REQUEST['profile_uid'] = local_user();
485 $_REQUEST['api_source'] = true;
486 $txt = urldecode(requestdata('status'));
488 require_once('library/HTMLPurifier.auto.php');
489 require_once('include/html2bbcode.php');
491 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
492 $txt = html2bb_video($txt);
493 $config = HTMLPurifier_Config::createDefault();
494 $config->set('Cache.DefinitionImpl', null);
495 $purifier = new HTMLPurifier($config);
496 $txt = $purifier->purify($txt);
498 $txt = html2bbcode($txt);
500 $a->argv[1]=$user_info['screen_name']; //should be set to username?
502 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
503 require_once('mod/wall_upload.php');
504 $bebop = wall_upload_post($a);
506 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
507 $_REQUEST['body']=$txt."\n\n".$bebop;
508 require_once('mod/item.php');
511 // this should output the last post (the one we just posted).
512 return api_status_show($a,$type);
514 api_register_func('api/statuses/mediap','api_statuses_mediap', true);
515 /*Waitman Gobble Mod*/
518 function api_statuses_update(&$a, $type) {
519 if (local_user()===false) {
520 logger('api_statuses_update: no user');
523 $user_info = api_get_user($a);
525 // convert $_POST array items to the form we use for web posts.
527 // logger('api_post: ' . print_r($_POST,true));
529 if(requestdata('htmlstatus')) {
530 require_once('library/HTMLPurifier.auto.php');
531 require_once('include/html2bbcode.php');
533 $txt = requestdata('htmlstatus');
534 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
536 $txt = html2bb_video($txt);
538 $config = HTMLPurifier_Config::createDefault();
539 $config->set('Cache.DefinitionImpl', null);
542 $purifier = new HTMLPurifier($config);
543 $txt = $purifier->purify($txt);
545 $_REQUEST['body'] = html2bbcode($txt);
550 $_REQUEST['body'] = urldecode(requestdata('status'));
552 $parent = requestdata('in_reply_to_status_id');
553 if(ctype_digit($parent))
554 $_REQUEST['parent'] = $parent;
556 $_REQUEST['parent_uri'] = $parent;
558 if(requestdata('lat') && requestdata('long'))
559 $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
560 $_REQUEST['profile_uid'] = local_user();
561 if(requestdata('parent'))
562 $_REQUEST['type'] = 'net-comment';
564 $_REQUEST['type'] = 'wall';
566 // set this so that the item_post() function is quiet and doesn't redirect or emit json
568 $_REQUEST['api_source'] = true;
570 // call out normal post function
572 require_once('mod/item.php');
575 // this should output the last post (the one we just posted).
576 return api_status_show($a,$type);
578 api_register_func('api/statuses/update','api_statuses_update', true);
581 function api_status_show(&$a, $type){
582 $user_info = api_get_user($a);
583 // get last public wall message
584 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
585 FROM `item`, `contact`,
586 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
587 WHERE `item`.`contact-id` = %d
588 AND `i`.`id` = `item`.`parent`
589 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
590 AND `type`!='activity'
591 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
592 ORDER BY `created` DESC
594 intval($user_info['id'])
597 if (count($lastwall)>0){
598 $lastwall = $lastwall[0];
600 $in_reply_to_status_id = '';
601 $in_reply_to_user_id = '';
602 $in_reply_to_screen_name = '';
603 if ($lastwall['parent']!=$lastwall['id']) {
604 $in_reply_to_status_id=$lastwall['parent'];
605 $in_reply_to_user_id = $lastwall['reply_uid'];
606 $in_reply_to_screen_name = $lastwall['reply_author'];
608 $status_info = array(
609 'text' => html2plain(bbcode($lastwall['body']), 0),
610 'truncated' => false,
611 'created_at' => api_date($lastwall['created']),
612 'in_reply_to_status_id' => $in_reply_to_status_id,
613 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
614 'id' => $lastwall['contact-id'],
615 'in_reply_to_user_id' => $in_reply_to_user_id,
616 'in_reply_to_screen_name' => $in_reply_to_screen_name,
618 'favorited' => false,
619 'coordinates' => $lastwall['coord'],
620 'place' => $lastwall['location'],
623 $status_info['user'] = $user_info;
625 return api_apply_template("status", $type, array('$status' => $status_info));
634 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
635 * The author's most recent status will be returned inline.
636 * http://developer.twitter.com/doc/get/users/show
638 function api_users_show(&$a, $type){
639 $user_info = api_get_user($a);
640 // get last public wall message
641 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
642 FROM `item`, `contact`,
643 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
644 WHERE `item`.`contact-id` = %d
645 AND `i`.`id` = `item`.`parent`
646 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
647 AND `type`!='activity'
648 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
649 ORDER BY `created` DESC
651 intval($user_info['id'])
654 if (count($lastwall)>0){
655 $lastwall = $lastwall[0];
657 $in_reply_to_status_id = '';
658 $in_reply_to_user_id = '';
659 $in_reply_to_screen_name = '';
660 if ($lastwall['parent']!=$lastwall['id']) {
661 $in_reply_to_status_id=$lastwall['parent'];
662 $in_reply_to_user_id = $lastwall['reply_uid'];
663 $in_reply_to_screen_name = $lastwall['reply_author'];
665 $user_info['status'] = array(
666 'created_at' => api_date($lastwall['created']),
667 'id' => $lastwall['contact-id'],
668 'text' => html2plain(bbcode($lastwall['body']), 0),
669 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
670 'truncated' => false,
671 'in_reply_to_status_id' => $in_reply_to_status_id,
672 'in_reply_to_user_id' => $in_reply_to_user_id,
673 'favorited' => false,
674 'in_reply_to_screen_name' => $in_reply_to_screen_name,
676 'coordinates' => $lastwall['coord'],
677 'place' => $lastwall['location'],
681 return api_apply_template("user", $type, array('$user' => $user_info));
684 api_register_func('api/users/show','api_users_show');
688 * http://developer.twitter.com/doc/get/statuses/home_timeline
690 * TODO: Optional parameters
691 * TODO: Add reply info
693 function api_statuses_home_timeline(&$a, $type){
694 if (local_user()===false) return false;
696 $user_info = api_get_user($a);
697 // get last newtork messages
701 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
702 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
703 if ($page<0) $page=0;
704 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
705 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
706 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
708 $start = $page*$count;
710 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
713 $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
715 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
716 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
717 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
718 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
719 FROM `item`, `contact`
720 WHERE `item`.`uid` = %d
721 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
722 AND `contact`.`id` = `item`.`contact-id`
723 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
726 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
727 intval($user_info['uid']),
729 intval($start), intval($count)
732 $ret = api_format_items($r,$user_info);
735 $data = array('$statuses' => $ret);
739 $data = api_rss_extra($a, $data, $user_info);
742 return api_apply_template("timeline", $type, $data);
744 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
745 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
750 function api_statuses_show(&$a, $type){
751 if (local_user()===false) return false;
753 $user_info = api_get_user($a);
756 $id = intval($a->argv[3]);
758 logger('API: api_statuses_show: '.$id);
760 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
762 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
763 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
764 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
765 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
766 FROM `item`, `contact`
767 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
768 AND `contact`.`id` = `item`.`contact-id`
769 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
775 $ret = api_format_items($r,$user_info);
777 $data = array('$status' => $ret[0]);
781 $data = api_rss_extra($a, $data, $user_info);
783 return api_apply_template("status", $type, $data);
785 api_register_func('api/statuses/show','api_statuses_show', true);
791 function api_statuses_repeat(&$a, $type){
792 if (local_user()===false) return false;
794 $user_info = api_get_user($a);
797 $id = intval($a->argv[3]);
799 logger('API: api_statuses_repeat: '.$id);
801 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
803 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
804 `contact`.`name`, `contact`.`photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
805 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
806 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
807 FROM `item`, `contact`
808 WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
809 AND `contact`.`id` = `item`.`contact-id`
810 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
816 $_REQUEST['body'] = html_entity_decode("♲ ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
817 $_REQUEST['profile_uid'] = local_user();
818 $_REQUEST['type'] = 'wall';
819 $_REQUEST['api_source'] = true;
821 require_once('mod/item.php');
829 return api_apply_template('test', $type, array('$ok' => $ok));
831 api_register_func('api/statuses/retweet','api_statuses_repeat', true);
836 function api_statuses_destroy(&$a, $type){
837 if (local_user()===false) return false;
839 $user_info = api_get_user($a);
842 $id = intval($a->argv[3]);
844 logger('API: api_statuses_destroy: '.$id);
846 require_once('include/items.php');
847 drop_item($id, false);
854 return api_apply_template('test', $type, array('$ok' => $ok));
856 api_register_func('api/statuses/destroy','api_statuses_destroy', true);
860 * http://developer.twitter.com/doc/get/statuses/mentions
863 function api_statuses_mentions(&$a, $type){
864 if (local_user()===false) return false;
866 $user_info = api_get_user($a);
867 // get last newtork messages
871 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
872 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
873 if ($page<0) $page=0;
874 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
875 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
876 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
878 $start = $page*$count;
880 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
882 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
883 $myurl = substr($myurl,strpos($myurl,'://')+3);
884 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
885 $diasp_url = str_replace('/profile/','/u/',$myurl);
886 $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where ( `author-link` regexp '%s' or `tag` regexp '%s' or tag regexp '%s' )) ",
888 dbesc($myurl . '\\]'),
889 dbesc($diasp_url . '\\]')
893 $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
895 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
896 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
897 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
898 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
899 FROM `item`, `contact`
900 WHERE `item`.`uid` = %d
901 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
902 AND `contact`.`id` = `item`.`contact-id`
903 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
906 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
907 intval($user_info['uid']),
909 intval($start), intval($count)
912 $ret = api_format_items($r,$user_info);
915 $data = array('$statuses' => $ret);
919 $data = api_rss_extra($a, $data, $user_info);
922 return api_apply_template("timeline", $type, $data);
924 api_register_func('api/statuses/mentions','api_statuses_mentions', true);
925 api_register_func('api/statuses/replies','api_statuses_mentions', true);
928 function api_statuses_user_timeline(&$a, $type){
929 if (local_user()===false) return false;
931 $user_info = api_get_user($a);
932 // get last newtork messages
935 logger("api_statuses_user_timeline: local_user: ". local_user() .
936 "\nuser_info: ".print_r($user_info, true) .
937 "\n_REQUEST: ".print_r($_REQUEST, true),
941 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
942 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
943 if ($page<0) $page=0;
944 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
945 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
947 $start = $page*$count;
949 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
951 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
952 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
953 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
954 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
955 FROM `item`, `contact`
956 WHERE `item`.`uid` = %d
957 AND `item`.`contact-id` = %d
958 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
959 AND `contact`.`id` = `item`.`contact-id`
960 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
963 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
964 intval(local_user()),
965 intval($user_info['id']),
967 intval($start), intval($count)
970 $ret = api_format_items($r,$user_info);
973 $data = array('$statuses' => $ret);
977 $data = api_rss_extra($a, $data, $user_info);
980 return api_apply_template("timeline", $type, $data);
983 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
986 function api_favorites(&$a, $type){
987 if (local_user()===false) return false;
989 $user_info = api_get_user($a);
990 // in friendica starred item are private
991 // return favorites only for self
992 logger('api_favorites: self:' . $user_info['self']);
994 if ($user_info['self']==0) {
1000 $count = (x($_GET,'count')?$_GET['count']:20);
1001 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1002 if ($page<0) $page=0;
1004 $start = $page*$count;
1006 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1007 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1008 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1009 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1010 FROM `item`, `contact`
1011 WHERE `item`.`uid` = %d
1012 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1013 AND `item`.`starred` = 1
1014 AND `contact`.`id` = `item`.`contact-id`
1015 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1017 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1018 intval($user_info['uid']),
1019 intval($start), intval($count)
1022 $ret = api_format_items($r,$user_info);
1026 $data = array('$statuses' => $ret);
1030 $data = api_rss_extra($a, $data, $user_info);
1033 return api_apply_template("timeline", $type, $data);
1036 api_register_func('api/favorites','api_favorites', true);
1039 function api_format_items($r,$user_info) {
1041 //logger('api_format_items: ' . print_r($r,true));
1043 //logger('api_format_items: ' . print_r($user_info,true));
1048 foreach($r as $item) {
1049 localize_item($item);
1050 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
1052 if ($item['parent']!=$item['id']) {
1053 $r = q("select id from item where parent=%s and id<%s order by id desc limit 1",
1054 intval($item['parent']), intval($item['id']));
1056 $in_reply_to_status_id = $r[0]['id'];
1058 $in_reply_to_status_id = $item['parent'];
1060 $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact
1061 where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id));
1063 $in_reply_to_screen_name = $r[0]['author-name'];
1064 $in_reply_to_user_id = $r[0]['contact-id'];
1067 $in_reply_to_screen_name = '';
1068 $in_reply_to_user_id = 0;
1069 $in_reply_to_status_id = 0;
1073 'text' => trim($item['title']." \n".html2plain(bbcode($item['body']), 0)),
1074 'truncated' => False,
1075 'created_at'=> api_date($item['created']),
1076 'in_reply_to_status_id' => $in_reply_to_status_id,
1077 'source' => (($item['app']) ? $item['app'] : 'web'),
1078 'id' => intval($item['id']),
1079 'in_reply_to_user_id' => $in_reply_to_user_id,
1080 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1082 'favorited' => $item['starred'] ? true : false,
1083 'user' => $status_user ,
1084 'statusnet_html' => bbcode($item['body']),
1085 'statusnet_conversation_id' => 0,
1088 // Seesmic doesn't like the following content
1089 if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1091 'updated' => api_date($item['edited']),
1092 'published' => api_date($item['created']),
1093 'message_id' => $item['uri'],
1094 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
1095 'coordinates' => $item['coord'],
1096 'place' => $item['location'],
1097 'contributors' => '',
1098 'annotations' => '',
1100 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1101 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1102 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1103 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1106 $status = array_merge($status, $status2);
1115 function api_account_rate_limit_status(&$a,$type) {
1118 'reset_time_in_seconds' => strtotime('now + 1 hour'),
1119 'remaining_hits' => (string) 150,
1120 'hourly_limit' => (string) 150,
1121 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1124 $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1126 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1129 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1131 function api_help_test(&$a,$type) {
1138 return api_apply_template('test', $type, array('$ok' => $ok));
1141 api_register_func('api/help/test','api_help_test',true);
1144 * https://dev.twitter.com/docs/api/1/get/statuses/friends
1145 * This function is deprecated by Twitter
1146 * returns: json, xml
1148 function api_statuses_f(&$a, $type, $qtype) {
1149 if (local_user()===false) return false;
1150 $user_info = api_get_user($a);
1153 // friends and followers only for self
1154 if ($user_info['self']==0){
1158 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1159 /* this is to stop Hotot to load friends multiple times
1160 * I'm not sure if I'm missing return something or
1161 * is a bug in hotot. Workaround, meantime
1165 return array('$users' => $ret);*/
1169 if($qtype == 'friends')
1170 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1171 if($qtype == 'followers')
1172 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1174 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1175 intval(local_user())
1179 foreach($r as $cid){
1180 $ret[] = api_get_user($a, $cid['id']);
1184 return array('$users' => $ret);
1187 function api_statuses_friends(&$a, $type){
1188 $data = api_statuses_f($a,$type,"friends");
1189 if ($data===false) return false;
1190 return api_apply_template("friends", $type, $data);
1192 function api_statuses_followers(&$a, $type){
1193 $data = api_statuses_f($a,$type,"followers");
1194 if ($data===false) return false;
1195 return api_apply_template("friends", $type, $data);
1197 api_register_func('api/statuses/friends','api_statuses_friends',true);
1198 api_register_func('api/statuses/followers','api_statuses_followers',true);
1205 function api_statusnet_config(&$a,$type) {
1206 $name = $a->config['sitename'];
1207 $server = $a->get_hostname();
1208 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1209 $email = $a->config['admin_email'];
1210 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1211 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1212 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1213 if($a->config['api_import_size'])
1214 $texlimit = string($a->config['api_import_size']);
1215 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1216 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1219 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1220 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1221 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1222 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1223 'shorturllength' => '30'
1227 return api_apply_template('config', $type, array('$config' => $config));
1230 api_register_func('api/statusnet/config','api_statusnet_config',false);
1232 function api_statusnet_version(&$a,$type) {
1236 if($type === 'xml') {
1237 header("Content-type: application/xml");
1238 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1241 elseif($type === 'json') {
1242 header("Content-type: application/json");
1247 api_register_func('api/statusnet/version','api_statusnet_version',false);
1250 function api_ff_ids(&$a,$type,$qtype) {
1254 if($qtype == 'friends')
1255 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1256 if($qtype == 'followers')
1257 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1260 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1261 intval(local_user())
1265 if($type === 'xml') {
1266 header("Content-type: application/xml");
1267 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1269 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1270 echo '</ids>' . "\r\n";
1273 elseif($type === 'json') {
1275 header("Content-type: application/json");
1276 foreach($r as $rr) $ret[] = $rr['id'];
1277 echo json_encode($ret);
1283 function api_friends_ids(&$a,$type) {
1284 api_ff_ids($a,$type,'friends');
1286 function api_followers_ids(&$a,$type) {
1287 api_ff_ids($a,$type,'followers');
1289 api_register_func('api/friends/ids','api_friends_ids',true);
1290 api_register_func('api/followers/ids','api_followers_ids',true);
1293 function api_direct_messages_new(&$a, $type) {
1294 if (local_user()===false) return false;
1296 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1298 $sender = api_get_user($a);
1300 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1301 intval(local_user()),
1302 dbesc($_POST['screen_name']));
1304 $recipient = api_get_user($a, $r[0]['id']);
1307 require_once("include/message.php");
1308 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1309 $id = send_message($recipient['id'], $_POST['text'], $sub);
1313 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1316 'id' => $item['id'],
1317 'created_at'=> api_date($item['created']),
1318 'sender_id'=> $sender['id'] ,
1319 'sender_screen_name'=> $sender['screen_name'],
1321 'recipient_id'=> $recipient['id'],
1322 'recipient_screen_name'=> $recipient['screen_name'],
1323 'recipient'=> $recipient,
1325 'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1330 $ret = array("error"=>$id);
1333 $data = Array('$messages'=>$ret);
1338 $data = api_rss_extra($a, $data, $user_info);
1341 return api_apply_template("direct_messages", $type, $data);
1344 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1346 function api_direct_messages_box(&$a, $type, $box) {
1347 if (local_user()===false) return false;
1349 $user_info = api_get_user($a);
1352 $count = (x($_GET,'count')?$_GET['count']:20);
1353 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1354 if ($page<0) $page=0;
1356 $start = $page*$count;
1359 if ($box=="sentbox") {
1360 $sql_extra = "`from-url`='%s'";
1362 $sql_extra = "`from-url`!='%s'";
1365 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1366 intval(local_user()),
1367 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1368 intval($start), intval($count)
1372 foreach($r as $item){
1375 $recipient = $user_info;
1376 $sender = api_get_user($a,$item['contact-id']);
1379 $recipient = api_get_user($a,$item['contact-id']);
1380 $sender = $user_info;
1385 'id' => $item['id'],
1386 'created_at'=> api_date($item['created']),
1387 'sender_id'=> $sender['id'] ,
1388 'sender_screen_name'=> $sender['screen_name'],
1390 'recipient_id'=> $recipient['id'],
1391 'recipient_screen_name'=> $recipient['screen_name'],
1392 'recipient'=> $recipient,
1394 'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1401 $data = array('$messages' => $ret);
1405 $data = api_rss_extra($a, $data, $user_info);
1408 return api_apply_template("direct_messages", $type, $data);
1412 function api_direct_messages_sentbox(&$a, $type){
1413 return api_direct_messages_box($a, $type, "sentbox");
1415 function api_direct_messages_inbox(&$a, $type){
1416 return api_direct_messages_box($a, $type, "inbox");
1418 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1419 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1423 function api_oauth_request_token(&$a, $type){
1425 $oauth = new FKOAuth1();
1426 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1427 }catch(Exception $e){
1428 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1433 function api_oauth_access_token(&$a, $type){
1435 $oauth = new FKOAuth1();
1436 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1437 }catch(Exception $e){
1438 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1444 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1445 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1448 Not implemented by now:
1452 statuses/public_timeline
1453 statuses/retweets_of_me
1458 account/update_location
1459 account/update_profile_background_image
1460 account/update_profile_image
1465 Not implemented in status.net:
1466 statuses/retweeted_to_me
1467 statuses/retweeted_by_me
1468 direct_messages/destroy
1470 account/update_delivery_device
1471 notifications/follow