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