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