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;
25 use Friendica\BaseModule;
26 use Friendica\Core\Logger;
27 use Friendica\Core\System;
28 use Friendica\Database\Database;
29 use Friendica\Database\DBA;
31 use Friendica\Network\HTTPException;
32 use Friendica\Util\DateTimeFormat;
34 require_once __DIR__ . '/../../include/api.php';
36 class BaseApi extends BaseModule
39 * @var string json|xml|rss|atom
41 protected static $format = 'json';
45 protected static $current_user_id;
47 public static function init(array $parameters = [])
49 $arguments = DI::args();
51 if (substr($arguments->getCommand(), -4) === '.xml') {
52 self::$format = 'xml';
54 if (substr($arguments->getCommand(), -4) === '.rss') {
55 self::$format = 'rss';
57 if (substr($arguments->getCommand(), -4) === '.atom') {
58 self::$format = 'atom';
62 public static function delete(array $parameters = [])
65 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
70 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
71 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
75 public static function patch(array $parameters = [])
78 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
83 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
84 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
88 public static function post(array $parameters = [])
91 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
96 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
97 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
101 public static function put(array $parameters = [])
104 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
109 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
110 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
115 * Quit execution with the message that the endpoint isn't implemented
117 * @param string $method
120 public static function unsupported(string $method = 'all')
122 $path = DI::args()->getQueryString();
123 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
124 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
125 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');
126 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
127 System::jsonError(501, $errorobj->toArray());
131 * Log in user via OAuth1 or Simple HTTP Auth.
133 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
135 * @return bool Was a user authenticated?
136 * @throws HTTPException\ForbiddenException
137 * @throws HTTPException\UnauthorizedException
138 * @throws HTTPException\InternalServerErrorException
139 * @hook 'authenticate'
141 * 'username' => username from login form
142 * 'password' => password from login form
143 * 'authenticated' => return status,
144 * 'user_record' => return authenticated user record
146 protected static function login()
148 if (empty(self::$current_user_id)) {
149 self::$current_user_id = self::getUserByBearer();
152 if (empty(self::$current_user_id)) {
153 // The execution stops here if no one is logged in
154 api_login(DI::app());
157 self::$current_user_id = api_user();
159 return (bool)self::$current_user_id;
163 * Get current user id, returns 0 if not logged in
165 * @return int User ID
167 protected static function getCurrentUserID()
169 if (empty(self::$current_user_id)) {
170 self::$current_user_id = self::getUserByBearer();
173 if (empty(self::$current_user_id)) {
174 // Fetch the user id if logged in - but don't fail if not
175 api_login(DI::app(), false);
177 self::$current_user_id = api_user();
180 return (int)self::$current_user_id;
184 * Get the user id via the Bearer token
186 * @return int User-ID
188 private static function getUserByBearer()
190 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
192 if (substr($authorization, 0, 7) != 'Bearer ') {
196 $bearer = trim(substr($authorization, 7));
197 $condition = ['access_token' => $bearer];
198 $token = DBA::selectFirst('application-token', ['uid'], $condition);
199 if (!DBA::isResult($token)) {
200 Logger::warning('Token not found', $condition);
203 Logger::info('Token found', $token);
204 return $token['uid'];
208 * Get the application record via the proved request header fields
210 * @param string $client_id
211 * @param string $client_secret
212 * @param string $redirect_uri
213 * @return array application record
215 public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
217 $condition = ['client_id' => $client_id];
218 if (!empty($client_secret)) {
219 $condition['client_secret'] = $client_secret;
221 if (!empty($redirect_uri)) {
222 $condition['redirect_uri'] = $redirect_uri;
225 $application = DBA::selectFirst('application', [], $condition);
226 if (!DBA::isResult($application)) {
227 Logger::warning('Application not found', $condition);
234 * Check if an token for the application and user exists
236 * @param array $application
237 * @param integer $uid
240 public static function existsTokenForUser(array $application, int $uid)
242 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
246 * Fetch the token for the given application and user
248 * @param array $application
249 * @param integer $uid
250 * @return array application record
252 public static function getTokenForUser(array $application, int $uid)
254 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
258 * Create and fetch an token for the application and user
260 * @param array $application
261 * @param integer $uid
262 * @param string $scope
263 * @return array application record
265 public static function createTokenForUser(array $application, int $uid, string $scope)
267 $code = bin2hex(random_bytes(32));
268 $access_token = bin2hex(random_bytes(32));
270 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
271 'read' => (stripos($scope, 'read') !== false), 'write' => (stripos($scope, 'write') !== false),
272 'follow' => (stripos($scope, 'follow') !== false), 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
273 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
277 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
281 * Get user info array.
283 * @param int|string $contact_id Contact ID or URL
285 * @throws HTTPException\BadRequestException
286 * @throws HTTPException\InternalServerErrorException
287 * @throws HTTPException\UnauthorizedException
288 * @throws \ImagickException
290 protected static function getUser($contact_id = null)
292 return api_get_user(DI::app(), $contact_id);
296 * Formats the data according to the data type
298 * @param string $root_element
299 * @param array $data An array with a single element containing the returned result
300 * @return false|string
302 protected static function format(string $root_element, array $data)
304 $return = api_format_data($root_element, self::$format, $data);
306 switch (self::$format) {
308 header("Content-Type: text/xml");
311 header("Content-Type: application/json");
312 if (!empty($return)) {
313 $json = json_encode(end($return));
314 if (!empty($_GET['callback'])) {
315 $json = $_GET['callback'] . "(" . $json . ")";
321 header("Content-Type: application/rss+xml");
322 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
325 header("Content-Type: application/atom+xml");
326 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
334 * Creates the XML from a JSON style array
337 * @param $root_element
340 protected static function createXml($data, $root_element)
342 return api_create_xml($data, $root_element);