3 * @copyright Copyright (C) 2010-2021, the Friendica project
5 * @license GNU AGPL version 3 or any later version
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.
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.
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/>.
22 namespace Friendica\Module;
24 use Friendica\BaseModule;
25 use Friendica\Core\Logger;
26 use Friendica\Core\System;
27 use Friendica\Database\Database;
28 use Friendica\Database\DBA;
30 use Friendica\Network\HTTPException;
31 use Friendica\Util\DateTimeFormat;
32 use Friendica\Util\Network;
34 require_once __DIR__ . '/../../include/api.php';
36 class BaseApi extends BaseModule
38 const SCOPE_READ = 'read';
39 const SCOPE_WRITE = 'write';
40 const SCOPE_FOLLOW = 'follow';
41 const SCOPE_PUSH = 'push';
44 * @var string json|xml|rss|atom
46 protected static $format = 'json';
50 protected static $current_user_id;
54 protected static $current_token = [];
56 public static function init(array $parameters = [])
58 $arguments = DI::args();
60 if (substr($arguments->getCommand(), -4) === '.xml') {
61 self::$format = 'xml';
63 if (substr($arguments->getCommand(), -4) === '.rss') {
64 self::$format = 'rss';
66 if (substr($arguments->getCommand(), -4) === '.atom') {
67 self::$format = 'atom';
71 public static function delete(array $parameters = [])
74 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
79 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
80 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
84 public static function patch(array $parameters = [])
87 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
92 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
93 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
97 public static function post(array $parameters = [])
100 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
105 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
106 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
110 public static function put(array $parameters = [])
113 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
118 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
119 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
124 * Quit execution with the message that the endpoint isn't implemented
126 * @param string $method
129 public static function unsupported(string $method = 'all')
131 $path = DI::args()->getQueryString();
132 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
133 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
134 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
135 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
136 System::jsonError(501, $errorobj->toArray());
140 * Get post data that is transmitted as JSON
142 * @return array request data
144 public static function getJsonPostData()
146 $postdata = Network::postdata();
147 if (empty($postdata)) {
151 return json_decode($postdata, true);
155 * Get request data for put requests
157 * @return array request data
159 public static function getPutData()
161 $rawdata = Network::postdata();
162 if (empty($rawdata)) {
168 foreach (explode('&', $rawdata) as $value) {
169 $data = explode('=', $value);
170 if (count($data) == 2) {
171 $putdata[$data[0]] = urldecode($data[1]);
179 * Log in user via OAuth1 or Simple HTTP Auth.
181 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
183 * @param string $scope the requested scope (read, write, follow)
185 * @return bool Was a user authenticated?
186 * @throws HTTPException\ForbiddenException
187 * @throws HTTPException\UnauthorizedException
188 * @throws HTTPException\InternalServerErrorException
189 * @hook 'authenticate'
191 * 'username' => username from login form
192 * 'password' => password from login form
193 * 'authenticated' => return status,
194 * 'user_record' => return authenticated user record
196 protected static function login(string $scope)
198 if (empty(self::$current_user_id)) {
199 self::$current_token = self::getTokenByBearer();
200 if (!empty(self::$current_token['uid'])) {
201 self::$current_user_id = self::$current_token['uid'];
203 self::$current_user_id = 0;
207 if (!empty($scope) && !empty(self::$current_token)) {
208 if (empty(self::$current_token[$scope])) {
209 Logger::warning('The requested scope is not allowed', ['scope' => $scope, 'application' => self::$current_token]);
210 DI::mstdnError()->Forbidden();
214 if (empty(self::$current_user_id)) {
215 // The execution stops here if no one is logged in
216 api_login(DI::app());
219 self::$current_user_id = api_user();
221 return (bool)self::$current_user_id;
225 * Get current application
227 * @return array token
229 protected static function getCurrentApplication()
231 return self::$current_token;
235 * Get current user id, returns 0 if not logged in
237 * @return int User ID
239 protected static function getCurrentUserID()
241 if (empty(self::$current_user_id)) {
242 self::$current_token = self::getTokenByBearer();
243 if (!empty(self::$current_token['uid'])) {
244 self::$current_user_id = self::$current_token['uid'];
246 self::$current_user_id = 0;
251 if (empty(self::$current_user_id)) {
252 // Fetch the user id if logged in - but don't fail if not
253 api_login(DI::app(), false);
255 self::$current_user_id = api_user();
258 return (int)self::$current_user_id;
262 * Get the user token via the Bearer token
264 * @return array User Token
266 private static function getTokenByBearer()
268 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
270 if (substr($authorization, 0, 7) != 'Bearer ') {
274 $bearer = trim(substr($authorization, 7));
275 $condition = ['access_token' => $bearer];
276 $token = DBA::selectFirst('application-view', ['uid', 'id', 'name', 'website', 'created_at', 'read', 'write', 'follow', 'push'], $condition);
277 if (!DBA::isResult($token)) {
278 Logger::warning('Token not found', $condition);
281 Logger::info('Token found', $token);
286 * Get the application record via the proved request header fields
288 * @param string $client_id
289 * @param string $client_secret
290 * @param string $redirect_uri
291 * @return array application record
293 public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
295 $condition = ['client_id' => $client_id];
296 if (!empty($client_secret)) {
297 $condition['client_secret'] = $client_secret;
299 if (!empty($redirect_uri)) {
300 $condition['redirect_uri'] = $redirect_uri;
303 $application = DBA::selectFirst('application', [], $condition);
304 if (!DBA::isResult($application)) {
305 Logger::warning('Application not found', $condition);
312 * Check if an token for the application and user exists
314 * @param array $application
315 * @param integer $uid
318 public static function existsTokenForUser(array $application, int $uid)
320 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
324 * Fetch the token for the given application and user
326 * @param array $application
327 * @param integer $uid
328 * @return array application record
330 public static function getTokenForUser(array $application, int $uid)
332 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
336 * Create and fetch an token for the application and user
338 * @param array $application
339 * @param integer $uid
340 * @param string $scope
341 * @return array application record
343 public static function createTokenForUser(array $application, int $uid, string $scope)
345 $code = bin2hex(random_bytes(32));
346 $access_token = bin2hex(random_bytes(32));
348 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
349 'read' => (stripos($scope, self::SCOPE_READ) !== false),
350 'write' => (stripos($scope, self::SCOPE_WRITE) !== false),
351 'follow' => (stripos($scope, self::SCOPE_FOLLOW) !== false),
352 'push' => (stripos($scope, self::SCOPE_PUSH) !== false),
353 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
355 foreach ([self::SCOPE_READ, self::SCOPE_WRITE, self::SCOPE_WRITE, self::SCOPE_PUSH] as $scope) {
356 if ($fields[$scope] && !$application[$scope]) {
357 Logger::warning('Requested token scope is not allowed for the application', ['token' => $fields, 'application' => $application]);
361 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
365 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
369 * Get user info array.
371 * @param int|string $contact_id Contact ID or URL
373 * @throws HTTPException\BadRequestException
374 * @throws HTTPException\InternalServerErrorException
375 * @throws HTTPException\UnauthorizedException
376 * @throws \ImagickException
378 protected static function getUser($contact_id = null)
380 return api_get_user(DI::app(), $contact_id);
384 * Formats the data according to the data type
386 * @param string $root_element
387 * @param array $data An array with a single element containing the returned result
388 * @return false|string
390 protected static function format(string $root_element, array $data)
392 $return = api_format_data($root_element, self::$format, $data);
394 switch (self::$format) {
396 header("Content-Type: text/xml");
399 header("Content-Type: application/json");
400 if (!empty($return)) {
401 $json = json_encode(end($return));
402 if (!empty($_GET['callback'])) {
403 $json = $_GET['callback'] . "(" . $json . ")";
409 header("Content-Type: application/rss+xml");
410 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
413 header("Content-Type: application/atom+xml");
414 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
422 * Creates the XML from a JSON style array
425 * @param $root_element
428 protected static function createXml($data, $root_element)
430 return api_create_xml($data, $root_element);