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