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