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;
25 use Friendica\BaseModule;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Logger;
28 use Friendica\Core\System;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Post;
32 use Friendica\Model\User;
33 use Friendica\Module\Api\ApiResponse;
34 use Friendica\Network\HTTPException;
35 use Friendica\Security\BasicAuth;
36 use Friendica\Security\OAuth;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\HTTPInputData;
39 use Friendica\Util\Profiler;
40 use Psr\Log\LoggerInterface;
42 class BaseApi extends BaseModule
44 const LOG_PREFIX = 'API {action} - ';
46 const SCOPE_READ = 'read';
47 const SCOPE_WRITE = 'write';
48 const SCOPE_FOLLOW = 'follow';
49 const SCOPE_PUSH = 'push';
54 protected static $boundaries = [];
59 protected static $request = [];
64 /** @var ApiResponse */
67 public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
69 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
72 protected function delete()
74 self::checkAllowedScope(self::SCOPE_WRITE);
76 if (!$this->app->isLoggedIn()) {
77 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
81 protected function patch()
83 self::checkAllowedScope(self::SCOPE_WRITE);
85 if (!$this->app->isLoggedIn()) {
86 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
90 protected function post(array $request = [], array $post = [])
92 self::checkAllowedScope(self::SCOPE_WRITE);
94 if (!$this->app->isLoggedIn()) {
95 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
101 self::checkAllowedScope(self::SCOPE_WRITE);
103 if (!$this->app->isLoggedIn()) {
104 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
109 * Processes data from GET requests and sets defaults
111 * @param array $defaults Associative array of expected request keys and their default typed value. A null
112 * value will remove the request key from the resulting value array.
113 * @param array|null $request Custom REQUEST array, superglobal instead
114 * @return array request data
117 public static function getRequest(array $defaults, array $request = null): array
119 $httpinput = HTTPInputData::process();
120 $input = array_merge($httpinput['variables'], $httpinput['files'], $request ?? $_REQUEST);
122 self::$request = $input;
123 self::$boundaries = [];
125 unset(self::$request['pagename']);
129 foreach ($defaults as $parameter => $defaultvalue) {
130 if (is_string($defaultvalue)) {
131 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
132 } elseif (is_int($defaultvalue)) {
133 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
134 } elseif (is_float($defaultvalue)) {
135 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
136 } elseif (is_array($defaultvalue)) {
137 $request[$parameter] = $input[$parameter] ?? [];
138 } elseif (is_bool($defaultvalue)) {
139 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
141 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
145 foreach ($input ?? [] as $parameter => $value) {
146 if ($parameter == 'pagename') {
149 if (!in_array($parameter, array_keys($defaults))) {
150 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
154 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
159 * Set boundaries for the "link" header
160 * @param array $boundaries
163 protected static function setBoundaries(int $id)
165 if (!isset(self::$boundaries['min'])) {
166 self::$boundaries['min'] = $id;
169 if (!isset(self::$boundaries['max'])) {
170 self::$boundaries['max'] = $id;
173 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
174 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
178 * Set the "link" header with "next" and "prev" links
181 protected static function setLinkHeader()
183 if (empty(self::$boundaries)) {
187 $request = self::$request;
189 unset($request['min_id']);
190 unset($request['max_id']);
191 unset($request['since_id']);
193 $prev_request = $next_request = $request;
195 $prev_request['min_id'] = self::$boundaries['max'];
196 $next_request['max_id'] = self::$boundaries['min'];
198 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
200 $prev = $command . '?' . http_build_query($prev_request);
201 $next = $command . '?' . http_build_query($next_request);
203 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
207 * Get current application token
209 * @return array token
211 public static function getCurrentApplication()
213 $token = OAuth::getCurrentApplicationToken();
216 $token = BasicAuth::getCurrentApplicationToken();
223 * Get current user id, returns 0 if not logged in
225 * @return int User ID
227 public static function getCurrentUserID()
229 $uid = OAuth::getCurrentUserID();
232 $uid = BasicAuth::getCurrentUserID(false);
239 * Check if the provided scope does exist.
240 * halts execution on missing scope or when not logged in.
242 * @param string $scope the requested scope (read, write, follow, push)
244 public static function checkAllowedScope(string $scope)
246 $token = self::getCurrentApplication();
249 Logger::notice('Empty application token');
250 DI::mstdnError()->Forbidden();
253 if (!isset($token[$scope])) {
254 Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
255 DI::mstdnError()->Forbidden();
258 if (empty($token[$scope])) {
259 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
260 DI::mstdnError()->Forbidden();
264 public static function checkThrottleLimit()
266 $uid = self::getCurrentUserID();
268 // Check for throttling (maximum posts per day, week and month)
269 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
270 if ($throttle_day > 0) {
271 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
273 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
274 $posts_day = Post::countThread($condition);
276 if ($posts_day > $throttle_day) {
277 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
278 $error = DI::l10n()->t('Too Many Requests');
279 $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);
280 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
281 System::jsonError(429, $errorobj->toArray());
285 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
286 if ($throttle_week > 0) {
287 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
289 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
290 $posts_week = Post::countThread($condition);
292 if ($posts_week > $throttle_week) {
293 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
294 $error = DI::l10n()->t('Too Many Requests');
295 $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);
296 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
297 System::jsonError(429, $errorobj->toArray());
301 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
302 if ($throttle_month > 0) {
303 $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
305 $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
306 $posts_month = Post::countThread($condition);
308 if ($posts_month > $throttle_month) {
309 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
310 $error = DI::l10n()->t('Too Many Requests');
311 $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);
312 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
313 System::jsonError(429, $errorobj->toArray());
318 public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
324 if (!empty($profileurl)) {
325 return Contact::getIdForURL($profileurl);
328 if (empty($cid) && !empty($screen_name)) {
329 if (strpos($screen_name, '@') !== false) {
330 return Contact::getIdForURL($screen_name, 0, false);
333 $user = User::getByNickname($screen_name, ['uid']);
334 if (!empty($user['uid'])) {
335 return Contact::getPublicIdByUserId($user['uid']);
340 return Contact::getPublicIdByUserId($uid);