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);
80 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
81 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
85 public static function patch(array $parameters = [])
87 self::checkAllowedScope(self::SCOPE_WRITE);
91 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
92 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
96 public static function post(array $parameters = [])
98 self::checkAllowedScope(self::SCOPE_WRITE);
102 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
103 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
107 public static function put(array $parameters = [])
109 self::checkAllowedScope(self::SCOPE_WRITE);
113 if (!empty($a->user['uid']) && $a->user['uid'] != self::getCurrentUserID()) {
114 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
119 * Quit execution with the message that the endpoint isn't implemented
121 * @param string $method
124 public static function unsupported(string $method = 'all')
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());
135 * Processes data from GET requests and sets defaults
137 * @return array request data
139 public static function getRequest(array $defaults)
141 $httpinput = HTTPInputData::process();
142 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
144 self::$request = $input;
145 self::$boundaries = [];
147 unset(self::$request['pagename']);
151 foreach ($defaults as $parameter => $defaultvalue) {
152 if (is_string($defaultvalue)) {
153 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
154 } elseif (is_int($defaultvalue)) {
155 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
156 } elseif (is_float($defaultvalue)) {
157 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
158 } elseif (is_array($defaultvalue)) {
159 $request[$parameter] = $input[$parameter] ?? [];
160 } elseif (is_bool($defaultvalue)) {
161 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
163 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
167 foreach ($input ?? [] as $parameter => $value) {
168 if ($parameter == 'pagename') {
171 if (!in_array($parameter, array_keys($defaults))) {
172 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
176 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
181 * Set boundaries for the "link" header
182 * @param array $boundaries
186 protected static function setBoundaries(int $id)
188 if (!isset(self::$boundaries['min'])) {
189 self::$boundaries['min'] = $id;
192 if (!isset(self::$boundaries['max'])) {
193 self::$boundaries['max'] = $id;
196 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
197 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
201 * Set the "link" header with "next" and "prev" links
204 protected static function setLinkHeader()
206 if (empty(self::$boundaries)) {
210 $request = self::$request;
212 unset($request['min_id']);
213 unset($request['max_id']);
214 unset($request['since_id']);
216 $prev_request = $next_request = $request;
218 $prev_request['min_id'] = self::$boundaries['max'];
219 $next_request['max_id'] = self::$boundaries['min'];
221 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
223 $prev = $command . '?' . http_build_query($prev_request);
224 $next = $command . '?' . http_build_query($next_request);
226 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
230 * Get current application token
232 * @return array token
234 protected static function getCurrentApplication()
236 $token = OAuth::getCurrentApplicationToken();
239 $token = BasicAuth::getCurrentApplicationToken();
246 * Get current user id, returns 0 if not logged in
248 * @return int User ID
250 protected static function getCurrentUserID()
252 $uid = OAuth::getCurrentUserID();
255 $uid = BasicAuth::getCurrentUserID(false);
262 * Check if the provided scope does exist.
263 * halts execution on missing scope or when not logged in.
265 * @param string $scope the requested scope (read, write, follow, push)
267 public static function checkAllowedScope(string $scope)
269 $token = self::getCurrentApplication();
272 Logger::notice('Empty application token');
273 DI::mstdnError()->Forbidden();
276 if (!isset($token[$scope])) {
277 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
278 DI::mstdnError()->Forbidden();
281 if (empty($token[$scope])) {
282 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
283 DI::mstdnError()->Forbidden();
287 public static function checkThrottleLimit()
289 $uid = self::getCurrentUserID();
291 // Check for throttling (maximum posts per day, week and month)
292 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
293 if ($throttle_day > 0) {
294 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
296 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
297 $posts_day = Post::countThread($condition);
299 if ($posts_day > $throttle_day) {
300 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
301 $error = DI::l10n()->t('Too Many Requests');
302 $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);
303 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
304 System::jsonError(429, $errorobj->toArray());
308 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
309 if ($throttle_week > 0) {
310 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
312 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
313 $posts_week = Post::countThread($condition);
315 if ($posts_week > $throttle_week) {
316 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
317 $error = DI::l10n()->t('Too Many Requests');
318 $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);
319 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
320 System::jsonError(429, $errorobj->toArray());
324 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
325 if ($throttle_month > 0) {
326 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
328 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
329 $posts_month = Post::countThread($condition);
331 if ($posts_month > $throttle_month) {
332 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
333 $error = DI::l10n()->t('Too Many Requests');
334 $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);
335 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
336 System::jsonError(429, $errorobj->toArray());
342 * Get user info array.
344 * @param int|string $contact_id Contact ID or URL
346 * @throws HTTPException\BadRequestException
347 * @throws HTTPException\InternalServerErrorException
348 * @throws HTTPException\UnauthorizedException
349 * @throws \ImagickException
351 protected static function getUser($contact_id = null)
353 return api_get_user(DI::app(), $contact_id);
357 * Formats the data according to the data type
359 * @param string $root_element
360 * @param array $data An array with a single element containing the returned result
361 * @return false|string
363 protected static function format(string $root_element, array $data)
365 $return = api_format_data($root_element, self::$format, $data);
367 switch (self::$format) {
369 header("Content-Type: text/xml");
372 header("Content-Type: application/json");
373 if (!empty($return)) {
374 $json = json_encode(end($return));
375 if (!empty($_GET['callback'])) {
376 $json = $_GET['callback'] . "(" . $json . ")";
382 header("Content-Type: application/rss+xml");
383 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
386 header("Content-Type: application/atom+xml");
387 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
395 * Creates the XML from a JSON style array
398 * @param $root_element
401 protected static function createXml($data, $root_element)
403 return api_create_xml($data, $root_element);