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