]> git.mxchange.org Git - friendica.git/blob - include/api.php
waitman gobble media upload via api patch
[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         /* 
7          * Twitter-Like API
8          *  
9          */
10
11         $API = Array();
12         $called_api = Null; 
13
14         function api_date($str){
15                 //Wed May 23 06:01:13 +0000 2007
16                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
17         }
18          
19         
20         function api_register_func($path, $func, $auth=false){
21                 global $API;
22                 $API[$path] = array('func'=>$func,
23                                                         'auth'=>$auth);
24         }
25         
26         /**
27          * Simple HTTP Login
28          */
29
30         function api_login(&$a){
31                 // login with oauth
32                 try{
33                         $oauth = new FKOAuth1();
34                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
35                         if (!is_null($token)){
36                                 $oauth->loginUser($token->uid);
37                                 call_hooks('logged_in', $a->user);
38                                 return;
39                         }
40                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
41                 }catch(Exception $e){
42                         logger(__file__.__line__.__function__."\n".$e);
43                         //die(__file__.__line__.__function__."<pre>".$e); die();
44                 }
45
46                 
47                 
48                 // workaround for HTTP-auth in CGI mode
49                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
50                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
51                         if(strlen($userpass)) {
52                                 list($name, $password) = explode(':', $userpass);
53                                 $_SERVER['PHP_AUTH_USER'] = $name;
54                                 $_SERVER['PHP_AUTH_PW'] = $password;
55                         }
56                 }
57
58                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
59                    logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
60                     header('WWW-Authenticate: Basic realm="Friendica"');
61                     header('HTTP/1.0 401 Unauthorized');
62                     die('This api requires login');
63                 }
64                 
65                 $user = $_SERVER['PHP_AUTH_USER'];
66                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
67                 
68                 
69                         /**
70                          *  next code from mod/auth.php. needs better solution
71                          */
72                         
73                 // process normal login request
74
75                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) 
76                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
77                         dbesc(trim($user)),
78                         dbesc(trim($user)),
79                         dbesc($encrypted)
80                 );
81                 if(count($r)){
82                         $record = $r[0];
83                 } else {
84                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
85                     header('WWW-Authenticate: Basic realm="Friendika"');
86                     header('HTTP/1.0 401 Unauthorized');
87                     die('This api requires login');
88                 }
89
90                 require_once('include/security.php');
91                 authenticate_success($record);
92
93                 call_hooks('logged_in', $a->user);
94
95         }
96         
97         /**************************
98          *  MAIN API ENTRY POINT  *
99          **************************/
100         function api_call(&$a){
101                 GLOBAL $API, $called_api;
102                 foreach ($API as $p=>$info){
103                         if (strpos($a->query_string, $p)===0){
104                                 $called_api= explode("/",$p);
105                                 //unset($_SERVER['PHP_AUTH_USER']);
106                                 if ($info['auth']===true && local_user()===false) {
107                                                 api_login($a);
108                                 }
109
110                                 load_contact_links(local_user());
111
112                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);               
113                                 logger('API parameters: ' . print_r($_REQUEST,true));
114                                 $type="json";           
115                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
116                                 if (strpos($a->query_string, ".json")>0) $type="json";
117                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
118                                 if (strpos($a->query_string, ".atom")>0) $type="atom";                          
119                                 
120                                 $r = call_user_func($info['func'], $a, $type);
121                                 if ($r===false) return;
122
123                                 switch($type){
124                                         case "xml":
125                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
126                                                 header ("Content-Type: text/xml");
127                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
128                                                 break;
129                                         case "json": 
130                                                 //header ("Content-Type: application/json");  
131                                                 foreach($r as $rr)
132                                                     return json_encode($rr);
133                                                 break;
134                                         case "rss":
135                                                 header ("Content-Type: application/rss+xml");
136                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
137                                                 break;
138                                         case "atom":
139                                                 header ("Content-Type: application/atom+xml");
140                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
141                                                 break;
142                                                 
143                                 }
144                                 //echo "<pre>"; var_dump($r); die();
145                         }
146                 }
147                 $r = '<status><error>not implemented</error></status>';
148                 switch($type){
149                         case "xml":
150                                 header ("Content-Type: text/xml");
151                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
152                                 break;
153                         case "json": 
154                                 header ("Content-Type: application/json");  
155                             return json_encode(array('error' => 'not implemented'));
156                                 break;
157                         case "rss":
158                                 header ("Content-Type: application/rss+xml");
159                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
160                                 break;
161                         case "atom":
162                                 header ("Content-Type: application/atom+xml");
163                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
164                                 break;
165                                 
166                 }
167         }
168
169         /**
170          * RSS extra info
171          */
172         function api_rss_extra(&$a, $arr, $user_info){
173                 if (is_null($user_info)) $user_info = api_get_user($a);
174                 $arr['$user'] = $user_info;
175                 $arr['$rss'] = array(
176                         'alternate' => $user_info['url'],
177                         'self' => $a->get_baseurl(). "/". $a->query_string,
178                         'base' => $a->get_baseurl(),
179                         'updated' => api_date(null),
180                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
181                         'language' => $user_info['language'],
182                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
183                 );
184                 
185                 return $arr;
186         }
187          
188         /**
189          * Returns user info array.
190          */
191         function api_get_user(&$a, $contact_id = Null){
192                 global $called_api;
193                 $user = null;
194                 $extra_query = "";
195
196
197                 if(!is_null($contact_id)){
198                         $user=$contact_id;
199                         $extra_query = "AND `contact`.`id` = %d ";
200                 }
201                 
202                 if(is_null($user) && x($_GET, 'user_id')) {
203                         $user = intval($_GET['user_id']);       
204                         $extra_query = "AND `contact`.`id` = %d ";
205                 }
206                 if(is_null($user) && x($_GET, 'screen_name')) {
207                         $user = dbesc($_GET['screen_name']);    
208                         $extra_query = "AND `contact`.`nick` = '%s' ";
209                         if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
210                         
211                 }
212                 
213                 if (is_null($user) && $a->argc > (count($called_api)-1)){
214                         $argid = count($called_api);
215                         list($user, $null) = explode(".",$a->argv[$argid]);
216                         if(is_numeric($user)){
217                                 $user = intval($user);
218                                 $extra_query = "AND `contact`.`id` = %d ";
219                         } else {
220                                 $user = dbesc($user);
221                                 $extra_query = "AND `contact`.`nick` = '%s' ";
222                                 if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
223                         }
224                 }
225                 
226                 if (! $user) {
227                         if (local_user()===false) {
228                                 api_login($a); return False;
229                         } else {
230                                 $user = $_SESSION['uid'];
231                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
232                         }
233                         
234                 }
235                 
236                 logger('api_user: ' . $extra_query . ' ' , $user);
237                 // user info            
238                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
239                                 WHERE 1
240                                 $extra_query",
241                                 $user
242                 );
243                 if (count($uinfo)==0) {
244                         return False;
245                 }
246                 
247                 if($uinfo[0]['self']) {
248                         $usr = q("select * from user where uid = %d limit 1",
249                                 intval(local_user())
250                         );
251                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
252                                 intval(local_user())
253                         );
254
255                         // count public wall messages
256                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
257                                         WHERE  `uid` = %d
258                                         AND `type`='wall' 
259                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
260                                         intval($uinfo[0]['uid'])
261                         );
262                         $countitms = $r[0]['count'];
263                 }
264                 else {
265                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
266                                         WHERE  `contact-id` = %d
267                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
268                                         intval($uinfo[0]['id'])
269                         );
270                         $countitms = $r[0]['count'];
271                 }
272
273                 // count friends
274                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
275                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
276                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
277                                 intval($uinfo[0]['uid']),
278                                 intval(CONTACT_IS_SHARING),
279                                 intval(CONTACT_IS_FRIEND)
280                 );
281                 $countfriends = $r[0]['count'];
282
283                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
284                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
285                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
286                                 intval($uinfo[0]['uid']),
287                                 intval(CONTACT_IS_FOLLOWER),
288                                 intval(CONTACT_IS_FRIEND)
289                 );
290                 $countfollowers = $r[0]['count'];
291
292                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
293                         intval($uinfo[0]['uid'])
294                 );
295                 $starred = $r[0]['count'];
296         
297
298                 if(! $uinfo[0]['self']) {
299                         $countfriends = 0;
300                         $countfollowers = 0;
301                         $starred = 0;
302                 }
303
304                 $ret = Array(
305                         'self' => intval($uinfo[0]['self']),
306                         'uid' => intval($uinfo[0]['uid']),
307                         'id' => intval($uinfo[0]['cid']),
308                         'name' => $uinfo[0]['name'],
309                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
310                         'location' => ($usr) ? $usr[0]['default-location'] : '',
311                         'profile_image_url' => $uinfo[0]['micro'],
312                         'url' => $uinfo[0]['url'],
313                         'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
314                         'protected' => false,   
315                         'friends_count' => intval($countfriends),
316                         'created_at' => api_date($uinfo[0]['name-date']),
317                         'utc_offset' => "+00:00",
318                         'time_zone' => 'UTC', //$uinfo[0]['timezone'],
319                         'geo_enabled' => false,
320                         'statuses_count' => intval($countitms), #XXX: fix me 
321                         'lang' => 'en', #XXX: fix me
322                         'description' => (($profile) ? $profile[0]['pdesc'] : ''),
323                         'followers_count' => intval($countfollowers),
324                         'favourites_count' => intval($starred),
325                         'contributors_enabled' => false,
326                         'follow_request_sent' => true,
327                         'profile_background_color' => 'cfe8f6',
328                         'profile_text_color' => '000000',
329                         'profile_link_color' => 'FF8500',
330                         'profile_sidebar_fill_color' =>'AD0066',
331                         'profile_sidebar_border_color' => 'AD0066',
332                         'profile_background_image_url' => '',
333                         'profile_background_tile' => false,
334                         'profile_use_background_image' => false,
335                         'notifications' => false,
336                         'following' => '', #XXX: fix me
337                         'verified' => true, #XXX: fix me
338                         'status' => array()
339                 );
340         
341                 return $ret;
342                 
343         }
344
345         function api_item_get_user(&$a, $item) {
346                 // The author is our direct contact, in a conversation with us.
347                 if(link_compare($item['url'],$item['author-link'])) {
348                         return api_get_user($a,$item['cid']);
349                 }
350                 else {
351                         // The author may be a contact of ours, but is replying to somebody else. 
352                         // Figure out if we know him/her.
353                         $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
354             if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
355                                 return api_get_user($a,$a->contacts[$normalised]['id']);
356                 }
357                 // We don't know this person directly.
358                 
359                 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
360                 $name=str_replace(")","",$name);
361                 
362                 $ret = array(
363                         'uid' => 0,
364                         'id' => 0,
365                         'name' => $name,
366                         'screen_name' => $nick,
367                         'location' => '', //$uinfo[0]['default-location'],
368                         'profile_image_url' => $item['author-avatar'],
369                         'url' => $item['author-link'],
370                         'contact_url' => 0,
371                         'protected' => false,   #
372                         'friends_count' => 0,
373                         'created_at' => '',
374                         'utc_offset' => 0, #XXX: fix me
375                         'time_zone' => '', //$uinfo[0]['timezone'],
376                         'geo_enabled' => false,
377                         'statuses_count' => 0,
378                         'lang' => 'en', #XXX: fix me
379                         'description' => '',
380                         'followers_count' => 0,
381                         'favourites_count' => 0,
382                         'contributors_enabled' => false,
383                         'follow_request_sent' => false,
384                         'profile_background_color' => 'cfe8f6',
385                         'profile_text_color' => '000000',
386                         'profile_link_color' => 'FF8500',
387                         'profile_sidebar_fill_color' =>'AD0066',
388                         'profile_sidebar_border_color' => 'AD0066',
389                         'profile_background_image_url' => '',
390                         'profile_background_tile' => false,
391                         'profile_use_background_image' => false,
392                         'notifications' => false,
393                         'verified' => true, #XXX: fix me
394                         'followers' => '', #XXX: fix me
395                         'status' => array()
396                 );
397
398                 return $ret; 
399         }
400
401
402         /**
403          *  load api $templatename for $type and replace $data array
404          */
405         function api_apply_template($templatename, $type, $data){
406
407                 $a = get_app();
408
409                 switch($type){
410                         case "atom":
411                         case "rss":
412                         case "xml":
413                                 $data = array_xmlify($data);
414                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
415                                 $ret = replace_macros($tpl, $data);
416                                 break;
417                         case "json":
418                                 $ret = $data;
419                                 break;
420                 }
421                 return $ret;
422         }
423         
424         /**
425          ** TWITTER API
426          */
427         
428         /**
429          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
430          * returns a 401 status code and an error message if not. 
431          * http://developer.twitter.com/doc/get/account/verify_credentials
432          */
433         function api_account_verify_credentials(&$a, $type){
434                 if (local_user()===false) return false;
435                 $user_info = api_get_user($a);
436                 
437                 return api_apply_template("user", $type, array('$user' => $user_info));
438
439         }
440         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
441                 
442
443         /**
444          * get data from $_POST or $_GET
445          */
446         function requestdata($k){
447                 if (isset($_POST[$k])){
448                         return $_POST[$k];
449                 }
450                 if (isset($_GET[$k])){
451                         return $_GET[$k];
452                 }
453                 return null;
454         }
455
456 /*Waitman Gobble Mod*/
457         function api_statuses_mediap(&$a, $type) {
458                 if (local_user()===false) {
459                         logger('api_statuses_update: no user');
460                         return false;
461                 }
462                 $user_info = api_get_user($a);
463
464                 $_REQUEST['type'] = 'wall';
465                 $_REQUEST['profile_uid'] = local_user();
466                 $_REQUEST['api_source'] = true;
467                 $txt = urldecode(requestdata('status'));
468
469                 require_once('library/HTMLPurifier.auto.php');
470                 require_once('include/html2bbcode.php');
471
472                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
473                         $txt = html2bb_video($txt);
474                         $config = HTMLPurifier_Config::createDefault();
475                         $config->set('Cache.DefinitionImpl', null);
476                         $purifier = new HTMLPurifier($config);
477                         $txt = $purifier->purify($txt);
478                 }
479                 $txt = html2bbcode($txt);
480                 
481                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
482                 
483                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
484                 require_once('mod/wall_upload.php');
485                 $bebop = wall_upload_post($a);
486                 
487                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
488                 $_REQUEST['body']=$txt."\n\n".$bebop;
489                 require_once('mod/item.php');
490                 item_post($a);
491
492                 // this should output the last post (the one we just posted).
493                 return api_status_show($a,$type);
494         }
495         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
496 /*Waitman Gobble Mod*/
497
498
499         function api_statuses_update(&$a, $type) {
500                 if (local_user()===false) {
501                         logger('api_statuses_update: no user');
502                         return false;
503                 }
504                 $user_info = api_get_user($a);
505
506                 // convert $_POST array items to the form we use for web posts.
507
508                 // logger('api_post: ' . print_r($_POST,true));
509
510                 if(requestdata('htmlstatus')) {
511                         require_once('library/HTMLPurifier.auto.php');
512                         require_once('include/html2bbcode.php');
513
514                         $txt = requestdata('htmlstatus');
515                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
516
517                                 $txt = html2bb_video($txt);
518
519                                 $config = HTMLPurifier_Config::createDefault();
520                                 $config->set('Cache.DefinitionImpl', null);
521
522
523                                 $purifier = new HTMLPurifier($config);
524                                 $txt = $purifier->purify($txt);
525
526                                 $_REQUEST['body'] = html2bbcode($txt);
527                         }
528
529                 }
530                 else
531                         $_REQUEST['body'] = urldecode(requestdata('status'));
532
533                 $parent = requestdata('in_reply_to_status_id');
534                 if(ctype_digit($parent))
535                         $_REQUEST['parent'] = $parent;
536                 else
537                         $_REQUEST['parent_uri'] = $parent;
538
539                 if(requestdata('lat') && requestdata('long'))
540                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
541                 $_REQUEST['profile_uid'] = local_user();
542                 if(requestdata('parent'))
543                         $_REQUEST['type'] = 'net-comment';
544                 else
545                         $_REQUEST['type'] = 'wall';
546
547                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
548
549                 $_REQUEST['api_source'] = true;
550
551                 // call out normal post function
552
553                 require_once('mod/item.php');
554                 item_post($a);  
555
556                 // this should output the last post (the one we just posted).
557                 return api_status_show($a,$type);
558         }
559         api_register_func('api/statuses/update','api_statuses_update', true);
560
561
562         function api_status_show(&$a, $type){
563                 $user_info = api_get_user($a);
564                 // get last public wall message
565                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
566                                 FROM `item`, `contact`,
567                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
568                                 WHERE `item`.`contact-id` = %d
569                                         AND `i`.`id` = `item`.`parent`
570                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
571                                         AND `type`!='activity'
572                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
573                                 ORDER BY `created` DESC 
574                                 LIMIT 1",
575                                 intval($user_info['id'])
576                 );
577
578                 if (count($lastwall)>0){
579                         $lastwall = $lastwall[0];
580                         
581                         $in_reply_to_status_id = '';
582                         $in_reply_to_user_id = '';
583                         $in_reply_to_screen_name = '';
584                         if ($lastwall['parent']!=$lastwall['id']) {
585                                 $in_reply_to_status_id=$lastwall['parent'];
586                                 $in_reply_to_user_id = $lastwall['reply_uid'];
587                                 $in_reply_to_screen_name = $lastwall['reply_author'];
588                         }  
589                         $status_info = array(
590                                 'created_at' => api_date($lastwall['created']),
591                                 'id' => $lastwall['contact-id'],
592                                 'text' => strip_tags(bbcode($lastwall['body'])),
593                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
594                                 'truncated' => false,
595                                 'in_reply_to_status_id' => $in_reply_to_status_id,
596                                 'in_reply_to_user_id' => $in_reply_to_user_id,
597                                 'favorited' => false,
598                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
599                                 'geo' => '',
600                                 'coordinates' => $lastwall['coord'],
601                                 'place' => $lastwall['location'],
602                                 'contributors' => ''                                    
603                         );
604                         $status_info['user'] = $user_info;
605                 }
606                 return  api_apply_template("status", $type, array('$status' => $status_info));
607                 
608         }
609
610
611
612
613                 
614         /**
615          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
616          * The author's most recent status will be returned inline.
617          * http://developer.twitter.com/doc/get/users/show
618          */
619         function api_users_show(&$a, $type){
620                 $user_info = api_get_user($a);
621                 // get last public wall message
622                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
623                                 FROM `item`, `contact`,
624                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
625                                 WHERE `item`.`contact-id` = %d
626                                         AND `i`.`id` = `item`.`parent`
627                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
628                                         AND `type`!='activity'
629                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
630                                 ORDER BY `created` DESC 
631                                 LIMIT 1",
632                                 intval($user_info['id'])
633                 );
634
635                 if (count($lastwall)>0){
636                         $lastwall = $lastwall[0];
637                         
638                         $in_reply_to_status_id = '';
639                         $in_reply_to_user_id = '';
640                         $in_reply_to_screen_name = '';
641                         if ($lastwall['parent']!=$lastwall['id']) {
642                                 $in_reply_to_status_id=$lastwall['parent'];
643                                 $in_reply_to_user_id = $lastwall['reply_uid'];
644                                 $in_reply_to_screen_name = $lastwall['reply_author'];
645                         }  
646                         $user_info['status'] = array(
647                                 'created_at' => api_date($lastwall['created']),
648                                 'id' => $lastwall['contact-id'],
649                                 'text' => strip_tags(bbcode($lastwall['body'])),
650                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
651                                 'truncated' => false,
652                                 'in_reply_to_status_id' => $in_reply_to_status_id,
653                                 'in_reply_to_user_id' => $in_reply_to_user_id,
654                                 'favorited' => false,
655                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
656                                 'geo' => '',
657                                 'coordinates' => $lastwall['coord'],
658                                 'place' => $lastwall['location'],
659                                 'contributors' => ''                                    
660                         );
661                 }
662                 return  api_apply_template("user", $type, array('$user' => $user_info));
663                 
664         }
665         api_register_func('api/users/show','api_users_show');
666         
667         /**
668          * 
669          * http://developer.twitter.com/doc/get/statuses/home_timeline
670          * 
671          * TODO: Optional parameters
672          * TODO: Add reply info
673          */
674         function api_statuses_home_timeline(&$a, $type){
675                 if (local_user()===false) return false;
676                                 
677                 $user_info = api_get_user($a);
678                 // get last newtork messages
679
680
681                 // params
682                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
683                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
684                 if ($page<0) $page=0;
685                 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
686                 
687                 $start = $page*$count;
688
689                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
690                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
691                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
692                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
693                         FROM `item`, `contact`
694                         WHERE `item`.`uid` = %d
695                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
696                         AND `contact`.`id` = `item`.`contact-id`
697                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
698                         $sql_extra
699                         AND `item`.`id`>%d
700                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
701                         intval($user_info['uid']),
702                         intval($since_id),
703                         intval($start), intval($count)
704                 );
705
706                 $ret = api_format_items($r,$user_info);
707
708                 
709                 $data = array('$statuses' => $ret);
710                 switch($type){
711                         case "atom":
712                         case "rss":
713                                 $data = api_rss_extra($a, $data, $user_info);
714                 }
715                                 
716                 return  api_apply_template("timeline", $type, $data);
717         }
718         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
719         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
720
721
722
723         function api_statuses_user_timeline(&$a, $type){
724                 if (local_user()===false) return false;
725                 
726                 $user_info = api_get_user($a);
727                 // get last newtork messages
728
729
730                 logger("api_statuses_user_timeline: local_user: ". local_user() .
731                            "\nuser_info: ".print_r($user_info, true) .
732                            "\n_REQUEST:  ".print_r($_REQUEST, true),
733                            LOGGER_DEBUG);
734
735                 // params
736                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
737                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
738                 if ($page<0) $page=0;
739                 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
740                 
741                 $start = $page*$count;
742
743                 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
744
745                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
746                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
747                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
748                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
749                         FROM `item`, `contact`
750                         WHERE `item`.`uid` = %d
751                         AND `item`.`contact-id` = %d
752                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
753                         AND `contact`.`id` = `item`.`contact-id`
754                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
755                         $sql_extra
756                         AND `item`.`id`>%d
757                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
758                         intval(local_user()),
759                         intval($user_info['id']),
760                         intval($since_id),
761                         intval($start), intval($count)
762                 );
763
764                 $ret = api_format_items($r,$user_info);
765
766                 
767                 $data = array('$statuses' => $ret);
768                 switch($type){
769                         case "atom":
770                         case "rss":
771                                 $data = api_rss_extra($a, $data, $user_info);
772                 }
773                                 
774                 return  api_apply_template("timeline", $type, $data);
775         }
776
777         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
778
779
780         function api_favorites(&$a, $type){
781                 if (local_user()===false) return false;
782                 
783                 $user_info = api_get_user($a);
784                 // in friendica starred item are private
785                 // return favorites only for self
786                 logger('api_favorites: self:' . $user_info['self']);
787                 
788                 if ($user_info['self']==0) {
789                         $ret = array();
790                 } else {
791                         
792                         
793                         // params
794                         $count = (x($_GET,'count')?$_GET['count']:20);
795                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
796                         if ($page<0) $page=0;
797                         
798                         $start = $page*$count;
799
800                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
801                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
802                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
803                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
804                                 FROM `item`, `contact`
805                                 WHERE `item`.`uid` = %d
806                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
807                                 AND `item`.`starred` = 1
808                                 AND `contact`.`id` = `item`.`contact-id`
809                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
810                                 $sql_extra
811                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
812                                 intval($user_info['uid']),
813                                 intval($start), intval($count)
814                         );
815
816                         $ret = api_format_items($r,$user_info);
817                 
818                 }
819                 
820                 $data = array('$statuses' => $ret);
821                 switch($type){
822                         case "atom":
823                         case "rss":
824                                 $data = api_rss_extra($a, $data, $user_info);
825                 }
826                                 
827                 return  api_apply_template("timeline", $type, $data);
828         }
829
830         api_register_func('api/favorites','api_favorites', true);
831
832         
833         function api_format_items($r,$user_info) {
834
835                 //logger('api_format_items: ' . print_r($r,true));
836
837                 //logger('api_format_items: ' . print_r($user_info,true));
838
839                 $a = get_app();
840                 $ret = Array();
841
842                 foreach($r as $item) {
843                         localize_item($item);
844                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
845                         $status = array(
846                                 'created_at'=> api_date($item['created']),
847                                 'published' => api_date($item['created']),
848                                 'updated'   => api_date($item['edited']),
849                                 'id'            => intval($item['id']),
850                                 'message_id' => $item['uri'],
851                                 'text'          => strip_tags(bbcode($item['body'])),
852                                 'statusnet_html'                => bbcode($item['body']),
853                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
854                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
855                                 'truncated' => False,
856                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
857                                 'in_reply_to_user_id' => '',
858                                 'favorited' => $item['starred'] ? true : false,
859                                 'in_reply_to_screen_name' => '',
860                                 'geo' => '',
861                                 'coordinates' => $item['coord'],
862                                 'place' => $item['location'],
863                                 'contributors' => '',
864                                 'annotations'  => '',
865                                 'entities'  => '',
866                                 'user' =>  $status_user ,
867                                 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
868                                 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
869                                 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
870                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,                                
871                         );
872                         $ret[]=$status;
873                 };
874                 return $ret;
875         }
876
877
878         function api_account_rate_limit_status(&$a,$type) {
879
880                 $hash = array(
881                           'remaining_hits' => (string) 150,
882                           'hourly_limit' => (string) 150,
883                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
884                           'reset_time_in_seconds' => strtotime('now + 1 hour')
885                 );
886
887                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
888
889         }
890         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
891
892         /**
893          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
894          *  This function is deprecated by Twitter
895          *  returns: json, xml 
896          **/
897         function api_statuses_f(&$a, $type, $qtype) {
898                 if (local_user()===false) return false;
899                 $user_info = api_get_user($a);
900                 
901                 
902                 // friends and followers only for self
903                 if ($user_info['self']==0){
904                         return false;
905                 }
906                 
907                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
908                         /* this is to stop Hotot to load friends multiple times
909                         *  I'm not sure if I'm missing return something or
910                         *  is a bug in hotot. Workaround, meantime
911                         */
912                         
913                         /*$ret=Array();
914                         return array('$users' => $ret);*/
915                         return false;
916                 }
917                 
918                 if($qtype == 'friends')
919                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
920                 if($qtype == 'followers')
921                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
922  
923                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
924                         intval(local_user())
925                 );
926
927                 $ret = array();
928                 foreach($r as $cid){
929                         $ret[] = api_get_user($a, $cid['id']);
930                 }
931
932                 
933                 return array('$users' => $ret);
934
935         }
936         function api_statuses_friends(&$a, $type){
937                 $data =  api_statuses_f($a,$type,"friends");
938                 if ($data===false) return false;
939                 return  api_apply_template("friends", $type, $data);
940         }
941         function api_statuses_followers(&$a, $type){
942                 $data = api_statuses_f($a,$type,"followers");
943                 if ($data===false) return false;
944                 return  api_apply_template("friends", $type, $data);
945         }
946         api_register_func('api/statuses/friends','api_statuses_friends',true);
947         api_register_func('api/statuses/followers','api_statuses_followers',true);
948
949
950
951
952
953
954         function api_statusnet_config(&$a,$type) {
955                 $name = $a->config['sitename'];
956                 $server = $a->get_hostname();
957                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
958                 $email = $a->config['admin_email'];
959                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
960                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
961                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
962                 if($a->config['api_import_size'])
963                         $texlimit = string($a->config['api_import_size']);
964                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
965                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
966
967                 $config = array(
968                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
969                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
970                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
971                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
972                                 'shorturllength' => '30'
973                         ),
974                 );  
975
976                 return api_apply_template('config', $type, array('$config' => $config));
977
978         }
979         api_register_func('api/statusnet/config','api_statusnet_config',false);
980
981         function api_statusnet_version(&$a,$type) {
982
983                 // liar
984
985                 if($type === 'xml') {
986                         header("Content-type: application/xml");
987                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
988                         killme();
989                 }
990                 elseif($type === 'json') {
991                         header("Content-type: application/json");
992                         echo '"0.9.7"';
993                         killme();
994                 }
995         }
996         api_register_func('api/statusnet/version','api_statusnet_version',false);
997
998
999         function api_ff_ids(&$a,$type,$qtype) {
1000                 if(! local_user())
1001                         return false;
1002
1003                 if($qtype == 'friends')
1004                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1005                 if($qtype == 'followers')
1006                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1007  
1008
1009                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1010                         intval(local_user())
1011                 );
1012
1013                 if(is_array($r)) {
1014                         if($type === 'xml') {
1015                                 header("Content-type: application/xml");
1016                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1017                                 foreach($r as $rr)
1018                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1019                                 echo '</ids>' . "\r\n";
1020                                 killme();
1021                         }
1022                         elseif($type === 'json') {
1023                                 $ret = array();
1024                                 header("Content-type: application/json");
1025                                 foreach($r as $rr) $ret[] = $rr['id'];
1026                                 echo json_encode($ret);
1027                                 killme();
1028                         }
1029                 }
1030         }
1031
1032         function api_friends_ids(&$a,$type) {
1033                 api_ff_ids($a,$type,'friends');
1034         }
1035         function api_followers_ids(&$a,$type) {
1036                 api_ff_ids($a,$type,'followers');
1037         }
1038         api_register_func('api/friends/ids','api_friends_ids',true);
1039         api_register_func('api/followers/ids','api_followers_ids',true);
1040
1041
1042         function api_direct_messages_new(&$a, $type) {
1043                 if (local_user()===false) return false;
1044                 
1045                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1046                 
1047                 $sender = api_get_user($a);
1048                 
1049                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1050                                 intval(local_user()),
1051                                 dbesc($_POST['screen_name']));
1052                 
1053                 $recipient = api_get_user($a, $r[0]['id']);                     
1054                 
1055
1056                 require_once("include/message.php");
1057                 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1058                 $id = send_message($recipient['id'], $_POST['text'], $sub);
1059                 
1060                 
1061                 if ($id>-1) {
1062                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1063                         $item = $r[0];
1064                         $ret=Array(
1065                                         'id' => $item['id'],
1066                                         'created_at'=> api_date($item['created']),
1067                                         'sender_id'=> $sender['id'] ,
1068                                         'sender_screen_name'=> $sender['screen_name'],
1069                                         'sender'=> $sender,
1070                                         'recipient_id'=> $recipient['id'],
1071                                         'recipient_screen_name'=> $recipient['screen_name'],
1072                                         'recipient'=> $recipient,
1073                                         
1074                                         'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1075                                         
1076                         );
1077                 
1078                 } else {
1079                         $ret = array("error"=>$id);     
1080                 }
1081                 
1082                 $data = Array('$messages'=>$ret);
1083                 
1084                 switch($type){
1085                         case "atom":
1086                         case "rss":
1087                                 $data = api_rss_extra($a, $data, $user_info);
1088                 }
1089                                 
1090                 return  api_apply_template("direct_messages", $type, $data);
1091                                 
1092         }
1093         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1094
1095     function api_direct_messages_box(&$a, $type, $box) {
1096                 if (local_user()===false) return false;
1097                 
1098                 $user_info = api_get_user($a);
1099                 
1100                 // params
1101                 $count = (x($_GET,'count')?$_GET['count']:20);
1102                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1103                 if ($page<0) $page=0;
1104                 
1105                 $start = $page*$count;
1106                 
1107         
1108                 if ($box=="sentbox") {
1109                         $sql_extra = "`from-url`='%s'";
1110                 } else {
1111                         $sql_extra = "`from-url`!='%s'";
1112                 }
1113                 
1114                 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1115                                 intval(local_user()),
1116                                 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1117                                 intval($start), intval($count)
1118                            );
1119                 
1120                 $ret = Array();
1121                 foreach($r as $item){
1122                         switch ($box){
1123                                 case "inbox":
1124                                         $recipient = $user_info;
1125                                         $sender = api_get_user($a,$item['contact-id']);
1126                                         break;
1127                                 case "sentbox":
1128                                         $recipient = api_get_user($a,$item['contact-id']);
1129                                         $sender = $user_info;
1130                                         break;
1131                         }
1132                                 
1133                         $ret[]=Array(
1134                                 'id' => $item['id'],
1135                                 'created_at'=> api_date($item['created']),
1136                                 'sender_id'=> $sender['id'] ,
1137                                 'sender_screen_name'=> $sender['screen_name'],
1138                                 'sender'=> $sender,
1139                                 'recipient_id'=> $recipient['id'],
1140                                 'recipient_screen_name'=> $recipient['screen_name'],
1141                                 'recipient'=> $recipient,
1142                                 
1143                                 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1144                                 
1145                         );
1146                         
1147                 }
1148                 
1149
1150                 $data = array('$messages' => $ret);
1151                 switch($type){
1152                         case "atom":
1153                         case "rss":
1154                                 $data = api_rss_extra($a, $data, $user_info);
1155                 }
1156                                 
1157                 return  api_apply_template("direct_messages", $type, $data);
1158                 
1159         }
1160
1161         function api_direct_messages_sentbox(&$a, $type){
1162                 return api_direct_messages_box($a, $type, "sentbox");
1163         }
1164         function api_direct_messages_inbox(&$a, $type){
1165                 return api_direct_messages_box($a, $type, "inbox");
1166         }
1167         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1168         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1169
1170
1171
1172         function api_oauth_request_token(&$a, $type){
1173                 try{
1174                         $oauth = new FKOAuth1();
1175                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1176                 }catch(Exception $e){
1177                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1178                 }
1179                 echo $r;
1180                 killme();       
1181         }
1182         function api_oauth_access_token(&$a, $type){
1183                 try{
1184                         $oauth = new FKOAuth1();
1185                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1186                 }catch(Exception $e){
1187                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1188                 }
1189                 echo $r;
1190                 killme();                       
1191         }
1192
1193         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1194         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1195
1196