]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/api.php
Better check to see if the XML prolog should be outputted for XML
[quix0rs-gnu-social.git] / actions / api.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.     See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.     If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 class ApiAction extends Action
23 {
24
25     var $user;
26     var $content_type;
27     var $api_arg;
28     var $api_method;
29     var $api_action;
30     var $auth_user;
31     var $auth_pw;
32
33     function handle($args)
34     {
35         parent::handle($args);
36
37         $this->api_action = $this->arg('apiaction');
38         $method = $this->arg('method');
39         $argument = $this->arg('argument');
40         $this->basic_auth_process_header();
41
42         if (isset($argument)) {
43             $cmdext = explode('.', $argument);
44             $this->api_arg =  $cmdext[0];
45             $this->api_method = $method;
46             $this->content_type = strtolower($cmdext[1]);
47         } else {
48
49             # Requested format / content-type will be an extension on the method
50             $cmdext = explode('.', $method);
51             $this->api_method = $cmdext[0];
52             $this->content_type = strtolower($cmdext[1]);
53         }
54
55         if ($this->requires_auth()) {
56             if (!isset($this->auth_user)) {
57
58                 # This header makes basic auth go
59                 header('WWW-Authenticate: Basic realm="StatusNet API"');
60
61                 # If the user hits cancel -- bam!
62                 $this->show_basic_auth_error();
63             } else {
64                 $nickname = $this->auth_user;
65                 $password = $this->auth_pw;
66                 $user = common_check_user($nickname, $password);
67
68                 if ($user) {
69                     $this->user = $user;
70                     $this->process_command();
71                 } else {
72                     # basic authentication failed
73                     list($proxy, $ip) = common_client_ip();
74
75                     common_log(LOG_WARNING, "Failed API auth attempt, nickname = $nickname, proxy = $proxy, ip = $ip.");
76                     $this->show_basic_auth_error();
77                 }
78             }
79         } else {
80
81             // Caller might give us a username even if not required
82             if (isset($this->auth_user)) {
83                 $user = User::staticGet('nickname', $this->auth_user);
84                 if ($user) {
85                     $this->user = $user;
86                 }
87                 # Twitter doesn't throw an error if the user isn't found
88             }
89
90             $this->process_command();
91         }
92     }
93
94     function process_command()
95     {
96         $action = "twitapi$this->api_action";
97         $actionfile = INSTALLDIR."/actions/$action.php";
98
99         if (file_exists($actionfile)) {
100             require_once($actionfile);
101             $action_class = ucfirst($action)."Action";
102             $action_obj = new $action_class();
103
104             if (!$action_obj->prepare($this->args)) {
105                 return;
106             }
107
108             if (method_exists($action_obj, $this->api_method)) {
109                 $apidata = array(    'content-type' => $this->content_type,
110                                     'api_method' => $this->api_method,
111                                     'api_arg' => $this->api_arg,
112                                     'user' => $this->user);
113
114                 call_user_func(array($action_obj, $this->api_method), $_REQUEST, $apidata);
115             } else {
116                 $this->clientError("API method not found!", $code=404);
117             }
118         } else {
119             $this->clientError("API method not found!", $code=404);
120         }
121     }
122
123     // Whitelist of API methods that don't need authentication
124     function requires_auth()
125     {
126         static $noauth = array( 'statuses/public_timeline',
127                                 'statuses/show',
128                                 'users/show',
129                                 'help/test',
130                                 'help/downtime_schedule',
131                                 'statusnet/version',
132                                 'statusnet/config',
133                                 'statusnet/wadl',
134                                 'tags/timeline',
135                                 'oembed/oembed',
136                                 'groups/show',
137                                 'groups/timeline',
138                                 'groups/list_all',
139                                 'groups/membership',
140                                 'groups/is_member',
141                                 'groups/timeline');
142
143         static $bareauth = array('statuses/user_timeline',
144                                  'statuses/friends_timeline',
145                                  'statuses/home_timeline',
146                                  'statuses/friends',
147                                  'statuses/replies',
148                                  'statuses/mentions',
149                                  'statuses/followers',
150                                  'favorites/favorites',
151                                  'friendships/show',
152                                  'groups/list_groups');
153
154         $fullname = "$this->api_action/$this->api_method";
155
156         // If the site is "private", all API methods except statusnet/config
157         // need authentication
158
159         if (common_config('site', 'private')) {
160             return $fullname != 'statusnet/config' || false;
161         }
162
163         // bareauth: only needs auth if without an argument or query param specifying user
164
165         if (in_array($fullname, $bareauth)) {
166
167             // Special case: friendships/show only needs auth if source_id or
168             // source_screen_name is not specified as a param
169
170             if ($fullname == 'friendships/show') {
171
172                 $source_id          = $this->arg('source_id');
173                 $source_screen_name = $this->arg('source_screen_name');
174
175                 if (empty($source_id) && empty($source_screen_name)) {
176                     return true;
177                 }
178
179                 return false;
180             }
181
182             // if all of these are empty, auth is required
183
184             $id          = $this->arg('id');
185             $user_id     = $this->arg('user_id');
186             $screen_name = $this->arg('screen_name');
187
188             if (empty($this->api_arg) &&
189                 empty($id)            &&
190                 empty($user_id)       &&
191                 empty($screen_name)) {
192                 return true;
193             } else {
194                 return false;
195             }
196
197         } else if (in_array($fullname, $noauth)) {
198
199             // noauth: never needs auth
200
201             return false;
202         } else {
203
204             // everybody else needs auth
205
206             return true;
207         }
208     }
209
210     function basic_auth_process_header()
211     {
212         if(isset($_SERVER['AUTHORIZATION']) || isset($_SERVER['HTTP_AUTHORIZATION']))
213         {
214                 $authorization_header = isset($_SERVER['HTTP_AUTHORIZATION'])?$_SERVER['HTTP_AUTHORIZATION']:$_SERVER['AUTHORIZATION'];
215         }
216
217         if(isset($_SERVER['PHP_AUTH_USER']))
218         {
219                 $this->auth_user = $_SERVER['PHP_AUTH_USER'];
220                 $this->auth_pw = $_SERVER['PHP_AUTH_PW'];
221         }
222         elseif ( isset($authorization_header) && strstr(substr($authorization_header, 0,5),'Basic')  )
223         {
224                 // decode the HTTP_AUTHORIZATION header on php-cgi server self
225                 // on fcgid server the header name is AUTHORIZATION
226
227                 $auth_hash = base64_decode( substr($authorization_header, 6) );
228                 list($this->auth_user, $this->auth_pw) = explode(':', $auth_hash);
229
230                 // set all to NULL on a empty basic auth request
231                 if($this->auth_user == "") {
232                         $this->auth_user = NULL;
233                         $this->auth_pw = NULL;
234                 }
235         }
236         else
237         {
238                 $this->auth_user = NULL;
239                 $this->auth_pw = NULL;
240         }
241     }
242
243     function show_basic_auth_error()
244     {
245         header('HTTP/1.1 401 Unauthorized');
246         $msg = 'Could not authenticate you.';
247
248         if ($this->content_type == 'xml') {
249             header('Content-Type: application/xml; charset=utf-8');
250             $this->startXML();
251             $this->elementStart('hash');
252             $this->element('error', null, $msg);
253             $this->element('request', null, $_SERVER['REQUEST_URI']);
254             $this->elementEnd('hash');
255             $this->endXML();
256         } else if ($this->content_type == 'json')  {
257             header('Content-Type: application/json; charset=utf-8');
258             $error_array = array('error' => $msg, 'request' => $_SERVER['REQUEST_URI']);
259             print(json_encode($error_array));
260         } else {
261             header('Content-type: text/plain');
262             print "$msg\n";
263         }
264     }
265
266     function isReadOnly($args)
267     {
268         $apiaction = $args['apiaction'];
269         $method = $args['method'];
270
271         list($cmdtext, $fmt) = explode('.', $method);
272
273         static $write_methods = array(
274             'account' => array('update_location', 'update_delivery_device', 'end_session'),
275             'blocks' => array('create', 'destroy'),
276             'direct_messages' => array('create', 'destroy'),
277             'favorites' => array('create', 'destroy'),
278             'friendships' => array('create', 'destroy'),
279             'help' => array(),
280             'notifications' => array('follow', 'leave'),
281             'statuses' => array('update', 'destroy'),
282             'users' => array()
283         );
284
285         if (array_key_exists($apiaction, $write_methods)) {
286             if (!in_array($cmdtext, $write_methods[$apiaction])) {
287                 return true;
288             }
289         }
290
291         return false;
292     }
293 }