]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Merge remote-tracking branch 'upstream/develop' into update
[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         /**
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          * Get post data that is transmitted as JSON
132          *
133          * @return array request data
134          */
135         public static function getJsonPostData()
136         {
137                 $postdata = Network::postdata();
138                 if (empty($postdata)) {
139                         return [];
140                 }
141
142                 return json_decode($postdata, true);
143         }
144
145         /**
146          * Get request data for put requests
147          *
148          * @return array request data
149          */
150         public static function getPutData()
151         {
152                 $rawdata = Network::postdata();
153                 if (empty($rawdata)) {
154                         return [];
155                 }
156
157                 $putdata = [];
158
159                 foreach (explode('&', $rawdata) as $value) {
160                         $data = explode('=', $value);
161                         if (count($data) == 2) {
162                                 $putdata[$data[0]] = urldecode($data[1]);
163                         }
164                 }
165
166                 return $putdata;
167         }
168
169         /**
170          * Log in user via OAuth1 or Simple HTTP Auth.
171          *
172          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
173          *
174          * @return bool Was a user authenticated?
175          * @throws HTTPException\ForbiddenException
176          * @throws HTTPException\UnauthorizedException
177          * @throws HTTPException\InternalServerErrorException
178          * @hook  'authenticate'
179          *               array $addon_auth
180          *               'username' => username from login form
181          *               'password' => password from login form
182          *               'authenticated' => return status,
183          *               'user_record' => return authenticated user record
184          */
185         protected static function login()
186         {
187                 if (empty(self::$current_user_id)) {
188                         self::$current_user_id = self::getUserByBearer();
189                 }
190
191                 if (empty(self::$current_user_id)) {
192                         // The execution stops here if no one is logged in
193                         api_login(DI::app());
194                 }
195
196                 self::$current_user_id = api_user();
197
198                 return (bool)self::$current_user_id;
199         }
200
201         /**
202          * Get current user id, returns 0 if not logged in
203          *
204          * @return int User ID
205          */
206         protected static function getCurrentUserID()
207         {
208                 if (empty(self::$current_user_id)) {
209                         self::$current_user_id = self::getUserByBearer();
210                 }
211
212                 if (empty(self::$current_user_id)) {
213                         // Fetch the user id if logged in - but don't fail if not
214                         api_login(DI::app(), false);
215
216                         self::$current_user_id = api_user();
217                 }
218
219                 return (int)self::$current_user_id;
220         }
221
222         /**
223          * Get the user id via the Bearer token
224          *
225          * @return int User-ID
226          */
227         private static function getUserByBearer()
228         {
229                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
230
231                 if (substr($authorization, 0, 7) != 'Bearer ') {
232                         return 0;
233                 }
234
235                 $bearer = trim(substr($authorization, 7));
236                 $condition = ['access_token' => $bearer];
237                 $token = DBA::selectFirst('application-token', ['uid'], $condition);
238                 if (!DBA::isResult($token)) {
239                         Logger::warning('Token not found', $condition);
240                         return 0;
241                 }
242                 Logger::info('Token found', $token);
243                 return $token['uid'];
244         }
245
246         /**
247          * Get the application record via the proved request header fields
248          *
249          * @param string $client_id
250          * @param string $client_secret
251          * @param string $redirect_uri
252          * @return array application record
253          */
254         public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
255         {
256                 $condition = ['client_id' => $client_id];
257                 if (!empty($client_secret)) {
258                         $condition['client_secret'] = $client_secret;
259                 }
260                 if (!empty($redirect_uri)) {
261                         $condition['redirect_uri'] = $redirect_uri;
262                 }
263
264                 $application = DBA::selectFirst('application', [], $condition);
265                 if (!DBA::isResult($application)) {
266                         Logger::warning('Application not found', $condition);
267                         return [];
268                 }
269                 return $application;
270         }
271
272         /**
273          * Check if an token for the application and user exists
274          *
275          * @param array $application
276          * @param integer $uid
277          * @return boolean
278          */
279         public static function existsTokenForUser(array $application, int $uid)
280         {
281                 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
282         }
283
284         /**
285          * Fetch the token for the given application and user
286          *
287          * @param array $application
288          * @param integer $uid
289          * @return array application record
290          */
291         public static function getTokenForUser(array $application, int $uid)
292         {
293                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
294         }
295
296         /**
297          * Create and fetch an token for the application and user
298          *
299          * @param array   $application
300          * @param integer $uid
301          * @param string  $scope
302          * @return array application record
303          */
304         public static function createTokenForUser(array $application, int $uid, string $scope)
305         {
306                 $code         = bin2hex(random_bytes(32));
307                 $access_token = bin2hex(random_bytes(32));
308
309                 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
310                         'read' => (stripos($scope, 'read') !== false), 'write' => (stripos($scope, 'write') !== false),
311                         'follow' => (stripos($scope, 'follow') !== false), 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
312                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
313                         return [];
314                 }
315
316                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
317         }
318
319         /**
320          * Get user info array.
321          *
322          * @param int|string $contact_id Contact ID or URL
323          * @return array|bool
324          * @throws HTTPException\BadRequestException
325          * @throws HTTPException\InternalServerErrorException
326          * @throws HTTPException\UnauthorizedException
327          * @throws \ImagickException
328          */
329         protected static function getUser($contact_id = null)
330         {
331                 return api_get_user(DI::app(), $contact_id);
332         }
333
334         /**
335          * Formats the data according to the data type
336          *
337          * @param string $root_element
338          * @param array $data An array with a single element containing the returned result
339          * @return false|string
340          */
341         protected static function format(string $root_element, array $data)
342         {
343                 $return = api_format_data($root_element, self::$format, $data);
344
345                 switch (self::$format) {
346                         case "xml":
347                                 header("Content-Type: text/xml");
348                                 break;
349                         case "json":
350                                 header("Content-Type: application/json");
351                                 if (!empty($return)) {
352                                         $json = json_encode(end($return));
353                                         if (!empty($_GET['callback'])) {
354                                                 $json = $_GET['callback'] . "(" . $json . ")";
355                                         }
356                                         $return = $json;
357                                 }
358                                 break;
359                         case "rss":
360                                 header("Content-Type: application/rss+xml");
361                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
362                                 break;
363                         case "atom":
364                                 header("Content-Type: application/atom+xml");
365                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
366                                 break;
367                 }
368
369                 return $return;
370         }
371
372         /**
373          * Creates the XML from a JSON style array
374          *
375          * @param $data
376          * @param $root_element
377          * @return string
378          */
379         protected static function createXml($data, $root_element)
380         {
381                 return api_create_xml($data, $root_element);
382         }
383 }