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\Arrays;
33 use Friendica\Util\DateTimeFormat;
34 use Friendica\Util\HTTPInputData;
35 use Friendica\Util\XML;
37 require_once __DIR__ . '/../../include/api.php';
39 class BaseApi extends BaseModule
41 const SCOPE_READ = 'read';
42 const SCOPE_WRITE = 'write';
43 const SCOPE_FOLLOW = 'follow';
44 const SCOPE_PUSH = 'push';
49 protected static $boundaries = [];
54 protected static $request = [];
56 public static function delete(array $parameters = [])
58 self::checkAllowedScope(self::SCOPE_WRITE);
60 if (!DI::app()->isLoggedIn()) {
61 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
65 public static function patch(array $parameters = [])
67 self::checkAllowedScope(self::SCOPE_WRITE);
69 if (!DI::app()->isLoggedIn()) {
70 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
74 public static function post(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 put(array $parameters = [])
85 self::checkAllowedScope(self::SCOPE_WRITE);
87 if (!DI::app()->isLoggedIn()) {
88 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
93 * Processes data from GET requests and sets defaults
95 * @return array request data
97 public static function getRequest(array $defaults)
99 $httpinput = HTTPInputData::process();
100 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
102 self::$request = $input;
103 self::$boundaries = [];
105 unset(self::$request['pagename']);
109 foreach ($defaults as $parameter => $defaultvalue) {
110 if (is_string($defaultvalue)) {
111 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
112 } elseif (is_int($defaultvalue)) {
113 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
114 } elseif (is_float($defaultvalue)) {
115 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
116 } elseif (is_array($defaultvalue)) {
117 $request[$parameter] = $input[$parameter] ?? [];
118 } elseif (is_bool($defaultvalue)) {
119 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
121 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
125 foreach ($input ?? [] as $parameter => $value) {
126 if ($parameter == 'pagename') {
129 if (!in_array($parameter, array_keys($defaults))) {
130 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
134 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
139 * Set boundaries for the "link" header
140 * @param array $boundaries
144 protected static function setBoundaries(int $id)
146 if (!isset(self::$boundaries['min'])) {
147 self::$boundaries['min'] = $id;
150 if (!isset(self::$boundaries['max'])) {
151 self::$boundaries['max'] = $id;
154 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
155 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
159 * Set the "link" header with "next" and "prev" links
162 protected static function setLinkHeader()
164 if (empty(self::$boundaries)) {
168 $request = self::$request;
170 unset($request['min_id']);
171 unset($request['max_id']);
172 unset($request['since_id']);
174 $prev_request = $next_request = $request;
176 $prev_request['min_id'] = self::$boundaries['max'];
177 $next_request['max_id'] = self::$boundaries['min'];
179 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
181 $prev = $command . '?' . http_build_query($prev_request);
182 $next = $command . '?' . http_build_query($next_request);
184 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
188 * Get current application token
190 * @return array token
192 protected static function getCurrentApplication()
194 $token = OAuth::getCurrentApplicationToken();
197 $token = BasicAuth::getCurrentApplicationToken();
204 * Get current user id, returns 0 if not logged in
206 * @return int User ID
208 public static function getCurrentUserID()
210 $uid = OAuth::getCurrentUserID();
213 $uid = BasicAuth::getCurrentUserID(false);
220 * Check if the provided scope does exist.
221 * halts execution on missing scope or when not logged in.
223 * @param string $scope the requested scope (read, write, follow, push)
225 public static function checkAllowedScope(string $scope)
227 $token = self::getCurrentApplication();
230 Logger::notice('Empty application token');
231 DI::mstdnError()->Forbidden();
234 if (!isset($token[$scope])) {
235 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
236 DI::mstdnError()->Forbidden();
239 if (empty($token[$scope])) {
240 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
241 DI::mstdnError()->Forbidden();
245 public static function checkThrottleLimit()
247 $uid = self::getCurrentUserID();
249 // Check for throttling (maximum posts per day, week and month)
250 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
251 if ($throttle_day > 0) {
252 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
254 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
255 $posts_day = Post::countThread($condition);
257 if ($posts_day > $throttle_day) {
258 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
259 $error = DI::l10n()->t('Too Many Requests');
260 $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);
261 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
262 System::jsonError(429, $errorobj->toArray());
266 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
267 if ($throttle_week > 0) {
268 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
270 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
271 $posts_week = Post::countThread($condition);
273 if ($posts_week > $throttle_week) {
274 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
275 $error = DI::l10n()->t('Too Many Requests');
276 $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);
277 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
278 System::jsonError(429, $errorobj->toArray());
282 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
283 if ($throttle_month > 0) {
284 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
286 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
287 $posts_month = Post::countThread($condition);
289 if ($posts_month > $throttle_month) {
290 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
291 $error = DI::l10n()->t('Too Many Requests');
292 $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);
293 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
294 System::jsonError(429, $errorobj->toArray());
300 * Get user info array.
302 * @param int|string $contact_id Contact ID or URL
304 * @throws HTTPException\BadRequestException
305 * @throws HTTPException\InternalServerErrorException
306 * @throws HTTPException\UnauthorizedException
307 * @throws \ImagickException
309 protected static function getUser($contact_id = null)
311 return api_get_user($contact_id);