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