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