]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Merge branch 'develop' into notifications-summary
[friendica.git] / src / Module / BaseApi.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2023, the Friendica project
4  *
5  * @license GNU AGPL version 3 or any later version
6  *
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.
11  *
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.
16  *
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/>.
19  *
20  */
21
22 namespace Friendica\Module;
23
24 use Friendica\App;
25 use Friendica\App\Router;
26 use Friendica\BaseModule;
27 use Friendica\Core\L10n;
28 use Friendica\Core\Logger;
29 use Friendica\Core\System;
30 use Friendica\DI;
31 use Friendica\Model\Contact;
32 use Friendica\Model\Item;
33 use Friendica\Model\Post;
34 use Friendica\Model\User;
35 use Friendica\Module\Api\ApiResponse;
36 use Friendica\Module\Special\HTTPException as ModuleHTTPException;
37 use Friendica\Network\HTTPException;
38 use Friendica\Security\BasicAuth;
39 use Friendica\Security\OAuth;
40 use Friendica\Util\DateTimeFormat;
41 use Friendica\Util\Profiler;
42 use Psr\Http\Message\ResponseInterface;
43 use Psr\Log\LoggerInterface;
44
45 class BaseApi extends BaseModule
46 {
47         const LOG_PREFIX = 'API {action} - ';
48
49         const SCOPE_READ   = 'read';
50         const SCOPE_WRITE  = 'write';
51         const SCOPE_FOLLOW = 'follow';
52         const SCOPE_PUSH   = 'push';
53
54         /**
55          * @var array
56          */
57         protected static $boundaries = [];
58
59         /**
60          * @var array
61          */
62         protected static $request = [];
63
64         /** @var App */
65         protected $app;
66
67         /** @var ApiResponse */
68         protected $response;
69
70         public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
71         {
72                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
73
74                 $this->app = $app;
75         }
76
77         /**
78          * Additionally checks, if the caller is permitted to do this action
79          *
80          * {@inheritDoc}
81          *
82          * @throws HTTPException\ForbiddenException
83          */
84         public function run(ModuleHTTPException $httpException, array $request = [], bool $scopecheck = true): ResponseInterface
85         {
86                 if ($scopecheck) {
87                         switch ($this->args->getMethod()) {
88                                 case Router::DELETE:
89                                 case Router::PATCH:
90                                 case Router::POST:
91                                 case Router::PUT:
92                                         self::checkAllowedScope(self::SCOPE_WRITE);
93
94                                         if (!self::getCurrentUserID()) {
95                                                 throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
96                                         }
97                                         break;
98                         }
99                 }
100
101                 return parent::run($httpException, $request);
102         }
103
104         /**
105          * Processes data from GET requests and sets defaults
106          *
107          * @param array      $defaults Associative array of expected request keys and their default typed value. A null
108          *                             value will remove the request key from the resulting value array.
109          * @param array $request       Custom REQUEST array, superglobal instead
110          * @return array request data
111          * @throws \Exception
112          */
113         public function getRequest(array $defaults, array $request): array
114         {
115                 self::$request    = $request;
116                 self::$boundaries = [];
117
118                 unset(self::$request['pagename']);
119
120                 return $this->checkDefaults($defaults, $request);
121         }
122
123         /**
124          * Set boundaries for the "link" header
125          * @param array $boundaries
126          * @param int $id
127          */
128         protected static function setBoundaries(int $id)
129         {
130                 if (!isset(self::$boundaries['min'])) {
131                         self::$boundaries['min'] = $id;
132                 }
133
134                 if (!isset(self::$boundaries['max'])) {
135                         self::$boundaries['max'] = $id;
136                 }
137
138                 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
139                 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
140         }
141
142         /**
143          * Get the "link" header with "next" and "prev" links
144          * @return string
145          */
146         protected static function getLinkHeader(): string
147         {
148                 if (empty(self::$boundaries)) {
149                         return '';
150                 }
151
152                 $request = self::$request;
153
154                 unset($request['min_id']);
155                 unset($request['max_id']);
156                 unset($request['since_id']);
157
158                 $prev_request = $next_request = $request;
159
160                 $prev_request['min_id'] = self::$boundaries['max'];
161                 $next_request['max_id'] = self::$boundaries['min'];
162
163                 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
164
165                 $prev = $command . '?' . http_build_query($prev_request);
166                 $next = $command . '?' . http_build_query($next_request);
167
168                 return 'Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"';
169         }
170
171         /**
172          * Get the "link" header with "next" and "prev" links for an offset/limit type call
173          * @return string
174          */
175         protected static function getOffsetAndLimitLinkHeader(int $offset, int $limit): string
176         {
177                 $request = self::$request;
178
179                 unset($request['offset']);
180                 $request['limit'] = $limit;
181
182                 $prev_request = $next_request = $request;
183
184                 $prev_request['offset'] = $offset - $limit;
185                 $next_request['offset'] = $offset + $limit;
186
187                 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
188
189                 $prev = $command . '?' . http_build_query($prev_request);
190                 $next = $command . '?' . http_build_query($next_request);
191
192                 if ($prev_request['offset'] >= 0) {
193                         return 'Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"';
194                 } else {
195                         return 'Link: <' . $next . '>; rel="next"';
196                 }
197         }
198
199         /**
200          * Set the "link" header with "next" and "prev" links
201          * @return void
202          */
203         protected static function setLinkHeader()
204         {
205                 $header = self::getLinkHeader();
206                 if (!empty($header)) {
207                         header($header);
208                 }
209         }
210
211         /**
212          * Set the "link" header with "next" and "prev" links
213          * @return void
214          */
215         protected static function setLinkHeaderByOffsetLimit(int $offset, int $limit)
216         {
217                 $header = self::getOffsetAndLimitLinkHeader($offset, $limit);
218                 if (!empty($header)) {
219                         header($header);
220                 }
221         }
222
223         /**
224          * Check if the app is known to support quoted posts
225          *
226          * @return bool
227          */
228         public static function appSupportsQuotes(): bool
229         {
230                 $token = self::getCurrentApplication();
231                 return (!empty($token['name']) && in_array($token['name'], ['Fedilab']));
232         }
233
234         /**
235          * Get current application token
236          *
237          * @return array token
238          */
239         public static function getCurrentApplication()
240         {
241                 $token = OAuth::getCurrentApplicationToken();
242
243                 if (empty($token)) {
244                         $token = BasicAuth::getCurrentApplicationToken();
245                 }
246
247                 return $token;
248         }
249
250         /**
251          * Get current user id, returns 0 if not logged in
252          *
253          * @return int User ID
254          */
255         public static function getCurrentUserID()
256         {
257                 $uid = OAuth::getCurrentUserID();
258
259                 if (empty($uid)) {
260                         $uid = BasicAuth::getCurrentUserID(false);
261                 }
262
263                 return (int)$uid;
264         }
265
266         /**
267          * Check if the provided scope does exist.
268          * halts execution on missing scope or when not logged in.
269          *
270          * @param string $scope the requested scope (read, write, follow, push)
271          */
272         public static function checkAllowedScope(string $scope)
273         {
274                 $token = self::getCurrentApplication();
275
276                 if (empty($token)) {
277                         Logger::notice('Empty application token');
278                         DI::mstdnError()->Forbidden();
279                 }
280
281                 if (!isset($token[$scope])) {
282                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
283                         DI::mstdnError()->Forbidden();
284                 }
285
286                 if (empty($token[$scope])) {
287                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
288                         DI::mstdnError()->Forbidden();
289                 }
290         }
291
292         public static function checkThrottleLimit()
293         {
294                 $uid = self::getCurrentUserID();
295
296                 // Check for throttling (maximum posts per day, week and month)
297                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
298                 if ($throttle_day > 0) {
299                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
300
301                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
302                         $posts_day = Post::countThread($condition);
303
304                         if ($posts_day > $throttle_day) {
305                                 Logger::notice('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
306                                 $error = DI::l10n()->t('Too Many Requests');
307                                 $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);
308                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
309                                 System::jsonError(429, $errorobj->toArray());
310                         }
311                 }
312
313                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
314                 if ($throttle_week > 0) {
315                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
316
317                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
318                         $posts_week = Post::countThread($condition);
319
320                         if ($posts_week > $throttle_week) {
321                                 Logger::notice('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
322                                 $error = DI::l10n()->t('Too Many Requests');
323                                 $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);
324                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
325                                 System::jsonError(429, $errorobj->toArray());
326                         }
327                 }
328
329                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
330                 if ($throttle_month > 0) {
331                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
332
333                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", Item::GRAVITY_PARENT, $uid, $datefrom];
334                         $posts_month = Post::countThread($condition);
335
336                         if ($posts_month > $throttle_month) {
337                                 Logger::notice('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
338                                 $error = DI::l10n()->t('Too Many Requests');
339                                 $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);
340                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
341                                 System::jsonError(429, $errorobj->toArray());
342                         }
343                 }
344         }
345
346         public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
347         {
348                 if (!empty($cid)) {
349                         return $cid;
350                 }
351
352                 if (!empty($profileurl)) {
353                         return Contact::getIdForURL($profileurl);
354                 }
355
356                 if (empty($cid) && !empty($screen_name)) {
357                         if (strpos($screen_name, '@') !== false) {
358                                 return Contact::getIdForURL($screen_name, 0, false);
359                         }
360
361                         $user = User::getByNickname($screen_name, ['uid']);
362                         if (!empty($user['uid'])) {
363                                 return Contact::getPublicIdByUserId($user['uid']);
364                         }
365                 }
366
367                 if ($uid != 0) {
368                         return Contact::getPublicIdByUserId($uid);
369                 }
370
371                 return null;
372         }
373 }