]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Rearranged scope check
[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         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' => HTTPInputData::process()]);
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          * Processes data from GET requests and sets defaults
132          *
133          * @return array request data
134          */
135         public static function getRequest(array $defaults)
136         {
137                 $httpinput = HTTPInputData::process();
138                 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
139
140                 $request = [];
141
142                 foreach ($defaults as $parameter => $defaultvalue) {
143                         if (is_string($defaultvalue)) {
144                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
145                         } elseif (is_int($defaultvalue)) {
146                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
147                         } elseif (is_float($defaultvalue)) {
148                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
149                         } elseif (is_array($defaultvalue)) {
150                                 $request[$parameter] = $input[$parameter] ?? [];
151                         } elseif (is_bool($defaultvalue)) {
152                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
153                         } else {
154                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
155                         }
156                 }
157
158                 foreach ($input ?? [] as $parameter => $value) {
159                         if ($parameter == 'pagename') {
160                                 continue;
161                         }
162                         if (!in_array($parameter, array_keys($defaults))) {
163                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
164                         }
165                 }
166
167                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
168                 return $request;
169         }
170
171         /**
172          * @deprecated Use checkAllowedScope instead
173          * Log in user via OAuth or Basic HTTP Auth.
174          *
175          * @param string $scope the requested scope (read, write, follow)
176          */
177         protected static function login(string $scope)
178         {
179                 self::checkAllowedScope($scope);
180         }
181
182         /**
183          * Get current application token
184          *
185          * @return array token
186          */
187         protected static function getCurrentApplication()
188         {
189                 $token = OAuth::getCurrentApplicationToken();
190
191                 if (empty($token)) {
192                         $token = BasicAuth::getCurrentApplicationToken();
193                 }
194
195                 return $token;
196         }
197
198         /**
199          * Get current user id, returns 0 if not logged in
200          *
201          * @return int User ID
202          */
203         public static function getCurrentUserID()
204         {
205                 $uid = OAuth::getCurrentUserID();
206
207                 if (empty($uid)) {
208                         $uid = BasicAuth::getCurrentUserID(false);
209                 }
210
211                 return (int)$uid;
212         }
213
214         /**
215          * Check if the provided scope does exist.
216          * halts execution on missing scope or when not logged in.
217          *
218          * @param string $scope the requested scope (read, write, follow, push)
219          */
220         public static function checkAllowedScope(string $scope)
221         {
222                 $token = self::getCurrentApplication();
223
224                 if (empty($token)) {
225                         Logger::notice('Empty application token');
226                         DI::mstdnError()->Forbidden();
227                 }
228
229                 if (!isset($token[$scope])) {
230                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
231                         DI::mstdnError()->Forbidden();
232                 }
233
234                 if (empty($token[$scope])) {
235                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
236                         DI::mstdnError()->Forbidden();
237                 }
238         }
239
240         /**
241          * Get user info array.
242          *
243          * @param int|string $contact_id Contact ID or URL
244          * @return array|bool
245          * @throws HTTPException\BadRequestException
246          * @throws HTTPException\InternalServerErrorException
247          * @throws HTTPException\UnauthorizedException
248          * @throws \ImagickException
249          */
250         protected static function getUser($contact_id = null)
251         {
252                 return api_get_user(DI::app(), $contact_id);
253         }
254
255         /**
256          * Formats the data according to the data type
257          *
258          * @param string $root_element
259          * @param array $data An array with a single element containing the returned result
260          * @return false|string
261          */
262         protected static function format(string $root_element, array $data)
263         {
264                 $return = api_format_data($root_element, self::$format, $data);
265
266                 switch (self::$format) {
267                         case "xml":
268                                 header("Content-Type: text/xml");
269                                 break;
270                         case "json":
271                                 header("Content-Type: application/json");
272                                 if (!empty($return)) {
273                                         $json = json_encode(end($return));
274                                         if (!empty($_GET['callback'])) {
275                                                 $json = $_GET['callback'] . "(" . $json . ")";
276                                         }
277                                         $return = $json;
278                                 }
279                                 break;
280                         case "rss":
281                                 header("Content-Type: application/rss+xml");
282                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
283                                 break;
284                         case "atom":
285                                 header("Content-Type: application/atom+xml");
286                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
287                                 break;
288                 }
289
290                 return $return;
291         }
292
293         /**
294          * Creates the XML from a JSON style array
295          *
296          * @param $data
297          * @param $root_element
298          * @return string
299          */
300         protected static function createXml($data, $root_element)
301         {
302                 return api_create_xml($data, $root_element);
303         }
304 }