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