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