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\Model\Post;
29 use Friendica\Network\HTTPException;
30 use Friendica\Security\BasicAuth;
31 use Friendica\Security\OAuth;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\HTTPInputData;
35 require_once __DIR__ . '/../../include/api.php';
37 class BaseApi extends BaseModule
39 const SCOPE_READ = 'read';
40 const SCOPE_WRITE = 'write';
41 const SCOPE_FOLLOW = 'follow';
42 const SCOPE_PUSH = 'push';
45 * @var string json|xml|rss|atom
47 protected static $format = 'json';
52 protected static $boundaries = [];
57 protected static $request = [];
59 public static function init(array $parameters = [])
61 $arguments = DI::args();
63 if (substr($arguments->getCommand(), -4) === '.xml') {
64 self::$format = 'xml';
66 if (substr($arguments->getCommand(), -4) === '.rss') {
67 self::$format = 'rss';
69 if (substr($arguments->getCommand(), -4) === '.atom') {
70 self::$format = 'atom';
74 public static function delete(array $parameters = [])
76 self::checkAllowedScope(self::SCOPE_WRITE);
78 if (!DI::app()->isLoggedIn()) {
79 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
83 public static function patch(array $parameters = [])
85 self::checkAllowedScope(self::SCOPE_WRITE);
87 if (!DI::app()->isLoggedIn()) {
88 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
92 public static function post(array $parameters = [])
94 self::checkAllowedScope(self::SCOPE_WRITE);
96 if (!DI::app()->isLoggedIn()) {
97 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
101 public static function put(array $parameters = [])
103 self::checkAllowedScope(self::SCOPE_WRITE);
105 if (!DI::app()->isLoggedIn()) {
106 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
111 * Quit execution with the message that the endpoint isn't implemented
113 * @param string $method
116 public static function unsupported(string $method = 'all')
118 $path = DI::args()->getQueryString();
119 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => HTTPInputData::process()]);
120 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
121 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
122 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
123 System::jsonError(501, $errorobj->toArray());
127 * Processes data from GET requests and sets defaults
129 * @return array request data
131 public static function getRequest(array $defaults)
133 $httpinput = HTTPInputData::process();
134 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
136 self::$request = $input;
137 self::$boundaries = [];
139 unset(self::$request['pagename']);
143 foreach ($defaults as $parameter => $defaultvalue) {
144 if (is_string($defaultvalue)) {
145 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
146 } elseif (is_int($defaultvalue)) {
147 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
148 } elseif (is_float($defaultvalue)) {
149 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
150 } elseif (is_array($defaultvalue)) {
151 $request[$parameter] = $input[$parameter] ?? [];
152 } elseif (is_bool($defaultvalue)) {
153 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
155 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
159 foreach ($input ?? [] as $parameter => $value) {
160 if ($parameter == 'pagename') {
163 if (!in_array($parameter, array_keys($defaults))) {
164 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
168 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
173 * Set boundaries for the "link" header
174 * @param array $boundaries
178 protected static function setBoundaries(int $id)
180 if (!isset(self::$boundaries['min'])) {
181 self::$boundaries['min'] = $id;
184 if (!isset(self::$boundaries['max'])) {
185 self::$boundaries['max'] = $id;
188 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
189 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
193 * Set the "link" header with "next" and "prev" links
196 protected static function setLinkHeader()
198 if (empty(self::$boundaries)) {
202 $request = self::$request;
204 unset($request['min_id']);
205 unset($request['max_id']);
206 unset($request['since_id']);
208 $prev_request = $next_request = $request;
210 $prev_request['min_id'] = self::$boundaries['max'];
211 $next_request['max_id'] = self::$boundaries['min'];
213 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
215 $prev = $command . '?' . http_build_query($prev_request);
216 $next = $command . '?' . http_build_query($next_request);
218 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
222 * Get current application token
224 * @return array token
226 protected static function getCurrentApplication()
228 $token = OAuth::getCurrentApplicationToken();
231 $token = BasicAuth::getCurrentApplicationToken();
238 * Get current user id, returns 0 if not logged in
240 * @return int User ID
242 protected static function getCurrentUserID()
244 $uid = OAuth::getCurrentUserID();
247 $uid = BasicAuth::getCurrentUserID(false);
254 * Check if the provided scope does exist.
255 * halts execution on missing scope or when not logged in.
257 * @param string $scope the requested scope (read, write, follow, push)
259 public static function checkAllowedScope(string $scope)
261 $token = self::getCurrentApplication();
264 Logger::notice('Empty application token');
265 DI::mstdnError()->Forbidden();
268 if (!isset($token[$scope])) {
269 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
270 DI::mstdnError()->Forbidden();
273 if (empty($token[$scope])) {
274 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
275 DI::mstdnError()->Forbidden();
279 public static function checkThrottleLimit()
281 $uid = self::getCurrentUserID();
283 // Check for throttling (maximum posts per day, week and month)
284 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
285 if ($throttle_day > 0) {
286 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
288 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
289 $posts_day = Post::countThread($condition);
291 if ($posts_day > $throttle_day) {
292 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
293 $error = DI::l10n()->t('Too Many Requests');
294 $error_description = DI::l10n()->tt("Daily posting limit of %d post reached. The post was rejected.", "Daily posting limit of %d posts reached. The post was rejected.", $throttle_day);
295 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
296 System::jsonError(429, $errorobj->toArray());
300 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
301 if ($throttle_week > 0) {
302 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
304 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
305 $posts_week = Post::countThread($condition);
307 if ($posts_week > $throttle_week) {
308 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
309 $error = DI::l10n()->t('Too Many Requests');
310 $error_description = DI::l10n()->tt("Weekly posting limit of %d post reached. The post was rejected.", "Weekly posting limit of %d posts reached. The post was rejected.", $throttle_week);
311 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
312 System::jsonError(429, $errorobj->toArray());
316 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
317 if ($throttle_month > 0) {
318 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
320 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
321 $posts_month = Post::countThread($condition);
323 if ($posts_month > $throttle_month) {
324 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
325 $error = DI::l10n()->t('Too Many Requests');
326 $error_description = DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month);
327 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
328 System::jsonError(429, $errorobj->toArray());
334 * Get user info array.
336 * @param int|string $contact_id Contact ID or URL
338 * @throws HTTPException\BadRequestException
339 * @throws HTTPException\InternalServerErrorException
340 * @throws HTTPException\UnauthorizedException
341 * @throws \ImagickException
343 protected static function getUser($contact_id = null)
345 return api_get_user(DI::app(), $contact_id);
349 * Formats the data according to the data type
351 * @param string $root_element
352 * @param array $data An array with a single element containing the returned result
353 * @return false|string
355 protected static function format(string $root_element, array $data)
357 $return = api_format_data($root_element, self::$format, $data);
359 switch (self::$format) {
361 header("Content-Type: text/xml");
364 header("Content-Type: application/json");
365 if (!empty($return)) {
366 $json = json_encode(end($return));
367 if (!empty($_GET['callback'])) {
368 $json = $_GET['callback'] . "(" . $json . ")";
374 header("Content-Type: application/rss+xml");
375 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
378 header("Content-Type: application/atom+xml");
379 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
387 * Creates the XML from a JSON style array
390 * @param $root_element
393 protected static function createXml($data, $root_element)
395 return api_create_xml($data, $root_element);