]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
9e7ee38365708f249c22271c6fd3fe6d9598f5fe
[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
33 require_once __DIR__ . '/../../include/api.php';
34
35 class BaseApi extends BaseModule
36 {
37         /**
38          * @var string json|xml|rss|atom
39          */
40         protected static $format = 'json';
41         /**
42          * @var bool|int
43          */
44         protected static $current_user_id;
45
46         public static function init(array $parameters = [])
47         {
48                 $arguments = DI::args();
49
50                 if (substr($arguments->getCommand(), -4) === '.xml') {
51                         self::$format = 'xml';
52                 }
53                 if (substr($arguments->getCommand(), -4) === '.rss') {
54                         self::$format = 'rss';
55                 }
56                 if (substr($arguments->getCommand(), -4) === '.atom') {
57                         self::$format = 'atom';
58                 }
59         }
60
61         public static function delete(array $parameters = [])
62         {
63                 if (!api_user()) {
64                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
65                 }
66
67                 $a = DI::app();
68
69                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
70                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
71                 }
72         }
73
74         public static function patch(array $parameters = [])
75         {
76                 if (!api_user()) {
77                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
78                 }
79
80                 $a = DI::app();
81
82                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
83                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
84                 }
85         }
86
87         public static function post(array $parameters = [])
88         {
89                 if (!api_user()) {
90                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
91                 }
92
93                 $a = DI::app();
94
95                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
96                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
97                 }
98         }
99
100         public static function put(array $parameters = [])
101         {
102                 if (!api_user()) {
103                         throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
104                 }
105
106                 $a = DI::app();
107
108                 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
109                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
110                 }
111         }
112
113         public static function unsupported(string $method = 'all')
114         {
115                 $path = DI::args()->getQueryString();
116                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
117                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
118                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');;
119                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
120                 System::jsonError(501, $errorobj->toArray());
121         }
122
123         /**
124          * Log in user via OAuth1 or Simple HTTP Auth.
125          *
126          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
127          *
128          * @return bool Was a user authenticated?
129          * @throws HTTPException\ForbiddenException
130          * @throws HTTPException\UnauthorizedException
131          * @throws HTTPException\InternalServerErrorException
132          * @hook  'authenticate'
133          *               array $addon_auth
134          *               'username' => username from login form
135          *               'password' => password from login form
136          *               'authenticated' => return status,
137          *               'user_record' => return authenticated user record
138          */
139         protected static function login()
140         {
141                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
142                 $authorization = $_SERVER['AUTHORIZATION'] ?? $authorization;
143
144                 if (self::checkBearer($authorization)) {
145                         self::$current_user_id = self::getUserByBearer($authorization);
146                         return (bool)self::$current_user_id;
147                 }
148
149                 api_login(DI::app());
150
151                 self::$current_user_id = api_user();
152
153                 return (bool)self::$current_user_id;
154         }
155
156         /**
157          * Get current user id, returns 0 if not logged in
158          *
159          * @return int User ID
160          */
161         protected static function getCurrentUserID()
162         {
163                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
164                 $authorization = $_SERVER['AUTHORIZATION'] ?? $authorization;
165
166                 if (self::checkBearer($authorization)) {
167                         self::$current_user_id = self::getUserByBearer($authorization);
168                         return (int)self::$current_user_id;
169                 }
170
171                 if (is_null(self::$current_user_id)) {
172                         api_login(DI::app(), false);
173
174                         self::$current_user_id = api_user();
175                 }
176
177                 return (int)self::$current_user_id;
178         }
179
180         private static function checkBearer(string $authorization)
181         {
182                 return(strpos($authorization, 'Bearer ') !== false);
183         }
184
185         private static function getUserByBearer(string $authorization)
186         {
187                 $bearer = trim(substr($authorization, 6));
188                 $condition = ['access_token' => $bearer];
189                 $token = DBA::selectFirst('application-token', ['uid'], $condition);
190                 if (!DBA::isResult($token)) {
191                         Logger::warning('Token not found', $condition);
192                         return 0;
193                 }
194                 Logger::info('Token found', $token);
195                 return $token['uid'];
196         }
197
198         public static function getApplication()
199         {
200                 $redirect_uri = !isset($_REQUEST['redirect_uri']) ? '' : $_REQUEST['redirect_uri'];
201                 $client_id    = !isset($_REQUEST['client_id']) ? '' : $_REQUEST['client_id'];
202
203                 if (empty($redirect_uri) || empty($client_id)) {
204                         Logger::warning('Incomplete request');
205                         return [];
206                 }
207
208                 $condition = ['redirect_uri' => $redirect_uri, 'client_id' => $client_id];
209                 $application = DBA::selectFirst('application', [], $condition);
210                 if (!DBA::isResult($application)) {
211                         Logger::warning('Application not found', $condition);
212                         return [];
213                 }
214                 return $application;
215         }
216
217         public static function getTokenForUser(array $application, int $uid)
218         {
219                 $code         = bin2hex(random_bytes(32));
220                 $access_token = bin2hex(random_bytes(32));
221
222                 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
223                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
224                         return [];
225                 }
226
227                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
228         }
229         /**
230          * Get user info array.
231          *
232          * @param int|string $contact_id Contact ID or URL
233          * @return array|bool
234          * @throws HTTPException\BadRequestException
235          * @throws HTTPException\InternalServerErrorException
236          * @throws HTTPException\UnauthorizedException
237          * @throws \ImagickException
238          */
239         protected static function getUser($contact_id = null)
240         {
241                 return api_get_user(DI::app(), $contact_id);
242         }
243
244         /**
245          * Formats the data according to the data type
246          *
247          * @param string $root_element
248          * @param array $data An array with a single element containing the returned result
249          * @return false|string
250          */
251         protected static function format(string $root_element, array $data)
252         {
253                 $return = api_format_data($root_element, self::$format, $data);
254
255                 switch (self::$format) {
256                         case "xml":
257                                 header("Content-Type: text/xml");
258                                 break;
259                         case "json":
260                                 header("Content-Type: application/json");
261                                 if (!empty($return)) {
262                                         $json = json_encode(end($return));
263                                         if (!empty($_GET['callback'])) {
264                                                 $json = $_GET['callback'] . "(" . $json . ")";
265                                         }
266                                         $return = $json;
267                                 }
268                                 break;
269                         case "rss":
270                                 header("Content-Type: application/rss+xml");
271                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
272                                 break;
273                         case "atom":
274                                 header("Content-Type: application/atom+xml");
275                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
276                                 break;
277                 }
278
279                 return $return;
280         }
281
282         /**
283          * Creates the XML from a JSON style array
284          *
285          * @param $data
286          * @param $root_element
287          * @return string
288          */
289         protected static function createXml($data, $root_element)
290         {
291                 return api_create_xml($data, $root_element);
292         }
293 }