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