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