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