]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Added documentation headers
[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         /**
114          * Quit execution with the message that the endpoint isn't implemented
115          *
116          * @param string $method
117          * @return void
118          */
119         public static function unsupported(string $method = 'all')
120         {
121                 $path = DI::args()->getQueryString();
122                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
123                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
124                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
125                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
126                 System::jsonError(501, $errorobj->toArray());
127         }
128
129         /**
130          * Log in user via OAuth1 or Simple HTTP Auth.
131          *
132          * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
133          *
134          * @return bool Was a user authenticated?
135          * @throws HTTPException\ForbiddenException
136          * @throws HTTPException\UnauthorizedException
137          * @throws HTTPException\InternalServerErrorException
138          * @hook  'authenticate'
139          *               array $addon_auth
140          *               'username' => username from login form
141          *               'password' => password from login form
142          *               'authenticated' => return status,
143          *               'user_record' => return authenticated user record
144          */
145         protected static function login()
146         {
147                 if (empty(self::$current_user_id)) {
148                         self::$current_user_id = self::getUserByBearer();
149                 }
150
151                 if (empty(self::$current_user_id)) {
152                         // The execution stops here if no one is logged in
153                         api_login(DI::app());
154                 }
155
156                 self::$current_user_id = api_user();
157
158                 return (bool)self::$current_user_id;
159         }
160
161         /**
162          * Get current user id, returns 0 if not logged in
163          *
164          * @return int User ID
165          */
166         protected static function getCurrentUserID()
167         {
168                 if (empty(self::$current_user_id)) {
169                         self::$current_user_id = self::getUserByBearer();
170                 }
171
172                 if (empty(self::$current_user_id)) {
173                         // Fetch the user id if logged in - but don't fail if not
174                         api_login(DI::app(), false);
175
176                         self::$current_user_id = api_user();
177                 }
178
179                 return (int)self::$current_user_id;
180         }
181
182         /**
183          * Get the user id via the Bearer token
184          *
185          * @return int User-ID
186          */
187         private static function getUserByBearer()
188         {
189                 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
190                 $authorization = $_SERVER['AUTHORIZATION'] ?? $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          * @return array application record
211          */
212         public static function getApplication()
213         {
214                 $redirect_uri  = !isset($_REQUEST['redirect_uri']) ? '' : $_REQUEST['redirect_uri'];
215                 $client_id     = !isset($_REQUEST['client_id']) ? '' : $_REQUEST['client_id'];
216                 $client_secret = !isset($_REQUEST['client_secret']) ? '' : $_REQUEST['client_secret'];
217
218                 if ((empty($redirect_uri) && empty($client_secret)) || empty($client_id)) {
219                         Logger::warning('Incomplete request', ['request' => $_REQUEST]);
220                         return [];
221                 }
222
223                 $condition = ['client_id' => $client_id];
224                 if (!empty($client_secret)) {
225                         $condition['client_secret'] = $client_secret;
226                 }
227                 if (!empty($redirect_uri)) {
228                         $condition['redirect_uri'] = $redirect_uri;
229                 }
230
231                 $application = DBA::selectFirst('application', [], $condition);
232                 if (!DBA::isResult($application)) {
233                         Logger::warning('Application not found', $condition);
234                         return [];
235                 }
236                 return $application;
237         }
238
239         /**
240          * Check if an token for the application and user exists
241          *
242          * @param array $application
243          * @param integer $uid
244          * @return boolean
245          */
246         public static function existsTokenForUser(array $application, int $uid)
247         {
248                 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
249         }
250
251         /**
252          * Fetch the token for the given application and user
253          *
254          * @param array $application
255          * @param integer $uid
256          * @return array application record
257          */
258         public static function getTokenForUser(array $application, int $uid)
259         {
260                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
261         }
262
263         /**
264          * Create and fetch an token for the application and user
265          *
266          * @param array $application
267          * @param integer $uid
268          * @return array application record
269          */
270         public static function createTokenForUser(array $application, int $uid)
271         {
272                 $code         = bin2hex(random_bytes(32));
273                 $access_token = bin2hex(random_bytes(32));
274
275                 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
276                 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
277                         return [];
278                 }
279
280                 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
281         }
282
283         /**
284          * Get user info array.
285          *
286          * @param int|string $contact_id Contact ID or URL
287          * @return array|bool
288          * @throws HTTPException\BadRequestException
289          * @throws HTTPException\InternalServerErrorException
290          * @throws HTTPException\UnauthorizedException
291          * @throws \ImagickException
292          */
293         protected static function getUser($contact_id = null)
294         {
295                 return api_get_user(DI::app(), $contact_id);
296         }
297
298         /**
299          * Formats the data according to the data type
300          *
301          * @param string $root_element
302          * @param array $data An array with a single element containing the returned result
303          * @return false|string
304          */
305         protected static function format(string $root_element, array $data)
306         {
307                 $return = api_format_data($root_element, self::$format, $data);
308
309                 switch (self::$format) {
310                         case "xml":
311                                 header("Content-Type: text/xml");
312                                 break;
313                         case "json":
314                                 header("Content-Type: application/json");
315                                 if (!empty($return)) {
316                                         $json = json_encode(end($return));
317                                         if (!empty($_GET['callback'])) {
318                                                 $json = $_GET['callback'] . "(" . $json . ")";
319                                         }
320                                         $return = $json;
321                                 }
322                                 break;
323                         case "rss":
324                                 header("Content-Type: application/rss+xml");
325                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
326                                 break;
327                         case "atom":
328                                 header("Content-Type: application/atom+xml");
329                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
330                                 break;
331                 }
332
333                 return $return;
334         }
335
336         /**
337          * Creates the XML from a JSON style array
338          *
339          * @param $data
340          * @param $root_element
341          * @return string
342          */
343         protected static function createXml($data, $root_element)
344         {
345                 return api_create_xml($data, $root_element);
346         }
347 }