]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge remote-tracking branch 'friendika/master'
[friendica.git] / include / api.php
1 <?php
2         require_once("bbcode.php");
3         require_once("datetime.php");
4         
5         /* 
6          * Twitter-Like API
7          *  
8          */
9
10         $API = Array();
11          
12
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         function api_login(&$a){
30                 // workaround for HTTP-auth in CGI mode
31                 if(x($_SERVER,'REDIRECT_REMOTE_USER')) {
32                         $userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"],6)) ;
33                         if(strlen($userpass)) {
34                                 list($name, $password) = explode(':', $userpass);
35                                 $_SERVER['PHP_AUTH_USER'] = $name;
36                                 $_SERVER['PHP_AUTH_PW'] = $password;
37                         }
38                 }
39
40                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
41                    logger('API_login: ' . print_r($_SERVER,true), LOGGER_DEBUG);
42                     header('WWW-Authenticate: Basic realm="Friendika"');
43                     header('HTTP/1.0 401 Unauthorized');
44                     die('This api requires login');
45                 }
46                 
47                 $user = $_SERVER['PHP_AUTH_USER'];
48                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
49                 
50                 
51                         /**
52                          *  next code from mod/auth.php. needs better solution
53                          */
54                         
55                 // process normal login request
56
57                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) 
58                         AND `password` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1",
59                         dbesc(trim($user)),
60                         dbesc(trim($user)),
61                         dbesc($encrypted)
62                 );
63                 if(count($r)){
64                         $record = $r[0];
65                 } else {
66                    logger('API_login failure: ' . print_r($_SERVER,true), LOGGER_DEBUG);
67                     header('WWW-Authenticate: Basic realm="Friendika"');
68                     header('HTTP/1.0 401 Unauthorized');
69                     die('This api requires login');
70                 }
71                 $_SESSION['uid'] = $record['uid'];
72                 $_SESSION['theme'] = $record['theme'];
73                 $_SESSION['authenticated'] = 1;
74                 $_SESSION['page_flags'] = $record['page-flags'];
75                 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
76                 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
77
78                 //notice( t("Welcome back ") . $record['username'] . EOL);
79                 $a->user = $record;
80
81                 if(strlen($a->user['timezone'])) {
82                         date_default_timezone_set($a->user['timezone']);
83                         $a->timezone = $a->user['timezone'];
84                 }
85
86                 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
87                         intval($_SESSION['uid']));
88                 if(count($r)) {
89                         $a->contact = $r[0];
90                         $a->cid = $r[0]['id'];
91                         $_SESSION['cid'] = $a->cid;
92                 }
93                 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
94                         dbesc(datetime_convert()),
95                         intval($_SESSION['uid'])
96                 );
97
98                 call_hooks('logged_in', $a->user);
99
100                 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
101         }
102         
103         /**************************
104          *  MAIN API ENTRY POINT  *
105          **************************/
106         function api_call(&$a){
107                 GLOBAL $API;
108                 foreach ($API as $p=>$info){
109                         if (strpos($a->query_string, $p)===0){
110                                 #unset($_SERVER['PHP_AUTH_USER']);
111                                 if ($info['auth']===true && local_user()===false) {
112                                                 api_login($a);
113                                 }
114                 
115                                 $type="json";           
116                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
117                                 if (strpos($a->query_string, ".json")>0) $type="json";
118                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
119                                 if (strpos($a->query_string, ".atom")>0) $type="atom";                          
120                                 
121                                 $r = call_user_func($info['func'], $a, $type);
122                                 if ($r===false) return;
123
124                                 switch($type){
125                                         case "xml":
126                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
127                                                 header ("Content-Type: text/xml");
128                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
129                                                 break;
130                                         case "json": 
131                                                 header ("Content-Type: application/json");  
132                                                 foreach($r as $rr)
133                                                     return json_encode($rr);
134                                                 break;
135                                         case "rss":
136                                                 header ("Content-Type: application/rss+xml");
137                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
138                                                 break;
139                                         case "atom":
140                                                 header ("Content-Type: application/atom+xml");
141                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
142                                                 break;
143                                                 
144                                 }
145                                 //echo "<pre>"; var_dump($r); die();
146                         }
147                 }
148                 return false;
149         }
150
151         /**
152          * RSS extra info
153          */
154         function api_rss_extra(&$a, $arr, $user_info){
155                 if (is_null($user_info)) $user_info = api_get_user($a);
156                 $arr['$user'] = $user_info;
157                 $arr['$rss'] = array(
158                         'alternate' => $user_info['url'],
159                         'self' => $a->get_baseurl(). "/". $a->query_string,
160                         'updated' => api_date(null),
161                         'language' => $user_info['language'],
162                         'logo'  => $a->get_baseurl()."/images/friendika-32.png",
163                 );
164                 
165                 return $arr;
166         }
167          
168         /**
169          * Returns user info array.
170          */
171         function api_get_user(&$a, $contact_id=Null){
172                 $user = null;
173                 $extra_query = "";
174                 if(!is_null($contact_id)){
175                         $user=$contact_id;
176                         $extra_query = "AND `contact`.`id` = %d ";
177                 }
178                 
179                 if(is_null($user) && x($_GET, 'user_id')) {
180                         $user = intval($_GET['user_id']);       
181                         $extra_query = "AND `contact`.`id` = %d ";
182                 }
183                 if(is_null($user) && x($_GET, 'screen_name')) {
184                         $user = dbesc($_GET['screen_name']);    
185                         $extra_query = "AND `contact`.`nick` = '%s' ";
186                 }
187                 
188                 if (is_null($user)){
189                         list($user, $null) = explode(".",$a->argv[3]);
190                         if(is_numeric($user)){
191                                 $user = intval($user);
192                                 $extra_query = "AND `contact`.`id` = %d ";
193                         } else {
194                                 $user = dbesc($user);
195                                 $extra_query = "AND `contact`.`nick` = '%s' ";
196                         }
197                 }
198                 
199                 if ($user==='') {
200                         if (local_user()===false) {
201                                 api_login($a); return False;
202                         } else {
203                                 $user = $_SESSION['uid'];
204                                 $extra_query = "AND `contact`.`uid` = %d ";
205                         }
206                         
207                 }
208                 
209
210                 // user info            
211                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `contact`
212                                 WHERE 1
213                                 $extra_query",
214                                 $user
215                 );
216                 if (count($uinfo)==0) {
217                         return False;
218                 }
219                 
220                 // count public wall messages
221                 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
222                                 WHERE  `uid` = %d
223                                 AND `type`='wall' 
224                                 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
225                                 intval($uinfo[0]['uid'])
226                 );
227                 $countitms = $r[0]['count'];
228                 
229                 // count friends
230                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
231                                 WHERE  `uid` = %d
232                                 AND `self`=0 AND `blocked`=0", 
233                                 intval($uinfo[0]['uid'])
234                 );
235                 $countfriends = $r[0]['count'];
236                                 
237
238                 $ret = Array(
239                         'uid' => $uinfo[0]['uid'],
240                         'id' => $uinfo[0]['cid'],
241                         'name' => $uinfo[0]['name'],
242                         'screen_name' => $uinfo[0]['nick'],
243                         'location' => '', //$uinfo[0]['default-location'],
244                         'profile_image_url' => $uinfo[0]['micro'],
245                         'url' => $uinfo[0]['url'],
246                         'contact_url' => $a->get_baseurl()."/contacts/".$uinfo[0]['cid'],
247                         'protected' => false,   #
248                         'friends_count' => $countfriends,
249                         'created_at' => api_date($uinfo[0]['name-date']),
250                         'utc_offset' => 0, #XXX: fix me
251                         'time_zone' => '', //$uinfo[0]['timezone'],
252                         'geo_enabled' => false,
253                         'statuses_count' => $countitms, #XXX: fix me 
254                         'lang' => 'en', #XXX: fix me
255                         'description' => '',
256                         'followers_count' => $countfriends, #XXX: fix me
257                         'favourites_count' => 0,
258                         'contributors_enabled' => false,
259                         'follow_request_sent' => false,
260                         'profile_background_color' => 'cfe8f6',
261                         'profile_text_color' => '000000',
262                         'profile_link_color' => 'FF8500',
263                         'profile_sidebar_fill_color' =>'AD0066',
264                         'profile_sidebar_border_color' => 'AD0066',
265                         'profile_background_image_url' => '',
266                         'profile_background_tile' => false,
267                         'profile_use_background_image' => false,
268                         'notifications' => false,
269                         'verified' => true, #XXX: fix me
270                         'followers' => '', #XXX: fix me
271                         #'status' => null
272                 );
273         
274                 return $ret;
275                 
276         }
277
278         /**
279          * apply xmlify() to all values of array $val, recursively
280          */
281         function api_xmlify($val){
282                 if (is_bool($val)) return $val?"true":"false";
283                 if (is_array($val)) return array_map('api_xmlify', $val);
284                 return xmlify($val);
285         }
286
287         /**
288          *  load api $templatename for $type and replace $data array
289          */
290         function api_apply_template($templatename, $type, $data){
291
292                 switch($type){
293                         case "rss":
294                         case "atom":
295                         case "xml":
296                                 $data = api_xmlify($data);
297                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
298                                 $ret = replace_macros($tpl, $data);
299                                 break;
300                         case "json":
301                                 $ret = $data;
302                                 break;
303                 }
304                 return $ret;
305         }
306         
307         /**
308          ** TWITTER API
309          */
310         
311         /**
312          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
313          * returns a 401 status code and an error message if not. 
314          * http://developer.twitter.com/doc/get/account/verify_credentials
315          */
316         function api_account_verify_credentials(&$a, $type){
317                 if (local_user()===false) return false;
318                 $user_info = api_get_user($a);
319                 
320                 return api_apply_template("user", $type, array('$user' => $user_info));
321
322         }
323         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
324                 
325
326         /**
327          * get data from $_POST or $_GET
328          */
329         function requestdata($k){
330                 if (isset($_POST[$k])){
331                         return $_POST[$k];
332                 }
333                 if (isset($_GET[$k])){
334                         return $_GET[$k];
335                 }
336                 return null;
337         }
338         // TODO - media uploads
339         function api_statuses_update(&$a, $type) {
340                 if (local_user()===false) return false;
341                 $user_info = api_get_user($a);
342
343                 // convert $_POST array items to the form we use for web posts.
344
345                 $_POST['body'] = urldecode(requestdata('status'));
346                 $_POST['parent'] = requestdata('in_reply_to_status_id');
347                 if(requestdata('lat') && requestdata('long'))
348                         $_POST['coord'] = sprintf("%s %s",requestdata('lat'),requestdata('long'));
349                 $_POST['profile_uid'] = local_user();
350                 if(requestdata('parent'))
351                         $_POST['type'] = 'net-comment';
352                 else
353                         $_POST['type'] = 'wall';
354
355                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
356
357                 $_POST['api_source'] = true;
358
359                 // call out normal post function
360
361                 require_once('mod/item.php');
362                 item_post($a);  
363
364                 // this should output the last post (the one we just posted).
365                 return api_status_show($a,$type);
366         }
367         api_register_func('api/statuses/update','api_statuses_update', true);
368
369
370         function api_status_show(&$a, $type){
371                 $user_info = api_get_user($a);
372                 // get last public wall message
373                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
374                                 FROM `item`, `contact`,
375                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
376                                 WHERE `item`.`contact-id` = %d
377                                         AND `i`.`id` = `item`.`parent`
378                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
379                                         AND `type`!='activity'
380                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
381                                 ORDER BY `created` DESC 
382                                 LIMIT 1",
383                                 intval($user_info['id'])
384                 );
385
386                 if (count($lastwall)>0){
387                         $lastwall = $lastwall[0];
388                         
389                         $in_reply_to_status_id = '';
390                         $in_reply_to_user_id = '';
391                         $in_reply_to_screen_name = '';
392                         if ($lastwall['parent']!=$lastwall['id']) {
393                                 $in_reply_to_status_id=$lastwall['parent'];
394                                 $in_reply_to_user_id = $lastwall['reply_uid'];
395                                 $in_reply_to_screen_name = $lastwall['reply_author'];
396                         }  
397                         $status_info = array(
398                                 'created_at' => api_date($lastwall['created']),
399                                 'id' => $lastwall['contact-id'],
400                                 'text' => strip_tags(bbcode($lastwall['body'])),
401                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
402                                 'truncated' => false,
403                                 'in_reply_to_status_id' => $in_reply_to_status_id,
404                                 'in_reply_to_user_id' => $in_reply_to_user_id,
405                                 'favorited' => false,
406                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
407                                 'geo' => '',
408                                 'coordinates' => $lastwall['coord'],
409                                 'place' => $lastwall['location'],
410                                 'contributors' => ''                                    
411                         );
412                         $status_info['user'] = $user_info;
413                 }
414                 return  api_apply_template("status", $type, array('$status' => $status_info));
415                 
416         }
417
418
419
420
421                 
422         /**
423          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
424          * The author's most recent status will be returned inline.
425          * http://developer.twitter.com/doc/get/users/show
426          */
427         function api_users_show(&$a, $type){
428                 $user_info = api_get_user($a);
429                 // get last public wall message
430                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
431                                 FROM `item`, `contact`,
432                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
433                                 WHERE `item`.`contact-id` = %d
434                                         AND `i`.`id` = `item`.`parent`
435                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
436                                         AND `type`!='activity'
437                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
438                                 ORDER BY `created` DESC 
439                                 LIMIT 1",
440                                 intval($user_info['id'])
441                 );
442
443                 if (count($lastwall)>0){
444                         $lastwall = $lastwall[0];
445                         
446                         $in_reply_to_status_id = '';
447                         $in_reply_to_user_id = '';
448                         $in_reply_to_screen_name = '';
449                         if ($lastwall['parent']!=$lastwall['id']) {
450                                 $in_reply_to_status_id=$lastwall['parent'];
451                                 $in_reply_to_user_id = $lastwall['reply_uid'];
452                                 $in_reply_to_screen_name = $lastwall['reply_author'];
453                         }  
454                         $user_info['status'] = array(
455                                 'created_at' => api_date($lastwall['created']),
456                                 'id' => $lastwall['contact-id'],
457                                 'text' => strip_tags(bbcode($lastwall['body'])),
458                                 'source' => (($lastwall['app']) ? $lastwall['app'] : 'web'),
459                                 'truncated' => false,
460                                 'in_reply_to_status_id' => $in_reply_to_status_id,
461                                 'in_reply_to_user_id' => $in_reply_to_user_id,
462                                 'favorited' => false,
463                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
464                                 'geo' => '',
465                                 'coordinates' => $lastwall['coord'],
466                                 'place' => $lastwall['location'],
467                                 'contributors' => ''                                    
468                         );
469                 }
470                 return  api_apply_template("user", $type, array('$user' => $user_info));
471                 
472         }
473         api_register_func('api/users/show','api_users_show');
474         
475         /**
476          * 
477          * http://developer.twitter.com/doc/get/statuses/home_timeline
478          * 
479          * TODO: Optional parameters
480          * TODO: Add reply info
481          */
482         function api_statuses_home_timeline(&$a, $type){
483                 if (local_user()===false) return false;
484                 
485                 $user_info = api_get_user($a);
486                 // get last newtork messages
487                 $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
488
489                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
490                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
491                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
492                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
493                         FROM `item`, `contact`
494                         WHERE `item`.`uid` = %d
495                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
496                         AND `contact`.`id` = `item`.`contact-id`
497                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
498                         $sql_extra
499                         ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
500                         intval($user_info['uid']),
501                         0,20
502                 );
503                 $ret = Array();
504
505                 foreach($r as $item) {
506                         $status_user = (($item['cid']==$user_info['id'])?$user_info: api_get_user($a,$item['cid']));
507                         $status = array(
508                                 'created_at'=> api_date($item['created']),
509                                 'published' => datetime_convert('UTC','UTC',$item['created'],ATOM_TIME),
510                                 'updated'   => datetime_convert('UTC','UTC',$item['edited'],ATOM_TIME),
511                                 'id'            => $item['id'],
512                                 'text'          => strip_tags(bbcode($item['body'])),
513                                 'html'          => bbcode($item['body']),
514                                 'source'    => (($item['app']) ? $item['app'] : 'web'),
515                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
516                                 'truncated' => False,
517                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
518                                 'in_reply_to_user_id' => '',
519                                 'favorited' => false,
520                                 'in_reply_to_screen_name' => '',
521                                 'geo' => '',
522                                 'coordinates' => $item['coord'],
523                                 'place' => $item['location'],
524                                 'contributors' => '',
525                                 'annotations'  => '',
526                                 'entities'  => '',
527                                 'user' =>  $status_user ,
528                                 'objecttype' => $item['object-type'],
529                                 'verb' => $item['verb'],
530                                 'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
531                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,                         
532                         );
533                         $ret[]=$status;
534                 };
535                 
536                 $data = array('$statuses' => $ret);
537                 switch($type){
538                         case "atom":
539                         case "rss":
540                                 $data = api_rss_extra($a, $data, $user_info);
541                 }
542                                 
543                 return  api_apply_template("timeline", $type, $data);
544         }
545         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
546         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
547         api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
548         # TODO: user_timeline should be profile view
549         
550
551         function api_account_rate_limit_status(&$a,$type) {
552
553                 $hash = array(
554                           'remaining_hits' => (string) 150,
555                           'hourly_limit' => (string) 150,
556                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
557                           'reset_time_in_seconds' => strtotime('now + 1 hour')
558                 );
559
560                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
561
562         }
563         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);
564
565
566         function api_statusnet_config(&$a,$type) {
567                 $name = $a->config['sitename'];
568                 $server = $a->get_hostname();
569                 $logo = $a->get_baseurl() . '/images/friendika-64.png';
570                 $email = $a->config['admin_email'];
571                 $closed = (($a->config['register_policy'] == REGISTER_CLOSED) ? 'true' : 'false');
572                 $private = (($a->config['system']['block_public']) ? 'true' : 'false');
573                 $textlimit = (($a->config['max_import_size']) ? $a->config['max_import_size'] : '200000');
574                 $ssl = (($a->config['system']['have_ssl']) ? 'true' : 'false');
575                 $sslserver = (($ssl === 'true') ? str_replace('http:','https:',$a->get_baseurl()) : '');
576
577                 $config = array(
578                         'site' => array('name' => $name,'server' => $server, 'theme' => 'default', 'path' => '',
579                                 'logo' => $logo, 'fancy' => 'true', 'language' => 'en', 'email' => $email, 'broughtby' => '',
580                                 'broughtbyurl' => '', 'timezone' => 'UTC', 'closed' => $closed, 'inviteonly' => 'false',
581                                 'private' => $private, 'textlimit' => $textlimit, 'sslserver' => $sslserver, 'ssl' => $ssl,
582                                 'shorturllength' => '30'
583                         ),
584                 );  
585
586                 return api_apply_template('config', $type, array('$config' => $config));
587
588         }
589         api_register_func('api/statusnet/config','api_statusnet_config',true);
590