]> git.mxchange.org Git - friendica.git/blob - src/Module/BaseApi.php
Merge pull request #10962 from annando/db-doc
[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\Post;
29 use Friendica\Network\HTTPException;
30 use Friendica\Security\BasicAuth;
31 use Friendica\Security\OAuth;
32 use Friendica\Util\DateTimeFormat;
33 use Friendica\Util\HTTPInputData;
34
35 require_once __DIR__ . '/../../include/api.php';
36
37 class BaseApi extends BaseModule
38 {
39         const SCOPE_READ   = 'read';
40         const SCOPE_WRITE  = 'write';
41         const SCOPE_FOLLOW = 'follow';
42         const SCOPE_PUSH   = 'push';
43
44         /**
45          * @var string json|xml|rss|atom
46          */
47         protected static $format = 'json';
48
49         /**
50          * @var array
51          */
52         protected static $boundaries = [];
53
54         /**
55          * @var array
56          */
57         protected static $request = [];
58
59         public static function init(array $parameters = [])
60         {
61                 $arguments = DI::args();
62
63                 if (substr($arguments->getCommand(), -4) === '.xml') {
64                         self::$format = 'xml';
65                 }
66                 if (substr($arguments->getCommand(), -4) === '.rss') {
67                         self::$format = 'rss';
68                 }
69                 if (substr($arguments->getCommand(), -4) === '.atom') {
70                         self::$format = 'atom';
71                 }
72         }
73
74         public static function delete(array $parameters = [])
75         {
76                 self::checkAllowedScope(self::SCOPE_WRITE);
77
78                 if (!DI::app()->isLoggedIn()) {
79                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
80                 }
81         }
82
83         public static function patch(array $parameters = [])
84         {
85                 self::checkAllowedScope(self::SCOPE_WRITE);
86
87                 if (!DI::app()->isLoggedIn()) {
88                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
89                 }
90         }
91
92         public static function post(array $parameters = [])
93         {
94                 self::checkAllowedScope(self::SCOPE_WRITE);
95
96                 if (!DI::app()->isLoggedIn()) {
97                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
98                 }
99         }
100
101         public static function put(array $parameters = [])
102         {
103                 self::checkAllowedScope(self::SCOPE_WRITE);
104
105                 if (!DI::app()->isLoggedIn()) {
106                         throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
107                 }
108         }
109
110         /**
111          * Quit execution with the message that the endpoint isn't implemented
112          *
113          * @param string $method
114          * @return void
115          */
116         public static function unsupported(string $method = 'all')
117         {
118                 $path = DI::args()->getQueryString();
119                 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => HTTPInputData::process()]);
120                 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
121                 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
122                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
123                 System::jsonError(501, $errorobj->toArray());
124         }
125
126         /**
127          * Processes data from GET requests and sets defaults
128          *
129          * @return array request data
130          */
131         public static function getRequest(array $defaults)
132         {
133                 $httpinput = HTTPInputData::process();
134                 $input = array_merge($httpinput['variables'], $httpinput['files'], $_REQUEST);
135
136                 self::$request    = $input;
137                 self::$boundaries = [];
138
139                 unset(self::$request['pagename']);
140
141                 $request = [];
142
143                 foreach ($defaults as $parameter => $defaultvalue) {
144                         if (is_string($defaultvalue)) {
145                                 $request[$parameter] = $input[$parameter] ?? $defaultvalue;
146                         } elseif (is_int($defaultvalue)) {
147                                 $request[$parameter] = (int)($input[$parameter] ?? $defaultvalue);
148                         } elseif (is_float($defaultvalue)) {
149                                 $request[$parameter] = (float)($input[$parameter] ?? $defaultvalue);
150                         } elseif (is_array($defaultvalue)) {
151                                 $request[$parameter] = $input[$parameter] ?? [];
152                         } elseif (is_bool($defaultvalue)) {
153                                 $request[$parameter] = in_array(strtolower($input[$parameter] ?? ''), ['true', '1']);
154                         } else {
155                                 Logger::notice('Unhandled default value type', ['parameter' => $parameter, 'type' => gettype($defaultvalue)]);
156                         }
157                 }
158
159                 foreach ($input ?? [] as $parameter => $value) {
160                         if ($parameter == 'pagename') {
161                                 continue;
162                         }
163                         if (!in_array($parameter, array_keys($defaults))) {
164                                 Logger::notice('Unhandled request field', ['parameter' => $parameter, 'value' => $value, 'command' => DI::args()->getCommand()]);
165                         }
166                 }
167
168                 Logger::debug('Got request parameters', ['request' => $request, 'command' => DI::args()->getCommand()]);
169                 return $request;
170         }
171
172         /**
173          * Set boundaries for the "link" header
174          * @param array $boundaries
175          * @param int $id
176          * @return array
177          */
178         protected static function setBoundaries(int $id)
179         {
180                 if (!isset(self::$boundaries['min'])) {
181                         self::$boundaries['min'] = $id;
182                 }
183
184                 if (!isset(self::$boundaries['max'])) {
185                         self::$boundaries['max'] = $id;
186                 }
187
188                 self::$boundaries['min'] = min(self::$boundaries['min'], $id);
189                 self::$boundaries['max'] = max(self::$boundaries['max'], $id);
190         }
191
192         /**
193          * Set the "link" header with "next" and "prev" links
194          * @return void
195          */
196         protected static function setLinkHeader()
197         {
198                 if (empty(self::$boundaries)) {
199                         return;
200                 }
201
202                 $request = self::$request;
203
204                 unset($request['min_id']);
205                 unset($request['max_id']);
206                 unset($request['since_id']);
207
208                 $prev_request = $next_request = $request;
209
210                 $prev_request['min_id'] = self::$boundaries['max'];
211                 $next_request['max_id'] = self::$boundaries['min'];
212
213                 $command = DI::baseUrl() . '/' . DI::args()->getCommand();
214
215                 $prev = $command . '?' . http_build_query($prev_request);
216                 $next = $command . '?' . http_build_query($next_request);
217
218                 header('Link: <' . $next . '>; rel="next", <' . $prev . '>; rel="prev"');
219         }
220
221         /**
222          * Get current application token
223          *
224          * @return array token
225          */
226         protected static function getCurrentApplication()
227         {
228                 $token = OAuth::getCurrentApplicationToken();
229
230                 if (empty($token)) {
231                         $token = BasicAuth::getCurrentApplicationToken();
232                 }
233
234                 return $token;
235         }
236
237         /**
238          * Get current user id, returns 0 if not logged in
239          *
240          * @return int User ID
241          */
242         protected static function getCurrentUserID()
243         {
244                 $uid = OAuth::getCurrentUserID();
245
246                 if (empty($uid)) {
247                         $uid = BasicAuth::getCurrentUserID(false);
248                 }
249
250                 return (int)$uid;
251         }
252
253         /**
254          * Check if the provided scope does exist.
255          * halts execution on missing scope or when not logged in.
256          *
257          * @param string $scope the requested scope (read, write, follow, push)
258          */
259         public static function checkAllowedScope(string $scope)
260         {
261                 $token = self::getCurrentApplication();
262
263                 if (empty($token)) {
264                         Logger::notice('Empty application token');
265                         DI::mstdnError()->Forbidden();
266                 }
267
268                 if (!isset($token[$scope])) {
269                         Logger::warning('The requested scope does not exist', ['scope' => $scope, 'application' => $token]);
270                         DI::mstdnError()->Forbidden();
271                 }
272
273                 if (empty($token[$scope])) {
274                         Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => $token]);
275                         DI::mstdnError()->Forbidden();
276                 }
277         }
278
279         public static function checkThrottleLimit()
280         {
281                 $uid = self::getCurrentUserID();
282
283                 // Check for throttling (maximum posts per day, week and month)
284                 $throttle_day = DI::config()->get('system', 'throttle_limit_day');
285                 if ($throttle_day > 0) {
286                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60);
287
288                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
289                         $posts_day = Post::countThread($condition);
290
291                         if ($posts_day > $throttle_day) {
292                                 Logger::info('Daily posting limit reached', ['uid' => $uid, 'posts' => $posts_day, 'limit' => $throttle_day]);
293                                 $error = DI::l10n()->t('Too Many Requests');
294                                 $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);
295                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
296                                 System::jsonError(429, $errorobj->toArray());
297                         }
298                 }
299
300                 $throttle_week = DI::config()->get('system', 'throttle_limit_week');
301                 if ($throttle_week > 0) {
302                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*7);
303
304                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
305                         $posts_week = Post::countThread($condition);
306
307                         if ($posts_week > $throttle_week) {
308                                 Logger::info('Weekly posting limit reached', ['uid' => $uid, 'posts' => $posts_week, 'limit' => $throttle_week]);
309                                 $error = DI::l10n()->t('Too Many Requests');
310                                 $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);
311                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
312                                 System::jsonError(429, $errorobj->toArray());
313                         }
314                 }
315
316                 $throttle_month = DI::config()->get('system', 'throttle_limit_month');
317                 if ($throttle_month > 0) {
318                         $datefrom = date(DateTimeFormat::MYSQL, time() - 24*60*60*30);
319
320                         $condition = ["`gravity` = ? AND `uid` = ? AND `wall` AND `received` > ?", GRAVITY_PARENT, $uid, $datefrom];
321                         $posts_month = Post::countThread($condition);
322
323                         if ($posts_month > $throttle_month) {
324                                 Logger::info('Monthly posting limit reached', ['uid' => $uid, 'posts' => $posts_month, 'limit' => $throttle_month]);
325                                 $error = DI::l10n()->t('Too Many Requests');
326                                 $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);
327                                 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
328                                 System::jsonError(429, $errorobj->toArray());
329                         }
330                 }
331         }
332
333         /**
334          * Get user info array.
335          *
336          * @param int|string $contact_id Contact ID or URL
337          * @return array|bool
338          * @throws HTTPException\BadRequestException
339          * @throws HTTPException\InternalServerErrorException
340          * @throws HTTPException\UnauthorizedException
341          * @throws \ImagickException
342          */
343         protected static function getUser($contact_id = null)
344         {
345                 return api_get_user(DI::app(), $contact_id);
346         }
347
348         /**
349          * Formats the data according to the data type
350          *
351          * @param string $root_element
352          * @param array $data An array with a single element containing the returned result
353          * @return false|string
354          */
355         protected static function format(string $root_element, array $data)
356         {
357                 $return = api_format_data($root_element, self::$format, $data);
358
359                 switch (self::$format) {
360                         case "xml":
361                                 header("Content-Type: text/xml");
362                                 break;
363                         case "json":
364                                 header("Content-Type: application/json");
365                                 if (!empty($return)) {
366                                         $json = json_encode(end($return));
367                                         if (!empty($_GET['callback'])) {
368                                                 $json = $_GET['callback'] . "(" . $json . ")";
369                                         }
370                                         $return = $json;
371                                 }
372                                 break;
373                         case "rss":
374                                 header("Content-Type: application/rss+xml");
375                                 $return  = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
376                                 break;
377                         case "atom":
378                                 header("Content-Type: application/atom+xml");
379                                 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
380                                 break;
381                 }
382
383                 return $return;
384         }
385
386         /**
387          * Creates the XML from a JSON style array
388          *
389          * @param $data
390          * @param $root_element
391          * @return string
392          */
393         protected static function createXml($data, $root_element)
394         {
395                 return api_create_xml($data, $root_element);
396         }
397 }