3 * @copyright Copyright (C) 2010-2022, 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;
25 use Friendica\App\Router;
26 use Friendica\BaseModule;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Logger;
29 use Friendica\Core\System;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Post;
33 use Friendica\Model\User;
34 use Friendica\Module\Api\ApiResponse;
35 use Friendica\Network\HTTPException;
36 use Friendica\Security\BasicAuth;
37 use Friendica\Security\OAuth;
38 use Friendica\Util\DateTimeFormat;
39 use Friendica\Util\Profiler;
40 use Psr\Http\Message\ResponseInterface;
41 use Psr\Log\LoggerInterface;
43 class BaseApi extends BaseModule
45 const LOG_PREFIX = 'API {action} - ';
47 const SCOPE_READ = 'read';
48 const SCOPE_WRITE = 'write';
49 const SCOPE_FOLLOW = 'follow';
50 const SCOPE_PUSH = 'push';
55 protected static $boundaries = [];
60 protected static $request = [];
65 /** @var ApiResponse */
68 public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
70 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
76 * Additionally checks, if the caller is permitted to do this action
80 * @throws HTTPException\ForbiddenException
82 public function run(array $request = [], bool $scopecheck = true): ResponseInterface
85 switch ($this->server['REQUEST_METHOD'] ?? Router::GET) {
90 self::checkAllowedScope(self::SCOPE_WRITE);
92 if (!self::getCurrentUserID()) {
93 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
99 return parent::run($request);
103 * Processes data from GET requests and sets defaults
105 * @param array $defaults Associative array of expected request keys and their default typed value. A null
106 * value will remove the request key from the resulting value array.
107 * @param array $request Custom REQUEST array, superglobal instead
108 * @return array request data
111 public function getRequest(array $defaults, array $request): array
113 self::$request = $request;
114 self::$boundaries = [];
116 unset(self::$request['pagename']);
118 return $this->checkDefaults($defaults, $request);
122 * Set boundaries for the "link" header
123 * @param array $boundaries
126 protected static function setBoundaries(int $id)
128 if (!isset(self::$boundaries['min'])) {
129 self::$boundaries['min'] = $id;
132 if (!isset(self::$boundaries['max'])) {
133 self::$boundaries['max'] = $id;
136 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
137 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
141 * Set the "link" header with "next" and "prev" links
144 protected static function setLinkHeader()
146 if (empty(self::$boundaries)) {
150 $request = self::$request;
152 unset($request['min_id']);
153 unset($request['max_id']);
154 unset($request['since_id']);
156 $prev_request = $next_request = $request;
158 $prev_request['min_id'] = self::$boundaries['max'];
159 $next_request['max_id'] = self::$boundaries['min'];
161 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
163 $prev = $command . '?' . http_build_query($prev_request);
164 $next = $command . '?' . http_build_query($next_request);
166 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
170 * Get current application token
172 * @return array token
174 public static function getCurrentApplication()
176 $token = OAuth::getCurrentApplicationToken();
179 $token = BasicAuth::getCurrentApplicationToken();
186 * Get current user id, returns 0 if not logged in
188 * @return int User ID
190 public static function getCurrentUserID()
192 $uid = OAuth::getCurrentUserID();
195 $uid = BasicAuth::getCurrentUserID(false);
202 * Check if the provided scope does exist.
203 * halts execution on missing scope or when not logged in.
205 * @param string $scope the requested scope (read, write, follow, push)
207 public static function checkAllowedScope(string $scope)
209 $token = self::getCurrentApplication();
212 Logger::notice('Empty application token');
213 DI::mstdnError()->Forbidden();
216 if (!isset($token[$scope])) {
217 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
218 DI::mstdnError()->Forbidden();
221 if (empty($token[$scope])) {
222 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
223 DI::mstdnError()->Forbidden();
227 public static function checkThrottleLimit()
229 $uid = self::getCurrentUserID();
231 // Check for throttling (maximum posts per day, week and month)
232 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
233 if ($throttle_day > 0) {
234 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
236 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
237 $posts_day = Post::countThread($condition);
239 if ($posts_day > $throttle_day) {
240 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
241 $error = DI::l10n()->t('Too Many Requests');
242 $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);
243 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
244 System::jsonError(429, $errorobj->toArray());
248 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
249 if ($throttle_week > 0) {
250 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
252 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
253 $posts_week = Post::countThread($condition);
255 if ($posts_week > $throttle_week) {
256 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
257 $error = DI::l10n()->t('Too Many Requests');
258 $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);
259 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
260 System::jsonError(429, $errorobj->toArray());
264 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
265 if ($throttle_month > 0) {
266 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
268 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
269 $posts_month = Post::countThread($condition);
271 if ($posts_month > $throttle_month) {
272 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
273 $error = DI::l10n()->t('Too Many Requests');
274 $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);
275 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
276 System::jsonError(429, $errorobj->toArray());
281 public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
287 if (!empty($profileurl)) {
288 return Contact::getIdForURL($profileurl);
291 if (empty($cid) && !empty($screen_name)) {
292 if (strpos($screen_name, '@') !== false) {
293 return Contact::getIdForURL($screen_name, 0, false);
296 $user = User::getByNickname($screen_name, ['uid']);
297 if (!empty($user['uid'])) {
298 return Contact::getPublicIdByUserId($user['uid']);
303 return Contact::getPublicIdByUserId($uid);