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