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