3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module;
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
28 use Friendica\Network\HTTPException;
29 use Friendica\Security\BasicAuth;
30 use Friendica\Security\OAuth;
31 use Friendica\Util\HTTPInputData;
33 require_once __DIR__ . '/../../include/api.php';
35 class BaseApi extends BaseModule
37 const SCOPE_READ = 'read';
38 const SCOPE_WRITE = 'write';
39 const SCOPE_FOLLOW = 'follow';
40 const SCOPE_PUSH = 'push';
43 * @var string json|xml|rss|atom
45 protected static $format = 'json';
50 protected static $boundaries = [];
55 protected static $request = [];
57 public static function init(array $parameters = [])
59 $arguments = DI::args();
61 if (substr($arguments->getCommand(), -4) === '.xml') {
62 self::$format = 'xml';
64 if (substr($arguments->getCommand(), -4) === '.rss') {
65 self::$format = 'rss';
67 if (substr($arguments->getCommand(), -4) === '.atom') {
68 self::$format = 'atom';
72 public static function delete(array $parameters = [])
74 self::checkAllowedScope(self::SCOPE_WRITE);
78 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
79 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
83 public static function patch(array $parameters = [])
85 self::checkAllowedScope(self::SCOPE_WRITE);
89 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
90 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
94 public static function post(array $parameters = [])
96 self::checkAllowedScope(self::SCOPE_WRITE);
100 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
101 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
105 public static function put(array $parameters = [])
107 self::checkAllowedScope(self::SCOPE_WRITE);
111 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
112 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
117 * Quit execution with the message that the endpoint isn't implemented
119 * @param string $method
122 public static function unsupported(string $method = 'all')
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());
133 * Processes data from GET requests and sets defaults
135 * @return array request data
137 public static function getRequest(array $defaults)
139 $httpinput = HTTPInputData::process();
140 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
142 self::$request = $input;
143 self::$boundaries = [];
145 unset(self::$request['pagename']);
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']);
161 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
165 foreach ($input ?? [] as $parameter => $value) {
166 if ($parameter == 'pagename') {
169 if (!in_array($parameter, array_keys($defaults))) {
170 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
174 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
179 * Set boundaries for the "link" header
180 * @param array $boundaries
184 protected static function setBoundaries(int $id)
186 if (!isset(self::$boundaries['min'])) {
187 self::$boundaries['min'] = $id;
190 if (!isset(self::$boundaries['max'])) {
191 self::$boundaries['max'] = $id;
194 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
195 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
199 * Set the "link" header with "next" and "prev" links
202 protected static function setLinkHeader()
204 if (empty(self::$boundaries)) {
208 $request = self::$request;
210 unset($request['min_id']);
211 unset($request['max_id']);
212 unset($request['since_id']);
214 $prev_request = $next_request = $request;
216 $prev_request['min_id'] = self::$boundaries['max'];
217 $next_request['max_id'] = self::$boundaries['min'];
219 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
221 $prev = $command . '?' . http_build_query($prev_request);
222 $next = $command . '?' . http_build_query($next_request);
224 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
228 * Get current application token
230 * @return array token
232 protected static function getCurrentApplication()
234 $token = OAuth::getCurrentApplicationToken();
237 $token = BasicAuth::getCurrentApplicationToken();
244 * Get current user id, returns 0 if not logged in
246 * @return int User ID
248 protected static function getCurrentUserID()
250 $uid = OAuth::getCurrentUserID();
253 $uid = BasicAuth::getCurrentUserID(false);
260 * Check if the provided scope does exist.
261 * halts execution on missing scope or when not logged in.
263 * @param string $scope the requested scope (read, write, follow, push)
265 public static function checkAllowedScope(string $scope)
267 $token = self::getCurrentApplication();
270 Logger::notice('Empty application token');
271 DI::mstdnError()->Forbidden();
274 if (!isset($token[$scope])) {
275 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
276 DI::mstdnError()->Forbidden();
279 if (empty($token[$scope])) {
280 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
281 DI::mstdnError()->Forbidden();
286 * Get user info array.
288 * @param int|string $contact_id Contact ID or URL
290 * @throws HTTPException\BadRequestException
291 * @throws HTTPException\InternalServerErrorException
292 * @throws HTTPException\UnauthorizedException
293 * @throws \ImagickException
295 protected static function getUser($contact_id = null)
297 return api_get_user(DI::app(), $contact_id);
301 * Formats the data according to the data type
303 * @param string $root_element
304 * @param array $data An array with a single element containing the returned result
305 * @return false|string
307 protected static function format(string $root_element, array $data)
309 $return = api_format_data($root_element, self::$format, $data);
311 switch (self::$format) {
313 header("Content-Type: text/xml");
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 . ")";
326 header("Content-Type: application/rss+xml");
327 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
330 header("Content-Type: application/atom+xml");
331 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
339 * Creates the XML from a JSON style array
342 * @param $root_element
345 protected static function createXml($data, $root_element)
347 return api_create_xml($data, $root_element);