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