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