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