]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Merge branch 'stable' into develop
[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\DI;
28 use Friendica\Network\HTTPException;
29 use Friendica\Security\BasicAuth;
30 use Friendica\Security\OAuth;
31 use Friendica\Util\HTTPInputData;
32
33 require_once __DIR__ . '/../../include/api.php';
34
35 class BaseApi extends BaseModule
36 {
37         const SCOPE_READ   = 'read';
38         const SCOPE_WRITE  = 'write';
39         const SCOPE_FOLLOW = 'follow';
40         const SCOPE_PUSH   = 'push';
41
42         /**
43          * @var string json|xml|rss|atom
44          */
45         protected static $format = 'json';
46
47         /**
48          * @var array
49          */
50         protected static $boundaries = [];
51
52         /**
53          * @var array
54          */
55         protected static $request = [];
56
57         public static function init(array $parameters = [])
58         {
59                 $arguments = DI::args();
60
61                 if (substr($arguments->getCommand(), -4) === '.xml') {
62                         self::$format = 'xml';
63                 }
64                 if (substr($arguments->getCommand(), -4) === '.rss') {
65                         self::$format = 'rss';
66                 }
67                 if (substr($arguments->getCommand(), -4) === '.atom') {
68                         self::$format = 'atom';
69                 }
70         }
71
72         public static function delete(array $parameters = [])
73         {
74                 self::checkAllowedScope(self::SCOPE_WRITE);
75
76                 $a = DI::app();
77
78                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
79                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
80                 }
81         }
82
83         public static function patch(array $parameters = [])
84         {
85                 self::checkAllowedScope(self::SCOPE_WRITE);
86
87                 $a = DI::app();
88
89                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
90                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
91                 }
92         }
93
94         public static function post(array $parameters = [])
95         {
96                 self::checkAllowedScope(self::SCOPE_WRITE);
97
98                 $a = DI::app();
99
100                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
101                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
102                 }
103         }
104
105         public static function put(array $parameters = [])
106         {
107                 self::checkAllowedScope(self::SCOPE_WRITE);
108
109                 $a = DI::app();
110
111                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
112                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
113                 }
114         }
115
116         /**
117          * Quit execution with the message that the endpoint isn't implemented
118          *
119          * @param string $method
120          * @return void
121          */
122         public static function unsupported(string $method = 'all')
123         {
124                 $path = DI::args()->getQueryString();
125                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => HTTPInputData::process()]);
126                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
127                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
128                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
129                 System::jsonError(501, $errorobj->toArray());
130         }
131
132         /**
133          * Processes data from GET requests and sets defaults
134          *
135          * @return array request data
136          */
137         public static function getRequest(array $defaults)
138         {
139                 $httpinput = HTTPInputData::process();
140                 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
141
142                 self::$request    = $input;
143                 self::$boundaries = [];
144
145                 unset(self::$request['pagename']);
146
147                 $request = [];
148
149                 foreach ($defaults as $parameter => $defaultvalue) {
150                         if (is_string($defaultvalue)) {
151                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
152                         } elseif (is_int($defaultvalue)) {
153                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
154                         } elseif (is_float($defaultvalue)) {
155                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
156                         } elseif (is_array($defaultvalue)) {
157                                 $request[$parameter] = $input[$parameter] ?? [];
158                         } elseif (is_bool($defaultvalue)) {
159                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
160                         } else {
161                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
162                         }
163                 }
164
165                 foreach ($input ?? [] as $parameter => $value) {
166                         if ($parameter == 'pagename') {
167                                 continue;
168                         }
169                         if (!in_array($parameter, array_keys($defaults))) {
170                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
171                         }
172                 }
173
174                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
175                 return $request;
176         }
177
178         /**
179          * Set boundaries for the "link" header
180          * @param array $boundaries
181          * @param int $id
182          * @return array
183          */
184         protected static function setBoundaries(int $id)
185         {
186                 if (!isset(self::$boundaries['min'])) {
187                         self::$boundaries['min'] = $id;
188                 }
189
190                 if (!isset(self::$boundaries['max'])) {
191                         self::$boundaries['max'] = $id;
192                 }
193
194                 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
195                 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
196         }
197
198         /**
199          * Set the "link" header with "next" and "prev" links
200          * @return void
201          */
202         protected static function setLinkHeader()
203         {
204                 if (empty(self::$boundaries)) {
205                         return;
206                 }
207
208                 $request = self::$request;
209
210                 unset($request['min_id']);
211                 unset($request['max_id']);
212                 unset($request['since_id']);
213
214                 $prev_request = $next_request = $request;
215
216                 $prev_request['min_id'] = self::$boundaries['max'];
217                 $next_request['max_id'] = self::$boundaries['min'];
218
219                 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
220
221                 $prev = $command . '?' . http_build_query($prev_request);
222                 $next = $command . '?' . http_build_query($next_request);
223
224                 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
225         }
226
227         /**
228          * Get current application token
229          *
230          * @return array token
231          */
232         protected static function getCurrentApplication()
233         {
234                 $token = OAuth::getCurrentApplicationToken();
235
236                 if (empty($token)) {
237                         $token = BasicAuth::getCurrentApplicationToken();
238                 }
239
240                 return $token;
241         }
242
243         /**
244          * Get current user id, returns 0 if not logged in
245          *
246          * @return int User ID
247          */
248         protected static function getCurrentUserID()
249         {
250                 $uid = OAuth::getCurrentUserID();
251
252                 if (empty($uid)) {
253                         $uid = BasicAuth::getCurrentUserID(false);
254                 }
255
256                 return (int)$uid;
257         }
258
259         /**
260          * Check if the provided scope does exist.
261          * halts execution on missing scope or when not logged in.
262          *
263          * @param string $scope the requested scope (read, write, follow, push)
264          */
265         public static function checkAllowedScope(string $scope)
266         {
267                 $token = self::getCurrentApplication();
268
269                 if (empty($token)) {
270                         Logger::notice('Empty application token');
271                         DI::mstdnError()->Forbidden();
272                 }
273
274                 if (!isset($token[$scope])) {
275                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
276                         DI::mstdnError()->Forbidden();
277                 }
278
279                 if (empty($token[$scope])) {
280                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
281                         DI::mstdnError()->Forbidden();
282                 }
283         }
284
285         /**
286          * Get user info array.
287          *
288          * @param int|string $contact_id Contact ID or URL
289          * @return array|bool
290          * @throws HTTPException\BadRequestException
291          * @throws HTTPException\InternalServerErrorException
292          * @throws HTTPException\UnauthorizedException
293          * @throws \ImagickException
294          */
295         protected static function getUser($contact_id = null)
296         {
297                 return api_get_user(DI::app(), $contact_id);
298         }
299
300         /**
301          * Formats the data according to the data type
302          *
303          * @param string $root_element
304          * @param array $data An array with a single element containing the returned result
305          * @return false|string
306          */
307         protected static function format(string $root_element, array $data)
308         {
309                 $return = api_format_data($root_element, self::$format, $data);
310
311                 switch (self::$format) {
312                         case "xml":
313                                 header("Content-Type: text/xml");
314                                 break;
315                         case "json":
316                                 header("Content-Type: application/json");
317                                 if (!empty($return)) {
318                                         $json = json_encode(end($return));
319                                         if (!empty($_GET['callback'])) {
320                                                 $json = $_GET['callback'] . "(" . $json . ")";
321                                         }
322                                         $return = $json;
323                                 }
324                                 break;
325                         case "rss":
326                                 header("Content-Type: application/rss+xml");
327                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
328                                 break;
329                         case "atom":
330                                 header("Content-Type: application/atom+xml");
331                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
332                                 break;
333                 }
334
335                 return $return;
336         }
337
338         /**
339          * Creates the XML from a JSON style array
340          *
341          * @param $data
342          * @param $root_element
343          * @return string
344          */
345         protected static function createXml($data, $root_element)
346         {
347                 return api_create_xml($data, $root_element);
348         }
349 }