]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Fix Tos Module
[friendica.git] / src / Module / BaseApi.php
1 <?php
2 /**
3  * @copyright Copyright (C) 2010-2021, 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 Friendica\App;
25 use Friendica\BaseModule;
26 use Friendica\Core\L10n;
27 use Friendica\Core\Logger;
28 use Friendica\Core\System;
29 use Friendica\DI;
30 use Friendica\Model\Contact;
31 use Friendica\Model\Post;
32 use Friendica\Model\User;
33 use Friendica\Module\Api\ApiResponse;
34 use Friendica\Network\HTTPException;
35 use Friendica\Security\BasicAuth;
36 use Friendica\Security\OAuth;
37 use Friendica\Util\DateTimeFormat;
38 use Friendica\Util\HTTPInputData;
39 use Friendica\Util\Profiler;
40 use Psr\Log\LoggerInterface;
41
42 class BaseApi extends BaseModule
43 {
44         const LOG_PREFIX = 'API {action} - ';
45
46         const SCOPE_READ   = 'read';
47         const SCOPE_WRITE  = 'write';
48         const SCOPE_FOLLOW = 'follow';
49         const SCOPE_PUSH   = 'push';
50
51         /**
52          * @var array
53          */
54         protected static $boundaries = [];
55
56         /**
57          * @var array
58          */
59         protected static $request = [];
60
61         /** @var App */
62         protected $app;
63
64         /** @var ApiResponse */
65         protected $response;
66
67         public function __construct(App $app, L10n $l10n, App\BaseURL $baseUrl, App\Arguments $args, LoggerInterface $logger, Profiler $profiler, ApiResponse $response, array $server, array $parameters = [])
68         {
69                 parent::__construct($l10n, $baseUrl, $args, $logger, $profiler, $response, $server, $parameters);
70         }
71
72         protected function delete()
73         {
74                 self::checkAllowedScope(self::SCOPE_WRITE);
75
76                 if (!$this->app->isLoggedIn()) {
77                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
78                 }
79         }
80
81         protected function patch()
82         {
83                 self::checkAllowedScope(self::SCOPE_WRITE);
84
85                 if (!$this->app->isLoggedIn()) {
86                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
87                 }
88         }
89
90         protected function post(array $request = [], array $post = [])
91         {
92                 self::checkAllowedScope(self::SCOPE_WRITE);
93
94                 if (!$this->app->isLoggedIn()) {
95                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
96                 }
97         }
98
99         public function put()
100         {
101                 self::checkAllowedScope(self::SCOPE_WRITE);
102
103                 if (!$this->app->isLoggedIn()) {
104                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
105                 }
106         }
107
108         /**
109          * Processes data from GET requests and sets defaults
110          *
111          * @return array request data
112          */
113         public static function getRequest(array $defaults)
114         {
115                 $httpinput = HTTPInputData::process();
116                 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
117
118                 self::$request    = $input;
119                 self::$boundaries = [];
120
121                 unset(self::$request['pagename']);
122
123                 $request = [];
124
125                 foreach ($defaults as $parameter => $defaultvalue) {
126                         if (is_string($defaultvalue)) {
127                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
128                         } elseif (is_int($defaultvalue)) {
129                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
130                         } elseif (is_float($defaultvalue)) {
131                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
132                         } elseif (is_array($defaultvalue)) {
133                                 $request[$parameter] = $input[$parameter] ?? [];
134                         } elseif (is_bool($defaultvalue)) {
135                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
136                         } else {
137                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
138                         }
139                 }
140
141                 foreach ($input ?? [] as $parameter => $value) {
142                         if ($parameter == 'pagename') {
143                                 continue;
144                         }
145                         if (!in_array($parameter, array_keys($defaults))) {
146                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
147                         }
148                 }
149
150                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
151                 return $request;
152         }
153
154         /**
155          * Set boundaries for the "link" header
156          * @param array $boundaries
157          * @param int $id
158          */
159         protected static function setBoundaries(int $id)
160         {
161                 if (!isset(self::$boundaries['min'])) {
162                         self::$boundaries['min'] = $id;
163                 }
164
165                 if (!isset(self::$boundaries['max'])) {
166                         self::$boundaries['max'] = $id;
167                 }
168
169                 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
170                 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
171         }
172
173         /**
174          * Set the "link" header with "next" and "prev" links
175          * @return void
176          */
177         protected static function setLinkHeader()
178         {
179                 if (empty(self::$boundaries)) {
180                         return;
181                 }
182
183                 $request = self::$request;
184
185                 unset($request['min_id']);
186                 unset($request['max_id']);
187                 unset($request['since_id']);
188
189                 $prev_request = $next_request = $request;
190
191                 $prev_request['min_id'] = self::$boundaries['max'];
192                 $next_request['max_id'] = self::$boundaries['min'];
193
194                 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
195
196                 $prev = $command . '?' . http_build_query($prev_request);
197                 $next = $command . '?' . http_build_query($next_request);
198
199                 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
200         }
201
202         /**
203          * Get current application token
204          *
205          * @return array token
206          */
207         public static function getCurrentApplication()
208         {
209                 $token = OAuth::getCurrentApplicationToken();
210
211                 if (empty($token)) {
212                         $token = BasicAuth::getCurrentApplicationToken();
213                 }
214
215                 return $token;
216         }
217
218         /**
219          * Get current user id, returns 0 if not logged in
220          *
221          * @return int User ID
222          */
223         public static function getCurrentUserID()
224         {
225                 $uid = OAuth::getCurrentUserID();
226
227                 if (empty($uid)) {
228                         $uid = BasicAuth::getCurrentUserID(false);
229                 }
230
231                 return (int)$uid;
232         }
233
234         /**
235          * Check if the provided scope does exist.
236          * halts execution on missing scope or when not logged in.
237          *
238          * @param string $scope the requested scope (read, write, follow, push)
239          */
240         public static function checkAllowedScope(string $scope)
241         {
242                 $token = self::getCurrentApplication();
243
244                 if (empty($token)) {
245                         Logger::notice('Empty application token');
246                         DI::mstdnError()->Forbidden();
247                 }
248
249                 if (!isset($token[$scope])) {
250                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
251                         DI::mstdnError()->Forbidden();
252                 }
253
254                 if (empty($token[$scope])) {
255                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
256                         DI::mstdnError()->Forbidden();
257                 }
258         }
259
260         public static function checkThrottleLimit()
261         {
262                 $uid = self::getCurrentUserID();
263
264                 // Check for throttling (maximum posts per day, week and month)
265                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
266                 if ($throttle_day > 0) {
267                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
268
269                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
270                         $posts_day = Post::countThread($condition);
271
272                         if ($posts_day > $throttle_day) {
273                                 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
274                                 $error = DI::l10n()->t('Too Many Requests');
275                                 $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);
276                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
277                                 System::jsonError(429, $errorobj->toArray());
278                         }
279                 }
280
281                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
282                 if ($throttle_week > 0) {
283                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
284
285                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
286                         $posts_week = Post::countThread($condition);
287
288                         if ($posts_week > $throttle_week) {
289                                 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
290                                 $error = DI::l10n()->t('Too Many Requests');
291                                 $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);
292                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
293                                 System::jsonError(429, $errorobj->toArray());
294                         }
295                 }
296
297                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
298                 if ($throttle_month > 0) {
299                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
300
301                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
302                         $posts_month = Post::countThread($condition);
303
304                         if ($posts_month > $throttle_month) {
305                                 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
306                                 $error = DI::l10n()->t('Too Many Requests');
307                                 $error_description = DI::l10n()->t("Monthly posting limit of %d post reached. The post was rejected.", "Monthly posting limit of %d posts reached. The post was rejected.", $throttle_month);
308                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
309                                 System::jsonError(429, $errorobj->toArray());
310                         }
311                 }
312         }
313
314         public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
315         {
316                 if (!empty($cid)) {
317                         return $cid;
318                 }
319
320                 if (!empty($profileurl)) {
321                         return Contact::getIdForURL($profileurl);
322                 }
323
324                 if (empty($cid) && !empty($screen_name)) {
325                         if (strpos($screen_name, '@') !== false) {
326                                 return Contact::getIdForURL($screen_name, 0, false);
327                         }
328
329                         $user = User::getByNickname($screen_name, ['uid']);
330                         if (!empty($user['uid'])) {
331                                 return Contact::getPublicIdByUserId($user['uid']);
332                         }
333                 }
334
335                 if ($uid != 0) {
336                         return Contact::getPublicIdByUserId($uid);
337                 }
338
339                 return null;
340         }
341 }