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