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