]> git.mxchange.org Git - friendica.git/blob - include/api.php
629b5fcc2ad19cabd87f3a1ada420396996fb0cc
[friendica.git] / include / api.php
1 <?php
2         require_once("bbcode.php");
3         require_once("datetime.php");
4         require_once("conversation.php");
5         require_once("oauth.php");
6         require_once("html2plain.php");
7         /*
8          * Twitter-Like API
9          *
10          */
11
12         $API = Array();
13         $called_api = Null;
14
15         function api_date($str){
16                 //Wed May 23 06:01:13 +0000 2007
17                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
18         }
19
20
21         function api_register_func($path, $func, $auth=false){
22                 global $API;
23                 $API[$path] = array('func'=>$func,
24                                                         'auth'=>$auth);
25         }
26
27         /**
28          * Simple HTTP Login
29          */
30
31         function api_login(&$a){
32                 // login with oauth
33                 try{
34                         $oauth = new FKOAuth1();
35                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
36                         if (!is_null($token)){
37                                 $oauth->loginUser($token->uid);
38                                 call_hooks('logged_in', $a->user);
39                                 return;
40                         }
41                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
42                 }catch(Exception $e){
43                         logger(__file__.__line__.__function__."\n".$e);
44                         //die(__file__.__line__.__function__."<pre>".$e); die();
45                 }
46
47                 
48                 
49                 // workaround for HTTP-auth in CGI mode
50                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
51                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
52                         if(strlen($userpass)) {
53                                 list($name, $password) = explode(':', $userpass);
54                                 $_SERVER['PHP_AUTH_USER'] = $name;
55                                 $_SERVER['PHP_AUTH_PW'] = $password;
56                         }
57                 }
58
59                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
60                    logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
61                     header('WWW-Authenticate: Basic realm="Friendica"');
62                     header('HTTP/1.0 401 Unauthorized');
63                     die('This api requires login');
64                 }
65                 
66                 $user = $_SERVER['PHP_AUTH_USER'];
67                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
68                 
69                 
70                         /**
71                          *  next code from mod/auth.php. needs better solution
72                          */
73                         
74                 // process normal login request
75
76                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) 
77                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
78                         dbesc(trim($user)),
79                         dbesc(trim($user)),
80                         dbesc($encrypted)
81                 );
82                 if(count($r)){
83                         $record = $r[0];
84                 } else {
85                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
86                     header('WWW-Authenticate: Basic realm="Friendica"');
87                     header('HTTP/1.0 401 Unauthorized');
88                     die('This api requires login');
89                 }
90
91                 require_once('include/security.php');
92                 authenticate_success($record);
93
94                 call_hooks('logged_in', $a->user);
95
96         }
97         
98         /**************************
99          *  MAIN API ENTRY POINT  *
100          **************************/
101         function api_call(&$a){
102                 GLOBAL $API, $called_api;
103
104                 // preset
105                 $type="json";
106
107                 foreach ($API as $p=>$info){
108                         if (strpos($a->query_string, $p)===0){
109                                 $called_api= explode("/",$p);
110                                 //unset($_SERVER['PHP_AUTH_USER']);
111                                 if ($info['auth']===true && local_user()===false) {
112                                                 api_login($a);
113                                 }
114
115                                 load_contact_links(local_user());
116
117                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
118                                 logger('API parameters: ' . print_r($_REQUEST,true));
119                                 $type="json";
120                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
121                                 if (strpos($a->query_string, ".json")>0) $type="json";
122                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
123                                 if (strpos($a->query_string, ".atom")>0) $type="atom";
124                                 if (strpos($a->query_string, ".as")>0) $type="as";
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                                         case "as":
149                                                 //header ("Content-Type: application/json");
150                                                 //foreach($r as $rr)
151                                                 //    return json_encode($rr);
152                                                 return json_encode($r);
153                                                 break;
154
155                                 }
156                                 //echo "<pre>"; var_dump($r); die();
157                         }
158                 }
159                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
160                 $r = '<status><error>not implemented</error></status>';
161                 switch($type){
162                         case "xml":
163                                 header ("Content-Type: text/xml");
164                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
165                                 break;
166                         case "json":
167                                 header ("Content-Type: application/json");
168                             return json_encode(array('error' => 'not implemented'));
169                                 break;
170                         case "rss":
171                                 header ("Content-Type: application/rss+xml");
172                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
173                                 break;
174                         case "atom":
175                                 header ("Content-Type: application/atom+xml");
176                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
177                                 break;
178                 }
179         }
180
181         /**
182          * RSS extra info
183          */
184         function api_rss_extra(&$a, $arr, $user_info){
185                 if (is_null($user_info)) $user_info = api_get_user($a);
186                 $arr['$user'] = $user_info;
187                 $arr['$rss'] = array(
188                         'alternate' => $user_info['url'],
189                         'self' => $a->get_baseurl(). "/". $a->query_string,
190                         'base' => $a->get_baseurl(),
191                         'updated' => api_date(null),
192                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
193                         'language' => $user_info['language'],
194                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
195                 );
196                 
197                 return $arr;
198         }
199          
200         /**
201          * Returns user info array.
202          */
203         function api_get_user(&$a, $contact_id = Null){
204                 global $called_api;
205                 $user = null;
206                 $extra_query = "";
207
208
209                 if(!is_null($contact_id)){
210                         $user=$contact_id;
211                         $extra_query = "AND `contact`.`id` = %d ";
212                 }
213                 
214                 if(is_null($user) && x($_GET, 'user_id')) {
215                         $user = intval($_GET['user_id']);       
216                         $extra_query = "AND `contact`.`id` = %d ";
217                 }
218                 if(is_null($user) && x($_GET, 'screen_name')) {
219                         $user = dbesc($_GET['screen_name']);    
220                         $extra_query = "AND `contact`.`nick` = '%s' ";
221                         if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
222                         
223                 }
224                 
225                 if (is_null($user) && $a->argc > (count($called_api)-1)){
226                         $argid = count($called_api);
227                         list($user, $null) = explode(".",$a->argv[$argid]);
228                         if(is_numeric($user)){
229                                 $user = intval($user);
230                                 $extra_query = "AND `contact`.`id` = %d ";
231                         } else {
232                                 $user = dbesc($user);
233                                 $extra_query = "AND `contact`.`nick` = '%s' ";
234                                 if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
235                         }
236                 }
237                 
238                 if (! $user) {
239                         if (local_user()===false) {
240                                 api_login($a); return False;
241                         } else {
242                                 $user = $_SESSION['uid'];
243                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
244                         }
245                         
246                 }
247                 
248                 logger('api_user: ' . $extra_query . ', user: ' . $user);
249                 // user info            
250                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
251                                 WHERE 1
252                                 $extra_query",
253                                 $user
254                 );
255                 if (count($uinfo)==0) {
256                         return False;
257                 }
258                 
259                 if($uinfo[0]['self']) {
260                         $usr = q("select * from user where uid = %d limit 1",
261                                 intval(local_user())
262                         );
263                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
264                                 intval(local_user())
265                         );
266
267                         // count public wall messages
268                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
269                                         WHERE  `uid` = %d
270                                         AND `type`='wall' 
271                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
272                                         intval($uinfo[0]['uid'])
273                         );
274                         $countitms = $r[0]['count'];
275                 }
276                 else {
277                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
278                                         WHERE  `contact-id` = %d
279                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
280                                         intval($uinfo[0]['id'])
281                         );
282                         $countitms = $r[0]['count'];
283                 }
284
285                 // count friends
286                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
287                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
288                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
289                                 intval($uinfo[0]['uid']),
290                                 intval(CONTACT_IS_SHARING),
291                                 intval(CONTACT_IS_FRIEND)
292                 );
293                 $countfriends = $r[0]['count'];
294
295                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
296                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
297                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
298                                 intval($uinfo[0]['uid']),
299                                 intval(CONTACT_IS_FOLLOWER),
300                                 intval(CONTACT_IS_FRIEND)
301                 );
302                 $countfollowers = $r[0]['count'];
303
304                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
305                         intval($uinfo[0]['uid'])
306                 );
307                 $starred = $r[0]['count'];
308         
309
310                 if(! $uinfo[0]['self']) {
311                         $countfriends = 0;
312                         $countfollowers = 0;
313                         $starred = 0;
314                 }
315
316                 $ret = Array(
317                         'id' => intval($uinfo[0]['cid']),
318                         'self' => intval($uinfo[0]['self']),
319                         'uid' => intval($uinfo[0]['uid']),
320                         'name' => (($uinfo[0]['name']) ? $uinfo[0]['name'] : $uinfo[0]['nick']),
321                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
322                         'location' => ($usr) ? $usr[0]['default-location'] : '',
323                         'profile_image_url' => $uinfo[0]['micro'],
324                         'url' => $uinfo[0]['url'],
325                         'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
326                         'protected' => false,   
327                         'friends_count' => intval($countfriends),
328                         'created_at' => api_date($uinfo[0]['name-date']),
329                         'utc_offset' => "+00:00",
330                         'time_zone' => 'UTC', //$uinfo[0]['timezone'],
331                         'geo_enabled' => false,
332                         'statuses_count' => intval($countitms), #XXX: fix me 
333                         'lang' => 'en', #XXX: fix me
334                         'description' => (($profile) ? $profile[0]['pdesc'] : ''),
335                         'followers_count' => intval($countfollowers),
336                         'favourites_count' => intval($starred),
337                         'contributors_enabled' => false,
338                         'follow_request_sent' => true,
339                         'profile_background_color' => 'cfe8f6',
340                         'profile_text_color' => '000000',
341                         'profile_link_color' => 'FF8500',
342                         'profile_sidebar_fill_color' =>'AD0066',
343                         'profile_sidebar_border_color' => 'AD0066',
344                         'profile_background_image_url' => '',
345                         'profile_background_tile' => false,
346                         'profile_use_background_image' => false,
347                         'notifications' => false,
348                         'following' => '', #XXX: fix me
349                         'verified' => true, #XXX: fix me
350                         'status' => array()
351                 );
352         
353                 return $ret;
354                 
355         }
356
357         function api_item_get_user(&$a, $item) {
358                 global $usercache;
359
360                 // The author is our direct contact, in a conversation with us.
361                 if(link_compare($item['url'],$item['author-link'])) {
362                         return api_get_user($a,$item['cid']);
363                 }
364                 else {
365                         // The author may be a contact of ours, but is replying to somebody else. 
366                         // Figure out if we know him/her.
367                         $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
368             if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
369                                 return api_get_user($a,$a->contacts[$normalised]['id']);
370                 }
371                 // We don't know this person directly.
372                 
373                 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
374                 $name=str_replace(")","",$name);
375
376                 if ($name == '')
377                         $name = $nick;
378
379                 if ($nick == '')
380                         $nick = $name;
381
382                 // Generating a random ID
383                 if (is_null($usercache[$nick]) or !array_key_exists($nick, $usercache))
384                         $usercache[$nick] = mt_rand(2000000, 2100000);
385
386                 $ret = array(
387                         'id' => $usercache[$nick],
388                         'name' => $name,
389                         'screen_name' => $nick,
390                         'location' => '', //$uinfo[0]['default-location'],
391                         'description' => '',
392                         'profile_image_url' => $item['author-avatar'],
393                         'url' => $item['author-link'],
394                         'protected' => false,   #
395                         'followers_count' => 0,
396                         'friends_count' => 0,
397                         'created_at' => '',
398                         'favourites_count' => 0,
399                         'utc_offset' => 0, #XXX: fix me
400                         'time_zone' => '', //$uinfo[0]['timezone'],
401                         'statuses_count' => 0,
402                         'following' => 1,
403                         'statusnet_blocking' => false,
404                         'notifications' => false,
405                         'uid' => 0,
406                         'contact_url' => 0,
407                         'geo_enabled' => false,
408                         'lang' => 'en', #XXX: fix me
409                         'contributors_enabled' => false,
410                         'follow_request_sent' => false,
411                         'profile_background_color' => 'cfe8f6',
412                         'profile_text_color' => '000000',
413                         'profile_link_color' => 'FF8500',
414                         'profile_sidebar_fill_color' =>'AD0066',
415                         'profile_sidebar_border_color' => 'AD0066',
416                         'profile_background_image_url' => '',
417                         'profile_background_tile' => false,
418                         'profile_use_background_image' => false,
419                         'verified' => true, #XXX: fix me
420                         'followers' => '', #XXX: fix me
421                         'status' => array()
422                 );
423
424                 return $ret; 
425         }
426
427
428         /**
429          *  load api $templatename for $type and replace $data array
430          */
431         function api_apply_template($templatename, $type, $data){
432
433                 $a = get_app();
434
435                 switch($type){
436                         case "atom":
437                         case "rss":
438                         case "xml":
439                                 $data = array_xmlify($data);
440                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
441                                 $ret = replace_macros($tpl, $data);
442                                 break;
443                         case "json":
444                                 $ret = $data;
445                                 break;
446                 }
447                 return $ret;
448         }
449         
450         /**
451          ** TWITTER API
452          */
453         
454         /**
455          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
456          * returns a 401 status code and an error message if not. 
457          * http://developer.twitter.com/doc/get/account/verify_credentials
458          */
459         function api_account_verify_credentials(&$a, $type){
460                 if (local_user()===false) return false;
461                 $user_info = api_get_user($a);
462                 
463                 return api_apply_template("user", $type, array('$user' => $user_info));
464
465         }
466         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
467                 
468
469         /**
470          * get data from $_POST or $_GET
471          */
472         function requestdata($k){
473                 if (isset($_POST[$k])){
474                         return $_POST[$k];
475                 }
476                 if (isset($_GET[$k])){
477                         return $_GET[$k];
478                 }
479                 return null;
480         }
481
482 /*Waitman Gobble Mod*/
483         function api_statuses_mediap(&$a, $type) {
484                 if (local_user()===false) {
485                         logger('api_statuses_update: no user');
486                         return false;
487                 }
488                 $user_info = api_get_user($a);
489
490                 $_REQUEST['type'] = 'wall';
491                 $_REQUEST['profile_uid'] = local_user();
492                 $_REQUEST['api_source'] = true;
493                 $txt = urldecode(requestdata('status'));
494
495                 require_once('library/HTMLPurifier.auto.php');
496                 require_once('include/html2bbcode.php');
497
498                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
499                         $txt = html2bb_video($txt);
500                         $config = HTMLPurifier_Config::createDefault();
501                         $config->set('Cache.DefinitionImpl', null);
502                         $purifier = new HTMLPurifier($config);
503                         $txt = $purifier->purify($txt);
504                 }
505                 $txt = html2bbcode($txt);
506                 
507                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
508                 
509                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
510                 require_once('mod/wall_upload.php');
511                 $bebop = wall_upload_post($a);
512                 
513                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
514                 $_REQUEST['body']=$txt."\n\n".$bebop;
515                 require_once('mod/item.php');
516                 item_post($a);
517
518                 // this should output the last post (the one we just posted).
519                 return api_status_show($a,$type);
520         }
521         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
522 /*Waitman Gobble Mod*/
523
524
525         function api_statuses_update(&$a, $type) {
526                 if (local_user()===false) {
527                         logger('api_statuses_update: no user');
528                         return false;
529                 }
530                 $user_info = api_get_user($a);
531
532                 // convert $_POST array items to the form we use for web posts.
533
534                 // logger('api_post: ' . print_r($_POST,true));
535
536                 if(requestdata('htmlstatus')) {
537                         require_once('library/HTMLPurifier.auto.php');
538                         require_once('include/html2bbcode.php');
539
540                         $txt = requestdata('htmlstatus');
541                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
542
543                                 $txt = html2bb_video($txt);
544
545                                 $config = HTMLPurifier_Config::createDefault();
546                                 $config->set('Cache.DefinitionImpl', null);
547
548
549                                 $purifier = new HTMLPurifier($config);
550                                 $txt = $purifier->purify($txt);
551
552                                 $_REQUEST['body'] = html2bbcode($txt);
553                         }
554
555                 }
556                 else
557                         $_REQUEST['body'] = urldecode(requestdata('status'));
558
559                 $parent = requestdata('in_reply_to_status_id');
560                 if(ctype_digit($parent))
561                         $_REQUEST['parent'] = $parent;
562                 else
563                         $_REQUEST['parent_uri'] = $parent;
564
565                 if(requestdata('lat') && requestdata('long'))
566                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
567                 $_REQUEST['profile_uid'] = local_user();
568
569                 if($parent)
570                         $_REQUEST['type'] = 'net-comment';
571                 else {
572                         $_REQUEST['type'] = 'wall';
573                         if(x($_FILES,'media')) {
574                                 // upload the image if we have one
575                                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
576                                 require_once('mod/wall_upload.php');
577                                 $media = wall_upload_post($a);
578                                 if(strlen($media)>0)
579                                         $_REQUEST['body'] .= "\n\n".$media;
580                         }
581                 }
582
583                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
584
585                 $_REQUEST['api_source'] = true;
586
587                 // call out normal post function
588
589                 require_once('mod/item.php');
590                 item_post($a);  
591
592                 // this should output the last post (the one we just posted).
593                 return api_status_show($a,$type);
594         }
595         api_register_func('api/statuses/update','api_statuses_update', true);
596
597
598         function api_status_show(&$a, $type){
599                 $user_info = api_get_user($a);
600                 // get last public wall message
601                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
602                                 FROM `item`, `contact`,
603                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
604                                 WHERE `item`.`contact-id` = %d
605                                         AND `i`.`id` = `item`.`parent`
606                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
607                                         AND `type`!='activity'
608                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
609                                 ORDER BY `created` DESC 
610                                 LIMIT 1",
611                                 intval($user_info['id'])
612                 );
613
614                 if (count($lastwall)>0){
615                         $lastwall = $lastwall[0];
616                         
617                         $in_reply_to_status_id = '';
618                         $in_reply_to_user_id = '';
619                         $in_reply_to_screen_name = '';
620                         if ($lastwall['parent']!=$lastwall['id']) {
621                                 $in_reply_to_status_id=$lastwall['parent'];
622                                 $in_reply_to_user_id = $lastwall['reply_uid'];
623                                 $in_reply_to_screen_name = $lastwall['reply_author'];
624                         }  
625                         $status_info = array(
626                                 'text' => html2plain(bbcode($lastwall['body']), 0),
627                                 'truncated' => false,
628                                 'created_at' => api_date($lastwall['created']),
629                                 'in_reply_to_status_id' => $in_reply_to_status_id,
630                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
631                                 'id' => $lastwall['contact-id'],
632                                 'in_reply_to_user_id' => $in_reply_to_user_id,
633                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
634                                 'geo' => '',
635                                 'favorited' => false,
636                                 'coordinates' => $lastwall['coord'],
637                                 'place' => $lastwall['location'],
638                                 'contributors' => ''                                    
639                         );
640                         $status_info['user'] = $user_info;
641                 }
642                 return  api_apply_template("status", $type, array('$status' => $status_info));
643                 
644         }
645
646
647
648
649                 
650         /**
651          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
652          * The author's most recent status will be returned inline.
653          * http://developer.twitter.com/doc/get/users/show
654          */
655         function api_users_show(&$a, $type){
656                 $user_info = api_get_user($a);
657                 // get last public wall message
658                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
659                                 FROM `item`, `contact`,
660                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
661                                 WHERE `item`.`contact-id` = %d
662                                         AND `i`.`id` = `item`.`parent`
663                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
664                                         AND `type`!='activity'
665                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
666                                 ORDER BY `created` DESC 
667                                 LIMIT 1",
668                                 intval($user_info['id'])
669                 );
670
671                 if (count($lastwall)>0){
672                         $lastwall = $lastwall[0];
673                         
674                         $in_reply_to_status_id = '';
675                         $in_reply_to_user_id = '';
676                         $in_reply_to_screen_name = '';
677                         if ($lastwall['parent']!=$lastwall['id']) {
678                                 $in_reply_to_status_id=$lastwall['parent'];
679                                 $in_reply_to_user_id = $lastwall['reply_uid'];
680                                 $in_reply_to_screen_name = $lastwall['reply_author'];
681                         }  
682                         $user_info['status'] = array(
683                                 'created_at' => api_date($lastwall['created']),
684                                 'id' => $lastwall['contact-id'],
685                                 'text' => html2plain(bbcode($lastwall['body']), 0),
686                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
687                                 'truncated' => false,
688                                 'in_reply_to_status_id' => $in_reply_to_status_id,
689                                 'in_reply_to_user_id' => $in_reply_to_user_id,
690                                 'favorited' => false,
691                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
692                                 'geo' => '',
693                                 'coordinates' => $lastwall['coord'],
694                                 'place' => $lastwall['location'],
695                                 'contributors' => ''
696                         );
697                 }
698                 return  api_apply_template("user", $type, array('$user' => $user_info));
699
700         }
701         api_register_func('api/users/show','api_users_show');
702
703         /**
704          *
705          * http://developer.twitter.com/doc/get/statuses/home_timeline
706          *
707          * TODO: Optional parameters
708          * TODO: Add reply info
709          */
710         function api_statuses_home_timeline(&$a, $type){
711                 if (local_user()===false) return false;
712
713                 $user_info = api_get_user($a);
714                 // get last newtork messages
715
716
717                 // params
718                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
719                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
720                 if ($page<0) $page=0;
721                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
722                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
723                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
724                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
725
726                 $start = $page*$count;
727
728                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
729
730                 $sql_extra = '';
731                 if ($max_id > 0)
732                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
733                 if ($exclude_replies > 0)
734                         $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
735
736                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
737                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
738                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
739                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
740                         FROM `item`, `contact`
741                         WHERE `item`.`uid` = %d
742                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
743                         AND `contact`.`id` = `item`.`contact-id`
744                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
745                         $sql_extra
746                         AND `item`.`id`>%d
747                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
748                         intval($user_info['uid']),
749                         intval($since_id),
750                         intval($start), intval($count)
751                 );
752
753                 $ret = api_format_items($r,$user_info);
754
755
756                 $data = array('$statuses' => $ret);
757                 switch($type){
758                         case "atom":
759                         case "rss":
760                                 $data = api_rss_extra($a, $data, $user_info);
761                                 break;
762                         case "as":
763                                 $as = api_format_as($a, $ret, $user_info);
764                                 $as['title'] = $a->config['sitename']." Home Timeline";
765                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
766                                 return($as);
767                                 break;
768                 }
769
770                 return  api_apply_template("timeline", $type, $data);
771         }
772         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
773         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
774
775         function api_statuses_public_timeline(&$a, $type){
776                 if (local_user()===false) return false;
777
778                 $user_info = api_get_user($a);
779                 // get last newtork messages
780
781
782                 // params
783                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
784                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
785                 if ($page<0) $page=0;
786                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
787                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
788                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
789
790                 $start = $page*$count;
791
792                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
793
794                 if ($max_id > 0)
795                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
796
797                 /*$r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
798                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
799                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
800                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
801                         FROM `item`, `contact`
802                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
803                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = '' 
804                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' 
805                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
806                         AND `contact`.`id` = `item`.`contact-id`
807                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
808                         $sql_extra
809                         AND `item`.`id`>%d
810                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
811                         intval($since_id),
812                         intval($start), intval($count)
813                 );*/
814                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
815                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
816                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
817                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
818                         `user`.`nickname`, `user`.`hidewall`
819                         FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
820                         LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
821                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
822                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
823                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
824                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
825                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
826                         $sql_extra
827                         AND `item`.`id`>%d
828                         ORDER BY `received` DESC LIMIT %d, %d ",
829                         intval($since_id),
830                         intval($start),
831                         intval($count));
832
833                 $ret = api_format_items($r,$user_info);
834
835
836                 $data = array('$statuses' => $ret);
837                 switch($type){
838                         case "atom":
839                         case "rss":
840                                 $data = api_rss_extra($a, $data, $user_info);
841                                 break;
842                         case "as":
843                                 $as = api_format_as($a, $ret, $user_info);
844                                 $as['title'] = $a->config['sitename']." Public Timeline";
845                                 $as['link']['url'] = $a->get_baseurl()."/";
846                                 return($as);
847                                 break;
848                 }
849
850                 return  api_apply_template("timeline", $type, $data);
851         }
852         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
853
854         /**
855          * 
856          */
857         function api_statuses_show(&$a, $type){
858                 if (local_user()===false) return false;
859
860                 $user_info = api_get_user($a);
861
862                 // params
863                 $id = intval($a->argv[3]);
864
865                 logger('API: api_statuses_show: '.$id);
866
867                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
868                 $conversation = (x($_REQUEST,'conversation')?1:0);
869
870                 $sql_extra = '';
871                 if ($conversation)
872                         $sql_extra .= " AND `item`.`parent` = %d  ORDER BY `received` ASC ";
873                 else
874                         $sql_extra .= " AND `item`.`id` = %d";
875
876                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
877                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
878                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
879                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
880                         FROM `item`, `contact`
881                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
882                         AND `contact`.`id` = `item`.`contact-id`
883                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
884                         $sql_extra",
885                         intval($id)
886                 );
887
888                 $ret = api_format_items($r,$user_info);
889
890                 if ($conversation) {
891                         $data = array('$statuses' => $ret);
892                         return api_apply_template("timeline", $type, $data);
893                 } else {
894                         $data = array('$status' => $ret[0]);
895                         /*switch($type){
896                                 case "atom":
897                                 case "rss":
898                                         $data = api_rss_extra($a, $data, $user_info);
899                         }*/
900                         return  api_apply_template("status", $type, $data);
901                 }
902         }
903         api_register_func('api/statuses/show','api_statuses_show', true);
904
905
906         /**
907          * 
908          */
909         function api_statuses_repeat(&$a, $type){
910                 if (local_user()===false) return false;
911
912                 $user_info = api_get_user($a);
913
914                 // params
915                 $id = intval($a->argv[3]);
916
917                 logger('API: api_statuses_repeat: '.$id);
918
919                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
920
921                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
922                         `contact`.`name`, `contact`.`photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
923                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
924                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
925                         FROM `item`, `contact`
926                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
927                         AND `contact`.`id` = `item`.`contact-id`
928                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
929                         $sql_extra
930                         AND `item`.`id`=%d",
931                         intval($id)
932                 );
933
934                 if ($r[0]['body'] != "") {
935                         $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
936                         $_REQUEST['profile_uid'] = local_user();
937                         $_REQUEST['type'] = 'wall';
938                         $_REQUEST['api_source'] = true;
939
940                         require_once('mod/item.php');
941                         item_post($a);
942                 }
943
944                 if ($type == 'xml')
945                         $ok = "true";
946                 else
947                         $ok = "ok";
948
949                 return api_apply_template('test', $type, array('$ok' => $ok));
950         }
951         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
952
953         /**
954          * 
955          */
956         function api_statuses_destroy(&$a, $type){
957                 if (local_user()===false) return false;
958
959                 $user_info = api_get_user($a);
960
961                 // params
962                 $id = intval($a->argv[3]);
963
964                 logger('API: api_statuses_destroy: '.$id);
965
966                 require_once('include/items.php');
967                 drop_item($id, false);
968
969                 if ($type == 'xml')
970                         $ok = "true";
971                 else
972                         $ok = "ok";
973
974                 return api_apply_template('test', $type, array('$ok' => $ok));
975         }
976         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
977
978         /**
979          * 
980          * http://developer.twitter.com/doc/get/statuses/mentions
981          * 
982          */
983         function api_statuses_mentions(&$a, $type){
984                 if (local_user()===false) return false;
985                                 
986                 $user_info = api_get_user($a);
987                 // get last newtork messages
988
989
990                 // params
991                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
992                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
993                 if ($page<0) $page=0;
994                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
995                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
996                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
997
998                 $start = $page*$count;
999
1000                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
1001
1002                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
1003                 $myurl = substr($myurl,strpos($myurl,'://')+3);
1004                 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
1005                 $diasp_url = str_replace('/profile/','/u/',$myurl);
1006
1007                 if (get_config('system','use_fulltext_engine'))
1008                         $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where (MATCH(`author-link`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(`tag`) AGAINST ('".'"%s"'."' in boolean mode) or MATCH(tag) AGAINST ('".'"%s"'."' in boolean mode))) ",
1009                                 dbesc(protect_sprintf($myurl)),
1010                                 dbesc(protect_sprintf($myurl)),
1011                                 dbesc(protect_sprintf($diasp_url))
1012                         );
1013                 else
1014                         $sql_extra .= sprintf(" AND `item`.`parent` IN (SELECT distinct(`parent`) from item where ( `author-link` like '%s' or `tag` like '%s' or tag like '%s' )) ",
1015                                 dbesc(protect_sprintf('%' . $myurl)),
1016                                 dbesc(protect_sprintf('%' . $myurl . ']%')),
1017                                 dbesc(protect_sprintf('%' . $diasp_url . ']%'))
1018                         );
1019
1020                 if ($max_id > 0)
1021                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1022
1023                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1024                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1025                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1026                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1027                         FROM `item`, `contact`
1028                         WHERE `item`.`uid` = %d
1029                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1030                         AND `contact`.`id` = `item`.`contact-id`
1031                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1032                         $sql_extra
1033                         AND `item`.`id`>%d
1034                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1035                         intval($user_info['uid']),
1036                         intval($since_id),
1037                         intval($start), intval($count)
1038                 );
1039
1040                 $ret = api_format_items($r,$user_info);
1041
1042
1043                 $data = array('$statuses' => $ret);
1044                 switch($type){
1045                         case "atom":
1046                         case "rss":
1047                                 $data = api_rss_extra($a, $data, $user_info);
1048                                 break;
1049                         case "as":
1050                                 $as = api_format_as($a, $ret, $user_info);
1051                                 $as["title"] = $a->config['sitename']." Mentions";
1052                                 $as['link']['url'] = $a->get_baseurl()."/";
1053                                 return($as);
1054                                 break;
1055                 }
1056
1057                 return  api_apply_template("timeline", $type, $data);
1058         }
1059         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1060         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1061
1062
1063         function api_statuses_user_timeline(&$a, $type){
1064                 if (local_user()===false) return false;
1065                 
1066                 $user_info = api_get_user($a);
1067                 // get last newtork messages
1068
1069
1070                 logger("api_statuses_user_timeline: local_user: ". local_user() .
1071                            "\nuser_info: ".print_r($user_info, true) .
1072                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1073                            LOGGER_DEBUG);
1074
1075                 // params
1076                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1077                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1078                 if ($page<0) $page=0;
1079                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1080                 $exclude_replies = (x($_REQUEST,'exclude_replies')?1:0);
1081                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1082                 
1083                 $start = $page*$count;
1084
1085                 $sql_extra = '';
1086                 if ($user_info['self']==1) $sql_extra .= " AND `item`.`wall` = 1 ";
1087                 if ($exclude_replies > 0)  $sql_extra .= ' AND `item`.`parent` = `item`.`id`';
1088
1089                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1090                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1091                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1092                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1093                         FROM `item`, `contact`
1094                         WHERE `item`.`uid` = %d
1095                         AND `item`.`contact-id` = %d
1096                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1097                         AND `contact`.`id` = `item`.`contact-id`
1098                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1099                         $sql_extra
1100                         AND `item`.`id`>%d
1101                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1102                         intval(local_user()),
1103                         intval($user_info['id']),
1104                         intval($since_id),
1105                         intval($start), intval($count)
1106                 );
1107
1108                 $ret = api_format_items($r,$user_info);
1109
1110
1111                 $data = array('$statuses' => $ret);
1112                 switch($type){
1113                         case "atom":
1114                         case "rss":
1115                                 $data = api_rss_extra($a, $data, $user_info);
1116                 }
1117
1118                 return  api_apply_template("timeline", $type, $data);
1119         }
1120
1121         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1122
1123
1124         function api_favorites(&$a, $type){
1125                 if (local_user()===false) return false;
1126
1127                 $user_info = api_get_user($a);
1128                 // in friendica starred item are private
1129                 // return favorites only for self
1130                 logger('api_favorites: self:' . $user_info['self']);
1131
1132                 if ($user_info['self']==0) {
1133                         $ret = array();
1134                 } else {
1135
1136
1137                         // params
1138                         $count = (x($_GET,'count')?$_GET['count']:20);
1139                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1140                         if ($page<0) $page=0;
1141
1142                         $start = $page*$count;
1143
1144                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1145                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1146                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1147                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1148                                 FROM `item`, `contact`
1149                                 WHERE `item`.`uid` = %d
1150                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1151                                 AND `item`.`starred` = 1
1152                                 AND `contact`.`id` = `item`.`contact-id`
1153                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1154                                 $sql_extra
1155                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1156                                 intval($user_info['uid']),
1157                                 intval($start), intval($count)
1158                         );
1159
1160                         $ret = api_format_items($r,$user_info);
1161
1162                 }
1163
1164                 $data = array('$statuses' => $ret);
1165                 switch($type){
1166                         case "atom":
1167                         case "rss":
1168                                 $data = api_rss_extra($a, $data, $user_info);
1169                 }
1170
1171                 return  api_apply_template("timeline", $type, $data);
1172         }
1173
1174         api_register_func('api/favorites','api_favorites', true);
1175
1176         function api_format_as($a, $ret, $user_info) {
1177
1178                 $as = array();
1179                 $as['title'] = $a->config['sitename']." Public Timeline";
1180                 $items = array();
1181                 foreach ($ret as $item) {
1182                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1183                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1184                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1185                         $avatar[0]["rel"] = "avatar";
1186                         $avatar[0]["type"] = "";
1187                         $avatar[0]["width"] = 96;
1188                         $avatar[0]["height"] = 96;
1189                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1190                         $avatar[1]["rel"] = "avatar";
1191                         $avatar[1]["type"] = "";
1192                         $avatar[1]["width"] = 48;
1193                         $avatar[1]["height"] = 48;
1194                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1195                         $avatar[2]["rel"] = "avatar";
1196                         $avatar[2]["type"] = "";
1197                         $avatar[2]["width"] = 24;
1198                         $avatar[2]["height"] = 24;
1199                         $singleitem["actor"]["avatarLinks"] = $avatar;
1200
1201                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1202                         $singleitem["actor"]["image"]["rel"] = "avatar";
1203                         $singleitem["actor"]["image"]["type"] = "";
1204                         $singleitem["actor"]["image"]["width"] = 96;
1205                         $singleitem["actor"]["image"]["height"] = 96;
1206                         $singleitem["actor"]["type"] = "person";
1207                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1208                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1209                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1210                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1211                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1212                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1213                         $singleitem["actor"]["contact"]["addresses"] = "";
1214
1215                         $singleitem["body"] = $item["text"];
1216                         $singleitem["object"]["displayName"] = $item["text"];
1217                         $singleitem["object"]["id"] = $item["url"];
1218                         $singleitem["object"]["type"] = "note";
1219                         $singleitem["object"]["url"] = $item["url"];
1220                         //$singleitem["context"] =;
1221                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1222                         $singleitem["provider"]["objectType"] = "service";
1223                         $singleitem["provider"]["displayName"] = "Test";
1224                         $singleitem["provider"]["url"] = "http://test.tld";
1225                         $singleitem["title"] = $item["text"];
1226                         $singleitem["verb"] = "post";
1227                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1228                                 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1229                                 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1230                                 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1231                                 //$singleitem["original"] = $item;
1232                                 $items[] = $singleitem;
1233                 }
1234                 $as['items'] = $items;
1235                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1236                 $as['link']['rel'] = "alternate";
1237                 $as['link']['type'] = "text/html";
1238                 return($as);
1239         }
1240
1241         function api_format_messages($item, $recipient, $sender) {
1242                 // standard meta information
1243                 $ret=Array(
1244                                 'id'                    => $item['id'],
1245                                 'created_at'            => api_date($item['created']),
1246                                 'sender_id'             => $sender['id'] ,
1247                                 'sender_screen_name'    => $sender['screen_name'],
1248                                 'sender'                => $sender,
1249                                 'recipient_id'          => $recipient['id'],
1250                                 'recipient_screen_name' => $recipient['screen_name'],
1251                                 'recipient'             => $recipient,
1252                 );
1253
1254                 //don't send title to regular StatusNET requests to avoid confusing these apps
1255                 if (x($_GET, 'getText')) {
1256                         $ret['title'] = $item['title'] ;
1257                         if ($_GET["getText"] == "html") {
1258                                 $ret['text'] = bbcode($item['body']);
1259                         }
1260                         elseif ($_GET["getText"] == "plain") {
1261                                 $ret['text'] = html2plain(bbcode($item['body']), 0);
1262                         }
1263                 }
1264                 else {
1265                         $ret['text'] = $item['title']."\n".html2plain(bbcode($item['body']), 0);
1266                 }
1267                 if (isset($_GET["getUserObjects"]) && $_GET["getUserObjects"] == "false") {
1268                         unset($ret['sender']);
1269                         unset($ret['recipient']);
1270                 }
1271
1272                 return $ret;
1273         }
1274
1275         function api_format_items($r,$user_info) {
1276
1277                 //logger('api_format_items: ' . print_r($r,true));
1278
1279                 //logger('api_format_items: ' . print_r($user_info,true));
1280
1281                 $a = get_app();
1282                 $ret = Array();
1283
1284                 foreach($r as $item) {
1285                         localize_item($item);
1286                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
1287
1288                         if ($item['parent']!=$item['id']) {
1289                                 $r = q("select id from item where parent=%s and id<%s order by id desc limit 1",
1290                                         intval($item['parent']), intval($item['id']));
1291                                 if ($r)
1292                                         $in_reply_to_status_id = $r[0]['id'];
1293                                 else
1294                                         $in_reply_to_status_id = $item['parent'];
1295
1296                                 $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact
1297                                         where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id));
1298
1299                                 $in_reply_to_screen_name = $r[0]['author-name'];
1300                                 $in_reply_to_user_id = $r[0]['contact-id'];
1301
1302                         } else {
1303                                 $in_reply_to_screen_name = '';
1304                                 $in_reply_to_user_id = 0;
1305                                 $in_reply_to_status_id = 0;
1306                         }
1307
1308                         // Workaround for ostatus messages where the title is identically to the body
1309                         $statusbody = trim(html2plain(bbcode($item['body']), 0));
1310                         $statustitle = trim($item['title']);
1311
1312                         if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1313                                 $statustext = trim($statusbody);
1314                         else
1315                                 $statustext = trim($statustitle."\n\n".$statusbody);
1316
1317                         if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1318                                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1319
1320                         $status = array(
1321                                 'text'          => $statustext,
1322                                 'truncated' => False,
1323                                 'created_at'=> api_date($item['created']),
1324                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1325                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
1326                                 'id'            => intval($item['id']),
1327                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1328                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1329                                 'geo' => '',
1330                                 'favorited' => $item['starred'] ? true : false,
1331                                 'user' =>  $status_user ,
1332                                 'statusnet_html'                => trim(bbcode($item['body'])),
1333                                 'statusnet_conversation_id'     => $item['parent'],
1334                         );
1335
1336                         // Seesmic doesn't like the following content
1337                         if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1338                                 $status2 = array(
1339                                         'updated'   => api_date($item['edited']),
1340                                         'published' => api_date($item['created']),
1341                                         'message_id' => $item['uri'],
1342                                         'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
1343                                         'coordinates' => $item['coord'],
1344                                         'place' => $item['location'],
1345                                         'contributors' => '',
1346                                         'annotations'  => '',
1347                                         'entities'  => '',
1348                                         'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1349                                         'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1350                                         'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1351                                         'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1352                                 );
1353
1354                                 $status = array_merge($status, $status2);
1355                         }
1356
1357                         $ret[]=$status;
1358                 };
1359                 return $ret;
1360         }
1361
1362
1363         function api_account_rate_limit_status(&$a,$type) {
1364
1365                 $hash = array(
1366                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
1367                           'remaining_hits' => (string) 150,
1368                           'hourly_limit' => (string) 150,
1369                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1370                 );
1371                 if ($type == "xml")
1372                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1373
1374                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1375
1376         }
1377         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1378
1379         function api_help_test(&$a,$type) {
1380
1381                 if ($type == 'xml')
1382                         $ok = "true";
1383                 else
1384                         $ok = "ok";
1385
1386                 return api_apply_template('test', $type, array('$ok' => $ok));
1387
1388         }
1389         api_register_func('api/help/test','api_help_test',true);
1390
1391         /**
1392          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
1393          *  This function is deprecated by Twitter
1394          *  returns: json, xml 
1395          **/
1396         function api_statuses_f(&$a, $type, $qtype) {
1397                 if (local_user()===false) return false;
1398                 $user_info = api_get_user($a);
1399                 
1400                 
1401                 // friends and followers only for self
1402                 if ($user_info['self']==0){
1403                         return false;
1404                 }
1405                 
1406                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1407                         /* this is to stop Hotot to load friends multiple times
1408                         *  I'm not sure if I'm missing return something or
1409                         *  is a bug in hotot. Workaround, meantime
1410                         */
1411                         
1412                         /*$ret=Array();
1413                         return array('$users' => $ret);*/
1414                         return false;
1415                 }
1416                 
1417                 if($qtype == 'friends')
1418                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1419                 if($qtype == 'followers')
1420                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1421  
1422                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1423                         intval(local_user())
1424                 );
1425
1426                 $ret = array();
1427                 foreach($r as $cid){
1428                         $ret[] = api_get_user($a, $cid['id']);
1429                 }
1430
1431                 
1432                 return array('$users' => $ret);
1433
1434         }
1435         function api_statuses_friends(&$a, $type){
1436                 $data =  api_statuses_f($a,$type,"friends");
1437                 if ($data===false) return false;
1438                 return  api_apply_template("friends", $type, $data);
1439         }
1440         function api_statuses_followers(&$a, $type){
1441                 $data = api_statuses_f($a,$type,"followers");
1442                 if ($data===false) return false;
1443                 return  api_apply_template("friends", $type, $data);
1444         }
1445         api_register_func('api/statuses/friends','api_statuses_friends',true);
1446         api_register_func('api/statuses/followers','api_statuses_followers',true);
1447
1448
1449
1450
1451
1452
1453         function api_statusnet_config(&$a,$type) {
1454                 $name = $a->config['sitename'];
1455                 $server = $a->get_hostname();
1456                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1457                 $email = $a->config['admin_email'];
1458                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1459                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1460                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1461                 if($a->config['api_import_size'])
1462                         $texlimit = string($a->config['api_import_size']);
1463                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1464                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1465
1466                 $config = array(
1467                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1468                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1469                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1470                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1471                                 'shorturllength' => '30',
1472         'friendica' => array(
1473                              'FRIENDICA_PLATFORM' => FRIENDICA_PLATFORM,
1474                              'FRIENDICA_VERSION' => FRIENDICA_VERSION,
1475                              'DFRN_PROTOCOL_VERSION' => DFRN_PROTOCOL_VERSION,
1476                              'DB_UPDATE_VERSION' => DB_UPDATE_VERSION
1477                              )
1478                         ),
1479                 );  
1480
1481                 return api_apply_template('config', $type, array('$config' => $config));
1482
1483         }
1484         api_register_func('api/statusnet/config','api_statusnet_config',false);
1485
1486         function api_statusnet_version(&$a,$type) {
1487
1488                 // liar
1489
1490                 if($type === 'xml') {
1491                         header("Content-type: application/xml");
1492                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1493                         killme();
1494                 }
1495                 elseif($type === 'json') {
1496                         header("Content-type: application/json");
1497                         echo '"0.9.7"';
1498                         killme();
1499                 }
1500         }
1501         api_register_func('api/statusnet/version','api_statusnet_version',false);
1502
1503
1504         function api_ff_ids(&$a,$type,$qtype) {
1505                 if(! local_user())
1506                         return false;
1507
1508                 if($qtype == 'friends')
1509                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1510                 if($qtype == 'followers')
1511                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1512  
1513
1514                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1515                         intval(local_user())
1516                 );
1517
1518                 if(is_array($r)) {
1519                         if($type === 'xml') {
1520                                 header("Content-type: application/xml");
1521                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1522                                 foreach($r as $rr)
1523                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1524                                 echo '</ids>' . "\r\n";
1525                                 killme();
1526                         }
1527                         elseif($type === 'json') {
1528                                 $ret = array();
1529                                 header("Content-type: application/json");
1530                                 foreach($r as $rr) $ret[] = $rr['id'];
1531                                 echo json_encode($ret);
1532                                 killme();
1533                         }
1534                 }
1535         }
1536
1537         function api_friends_ids(&$a,$type) {
1538                 api_ff_ids($a,$type,'friends');
1539         }
1540         function api_followers_ids(&$a,$type) {
1541                 api_ff_ids($a,$type,'followers');
1542         }
1543         api_register_func('api/friends/ids','api_friends_ids',true);
1544         api_register_func('api/followers/ids','api_followers_ids',true);
1545
1546
1547         function api_direct_messages_new(&$a, $type) {
1548                 if (local_user()===false) return false;
1549                 
1550                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1551
1552                 $sender = api_get_user($a);
1553                 
1554                 require_once("include/message.php");
1555
1556                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1557                                 intval(local_user()),
1558                                 dbesc($_POST['screen_name']));
1559
1560                 $recipient = api_get_user($a, $r[0]['id']);                     
1561                 $replyto = '';
1562                 $sub     = '';
1563                 if (x($_REQUEST,'replyto')) {
1564                         $r = q('SELECT `parent-uri`, `title` FROM `mail` WHERE `uid`=%d AND `id`=%d',
1565                                         intval(local_user()),
1566                                         intval($_REQUEST['replyto']));
1567                         $replyto = $r[0]['parent-uri'];
1568                         $sub     = $r[0]['title'];
1569                 }
1570                 else {
1571                         if (x($_REQUEST,'title')) {
1572                                 $sub = $_REQUEST['title'];
1573                         }
1574                         else {
1575                                 $sub = ((strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1576                         }
1577                 }
1578
1579                 $id = send_message($recipient['id'], $_POST['text'], $sub, $replyto);
1580
1581                 if ($id>-1) {
1582                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1583                         $ret = api_format_messages($r[0], $recipient, $sender);
1584                 
1585                 } else {
1586                         $ret = array("error"=>$id);     
1587                 }
1588                 
1589                 $data = Array('$messages'=>$ret);
1590                 
1591                 switch($type){
1592                         case "atom":
1593                         case "rss":
1594                                 $data = api_rss_extra($a, $data, $user_info);
1595                 }
1596                                 
1597                 return  api_apply_template("direct_messages", $type, $data);
1598                                 
1599         }
1600         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1601
1602         function api_direct_messages_box(&$a, $type, $box) {
1603                 if (local_user()===false) return false;
1604                 
1605                 $user_info = api_get_user($a);
1606                 
1607                 // params
1608                 $count = (x($_GET,'count')?$_GET['count']:20);
1609                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1610                 if ($page<0) $page=0;
1611                 
1612                 $start = $page*$count;
1613                 
1614                 $profile_url = $a->get_baseurl() . '/profile/' . $a->user['nickname'];
1615                 if ($box=="sentbox") {
1616                         $sql_extra = "`from-url`='".dbesc( $profile_url )."'";
1617                 }
1618                 elseif ($box=="conversation") {
1619                         $sql_extra = "`parent-uri`='".dbesc( $_GET["uri"] )  ."'";
1620                 }
1621                 elseif ($box=="all") {
1622                         $sql_extra = "true";
1623                 }
1624                 elseif ($box=="inbox") {
1625                         $sql_extra = "`from-url`!='".dbesc( $profile_url )."'";
1626                 }
1627                 
1628                 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1629                                 intval(local_user()),
1630                                 intval($start), intval($count)
1631                 );
1632                 
1633                 $ret = Array();
1634                 foreach($r as $item) {
1635                         if ($box == "inbox" || $item['from-url'] != $profile_url){
1636                                 $recipient = $user_info;
1637                                 $sender = api_get_user($a,$item['contact-id']);
1638                         }
1639                         elseif ($box == "sentbox" || $item['from-url'] != $profile_url){
1640                                 $recipient = api_get_user($a,$item['contact-id']);
1641                                 $sender = $user_info;
1642                         }
1643
1644                         $ret[]=api_format_messages($item, $recipient, $sender);
1645                 }
1646                 
1647
1648                 $data = array('$messages' => $ret);
1649                 switch($type){
1650                         case "atom":
1651                         case "rss":
1652                                 $data = api_rss_extra($a, $data, $user_info);
1653                 }
1654                                 
1655                 return  api_apply_template("direct_messages", $type, $data);
1656                 
1657         }
1658
1659         function api_direct_messages_sentbox(&$a, $type){
1660                 return api_direct_messages_box($a, $type, "sentbox");
1661         }
1662         function api_direct_messages_inbox(&$a, $type){
1663                 return api_direct_messages_box($a, $type, "inbox");
1664         }
1665         function api_direct_messages_all(&$a, $type){
1666                 return api_direct_messages_box($a, $type, "all");
1667         }
1668         function api_direct_messages_conversation(&$a, $type){
1669                 return api_direct_messages_box($a, $type, "conversation");
1670         }
1671         api_register_func('api/direct_messages/conversation','api_direct_messages_conversation',true);
1672         api_register_func('api/direct_messages/all','api_direct_messages_all',true);
1673         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1674         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1675
1676
1677
1678         function api_oauth_request_token(&$a, $type){
1679                 try{
1680                         $oauth = new FKOAuth1();
1681                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1682                 }catch(Exception $e){
1683                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1684                 }
1685                 echo $r;
1686                 killme();       
1687         }
1688         function api_oauth_access_token(&$a, $type){
1689                 try{
1690                         $oauth = new FKOAuth1();
1691                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1692                 }catch(Exception $e){
1693                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1694                 }
1695                 echo $r;
1696                 killme();                       
1697         }
1698
1699         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1700         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1701
1702 /*
1703 Not implemented by now:
1704 favorites
1705 favorites/create
1706 favorites/destroy
1707 statuses/retweets_of_me
1708 friendships/create
1709 friendships/destroy
1710 friendships/exists
1711 friendships/show
1712 account/update_location
1713 account/update_profile_background_image
1714 account/update_profile_image
1715 blocks/create
1716 blocks/destroy
1717
1718 Not implemented in status.net:
1719 statuses/retweeted_to_me
1720 statuses/retweeted_by_me
1721 direct_messages/destroy
1722 account/end_session
1723 account/update_delivery_device
1724 notifications/follow
1725 notifications/leave
1726 blocks/exists
1727 blocks/blocking
1728 */
1729