]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
extract "BaseApi::checkDefaults()" method for later usage
[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                 $this->app = $app;
72         }
73
74         protected function delete()
75         {
76                 self::checkAllowedScope(self::SCOPE_WRITE);
77
78                 if (!$this->app->isLoggedIn()) {
79                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
80                 }
81         }
82
83         protected function patch()
84         {
85                 self::checkAllowedScope(self::SCOPE_WRITE);
86
87                 if (!$this->app->isLoggedIn()) {
88                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
89                 }
90         }
91
92         protected function post(array $request = [], array $post = [])
93         {
94                 self::checkAllowedScope(self::SCOPE_WRITE);
95
96                 if (!$this->app->isLoggedIn()) {
97                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
98                 }
99         }
100
101         public function put()
102         {
103                 self::checkAllowedScope(self::SCOPE_WRITE);
104
105                 if (!$this->app->isLoggedIn()) {
106                         throw new HTTPException\ForbiddenException($this->t('Permission denied.'));
107                 }
108         }
109
110         /**
111          * Processes data from GET requests and sets defaults
112          *
113          * @param array      $defaults Associative array of expected request keys and their default typed value. A null
114          *                             value will remove the request key from the resulting value array.
115          * @param array|null $request  Custom REQUEST array, superglobal instead
116          * @return array request data
117          * @throws \Exception
118          */
119         public function getRequest(array $defaults, array $request = null): array
120         {
121                 $httpinput = HTTPInputData::process();
122                 $input = array_merge($httpinput['variables'], $httpinput['files'], $request ?? $_REQUEST);
123
124                 self::$request    = $input;
125                 self::$boundaries = [];
126
127                 unset(self::$request['pagename']);
128
129                 return $this->checkDefaults($defaults, $input);
130         }
131
132         /**
133          * Set boundaries for the "link" header
134          * @param array $boundaries
135          * @param int $id
136          */
137         protected static function setBoundaries(int $id)
138         {
139                 if (!isset(self::$boundaries['min'])) {
140                         self::$boundaries['min'] = $id;
141                 }
142
143                 if (!isset(self::$boundaries['max'])) {
144                         self::$boundaries['max'] = $id;
145                 }
146
147                 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
148                 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
149         }
150
151         /**
152          * Set the "link" header with "next" and "prev" links
153          * @return void
154          */
155         protected static function setLinkHeader()
156         {
157                 if (empty(self::$boundaries)) {
158                         return;
159                 }
160
161                 $request = self::$request;
162
163                 unset($request['min_id']);
164                 unset($request['max_id']);
165                 unset($request['since_id']);
166
167                 $prev_request = $next_request = $request;
168
169                 $prev_request['min_id'] = self::$boundaries['max'];
170                 $next_request['max_id'] = self::$boundaries['min'];
171
172                 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
173
174                 $prev = $command . '?' . http_build_query($prev_request);
175                 $next = $command . '?' . http_build_query($next_request);
176
177                 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
178         }
179
180         /**
181          * Get current application token
182          *
183          * @return array token
184          */
185         public static function getCurrentApplication()
186         {
187                 $token = OAuth::getCurrentApplicationToken();
188
189                 if (empty($token)) {
190                         $token = BasicAuth::getCurrentApplicationToken();
191                 }
192
193                 return $token;
194         }
195
196         /**
197          * Get current user id, returns 0 if not logged in
198          *
199          * @return int User ID
200          */
201         public static function getCurrentUserID()
202         {
203                 $uid = OAuth::getCurrentUserID();
204
205                 if (empty($uid)) {
206                         $uid = BasicAuth::getCurrentUserID(false);
207                 }
208
209                 return (int)$uid;
210         }
211
212         /**
213          * Check if the provided scope does exist.
214          * halts execution on missing scope or when not logged in.
215          *
216          * @param string $scope the requested scope (read, write, follow, push)
217          */
218         public static function checkAllowedScope(string $scope)
219         {
220                 $token = self::getCurrentApplication();
221
222                 if (empty($token)) {
223                         Logger::notice('Empty application token');
224                         DI::mstdnError()->Forbidden();
225                 }
226
227                 if (!isset($token[$scope])) {
228                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
229                         DI::mstdnError()->Forbidden();
230                 }
231
232                 if (empty($token[$scope])) {
233                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
234                         DI::mstdnError()->Forbidden();
235                 }
236         }
237
238         public static function checkThrottleLimit()
239         {
240                 $uid = self::getCurrentUserID();
241
242                 // Check for throttling (maximum posts per day, week and month)
243                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
244                 if ($throttle_day > 0) {
245                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
246
247                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
248                         $posts_day = Post::countThread($condition);
249
250                         if ($posts_day > $throttle_day) {
251                                 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
252                                 $error = DI::l10n()->t('Too Many Requests');
253                                 $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);
254                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
255                                 System::jsonError(429, $errorobj->toArray());
256                         }
257                 }
258
259                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
260                 if ($throttle_week > 0) {
261                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
262
263                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
264                         $posts_week = Post::countThread($condition);
265
266                         if ($posts_week > $throttle_week) {
267                                 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
268                                 $error = DI::l10n()->t('Too Many Requests');
269                                 $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);
270                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
271                                 System::jsonError(429, $errorobj->toArray());
272                         }
273                 }
274
275                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
276                 if ($throttle_month > 0) {
277                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
278
279                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
280                         $posts_month = Post::countThread($condition);
281
282                         if ($posts_month > $throttle_month) {
283                                 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
284                                 $error = DI::l10n()->t('Too Many Requests');
285                                 $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);
286                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
287                                 System::jsonError(429, $errorobj->toArray());
288                         }
289                 }
290         }
291
292         public static function getContactIDForSearchterm(string $screen_name = null, string $profileurl = null, int $cid = null, int $uid)
293         {
294                 if (!empty($cid)) {
295                         return $cid;
296                 }
297
298                 if (!empty($profileurl)) {
299                         return Contact::getIdForURL($profileurl);
300                 }
301
302                 if (empty($cid) && !empty($screen_name)) {
303                         if (strpos($screen_name, '@') !== false) {
304                                 return Contact::getIdForURL($screen_name, 0, false);
305                         }
306
307                         $user = User::getByNickname($screen_name, ['uid']);
308                         if (!empty($user['uid'])) {
309                                 return Contact::getPublicIdByUserId($user['uid']);
310                         }
311                 }
312
313                 if ($uid != 0) {
314                         return Contact::getPublicIdByUserId($uid);
315                 }
316
317                 return null;
318         }
319 }