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