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