]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Reduced log level
[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\Network;
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' => $_REQUEST ?? []]);
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                 $request = [];
146
147                 foreach ($defaults as $parameter => $defaultvalue) {
148                         if (is_string($defaultvalue)) {
149                                 $request[$parameter] = $_REQUEST[$parameter] ?? $defaultvalue;
150                         } elseif (is_int($defaultvalue)) {
151                                 $request[$parameter] = (int)($_REQUEST[$parameter] ?? $defaultvalue);
152                         } elseif (is_float($defaultvalue)) {
153                                 $request[$parameter] = (float)($_REQUEST[$parameter] ?? $defaultvalue);
154                         } elseif (is_array($defaultvalue)) {
155                                 $request[$parameter] = $_REQUEST[$parameter] ?? [];
156                         } elseif (is_bool($defaultvalue)) {
157                                 $request[$parameter] = in_array(strtolower($_REQUEST[$parameter] ?? ''), ['true', '1']);
158                         } else {
159                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
160                         }
161                 }
162
163                 foreach ($_REQUEST ?? [] as $parameter => $value) {
164                         if ($parameter == 'pagename') {
165                                 continue;
166                         }
167                         if (!in_array($parameter, array_keys($defaults))) {
168                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
169                         }
170                 }
171
172                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
173                 return $request;
174         }
175
176         /**
177          * Get post data that is transmitted as JSON
178          *
179          * @return array request data
180          */
181         public static function getJsonPostData()
182         {
183                 $postdata = Network::postdata();
184                 if (empty($postdata)) {
185                         return [];
186                 }
187
188                 return json_decode($postdata, true);
189         }
190
191         /**
192          * Get request data for put requests
193          *
194          * @return array request data
195          */
196         public static function getPutData()
197         {
198                 $rawdata = Network::postdata();
199                 if (empty($rawdata)) {
200                         return [];
201                 }
202
203                 $putdata = [];
204
205                 foreach (explode('&', $rawdata) as $value) {
206                         $data = explode('=', $value);
207                         if (count($data) == 2) {
208                                 $putdata[$data[0]] = urldecode($data[1]);
209                         }
210                 }
211
212                 return $putdata;
213         }
214
215         /**
216          * Log in user via OAuth1 or Simple HTTP Auth.
217          *
218          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
219          *
220          * @param string $scope the requested scope (read, write, follow)
221          *
222          * @return bool Was a user authenticated?
223          * @throws HTTPException\ForbiddenException
224          * @throws HTTPException\UnauthorizedException
225          * @throws HTTPException\InternalServerErrorException
226          * @hook  'authenticate'
227          *               array $addon_auth
228          *               'username' => username from login form
229          *               'password' => password from login form
230          *               'authenticated' => return status,
231          *               'user_record' => return authenticated user record
232          */
233         protected static function login(string $scope)
234         {
235                 if (empty(self::$current_user_id)) {
236                         self::$current_token = self::getTokenByBearer();
237                         if (!empty(self::$current_token['uid'])) {
238                                 self::$current_user_id = self::$current_token['uid'];
239                         } else {
240                                 self::$current_user_id = 0;
241                         }
242                 }
243
244                 if (!empty($scope) && !empty(self::$current_token)) {
245                         if (empty(self::$current_token[$scope])) {
246                                 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => self::$current_token]);
247                                 DI::mstdnError()->Forbidden();
248                         }
249                 }
250
251                 if (empty(self::$current_user_id)) {
252                         // The execution stops here if no one is logged in
253                         api_login(DI::app());
254                 }
255
256                 self::$current_user_id = api_user();
257
258                 return (bool)self::$current_user_id;
259         }
260
261         /**
262          * Get current application
263          *
264          * @return array token
265          */
266         protected static function getCurrentApplication()
267         {
268                 return self::$current_token;
269         }
270
271         /**
272          * Get current user id, returns 0 if not logged in
273          *
274          * @return int User ID
275          */
276         protected static function getCurrentUserID()
277         {
278                 if (empty(self::$current_user_id)) {
279                         self::$current_token = self::getTokenByBearer();
280                         if (!empty(self::$current_token['uid'])) {
281                                 self::$current_user_id = self::$current_token['uid'];
282                         } else {
283                                 self::$current_user_id = 0;
284                         }
285
286                 }
287
288                 if (empty(self::$current_user_id)) {
289                         // Fetch the user id if logged in - but don't fail if not
290                         api_login(DI::app(), false);
291
292                         self::$current_user_id = api_user();
293                 }
294
295                 return (int)self::$current_user_id;
296         }
297
298         /**
299          * Get the user token via the Bearer token
300          *
301          * @return array User Token
302          */
303         private static function getTokenByBearer()
304         {
305                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
306
307                 if (substr($authorization, 0, 7) != 'Bearer ') {
308                         return [];
309                 }
310
311                 $bearer = trim(substr($authorization, 7));
312                 $condition = ['access_token' => $bearer];
313                 $token = DBA::selectFirst('application-view', ['uid', 'id', 'name', 'website', 'created_at', 'read', 'write', 'follow', 'push'], $condition);
314                 if (!DBA::isResult($token)) {
315                         Logger::warning('Token not found', $condition);
316                         return [];
317                 }
318                 Logger::debug('Token found', $token);
319                 return $token;
320         }
321
322         /**
323          * Get the application record via the proved request header fields
324          *
325          * @param string $client_id
326          * @param string $client_secret
327          * @param string $redirect_uri
328          * @return array application record
329          */
330         public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
331         {
332                 $condition = ['client_id' => $client_id];
333                 if (!empty($client_secret)) {
334                         $condition['client_secret'] = $client_secret;
335                 }
336                 if (!empty($redirect_uri)) {
337                         $condition['redirect_uri'] = $redirect_uri;
338                 }
339
340                 $application = DBA::selectFirst('application', [], $condition);
341                 if (!DBA::isResult($application)) {
342                         Logger::warning('Application not found', $condition);
343                         return [];
344                 }
345                 return $application;
346         }
347
348         /**
349          * Check if an token for the application and user exists
350          *
351          * @param array $application
352          * @param integer $uid
353          * @return boolean
354          */
355         public static function existsTokenForUser(array $application, int $uid)
356         {
357                 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
358         }
359
360         /**
361          * Fetch the token for the given application and user
362          *
363          * @param array $application
364          * @param integer $uid
365          * @return array application record
366          */
367         public static function getTokenForUser(array $application, int $uid)
368         {
369                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
370         }
371
372         /**
373          * Create and fetch an token for the application and user
374          *
375          * @param array   $application
376          * @param integer $uid
377          * @param string  $scope
378          * @return array application record
379          */
380         public static function createTokenForUser(array $application, int $uid, string $scope)
381         {
382                 $code         = bin2hex(random_bytes(32));
383                 $access_token = bin2hex(random_bytes(32));
384
385                 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
386                         'read' => (stripos($scope, self::SCOPE_READ) !== false),
387                         'write' => (stripos($scope, self::SCOPE_WRITE) !== false),
388                         'follow' => (stripos($scope, self::SCOPE_FOLLOW) !== false),
389                         'push' => (stripos($scope, self::SCOPE_PUSH) !== false),
390                          'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
391
392                 foreach ([self::SCOPE_READ, self::SCOPE_WRITE, self::SCOPE_WRITE, self::SCOPE_PUSH] as $scope) {
393                         if ($fields[$scope] && !$application[$scope]) {
394                                 Logger::warning('Requested token scope is not allowed for the application', ['token' => $fields, 'application' => $application]);
395                         }
396                 }
397         
398                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
399                         return [];
400                 }
401
402                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
403         }
404
405         /**
406          * Get user info array.
407          *
408          * @param int|string $contact_id Contact ID or URL
409          * @return array|bool
410          * @throws HTTPException\BadRequestException
411          * @throws HTTPException\InternalServerErrorException
412          * @throws HTTPException\UnauthorizedException
413          * @throws \ImagickException
414          */
415         protected static function getUser($contact_id = null)
416         {
417                 return api_get_user(DI::app(), $contact_id);
418         }
419
420         /**
421          * Formats the data according to the data type
422          *
423          * @param string $root_element
424          * @param array $data An array with a single element containing the returned result
425          * @return false|string
426          */
427         protected static function format(string $root_element, array $data)
428         {
429                 $return = api_format_data($root_element, self::$format, $data);
430
431                 switch (self::$format) {
432                         case "xml":
433                                 header("Content-Type: text/xml");
434                                 break;
435                         case "json":
436                                 header("Content-Type: application/json");
437                                 if (!empty($return)) {
438                                         $json = json_encode(end($return));
439                                         if (!empty($_GET['callback'])) {
440                                                 $json = $_GET['callback'] . "(" . $json . ")";
441                                         }
442                                         $return = $json;
443                                 }
444                                 break;
445                         case "rss":
446                                 header("Content-Type: application/rss+xml");
447                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
448                                 break;
449                         case "atom":
450                                 header("Content-Type: application/atom+xml");
451                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
452                                 break;
453                 }
454
455                 return $return;
456         }
457
458         /**
459          * Creates the XML from a JSON style array
460          *
461          * @param $data
462          * @param $root_element
463          * @return string
464          */
465         protected static function createXml($data, $root_element)
466         {
467                 return api_create_xml($data, $root_element);
468         }
469 }