]> git.mxchange.org Git - friendica.git/blob - include/api.php
better handling of dead contacts
[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);
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                 if(requestdata('parent'))
569                         $_REQUEST['type'] = 'net-comment';
570                 else {
571                         $_REQUEST['type'] = 'wall';
572                         if(x($_FILES,'media')) {
573                                 // upload the image if we have one
574                                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
575                                 require_once('mod/wall_upload.php');
576                                 $media = wall_upload_post($a);
577                                 if(strlen($media)>0)
578                                         $_REQUEST['body'] .= "\n\n".$media;
579                                 }
580                 }
581
582                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
583
584                 $_REQUEST['api_source'] = true;
585
586                 // call out normal post function
587
588                 require_once('mod/item.php');
589                 item_post($a);  
590
591                 // this should output the last post (the one we just posted).
592                 return api_status_show($a,$type);
593         }
594         api_register_func('api/statuses/update','api_statuses_update', true);
595
596
597         function api_status_show(&$a, $type){
598                 $user_info = api_get_user($a);
599                 // get last public wall message
600                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
601                                 FROM `item`, `contact`,
602                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
603                                 WHERE `item`.`contact-id` = %d
604                                         AND `i`.`id` = `item`.`parent`
605                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
606                                         AND `type`!='activity'
607                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
608                                 ORDER BY `created` DESC 
609                                 LIMIT 1",
610                                 intval($user_info['id'])
611                 );
612
613                 if (count($lastwall)>0){
614                         $lastwall = $lastwall[0];
615                         
616                         $in_reply_to_status_id = '';
617                         $in_reply_to_user_id = '';
618                         $in_reply_to_screen_name = '';
619                         if ($lastwall['parent']!=$lastwall['id']) {
620                                 $in_reply_to_status_id=$lastwall['parent'];
621                                 $in_reply_to_user_id = $lastwall['reply_uid'];
622                                 $in_reply_to_screen_name = $lastwall['reply_author'];
623                         }  
624                         $status_info = array(
625                                 'text' => html2plain(bbcode($lastwall['body']), 0),
626                                 'truncated' => false,
627                                 'created_at' => api_date($lastwall['created']),
628                                 'in_reply_to_status_id' => $in_reply_to_status_id,
629                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
630                                 'id' => $lastwall['contact-id'],
631                                 'in_reply_to_user_id' => $in_reply_to_user_id,
632                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
633                                 'geo' => '',
634                                 'favorited' => false,
635                                 'coordinates' => $lastwall['coord'],
636                                 'place' => $lastwall['location'],
637                                 'contributors' => ''                                    
638                         );
639                         $status_info['user'] = $user_info;
640                 }
641                 return  api_apply_template("status", $type, array('$status' => $status_info));
642                 
643         }
644
645
646
647
648                 
649         /**
650          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
651          * The author's most recent status will be returned inline.
652          * http://developer.twitter.com/doc/get/users/show
653          */
654         function api_users_show(&$a, $type){
655                 $user_info = api_get_user($a);
656                 // get last public wall message
657                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
658                                 FROM `item`, `contact`,
659                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
660                                 WHERE `item`.`contact-id` = %d
661                                         AND `i`.`id` = `item`.`parent`
662                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
663                                         AND `type`!='activity'
664                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
665                                 ORDER BY `created` DESC 
666                                 LIMIT 1",
667                                 intval($user_info['id'])
668                 );
669
670                 if (count($lastwall)>0){
671                         $lastwall = $lastwall[0];
672                         
673                         $in_reply_to_status_id = '';
674                         $in_reply_to_user_id = '';
675                         $in_reply_to_screen_name = '';
676                         if ($lastwall['parent']!=$lastwall['id']) {
677                                 $in_reply_to_status_id=$lastwall['parent'];
678                                 $in_reply_to_user_id = $lastwall['reply_uid'];
679                                 $in_reply_to_screen_name = $lastwall['reply_author'];
680                         }  
681                         $user_info['status'] = array(
682                                 'created_at' => api_date($lastwall['created']),
683                                 'id' => $lastwall['contact-id'],
684                                 'text' => html2plain(bbcode($lastwall['body']), 0),
685                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
686                                 'truncated' => false,
687                                 'in_reply_to_status_id' => $in_reply_to_status_id,
688                                 'in_reply_to_user_id' => $in_reply_to_user_id,
689                                 'favorited' => false,
690                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
691                                 'geo' => '',
692                                 'coordinates' => $lastwall['coord'],
693                                 'place' => $lastwall['location'],
694                                 'contributors' => ''
695                         );
696                 }
697                 return  api_apply_template("user", $type, array('$user' => $user_info));
698
699         }
700         api_register_func('api/users/show','api_users_show');
701
702         /**
703          *
704          * http://developer.twitter.com/doc/get/statuses/home_timeline
705          *
706          * TODO: Optional parameters
707          * TODO: Add reply info
708          */
709         function api_statuses_home_timeline(&$a, $type){
710                 if (local_user()===false) return false;
711
712                 $user_info = api_get_user($a);
713                 // get last newtork messages
714
715
716                 // params
717                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
718                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
719                 if ($page<0) $page=0;
720                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
721                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
722                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
723
724                 $start = $page*$count;
725
726                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
727
728                 if ($max_id > 0)
729                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
730
731                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
732                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
733                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
734                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
735                         FROM `item`, `contact`
736                         WHERE `item`.`uid` = %d
737                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
738                         AND `contact`.`id` = `item`.`contact-id`
739                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
740                         $sql_extra
741                         AND `item`.`id`>%d
742                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
743                         intval($user_info['uid']),
744                         intval($since_id),
745                         intval($start), intval($count)
746                 );
747
748                 $ret = api_format_items($r,$user_info);
749
750
751                 $data = array('$statuses' => $ret);
752                 switch($type){
753                         case "atom":
754                         case "rss":
755                                 $data = api_rss_extra($a, $data, $user_info);
756                                 break;
757                         case "as":
758                                 $as = api_format_as($a, $ret, $user_info);
759                                 $as['title'] = $a->config['sitename']." Home Timeline";
760                                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
761                                 return($as);
762                                 break;
763                 }
764
765                 return  api_apply_template("timeline", $type, $data);
766         }
767         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
768         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
769
770         function api_statuses_public_timeline(&$a, $type){
771                 if (local_user()===false) return false;
772
773                 $user_info = api_get_user($a);
774                 // get last newtork messages
775
776
777                 // params
778                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
779                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
780                 if ($page<0) $page=0;
781                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
782                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
783                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
784
785                 $start = $page*$count;
786
787                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
788
789                 if ($max_id > 0)
790                         $sql_extra = 'AND `item`.`id` <= '.intval($max_id);
791
792                 /*$r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
793                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
794                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
795                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
796                         FROM `item`, `contact`
797                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
798                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = '' 
799                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = '' 
800                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
801                         AND `contact`.`id` = `item`.`contact-id`
802                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
803                         $sql_extra
804                         AND `item`.`id`>%d
805                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
806                         intval($since_id),
807                         intval($start), intval($count)
808                 );*/
809                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
810                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
811                         `contact`.`network`, `contact`.`thumb`, `contact`.`self`, `contact`.`writable`,
812                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`,
813                         `user`.`nickname`, `user`.`hidewall`
814                         FROM `item` LEFT JOIN `contact` ON `contact`.`id` = `item`.`contact-id`
815                         LEFT JOIN `user` ON `user`.`uid` = `item`.`uid`
816                         WHERE `item`.`visible` = 1 AND `item`.`deleted` = 0 and `item`.`moderated` = 0
817                         AND `item`.`allow_cid` = ''  AND `item`.`allow_gid` = ''
818                         AND `item`.`deny_cid`  = '' AND `item`.`deny_gid`  = ''
819                         AND `item`.`private` = 0 AND `item`.`wall` = 1 AND `user`.`hidewall` = 0
820                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
821                         $sql_extra
822                         AND `item`.`id`>%d
823                         ORDER BY `received` DESC LIMIT %d, %d ",
824                         intval($since_id),
825                         intval($start),
826                         intval($count));
827
828                 $ret = api_format_items($r,$user_info);
829
830
831                 $data = array('$statuses' => $ret);
832                 switch($type){
833                         case "atom":
834                         case "rss":
835                                 $data = api_rss_extra($a, $data, $user_info);
836                                 break;
837                         case "as":
838                                 $as = api_format_as($a, $ret, $user_info);
839                                 $as['title'] = $a->config['sitename']." Public Timeline";
840                                 $as['link']['url'] = $a->get_baseurl()."/";
841                                 return($as);
842                                 break;
843                 }
844
845                 return  api_apply_template("timeline", $type, $data);
846         }
847         api_register_func('api/statuses/public_timeline','api_statuses_public_timeline', true);
848
849         /**
850          * 
851          */
852         function api_statuses_show(&$a, $type){
853                 if (local_user()===false) return false;
854
855                 $user_info = api_get_user($a);
856
857                 // params
858                 $id = intval($a->argv[3]);
859
860                 logger('API: api_statuses_show: '.$id);
861
862                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
863
864                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
865                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
866                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
867                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
868                         FROM `item`, `contact`
869                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
870                         AND `contact`.`id` = `item`.`contact-id`
871                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
872                         $sql_extra
873                         AND `item`.`id`=%d",
874                         intval($id)
875                 );
876
877                 $ret = api_format_items($r,$user_info);
878
879                 $data = array('$status' => $ret[0]);
880                 /*switch($type){
881                         case "atom":
882                         case "rss":
883                                 $data = api_rss_extra($a, $data, $user_info);
884                 }*/
885                 return  api_apply_template("status", $type, $data);
886         }
887         api_register_func('api/statuses/show','api_statuses_show', true);
888
889
890         /**
891          * 
892          */
893         function api_statuses_repeat(&$a, $type){
894                 if (local_user()===false) return false;
895
896                 $user_info = api_get_user($a);
897
898                 // params
899                 $id = intval($a->argv[3]);
900
901                 logger('API: api_statuses_repeat: '.$id);
902
903                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
904
905                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, `contact`.`nick` as `reply_author`,
906                         `contact`.`name`, `contact`.`photo`, `contact`.`url` as `reply_url`, `contact`.`rel`,
907                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
908                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
909                         FROM `item`, `contact`
910                         WHERE `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
911                         AND `contact`.`id` = `item`.`contact-id`
912                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
913                         $sql_extra
914                         AND `item`.`id`=%d",
915                         intval($id)
916                 );
917
918                 if ($r[0]['body'] != "") {
919                         $_REQUEST['body'] = html_entity_decode("&#x2672; ", ENT_QUOTES, 'UTF-8')."[url=".$r[0]['reply_url']."]".$r[0]['reply_author']."[/url] \n".$r[0]['body'];
920                         $_REQUEST['profile_uid'] = local_user();
921                         $_REQUEST['type'] = 'wall';
922                         $_REQUEST['api_source'] = true;
923
924                         require_once('mod/item.php');
925                         item_post($a);
926                 }
927
928                 if ($type == 'xml')
929                         $ok = "true";
930                 else
931                         $ok = "ok";
932
933                 return api_apply_template('test', $type, array('$ok' => $ok));
934         }
935         api_register_func('api/statuses/retweet','api_statuses_repeat', true);
936
937         /**
938          * 
939          */
940         function api_statuses_destroy(&$a, $type){
941                 if (local_user()===false) return false;
942
943                 $user_info = api_get_user($a);
944
945                 // params
946                 $id = intval($a->argv[3]);
947
948                 logger('API: api_statuses_destroy: '.$id);
949
950                 require_once('include/items.php');
951                 drop_item($id, false);
952
953                 if ($type == 'xml')
954                         $ok = "true";
955                 else
956                         $ok = "ok";
957
958                 return api_apply_template('test', $type, array('$ok' => $ok));
959         }
960         api_register_func('api/statuses/destroy','api_statuses_destroy', true);
961
962         /**
963          * 
964          * http://developer.twitter.com/doc/get/statuses/mentions
965          * 
966          */
967         function api_statuses_mentions(&$a, $type){
968                 if (local_user()===false) return false;
969                                 
970                 $user_info = api_get_user($a);
971                 // get last newtork messages
972
973
974                 // params
975                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
976                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
977                 if ($page<0) $page=0;
978                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
979                 $max_id = (x($_REQUEST,'max_id')?$_REQUEST['max_id']:0);
980                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
981
982                 $start = $page*$count;
983
984                 //$include_entities = (x($_REQUEST,'include_entities')?$_REQUEST['include_entities']:false);
985
986                 $myurl = $a->get_baseurl() . '/profile/'. $a->user['nickname'];
987                 $myurl = substr($myurl,strpos($myurl,'://')+3);
988                 $myurl = str_replace(array('www.','.'),array('','\\.'),$myurl);
989                 $diasp_url = str_replace('/profile/','/u/',$myurl);
990
991                 if (get_config('system','use_fulltext_engine'))
992                         $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))) ",
993                                 dbesc(protect_sprintf($myurl)),
994                                 dbesc(protect_sprintf($myurl)),
995                                 dbesc(protect_sprintf($diasp_url))
996                         );
997                 else
998                         $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' )) ",
999                                 dbesc(protect_sprintf('%' . $myurl)),
1000                                 dbesc(protect_sprintf('%' . $myurl . ']%')),
1001                                 dbesc(protect_sprintf('%' . $diasp_url . ']%'))
1002                         );
1003
1004                 if ($max_id > 0)
1005                         $sql_extra .= ' AND `item`.`id` <= '.intval($max_id);
1006
1007                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1008                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1009                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1010                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1011                         FROM `item`, `contact`
1012                         WHERE `item`.`uid` = %d
1013                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1014                         AND `contact`.`id` = `item`.`contact-id`
1015                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1016                         $sql_extra
1017                         AND `item`.`id`>%d
1018                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1019                         intval($user_info['uid']),
1020                         intval($since_id),
1021                         intval($start), intval($count)
1022                 );
1023
1024                 $ret = api_format_items($r,$user_info);
1025
1026
1027                 $data = array('$statuses' => $ret);
1028                 switch($type){
1029                         case "atom":
1030                         case "rss":
1031                                 $data = api_rss_extra($a, $data, $user_info);
1032                                 break;
1033                         case "as":
1034                                 $as = api_format_as($a, $ret, $user_info);
1035                                 $as["title"] = $a->config['sitename']." Mentions";
1036                                 $as['link']['url'] = $a->get_baseurl()."/";
1037                                 return($as);
1038                                 break;
1039                 }
1040
1041                 return  api_apply_template("timeline", $type, $data);
1042         }
1043         api_register_func('api/statuses/mentions','api_statuses_mentions', true);
1044         api_register_func('api/statuses/replies','api_statuses_mentions', true);
1045
1046
1047         function api_statuses_user_timeline(&$a, $type){
1048                 if (local_user()===false) return false;
1049                 
1050                 $user_info = api_get_user($a);
1051                 // get last newtork messages
1052
1053
1054                 logger("api_statuses_user_timeline: local_user: ". local_user() .
1055                            "\nuser_info: ".print_r($user_info, true) .
1056                            "\n_REQUEST:  ".print_r($_REQUEST, true),
1057                            LOGGER_DEBUG);
1058
1059                 // params
1060                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
1061                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1062                 if ($page<0) $page=0;
1063                 $since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1064                 //$since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
1065                 
1066                 $start = $page*$count;
1067
1068                 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
1069
1070                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
1071                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1072                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1073                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1074                         FROM `item`, `contact`
1075                         WHERE `item`.`uid` = %d
1076                         AND `item`.`contact-id` = %d
1077                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1078                         AND `contact`.`id` = `item`.`contact-id`
1079                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1080                         $sql_extra
1081                         AND `item`.`id`>%d
1082                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1083                         intval(local_user()),
1084                         intval($user_info['id']),
1085                         intval($since_id),
1086                         intval($start), intval($count)
1087                 );
1088
1089                 $ret = api_format_items($r,$user_info);
1090
1091
1092                 $data = array('$statuses' => $ret);
1093                 switch($type){
1094                         case "atom":
1095                         case "rss":
1096                                 $data = api_rss_extra($a, $data, $user_info);
1097                 }
1098
1099                 return  api_apply_template("timeline", $type, $data);
1100         }
1101
1102         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
1103
1104
1105         function api_favorites(&$a, $type){
1106                 if (local_user()===false) return false;
1107
1108                 $user_info = api_get_user($a);
1109                 // in friendica starred item are private
1110                 // return favorites only for self
1111                 logger('api_favorites: self:' . $user_info['self']);
1112
1113                 if ($user_info['self']==0) {
1114                         $ret = array();
1115                 } else {
1116
1117
1118                         // params
1119                         $count = (x($_GET,'count')?$_GET['count']:20);
1120                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1121                         if ($page<0) $page=0;
1122
1123                         $start = $page*$count;
1124
1125                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`,
1126                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
1127                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
1128                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
1129                                 FROM `item`, `contact`
1130                                 WHERE `item`.`uid` = %d
1131                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
1132                                 AND `item`.`starred` = 1
1133                                 AND `contact`.`id` = `item`.`contact-id`
1134                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
1135                                 $sql_extra
1136                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
1137                                 intval($user_info['uid']),
1138                                 intval($start), intval($count)
1139                         );
1140
1141                         $ret = api_format_items($r,$user_info);
1142
1143                 }
1144
1145                 $data = array('$statuses' => $ret);
1146                 switch($type){
1147                         case "atom":
1148                         case "rss":
1149                                 $data = api_rss_extra($a, $data, $user_info);
1150                 }
1151
1152                 return  api_apply_template("timeline", $type, $data);
1153         }
1154
1155         api_register_func('api/favorites','api_favorites', true);
1156
1157         function api_format_as($a, $ret, $user_info) {
1158
1159                 $as = array();
1160                 $as['title'] = $a->config['sitename']." Public Timeline";
1161                 $items = array();
1162                 foreach ($ret as $item) {
1163                         $singleitem["actor"]["displayName"] = $item["user"]["name"];
1164                         $singleitem["actor"]["id"] = $item["user"]["contact_url"];
1165                         $avatar[0]["url"] = $item["user"]["profile_image_url"];
1166                         $avatar[0]["rel"] = "avatar";
1167                         $avatar[0]["type"] = "";
1168                         $avatar[0]["width"] = 96;
1169                         $avatar[0]["height"] = 96;
1170                         $avatar[1]["url"] = $item["user"]["profile_image_url"];
1171                         $avatar[1]["rel"] = "avatar";
1172                         $avatar[1]["type"] = "";
1173                         $avatar[1]["width"] = 48;
1174                         $avatar[1]["height"] = 48;
1175                         $avatar[2]["url"] = $item["user"]["profile_image_url"];
1176                         $avatar[2]["rel"] = "avatar";
1177                         $avatar[2]["type"] = "";
1178                         $avatar[2]["width"] = 24;
1179                         $avatar[2]["height"] = 24;
1180                         $singleitem["actor"]["avatarLinks"] = $avatar;
1181
1182                         $singleitem["actor"]["image"]["url"] = $item["user"]["profile_image_url"];
1183                         $singleitem["actor"]["image"]["rel"] = "avatar";
1184                         $singleitem["actor"]["image"]["type"] = "";
1185                         $singleitem["actor"]["image"]["width"] = 96;
1186                         $singleitem["actor"]["image"]["height"] = 96;
1187                         $singleitem["actor"]["type"] = "person";
1188                         $singleitem["actor"]["url"] = $item["person"]["contact_url"];
1189                         $singleitem["actor"]["statusnet:profile_info"]["local_id"] = $item["user"]["id"];
1190                         $singleitem["actor"]["statusnet:profile_info"]["following"] = $item["user"]["following"] ? "true" : "false";
1191                         $singleitem["actor"]["statusnet:profile_info"]["blocking"] = "false";
1192                         $singleitem["actor"]["contact"]["preferredUsername"] = $item["user"]["screen_name"];
1193                         $singleitem["actor"]["contact"]["displayName"] = $item["user"]["name"];
1194                         $singleitem["actor"]["contact"]["addresses"] = "";
1195
1196                         $singleitem["body"] = $item["text"];
1197                         $singleitem["object"]["displayName"] = $item["text"];
1198                         $singleitem["object"]["id"] = $item["url"];
1199                         $singleitem["object"]["type"] = "note";
1200                         $singleitem["object"]["url"] = $item["url"];
1201                         //$singleitem["context"] =;
1202                         $singleitem["postedTime"] = date("c", strtotime($item["published"]));
1203                         $singleitem["provider"]["objectType"] = "service";
1204                         $singleitem["provider"]["displayName"] = "Test";
1205                         $singleitem["provider"]["url"] = "http://test.tld";
1206                         $singleitem["title"] = $item["text"];
1207                         $singleitem["verb"] = "post";
1208                         $singleitem["statusnet:notice_info"]["local_id"] = $item["id"];
1209                                 $singleitem["statusnet:notice_info"]["source"] = $item["source"];
1210                                 $singleitem["statusnet:notice_info"]["favorite"] = "false";
1211                                 $singleitem["statusnet:notice_info"]["repeated"] = "false";
1212                                 //$singleitem["original"] = $item;
1213                                 $items[] = $singleitem;
1214                 }
1215                 $as['items'] = $items;
1216                 $as['link']['url'] = $a->get_baseurl()."/".$user_info["screen_name"]."/all";
1217                 $as['link']['rel'] = "alternate";
1218                 $as['link']['type'] = "text/html";
1219                 return($as);
1220         }
1221
1222         function api_format_items($r,$user_info) {
1223
1224                 //logger('api_format_items: ' . print_r($r,true));
1225
1226                 //logger('api_format_items: ' . print_r($user_info,true));
1227
1228                 $a = get_app();
1229                 $ret = Array();
1230
1231                 foreach($r as $item) {
1232                         localize_item($item);
1233                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
1234
1235                         if ($item['parent']!=$item['id']) {
1236                                 $r = q("select id from item where parent=%s and id<%s order by id desc limit 1",
1237                                         intval($item['parent']), intval($item['id']));
1238                                 if ($r)
1239                                         $in_reply_to_status_id = $r[0]['id'];
1240                                 else
1241                                         $in_reply_to_status_id = $item['parent'];
1242
1243                                 $r = q("select `item`.`contact-id`, `contact`.nick, `item`.`author-name` from item, contact
1244                                         where `contact`.`id` = `item`.`contact-id` and `item`.id=%d", intval($in_reply_to_status_id));
1245
1246                                 $in_reply_to_screen_name = $r[0]['author-name'];
1247                                 $in_reply_to_user_id = $r[0]['contact-id'];
1248
1249                         } else {
1250                                 $in_reply_to_screen_name = '';
1251                                 $in_reply_to_user_id = 0;
1252                                 $in_reply_to_status_id = 0;
1253                         }
1254
1255                         // Workaround for ostatus messages where the title is identically to the body
1256                         $statusbody = trim(html2plain(bbcode($item['body']), 0));
1257                         $statustitle = trim($item['title']);
1258
1259                         if (($statustitle != '') and (strpos($statusbody, $statustitle) !== false))
1260                                 $statustext = trim($statusbody);
1261                         else
1262                                 $statustext = trim($statustitle."\n\n".$statusbody);
1263
1264                         if (($item["network"] == NETWORK_FEED) and (strlen($statustext)> 1000))
1265                                 $statustext = substr($statustext, 0, 1000)."... \n".$item["plink"];
1266
1267                         $status = array(
1268                                 'text'          => $statustext,
1269                                 'truncated' => False,
1270                                 'created_at'=> api_date($item['created']),
1271                                 'in_reply_to_status_id' => $in_reply_to_status_id,
1272                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
1273                                 'id'            => intval($item['id']),
1274                                 'in_reply_to_user_id' => $in_reply_to_user_id,
1275                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
1276                                 'geo' => '',
1277                                 'favorited' => $item['starred'] ? true : false,
1278                                 'user' =>  $status_user ,
1279                                 'statusnet_html'                => trim(bbcode($item['body'])),
1280                                 'statusnet_conversation_id'     => $item['parent'],
1281                         );
1282
1283                         // Seesmic doesn't like the following content
1284                         if ($_SERVER['HTTP_USER_AGENT'] != 'Seesmic') {
1285                                 $status2 = array(
1286                                         'updated'   => api_date($item['edited']),
1287                                         'published' => api_date($item['created']),
1288                                         'message_id' => $item['uri'],
1289                                         'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
1290                                         'coordinates' => $item['coord'],
1291                                         'place' => $item['location'],
1292                                         'contributors' => '',
1293                                         'annotations'  => '',
1294                                         'entities'  => '',
1295                                         'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
1296                                         'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
1297                                         'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1298                                         'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
1299                                 );
1300
1301                                 $status = array_merge($status, $status2);
1302                         }
1303
1304                         $ret[]=$status;
1305                 };
1306                 return $ret;
1307         }
1308
1309
1310         function api_account_rate_limit_status(&$a,$type) {
1311
1312                 $hash = array(
1313                           'reset_time_in_seconds' => strtotime('now + 1 hour'),
1314                           'remaining_hits' => (string) 150,
1315                           'hourly_limit' => (string) 150,
1316                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
1317                 );
1318                 if ($type == "xml")
1319                         $hash['resettime_in_seconds'] = $hash['reset_time_in_seconds'];
1320
1321                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
1322
1323         }
1324         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
1325
1326         function api_help_test(&$a,$type) {
1327
1328                 if ($type == 'xml')
1329                         $ok = "true";
1330                 else
1331                         $ok = "ok";
1332
1333                 return api_apply_template('test', $type, array('$ok' => $ok));
1334
1335         }
1336         api_register_func('api/help/test','api_help_test',true);
1337
1338         /**
1339          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
1340          *  This function is deprecated by Twitter
1341          *  returns: json, xml 
1342          **/
1343         function api_statuses_f(&$a, $type, $qtype) {
1344                 if (local_user()===false) return false;
1345                 $user_info = api_get_user($a);
1346                 
1347                 
1348                 // friends and followers only for self
1349                 if ($user_info['self']==0){
1350                         return false;
1351                 }
1352                 
1353                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
1354                         /* this is to stop Hotot to load friends multiple times
1355                         *  I'm not sure if I'm missing return something or
1356                         *  is a bug in hotot. Workaround, meantime
1357                         */
1358                         
1359                         /*$ret=Array();
1360                         return array('$users' => $ret);*/
1361                         return false;
1362                 }
1363                 
1364                 if($qtype == 'friends')
1365                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1366                 if($qtype == 'followers')
1367                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1368  
1369                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1370                         intval(local_user())
1371                 );
1372
1373                 $ret = array();
1374                 foreach($r as $cid){
1375                         $ret[] = api_get_user($a, $cid['id']);
1376                 }
1377
1378                 
1379                 return array('$users' => $ret);
1380
1381         }
1382         function api_statuses_friends(&$a, $type){
1383                 $data =  api_statuses_f($a,$type,"friends");
1384                 if ($data===false) return false;
1385                 return  api_apply_template("friends", $type, $data);
1386         }
1387         function api_statuses_followers(&$a, $type){
1388                 $data = api_statuses_f($a,$type,"followers");
1389                 if ($data===false) return false;
1390                 return  api_apply_template("friends", $type, $data);
1391         }
1392         api_register_func('api/statuses/friends','api_statuses_friends',true);
1393         api_register_func('api/statuses/followers','api_statuses_followers',true);
1394
1395
1396
1397
1398
1399
1400         function api_statusnet_config(&$a,$type) {
1401                 $name = $a->config['sitename'];
1402                 $server = $a->get_hostname();
1403                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
1404                 $email = $a->config['admin_email'];
1405                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
1406                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
1407                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
1408                 if($a->config['api_import_size'])
1409                         $texlimit = string($a->config['api_import_size']);
1410                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
1411                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
1412
1413                 $config = array(
1414                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
1415                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
1416                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
1417                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
1418                                 'shorturllength' => '30'
1419                         ),
1420                 );  
1421
1422                 return api_apply_template('config', $type, array('$config' => $config));
1423
1424         }
1425         api_register_func('api/statusnet/config','api_statusnet_config',false);
1426
1427         function api_statusnet_version(&$a,$type) {
1428
1429                 // liar
1430
1431                 if($type === 'xml') {
1432                         header("Content-type: application/xml");
1433                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
1434                         killme();
1435                 }
1436                 elseif($type === 'json') {
1437                         header("Content-type: application/json");
1438                         echo '"0.9.7"';
1439                         killme();
1440                 }
1441         }
1442         api_register_func('api/statusnet/version','api_statusnet_version',false);
1443
1444
1445         function api_ff_ids(&$a,$type,$qtype) {
1446                 if(! local_user())
1447                         return false;
1448
1449                 if($qtype == 'friends')
1450                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1451                 if($qtype == 'followers')
1452                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1453  
1454
1455                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1456                         intval(local_user())
1457                 );
1458
1459                 if(is_array($r)) {
1460                         if($type === 'xml') {
1461                                 header("Content-type: application/xml");
1462                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1463                                 foreach($r as $rr)
1464                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1465                                 echo '</ids>' . "\r\n";
1466                                 killme();
1467                         }
1468                         elseif($type === 'json') {
1469                                 $ret = array();
1470                                 header("Content-type: application/json");
1471                                 foreach($r as $rr) $ret[] = $rr['id'];
1472                                 echo json_encode($ret);
1473                                 killme();
1474                         }
1475                 }
1476         }
1477
1478         function api_friends_ids(&$a,$type) {
1479                 api_ff_ids($a,$type,'friends');
1480         }
1481         function api_followers_ids(&$a,$type) {
1482                 api_ff_ids($a,$type,'followers');
1483         }
1484         api_register_func('api/friends/ids','api_friends_ids',true);
1485         api_register_func('api/followers/ids','api_followers_ids',true);
1486
1487
1488         function api_direct_messages_new(&$a, $type) {
1489                 if (local_user()===false) return false;
1490                 
1491                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1492                 
1493                 $sender = api_get_user($a);
1494                 
1495                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1496                                 intval(local_user()),
1497                                 dbesc($_POST['screen_name']));
1498                 
1499                 $recipient = api_get_user($a, $r[0]['id']);                     
1500                 
1501
1502                 require_once("include/message.php");
1503                 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1504                 $id = send_message($recipient['id'], $_POST['text'], $sub);
1505                 
1506                 
1507                 if ($id>-1) {
1508                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1509                         $item = $r[0];
1510                         $ret=Array(
1511                                         'id' => $item['id'],
1512                                         'created_at'=> api_date($item['created']),
1513                                         'sender_id'=> $sender['id'] ,
1514                                         'sender_screen_name'=> $sender['screen_name'],
1515                                         'sender'=> $sender,
1516                                         'recipient_id'=> $recipient['id'],
1517                                         'recipient_screen_name'=> $recipient['screen_name'],
1518                                         'recipient'=> $recipient,
1519                                         
1520                                         'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1521                                         
1522                         );
1523                 
1524                 } else {
1525                         $ret = array("error"=>$id);     
1526                 }
1527                 
1528                 $data = Array('$messages'=>$ret);
1529                 
1530                 switch($type){
1531                         case "atom":
1532                         case "rss":
1533                                 $data = api_rss_extra($a, $data, $user_info);
1534                 }
1535                                 
1536                 return  api_apply_template("direct_messages", $type, $data);
1537                                 
1538         }
1539         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1540
1541     function api_direct_messages_box(&$a, $type, $box) {
1542                 if (local_user()===false) return false;
1543                 
1544                 $user_info = api_get_user($a);
1545                 
1546                 // params
1547                 $count = (x($_GET,'count')?$_GET['count']:20);
1548                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1549                 if ($page<0) $page=0;
1550                 
1551                 $start = $page*$count;
1552                 
1553         
1554                 if ($box=="sentbox") {
1555                         $sql_extra = "`from-url`='%s'";
1556                 } else {
1557                         $sql_extra = "`from-url`!='%s'";
1558                 }
1559                 
1560                 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1561                                 intval(local_user()),
1562                                 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1563                                 intval($start), intval($count)
1564                            );
1565                 
1566                 $ret = Array();
1567                 foreach($r as $item){
1568                         switch ($box){
1569                                 case "inbox":
1570                                         $recipient = $user_info;
1571                                         $sender = api_get_user($a,$item['contact-id']);
1572                                         break;
1573                                 case "sentbox":
1574                                         $recipient = api_get_user($a,$item['contact-id']);
1575                                         $sender = $user_info;
1576                                         break;
1577                         }
1578                                 
1579                         $ret[]=Array(
1580                                 'id' => $item['id'],
1581                                 'created_at'=> api_date($item['created']),
1582                                 'sender_id'=> $sender['id'] ,
1583                                 'sender_screen_name'=> $sender['screen_name'],
1584                                 'sender'=> $sender,
1585                                 'recipient_id'=> $recipient['id'],
1586                                 'recipient_screen_name'=> $recipient['screen_name'],
1587                                 'recipient'=> $recipient,
1588                                 
1589                                 'text'=> $item['title']."\n".html2plain(bbcode($item['body']), 0) ,
1590                                 
1591                         );
1592                         
1593                 }
1594                 
1595
1596                 $data = array('$messages' => $ret);
1597                 switch($type){
1598                         case "atom":
1599                         case "rss":
1600                                 $data = api_rss_extra($a, $data, $user_info);
1601                 }
1602                                 
1603                 return  api_apply_template("direct_messages", $type, $data);
1604                 
1605         }
1606
1607         function api_direct_messages_sentbox(&$a, $type){
1608                 return api_direct_messages_box($a, $type, "sentbox");
1609         }
1610         function api_direct_messages_inbox(&$a, $type){
1611                 return api_direct_messages_box($a, $type, "inbox");
1612         }
1613         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1614         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1615
1616
1617
1618         function api_oauth_request_token(&$a, $type){
1619                 try{
1620                         $oauth = new FKOAuth1();
1621                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1622                 }catch(Exception $e){
1623                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1624                 }
1625                 echo $r;
1626                 killme();       
1627         }
1628         function api_oauth_access_token(&$a, $type){
1629                 try{
1630                         $oauth = new FKOAuth1();
1631                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1632                 }catch(Exception $e){
1633                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1634                 }
1635                 echo $r;
1636                 killme();                       
1637         }
1638
1639         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1640         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1641
1642 /*
1643 Not implemented by now:
1644 favorites
1645 favorites/create
1646 favorites/destroy
1647 statuses/retweets_of_me
1648 friendships/create
1649 friendships/destroy
1650 friendships/exists
1651 friendships/show
1652 account/update_location
1653 account/update_profile_background_image
1654 account/update_profile_image
1655 blocks/create
1656 blocks/destroy
1657
1658 Not implemented in status.net:
1659 statuses/retweeted_to_me
1660 statuses/retweeted_by_me
1661 direct_messages/destroy
1662 account/end_session
1663 account/update_delivery_device
1664 notifications/follow
1665 notifications/leave
1666 blocks/exists
1667 blocks/blocking
1668 */