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