]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Merge pull request #10381 from annando/basic-auth
[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                 self::checkAllowedScope(self::SCOPE_WRITE);
65
66                 $a = DI::app();
67
68                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
69                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
70                 }
71         }
72
73         public static function patch(array $parameters = [])
74         {
75                 self::checkAllowedScope(self::SCOPE_WRITE);
76
77                 $a = DI::app();
78
79                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
80                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
81                 }
82         }
83
84         public static function post(array $parameters = [])
85         {
86                 self::checkAllowedScope(self::SCOPE_WRITE);
87
88                 $a = DI::app();
89
90                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
91                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
92                 }
93         }
94
95         public static function put(array $parameters = [])
96         {
97                 self::checkAllowedScope(self::SCOPE_WRITE);
98
99                 $a = DI::app();
100
101                 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
102                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
103                 }
104         }
105
106         /**
107          * Quit execution with the message that the endpoint isn't implemented
108          *
109          * @param string $method
110          * @return void
111          */
112         public static function unsupported(string $method = 'all')
113         {
114                 $path = DI::args()->getQueryString();
115                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => HTTPInputData::process()]);
116                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
117                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
118                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
119                 System::jsonError(501, $errorobj->toArray());
120         }
121
122         /**
123          * Processes data from GET requests and sets defaults
124          *
125          * @return array request data
126          */
127         public static function getRequest(array $defaults)
128         {
129                 $httpinput = HTTPInputData::process();
130                 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
131
132                 $request = [];
133
134                 foreach ($defaults as $parameter => $defaultvalue) {
135                         if (is_string($defaultvalue)) {
136                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
137                         } elseif (is_int($defaultvalue)) {
138                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
139                         } elseif (is_float($defaultvalue)) {
140                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
141                         } elseif (is_array($defaultvalue)) {
142                                 $request[$parameter] = $input[$parameter] ?? [];
143                         } elseif (is_bool($defaultvalue)) {
144                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
145                         } else {
146                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
147                         }
148                 }
149
150                 foreach ($input ?? [] as $parameter => $value) {
151                         if ($parameter == 'pagename') {
152                                 continue;
153                         }
154                         if (!in_array($parameter, array_keys($defaults))) {
155                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
156                         }
157                 }
158
159                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
160                 return $request;
161         }
162
163         /**
164          * Get current application token
165          *
166          * @return array token
167          */
168         protected static function getCurrentApplication()
169         {
170                 $token = OAuth::getCurrentApplicationToken();
171
172                 if (empty($token)) {
173                         $token = BasicAuth::getCurrentApplicationToken();
174                 }
175
176                 return $token;
177         }
178
179         /**
180          * Get current user id, returns 0 if not logged in
181          *
182          * @return int User ID
183          */
184         protected static function getCurrentUserID()
185         {
186                 $uid = OAuth::getCurrentUserID();
187
188                 if (empty($uid)) {
189                         $uid = BasicAuth::getCurrentUserID(false);
190                 }
191
192                 return (int)$uid;
193         }
194
195         /**
196          * Check if the provided scope does exist.
197          * halts execution on missing scope or when not logged in.
198          *
199          * @param string $scope the requested scope (read, write, follow, push)
200          */
201         public static function checkAllowedScope(string $scope)
202         {
203                 $token = self::getCurrentApplication();
204
205                 if (empty($token)) {
206                         Logger::notice('Empty application token');
207                         DI::mstdnError()->Forbidden();
208                 }
209
210                 if (!isset($token[$scope])) {
211                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
212                         DI::mstdnError()->Forbidden();
213                 }
214
215                 if (empty($token[$scope])) {
216                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
217                         DI::mstdnError()->Forbidden();
218                 }
219         }
220
221         /**
222          * Get user info array.
223          *
224          * @param int|string $contact_id Contact ID or URL
225          * @return array|bool
226          * @throws HTTPException\BadRequestException
227          * @throws HTTPException\InternalServerErrorException
228          * @throws HTTPException\UnauthorizedException
229          * @throws \ImagickException
230          */
231         protected static function getUser($contact_id = null)
232         {
233                 return api_get_user(DI::app(), $contact_id);
234         }
235
236         /**
237          * Formats the data according to the data type
238          *
239          * @param string $root_element
240          * @param array $data An array with a single element containing the returned result
241          * @return false|string
242          */
243         protected static function format(string $root_element, array $data)
244         {
245                 $return = api_format_data($root_element, self::$format, $data);
246
247                 switch (self::$format) {
248                         case "xml":
249                                 header("Content-Type: text/xml");
250                                 break;
251                         case "json":
252                                 header("Content-Type: application/json");
253                                 if (!empty($return)) {
254                                         $json = json_encode(end($return));
255                                         if (!empty($_GET['callback'])) {
256                                                 $json = $_GET['callback'] . "(" . $json . ")";
257                                         }
258                                         $return = $json;
259                                 }
260                                 break;
261                         case "rss":
262                                 header("Content-Type: application/rss+xml");
263                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
264                                 break;
265                         case "atom":
266                                 header("Content-Type: application/atom+xml");
267                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
268                                 break;
269                 }
270
271                 return $return;
272         }
273
274         /**
275          * Creates the XML from a JSON style array
276          *
277          * @param $data
278          * @param $root_element
279          * @return string
280          */
281         protected static function createXml($data, $root_element)
282         {
283                 return api_create_xml($data, $root_element);
284         }
285 }