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