]> git.mxchange.org Git - friendica.git/blob - include/api.php
template proc: avoid a notice and allow template name to include to be passed with...
[friendica.git] / include / api.php
1 <?php
2         require_once("bbcode.php");
3         require_once("datetime.php");
4         require_once("conversation.php");
5         require_once("oauth.php");
6         /* 
7          * Twitter-Like API
8          *  
9          */
10
11         $API = Array();
12         $called_api = Null; 
13
14         function api_date($str){
15                 //Wed May 23 06:01:13 +0000 2007
16                 return datetime_convert('UTC', 'UTC', $str, "D M d H:i:s +0000 Y" );
17         }
18          
19         
20         function api_register_func($path, $func, $auth=false){
21                 global $API;
22                 $API[$path] = array('func'=>$func,
23                                                         'auth'=>$auth);
24         }
25         
26         /**
27          * Simple HTTP Login
28          */
29
30         function api_login(&$a){
31                 // login with oauth
32                 try{
33                         $oauth = new FKOAuth1();
34                         list($consumer,$token) = $oauth->verify_request(OAuthRequest::from_request());
35                         if (!is_null($token)){
36                                 $oauth->loginUser($token->uid);
37                                 call_hooks('logged_in', $a->user);
38                                 return;
39                         }
40                         echo __file__.__line__.__function__."<pre>"; var_dump($consumer, $token); die();
41                 }catch(Exception $e){
42                         logger(__file__.__line__.__function__."\n".$e);
43                         //die(__file__.__line__.__function__."<pre>".$e); die();
44                 }
45
46                 
47                 
48                 // workaround for HTTP-auth in CGI mode
49                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
50                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
51                         if(strlen($userpass)) {
52                                 list($name, $password) = explode(':', $userpass);
53                                 $_SERVER['PHP_AUTH_USER'] = $name;
54                                 $_SERVER['PHP_AUTH_PW'] = $password;
55                         }
56                 }
57
58                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
59                    logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
60                     header('WWW-Authenticate: Basic realm="Friendica"');
61                     header('HTTP/1.0 401 Unauthorized');
62                     die('This api requires login');
63                 }
64                 
65                 $user = $_SERVER['PHP_AUTH_USER'];
66                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
67                 
68                 
69                         /**
70                          *  next code from mod/auth.php. needs better solution
71                          */
72                         
73                 // process normal login request
74
75                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) 
76                         AND `password` = '%s' AND `blocked` = 0 AND `account_expired` = 0 AND `verified` = 1 LIMIT 1",
77                         dbesc(trim($user)),
78                         dbesc(trim($user)),
79                         dbesc($encrypted)
80                 );
81                 if(count($r)){
82                         $record = $r[0];
83                 } else {
84                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
85                     header('WWW-Authenticate: Basic realm="Friendika"');
86                     header('HTTP/1.0 401 Unauthorized');
87                     die('This api requires login');
88                 }
89
90                 require_once('include/security.php');
91                 authenticate_success($record);
92
93                 call_hooks('logged_in', $a->user);
94
95         }
96         
97         /**************************
98          *  MAIN API ENTRY POINT  *
99          **************************/
100         function api_call(&$a){
101                 GLOBAL $API, $called_api;
102
103                 // preset
104                 $type="json";
105
106                 foreach ($API as $p=>$info){
107                         if (strpos($a->query_string, $p)===0){
108                                 $called_api= explode("/",$p);
109                                 //unset($_SERVER['PHP_AUTH_USER']);
110                                 if ($info['auth']===true && local_user()===false) {
111                                                 api_login($a);
112                                 }
113
114                                 load_contact_links(local_user());
115
116                                 logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
117                                 logger('API parameters: ' . print_r($_REQUEST,true));
118                                 $type="json";
119                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
120                                 if (strpos($a->query_string, ".json")>0) $type="json";
121                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
122                                 if (strpos($a->query_string, ".atom")>0) $type="atom";
123
124                                 $r = call_user_func($info['func'], $a, $type);
125                                 if ($r===false) return;
126
127                                 switch($type){
128                                         case "xml":
129                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
130                                                 header ("Content-Type: text/xml");
131                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
132                                                 break;
133                                         case "json":
134                                                 //header ("Content-Type: application/json");
135                                                 foreach($r as $rr)
136                                                     return json_encode($rr);
137                                                 break;
138                                         case "rss":
139                                                 header ("Content-Type: application/rss+xml");
140                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
141                                                 break;
142                                         case "atom":
143                                                 header ("Content-Type: application/atom+xml");
144                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
145                                                 break;
146
147                                 }
148                                 //echo "<pre>"; var_dump($r); die();
149                         }
150                 }
151                 logger('API call not implemented: '.$a->query_string." - ".print_r($_REQUEST,true));
152                 $r = '<status><error>not implemented</error></status>';
153                 switch($type){
154                         case "xml":
155                                 header ("Content-Type: text/xml");
156                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
157                                 break;
158                         case "json":
159                                 header ("Content-Type: application/json");
160                             return json_encode(array('error' => 'not implemented'));
161                                 break;
162                         case "rss":
163                                 header ("Content-Type: application/rss+xml");
164                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
165                                 break;
166                         case "atom":
167                                 header ("Content-Type: application/atom+xml");
168                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
169                                 break;
170                 }
171         }
172
173         /**
174          * RSS extra info
175          */
176         function api_rss_extra(&$a, $arr, $user_info){
177                 if (is_null($user_info)) $user_info = api_get_user($a);
178                 $arr['$user'] = $user_info;
179                 $arr['$rss'] = array(
180                         'alternate' => $user_info['url'],
181                         'self' => $a->get_baseurl(). "/". $a->query_string,
182                         'base' => $a->get_baseurl(),
183                         'updated' => api_date(null),
184                         'atom_updated' => datetime_convert('UTC','UTC','now',ATOM_TIME),
185                         'language' => $user_info['language'],
186                         'logo'  => $a->get_baseurl()."/images/friendica-32.png",
187                 );
188                 
189                 return $arr;
190         }
191          
192         /**
193          * Returns user info array.
194          */
195         function api_get_user(&$a, $contact_id = Null){
196                 global $called_api;
197                 $user = null;
198                 $extra_query = "";
199
200
201                 if(!is_null($contact_id)){
202                         $user=$contact_id;
203                         $extra_query = "AND `contact`.`id` = %d ";
204                 }
205                 
206                 if(is_null($user) && x($_GET, 'user_id')) {
207                         $user = intval($_GET['user_id']);       
208                         $extra_query = "AND `contact`.`id` = %d ";
209                 }
210                 if(is_null($user) && x($_GET, 'screen_name')) {
211                         $user = dbesc($_GET['screen_name']);    
212                         $extra_query = "AND `contact`.`nick` = '%s' ";
213                         if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
214                         
215                 }
216                 
217                 if (is_null($user) && $a->argc > (count($called_api)-1)){
218                         $argid = count($called_api);
219                         list($user, $null) = explode(".",$a->argv[$argid]);
220                         if(is_numeric($user)){
221                                 $user = intval($user);
222                                 $extra_query = "AND `contact`.`id` = %d ";
223                         } else {
224                                 $user = dbesc($user);
225                                 $extra_query = "AND `contact`.`nick` = '%s' ";
226                                 if (local_user()!==false)  $extra_query .= "AND `contact`.`uid`=".intval(local_user());
227                         }
228                 }
229                 
230                 if (! $user) {
231                         if (local_user()===false) {
232                                 api_login($a); return False;
233                         } else {
234                                 $user = $_SESSION['uid'];
235                                 $extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` = 1 ";
236                         }
237                         
238                 }
239                 
240                 logger('api_user: ' . $extra_query . ' ' , $user);
241                 // user info            
242                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
243                                 WHERE 1
244                                 $extra_query",
245                                 $user
246                 );
247                 if (count($uinfo)==0) {
248                         return False;
249                 }
250                 
251                 if($uinfo[0]['self']) {
252                         $usr = q("select * from user where uid = %d limit 1",
253                                 intval(local_user())
254                         );
255                         $profile = q("select * from profile where uid = %d and `is-default` = 1 limit 1",
256                                 intval(local_user())
257                         );
258
259                         // count public wall messages
260                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
261                                         WHERE  `uid` = %d
262                                         AND `type`='wall' 
263                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
264                                         intval($uinfo[0]['uid'])
265                         );
266                         $countitms = $r[0]['count'];
267                 }
268                 else {
269                         $r = q("SELECT COUNT(`id`) as `count` FROM `item`
270                                         WHERE  `contact-id` = %d
271                                         AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
272                                         intval($uinfo[0]['id'])
273                         );
274                         $countitms = $r[0]['count'];
275                 }
276
277                 // count friends
278                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
279                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
280                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
281                                 intval($uinfo[0]['uid']),
282                                 intval(CONTACT_IS_SHARING),
283                                 intval(CONTACT_IS_FRIEND)
284                 );
285                 $countfriends = $r[0]['count'];
286
287                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
288                                 WHERE  `uid` = %d AND `rel` IN ( %d, %d )
289                                 AND `self`=0 AND `blocked`=0 AND `pending`=0 AND `hidden`=0", 
290                                 intval($uinfo[0]['uid']),
291                                 intval(CONTACT_IS_FOLLOWER),
292                                 intval(CONTACT_IS_FRIEND)
293                 );
294                 $countfollowers = $r[0]['count'];
295
296                 $r = q("SELECT count(`id`) as `count` FROM item where starred = 1 and uid = %d and deleted = 0",
297                         intval($uinfo[0]['uid'])
298                 );
299                 $starred = $r[0]['count'];
300         
301
302                 if(! $uinfo[0]['self']) {
303                         $countfriends = 0;
304                         $countfollowers = 0;
305                         $starred = 0;
306                 }
307
308                 $ret = Array(
309                         'self' => intval($uinfo[0]['self']),
310                         'uid' => intval($uinfo[0]['uid']),
311                         'id' => intval($uinfo[0]['cid']),
312                         'name' => $uinfo[0]['name'],
313                         'screen_name' => (($uinfo[0]['nick']) ? $uinfo[0]['nick'] : $uinfo[0]['name']),
314                         'location' => ($usr) ? $usr[0]['default-location'] : '',
315                         'profile_image_url' => $uinfo[0]['micro'],
316                         'url' => $uinfo[0]['url'],
317                         'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
318                         'protected' => false,   
319                         'friends_count' => intval($countfriends),
320                         'created_at' => api_date($uinfo[0]['name-date']),
321                         'utc_offset' => "+00:00",
322                         'time_zone' => 'UTC', //$uinfo[0]['timezone'],
323                         'geo_enabled' => false,
324                         'statuses_count' => intval($countitms), #XXX: fix me 
325                         'lang' => 'en', #XXX: fix me
326                         'description' => (($profile) ? $profile[0]['pdesc'] : ''),
327                         'followers_count' => intval($countfollowers),
328                         'favourites_count' => intval($starred),
329                         'contributors_enabled' => false,
330                         'follow_request_sent' => true,
331                         'profile_background_color' => 'cfe8f6',
332                         'profile_text_color' => '000000',
333                         'profile_link_color' => 'FF8500',
334                         'profile_sidebar_fill_color' =>'AD0066',
335                         'profile_sidebar_border_color' => 'AD0066',
336                         'profile_background_image_url' => '',
337                         'profile_background_tile' => false,
338                         'profile_use_background_image' => false,
339                         'notifications' => false,
340                         'following' => '', #XXX: fix me
341                         'verified' => true, #XXX: fix me
342                         'status' => array()
343                 );
344         
345                 return $ret;
346                 
347         }
348
349         function api_item_get_user(&$a, $item) {
350                 // The author is our direct contact, in a conversation with us.
351                 if(link_compare($item['url'],$item['author-link'])) {
352                         return api_get_user($a,$item['cid']);
353                 }
354                 else {
355                         // The author may be a contact of ours, but is replying to somebody else. 
356                         // Figure out if we know him/her.
357                         $normalised = normalise_link((strlen($item['author-link'])) ? $item['author-link'] : $item['url']);
358             if(($normalised != 'mailbox') && (x($a->contacts[$normalised])))
359                                 return api_get_user($a,$a->contacts[$normalised]['id']);
360                 }
361                 // We don't know this person directly.
362                 
363                 list($nick, $name) = array_map("trim",explode("(",$item['author-name']));
364                 $name=str_replace(")","",$name);
365                 
366                 $ret = array(
367                         'uid' => 0,
368                         'id' => 0,
369                         'name' => $name,
370                         'screen_name' => $nick,
371                         'location' => '', //$uinfo[0]['default-location'],
372                         'profile_image_url' => $item['author-avatar'],
373                         'url' => $item['author-link'],
374                         'contact_url' => 0,
375                         'protected' => false,   #
376                         'friends_count' => 0,
377                         'created_at' => '',
378                         'utc_offset' => 0, #XXX: fix me
379                         'time_zone' => '', //$uinfo[0]['timezone'],
380                         'geo_enabled' => false,
381                         'statuses_count' => 0,
382                         'lang' => 'en', #XXX: fix me
383                         'description' => '',
384                         'followers_count' => 0,
385                         'favourites_count' => 0,
386                         'contributors_enabled' => false,
387                         'follow_request_sent' => false,
388                         'profile_background_color' => 'cfe8f6',
389                         'profile_text_color' => '000000',
390                         'profile_link_color' => 'FF8500',
391                         'profile_sidebar_fill_color' =>'AD0066',
392                         'profile_sidebar_border_color' => 'AD0066',
393                         'profile_background_image_url' => '',
394                         'profile_background_tile' => false,
395                         'profile_use_background_image' => false,
396                         'notifications' => false,
397                         'verified' => true, #XXX: fix me
398                         'followers' => '', #XXX: fix me
399                         'status' => array()
400                 );
401
402                 return $ret; 
403         }
404
405
406         /**
407          *  load api $templatename for $type and replace $data array
408          */
409         function api_apply_template($templatename, $type, $data){
410
411                 $a = get_app();
412
413                 switch($type){
414                         case "atom":
415                         case "rss":
416                         case "xml":
417                                 $data = array_xmlify($data);
418                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
419                                 $ret = replace_macros($tpl, $data);
420                                 break;
421                         case "json":
422                                 $ret = $data;
423                                 break;
424                 }
425                 return $ret;
426         }
427         
428         /**
429          ** TWITTER API
430          */
431         
432         /**
433          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
434          * returns a 401 status code and an error message if not. 
435          * http://developer.twitter.com/doc/get/account/verify_credentials
436          */
437         function api_account_verify_credentials(&$a, $type){
438                 if (local_user()===false) return false;
439                 $user_info = api_get_user($a);
440                 
441                 return api_apply_template("user", $type, array('$user' => $user_info));
442
443         }
444         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
445                 
446
447         /**
448          * get data from $_POST or $_GET
449          */
450         function requestdata($k){
451                 if (isset($_POST[$k])){
452                         return $_POST[$k];
453                 }
454                 if (isset($_GET[$k])){
455                         return $_GET[$k];
456                 }
457                 return null;
458         }
459
460 /*Waitman Gobble Mod*/
461         function api_statuses_mediap(&$a, $type) {
462                 if (local_user()===false) {
463                         logger('api_statuses_update: no user');
464                         return false;
465                 }
466                 $user_info = api_get_user($a);
467
468                 $_REQUEST['type'] = 'wall';
469                 $_REQUEST['profile_uid'] = local_user();
470                 $_REQUEST['api_source'] = true;
471                 $txt = urldecode(requestdata('status'));
472
473                 require_once('library/HTMLPurifier.auto.php');
474                 require_once('include/html2bbcode.php');
475
476                 if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
477                         $txt = html2bb_video($txt);
478                         $config = HTMLPurifier_Config::createDefault();
479                         $config->set('Cache.DefinitionImpl', null);
480                         $purifier = new HTMLPurifier($config);
481                         $txt = $purifier->purify($txt);
482                 }
483                 $txt = html2bbcode($txt);
484                 
485                 $a->argv[1]=$user_info['screen_name']; //should be set to username?
486                 
487                 $_REQUEST['hush']='yeah'; //tell wall_upload function to return img info instead of echo
488                 require_once('mod/wall_upload.php');
489                 $bebop = wall_upload_post($a);
490                 
491                 //now that we have the img url in bbcode we can add it to the status and insert the wall item.
492                 $_REQUEST['body']=$txt."\n\n".$bebop;
493                 require_once('mod/item.php');
494                 item_post($a);
495
496                 // this should output the last post (the one we just posted).
497                 return api_status_show($a,$type);
498         }
499         api_register_func('api/statuses/mediap','api_statuses_mediap', true);
500 /*Waitman Gobble Mod*/
501
502
503         function api_statuses_update(&$a, $type) {
504                 if (local_user()===false) {
505                         logger('api_statuses_update: no user');
506                         return false;
507                 }
508                 $user_info = api_get_user($a);
509
510                 // convert $_POST array items to the form we use for web posts.
511
512                 // logger('api_post: ' . print_r($_POST,true));
513
514                 if(requestdata('htmlstatus')) {
515                         require_once('library/HTMLPurifier.auto.php');
516                         require_once('include/html2bbcode.php');
517
518                         $txt = requestdata('htmlstatus');
519                         if((strpos($txt,'<') !== false) || (strpos($txt,'>') !== false)) {
520
521                                 $txt = html2bb_video($txt);
522
523                                 $config = HTMLPurifier_Config::createDefault();
524                                 $config->set('Cache.DefinitionImpl', null);
525
526
527                                 $purifier = new HTMLPurifier($config);
528                                 $txt = $purifier->purify($txt);
529
530                                 $_REQUEST['body'] = html2bbcode($txt);
531                         }
532
533                 }
534                 else
535                         $_REQUEST['body'] = urldecode(requestdata('status'));
536
537                 $parent = requestdata('in_reply_to_status_id');
538                 if(ctype_digit($parent))
539                         $_REQUEST['parent'] = $parent;
540                 else
541                         $_REQUEST['parent_uri'] = $parent;
542
543                 if(requestdata('lat') && requestdata('long'))
544                         $_REQUEST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
545                 $_REQUEST['profile_uid'] = local_user();
546                 if(requestdata('parent'))
547                         $_REQUEST['type'] = 'net-comment';
548                 else
549                         $_REQUEST['type'] = 'wall';
550
551                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
552
553                 $_REQUEST['api_source'] = true;
554
555                 // call out normal post function
556
557                 require_once('mod/item.php');
558                 item_post($a);  
559
560                 // this should output the last post (the one we just posted).
561                 return api_status_show($a,$type);
562         }
563         api_register_func('api/statuses/update','api_statuses_update', true);
564
565
566         function api_status_show(&$a, $type){
567                 $user_info = api_get_user($a);
568                 // get last public wall message
569                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
570                                 FROM `item`, `contact`,
571                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
572                                 WHERE `item`.`contact-id` = %d
573                                         AND `i`.`id` = `item`.`parent`
574                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
575                                         AND `type`!='activity'
576                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
577                                 ORDER BY `created` DESC 
578                                 LIMIT 1",
579                                 intval($user_info['id'])
580                 );
581
582                 if (count($lastwall)>0){
583                         $lastwall = $lastwall[0];
584                         
585                         $in_reply_to_status_id = '';
586                         $in_reply_to_user_id = '';
587                         $in_reply_to_screen_name = '';
588                         if ($lastwall['parent']!=$lastwall['id']) {
589                                 $in_reply_to_status_id=$lastwall['parent'];
590                                 $in_reply_to_user_id = $lastwall['reply_uid'];
591                                 $in_reply_to_screen_name = $lastwall['reply_author'];
592                         }  
593                         $status_info = array(
594                                 'created_at' => api_date($lastwall['created']),
595                                 'id' => $lastwall['contact-id'],
596                                 'text' => strip_tags(bbcode($lastwall['body'])),
597                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
598                                 'truncated' => false,
599                                 'in_reply_to_status_id' => $in_reply_to_status_id,
600                                 'in_reply_to_user_id' => $in_reply_to_user_id,
601                                 'favorited' => false,
602                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
603                                 'geo' => '',
604                                 'coordinates' => $lastwall['coord'],
605                                 'place' => $lastwall['location'],
606                                 'contributors' => ''                                    
607                         );
608                         $status_info['user'] = $user_info;
609                 }
610                 return  api_apply_template("status", $type, array('$status' => $status_info));
611                 
612         }
613
614
615
616
617                 
618         /**
619          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
620          * The author's most recent status will be returned inline.
621          * http://developer.twitter.com/doc/get/users/show
622          */
623         function api_users_show(&$a, $type){
624                 $user_info = api_get_user($a);
625                 // get last public wall message
626                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
627                                 FROM `item`, `contact`,
628                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
629                                 WHERE `item`.`contact-id` = %d
630                                         AND `i`.`id` = `item`.`parent`
631                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
632                                         AND `type`!='activity'
633                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
634                                 ORDER BY `created` DESC 
635                                 LIMIT 1",
636                                 intval($user_info['id'])
637                 );
638
639                 if (count($lastwall)>0){
640                         $lastwall = $lastwall[0];
641                         
642                         $in_reply_to_status_id = '';
643                         $in_reply_to_user_id = '';
644                         $in_reply_to_screen_name = '';
645                         if ($lastwall['parent']!=$lastwall['id']) {
646                                 $in_reply_to_status_id=$lastwall['parent'];
647                                 $in_reply_to_user_id = $lastwall['reply_uid'];
648                                 $in_reply_to_screen_name = $lastwall['reply_author'];
649                         }  
650                         $user_info['status'] = array(
651                                 'created_at' => api_date($lastwall['created']),
652                                 'id' => $lastwall['contact-id'],
653                                 'text' => strip_tags(bbcode($lastwall['body'])),
654                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
655                                 'truncated' => false,
656                                 'in_reply_to_status_id' => $in_reply_to_status_id,
657                                 'in_reply_to_user_id' => $in_reply_to_user_id,
658                                 'favorited' => false,
659                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
660                                 'geo' => '',
661                                 'coordinates' => $lastwall['coord'],
662                                 'place' => $lastwall['location'],
663                                 'contributors' => ''                                    
664                         );
665                 }
666                 return  api_apply_template("user", $type, array('$user' => $user_info));
667                 
668         }
669         api_register_func('api/users/show','api_users_show');
670         
671         /**
672          * 
673          * http://developer.twitter.com/doc/get/statuses/home_timeline
674          * 
675          * TODO: Optional parameters
676          * TODO: Add reply info
677          */
678         function api_statuses_home_timeline(&$a, $type){
679                 if (local_user()===false) return false;
680                                 
681                 $user_info = api_get_user($a);
682                 // get last newtork messages
683
684
685                 // params
686                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
687                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
688                 if ($page<0) $page=0;
689                 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
690                 
691                 $start = $page*$count;
692
693                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
694                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
695                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
696                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
697                         FROM `item`, `contact`
698                         WHERE `item`.`uid` = %d
699                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
700                         AND `contact`.`id` = `item`.`contact-id`
701                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
702                         $sql_extra
703                         AND `item`.`id`>%d
704                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
705                         intval($user_info['uid']),
706                         intval($since_id),
707                         intval($start), intval($count)
708                 );
709
710                 $ret = api_format_items($r,$user_info);
711
712                 
713                 $data = array('$statuses' => $ret);
714                 switch($type){
715                         case "atom":
716                         case "rss":
717                                 $data = api_rss_extra($a, $data, $user_info);
718                 }
719                                 
720                 return  api_apply_template("timeline", $type, $data);
721         }
722         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
723         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
724
725
726
727         function api_statuses_user_timeline(&$a, $type){
728                 if (local_user()===false) return false;
729                 
730                 $user_info = api_get_user($a);
731                 // get last newtork messages
732
733
734                 logger("api_statuses_user_timeline: local_user: ". local_user() .
735                            "\nuser_info: ".print_r($user_info, true) .
736                            "\n_REQUEST:  ".print_r($_REQUEST, true),
737                            LOGGER_DEBUG);
738
739                 // params
740                 $count = (x($_REQUEST,'count')?$_REQUEST['count']:20);
741                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
742                 if ($page<0) $page=0;
743                 $since_id = 0;//$since_id = (x($_REQUEST,'since_id')?$_REQUEST['since_id']:0);
744                 
745                 $start = $page*$count;
746
747                 if ($user_info['self']==1) $sql_extra = "AND `item`.`wall` = 1 ";
748
749                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
750                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
751                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
752                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
753                         FROM `item`, `contact`
754                         WHERE `item`.`uid` = %d
755                         AND `item`.`contact-id` = %d
756                         AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
757                         AND `contact`.`id` = `item`.`contact-id`
758                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
759                         $sql_extra
760                         AND `item`.`id`>%d
761                         ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
762                         intval(local_user()),
763                         intval($user_info['id']),
764                         intval($since_id),
765                         intval($start), intval($count)
766                 );
767
768                 $ret = api_format_items($r,$user_info);
769
770                 
771                 $data = array('$statuses' => $ret);
772                 switch($type){
773                         case "atom":
774                         case "rss":
775                                 $data = api_rss_extra($a, $data, $user_info);
776                 }
777                                 
778                 return  api_apply_template("timeline", $type, $data);
779         }
780
781         api_register_func('api/statuses/user_timeline','api_statuses_user_timeline', true);
782
783
784         function api_favorites(&$a, $type){
785                 if (local_user()===false) return false;
786                 
787                 $user_info = api_get_user($a);
788                 // in friendica starred item are private
789                 // return favorites only for self
790                 logger('api_favorites: self:' . $user_info['self']);
791                 
792                 if ($user_info['self']==0) {
793                         $ret = array();
794                 } else {
795                         
796                         
797                         // params
798                         $count = (x($_GET,'count')?$_GET['count']:20);
799                         $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
800                         if ($page<0) $page=0;
801                         
802                         $start = $page*$count;
803
804                         $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
805                                 `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
806                                 `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
807                                 `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
808                                 FROM `item`, `contact`
809                                 WHERE `item`.`uid` = %d
810                                 AND `item`.`visible` = 1 and `item`.`moderated` = 0 AND `item`.`deleted` = 0
811                                 AND `item`.`starred` = 1
812                                 AND `contact`.`id` = `item`.`contact-id`
813                                 AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
814                                 $sql_extra
815                                 ORDER BY `item`.`received` DESC LIMIT %d ,%d ",
816                                 intval($user_info['uid']),
817                                 intval($start), intval($count)
818                         );
819
820                         $ret = api_format_items($r,$user_info);
821                 
822                 }
823                 
824                 $data = array('$statuses' => $ret);
825                 switch($type){
826                         case "atom":
827                         case "rss":
828                                 $data = api_rss_extra($a, $data, $user_info);
829                 }
830                                 
831                 return  api_apply_template("timeline", $type, $data);
832         }
833
834         api_register_func('api/favorites','api_favorites', true);
835
836         
837         function api_format_items($r,$user_info) {
838
839                 //logger('api_format_items: ' . print_r($r,true));
840
841                 //logger('api_format_items: ' . print_r($user_info,true));
842
843                 $a = get_app();
844                 $ret = Array();
845
846                 foreach($r as $item) {
847                         localize_item($item);
848                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_item_get_user($a,$item));
849                         $status = array(
850                                 'created_at'=> api_date($item['created']),
851                                 'published' => api_date($item['created']),
852                                 'updated'   => api_date($item['edited']),
853                                 'id'            => intval($item['id']),
854                                 'message_id' => $item['uri'],
855                                 'text'          => strip_tags(bbcode($item['body'])),
856                                 'statusnet_html'                => bbcode($item['body']),
857                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
858                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
859                                 'truncated' => False,
860                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']? intval($item['parent']):''),
861                                 'in_reply_to_user_id' => '',
862                                 'favorited' => $item['starred'] ? true : false,
863                                 'in_reply_to_screen_name' => '',
864                                 'geo' => '',
865                                 'coordinates' => $item['coord'],
866                                 'place' => $item['location'],
867                                 'contributors' => '',
868                                 'annotations'  => '',
869                                 'entities'  => '',
870                                 'user' =>  $status_user ,
871                                 'objecttype' => (($item['object-type']) ? $item['object-type'] : ACTIVITY_OBJ_NOTE),
872                                 'verb' => (($item['verb']) ? $item['verb'] : ACTIVITY_POST),
873                                 'self' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,
874                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$item['id'].".".$type,                                
875                         );
876                         $ret[]=$status;
877                 };
878                 return $ret;
879         }
880
881
882         function api_account_rate_limit_status(&$a,$type) {
883
884                 $hash = array(
885                           'remaining_hits' => (string) 150,
886                           'hourly_limit' => (string) 150,
887                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
888                           'reset_time_in_seconds' => strtotime('now + 1 hour')
889                 );
890
891                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
892
893         }
894         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
895
896         /**
897          *  https://dev.twitter.com/docs/api/1/get/statuses/friends 
898          *  This function is deprecated by Twitter
899          *  returns: json, xml 
900          **/
901         function api_statuses_f(&$a, $type, $qtype) {
902                 if (local_user()===false) return false;
903                 $user_info = api_get_user($a);
904                 
905                 
906                 // friends and followers only for self
907                 if ($user_info['self']==0){
908                         return false;
909                 }
910                 
911                 if (x($_GET,'cursor') && $_GET['cursor']=='undefined'){
912                         /* this is to stop Hotot to load friends multiple times
913                         *  I'm not sure if I'm missing return something or
914                         *  is a bug in hotot. Workaround, meantime
915                         */
916                         
917                         /*$ret=Array();
918                         return array('$users' => $ret);*/
919                         return false;
920                 }
921                 
922                 if($qtype == 'friends')
923                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
924                 if($qtype == 'followers')
925                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
926  
927                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
928                         intval(local_user())
929                 );
930
931                 $ret = array();
932                 foreach($r as $cid){
933                         $ret[] = api_get_user($a, $cid['id']);
934                 }
935
936                 
937                 return array('$users' => $ret);
938
939         }
940         function api_statuses_friends(&$a, $type){
941                 $data =  api_statuses_f($a,$type,"friends");
942                 if ($data===false) return false;
943                 return  api_apply_template("friends", $type, $data);
944         }
945         function api_statuses_followers(&$a, $type){
946                 $data = api_statuses_f($a,$type,"followers");
947                 if ($data===false) return false;
948                 return  api_apply_template("friends", $type, $data);
949         }
950         api_register_func('api/statuses/friends','api_statuses_friends',true);
951         api_register_func('api/statuses/followers','api_statuses_followers',true);
952
953
954
955
956
957
958         function api_statusnet_config(&$a,$type) {
959                 $name = $a->config['sitename'];
960                 $server = $a->get_hostname();
961                 $logo = $a->get_baseurl() . '/images/friendica-64.png';
962                 $email = $a->config['admin_email'];
963                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
964                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
965                 $textlimit = (string) (($a->config['max_import_size']) ? $a->config['max_import_size'] : 200000);
966                 if($a->config['api_import_size'])
967                         $texlimit = string($a->config['api_import_size']);
968                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
969                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
970
971                 $config = array(
972                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
973                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
974                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
975                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
976                                 'shorturllength' => '30'
977                         ),
978                 );  
979
980                 return api_apply_template('config', $type, array('$config' => $config));
981
982         }
983         api_register_func('api/statusnet/config','api_statusnet_config',false);
984
985         function api_statusnet_version(&$a,$type) {
986
987                 // liar
988
989                 if($type === 'xml') {
990                         header("Content-type: application/xml");
991                         echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<version>0.9.7</version>' . "\r\n";
992                         killme();
993                 }
994                 elseif($type === 'json') {
995                         header("Content-type: application/json");
996                         echo '"0.9.7"';
997                         killme();
998                 }
999         }
1000         api_register_func('api/statusnet/version','api_statusnet_version',false);
1001
1002
1003         function api_ff_ids(&$a,$type,$qtype) {
1004                 if(! local_user())
1005                         return false;
1006
1007                 if($qtype == 'friends')
1008                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_SHARING), intval(CONTACT_IS_FRIEND));
1009                 if($qtype == 'followers')
1010                         $sql_extra = sprintf(" AND ( `rel` = %d OR `rel` = %d ) ", intval(CONTACT_IS_FOLLOWER), intval(CONTACT_IS_FRIEND));
1011  
1012
1013                 $r = q("SELECT id FROM `contact` WHERE `uid` = %d AND `self` = 0 AND `blocked` = 0 AND `pending` = 0 $sql_extra",
1014                         intval(local_user())
1015                 );
1016
1017                 if(is_array($r)) {
1018                         if($type === 'xml') {
1019                                 header("Content-type: application/xml");
1020                                 echo '<?xml version="1.0" encoding="UTF-8"?>' . "\r\n" . '<ids>' . "\r\n";
1021                                 foreach($r as $rr)
1022                                         echo '<id>' . $rr['id'] . '</id>' . "\r\n";
1023                                 echo '</ids>' . "\r\n";
1024                                 killme();
1025                         }
1026                         elseif($type === 'json') {
1027                                 $ret = array();
1028                                 header("Content-type: application/json");
1029                                 foreach($r as $rr) $ret[] = $rr['id'];
1030                                 echo json_encode($ret);
1031                                 killme();
1032                         }
1033                 }
1034         }
1035
1036         function api_friends_ids(&$a,$type) {
1037                 api_ff_ids($a,$type,'friends');
1038         }
1039         function api_followers_ids(&$a,$type) {
1040                 api_ff_ids($a,$type,'followers');
1041         }
1042         api_register_func('api/friends/ids','api_friends_ids',true);
1043         api_register_func('api/followers/ids','api_followers_ids',true);
1044
1045
1046         function api_direct_messages_new(&$a, $type) {
1047                 if (local_user()===false) return false;
1048                 
1049                 if (!x($_POST, "text") || !x($_POST,"screen_name")) return;
1050                 
1051                 $sender = api_get_user($a);
1052                 
1053                 $r = q("SELECT `id` FROM `contact` WHERE `uid`=%d AND `nick`='%s'",
1054                                 intval(local_user()),
1055                                 dbesc($_POST['screen_name']));
1056                 
1057                 $recipient = api_get_user($a, $r[0]['id']);                     
1058                 
1059
1060                 require_once("include/message.php");
1061                 $sub = ( (strlen($_POST['text'])>10)?substr($_POST['text'],0,10)."...":$_POST['text']);
1062                 $id = send_message($recipient['id'], $_POST['text'], $sub);
1063                 
1064                 
1065                 if ($id>-1) {
1066                         $r = q("SELECT * FROM `mail` WHERE id=%d", intval($id));
1067                         $item = $r[0];
1068                         $ret=Array(
1069                                         'id' => $item['id'],
1070                                         'created_at'=> api_date($item['created']),
1071                                         'sender_id'=> $sender['id'] ,
1072                                         'sender_screen_name'=> $sender['screen_name'],
1073                                         'sender'=> $sender,
1074                                         'recipient_id'=> $recipient['id'],
1075                                         'recipient_screen_name'=> $recipient['screen_name'],
1076                                         'recipient'=> $recipient,
1077                                         
1078                                         'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1079                                         
1080                         );
1081                 
1082                 } else {
1083                         $ret = array("error"=>$id);     
1084                 }
1085                 
1086                 $data = Array('$messages'=>$ret);
1087                 
1088                 switch($type){
1089                         case "atom":
1090                         case "rss":
1091                                 $data = api_rss_extra($a, $data, $user_info);
1092                 }
1093                                 
1094                 return  api_apply_template("direct_messages", $type, $data);
1095                                 
1096         }
1097         api_register_func('api/direct_messages/new','api_direct_messages_new',true);
1098
1099     function api_direct_messages_box(&$a, $type, $box) {
1100                 if (local_user()===false) return false;
1101                 
1102                 $user_info = api_get_user($a);
1103                 
1104                 // params
1105                 $count = (x($_GET,'count')?$_GET['count']:20);
1106                 $page = (x($_REQUEST,'page')?$_REQUEST['page']-1:0);
1107                 if ($page<0) $page=0;
1108                 
1109                 $start = $page*$count;
1110                 
1111         
1112                 if ($box=="sentbox") {
1113                         $sql_extra = "`from-url`='%s'";
1114                 } else {
1115                         $sql_extra = "`from-url`!='%s'";
1116                 }
1117                 
1118                 $r = q("SELECT * FROM `mail` WHERE uid=%d AND $sql_extra ORDER BY created DESC LIMIT %d,%d",
1119                                 intval(local_user()),
1120                                 dbesc( $a->get_baseurl() . '/profile/' . $a->user['nickname'] ),
1121                                 intval($start), intval($count)
1122                            );
1123                 
1124                 $ret = Array();
1125                 foreach($r as $item){
1126                         switch ($box){
1127                                 case "inbox":
1128                                         $recipient = $user_info;
1129                                         $sender = api_get_user($a,$item['contact-id']);
1130                                         break;
1131                                 case "sentbox":
1132                                         $recipient = api_get_user($a,$item['contact-id']);
1133                                         $sender = $user_info;
1134                                         break;
1135                         }
1136                                 
1137                         $ret[]=Array(
1138                                 'id' => $item['id'],
1139                                 'created_at'=> api_date($item['created']),
1140                                 'sender_id'=> $sender['id'] ,
1141                                 'sender_screen_name'=> $sender['screen_name'],
1142                                 'sender'=> $sender,
1143                                 'recipient_id'=> $recipient['id'],
1144                                 'recipient_screen_name'=> $recipient['screen_name'],
1145                                 'recipient'=> $recipient,
1146                                 
1147                                 'text'=> $item['title']."\n".strip_tags(bbcode($item['body'])) ,
1148                                 
1149                         );
1150                         
1151                 }
1152                 
1153
1154                 $data = array('$messages' => $ret);
1155                 switch($type){
1156                         case "atom":
1157                         case "rss":
1158                                 $data = api_rss_extra($a, $data, $user_info);
1159                 }
1160                                 
1161                 return  api_apply_template("direct_messages", $type, $data);
1162                 
1163         }
1164
1165         function api_direct_messages_sentbox(&$a, $type){
1166                 return api_direct_messages_box($a, $type, "sentbox");
1167         }
1168         function api_direct_messages_inbox(&$a, $type){
1169                 return api_direct_messages_box($a, $type, "inbox");
1170         }
1171         api_register_func('api/direct_messages/sent','api_direct_messages_sentbox',true);
1172         api_register_func('api/direct_messages','api_direct_messages_inbox',true);
1173
1174
1175
1176         function api_oauth_request_token(&$a, $type){
1177                 try{
1178                         $oauth = new FKOAuth1();
1179                         $r = $oauth->fetch_request_token(OAuthRequest::from_request());
1180                 }catch(Exception $e){
1181                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1182                 }
1183                 echo $r;
1184                 killme();       
1185         }
1186         function api_oauth_access_token(&$a, $type){
1187                 try{
1188                         $oauth = new FKOAuth1();
1189                         $r = $oauth->fetch_access_token(OAuthRequest::from_request());
1190                 }catch(Exception $e){
1191                         echo "error=". OAuthUtil::urlencode_rfc3986($e->getMessage()); killme();
1192                 }
1193                 echo $r;
1194                 killme();                       
1195         }
1196
1197         api_register_func('api/oauth/request_token', 'api_oauth_request_token', false);
1198         api_register_func('api/oauth/access_token', 'api_oauth_access_token', false);
1199
1200