]> git.mxchange.org Git - friendica.git/blob - include/api.php
Merge pull request #102 from tobiasd/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                 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                         'lang' => 'en', #XXX: fix me
237                         'favourites_count' => 0,
238                         'contributors_enabled' => false,
239                         'follow_request_sent' => false,
240                         'profile_background_color' => 'cfe8f6',
241                         'profile_text_color' => '000000',
242                         'profile_link_color' => 'FF8500',
243                         'profile_sidebar_fill_color' =>'AD0066',
244                         'profile_sidebar_border_color' => 'AD0066',
245                         'profile_background_image_url' => '',
246                         'profile_background_tile' => false,
247                         'profile_use_background_image' => false,
248                         'notifications' => false,
249                         'verified' => true, #XXX: fix me
250                         'followers' => '', #XXX: fix me
251                         #'status' => null
252                 );
253         
254                 return $ret;
255                 
256         }
257
258         /**
259          * apply xmlify() to all values of array $val, recursively
260          */
261         function api_xmlify($val){
262                 if (is_bool($val)) return $val?"true":"false";
263                 if (is_array($val)) return array_map('api_xmlify', $val);
264                 return xmlify($val);
265         }
266
267         /**
268          *  load api $templatename for $type and replace $data array
269          */
270         function api_apply_template($templatename, $type, $data){
271                 switch($type){
272                         case "rss":
273                         case "atom":
274                         case "xml":
275                                 $data = api_xmlify($data);
276                                 $tpl = get_markup_template("api_".$templatename."_".$type.".tpl");
277                                 $ret = replace_macros($tpl, $data);
278                                 break;
279                         case "json":
280                                 $ret = $data;
281                                 break;
282                 }
283                 return $ret;
284         }
285         
286         /**
287          ** TWITTER API
288          */
289         
290         /**
291          * Returns an HTTP 200 OK response code and a representation of the requesting user if authentication was successful; 
292          * returns a 401 status code and an error message if not. 
293          * http://developer.twitter.com/doc/get/account/verify_credentials
294          */
295         function api_account_verify_credentials(&$a, $type){
296                 if (local_user()===false) return false;
297                 $user_info = api_get_user($a);
298                 
299                 return api_apply_template("user", $type, array('$user' => $user_info));
300
301         }
302         api_register_func('api/account/verify_credentials','api_account_verify_credentials', true);
303                 
304         
305                 
306         /**
307          * Returns extended information of a given user, specified by ID or screen name as per the required id parameter.
308          * The author's most recent status will be returned inline.
309          * http://developer.twitter.com/doc/get/users/show
310          */
311         function api_users_show(&$a, $type){
312                 $user_info = api_get_user($a);
313                 // get last public wall message
314                 $lastwall = q("SELECT `item`.*, `i`.`contact-id` as `reply_uid`, `i`.`nick` as `reply_author`
315                                 FROM `item`, `contact`,
316                                         (SELECT `item`.`id`, `item`.`contact-id`, `contact`.`nick` FROM `item`,`contact` WHERE `contact`.`id`=`item`.`contact-id`) as `i` 
317                                 WHERE `item`.`contact-id` = %d
318                                         AND `i`.`id` = `item`.`parent`
319                                         AND `contact`.`id`=`item`.`contact-id` AND `contact`.`self`=1
320                                         AND `type`!='activity'
321                                         AND `item`.`allow_cid`='' AND `item`.`allow_gid`='' AND `item`.`deny_cid`='' AND `item`.`deny_gid`=''
322                                 ORDER BY `created` DESC 
323                                 LIMIT 1",
324                                 intval($user_info['id'])
325                 );
326
327                 if (count($lastwall)>0){
328                         $lastwall = $lastwall[0];
329                         
330                         $in_reply_to_status_id = '';
331                         $in_reply_to_user_id = '';
332                         $in_reply_to_screen_name = '';
333                         if ($lastwall['parent']!=$lastwall['id']) {
334                                 $in_reply_to_status_id=$lastwall['parent'];
335                                 $in_reply_to_user_id = $lastwall['reply_uid'];
336                                 $in_reply_to_screen_name = $lastwall['reply_author'];
337                         }  
338                         $user_info['status'] = array(
339                                 'created_at' => api_date($lastwall['created']),
340                                 'id' => $lastwall['contact-id'],
341                                 'text' => strip_tags(bbcode($lastwall['body'])),
342                                 'source' => 'web',
343                                 'truncated' => false,
344                                 'in_reply_to_status_id' => $in_reply_to_status_id,
345                                 'in_reply_to_user_id' => $in_reply_to_user_id,
346                                 'favorited' => false,
347                                 'in_reply_to_screen_name' => $in_reply_to_screen_name,
348                                 'geo' => '',
349                                 'coordinates' => $lastwall['coord'],
350                                 'place' => $lastwall['location'],
351                                 'contributors' => ''                                    
352                         );
353                 }
354                 return  api_apply_template("user", $type, array('$user' => $user_info));
355                 
356         }
357         api_register_func('api/users/show','api_users_show');
358         
359         /**
360          * 
361          * http://developer.twitter.com/doc/get/statuses/home_timeline
362          * 
363          * TODO: Optional parameters
364          * TODO: Add reply info
365          */
366         function api_statuses_home_timeline(&$a, $type){
367                 if (local_user()===false) return false;
368                 
369                 $user_info = api_get_user($a);
370                 
371                 // get last newtork messages
372                 $sql_extra = " AND `item`.`parent` IN ( SELECT `parent` FROM `item` WHERE `id` = `parent` ) ";
373
374                 $r = q("SELECT `item`.*, `item`.`id` AS `item_id`, 
375                         `contact`.`name`, `contact`.`photo`, `contact`.`url`, `contact`.`rel`,
376                         `contact`.`network`, `contact`.`thumb`, `contact`.`dfrn-id`, `contact`.`self`,
377                         `contact`.`id` AS `cid`, `contact`.`uid` AS `contact-uid`
378                         FROM `item`, `contact`, `user`
379                         WHERE `item`.`contact-id` = %d AND `user`.`uid` = `item`.`uid` 
380                         AND `item`.`visible` = 1 AND `item`.`deleted` = 0
381                         AND `contact`.`id` = `item`.`contact-id`
382                         AND `contact`.`blocked` = 0 AND `contact`.`pending` = 0
383                         $sql_extra
384                         ORDER BY `item`.`created` DESC LIMIT %d ,%d ",
385                         intval($user_info['id']),
386                         0,20
387                 );
388                 $ret = Array();
389
390                 foreach($r as $item) {
391                         $status = array(
392                                 'created_at'=> api_date($item['created']),
393                                 'id'            => $item['id'],
394                                 'text'          => strip_tags(bbcode($item['body'])),
395                                 'html'          => bbcode($item['body']),
396                                 'source'        => 'web',
397                                 'url'           => ($item['plink']!=''?$item['plink']:$item['author-link']),
398                                 'truncated' => False,
399                                 'in_reply_to_status_id' => ($item['parent']!=$item['id']?$item['id']:''),
400                                 'in_reply_to_user_id' => '',
401                                 'favorited' => false,
402                                 'in_reply_to_screen_name' => '',
403                                 'geo' => '',
404                                 'coordinates' => $item['coord'],
405                                 'place' => $item['location'],
406                                 'contributors' => '',
407                                 'annotations'  => '',
408                                 'entities'  => '',
409                                 'user' =>  $user_info,
410                                 'objecttype' => $item['object-type'],
411                                 'verb' => $item['verb'],
412                                 'self' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,
413                                 'edit' => $a->get_baseurl()."/api/statuses/show/".$ite['id'].".".$type,                         
414                         );
415                         $ret[]=$status;
416                 };
417                 
418                 $data = array('$statuses' => $ret);
419                 switch($type){
420                         case "atom":
421                         case "rss":
422                                 $data = api_rss_extra($a, $data, $user_info);
423                 }
424                                 
425                 return  api_apply_template("timeline", $type, $data);
426         }
427         api_register_func('api/statuses/home_timeline','api_statuses_home_timeline', true);
428         api_register_func('api/statuses/friends_timeline','api_statuses_home_timeline', true);
429         api_register_func('api/statuses/user_timeline','api_statuses_home_timeline', true);
430         # TODO: user_timeline should be profile view
431