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