]> git.mxchange.org Git - friendica.git/blob - include/api.php
ef41c411c5b6550e908f222d3177f02de552a3aa
[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                 if (!isset($_SERVER['PHP_AUTH_USER'])) {
31                     header('WWW-Authenticate: Basic realm="Friendika"');
32                     header('HTTP/1.0 401 Unauthorized');
33                     die('This api require login');
34                 }
35                 
36                 $user = $_SERVER['PHP_AUTH_USER'];
37                 $encrypted = hash('whirlpool',trim($_SERVER['PHP_AUTH_PW']));
38                 
39                 
40                         /**
41                          *  next code from mod/auth.php. needs better solution
42                          */
43                         
44                 // process normal login request
45
46                 $r = q("SELECT * FROM `user` WHERE ( `email` = '%s' OR `nickname` = '%s' ) 
47                         AND `password` = '%s' AND `blocked` = 0 AND `verified` = 1 LIMIT 1",
48                         dbesc(trim($user)),
49                         dbesc(trim($user)),
50                         dbesc($encrypted)
51                 );
52                 if(count($r)){
53                         $record = $r[0];
54                 } else {
55                     header('WWW-Authenticate: Basic realm="Friendika"');
56                     header('HTTP/1.0 401 Unauthorized');
57                     die('This api require login');
58                 }
59                 $_SESSION['uid'] = $record['uid'];
60                 $_SESSION['theme'] = $record['theme'];
61                 $_SESSION['authenticated'] = 1;
62                 $_SESSION['page_flags'] = $record['page-flags'];
63                 $_SESSION['my_url'] = $a->get_baseurl() . '/profile/' . $record['nickname'];
64                 $_SESSION['addr'] = $_SERVER['REMOTE_ADDR'];
65
66                 //notice( t("Welcome back ") . $record['username'] . EOL);
67                 $a->user = $record;
68
69                 if(strlen($a->user['timezone'])) {
70                         date_default_timezone_set($a->user['timezone']);
71                         $a->timezone = $a->user['timezone'];
72                 }
73
74                 $r = q("SELECT * FROM `contact` WHERE `uid` = %s AND `self` = 1 LIMIT 1",
75                         intval($_SESSION['uid']));
76                 if(count($r)) {
77                         $a->contact = $r[0];
78                         $a->cid = $r[0]['id'];
79                         $_SESSION['cid'] = $a->cid;
80                 }
81                 q("UPDATE `user` SET `login_date` = '%s' WHERE `uid` = %d LIMIT 1",
82                         dbesc(datetime_convert()),
83                         intval($_SESSION['uid'])
84                 );
85
86                 call_hooks('logged_in', $a->user);
87
88                 header('X-Account-Management-Status: active; name="' . $a->user['username'] . '"; id="' . $a->user['nickname'] .'"');
89         }
90         
91         /**************************
92          *  MAIN API ENTRY POINT  *
93          **************************/
94         function api_call(&$a){
95                 GLOBAL $API;
96                 foreach ($API as $p=>$info){
97                         if (strpos($a->query_string, $p)===0){
98                                 #unset($_SERVER['PHP_AUTH_USER']);
99                                 if ($info['auth']===true && local_user()===false) {
100                                                 api_login($a);
101                                 }
102                 
103                                 $type="json";           
104                                 if (strpos($a->query_string, ".xml")>0) $type="xml";
105                                 if (strpos($a->query_string, ".json")>0) $type="json";
106                                 if (strpos($a->query_string, ".rss")>0) $type="rss";
107                                 if (strpos($a->query_string, ".atom")>0) $type="atom";                          
108                                 
109                                 $r = call_user_func($info['func'], $a, $type);
110                                 if ($r===false) return;
111
112                                 switch($type){
113                                         case "xml":
114                                                 $r = mb_convert_encoding($r, "UTF-8",mb_detect_encoding($r));
115                                                 header ("Content-Type: text/xml");
116                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
117                                                 break;
118                                         case "json": 
119                                                 header ("Content-Type: application/json");  
120                                                 return json_encode($r);
121                                                 break;
122                                         case "rss":
123                                                 header ("Content-Type: application/rss+xml");
124                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
125                                                 break;
126                                         case "atom":
127                                                 #header ("Content-Type: application/atom+xml");
128                                                 return '<?xml version="1.0" encoding="UTF-8"?>'."\n".$r;
129                                                 break;
130                                                 
131                                 }
132                                 //echo "<pre>"; var_dump($r); die();
133                         }
134                 }
135                 return false;
136         }
137
138         /**
139          * RSS extra info
140          */
141         function api_rss_extra(&$a, $arr, $user_info){
142                 if (is_null($user_info)) $user_info = api_get_user($a);
143                 $arr['$rss'] = array(
144                         'alternate' => $user_info['url'],
145                         'self' => $a->get_baseurl(). "/". $a->query_string,
146                         'updated' => api_date(null),
147                         'language' => $user_info['language'],
148                         'logo'  => $a->get_baseurl()."/images/friendika-32.png",
149                 );
150                 
151                 return $arr;
152         }
153          
154         /**
155          * Returns user info array.
156          */
157         function api_get_user(&$a){
158                 $user = null;
159                 $extra_query = "";
160                 if(x($_GET, 'user_id')) {
161                         $user = intval($_GET['user_id']);       
162                         $extra_query = "AND `contact`.`id` = %d ";
163                 }
164                 if(x($_GET, 'screen_name')) {
165                         $user = dbesc($_GET['screen_name']);    
166                         $extra_query = "AND `contact`.`nick` = '%s' ";
167                 }
168                 
169                 if ($user===null){
170                         list($user, $null) = explode(".",$a->argv[3]);
171                         if(is_numeric($user)){
172                                 $user = intval($user);
173                                 $extra_query = "AND `contact`.`id` = %d ";
174                         } else {
175                                 $user = dbesc($user);
176                                 $extra_query = "AND `contact`.`nick` = '%s' ";
177                         }
178                 }
179                 
180                 if ($user==='') {
181                         if (local_user()===false) {
182                                 api_login($a); return False;
183                         } else {
184                                 $user = $_SESSION['uid'];
185                                 $extra_query = "AND `user`.`uid` = %d ";
186                         }
187                         
188                 }
189                 
190
191                 // user info            
192                 $uinfo = q("SELECT *, `contact`.`id` as `cid` FROM `user`, `contact`
193                                 WHERE `user`.`uid`=`contact`.`uid` AND `contact`.`self`=1
194                                 $extra_query",
195                                 $user
196                 );
197                 if (count($uinfo)==0) {
198                         return False;
199                 }
200                 
201                 // count public wall messages
202                 $r = q("SELECT COUNT(`id`) as `count` FROM `item`
203                                 WHERE  `uid` = %d
204                                 AND `type`='wall' 
205                                 AND `allow_cid`='' AND `allow_gid`='' AND `deny_cid`='' AND `deny_gid`=''",
206                                 intval($uinfo[0]['uid'])
207                 );
208                 $countitms = $r[0]['count'];
209                 
210                 // count friends
211                 $r = q("SELECT COUNT(`id`) as `count` FROM `contact`
212                                 WHERE  `uid` = %d
213                                 AND `self`=0 AND `blocked`=0", 
214                                 intval($uinfo[0]['uid'])
215                 );
216                 $countfriends = $r[0]['count'];
217                                 
218
219                 $ret = Array(
220                         'id' => $uinfo[0]['cid'],
221                         'name' => $uinfo[0]['username'],
222                         'screen_name' => $uinfo[0]['nickname'],
223                         'location' => $uinfo[0]['default-location'],
224                         'profile_image_url' => $uinfo[0]['micro'],
225                         'url' => $uinfo[0]['url'],
226                         'protected' => false,   #
227                         'friends_count' => $countfriends,
228                         'created_at' => api_date($uinfo[0]['created']),
229                         'utc_offset' => 0, #XXX: fix me
230                         'time_zone' => $uinfo[0]['timezone'],
231                         'geo_enabled' => false,
232                         'statuses_count' => $countitms, #XXX: fix me 
233                         'lang' => 'en', #XXX: fix me
234                         'description' => '',
235                         'followers_count' => $countfriends, #XXX: fix me
236                         'favourites_count' => 0,
237                         'contributors_enabled' => false,
238                         'follow_request_sent' => false,
239                         'profile_background_color' => 'cfe8f6',
240                         'profile_text_color' => '000000',
241                         'profile_link_color' => 'FF8500',
242                         'profile_sidebar_fill_color' =>'AD0066',
243                         'profile_sidebar_border_color' => 'AD0066',
244                         'profile_background_image_url' => '',
245                         'profile_background_tile' => false,
246                         'profile_use_background_image' => false,
247                         'notifications' => false,
248                         'verified' => true, #XXX: fix me
249                         'followers' => '', #XXX: fix me
250                         #'status' => null
251                 );
252         
253                 return $ret;
254                 
255         }
256
257         /**
258          * apply xmlify() to all values of array $val, recursively
259          */
260         function api_xmlify($val){
261                 if (is_bool($val)) return $val?"true":"false";
262                 if (is_array($val)) return array_map('api_xmlify', $val);
263                 return xmlify($val);
264         }
265
266         /**
267          *  load api $templatename for $type and replace $data array
268          */
269         function api_apply_template($templatename, $type, $data){
270                 switch($type){
271                         case "rss":
272                         case "atom":
273                         case "xml":
274                                 $data = api_xmlify($data);
275                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
276                                 $ret = replace_macros($tpl, $data);
277                                 break;
278                         case "json":
279                                 $ret = $data;
280                                 break;
281                 }
282                 return $ret;
283         }
284         
285         /**
286          ** TWITTER API
287          */
288         
289         /**
290          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
291          * returns a 401 status code and an error message if not. 
292          * http://developer.twitter.com/doc/get/account/verify_credentials
293          */
294         function api_account_verify_credentials(&$a, $type){
295                 if (local_user()===false) return false;
296                 $user_info = api_get_user($a);
297                 
298                 return api_apply_template("user", $type, array('$user' => $user_info));
299
300         }
301         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
302                 
303
304         // TODO - media uploads and alternate 'source'
305         
306         function api_post_message(&$a, $type) {
307                 if (local_user()===false) return false;
308                 $user_info = api_get_user($a);
309
310                 // convert $_POST array items to the form we use for web posts.
311
312                 $_POST['body'] = urldecode($_POST['status']);
313                 $_POST['parent'] = $_POST['in_reply_to_status_id'];
314                 if($_POST['lat'] && $_POST['long'])
315                         $_POST['coord'] = sprintf("%s %s",$_POST['lat'],$_POST['long']);
316                 $_POST['profile_uid'] = local_user();
317                 if($_POST['parent'])
318                         $_POST['type'] = 'net-comment';
319                 else
320                         $_POST['type'] = 'wall';
321
322                 // set this so that the item_post() function is quiet and doesn't redirect or emit json
323
324                 $_POST['api_source'] = true;
325
326                 // call out normal post function
327
328                 require_once('mod/item.php');
329                 item_post($a);  
330
331                 // this should output the last post (the one we just posted).
332                 return api_users_show();
333         }
334         api_register_func('api/statuses/update','api_statuses_update', true);
335
336                 
337         /**
338          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
339          * The author's most recent status will be returned inline.
340          * http://developer.twitter.com/doc/get/users/show
341          */
342         function api_users_show(&$a, $type){
343                 $user_info = api_get_user($a);
344                 // get last public wall message
345                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
346                                 FROM `item`, `contact`,
347                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
348                                 WHERE `item`.`contact-id` = %d
349                                         AND `i`.`id` = `item`.`parent`
350                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
351                                         AND `type`!='activity'
352                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
353                                 ORDER BY `created` DESC 
354                                 LIMIT 1",
355                                 intval($user_info['id'])
356                 );
357
358                 if (count($lastwall)>0){
359                         $lastwall = $lastwall[0];
360                         
361                         $in_reply_to_status_id = '';
362                         $in_reply_to_user_id = '';
363                         $in_reply_to_screen_name = '';
364                         if ($lastwall['parent']!=$lastwall['id']) {
365                                 $in_reply_to_status_id=$lastwall['parent'];
366                                 $in_reply_to_user_id = $lastwall['reply_uid'];
367                                 $in_reply_to_screen_name = $lastwall['reply_author'];
368                         }  
369                         $user_info['status'] = array(
370                                 'created_at' => api_date($lastwall['created']),
371                                 'id' => $lastwall['contact-id'],
372                                 'text' => strip_tags(bbcode($lastwall['body'])),
373                                 'source' => 'web',
374                                 'truncated' => false,
375                                 'in_reply_to_status_id' => $in_reply_to_status_id,
376                                 'in_reply_to_user_id' => $in_reply_to_user_id,
377                                 'favorited' => false,
378                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
379                                 'geo' => '',
380                                 'coordinates' => $lastwall['coord'],
381                                 'place' => $lastwall['location'],
382                                 'contributors' => ''                                    
383                         );
384                 }
385                 return  api_apply_template("user", $type, array('$user' => $user_info));
386                 
387         }
388         api_register_func('api/users/show','api_users_show');
389         
390         /**
391          * 
392          * http://developer.twitter.com/doc/get/statuses/home_timeline
393          * 
394          * TODO: Optional parameters
395          * TODO: Add reply info
396          */
397         function api_statuses_home_timeline(&$a, $type){
398                 if (local_user()===false) return false;
399                 
400                 $user_info = api_get_user($a);
401                 
402                 // get last newtork messages
403                 $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
404
405                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
406                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
407                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
408                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
409                         FROM `item`, `contact`, `user`
410                         WHERE `item`.`contact-id` = %d AND `user`.`uid` = `item`.`uid` 
411                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
412                         AND `contact`.`id` = `item`.`contact-id`
413                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
414                         $sql_extra
415                         ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
416                         intval($user_info['id']),
417                         0,20
418                 );
419                 $ret = Array();
420
421                 foreach($r as $item) {
422                         $status = array(
423                                 'created_at'=> api_date($item['created']),
424                                 'id'            => $item['id'],
425                                 'text'          => strip_tags(bbcode($item['body'])),
426                                 'html'          => bbcode($item['body']),
427                                 'source'        => 'web',
428                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
429                                 'truncated' => False,
430                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['parent']:''),
431                                 'in_reply_to_user_id' => '',
432                                 'favorited' => false,
433                                 'in_reply_to_screen_name' => '',
434                                 'geo' => '',
435                                 'coordinates' => $item['coord'],
436                                 'place' => $item['location'],
437                                 'contributors' => '',
438                                 'annotations'  => '',
439                                 'entities'  => '',
440                                 'user' =>  $user_info,
441                                 'objecttype' => $item['object-type'],
442                                 'verb' => $item['verb'],
443                                 'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
444                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,                         
445                         );
446                         $ret[]=$status;
447                 };
448                 
449                 $data = array('$statuses' => $ret);
450                 switch($type){
451                         case "atom":
452                         case "rss":
453                                 $data = api_rss_extra($a, $data, $user_info);
454                 }
455                                 
456                 return  api_apply_template("timeline", $type, $data);
457         }
458         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
459         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
460         api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
461         # TODO: user_timeline should be profile view
462