2 require_once("bbcode.php");
3 require_once("datetime.php");
4 require_once("conversation.php");
5 require_once("oauth.php");
14 function api_date($str){
15 //Wed May 23 06:01:13 +0000 2007
16 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
20 function api_register_func($path, $func, $auth=false){
22 $API[$path] = array('func'=>$func,
29 function api_login(&$a){
32 $oauth = new FKOAuth1();
33 list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
34 if (!is_null($token)){
35 $oauth->loginUser($token->uid);
36 call_hooks('logged_in', $a->user);
39 echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
41 logger(__file__.__line__.__function__."\n".$e);
42 //die(__file__.__line__.__function__."<pre>".$e); die();
47 // workaround for HTTP-auth in CGI mode
48 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
49 $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
50 if(strlen($userpass)) {
51 list($name, $password) = explode(':', $userpass);
52 $_SERVER['PHP_AUTH_USER'] = $name;
53 $_SERVER['PHP_AUTH_PW'] = $password;
57 if (!isset($_SERVER['PHP_AUTH_USER'])) {
58 logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
59 header('WWW-Authenticate: Basic realm="Friendika"');
60 header('HTTP/1.0 401 Unauthorized');
61 die('This api requires login');
64 $user = $_SERVER['PHP_AUTH_USER'];
65 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
69 * next code from mod/auth.php. needs better solution
72 // process normal login request
74 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' )
75 AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
83 logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
84 header('WWW-Authenticate: Basic realm="Friendika"');
85 header('HTTP/1.0 401 Unauthorized');
86 die('This api requires login');
88 $_SESSION['uid'] = $record['uid'];
89 $_SESSION['theme'] = $record['theme'];
90 $_SESSION['authenticated'] = 1;
91 $_SESSION['page_flags'] = $record['page-flags'];
92 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
93 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
95 //notice( t("Welcome back ") . $record['username'] . EOL);
98 if(strlen($a->user['timezone'])) {
99 date_default_timezone_set($a->user['timezone']);
100 $a->timezone = $a->user['timezone'];
103 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
104 intval($_SESSION['uid']));
107 $a->cid = $r[0]['id'];
108 $_SESSION['cid'] = $a->cid;
110 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
111 dbesc(datetime_convert()),
112 intval($_SESSION['uid'])
115 call_hooks('logged_in', $a->user);
117 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
120 /**************************
121 * MAIN API ENTRY POINT *
122 **************************/
123 function api_call(&$a){
124 GLOBAL $API, $called_api;
125 foreach ($API as $p=>$info){
126 if (strpos($a->query_string, $p)===0){
127 $called_api= explode("/",$p);
128 #unset($_SERVER['PHP_AUTH_USER']);
129 if ($info['auth']===true && local_user()===false) {
133 load_contact_links(local_user());
135 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
136 logger('API parameters: ' . print_r($_REQUEST,true));
138 if (strpos($a->query_string, ".xml")>0) $type="xml";
139 if (strpos($a->query_string, ".json")>0) $type="json";
140 if (strpos($a->query_string, ".rss")>0) $type="rss";
141 if (strpos($a->query_string, ".atom")>0) $type="atom";
143 $r = call_user_func($info['func'], $a, $type);
144 if ($r===false) return;
148 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
149 header ("Content-Type: text/xml");
150 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
153 //header ("Content-Type: application/json");
155 return json_encode($rr);
158 header ("Content-Type: application/rss+xml");
159 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
162 header ("Content-Type: application/atom+xml");
163 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
167 //echo "<pre>"; var_dump($r); die();
170 $r = '<status><error>not implemented</error></status>';
173 header ("Content-Type: text/xml");
174 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
177 header ("Content-Type: application/json");
178 return json_encode(array('error' => 'not implemented'));
181 header ("Content-Type: application/rss+xml");
182 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
185 header ("Content-Type: application/atom+xml");
186 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
195 function api_rss_extra(&$a, $arr, $user_info){
196 if (is_null($user_info)) $user_info = api_get_user($a);
197 $arr['$user'] = $user_info;
198 $arr['$rss'] = array(
199 'alternate' => $user_info['url'],
200 'self' => $a->get_baseurl(). "/". $a->query_string,
201 'base' => $a->get_baseurl(),
202 'updated' => api_date(null),
203 'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
204 'language' => $user_info['language'],
205 'logo' => $a->get_baseurl()."/images/friendika-32.png",
212 * Returns user info array.
214 function api_get_user(&$a, $contact_id = Null){
220 if(!is_null($contact_id)){
222 $extra_query = "AND `contact`.`id` = %d ";
225 if(is_null($user) && x($_GET, 'user_id')) {
226 $user = intval($_GET['user_id']);
227 $extra_query = "AND `contact`.`id` = %d ";
229 if(is_null($user) && x($_GET, 'screen_name')) {
230 $user = dbesc($_GET['screen_name']);
231 $extra_query = "AND `contact`.`nick` = '%s' ";
232 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
236 if (is_null($user) && $a->argc > (count($called_api)-1)){
237 $argid = count($called_api);
238 list($user, $null) = explode(".",$a->argv[$argid]);
239 if(is_numeric($user)){
240 $user = intval($user);
241 $extra_query = "AND `contact`.`id` = %d ";
243 $user = dbesc($user);
244 $extra_query = "AND `contact`.`nick` = '%s' ";
245 if (local_user()!==false) $extra_query .= "AND `contact`.`uid`=".intval(local_user());
250 if (local_user()===false) {
251 api_login($a); return False;
253 $user = $_SESSION['uid'];
254 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
259 logger('api_user: ' . $extra_query . ' ' , $user);
261 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
266 if (count($uinfo)==0) {
270 if($uinfo[0]['self']) {
271 $usr = q("select * from user where uid = %d limit 1",
274 $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
278 // count public wall messages
279 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
282 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
283 intval($uinfo[0]['uid'])
285 $countitms = $r[0]['count'];
288 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
289 WHERE `contact-id` = %d
290 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
291 intval($uinfo[0]['id'])
293 $countitms = $r[0]['count'];
297 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
298 WHERE `uid` = %d AND `rel` IN ( %d, %d )
299 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
300 intval($uinfo[0]['uid']),
301 intval(CONTACT_IS_SHARING),
302 intval(CONTACT_IS_FRIEND)
304 $countfriends = $r[0]['count'];
306 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
307 WHERE `uid` = %d AND `rel` IN ( %d, %d )
308 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0",
309 intval($uinfo[0]['uid']),
310 intval(CONTACT_IS_FOLLOWER),
311 intval(CONTACT_IS_FRIEND)
313 $countfollowers = $r[0]['count'];
315 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
316 intval($uinfo[0]['uid'])
318 $starred = $r[0]['count'];
321 if(! $uinfo[0]['self']) {
328 'self' => intval($uinfo[0]['self']),
329 'uid' => intval($uinfo[0]['uid']),
330 'id' => intval($uinfo[0]['cid']),
331 'name' => $uinfo[0]['name'],
332 'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
333 'location' => ($usr) ? $usr[0]['default-location'] : '',
334 'profile_image_url' => $uinfo[0]['micro'],
335 'url' => $uinfo[0]['url'],
336 'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
337 'protected' => false,
338 'friends_count' => intval($countfriends),
339 'created_at' => api_date($uinfo[0]['name-date']),
340 'utc_offset' => "+00:00",
341 'time_zone' => 'UTC', //$uinfo[0]['timezone'],
342 'geo_enabled' => false,
343 'statuses_count' => intval($countitms), #XXX: fix me
344 'lang' => 'en', #XXX: fix me
345 'description' => (($profile) ? $profile[0]['pdesc'] : ''),
346 'followers_count' => intval($countfollowers),
347 'favourites_count' => intval($starred),
348 'contributors_enabled' => false,
349 'follow_request_sent' => true,
350 'profile_background_color' => 'cfe8f6',
351 'profile_text_color' => '000000',
352 'profile_link_color' => 'FF8500',
353 'profile_sidebar_fill_color' =>'AD0066',
354 'profile_sidebar_border_color' => 'AD0066',
355 'profile_background_image_url' => '',
356 'profile_background_tile' => false,
357 'profile_use_background_image' => false,
358 'notifications' => false,
359 'following' => '', #XXX: fix me
360 'verified' => true, #XXX: fix me
368 function api_item_get_user(&$a, $item) {
369 // The author is our direct contact, in a conversation with us.
370 if(link_compare($item['url'],$item['author-link'])) {
371 return api_get_user($a,$item['cid']);
374 // The author may be a contact of ours, but is replying to somebody else.
375 // Figure out if we know him/her.
376 $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
377 if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
378 return api_get_user($a,$a->contacts[$normalised]['id']);
380 // We don't know this person directly.
382 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
383 $name=str_replace(")","",$name);
389 'screen_name' => $nick,
390 'location' => '', //$uinfo[0]['default-location'],
391 'profile_image_url' => $item['author-avatar'],
392 'url' => $item['author-link'],
394 'protected' => false, #
395 'friends_count' => 0,
397 'utc_offset' => 0, #XXX: fix me
398 'time_zone' => '', //$uinfo[0]['timezone'],
399 'geo_enabled' => false,
400 'statuses_count' => 0,
401 'lang' => 'en', #XXX: fix me
403 'followers_count' => 0,
404 'favourites_count' => 0,
405 'contributors_enabled' => false,
406 'follow_request_sent' => false,
407 'profile_background_color' => 'cfe8f6',
408 'profile_text_color' => '000000',
409 'profile_link_color' => 'FF8500',
410 'profile_sidebar_fill_color' =>'AD0066',
411 'profile_sidebar_border_color' => 'AD0066',
412 'profile_background_image_url' => '',
413 'profile_background_tile' => false,
414 'profile_use_background_image' => false,
415 'notifications' => false,
416 'verified' => true, #XXX: fix me
417 'followers' => '', #XXX: fix me
426 * load api $templatename for $type and replace $data array
428 function api_apply_template($templatename, $type, $data){
436 $data = array_xmlify($data);
437 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
438 $ret = replace_macros($tpl, $data);
452 * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful;
453 * returns a 401 status code and an error message if not.
454 * http://developer.twitter.com/doc/get/account/verify_credentials
456 function api_account_verify_credentials(&$a, $type){
457 if (local_user()===false) return false;
458 $user_info = api_get_user($a);
460 return api_apply_template("user", $type, array('$user' => $user_info));
463 api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
467 * get data from $_POST or $_GET
469 function requestdata($k){
470 if (isset($_POST[$k])){
473 if (isset($_GET[$k])){
479 // TODO - media uploads
480 function api_statuses_update(&$a, $type) {
481 if (local_user()===false) return false;
482 $user_info = api_get_user($a);
484 // convert $_POST array items to the form we use for web posts.
486 // logger('api_post: ' . print_r($_POST,true));
488 if(requestdata('htmlstatus')) {
489 require_once('library/HTMLPurifier.auto.php');
490 require_once('include/html2bbcode.php');
492 $txt = requestdata('htmlstatus');
493 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
495 $txt = html2bb_video($txt);
497 $config = HTMLPurifier_Config::createDefault();
498 $config->set('Cache.DefinitionImpl', null);
501 $purifier = new HTMLPurifier($config);
502 $txt = $purifier->purify($txt);
504 $_POST['body'] = html2bbcode($txt);
509 $_POST['body'] = urldecode(requestdata('status'));
511 $parent = requestdata('in_reply_to_status_id');
512 if(ctype_digit($parent))
513 $_POST['parent'] = $parent;
515 $_POST['parent_uri'] = $parent;
517 if(requestdata('lat') && requestdata('long'))
518 $_POST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
519 $_POST['profile_uid'] = local_user();
520 if(requestdata('parent'))
521 $_POST['type'] = 'net-comment';
523 $_POST['type'] = 'wall';
525 // set this so that the item_post() function is quiet and doesn't redirect or emit json
527 $_POST['api_source'] = true;
529 // call out normal post function
531 require_once('mod/item.php');
534 // this should output the last post (the one we just posted).
535 return api_status_show($a,$type);
537 api_register_func('api/statuses/update','api_statuses_update', true);
540 function api_status_show(&$a, $type){
541 $user_info = api_get_user($a);
542 // get last public wall message
543 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
544 FROM `item`, `contact`,
545 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
546 WHERE `item`.`contact-id` = %d
547 AND `i`.`id` = `item`.`parent`
548 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
549 AND `type`!='activity'
550 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
551 ORDER BY `created` DESC
553 intval($user_info['id'])
556 if (count($lastwall)>0){
557 $lastwall = $lastwall[0];
559 $in_reply_to_status_id = '';
560 $in_reply_to_user_id = '';
561 $in_reply_to_screen_name = '';
562 if ($lastwall['parent']!=$lastwall['id']) {
563 $in_reply_to_status_id=$lastwall['parent'];
564 $in_reply_to_user_id = $lastwall['reply_uid'];
565 $in_reply_to_screen_name = $lastwall['reply_author'];
567 $status_info = array(
568 'created_at' => api_date($lastwall['created']),
569 'id' => $lastwall['contact-id'],
570 'text' => strip_tags(bbcode($lastwall['body'])),
571 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
572 'truncated' => false,
573 'in_reply_to_status_id' => $in_reply_to_status_id,
574 'in_reply_to_user_id' => $in_reply_to_user_id,
575 'favorited' => false,
576 'in_reply_to_screen_name' => $in_reply_to_screen_name,
578 'coordinates' => $lastwall['coord'],
579 'place' => $lastwall['location'],
582 $status_info['user'] = $user_info;
584 return api_apply_template("status", $type, array('$status' => $status_info));
593 * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
594 * The author's most recent status will be returned inline.
595 * http://developer.twitter.com/doc/get/users/show
597 function api_users_show(&$a, $type){
598 $user_info = api_get_user($a);
599 // get last public wall message
600 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
601 FROM `item`, `contact`,
602 (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i`
603 WHERE `item`.`contact-id` = %d
604 AND `i`.`id` = `item`.`parent`
605 AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
606 AND `type`!='activity'
607 AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
608 ORDER BY `created` DESC
610 intval($user_info['id'])
613 if (count($lastwall)>0){
614 $lastwall = $lastwall[0];
616 $in_reply_to_status_id = '';
617 $in_reply_to_user_id = '';
618 $in_reply_to_screen_name = '';
619 if ($lastwall['parent']!=$lastwall['id']) {
620 $in_reply_to_status_id=$lastwall['parent'];
621 $in_reply_to_user_id = $lastwall['reply_uid'];
622 $in_reply_to_screen_name = $lastwall['reply_author'];
624 $user_info['status'] = array(
625 'created_at' => api_date($lastwall['created']),
626 'id' => $lastwall['contact-id'],
627 'text' => strip_tags(bbcode($lastwall['body'])),
628 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
629 'truncated' => false,
630 'in_reply_to_status_id' => $in_reply_to_status_id,
631 'in_reply_to_user_id' => $in_reply_to_user_id,
632 'favorited' => false,
633 'in_reply_to_screen_name' => $in_reply_to_screen_name,
635 'coordinates' => $lastwall['coord'],
636 'place' => $lastwall['location'],
640 return api_apply_template("user", $type, array('$user' => $user_info));
643 api_register_func('api/users/show','api_users_show');
647 * http://developer.twitter.com/doc/get/statuses/home_timeline
649 * TODO: Optional parameters
650 * TODO: Add reply info
652 function api_statuses_home_timeline(&$a, $type){
653 if (local_user()===false) return false;
655 $user_info = api_get_user($a);
656 // get last newtork messages
660 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
661 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
662 if ($page<0) $page=0;
663 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
665 $start = $page*$count;
667 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
668 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
669 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
670 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
671 FROM `item`, `contact`
672 WHERE `item`.`uid` = %d
673 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
674 AND `contact`.`id` = `item`.`contact-id`
675 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
678 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
679 intval($user_info['uid']),
681 intval($start), intval($count)
684 $ret = api_format_items($r,$user_info);
687 $data = array('$statuses' => $ret);
691 $data = api_rss_extra($a, $data, $user_info);
694 return api_apply_template("timeline", $type, $data);
696 api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
697 api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
701 function api_statuses_user_timeline(&$a, $type){
702 if (local_user()===false) return false;
704 $user_info = api_get_user($a);
705 // get last newtork messages
708 logger("api_statuses_user_timeline: local_user: ". local_user() .
709 "\nuser_info: ".print_r($user_info, true) .
710 "\n_REQUEST: ".print_r($_REQUEST, true),
714 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
715 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
716 if ($page<0) $page=0;
717 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
719 $start = $page*$count;
721 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
723 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
724 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
725 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
726 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
727 FROM `item`, `contact`
728 WHERE `item`.`uid` = %d
729 AND `item`.`contact-id` = %d
730 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
731 AND `contact`.`id` = `item`.`contact-id`
732 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
735 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
736 intval(local_user()),
737 intval($user_info['id']),
739 intval($start), intval($count)
742 $ret = api_format_items($r,$user_info);
745 $data = array('$statuses' => $ret);
749 $data = api_rss_extra($a, $data, $user_info);
752 return api_apply_template("timeline", $type, $data);
755 api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
758 function api_favorites(&$a, $type){
759 if (local_user()===false) return false;
761 $user_info = api_get_user($a);
762 // in friendika starred item are private
763 // return favorites only for self
764 logger('api_favorites: self:' . $user_info['self']);
766 if ($user_info['self']==0) {
772 $count = (x($_GET,'count')?$_GET['count']:20);
773 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
774 if ($page<0) $page=0;
776 $start = $page*$count;
778 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
779 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
780 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
781 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
782 FROM `item`, `contact`
783 WHERE `item`.`uid` = %d
784 AND `item`.`visible` = 1 AND `item`.`deleted` = 0
785 AND `item`.`starred` = 1
786 AND `contact`.`id` = `item`.`contact-id`
787 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
789 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
790 intval($user_info['uid']),
791 intval($start), intval($count)
794 $ret = api_format_items($r,$user_info);
798 $data = array('$statuses' => $ret);
802 $data = api_rss_extra($a, $data, $user_info);
805 return api_apply_template("timeline", $type, $data);
808 api_register_func('api/favorites','api_favorites', true);
811 function api_format_items($r,$user_info) {
813 //logger('api_format_items: ' . print_r($r,true));
815 //logger('api_format_items: ' . print_r($user_info,true));
820 foreach($r as $item) {
821 localize_item($item);
822 $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
824 'created_at'=> api_date($item['created']),
825 'published' => api_date($item['created']),
826 'updated' => api_date($item['edited']),
827 'id' => intval($item['id']),
828 'message_id' => $item['uri'],
829 'text' => strip_tags(bbcode($item['body'])),
830 'statusnet_html' => bbcode($item['body']),
831 'source' => (($item['app']) ? $item['app'] : 'web'),
832 'url' => ($item['plink']!=''?$item['plink']:$item['author-link']),
833 'truncated' => False,
834 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
835 'in_reply_to_user_id' => '',
836 'favorited' => $item['starred'] ? true : false,
837 'in_reply_to_screen_name' => '',
839 'coordinates' => $item['coord'],
840 'place' => $item['location'],
841 'contributors' => '',
844 'user' => $status_user ,
845 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
846 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
847 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
848 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
856 function api_account_rate_limit_status(&$a,$type) {
859 'remaining_hits' => (string) 150,
860 'hourly_limit' => (string) 150,
861 'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
862 'reset_time_in_seconds' => strtotime('now + 1 hour')
865 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
868 api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
871 * https://dev.twitter.com/docs/api/1/get/statuses/friends
872 * This function is deprecated by Twitter
875 function api_statuses_f(&$a, $type, $qtype) {
876 if (local_user()===false) return false;
877 $user_info = api_get_user($a);
880 // friends and followers only for self
881 if ($user_info['self']==0){
885 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
886 /* this is to stop Hotot to load friends multiple times
887 * I'm not sure if I'm missing return something or
888 * is a bug in hotot. Workaround, meantime
892 return array('$users' => $ret);*/
896 if($qtype == 'friends')
897 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
898 if($qtype == 'followers')
899 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
901 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
907 $ret[] = api_get_user($a, $cid['id']);
911 return array('$users' => $ret);
914 function api_statuses_friends(&$a, $type){
915 $data = api_statuses_f($a,$type,"friends");
916 if ($data===false) return false;
917 return api_apply_template("friends", $type, $data);
919 function api_statuses_followers(&$a, $type){
920 $data = api_statuses_f($a,$type,"followers");
921 if ($data===false) return false;
922 return api_apply_template("friends", $type, $data);
924 api_register_func('api/statuses/friends','api_statuses_friends',true);
925 api_register_func('api/statuses/followers','api_statuses_followers',true);
932 function api_statusnet_config(&$a,$type) {
933 $name = $a->config['sitename'];
934 $server = $a->get_hostname();
935 $logo = $a->get_baseurl() . '/images/friendika-64.png';
936 $email = $a->config['admin_email'];
937 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
938 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
939 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
940 if($a->config['api_import_size'])
941 $texlimit = string($a->config['api_import_size']);
942 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
943 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
946 'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
947 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
948 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
949 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
950 'shorturllength' => '30'
954 return api_apply_template('config', $type, array('$config' => $config));
957 api_register_func('api/statusnet/config','api_statusnet_config',false);
959 function api_statusnet_version(&$a,$type) {
963 if($type === 'xml') {
964 header("Content-type: application/xml");
965 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
968 elseif($type === 'json') {
969 header("Content-type: application/json");
974 api_register_func('api/statusnet/version','api_statusnet_version',false);
977 function api_ff_ids(&$a,$type,$qtype) {
981 if($qtype == 'friends')
982 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
983 if($qtype == 'followers')
984 $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
987 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
992 if($type === 'xml') {
993 header("Content-type: application/xml");
994 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
996 echo '<id>' . $rr['id'] . '</id>' . "\r\n";
997 echo '</ids>' . "\r\n";
1000 elseif($type === 'json') {
1002 header("Content-type: application/json");
1003 foreach($r as $rr) $ret[] = $rr['id'];
1004 echo json_encode($ret);
1010 function api_friends_ids(&$a,$type) {
1011 api_ff_ids($a,$type,'friends');
1013 function api_followers_ids(&$a,$type) {
1014 api_ff_ids($a,$type,'followers');
1016 api_register_func('api/friends/ids','api_friends_ids',true);
1017 api_register_func('api/followers/ids','api_followers_ids',true);
1020 function api_direct_messages_new(&$a, $type) {
1021 if (local_user()===false) return false;
1023 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1025 $sender = api_get_user($a);
1027 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1028 intval(local_user()),
1029 dbesc($_POST['screen_name']));
1031 $recipient = api_get_user($a, $r[0]['id']);
1034 require_once("include/message.php");
1035 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1036 $id = send_message($recipient['id'], $_POST['text'], $sub);
1040 $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1043 'id' => $item['id'],
1044 'created_at'=> api_date($item['created']),
1045 'sender_id'=> $sender['id'] ,
1046 'sender_screen_name'=> $sender['screen_name'],
1048 'recipient_id'=> $recipient['id'],
1049 'recipient_screen_name'=> $recipient['screen_name'],
1050 'recipient'=> $recipient,
1052 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1057 $ret = array("error"=>$id);
1060 $data = Array('$messages'=>$ret);
1065 $data = api_rss_extra($a, $data, $user_info);
1068 return api_apply_template("direct_messages", $type, $data);
1071 api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1073 function api_direct_messages_box(&$a, $type, $box) {
1074 if (local_user()===false) return false;
1076 $user_info = api_get_user($a);
1079 $count = (x($_GET,'count')?$_GET['count']:20);
1080 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1081 if ($page<0) $page=0;
1083 $start = $page*$count;
1086 if ($box=="sentbox") {
1087 $sql_extra = "`from-url`='%s'";
1089 $sql_extra = "`from-url`!='%s'";
1092 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1093 intval(local_user()),
1094 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1095 intval($start), intval($count)
1099 foreach($r as $item){
1102 $recipient = $user_info;
1103 $sender = api_get_user($a,$item['contact-id']);
1106 $recipient = api_get_user($a,$item['contact-id']);
1107 $sender = $user_info;
1112 'id' => $item['id'],
1113 'created_at'=> api_date($item['created']),
1114 'sender_id'=> $sender['id'] ,
1115 'sender_screen_name'=> $sender['screen_name'],
1117 'recipient_id'=> $recipient['id'],
1118 'recipient_screen_name'=> $recipient['screen_name'],
1119 'recipient'=> $recipient,
1121 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1128 $data = array('$messages' => $ret);
1132 $data = api_rss_extra($a, $data, $user_info);
1135 return api_apply_template("direct_messages", $type, $data);
1139 function api_direct_messages_sentbox(&$a, $type){
1140 return api_direct_messages_box($a, $type, "sentbox");
1142 function api_direct_messages_inbox(&$a, $type){
1143 return api_direct_messages_box($a, $type, "inbox");
1145 api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1146 api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1150 function api_oauth_request_token(&$a, $type){
1152 $oauth = new FKOAuth1();
1153 $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1154 }catch(Exception $e){
1155 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1160 function api_oauth_access_token(&$a, $type){
1162 $oauth = new FKOAuth1();
1163 $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1164 }catch(Exception $e){
1165 echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1171 api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1172 api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);