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