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