3 * @copyright Copyright (C) 2010-2023, 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;
26 use Friendica\App\Router;
27 use Friendica\BaseModule;
28 use Friendica\Core\L10n;
29 use Friendica\Core\Logger;
30 use Friendica\Core\System;
31 use Friendica\Database\DBA;
33 use Friendica\Model\Contact;
34 use Friendica\Model\Item;
35 use Friendica\Model\Post;
36 use Friendica\Model\User;
37 use Friendica\Module\Api\ApiResponse;
38 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
39 use Friendica\Network\HTTPException;
40 use Friendica\Object\Api\Mastodon\TimelineOrderByTypes;
41 use Friendica\Security\BasicAuth;
42 use Friendica\Security\OAuth;
43 use Friendica\Util\DateTimeFormat;
44 use Friendica\Util\Profiler;
45 use Psr\Http\Message\ResponseInterface;
46 use Psr\Log\LoggerInterface;
48 class BaseApi extends BaseModule
50 const LOG_PREFIX = 'API {action} - ';
52 const SCOPE_READ = 'read';
53 const SCOPE_WRITE = 'write';
54 const SCOPE_FOLLOW = 'follow';
55 const SCOPE_PUSH = 'push';
60 protected static $boundaries = [];
65 protected static $request = [];
70 /** @var ApiResponse */
73 public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
75 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
81 * Additionally checks, if the caller is permitted to do this action
85 * @throws HTTPException\ForbiddenException
87 public function run(ModuleHTTPException $httpException, array $request = [], bool $scopecheck = true): ResponseInterface
90 switch ($this->args->getMethod()) {
95 self::checkAllowedScope(self::SCOPE_WRITE);
97 if (!self::getCurrentUserID()) {
98 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
104 return parent::run($httpException, $request);
108 * Processes data from GET requests and sets paging conditions
110 * @param array $request Custom REQUEST array
111 * @param array $condition Existing conditions to merge
112 * @return array paging data condition parameters data
115 public function addPagingConditions(array $request, array $condition): array
117 $requested_order = $request['friendica_order'];
118 if ($requested_order == TimelineOrderByTypes::ID) {
119 if (!empty($request['max_id'])) {
120 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", intval($request['max_id'])]);
123 if (!empty($request['since_id'])) {
124 $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", intval($request['since_id'])]);
127 if (!empty($request['min_id'])) {
128 $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", intval($request['min_id'])]);
131 switch ($requested_order) {
132 case TimelineOrderByTypes::CREATED:
133 $order_field = 'created';
136 $order_field = 'uri-id';
138 if (!empty($request['max_id'])) {
139 $condition = DBA::mergeConditions($condition, ["`$order_field` < ?", DateTimeFormat::convert($request['max_id'], DateTimeFormat::MYSQL)]);
143 if (!empty($request['min_id'])) {
144 $condition = DBA::mergeConditions($condition, ["`$order_field` > ?", DateTimeFormat::convert($request['min_id'], DateTimeFormat::MYSQL)]);
146 $params['order'] = [$order_field];
154 * Processes data from GET requests and sets paging conditions
156 * @param array $request Custom REQUEST array
157 * @param array $params Existing $params element to build on
158 * @return array ordering data added to the params blocks that was passed in
161 public function buildOrderAndLimitParams(array $request, array $params = []): array
163 $requested_order = $request['friendica_order'];
164 switch ($requested_order) {
165 case TimelineOrderByTypes::CREATED:
166 $order_field = 'created';
168 case TimelineOrderByTypes::ID:
170 $order_field = 'uri-id';
173 if(!empty($request['min_id'])) {
174 $params['order'] = [$order_field];
176 $params['order'] = [$order_field => true];
179 $params['limit']= $request['limit'];
185 * Processes data from GET requests and sets defaults
187 * @param array $defaults Associative array of expected request keys and their default typed value. A null
188 * value will remove the request key from the resulting value array.
189 * @param array $request Custom REQUEST array, superglobal instead
190 * @return array request data
193 public function getRequest(array $defaults, array $request): array
195 self::$request = $request;
196 self::$boundaries = [];
198 unset(self::$request['pagename']);
200 return $this->checkDefaults($defaults, $request);
204 * Set boundaries for the "link" header
205 * @param array $boundaries
208 protected static function setBoundaries(int $id)
210 if (!isset(self::$boundaries['min'])) {
211 self::$boundaries['min'] = $id;
214 if (!isset(self::$boundaries['max'])) {
215 self::$boundaries['max'] = $id;
218 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
219 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
223 * Get the "link" header with "next" and "prev" links
226 protected static function getLinkHeader(bool $asDate): string
228 if (empty(self::$boundaries)) {
232 $request = self::$request;
234 unset($request['min_id']);
235 unset($request['max_id']);
236 unset($request['since_id']);
238 $prev_request = $next_request = $request;
241 $max_date = new DateTime();
242 $max_date->setTimestamp(self::$boundaries['max']);
243 $min_date = new DateTime();
244 $min_date->setTimestamp(self::$boundaries['min']);
245 $prev_request['min_id'] = $max_date->format(DateTimeFormat::JSON);
246 $next_request['max_id'] = $min_date->format(DateTimeFormat::JSON);
248 $prev_request['min_id'] = self::$boundaries['max'];
249 $next_request['max_id'] = self::$boundaries['min'];
252 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
254 $prev = $command . '?' . http_build_query($prev_request);
255 $next = $command . '?' . http_build_query($next_request);
257 return 'Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"';
261 * Get the "link" header with "next" and "prev" links for an offset/limit type call
264 protected static function getOffsetAndLimitLinkHeader(int $offset, int $limit): string
266 $request = self::$request;
268 unset($request['offset']);
269 $request['limit'] = $limit;
271 $prev_request = $next_request = $request;
273 $prev_request['offset'] = $offset - $limit;
274 $next_request['offset'] = $offset + $limit;
276 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
278 $prev = $command . '?' . http_build_query($prev_request);
279 $next = $command . '?' . http_build_query($next_request);
281 if ($prev_request['offset'] >= 0) {
282 return 'Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"';
284 return 'Link: <' . $next . '>; rel="next"';
289 * Set the "link" header with "next" and "prev" links
292 protected static function setLinkHeader(bool $asDate = false)
294 $header = self::getLinkHeader($asDate);
295 if (!empty($header)) {
301 * Set the "link" header with "next" and "prev" links
304 protected static function setLinkHeaderByOffsetLimit(int $offset, int $limit)
306 $header = self::getOffsetAndLimitLinkHeader($offset, $limit);
307 if (!empty($header)) {
313 * Check if the app is known to support quoted posts
317 public static function appSupportsQuotes(): bool
319 $token = self::getCurrentApplication();
320 return (!empty($token['name']) && in_array($token['name'], ['Fedilab']));
324 * Get current application token
326 * @return array token
328 public static function getCurrentApplication()
330 $token = OAuth::getCurrentApplicationToken();
333 $token = BasicAuth::getCurrentApplicationToken();
340 * Get current user id, returns 0 if not logged in
342 * @return int User ID
344 public static function getCurrentUserID()
346 $uid = OAuth::getCurrentUserID();
349 $uid = BasicAuth::getCurrentUserID(false);
356 * Check if the provided scope does exist.
357 * halts execution on missing scope or when not logged in.
359 * @param string $scope the requested scope (read, write, follow, push)
361 public static function checkAllowedScope(string $scope)
363 $token = self::getCurrentApplication();
366 Logger::notice('Empty application token');
367 DI::mstdnError()->Forbidden();
370 if (!isset($token[$scope])) {
371 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
372 DI::mstdnError()->Forbidden();
375 if (empty($token[$scope])) {
376 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
377 DI::mstdnError()->Forbidden();
381 public static function checkThrottleLimit()
383 $uid = self::getCurrentUserID();
385 // Check for throttling (maximum posts per day, week and month)
386 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
387 if ($throttle_day > 0) {
388 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
390 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
391 $posts_day = Post::countThread($condition);
393 if ($posts_day > $throttle_day) {
394 Logger::notice('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
395 $error = DI::l10n()->t('Too Many Requests');
396 $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);
397 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
398 System::jsonError(429, $errorobj->toArray());
402 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
403 if ($throttle_week > 0) {
404 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
406 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
407 $posts_week = Post::countThread($condition);
409 if ($posts_week > $throttle_week) {
410 Logger::notice('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
411 $error = DI::l10n()->t('Too Many Requests');
412 $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);
413 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
414 System::jsonError(429, $errorobj->toArray());
418 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
419 if ($throttle_month > 0) {
420 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
422 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
423 $posts_month = Post::countThread($condition);
425 if ($posts_month > $throttle_month) {
426 Logger::notice('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
427 $error = DI::l10n()->t('Too Many Requests');
428 $error_description = DI::l10n()->tt('Monthly posting limit of %d post reached. The post was rejected.', 'Monthly posting limit of %d posts reached. The post was rejected.', $throttle_month);
429 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
430 System::jsonError(429, $errorobj->toArray());
435 public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
441 if (!empty($profileurl)) {
442 return Contact::getIdForURL($profileurl);
445 if (empty($cid) && !empty($screen_name)) {
446 if (strpos($screen_name, '@') !== false) {
447 return Contact::getIdForURL($screen_name, 0, false);
450 $user = User::getByNickname($screen_name, ['uid']);
451 if (!empty($user['uid'])) {
452 return Contact::getPublicIdByUserId($user['uid']);
457 return Contact::getPublicIdByUserId($uid);