]> git.mxchange.org Git - friendica.git/blob - include/api.php
add rate limit call so spaz will work
[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['$rss'] = array(
157                         'alternate' => $user_info['url'],
158                         'self' => $a->get_baseurl(). "/". $a->query_string,
159                         'updated' => api_date(null),
160                         'language' => $user_info['language'],
161                         'logo'  => $a->get_baseurl()."/images/friendika-32.png",
162                 );
163                 
164                 return $arr;
165         }
166          
167         /**
168          * Returns user info array.
169          */
170         function api_get_user(&$a){
171                 $user = null;
172                 $extra_query = "";
173                 if(x($_GET, 'user_id')) {
174                         $user = intval($_GET['user_id']);       
175                         $extra_query = "AND `contact`.`id` = %d ";
176                 }
177                 if(x($_GET, 'screen_name')) {
178                         $user = dbesc($_GET['screen_name']);    
179                         $extra_query = "AND `contact`.`nick` = '%s' ";
180                 }
181                 
182                 if ($user===null){
183                         list($user, $null) = explode(".",$a->argv[3]);
184                         if(is_numeric($user)){
185                                 $user = intval($user);
186                                 $extra_query = "AND `contact`.`id` = %d ";
187                         } else {
188                                 $user = dbesc($user);
189                                 $extra_query = "AND `contact`.`nick` = '%s' ";
190                         }
191                 }
192                 
193                 if ($user==='') {
194                         if (local_user()===false) {
195                                 api_login($a); return False;
196                         } else {
197                                 $user = $_SESSION['uid'];
198                                 $extra_query = "AND `user`.`uid` = %d ";
199                         }
200                         
201                 }
202                 
203
204                 // user info            
205                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `user`, `contact`
206                                 WHERE `user`.`uid`=`contact`.`uid` AND `contact`.`self`=1
207                                 $extra_query",
208                                 $user
209                 );
210                 if (count($uinfo)==0) {
211                         return False;
212                 }
213                 
214                 // count public wall messages
215                 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
216                                 WHERE  `uid` = %d
217                                 AND `type`='wall' 
218                                 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
219                                 intval($uinfo[0]['uid'])
220                 );
221                 $countitms = $r[0]['count'];
222                 
223                 // count friends
224                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
225                                 WHERE  `uid` = %d
226                                 AND `self`=0 AND `blocked`=0", 
227                                 intval($uinfo[0]['uid'])
228                 );
229                 $countfriends = $r[0]['count'];
230                                 
231
232                 $ret = Array(
233                         'id' => $uinfo[0]['cid'],
234                         'name' => $uinfo[0]['username'],
235                         'screen_name' => $uinfo[0]['nickname'],
236                         'location' => $uinfo[0]['default-location'],
237                         'profile_image_url' => $uinfo[0]['micro'],
238                         'url' => $uinfo[0]['url'],
239                         'protected' => false,   #
240                         'friends_count' => $countfriends,
241                         'created_at' => api_date($uinfo[0]['created']),
242                         'utc_offset' => 0, #XXX: fix me
243                         'time_zone' => $uinfo[0]['timezone'],
244                         'geo_enabled' => false,
245                         'statuses_count' => $countitms, #XXX: fix me 
246                         'lang' => 'en', #XXX: fix me
247                         'description' => '',
248                         'followers_count' => $countfriends, #XXX: fix me
249                         'favourites_count' => 0,
250                         'contributors_enabled' => false,
251                         'follow_request_sent' => false,
252                         'profile_background_color' => 'cfe8f6',
253                         'profile_text_color' => '000000',
254                         'profile_link_color' => 'FF8500',
255                         'profile_sidebar_fill_color' =>'AD0066',
256                         'profile_sidebar_border_color' => 'AD0066',
257                         'profile_background_image_url' => '',
258                         'profile_background_tile' => false,
259                         'profile_use_background_image' => false,
260                         'notifications' => false,
261                         'verified' => true, #XXX: fix me
262                         'followers' => '', #XXX: fix me
263                         #'status' => null
264                 );
265         
266                 return $ret;
267                 
268         }
269
270         /**
271          * apply xmlify() to all values of array $val, recursively
272          */
273         function api_xmlify($val){
274                 if (is_bool($val)) return $val?"true":"false";
275                 if (is_array($val)) return array_map('api_xmlify', $val);
276                 return xmlify($val);
277         }
278
279         /**
280          *  load api $templatename for $type and replace $data array
281          */
282         function api_apply_template($templatename, $type, $data){
283
284                 switch($type){
285                         case "rss":
286                         case "atom":
287                         case "xml":
288                                 $data = api_xmlify($data);
289                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
290                                 $ret = replace_macros($tpl, $data);
291                                 break;
292                         case "json":
293                                 $ret = $data;
294                                 break;
295                 }
296                 return $ret;
297         }
298         
299         /**
300          ** TWITTER API
301          */
302         
303         /**
304          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
305          * returns a 401 status code and an error message if not. 
306          * http://developer.twitter.com/doc/get/account/verify_credentials
307          */
308         function api_account_verify_credentials(&$a, $type){
309                 if (local_user()===false) return false;
310                 $user_info = api_get_user($a);
311                 
312                 return api_apply_template("user", $type, array('$user' => $user_info));
313
314         }
315         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
316                 
317
318         // TODO - media uploads and alternate 'source'
319         
320         function api_statuses_update(&$a, $type) {
321                 if (local_user()===false) return false;
322                 $user_info = api_get_user($a);
323
324                 // convert $_POST array items to the form we use for web posts.
325
326                 $_POST['body'] = urldecode($_POST['status']);
327                 $_POST['parent'] = $_POST['in_reply_to_status_id'];
328                 if($_POST['lat'] && $_POST['long'])
329                         $_POST['coord'] = sprintf("%s %s",$_POST['lat'],$_POST['long']);
330                 $_POST['profile_uid'] = local_user();
331                 if($_POST['parent'])
332                         $_POST['type'] = 'net-comment';
333                 else
334                         $_POST['type'] = 'wall';
335
336                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
337
338                 $_POST['api_source'] = true;
339
340                 // call out normal post function
341
342                 require_once('mod/item.php');
343                 item_post($a);  
344
345                 // this should output the last post (the one we just posted).
346                 return api_status_show($a,$type);
347         }
348         api_register_func('api/statuses/update','api_statuses_update', true);
349
350
351         function api_status_show(&$a, $type){
352                 $user_info = api_get_user($a);
353                 // get last public wall message
354                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
355                                 FROM `item`, `contact`,
356                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
357                                 WHERE `item`.`contact-id` = %d
358                                         AND `i`.`id` = `item`.`parent`
359                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
360                                         AND `type`!='activity'
361                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
362                                 ORDER BY `created` DESC 
363                                 LIMIT 1",
364                                 intval($user_info['id'])
365                 );
366
367                 if (count($lastwall)>0){
368                         $lastwall = $lastwall[0];
369                         
370                         $in_reply_to_status_id = '';
371                         $in_reply_to_user_id = '';
372                         $in_reply_to_screen_name = '';
373                         if ($lastwall['parent']!=$lastwall['id']) {
374                                 $in_reply_to_status_id=$lastwall['parent'];
375                                 $in_reply_to_user_id = $lastwall['reply_uid'];
376                                 $in_reply_to_screen_name = $lastwall['reply_author'];
377                         }  
378                         $status_info = array(
379                                 'created_at' => api_date($lastwall['created']),
380                                 'id' => $lastwall['contact-id'],
381                                 'text' => strip_tags(bbcode($lastwall['body'])),
382                                 'source' => 'web',
383                                 'truncated' => false,
384                                 'in_reply_to_status_id' => $in_reply_to_status_id,
385                                 'in_reply_to_user_id' => $in_reply_to_user_id,
386                                 'favorited' => false,
387                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
388                                 'geo' => '',
389                                 'coordinates' => $lastwall['coord'],
390                                 'place' => $lastwall['location'],
391                                 'contributors' => ''                                    
392                         );
393                         $status_info['user'] = $user_info;
394                 }
395                 return  api_apply_template("status", $type, array('$status' => $status_info));
396                 
397         }
398
399
400
401
402                 
403         /**
404          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
405          * The author's most recent status will be returned inline.
406          * http://developer.twitter.com/doc/get/users/show
407          */
408         function api_users_show(&$a, $type){
409                 $user_info = api_get_user($a);
410                 // get last public wall message
411                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
412                                 FROM `item`, `contact`,
413                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
414                                 WHERE `item`.`contact-id` = %d
415                                         AND `i`.`id` = `item`.`parent`
416                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
417                                         AND `type`!='activity'
418                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
419                                 ORDER BY `created` DESC 
420                                 LIMIT 1",
421                                 intval($user_info['id'])
422                 );
423
424                 if (count($lastwall)>0){
425                         $lastwall = $lastwall[0];
426                         
427                         $in_reply_to_status_id = '';
428                         $in_reply_to_user_id = '';
429                         $in_reply_to_screen_name = '';
430                         if ($lastwall['parent']!=$lastwall['id']) {
431                                 $in_reply_to_status_id=$lastwall['parent'];
432                                 $in_reply_to_user_id = $lastwall['reply_uid'];
433                                 $in_reply_to_screen_name = $lastwall['reply_author'];
434                         }  
435                         $user_info['status'] = array(
436                                 'created_at' => api_date($lastwall['created']),
437                                 'id' => $lastwall['contact-id'],
438                                 'text' => strip_tags(bbcode($lastwall['body'])),
439                                 'source' => 'web',
440                                 'truncated' => false,
441                                 'in_reply_to_status_id' => $in_reply_to_status_id,
442                                 'in_reply_to_user_id' => $in_reply_to_user_id,
443                                 'favorited' => false,
444                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
445                                 'geo' => '',
446                                 'coordinates' => $lastwall['coord'],
447                                 'place' => $lastwall['location'],
448                                 'contributors' => ''                                    
449                         );
450                 }
451                 return  api_apply_template("user", $type, array('$user' => $user_info));
452                 
453         }
454         api_register_func('api/users/show','api_users_show');
455         
456         /**
457          * 
458          * http://developer.twitter.com/doc/get/statuses/home_timeline
459          * 
460          * TODO: Optional parameters
461          * TODO: Add reply info
462          */
463         function api_statuses_home_timeline(&$a, $type){
464                 if (local_user()===false) return false;
465                 
466                 $user_info = api_get_user($a);
467                 
468                 // get last newtork messages
469                 $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
470
471                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
472                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
473                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
474                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
475                         FROM `item`, `contact`, `user`
476                         WHERE `item`.`contact-id` = %d AND `user`.`uid` = `item`.`uid` 
477                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
478                         AND `contact`.`id` = `item`.`contact-id`
479                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
480                         $sql_extra
481                         ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
482                         intval($user_info['id']),
483                         0,20
484                 );
485                 $ret = Array();
486
487                 foreach($r as $item) {
488                         $status = array(
489                                 'created_at'=> api_date($item['created']),
490                                 'published' => datetime_convert('UTC','UTC',$item['created'],ATOM_TIME),
491                                 'updated'   => datetime_convert('UTC','UTC',$item['edited'],ATOM_TIME),
492                                 'id'            => $item['id'],
493                                 'text'          => strip_tags(bbcode($item['body'])),
494                                 'html'          => bbcode($item['body']),
495                                 'source'        => 'web',
496                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
497                                 'truncated' => False,
498                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
499                                 'in_reply_to_user_id' => '',
500                                 'favorited' => false,
501                                 'in_reply_to_screen_name' => '',
502                                 'geo' => '',
503                                 'coordinates' => $item['coord'],
504                                 'place' => $item['location'],
505                                 'contributors' => '',
506                                 'annotations'  => '',
507                                 'entities'  => '',
508                                 'user' =>  $user_info,
509                                 'objecttype' => $item['object-type'],
510                                 'verb' => $item['verb'],
511                                 'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
512                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,                         
513                         );
514                         $ret[]=$status;
515                 };
516                 
517                 $data = array('$statuses' => $ret);
518                 switch($type){
519                         case "atom":
520                         case "rss":
521                                 $data = api_rss_extra($a, $data, $user_info);
522                 }
523                                 
524                 return  api_apply_template("timeline", $type, $data);
525         }
526         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
527         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
528         api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
529         # TODO: user_timeline should be profile view
530         
531
532         function api_account_rate_limit_status(&$a,$type) {
533
534                 $hash = array(
535                           'remaining_hits' => (string) 150,
536                           'hourly_limit' => (string) 150,
537                           'reset_time' => datetime_convert('UTC','UTC','now + 1 hour',ATOM_TIME),
538                           'reset_time_in_seconds' => strtotime('now + 1 hour')
539                 );
540
541                 return api_apply_template('ratelimit', $type, array('$hash' => $hash));
542
543         }
544         api_register_func('api/account/rate_limit_status','api_account_rate_limit_status',true);