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\Status;
41 use Friendica\Object\Api\Mastodon\TimelineOrderByTypes;
42 use Friendica\Security\BasicAuth;
43 use Friendica\Security\OAuth;
44 use Friendica\Util\DateTimeFormat;
45 use Friendica\Util\Profiler;
46 use Psr\Http\Message\ResponseInterface;
47 use Psr\Log\LoggerInterface;
49 class BaseApi extends BaseModule
51 const LOG_PREFIX = 'API {action} - ';
53 const SCOPE_READ = 'read';
54 const SCOPE_WRITE = 'write';
55 const SCOPE_FOLLOW = 'follow';
56 const SCOPE_PUSH = 'push';
61 protected static $boundaries = [];
66 protected static $request = [];
71 /** @var ApiResponse */
74 public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
76 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
82 * Additionally checks, if the caller is permitted to do this action
86 * @throws HTTPException\ForbiddenException
88 public function run(ModuleHTTPException $httpException, array $request = [], bool $scopecheck = true): ResponseInterface
91 switch ($this->args->getMethod()) {
96 self::checkAllowedScope(self::SCOPE_WRITE);
98 if (!self::getCurrentUserID()) {
99 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
105 return parent::run($httpException, $request);
109 * Processes data from GET requests and sets paging conditions
111 * @param array $request Custom REQUEST array
112 * @param array $condition Existing conditions to merge
113 * @return array paging data condition parameters data
116 protected function addPagingConditions(array $request, array $condition): array
118 $requested_order = $request['friendica_order'];
119 if ($requested_order == TimelineOrderByTypes::ID) {
120 if (!empty($request['max_id'])) {
121 $condition = DBA::mergeConditions($condition, ["`uri-id` < ?", intval($request['max_id'])]);
124 if (!empty($request['since_id'])) {
125 $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", intval($request['since_id'])]);
128 if (!empty($request['min_id'])) {
129 $condition = DBA::mergeConditions($condition, ["`uri-id` > ?", intval($request['min_id'])]);
132 switch ($requested_order) {
133 case TimelineOrderByTypes::RECEIVED:
134 case TimelineOrderByTypes::CHANGED:
135 case TimelineOrderByTypes::EDITED:
136 case TimelineOrderByTypes::CREATED:
137 case TimelineOrderByTypes::COMMENTED:
138 $order_field = $requested_order;
141 throw new \Exception("Unrecognized request order: $requested_order");
144 if (!empty($request['max_id'])) {
145 $condition = DBA::mergeConditions($condition, ["`$order_field` < ?", DateTimeFormat::convert($request['max_id'], DateTimeFormat::MYSQL)]);
148 if (!empty($request['since_id'])) {
149 $condition = DBA::mergeConditions($condition, ["`$order_field` > ?", DateTimeFormat::convert($request['since_id'], DateTimeFormat::MYSQL)]);
152 if (!empty($request['min_id'])) {
153 $condition = DBA::mergeConditions($condition, ["`$order_field` > ?", DateTimeFormat::convert($request['min_id'], DateTimeFormat::MYSQL)]);
161 * Processes data from GET requests and sets paging conditions
163 * @param array $request Custom REQUEST array
164 * @param array $params Existing $params element to build on
165 * @return array ordering data added to the params blocks that was passed in
168 protected function buildOrderAndLimitParams(array $request, array $params = []): array
170 $requested_order = $request['friendica_order'];
171 switch ($requested_order) {
172 case TimelineOrderByTypes::CHANGED:
173 $order_field = 'changed';
175 case TimelineOrderByTypes::CREATED:
176 $order_field = 'created';
178 case TimelineOrderByTypes::COMMENTED:
179 $order_field = 'commented';
181 case TimelineOrderByTypes::EDITED:
182 $order_field = 'edited';
184 case TimelineOrderByTypes::RECEIVED:
185 $order_field = 'received';
187 case TimelineOrderByTypes::ID:
189 $order_field = 'uri-id';
192 if (!empty($request['min_id'])) {
193 $params['order'] = [$order_field];
195 $params['order'] = [$order_field => true];
198 $params['limit'] = $request['limit'];
204 * Update the ID/time boundaries for this result set. Used for building Link Headers
206 * @param Status $status
207 * @param array $post_item
208 * @param string $order
212 protected function updateBoundaries(Status $status, array $post_item, string $order)
216 case TimelineOrderByTypes::CHANGED:
217 if (!empty($status->friendicaExtension()->changedAt())) {
218 self::setBoundaries(new DateTime(DateTimeFormat::utc($status->friendicaExtension()->changedAt(), DateTimeFormat::JSON)));
221 case TimelineOrderByTypes::CREATED:
222 if (!empty($status->createdAt())) {
223 self::setBoundaries(new DateTime(DateTimeFormat::utc($status->createdAt(), DateTimeFormat::JSON)));
226 case TimelineOrderByTypes::COMMENTED:
227 if (!empty($status->friendicaExtension()->commentedAt())) {
228 self::setBoundaries(new DateTime(DateTimeFormat::utc($status->friendicaExtension()->commentedAt(), DateTimeFormat::JSON)));
231 case TimelineOrderByTypes::EDITED:
232 if (!empty($status->friendicaExtension()->editedAt())) {
233 self::setBoundaries(new DateTime(DateTimeFormat::utc($status->friendicaExtension()->editedAt(), DateTimeFormat::JSON)));
236 case TimelineOrderByTypes::RECEIVED:
237 if (!empty($status->friendicaExtension()->receivedAt())) {
238 self::setBoundaries(new DateTime(DateTimeFormat::utc($status->friendicaExtension()->receivedAt(), DateTimeFormat::JSON)));
241 case TimelineOrderByTypes::ID:
243 self::setBoundaries($post_item['uri-id']);
245 } catch (\Exception $e) {
246 Logger::debug('Error processing page boundary calculation, skipping', ['error' => $e]);
251 * Processes data from GET requests and sets defaults
253 * @param array $defaults Associative array of expected request keys and their default typed value. A null
254 * value will remove the request key from the resulting value array.
255 * @param array $request Custom REQUEST array, superglobal instead
256 * @return array request data
259 public function getRequest(array $defaults, array $request): array
261 self::$request = $request;
262 self::$boundaries = [];
264 unset(self::$request['pagename']);
266 return $this->checkDefaults($defaults, $request);
270 * Set boundaries for the "link" header
271 * @param array $boundaries
272 * @param int|\DateTime $id
274 protected static function setBoundaries($id)
276 if (!isset(self::$boundaries['min'])) {
277 self::$boundaries['min'] = $id;
280 if (!isset(self::$boundaries['max'])) {
281 self::$boundaries['max'] = $id;
284 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
285 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
289 * Get the "link" header with "next" and "prev" links
292 protected static function getLinkHeader(bool $asDate = false): string
294 if (empty(self::$boundaries)) {
298 $request = self::$request;
300 unset($request['min_id']);
301 unset($request['max_id']);
302 unset($request['since_id']);
304 $prev_request = $next_request = $request;
307 $max_date = self::$boundaries['max'];
308 $min_date = self::$boundaries['min'];
309 $prev_request['min_id'] = $max_date->format(DateTimeFormat::JSON);
310 $next_request['max_id'] = $min_date->format(DateTimeFormat::JSON);
312 $prev_request['min_id'] = self::$boundaries['max'];
313 $next_request['max_id'] = self::$boundaries['min'];
316 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
318 $prev = $command . '?' . http_build_query($prev_request);
319 $next = $command . '?' . http_build_query($next_request);
321 return 'Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"';
325 * Get the "link" header with "next" and "prev" links for an offset/limit type call
328 protected static function getOffsetAndLimitLinkHeader(int $offset, int $limit): string
330 $request = self::$request;
332 unset($request['offset']);
333 $request['limit'] = $limit;
335 $prev_request = $next_request = $request;
337 $prev_request['offset'] = $offset - $limit;
338 $next_request['offset'] = $offset + $limit;
340 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
342 $prev = $command . '?' . http_build_query($prev_request);
343 $next = $command . '?' . http_build_query($next_request);
345 if ($prev_request['offset'] >= 0) {
346 return 'Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"';
348 return 'Link: <' . $next . '>; rel="next"';
353 * Set the "link" header with "next" and "prev" links
356 protected static function setLinkHeader(bool $asDate = false)
358 $header = self::getLinkHeader($asDate);
359 if (!empty($header)) {
365 * Set the "link" header with "next" and "prev" links
368 protected static function setLinkHeaderByOffsetLimit(int $offset, int $limit)
370 $header = self::getOffsetAndLimitLinkHeader($offset, $limit);
371 if (!empty($header)) {
377 * Check if the app is known to support quoted posts
381 public static function appSupportsQuotes(): bool
383 $token = self::getCurrentApplication();
384 return (!empty($token['name']) && in_array($token['name'], ['Fedilab']));
388 * Get current application token
390 * @return array token
392 public static function getCurrentApplication()
394 $token = OAuth::getCurrentApplicationToken();
397 $token = BasicAuth::getCurrentApplicationToken();
404 * Get current user id, returns 0 if not logged in
406 * @return int User ID
408 public static function getCurrentUserID()
410 $uid = OAuth::getCurrentUserID();
413 $uid = BasicAuth::getCurrentUserID(false);
420 * Check if the provided scope does exist.
421 * halts execution on missing scope or when not logged in.
423 * @param string $scope the requested scope (read, write, follow, push)
425 public static function checkAllowedScope(string $scope)
427 $token = self::getCurrentApplication();
430 Logger::notice('Empty application token');
431 DI::mstdnError()->Forbidden();
434 if (!isset($token[$scope])) {
435 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
436 DI::mstdnError()->Forbidden();
439 if (empty($token[$scope])) {
440 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
441 DI::mstdnError()->Forbidden();
445 public static function checkThrottleLimit()
447 $uid = self::getCurrentUserID();
449 // Check for throttling (maximum posts per day, week and month)
450 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
451 if ($throttle_day > 0) {
452 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
454 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
455 $posts_day = Post::countThread($condition);
457 if ($posts_day > $throttle_day) {
458 Logger::notice('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
459 $error = DI::l10n()->t('Too Many Requests');
460 $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);
461 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
462 System::jsonError(429, $errorobj->toArray());
466 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
467 if ($throttle_week > 0) {
468 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
470 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
471 $posts_week = Post::countThread($condition);
473 if ($posts_week > $throttle_week) {
474 Logger::notice('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
475 $error = DI::l10n()->t('Too Many Requests');
476 $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);
477 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
478 System::jsonError(429, $errorobj->toArray());
482 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
483 if ($throttle_month > 0) {
484 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
486 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
487 $posts_month = Post::countThread($condition);
489 if ($posts_month > $throttle_month) {
490 Logger::notice('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
491 $error = DI::l10n()->t('Too Many Requests');
492 $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);
493 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
494 System::jsonError(429, $errorobj->toArray());
499 public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
505 if (!empty($profileurl)) {
506 return Contact::getIdForURL($profileurl);
509 if (empty($cid) && !empty($screen_name)) {
510 if (strpos($screen_name, '@') !== false) {
511 return Contact::getIdForURL($screen_name, 0, false);
514 $user = User::getByNickname($screen_name, ['uid']);
515 if (!empty($user['uid'])) {
516 return Contact::getPublicIdByUserId($user['uid']);
521 return Contact::getPublicIdByUserId($uid);