]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
aca6070ae1e6cba1d1d1b0e29330887d8645b0fb
[friendica.git] / src / Module / BaseApi.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
7  * This program is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU Affero General Public License as
9  * published by the Free Software Foundation, either version 3 of the
10  * License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Affero General Public License for more details.
16  *
17  * You should have received a copy of the GNU Affero General Public License
18  * along with this program.  If not, see <https://www.gnu.org/licenses/>.
19  *
20  */
21
22 namespace Friendica\Module;
23
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
29 use Friendica\DI;
30 use Friendica\Network\HTTPException;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\HTTPInputData;
33
34 require_once __DIR__ . '/../../include/api.php';
35
36 class BaseApi extends BaseModule
37 {
38         const SCOPE_READ   = 'read';
39         const SCOPE_WRITE  = 'write';
40         const SCOPE_FOLLOW = 'follow';
41         const SCOPE_PUSH   = 'push';
42
43         /**
44          * @var string json|xml|rss|atom
45          */
46         protected static $format = 'json';
47         /**
48          * @var bool|int
49          */
50         protected static $current_user_id;
51         /**
52          * @var array
53          */
54         protected static $current_token = [];
55
56         public static function init(array $parameters = [])
57         {
58                 $arguments = DI::args();
59
60                 if (substr($arguments->getCommand(), -4) === '.xml') {
61                         self::$format = 'xml';
62                 }
63                 if (substr($arguments->getCommand(), -4) === '.rss') {
64                         self::$format = 'rss';
65                 }
66                 if (substr($arguments->getCommand(), -4) === '.atom') {
67                         self::$format = 'atom';
68                 }
69         }
70
71         public static function delete(array $parameters = [])
72         {
73                 if (!api_user()) {
74                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
75                 }
76
77                 $a = DI::app();
78
79                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
80                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
81                 }
82         }
83
84         public static function patch(array $parameters = [])
85         {
86                 if (!api_user()) {
87                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
88                 }
89
90                 $a = DI::app();
91
92                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
93                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
94                 }
95         }
96
97         public static function post(array $parameters = [])
98         {
99                 if (!api_user()) {
100                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
101                 }
102
103                 $a = DI::app();
104
105                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
106                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
107                 }
108         }
109
110         public static function put(array $parameters = [])
111         {
112                 if (!api_user()) {
113                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
114                 }
115
116                 $a = DI::app();
117
118                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
119                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
120                 }
121         }
122
123         /**
124          * Quit execution with the message that the endpoint isn't implemented
125          *
126          * @param string $method
127          * @return void
128          */
129         public static function unsupported(string $method = 'all')
130         {
131                 $path = DI::args()->getQueryString();
132                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => HTTPInputData::process()]);
133                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
134                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
135                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
136                 System::jsonError(501, $errorobj->toArray());
137         }
138
139         /**
140          * Processes data from GET requests and sets defaults
141          *
142          * @return array request data
143          */
144         public static function getRequest(array $defaults) {
145                 $httpinput = HTTPInputData::process();
146                 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
147
148                 $request = [];
149
150                 foreach ($defaults as $parameter => $defaultvalue) {
151                         if (is_string($defaultvalue)) {
152                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
153                         } elseif (is_int($defaultvalue)) {
154                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
155                         } elseif (is_float($defaultvalue)) {
156                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
157                         } elseif (is_array($defaultvalue)) {
158                                 $request[$parameter] = $input[$parameter] ?? [];
159                         } elseif (is_bool($defaultvalue)) {
160                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
161                         } else {
162                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
163                         }
164                 }
165
166                 foreach ($input ?? [] as $parameter => $value) {
167                         if ($parameter == 'pagename') {
168                                 continue;
169                         }
170                         if (!in_array($parameter, array_keys($defaults))) {
171                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
172                         }
173                 }
174
175                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
176                 return $request;
177         }
178
179         /**
180          * Log in user via OAuth1 or Simple HTTP Auth.
181          *
182          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
183          *
184          * @param string $scope the requested scope (read, write, follow)
185          *
186          * @return bool Was a user authenticated?
187          * @throws HTTPException\ForbiddenException
188          * @throws HTTPException\UnauthorizedException
189          * @throws HTTPException\InternalServerErrorException
190          * @hook  'authenticate'
191          *               array $addon_auth
192          *               'username' => username from login form
193          *               'password' => password from login form
194          *               'authenticated' => return status,
195          *               'user_record' => return authenticated user record
196          */
197         protected static function login(string $scope)
198         {
199                 if (empty(self::$current_user_id)) {
200                         self::$current_token = self::getTokenByBearer();
201                         if (!empty(self::$current_token['uid'])) {
202                                 self::$current_user_id = self::$current_token['uid'];
203                         } else {
204                                 self::$current_user_id = 0;
205                         }
206                 }
207
208                 if (!empty($scope) && !empty(self::$current_token)) {
209                         if (empty(self::$current_token[$scope])) {
210                                 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => self::$current_token]);
211                                 DI::mstdnError()->Forbidden();
212                         }
213                 }
214
215                 if (empty(self::$current_user_id)) {
216                         // The execution stops here if no one is logged in
217                         api_login(DI::app());
218                 }
219
220                 self::$current_user_id = api_user();
221
222                 return (bool)self::$current_user_id;
223         }
224
225         /**
226          * Get current application
227          *
228          * @return array token
229          */
230         protected static function getCurrentApplication()
231         {
232                 return self::$current_token;
233         }
234
235         /**
236          * Get current user id, returns 0 if not logged in
237          *
238          * @return int User ID
239          */
240         protected static function getCurrentUserID()
241         {
242                 if (empty(self::$current_user_id)) {
243                         self::$current_token = self::getTokenByBearer();
244                         if (!empty(self::$current_token['uid'])) {
245                                 self::$current_user_id = self::$current_token['uid'];
246                         } else {
247                                 self::$current_user_id = 0;
248                         }
249
250                 }
251
252                 if (empty(self::$current_user_id)) {
253                         // Fetch the user id if logged in - but don't fail if not
254                         api_login(DI::app(), false);
255
256                         self::$current_user_id = api_user();
257                 }
258
259                 return (int)self::$current_user_id;
260         }
261
262         /**
263          * Get the user token via the Bearer token
264          *
265          * @return array User Token
266          */
267         private static function getTokenByBearer()
268         {
269                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
270
271                 if (substr($authorization, 0, 7) != 'Bearer ') {
272                         return [];
273                 }
274
275                 $bearer = trim(substr($authorization, 7));
276                 $condition = ['access_token' => $bearer];
277                 $token = DBA::selectFirst('application-view', ['uid', 'id', 'name', 'website', 'created_at', 'read', 'write', 'follow', 'push'], $condition);
278                 if (!DBA::isResult($token)) {
279                         Logger::warning('Token not found', $condition);
280                         return [];
281                 }
282                 Logger::debug('Token found', $token);
283                 return $token;
284         }
285
286         /**
287          * Get the application record via the proved request header fields
288          *
289          * @param string $client_id
290          * @param string $client_secret
291          * @param string $redirect_uri
292          * @return array application record
293          */
294         public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
295         {
296                 $condition = ['client_id' => $client_id];
297                 if (!empty($client_secret)) {
298                         $condition['client_secret'] = $client_secret;
299                 }
300                 if (!empty($redirect_uri)) {
301                         $condition['redirect_uri'] = $redirect_uri;
302                 }
303
304                 $application = DBA::selectFirst('application', [], $condition);
305                 if (!DBA::isResult($application)) {
306                         Logger::warning('Application not found', $condition);
307                         return [];
308                 }
309                 return $application;
310         }
311
312         /**
313          * Check if an token for the application and user exists
314          *
315          * @param array $application
316          * @param integer $uid
317          * @return boolean
318          */
319         public static function existsTokenForUser(array $application, int $uid)
320         {
321                 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
322         }
323
324         /**
325          * Fetch the token for the given application and user
326          *
327          * @param array $application
328          * @param integer $uid
329          * @return array application record
330          */
331         public static function getTokenForUser(array $application, int $uid)
332         {
333                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
334         }
335
336         /**
337          * Create and fetch an token for the application and user
338          *
339          * @param array   $application
340          * @param integer $uid
341          * @param string  $scope
342          * @return array application record
343          */
344         public static function createTokenForUser(array $application, int $uid, string $scope)
345         {
346                 $code         = bin2hex(random_bytes(32));
347                 $access_token = bin2hex(random_bytes(32));
348
349                 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
350                         'read' => (stripos($scope, self::SCOPE_READ) !== false),
351                         'write' => (stripos($scope, self::SCOPE_WRITE) !== false),
352                         'follow' => (stripos($scope, self::SCOPE_FOLLOW) !== false),
353                         'push' => (stripos($scope, self::SCOPE_PUSH) !== false),
354                          'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
355
356                 foreach ([self::SCOPE_READ, self::SCOPE_WRITE, self::SCOPE_WRITE, self::SCOPE_PUSH] as $scope) {
357                         if ($fields[$scope] && !$application[$scope]) {
358                                 Logger::warning('Requested token scope is not allowed for the application', ['token' => $fields, 'application' => $application]);
359                         }
360                 }
361
362                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
363                         return [];
364                 }
365
366                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
367         }
368
369         /**
370          * Get user info array.
371          *
372          * @param int|string $contact_id Contact ID or URL
373          * @return array|bool
374          * @throws HTTPException\BadRequestException
375          * @throws HTTPException\InternalServerErrorException
376          * @throws HTTPException\UnauthorizedException
377          * @throws \ImagickException
378          */
379         protected static function getUser($contact_id = null)
380         {
381                 return api_get_user(DI::app(), $contact_id);
382         }
383
384         /**
385          * Formats the data according to the data type
386          *
387          * @param string $root_element
388          * @param array $data An array with a single element containing the returned result
389          * @return false|string
390          */
391         protected static function format(string $root_element, array $data)
392         {
393                 $return = api_format_data($root_element, self::$format, $data);
394
395                 switch (self::$format) {
396                         case "xml":
397                                 header("Content-Type: text/xml");
398                                 break;
399                         case "json":
400                                 header("Content-Type: application/json");
401                                 if (!empty($return)) {
402                                         $json = json_encode(end($return));
403                                         if (!empty($_GET['callback'])) {
404                                                 $json = $_GET['callback'] . "(" . $json . ")";
405                                         }
406                                         $return = $json;
407                                 }
408                                 break;
409                         case "rss":
410                                 header("Content-Type: application/rss+xml");
411                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
412                                 break;
413                         case "atom":
414                                 header("Content-Type: application/atom+xml");
415                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
416                                 break;
417                 }
418
419                 return $return;
420         }
421
422         /**
423          * Creates the XML from a JSON style array
424          *
425          * @param $data
426          * @param $root_element
427          * @return string
428          */
429         protected static function createXml($data, $root_element)
430         {
431                 return api_create_xml($data, $root_element);
432         }
433 }