]> git.mxchange.org Git - friendica.git/blob - include/api.php
API: Seesmic is now working. Optimizing text export.
[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="Friendika"');
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                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
706                 
707                 $start = $page*$count;
708
709                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
710
711                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
712                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
713                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
714                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
715                         FROM `item`, `contact`
716                         WHERE `item`.`uid` = %d
717                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
718                         AND `contact`.`id` = `item`.`contact-id`
719                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
720                         $sql_extra
721                         AND `item`.`id`>%d
722                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
723                         intval($user_info['uid']),
724                         intval($since_id),
725                         intval($start), intval($count)
726                 );
727
728                 $ret = api_format_items($r,$user_info);
729
730                 
731                 $data = array('$statuses' => $ret);
732                 switch($type){
733                         case "atom":
734                         case "rss":
735                                 $data = api_rss_extra($a, $data, $user_info);
736                 }
737                                 
738                 return  api_apply_template("timeline", $type, $data);
739         }
740         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
741         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
742
743         /**
744          * 
745          * http://developer.twitter.com/doc/get/statuses/show
746          * 
747          */
748         function api_statuses_show(&$a, $type){
749                 if (local_user()===false) return false;
750
751                 $user_info = api_get_user($a);
752
753                 // params
754                 $id = intval($a->argv[3]);
755
756                 logger('API: api_statuses_show: '.$id);         
757
758                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
759
760                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
761                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
762                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
763                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
764                         FROM `item`, `contact`
765                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
766                         AND `contact`.`id` = `item`.`contact-id`
767                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
768                         $sql_extra
769                         AND `item`.`id`=%d",
770                         intval($id)
771                 );
772
773                 $ret = api_format_items($r,$user_info);
774                 
775                 $data = array('$status' => $ret[0]);
776                 /*switch($type){
777                         case "atom":
778                         case "rss":
779                                 $data = api_rss_extra($a, $data, $user_info);
780                 }*/
781                 return  api_apply_template("status", $type, $data);
782         }
783         api_register_func('api/statuses/show','api_statuses_show', true);
784
785
786         function api_statuses_user_timeline(&$a, $type){
787                 if (local_user()===false) return false;
788                 
789                 $user_info = api_get_user($a);
790                 // get last newtork messages
791
792
793                 logger("api_statuses_user_timeline: local_user: ". local_user() .
794                            "\nuser_info: ".print_r($user_info, true) .
795                            "\n_REQUEST:  ".print_r($_REQUEST, true),
796                            LOGGER_DEBUG);
797
798                 // params
799                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
800                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
801                 if ($page<0) $page=0;
802                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
803                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
804                 
805                 $start = $page*$count;
806
807                 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
808
809                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
810                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
811                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
812                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
813                         FROM `item`, `contact`
814                         WHERE `item`.`uid` = %d
815                         AND `item`.`contact-id` = %d
816                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
817                         AND `contact`.`id` = `item`.`contact-id`
818                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
819                         $sql_extra
820                         AND `item`.`id`>%d
821                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
822                         intval(local_user()),
823                         intval($user_info['id']),
824                         intval($since_id),
825                         intval($start), intval($count)
826                 );
827
828                 $ret = api_format_items($r,$user_info);
829
830                 
831                 $data = array('$statuses' => $ret);
832                 switch($type){
833                         case "atom":
834                         case "rss":
835                                 $data = api_rss_extra($a, $data, $user_info);
836                 }
837                                 
838                 return  api_apply_template("timeline", $type, $data);
839         }
840
841         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
842
843
844         function api_favorites(&$a, $type){
845                 if (local_user()===false) return false;
846                 
847                 $user_info = api_get_user($a);
848                 // in friendica starred item are private
849                 // return favorites only for self
850                 logger('api_favorites: self:' . $user_info['self']);
851                 
852                 if ($user_info['self']==0) {
853                         $ret = array();
854                 } else {
855                         
856                         
857                         // params
858                         $count = (x($_GET,'count')?$_GET['count']:20);
859                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
860                         if ($page<0) $page=0;
861                         
862                         $start = $page*$count;
863
864                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
865                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
866                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
867                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
868                                 FROM `item`, `contact`
869                                 WHERE `item`.`uid` = %d
870                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
871                                 AND `item`.`starred` = 1
872                                 AND `contact`.`id` = `item`.`contact-id`
873                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
874                                 $sql_extra
875                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
876                                 intval($user_info['uid']),
877                                 intval($start), intval($count)
878                         );
879
880                         $ret = api_format_items($r,$user_info);
881                 
882                 }
883                 
884                 $data = array('$statuses' => $ret);
885                 switch($type){
886                         case "atom":
887                         case "rss":
888                                 $data = api_rss_extra($a, $data, $user_info);
889                 }
890                                 
891                 return  api_apply_template("timeline", $type, $data);
892         }
893
894         api_register_func('api/favorites','api_favorites', true);
895
896         
897         function api_format_items($r,$user_info) {
898
899                 //logger('api_format_items: ' . print_r($r,true));
900
901                 //logger('api_format_items: ' . print_r($user_info,true));
902
903                 $a = get_app();
904                 $ret = Array();
905
906                 foreach($r as $item) {
907                         localize_item($item);
908                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
909
910                         if ($item['parent']!=$item['id']) {
911
912                                 $r = q("select `item`.`contact-id`, `contact`.nick from item, contact 
913                                         where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($item['parent']));
914
915                                 $in_reply_to_screen_name = $r[0]['nick'];
916                                 $in_reply_to_user_id = $r[0]['contact-id'];
917                         } else {
918                                 $in_reply_to_screen_name = '';
919                                 $in_reply_to_user_id = 0;
920                         }
921
922                         $status = array(
923                                 'text'          => html2plain(bbcode($item['body']), 0),
924                                 'truncated' => False,
925                                 'created_at'=> api_date($item['created']),
926                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
927                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
928                                 'id'            => intval($item['id']),
929                                 'in_reply_to_user_id' => $in_reply_to_user_id,
930                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
931                                 'geo' => '',
932                                 'favorited' => $item['starred'] ? true : false,
933                                 'user' =>  $status_user ,
934                                 'statusnet_html'                => bbcode($item['body']),
935                                 'statusnet_conversation_id'     => 0,
936                         );
937
938                         // Seesmic doesn't like the following content
939                         if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
940                                 $status2 = array(
941                                         'updated'   => api_date($item['edited']),
942                                         'published' => api_date($item['created']),
943                                         'message_id' => $item['uri'],
944                                         'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
945                                         'coordinates' => $item['coord'],
946                                         'place' => $item['location'],
947                                         'contributors' => '',
948                                         'annotations'  => '',
949                                         'entities'  => '',
950                                         'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
951                                         'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
952                                         'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
953                                         'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
954                                 );
955
956                                 $status = array_merge($status, $status2);
957                         }
958
959                         $ret[]=$status;
960                 };
961                 return $ret;
962         }
963
964
965         function api_account_rate_limit_status(&$a,$type) {
966
967                 $hash = array(
968                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
969                           'remaining_hits' => (string) 150,
970                           'hourly_limit' => (string) 150,
971                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
972                 );
973                 if ($type == "xml")
974                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
975
976                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
977
978         }
979         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
980
981         function api_help_test(&$a,$type) {
982
983                 if ($type == 'xml')
984                         $ok = "true";
985                 else
986                         $ok = "ok";
987
988                 return api_apply_template('test', $type, array('$ok' => $ok));
989
990         }
991         api_register_func('api/help/test','api_help_test',true);
992
993         /**
994          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
995          *  This function is deprecated by Twitter
996          *  returns: json, xml 
997          **/
998         function api_statuses_f(&$a, $type, $qtype) {
999                 if (local_user()===false) return false;
1000                 $user_info = api_get_user($a);
1001                 
1002                 
1003                 // friends and followers only for self
1004                 if ($user_info['self']==0){
1005                         return false;
1006                 }
1007                 
1008                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1009                         /* this is to stop Hotot to load friends multiple times
1010                         *  I'm not sure if I'm missing return something or
1011                         *  is a bug in hotot. Workaround, meantime
1012                         */
1013                         
1014                         /*$ret=Array();
1015                         return array('$users' => $ret);*/
1016                         return false;
1017                 }
1018                 
1019                 if($qtype == 'friends')
1020                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1021                 if($qtype == 'followers')
1022                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1023  
1024                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1025                         intval(local_user())
1026                 );
1027
1028                 $ret = array();
1029                 foreach($r as $cid){
1030                         $ret[] = api_get_user($a, $cid['id']);
1031                 }
1032
1033                 
1034                 return array('$users' => $ret);
1035
1036         }
1037         function api_statuses_friends(&$a, $type){
1038                 $data =  api_statuses_f($a,$type,"friends");
1039                 if ($data===false) return false;
1040                 return  api_apply_template("friends", $type, $data);
1041         }
1042         function api_statuses_followers(&$a, $type){
1043                 $data = api_statuses_f($a,$type,"followers");
1044                 if ($data===false) return false;
1045                 return  api_apply_template("friends", $type, $data);
1046         }
1047         api_register_func('api/statuses/friends','api_statuses_friends',true);
1048         api_register_func('api/statuses/followers','api_statuses_followers',true);
1049
1050
1051
1052
1053
1054
1055         function api_statusnet_config(&$a,$type) {
1056                 $name = $a->config['sitename'];
1057                 $server = $a->get_hostname();
1058                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1059                 $email = $a->config['admin_email'];
1060                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1061                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1062                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1063                 if($a->config['api_import_size'])
1064                         $texlimit = string($a->config['api_import_size']);
1065                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1066                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1067
1068                 $config = array(
1069                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1070                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1071                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1072                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1073                                 'shorturllength' => '30'
1074                         ),
1075                 );  
1076
1077                 return api_apply_template('config', $type, array('$config' => $config));
1078
1079         }
1080         api_register_func('api/statusnet/config','api_statusnet_config',false);
1081
1082         function api_statusnet_version(&$a,$type) {
1083
1084                 // liar
1085
1086                 if($type === 'xml') {
1087                         header("Content-type: application/xml");
1088                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1089                         killme();
1090                 }
1091                 elseif($type === 'json') {
1092                         header("Content-type: application/json");
1093                         echo '"0.9.7"';
1094                         killme();
1095                 }
1096         }
1097         api_register_func('api/statusnet/version','api_statusnet_version',false);
1098
1099
1100         function api_ff_ids(&$a,$type,$qtype) {
1101                 if(! local_user())
1102                         return false;
1103
1104                 if($qtype == 'friends')
1105                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1106                 if($qtype == 'followers')
1107                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1108  
1109
1110                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1111                         intval(local_user())
1112                 );
1113
1114                 if(is_array($r)) {
1115                         if($type === 'xml') {
1116                                 header("Content-type: application/xml");
1117                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1118                                 foreach($r as $rr)
1119                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1120                                 echo '</ids>' . "\r\n";
1121                                 killme();
1122                         }
1123                         elseif($type === 'json') {
1124                                 $ret = array();
1125                                 header("Content-type: application/json");
1126                                 foreach($r as $rr) $ret[] = $rr['id'];
1127                                 echo json_encode($ret);
1128                                 killme();
1129                         }
1130                 }
1131         }
1132
1133         function api_friends_ids(&$a,$type) {
1134                 api_ff_ids($a,$type,'friends');
1135         }
1136         function api_followers_ids(&$a,$type) {
1137                 api_ff_ids($a,$type,'followers');
1138         }
1139         api_register_func('api/friends/ids','api_friends_ids',true);
1140         api_register_func('api/followers/ids','api_followers_ids',true);
1141
1142
1143         function api_direct_messages_new(&$a, $type) {
1144                 if (local_user()===false) return false;
1145                 
1146                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1147                 
1148                 $sender = api_get_user($a);
1149                 
1150                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1151                                 intval(local_user()),
1152                                 dbesc($_POST['screen_name']));
1153                 
1154                 $recipient = api_get_user($a, $r[0]['id']);                     
1155                 
1156
1157                 require_once("include/message.php");
1158                 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1159                 $id = send_message($recipient['id'], $_POST['text'], $sub);
1160                 
1161                 
1162                 if ($id>-1) {
1163                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1164                         $item = $r[0];
1165                         $ret=Array(
1166                                         'id' => $item['id'],
1167                                         'created_at'=> api_date($item['created']),
1168                                         'sender_id'=> $sender['id'] ,
1169                                         'sender_screen_name'=> $sender['screen_name'],
1170                                         'sender'=> $sender,
1171                                         'recipient_id'=> $recipient['id'],
1172                                         'recipient_screen_name'=> $recipient['screen_name'],
1173                                         'recipient'=> $recipient,
1174                                         
1175                                         'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1176                                         
1177                         );
1178                 
1179                 } else {
1180                         $ret = array("error"=>$id);     
1181                 }
1182                 
1183                 $data = Array('$messages'=>$ret);
1184                 
1185                 switch($type){
1186                         case "atom":
1187                         case "rss":
1188                                 $data = api_rss_extra($a, $data, $user_info);
1189                 }
1190                                 
1191                 return  api_apply_template("direct_messages", $type, $data);
1192                                 
1193         }
1194         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1195
1196     function api_direct_messages_box(&$a, $type, $box) {
1197                 if (local_user()===false) return false;
1198                 
1199                 $user_info = api_get_user($a);
1200                 
1201                 // params
1202                 $count = (x($_GET,'count')?$_GET['count']:20);
1203                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1204                 if ($page<0) $page=0;
1205                 
1206                 $start = $page*$count;
1207                 
1208         
1209                 if ($box=="sentbox") {
1210                         $sql_extra = "`from-url`='%s'";
1211                 } else {
1212                         $sql_extra = "`from-url`!='%s'";
1213                 }
1214                 
1215                 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1216                                 intval(local_user()),
1217                                 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1218                                 intval($start), intval($count)
1219                            );
1220                 
1221                 $ret = Array();
1222                 foreach($r as $item){
1223                         switch ($box){
1224                                 case "inbox":
1225                                         $recipient = $user_info;
1226                                         $sender = api_get_user($a,$item['contact-id']);
1227                                         break;
1228                                 case "sentbox":
1229                                         $recipient = api_get_user($a,$item['contact-id']);
1230                                         $sender = $user_info;
1231                                         break;
1232                         }
1233                                 
1234                         $ret[]=Array(
1235                                 'id' => $item['id'],
1236                                 'created_at'=> api_date($item['created']),
1237                                 'sender_id'=> $sender['id'] ,
1238                                 'sender_screen_name'=> $sender['screen_name'],
1239                                 'sender'=> $sender,
1240                                 'recipient_id'=> $recipient['id'],
1241                                 'recipient_screen_name'=> $recipient['screen_name'],
1242                                 'recipient'=> $recipient,
1243                                 
1244                                 'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1245                                 
1246                         );
1247                         
1248                 }
1249                 
1250
1251                 $data = array('$messages' => $ret);
1252                 switch($type){
1253                         case "atom":
1254                         case "rss":
1255                                 $data = api_rss_extra($a, $data, $user_info);
1256                 }
1257                                 
1258                 return  api_apply_template("direct_messages", $type, $data);
1259                 
1260         }
1261
1262         function api_direct_messages_sentbox(&$a, $type){
1263                 return api_direct_messages_box($a, $type, "sentbox");
1264         }
1265         function api_direct_messages_inbox(&$a, $type){
1266                 return api_direct_messages_box($a, $type, "inbox");
1267         }
1268         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1269         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1270
1271
1272
1273         function api_oauth_request_token(&$a, $type){
1274                 try{
1275                         $oauth = new FKOAuth1();
1276                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1277                 }catch(Exception $e){
1278                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1279                 }
1280                 echo $r;
1281                 killme();       
1282         }
1283         function api_oauth_access_token(&$a, $type){
1284                 try{
1285                         $oauth = new FKOAuth1();
1286                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1287                 }catch(Exception $e){
1288                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1289                 }
1290                 echo $r;
1291                 killme();                       
1292         }
1293
1294         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1295         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1296
1297