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