]> git.mxchange.org Git - friendica.git/blob - include/api.php
diabook-themes: small fix
[friendica.git] / include / api.php
1 <?php
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");
7         /* 
8          * Twitter-Like API
9          *  
10          */
11
12         $API = Array();
13         $called_api = Null; 
14
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" );
18         }
19          
20         
21         function api_register_func($path, $func, $auth=false){
22                 global $API;
23                 $API[$path] = array('func'=>$func,
24                                                         'auth'=>$auth);
25         }
26         
27         /**
28          * Simple HTTP Login
29          */
30
31         function api_login(&$a){
32                 // login with oauth
33                 try{
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);
39                                 return;
40                         }
41                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
42                 }catch(Exception $e){
43                         logger(__file__.__line__.__function__."\n".$e);
44                         //die(__file__.__line__.__function__."<pre>".$e); die();
45                 }
46
47                 
48                 
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;
56                         }
57                 }
58
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');
64                 }
65                 
66                 $user = $_SERVER['PHP_AUTH_USER'];
67                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
68                 
69                 
70                         /**
71                          *  next code from mod/auth.php. needs better solution
72                          */
73                         
74                 // process normal login request
75
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",
78                         dbesc(trim($user)),
79                         dbesc(trim($user)),
80                         dbesc($encrypted)
81                 );
82                 if(count($r)){
83                         $record = $r[0];
84                 } else {
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');
89                 }
90
91                 require_once('include/security.php');
92                 authenticate_success($record);
93
94                 call_hooks('logged_in', $a->user);
95
96         }
97         
98         /**************************
99          *  MAIN API ENTRY POINT  *
100          **************************/
101         function api_call(&$a){
102                 GLOBAL $API, $called_api;
103
104                 // preset
105                 $type="json";
106
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) {
112                                                 api_login($a);
113                                 }
114
115                                 load_contact_links(local_user());
116
117                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
118                                 logger('API parameters: ' . print_r($_REQUEST,true));
119                                 $type="json";
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";
124
125                                 $r = call_user_func($info['func'], $a, $type);
126                                 if ($r===false) return;
127
128                                 switch($type){
129                                         case "xml":
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;
133                                                 break;
134                                         case "json":
135                                                 //header ("Content-Type: application/json");
136                                                 foreach($r as $rr)
137                                                     return json_encode($rr);
138                                                 break;
139                                         case "rss":
140                                                 header ("Content-Type: application/rss+xml");
141                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
142                                                 break;
143                                         case "atom":
144                                                 header ("Content-Type: application/atom+xml");
145                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
146                                                 break;
147
148                                 }
149                                 //echo "<pre>"; var_dump($r); die();
150                         }
151                 }
152                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
153                 $r = '<status><error>not implemented</error></status>';
154                 switch($type){
155                         case "xml":
156                                 header ("Content-Type: text/xml");
157                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
158                                 break;
159                         case "json":
160                                 header ("Content-Type: application/json");
161                             return json_encode(array('error' => 'not implemented'));
162                                 break;
163                         case "rss":
164                                 header ("Content-Type: application/rss+xml");
165                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
166                                 break;
167                         case "atom":
168                                 header ("Content-Type: application/atom+xml");
169                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
170                                 break;
171                 }
172         }
173
174         /**
175          * RSS extra info
176          */
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",
188                 );
189                 
190                 return $arr;
191         }
192          
193         /**
194          * Returns user info array.
195          */
196         function api_get_user(&$a, $contact_id = Null){
197                 global $called_api;
198                 $user = null;
199                 $extra_query = "";
200
201
202                 if(!is_null($contact_id)){
203                         $user=$contact_id;
204                         $extra_query = "AND `contact`.`id` = %d ";
205                 }
206                 
207                 if(is_null($user) && x($_GET, 'user_id')) {
208                         $user = intval($_GET['user_id']);       
209                         $extra_query = "AND `contact`.`id` = %d ";
210                 }
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());
215                         
216                 }
217                 
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 ";
224                         } else {
225                                 $user = dbesc($user);
226                                 $extra_query = "AND `contact`.`nick` = '%s' ";
227                                 if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
228                         }
229                 }
230                 
231                 if (! $user) {
232                         if (local_user()===false) {
233                                 api_login($a); return False;
234                         } else {
235                                 $user = $_SESSION['uid'];
236                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
237                         }
238                         
239                 }
240                 
241                 logger('api_user: ' . $extra_query . ' ' , $user);
242                 // user info            
243                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
244                                 WHERE 1
245                                 $extra_query",
246                                 $user
247                 );
248                 if (count($uinfo)==0) {
249                         return False;
250                 }
251                 
252                 if($uinfo[0]['self']) {
253                         $usr = q("select * from user where uid = %d limit 1",
254                                 intval(local_user())
255                         );
256                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
257                                 intval(local_user())
258                         );
259
260                         // count public wall messages
261                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
262                                         WHERE  `uid` = %d
263                                         AND `type`='wall' 
264                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
265                                         intval($uinfo[0]['uid'])
266                         );
267                         $countitms = $r[0]['count'];
268                 }
269                 else {
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'])
274                         );
275                         $countitms = $r[0]['count'];
276                 }
277
278                 // count friends
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)
285                 );
286                 $countfriends = $r[0]['count'];
287
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)
294                 );
295                 $countfollowers = $r[0]['count'];
296
297                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
298                         intval($uinfo[0]['uid'])
299                 );
300                 $starred = $r[0]['count'];
301         
302
303                 if(! $uinfo[0]['self']) {
304                         $countfriends = 0;
305                         $countfollowers = 0;
306                         $starred = 0;
307                 }
308
309                 $ret = Array(
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
343                         'status' => array()
344                 );
345         
346                 return $ret;
347                 
348         }
349
350         function api_item_get_user(&$a, $item) {
351                 global $usercache;
352
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']);
356                 }
357                 else {
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']);
363                 }
364                 // We don't know this person directly.
365                 
366                 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
367                 $name=str_replace(")","",$name);
368
369                 if ($name == '')
370                         $name = $nick;
371
372                 if ($nick == '')
373                         $nick = $name;
374
375                 // Generating a random ID
376                 if (!array_key_exists($nick, $usercache))
377                         $usercache[$nick] = mt_rand(2000000, 2100000);
378
379                 $ret = array(
380                         'id' => $usercache[$nick],
381                         'name' => $name,
382                         'screen_name' => $nick,
383                         'location' => '', //$uinfo[0]['default-location'],
384                         'description' => '',
385                         'profile_image_url' => $item['author-avatar'],
386                         'url' => $item['author-link'],
387                         'protected' => false,   #
388                         'followers_count' => 0,
389                         'friends_count' => 0,
390                         'created_at' => '',
391                         'favourites_count' => 0,
392                         'utc_offset' => 0, #XXX: fix me
393                         'time_zone' => '', //$uinfo[0]['timezone'],
394                         'statuses_count' => 0,
395                         'following' => 1,
396                         'statusnet_blocking' => false,
397                         'notifications' => false,
398                         'uid' => 0,
399                         'contact_url' => 0,
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
414                         'status' => array()
415                 );
416
417                 return $ret; 
418         }
419
420
421         /**
422          *  load api $templatename for $type and replace $data array
423          */
424         function api_apply_template($templatename, $type, $data){
425
426                 $a = get_app();
427
428                 switch($type){
429                         case "atom":
430                         case "rss":
431                         case "xml":
432                                 $data = array_xmlify($data);
433                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
434                                 $ret = replace_macros($tpl, $data);
435                                 break;
436                         case "json":
437                                 $ret = $data;
438                                 break;
439                 }
440                 return $ret;
441         }
442         
443         /**
444          ** TWITTER API
445          */
446         
447         /**
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
451          */
452         function api_account_verify_credentials(&$a, $type){
453                 if (local_user()===false) return false;
454                 $user_info = api_get_user($a);
455                 
456                 return api_apply_template("user", $type, array('$user' => $user_info));
457
458         }
459         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
460                 
461
462         /**
463          * get data from $_POST or $_GET
464          */
465         function requestdata($k){
466                 if (isset($_POST[$k])){
467                         return $_POST[$k];
468                 }
469                 if (isset($_GET[$k])){
470                         return $_GET[$k];
471                 }
472                 return null;
473         }
474
475 /*Waitman Gobble Mod*/
476         function api_statuses_mediap(&$a, $type) {
477                 if (local_user()===false) {
478                         logger('api_statuses_update: no user');
479                         return false;
480                 }
481                 $user_info = api_get_user($a);
482
483                 $_REQUEST['type'] = 'wall';
484                 $_REQUEST['profile_uid'] = local_user();
485                 $_REQUEST['api_source'] = true;
486                 $txt = urldecode(requestdata('status'));
487
488                 require_once('library/HTMLPurifier.auto.php');
489                 require_once('include/html2bbcode.php');
490
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);
497                 }
498                 $txt = html2bbcode($txt);
499                 
500                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
501                 
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);
505                 
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');
509                 item_post($a);
510
511                 // this should output the last post (the one we just posted).
512                 return api_status_show($a,$type);
513         }
514         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
515 /*Waitman Gobble Mod*/
516
517
518         function api_statuses_update(&$a, $type) {
519                 if (local_user()===false) {
520                         logger('api_statuses_update: no user');
521                         return false;
522                 }
523                 $user_info = api_get_user($a);
524
525                 // convert $_POST array items to the form we use for web posts.
526
527                 // logger('api_post: ' . print_r($_POST,true));
528
529                 if(requestdata('htmlstatus')) {
530                         require_once('library/HTMLPurifier.auto.php');
531                         require_once('include/html2bbcode.php');
532
533                         $txt = requestdata('htmlstatus');
534                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
535
536                                 $txt = html2bb_video($txt);
537
538                                 $config = HTMLPurifier_Config::createDefault();
539                                 $config->set('Cache.DefinitionImpl', null);
540
541
542                                 $purifier = new HTMLPurifier($config);
543                                 $txt = $purifier->purify($txt);
544
545                                 $_REQUEST['body'] = html2bbcode($txt);
546                         }
547
548                 }
549                 else
550                         $_REQUEST['body'] = urldecode(requestdata('status'));
551
552                 $parent = requestdata('in_reply_to_status_id');
553                 if(ctype_digit($parent))
554                         $_REQUEST['parent'] = $parent;
555                 else
556                         $_REQUEST['parent_uri'] = $parent;
557
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';
563                 else
564                         $_REQUEST['type'] = 'wall';
565
566                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
567
568                 $_REQUEST['api_source'] = true;
569
570                 // call out normal post function
571
572                 require_once('mod/item.php');
573                 item_post($a);  
574
575                 // this should output the last post (the one we just posted).
576                 return api_status_show($a,$type);
577         }
578         api_register_func('api/statuses/update','api_statuses_update', true);
579
580
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 
593                                 LIMIT 1",
594                                 intval($user_info['id'])
595                 );
596
597                 if (count($lastwall)>0){
598                         $lastwall = $lastwall[0];
599                         
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'];
607                         }  
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,
617                                 'geo' => '',
618                                 'favorited' => false,
619                                 'coordinates' => $lastwall['coord'],
620                                 'place' => $lastwall['location'],
621                                 'contributors' => ''                                    
622                         );
623                         $status_info['user'] = $user_info;
624                 }
625                 return  api_apply_template("status", $type, array('$status' => $status_info));
626                 
627         }
628
629
630
631
632                 
633         /**
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
637          */
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 
650                                 LIMIT 1",
651                                 intval($user_info['id'])
652                 );
653
654                 if (count($lastwall)>0){
655                         $lastwall = $lastwall[0];
656                         
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'];
664                         }  
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,
675                                 'geo' => '',
676                                 'coordinates' => $lastwall['coord'],
677                                 'place' => $lastwall['location'],
678                                 'contributors' => ''                                    
679                         );
680                 }
681                 return  api_apply_template("user", $type, array('$user' => $user_info));
682                 
683         }
684         api_register_func('api/users/show','api_users_show');
685         
686         /**
687          * 
688          * http://developer.twitter.com/doc/get/statuses/home_timeline
689          * 
690          * TODO: Optional parameters
691          * TODO: Add reply info
692          */
693         function api_statuses_home_timeline(&$a, $type){
694                 if (local_user()===false) return false;
695                                 
696                 $user_info = api_get_user($a);
697                 // get last newtork messages
698
699
700                 // params
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);
707                 
708                 $start = $page*$count;
709
710                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
711
712                 if ($max_id > 0)
713                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
714
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
724                         $sql_extra
725                         AND `item`.`id`>%d
726                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
727                         intval($user_info['uid']),
728                         intval($since_id),
729                         intval($start), intval($count)
730                 );
731
732                 $ret = api_format_items($r,$user_info);
733
734                 
735                 $data = array('$statuses' => $ret);
736                 switch($type){
737                         case "atom":
738                         case "rss":
739                                 $data = api_rss_extra($a, $data, $user_info);
740                 }
741                                 
742                 return  api_apply_template("timeline", $type, $data);
743         }
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);
746
747         /**
748          * 
749          */
750         function api_statuses_show(&$a, $type){
751                 if (local_user()===false) return false;
752
753                 $user_info = api_get_user($a);
754
755                 // params
756                 $id = intval($a->argv[3]);
757
758                 logger('API: api_statuses_show: '.$id);         
759
760                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
761
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
770                         $sql_extra
771                         AND `item`.`id`=%d",
772                         intval($id)
773                 );
774
775                 $ret = api_format_items($r,$user_info);
776                 
777                 $data = array('$status' => $ret[0]);
778                 /*switch($type){
779                         case "atom":
780                         case "rss":
781                                 $data = api_rss_extra($a, $data, $user_info);
782                 }*/
783                 return  api_apply_template("status", $type, $data);
784         }
785         api_register_func('api/statuses/show','api_statuses_show', true);
786
787
788         /**
789          * 
790          */
791         function api_statuses_repeat(&$a, $type){
792                 if (local_user()===false) return false;
793
794                 $user_info = api_get_user($a);
795
796                 // params
797                 $id = intval($a->argv[3]);
798
799                 logger('API: api_statuses_repeat: '.$id);               
800
801                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
802
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
811                         $sql_extra
812                         AND `item`.`id`=%d",
813                         intval($id)
814                 );
815
816                 $_REQUEST['body'] = html_entity_decode("&#x2672; ", 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;
820
821                 require_once('mod/item.php');
822                 item_post($a);
823
824                 if ($type == 'xml')
825                         $ok = "true";
826                 else
827                         $ok = "ok";
828
829                 return api_apply_template('test', $type, array('$ok' => $ok));
830         }
831         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
832
833         /**
834          * 
835          */
836         function api_statuses_destroy(&$a, $type){
837                 if (local_user()===false) return false;
838
839                 $user_info = api_get_user($a);
840
841                 // params
842                 $id = intval($a->argv[3]);
843
844                 logger('API: api_statuses_destroy: '.$id);      
845
846                 require_once('include/items.php');
847                 drop_item($id, false);
848
849                 if ($type == 'xml')
850                         $ok = "true";
851                 else
852                         $ok = "ok";
853
854                 return api_apply_template('test', $type, array('$ok' => $ok));
855         }
856         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
857
858         /**
859          * 
860          * http://developer.twitter.com/doc/get/statuses/mentions
861          * 
862          */
863         function api_statuses_mentions(&$a, $type){
864                 if (local_user()===false) return false;
865                                 
866                 $user_info = api_get_user($a);
867                 // get last newtork messages
868
869
870                 // params
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);
877                 
878                 $start = $page*$count;
879
880                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
881
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' )) ",
887                         dbesc($myurl . '$'),
888                         dbesc($myurl . '\\]'),
889                         dbesc($diasp_url . '\\]')
890                 );
891
892                 if ($max_id > 0)
893                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
894
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
904                         $sql_extra
905                         AND `item`.`id`>%d
906                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
907                         intval($user_info['uid']),
908                         intval($since_id),
909                         intval($start), intval($count)
910                 );
911
912                 $ret = api_format_items($r,$user_info);
913
914                 
915                 $data = array('$statuses' => $ret);
916                 switch($type){
917                         case "atom":
918                         case "rss":
919                                 $data = api_rss_extra($a, $data, $user_info);
920                 }
921                                 
922                 return  api_apply_template("timeline", $type, $data);
923         }
924         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
925         api_register_func('api/statuses/replies','api_statuses_mentions', true);
926
927
928         function api_statuses_user_timeline(&$a, $type){
929                 if (local_user()===false) return false;
930                 
931                 $user_info = api_get_user($a);
932                 // get last newtork messages
933
934
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),
938                            LOGGER_DEBUG);
939
940                 // params
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);
946                 
947                 $start = $page*$count;
948
949                 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
950
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
961                         $sql_extra
962                         AND `item`.`id`>%d
963                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
964                         intval(local_user()),
965                         intval($user_info['id']),
966                         intval($since_id),
967                         intval($start), intval($count)
968                 );
969
970                 $ret = api_format_items($r,$user_info);
971
972                 
973                 $data = array('$statuses' => $ret);
974                 switch($type){
975                         case "atom":
976                         case "rss":
977                                 $data = api_rss_extra($a, $data, $user_info);
978                 }
979                                 
980                 return  api_apply_template("timeline", $type, $data);
981         }
982
983         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
984
985
986         function api_favorites(&$a, $type){
987                 if (local_user()===false) return false;
988                 
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']);
993                 
994                 if ($user_info['self']==0) {
995                         $ret = array();
996                 } else {
997                         
998                         
999                         // params
1000                         $count = (x($_GET,'count')?$_GET['count']:20);
1001                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1002                         if ($page<0) $page=0;
1003                         
1004                         $start = $page*$count;
1005
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
1016                                 $sql_extra
1017                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1018                                 intval($user_info['uid']),
1019                                 intval($start), intval($count)
1020                         );
1021
1022                         $ret = api_format_items($r,$user_info);
1023                 
1024                 }
1025                 
1026                 $data = array('$statuses' => $ret);
1027                 switch($type){
1028                         case "atom":
1029                         case "rss":
1030                                 $data = api_rss_extra($a, $data, $user_info);
1031                 }
1032                                 
1033                 return  api_apply_template("timeline", $type, $data);
1034         }
1035
1036         api_register_func('api/favorites','api_favorites', true);
1037
1038         
1039         function api_format_items($r,$user_info) {
1040
1041                 //logger('api_format_items: ' . print_r($r,true));
1042
1043                 //logger('api_format_items: ' . print_r($user_info,true));
1044
1045                 $a = get_app();
1046                 $ret = Array();
1047
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));
1051
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']));
1055                                 if ($r)
1056                                         $in_reply_to_status_id = $r[0]['id'];
1057                                 else
1058                                         $in_reply_to_status_id = $item['parent'];
1059
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));
1062
1063                                 $in_reply_to_screen_name = $r[0]['author-name'];
1064                                 $in_reply_to_user_id = $r[0]['contact-id'];
1065
1066                         } else {
1067                                 $in_reply_to_screen_name = '';
1068                                 $in_reply_to_user_id = 0;
1069                                 $in_reply_to_status_id = 0;
1070                         }
1071
1072                         $status = array(
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,
1081                                 'geo' => '',
1082                                 'favorited' => $item['starred'] ? true : false,
1083                                 'user' =>  $status_user ,
1084                                 'statusnet_html'                => bbcode($item['body']),
1085                                 'statusnet_conversation_id'     => 0,
1086                         );
1087
1088                         // Seesmic doesn't like the following content
1089                         if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1090                                 $status2 = array(
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'  => '',
1099                                         'entities'  => '',
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,
1104                                 );
1105
1106                                 $status = array_merge($status, $status2);
1107                         }
1108
1109                         $ret[]=$status;
1110                 };
1111                 return $ret;
1112         }
1113
1114
1115         function api_account_rate_limit_status(&$a,$type) {
1116
1117                 $hash = array(
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),
1122                 );
1123                 if ($type == "xml")
1124                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1125
1126                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1127
1128         }
1129         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1130
1131         function api_help_test(&$a,$type) {
1132
1133                 if ($type == 'xml')
1134                         $ok = "true";
1135                 else
1136                         $ok = "ok";
1137
1138                 return api_apply_template('test', $type, array('$ok' => $ok));
1139
1140         }
1141         api_register_func('api/help/test','api_help_test',true);
1142
1143         /**
1144          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
1145          *  This function is deprecated by Twitter
1146          *  returns: json, xml 
1147          **/
1148         function api_statuses_f(&$a, $type, $qtype) {
1149                 if (local_user()===false) return false;
1150                 $user_info = api_get_user($a);
1151                 
1152                 
1153                 // friends and followers only for self
1154                 if ($user_info['self']==0){
1155                         return false;
1156                 }
1157                 
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
1162                         */
1163                         
1164                         /*$ret=Array();
1165                         return array('$users' => $ret);*/
1166                         return false;
1167                 }
1168                 
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));
1173  
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())
1176                 );
1177
1178                 $ret = array();
1179                 foreach($r as $cid){
1180                         $ret[] = api_get_user($a, $cid['id']);
1181                 }
1182
1183                 
1184                 return array('$users' => $ret);
1185
1186         }
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);
1191         }
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);
1196         }
1197         api_register_func('api/statuses/friends','api_statuses_friends',true);
1198         api_register_func('api/statuses/followers','api_statuses_followers',true);
1199
1200
1201
1202
1203
1204
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()) : '');
1217
1218                 $config = array(
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'
1224                         ),
1225                 );  
1226
1227                 return api_apply_template('config', $type, array('$config' => $config));
1228
1229         }
1230         api_register_func('api/statusnet/config','api_statusnet_config',false);
1231
1232         function api_statusnet_version(&$a,$type) {
1233
1234                 // liar
1235
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";
1239                         killme();
1240                 }
1241                 elseif($type === 'json') {
1242                         header("Content-type: application/json");
1243                         echo '"0.9.7"';
1244                         killme();
1245                 }
1246         }
1247         api_register_func('api/statusnet/version','api_statusnet_version',false);
1248
1249
1250         function api_ff_ids(&$a,$type,$qtype) {
1251                 if(! local_user())
1252                         return false;
1253
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));
1258  
1259
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())
1262                 );
1263
1264                 if(is_array($r)) {
1265                         if($type === 'xml') {
1266                                 header("Content-type: application/xml");
1267                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1268                                 foreach($r as $rr)
1269                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1270                                 echo '</ids>' . "\r\n";
1271                                 killme();
1272                         }
1273                         elseif($type === 'json') {
1274                                 $ret = array();
1275                                 header("Content-type: application/json");
1276                                 foreach($r as $rr) $ret[] = $rr['id'];
1277                                 echo json_encode($ret);
1278                                 killme();
1279                         }
1280                 }
1281         }
1282
1283         function api_friends_ids(&$a,$type) {
1284                 api_ff_ids($a,$type,'friends');
1285         }
1286         function api_followers_ids(&$a,$type) {
1287                 api_ff_ids($a,$type,'followers');
1288         }
1289         api_register_func('api/friends/ids','api_friends_ids',true);
1290         api_register_func('api/followers/ids','api_followers_ids',true);
1291
1292
1293         function api_direct_messages_new(&$a, $type) {
1294                 if (local_user()===false) return false;
1295                 
1296                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1297                 
1298                 $sender = api_get_user($a);
1299                 
1300                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1301                                 intval(local_user()),
1302                                 dbesc($_POST['screen_name']));
1303                 
1304                 $recipient = api_get_user($a, $r[0]['id']);                     
1305                 
1306
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);
1310                 
1311                 
1312                 if ($id>-1) {
1313                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1314                         $item = $r[0];
1315                         $ret=Array(
1316                                         'id' => $item['id'],
1317                                         'created_at'=> api_date($item['created']),
1318                                         'sender_id'=> $sender['id'] ,
1319                                         'sender_screen_name'=> $sender['screen_name'],
1320                                         'sender'=> $sender,
1321                                         'recipient_id'=> $recipient['id'],
1322                                         'recipient_screen_name'=> $recipient['screen_name'],
1323                                         'recipient'=> $recipient,
1324                                         
1325                                         'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1326                                         
1327                         );
1328                 
1329                 } else {
1330                         $ret = array("error"=>$id);     
1331                 }
1332                 
1333                 $data = Array('$messages'=>$ret);
1334                 
1335                 switch($type){
1336                         case "atom":
1337                         case "rss":
1338                                 $data = api_rss_extra($a, $data, $user_info);
1339                 }
1340                                 
1341                 return  api_apply_template("direct_messages", $type, $data);
1342                                 
1343         }
1344         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1345
1346     function api_direct_messages_box(&$a, $type, $box) {
1347                 if (local_user()===false) return false;
1348                 
1349                 $user_info = api_get_user($a);
1350                 
1351                 // params
1352                 $count = (x($_GET,'count')?$_GET['count']:20);
1353                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1354                 if ($page<0) $page=0;
1355                 
1356                 $start = $page*$count;
1357                 
1358         
1359                 if ($box=="sentbox") {
1360                         $sql_extra = "`from-url`='%s'";
1361                 } else {
1362                         $sql_extra = "`from-url`!='%s'";
1363                 }
1364                 
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)
1369                            );
1370                 
1371                 $ret = Array();
1372                 foreach($r as $item){
1373                         switch ($box){
1374                                 case "inbox":
1375                                         $recipient = $user_info;
1376                                         $sender = api_get_user($a,$item['contact-id']);
1377                                         break;
1378                                 case "sentbox":
1379                                         $recipient = api_get_user($a,$item['contact-id']);
1380                                         $sender = $user_info;
1381                                         break;
1382                         }
1383                                 
1384                         $ret[]=Array(
1385                                 'id' => $item['id'],
1386                                 'created_at'=> api_date($item['created']),
1387                                 'sender_id'=> $sender['id'] ,
1388                                 'sender_screen_name'=> $sender['screen_name'],
1389                                 'sender'=> $sender,
1390                                 'recipient_id'=> $recipient['id'],
1391                                 'recipient_screen_name'=> $recipient['screen_name'],
1392                                 'recipient'=> $recipient,
1393                                 
1394                                 'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1395                                 
1396                         );
1397                         
1398                 }
1399                 
1400
1401                 $data = array('$messages' => $ret);
1402                 switch($type){
1403                         case "atom":
1404                         case "rss":
1405                                 $data = api_rss_extra($a, $data, $user_info);
1406                 }
1407                                 
1408                 return  api_apply_template("direct_messages", $type, $data);
1409                 
1410         }
1411
1412         function api_direct_messages_sentbox(&$a, $type){
1413                 return api_direct_messages_box($a, $type, "sentbox");
1414         }
1415         function api_direct_messages_inbox(&$a, $type){
1416                 return api_direct_messages_box($a, $type, "inbox");
1417         }
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);
1420
1421
1422
1423         function api_oauth_request_token(&$a, $type){
1424                 try{
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();
1429                 }
1430                 echo $r;
1431                 killme();       
1432         }
1433         function api_oauth_access_token(&$a, $type){
1434                 try{
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();
1439                 }
1440                 echo $r;
1441                 killme();                       
1442         }
1443
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);
1446
1447 /*
1448 Not implemented by now:
1449 favorites
1450 favorites/create
1451 favorites/destroy
1452 statuses/public_timeline
1453 statuses/retweets_of_me
1454 friendships/create
1455 friendships/destroy
1456 friendships/exists
1457 friendships/show
1458 account/update_location
1459 account/update_profile_background_image
1460 account/update_profile_image
1461 blocks/create
1462 blocks/destroy
1463 oauth/authorize
1464
1465 Not implemented in status.net:
1466 statuses/retweeted_to_me
1467 statuses/retweeted_by_me
1468 direct_messages/destroy
1469 account/end_session
1470 account/update_delivery_device
1471 notifications/follow
1472 notifications/leave
1473 blocks/exists
1474 blocks/blocking
1475 */