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