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