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