]> git.mxchange.org Git - friendica.git/blob - include/api.php
62dc7850649f7ffebac285f0251471b8f97f8155
[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                                 $type="json";           
118                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
119                                 if (strpos($a->query_string, ".json")>0) $type="json";
120                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
121                                 if (strpos($a->query_string, ".atom")>0) $type="atom";                          
122                                 
123                                 $r = call_user_func($info['func'], $a, $type);
124                                 if ($r===false) return;
125
126                                 switch($type){
127                                         case "xml":
128                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
129                                                 header ("Content-Type: text/xml");
130                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
131                                                 break;
132                                         case "json": 
133                                                 header ("Content-Type: application/json");  
134                                                 foreach($r as $rr)
135                                                     return json_encode($rr);
136                                                 break;
137                                         case "rss":
138                                                 header ("Content-Type: application/rss+xml");
139                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
140                                                 break;
141                                         case "atom":
142                                                 header ("Content-Type: application/atom+xml");
143                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
144                                                 break;
145                                                 
146                                 }
147                                 //echo "<pre>"; var_dump($r); die();
148                         }
149                 }
150                 return false;
151         }
152
153         /**
154          * RSS extra info
155          */
156         function api_rss_extra(&$a, $arr, $user_info){
157                 if (is_null($user_info)) $user_info = api_get_user($a);
158                 $arr['$user'] = $user_info;
159                 $arr['$rss'] = array(
160                         'alternate' => $user_info['url'],
161                         'self' => $a->get_baseurl(). "/". $a->query_string,
162                         'base' => $a->get_baseurl(),
163                         'updated' => api_date(null),
164                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
165                         'language' => $user_info['language'],
166                         'logo'  => $a->get_baseurl()."/images/friendika-32.png",
167                 );
168                 
169                 return $arr;
170         }
171          
172         /**
173          * Returns user info array.
174          */
175         function api_get_user(&$a, $contact_id = Null){
176                 $user = null;
177                 $extra_query = "";
178
179                 if(!is_null($contact_id)){
180                         $user=$contact_id;
181                         $extra_query = "AND `contact`.`id` = %d ";
182                 }
183                 
184                 if(is_null($user) && x($_GET, 'user_id')) {
185                         $user = intval($_GET['user_id']);       
186                         $extra_query = "AND `contact`.`id` = %d ";
187                 }
188                 if(is_null($user) && x($_GET, 'screen_name')) {
189                         $user = dbesc($_GET['screen_name']);    
190                         $extra_query = "AND `contact`.`nick` = '%s' ";
191                 }
192                 
193                 if (is_null($user)){
194                         list($user, $null) = explode(".",$a->argv[3]);
195                         if(is_numeric($user)){
196                                 $user = intval($user);
197                                 $extra_query = "AND `contact`.`id` = %d ";
198                         } else {
199                                 $user = dbesc($user);
200                                 $extra_query = "AND `contact`.`nick` = '%s' ";
201                         }
202                 }
203                 
204                 if ($user==='') {
205                         if (local_user()===false) {
206                                 api_login($a); return False;
207                         } else {
208                                 $user = $_SESSION['uid'];
209                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
210                         }
211                         
212                 }
213                 
214
215                 // user info            
216                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
217                                 WHERE 1
218                                 $extra_query",
219                                 $user
220                 );
221                 if (count($uinfo)==0) {
222                         return False;
223                 }
224                 
225                 // count public wall messages
226                 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
227                                 WHERE  `uid` = %d
228                                 AND `type`='wall' 
229                                 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
230                                 intval($uinfo[0]['uid'])
231                 );
232                 $countitms = $r[0]['count'];
233                 
234                 // count friends
235                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
236                                 WHERE  `uid` = %d
237                                 AND `self`=0 AND `blocked`=0", 
238                                 intval($uinfo[0]['uid'])
239                 );
240                 $countfriends = $r[0]['count'];
241                                 
242
243                 $ret = Array(
244                         'uid' => $uinfo[0]['uid'],
245                         'id' => $uinfo[0]['cid'],
246                         'name' => $uinfo[0]['name'],
247                         'screen_name' => $uinfo[0]['nick'],
248                         'location' => '', //$uinfo[0]['default-location'],
249                         'profile_image_url' => $uinfo[0]['micro'],
250                         'url' => $uinfo[0]['url'],
251                         'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
252                         'protected' => false,   #
253                         'friends_count' => $countfriends,
254                         'created_at' => api_date($uinfo[0]['name-date']),
255                         'utc_offset' => 0, #XXX: fix me
256                         'time_zone' => '', //$uinfo[0]['timezone'],
257                         'geo_enabled' => false,
258                         'statuses_count' => $countitms, #XXX: fix me 
259                         'lang' => 'en', #XXX: fix me
260                         'description' => '',
261                         'followers_count' => $countfriends, #XXX: fix me
262                         'favourites_count' => 0,
263                         'contributors_enabled' => false,
264                         'follow_request_sent' => false,
265                         'profile_background_color' => 'cfe8f6',
266                         'profile_text_color' => '000000',
267                         'profile_link_color' => 'FF8500',
268                         'profile_sidebar_fill_color' =>'AD0066',
269                         'profile_sidebar_border_color' => 'AD0066',
270                         'profile_background_image_url' => '',
271                         'profile_background_tile' => false,
272                         'profile_use_background_image' => false,
273                         'notifications' => false,
274                         'verified' => true, #XXX: fix me
275                         'followers' => '', #XXX: fix me
276                         #'status' => null
277                 );
278         
279                 return $ret;
280                 
281         }
282
283         function api_item_get_user(&$a, $item) {
284                 // The author is our direct contact, in a conversation with us.
285                 if(link_compare($item['url'],$item['author-link'])) {
286                         return api_get_user($a,$item['cid']);
287                 }
288                 else {
289                         // The author may be a contact of ours, but is replying to somebody else. 
290                         // Figure out if we know him/her.
291                         $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
292             if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
293                                 return api_get_user($a,$a->contacts[$normalised]['id']);
294                 }
295                 // We don't know this person directly.
296                 $ret = array(
297                         'uid' => 0,
298                         'id' => 0,
299                         'name' => $item['author-name'],
300                         'screen_name' => '',
301                         'location' => '', //$uinfo[0]['default-location'],
302                         'profile_image_url' => $item['author-avatar'],
303                         'url' => $item['author-link'],
304                         'contact_url' => 0,
305                         'protected' => false,   #
306                         'friends_count' => 0,
307                         'created_at' => '',
308                         'utc_offset' => 0, #XXX: fix me
309                         'time_zone' => '', //$uinfo[0]['timezone'],
310                         'geo_enabled' => false,
311                         'statuses_count' => 0,
312                         'lang' => 'en', #XXX: fix me
313                         'description' => '',
314                         'followers_count' => 0,
315                         'favourites_count' => 0,
316                         'contributors_enabled' => false,
317                         'follow_request_sent' => false,
318                         'profile_background_color' => 'cfe8f6',
319                         'profile_text_color' => '000000',
320                         'profile_link_color' => 'FF8500',
321                         'profile_sidebar_fill_color' =>'AD0066',
322                         'profile_sidebar_border_color' => 'AD0066',
323                         'profile_background_image_url' => '',
324                         'profile_background_tile' => false,
325                         'profile_use_background_image' => false,
326                         'notifications' => false,
327                         'verified' => true, #XXX: fix me
328                         'followers' => '', #XXX: fix me
329                         #'status' => null
330                 );
331
332                 return $ret; 
333         }
334
335         /**
336          * apply xmlify() to all values of array $val, recursively
337          */
338         function api_xmlify($val){
339                 if (is_bool($val)) return $val?"true":"false";
340                 if (is_array($val)) return array_map('api_xmlify', $val);
341                 return xmlify($val);
342         }
343
344         /**
345          *  load api $templatename for $type and replace $data array
346          */
347         function api_apply_template($templatename, $type, $data){
348
349                 $a = get_app();
350
351                 switch($type){
352                         case "atom":
353                         case "rss":
354                         case "xml":
355                                 $data = api_xmlify($data);
356                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
357                                 $ret = replace_macros($tpl, $data);
358                                 break;
359                         case "json":
360                                 $ret = $data;
361                                 break;
362                 }
363                 return $ret;
364         }
365         
366         /**
367          ** TWITTER API
368          */
369         
370         /**
371          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
372          * returns a 401 status code and an error message if not. 
373          * http://developer.twitter.com/doc/get/account/verify_credentials
374          */
375         function api_account_verify_credentials(&$a, $type){
376                 if (local_user()===false) return false;
377                 $user_info = api_get_user($a);
378                 
379                 return api_apply_template("user", $type, array('$user' => $user_info));
380
381         }
382         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
383                 
384
385         /**
386          * get data from $_POST or $_GET
387          */
388         function requestdata($k){
389                 if (isset($_POST[$k])){
390                         return $_POST[$k];
391                 }
392                 if (isset($_GET[$k])){
393                         return $_GET[$k];
394                 }
395                 return null;
396         }
397         // TODO - media uploads
398         function api_statuses_update(&$a, $type) {
399                 if (local_user()===false) return false;
400                 $user_info = api_get_user($a);
401
402                 // convert $_POST array items to the form we use for web posts.
403
404                 $_POST['body'] = urldecode(requestdata('status'));
405                 $_POST['parent'] = requestdata('in_reply_to_status_id');
406                 if(requestdata('lat') && requestdata('long'))
407                         $_POST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
408                 $_POST['profile_uid'] = local_user();
409                 if(requestdata('parent'))
410                         $_POST['type'] = 'net-comment';
411                 else
412                         $_POST['type'] = 'wall';
413
414                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
415
416                 $_POST['api_source'] = true;
417
418                 // call out normal post function
419
420                 require_once('mod/item.php');
421                 item_post($a);  
422
423                 // this should output the last post (the one we just posted).
424                 return api_status_show($a,$type);
425         }
426         api_register_func('api/statuses/update','api_statuses_update', true);
427
428
429         function api_status_show(&$a, $type){
430                 $user_info = api_get_user($a);
431                 // get last public wall message
432                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
433                                 FROM `item`, `contact`,
434                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
435                                 WHERE `item`.`contact-id` = %d
436                                         AND `i`.`id` = `item`.`parent`
437                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
438                                         AND `type`!='activity'
439                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
440                                 ORDER BY `created` DESC 
441                                 LIMIT 1",
442                                 intval($user_info['id'])
443                 );
444
445                 if (count($lastwall)>0){
446                         $lastwall = $lastwall[0];
447                         
448                         $in_reply_to_status_id = '';
449                         $in_reply_to_user_id = '';
450                         $in_reply_to_screen_name = '';
451                         if ($lastwall['parent']!=$lastwall['id']) {
452                                 $in_reply_to_status_id=$lastwall['parent'];
453                                 $in_reply_to_user_id = $lastwall['reply_uid'];
454                                 $in_reply_to_screen_name = $lastwall['reply_author'];
455                         }  
456                         $status_info = array(
457                                 'created_at' => api_date($lastwall['created']),
458                                 'id' => $lastwall['contact-id'],
459                                 'text' => strip_tags(bbcode($lastwall['body'])),
460                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
461                                 'truncated' => false,
462                                 'in_reply_to_status_id' => $in_reply_to_status_id,
463                                 'in_reply_to_user_id' => $in_reply_to_user_id,
464                                 'favorited' => false,
465                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
466                                 'geo' => '',
467                                 'coordinates' => $lastwall['coord'],
468                                 'place' => $lastwall['location'],
469                                 'contributors' => ''                                    
470                         );
471                         $status_info['user'] = $user_info;
472                 }
473                 return  api_apply_template("status", $type, array('$status' => $status_info));
474                 
475         }
476
477
478
479
480                 
481         /**
482          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
483          * The author's most recent status will be returned inline.
484          * http://developer.twitter.com/doc/get/users/show
485          */
486         function api_users_show(&$a, $type){
487                 $user_info = api_get_user($a);
488                 // get last public wall message
489                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
490                                 FROM `item`, `contact`,
491                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
492                                 WHERE `item`.`contact-id` = %d
493                                         AND `i`.`id` = `item`.`parent`
494                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
495                                         AND `type`!='activity'
496                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
497                                 ORDER BY `created` DESC 
498                                 LIMIT 1",
499                                 intval($user_info['id'])
500                 );
501
502                 if (count($lastwall)>0){
503                         $lastwall = $lastwall[0];
504                         
505                         $in_reply_to_status_id = '';
506                         $in_reply_to_user_id = '';
507                         $in_reply_to_screen_name = '';
508                         if ($lastwall['parent']!=$lastwall['id']) {
509                                 $in_reply_to_status_id=$lastwall['parent'];
510                                 $in_reply_to_user_id = $lastwall['reply_uid'];
511                                 $in_reply_to_screen_name = $lastwall['reply_author'];
512                         }  
513                         $user_info['status'] = array(
514                                 'created_at' => api_date($lastwall['created']),
515                                 'id' => $lastwall['contact-id'],
516                                 'text' => strip_tags(bbcode($lastwall['body'])),
517                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
518                                 'truncated' => false,
519                                 'in_reply_to_status_id' => $in_reply_to_status_id,
520                                 'in_reply_to_user_id' => $in_reply_to_user_id,
521                                 'favorited' => false,
522                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
523                                 'geo' => '',
524                                 'coordinates' => $lastwall['coord'],
525                                 'place' => $lastwall['location'],
526                                 'contributors' => ''                                    
527                         );
528                 }
529                 return  api_apply_template("user", $type, array('$user' => $user_info));
530                 
531         }
532         api_register_func('api/users/show','api_users_show');
533         
534         /**
535          * 
536          * http://developer.twitter.com/doc/get/statuses/home_timeline
537          * 
538          * TODO: Optional parameters
539          * TODO: Add reply info
540          */
541         function api_statuses_home_timeline(&$a, $type){
542                 if (local_user()===false) return false;
543                 
544                 $user_info = api_get_user($a);
545                 // get last newtork messages
546 //              $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
547
548                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
549                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
550                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
551                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
552                         FROM `item`, `contact`
553                         WHERE `item`.`uid` = %d
554                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
555                         AND `contact`.`id` = `item`.`contact-id`
556                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
557                         $sql_extra
558                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
559                         intval($user_info['uid']),
560                         0,20
561                 );
562
563                 $ret = api_format_items($r,$user_info);
564
565                 
566                 $data = array('$statuses' => $ret);
567                 switch($type){
568                         case "atom":
569                         case "rss":
570                                 $data = api_rss_extra($a, $data, $user_info);
571                 }
572                                 
573                 return  api_apply_template("timeline", $type, $data);
574         }
575         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
576         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
577
578
579
580         function api_statuses_user_timeline(&$a, $type){
581                 if (local_user()===false) return false;
582                 
583                 $user_info = api_get_user($a);
584                 // get last newtork messages
585 //              $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
586
587                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
588                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
589                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
590                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
591                         FROM `item`, `contact`
592                         WHERE `item`.`uid` = %d
593                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
594                         AND `item`.`wall` = 1
595                         AND `contact`.`id` = `item`.`contact-id`
596                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
597                         $sql_extra
598                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
599                         intval($user_info['uid']),
600                         0,20
601                 );
602
603                 $ret = api_format_items($r,$user_info);
604
605                 
606                 $data = array('$statuses' => $ret);
607                 switch($type){
608                         case "atom":
609                         case "rss":
610                                 $data = api_rss_extra($a, $data, $user_info);
611                 }
612                                 
613                 return  api_apply_template("timeline", $type, $data);
614         }
615
616         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
617
618
619         function api_favorites(&$a, $type){
620                 if (local_user()===false) return false;
621                 
622                 $user_info = api_get_user($a);
623                 // get last newtork messages
624 //              $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
625
626                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
627                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
628                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
629                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
630                         FROM `item`, `contact`
631                         WHERE `item`.`uid` = %d
632                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
633                         AND `item`.`starred` = 1
634                         AND `contact`.`id` = `item`.`contact-id`
635                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
636                         $sql_extra
637                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
638                         intval($user_info['uid']),
639                         0,20
640                 );
641
642                 $ret = api_format_items($r,$user_info);
643
644                 
645                 $data = array('$statuses' => $ret);
646                 switch($type){
647                         case "atom":
648                         case "rss":
649                                 $data = api_rss_extra($a, $data, $user_info);
650                 }
651                                 
652                 return  api_apply_template("timeline", $type, $data);
653         }
654
655         api_register_func('api/favorites','api_favorites', true);
656
657         
658         function api_format_items($r,$user_info) {
659                 $a = get_app();
660                 $ret = Array();
661
662                 foreach($r as $item) {
663                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
664                         $status = array(
665                                 'created_at'=> api_date($item['created']),
666                                 'published' => datetime_convert('UTC','UTC',$item['created'],ATOM_TIME),
667                                 'updated'   => datetime_convert('UTC','UTC',$item['edited'],ATOM_TIME),
668                                 'id'            => $item['uri'],
669                                 'text'          => strip_tags(bbcode($item['body'])),
670                                 'html'          => bbcode($item['body']),
671                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
672                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
673                                 'truncated' => False,
674                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
675                                 'in_reply_to_user_id' => '',
676                                 'favorited' => false,
677                                 'in_reply_to_screen_name' => '',
678                                 'geo' => '',
679                                 'coordinates' => $item['coord'],
680                                 'place' => $item['location'],
681                                 'contributors' => '',
682                                 'annotations'  => '',
683                                 'entities'  => '',
684                                 'user' =>  $status_user ,
685                                 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
686                                 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
687                                 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
688                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,                                
689                         );
690                         $ret[]=$status;
691                 };
692                 return $ret;
693         }
694
695
696         function api_account_rate_limit_status(&$a,$type) {
697
698                 $hash = array(
699                           'remaining_hits' => (string) 150,
700                           'hourly_limit' => (string) 150,
701                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
702                           'reset_time_in_seconds' => strtotime('now + 1 hour')
703                 );
704
705                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
706
707         }
708         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
709
710
711         function api_statusnet_config(&$a,$type) {
712                 $name = $a->config['sitename'];
713                 $server = $a->get_hostname();
714                 $logo = $a->get_baseurl() . '/images/friendika-64.png';
715                 $email = $a->config['admin_email'];
716                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
717                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
718                 $textlimit = (($a->config['max_import_size']) ? $a->config['max_import_size'] : '200000');
719                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
720                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
721
722                 $config = array(
723                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
724                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
725                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
726                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
727                                 'shorturllength' => '30'
728                         ),
729                 );  
730
731                 return api_apply_template('config', $type, array('$config' => $config));
732
733         }
734         api_register_func('api/statusnet/config','api_statusnet_config',false);
735
736
737         function api_statusnet_version(&$a,$type) {
738
739                 // liar
740
741                 if($type === 'xml') {
742                         header("Content-type: application/xml");
743                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
744                         killme();
745                 }
746                 elseif($type === 'json') {
747                         header("Content-type: application/json");
748                         echo '"0.9.7"';
749                         killme();
750                 }
751         }
752         api_register_func('api/statusnet/version','api_statusnet_version',false);