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