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