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