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
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 * Get post data that is transmitted as JSON
133 * @return array request data
135 public static function getJsonPostData()
137 $postdata = Network::postdata();
138 if (empty($postdata)) {
142 return json_decode($postdata, true);
146 * Get request data for put requests
148 * @return array request data
150 public static function getPutData()
152 $rawdata = Network::postdata();
153 if (empty($rawdata)) {
159 foreach (explode('&', $rawdata) as $value) {
160 $data = explode('=', $value);
161 if (count($data) == 2) {
162 $putdata[$data[0]] = urldecode($data[1]);
170 * Log in user via OAuth1 or Simple HTTP Auth.
172 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
174 * @return bool Was a user authenticated?
175 * @throws HTTPException\ForbiddenException
176 * @throws HTTPException\UnauthorizedException
177 * @throws HTTPException\InternalServerErrorException
178 * @hook 'authenticate'
180 * 'username' => username from login form
181 * 'password' => password from login form
182 * 'authenticated' => return status,
183 * 'user_record' => return authenticated user record
185 protected static function login()
187 if (empty(self::$current_user_id)) {
188 self::$current_user_id = self::getUserByBearer();
191 if (empty(self::$current_user_id)) {
192 // The execution stops here if no one is logged in
193 api_login(DI::app());
196 self::$current_user_id = api_user();
198 return (bool)self::$current_user_id;
202 * Get current user id, returns 0 if not logged in
204 * @return int User ID
206 protected static function getCurrentUserID()
208 if (empty(self::$current_user_id)) {
209 self::$current_user_id = self::getUserByBearer();
212 if (empty(self::$current_user_id)) {
213 // Fetch the user id if logged in - but don't fail if not
214 api_login(DI::app(), false);
216 self::$current_user_id = api_user();
219 return (int)self::$current_user_id;
223 * Get the user id via the Bearer token
225 * @return int User-ID
227 private static function getUserByBearer()
229 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
231 if (substr($authorization, 0, 7) != 'Bearer ') {
235 $bearer = trim(substr($authorization, 7));
236 $condition = ['access_token' => $bearer];
237 $token = DBA::selectFirst('application-token', ['uid'], $condition);
238 if (!DBA::isResult($token)) {
239 Logger::warning('Token not found', $condition);
242 Logger::info('Token found', $token);
243 return $token['uid'];
247 * Get the application record via the proved request header fields
249 * @param string $client_id
250 * @param string $client_secret
251 * @param string $redirect_uri
252 * @return array application record
254 public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
256 $condition = ['client_id' => $client_id];
257 if (!empty($client_secret)) {
258 $condition['client_secret'] = $client_secret;
260 if (!empty($redirect_uri)) {
261 $condition['redirect_uri'] = $redirect_uri;
264 $application = DBA::selectFirst('application', [], $condition);
265 if (!DBA::isResult($application)) {
266 Logger::warning('Application not found', $condition);
273 * Check if an token for the application and user exists
275 * @param array $application
276 * @param integer $uid
279 public static function existsTokenForUser(array $application, int $uid)
281 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
285 * Fetch the token for the given application and user
287 * @param array $application
288 * @param integer $uid
289 * @return array application record
291 public static function getTokenForUser(array $application, int $uid)
293 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
297 * Create and fetch an token for the application and user
299 * @param array $application
300 * @param integer $uid
301 * @param string $scope
302 * @return array application record
304 public static function createTokenForUser(array $application, int $uid, string $scope)
306 $code = bin2hex(random_bytes(32));
307 $access_token = bin2hex(random_bytes(32));
309 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
310 'read' => (stripos($scope, 'read') !== false), 'write' => (stripos($scope, 'write') !== false),
311 'follow' => (stripos($scope, 'follow') !== false), 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
312 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
316 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
320 * Get user info array.
322 * @param int|string $contact_id Contact ID or URL
324 * @throws HTTPException\BadRequestException
325 * @throws HTTPException\InternalServerErrorException
326 * @throws HTTPException\UnauthorizedException
327 * @throws \ImagickException
329 protected static function getUser($contact_id = null)
331 return api_get_user(DI::app(), $contact_id);
335 * Formats the data according to the data type
337 * @param string $root_element
338 * @param array $data An array with a single element containing the returned result
339 * @return false|string
341 protected static function format(string $root_element, array $data)
343 $return = api_format_data($root_element, self::$format, $data);
345 switch (self::$format) {
347 header("Content-Type: text/xml");
350 header("Content-Type: application/json");
351 if (!empty($return)) {
352 $json = json_encode(end($return));
353 if (!empty($_GET['callback'])) {
354 $json = $_GET['callback'] . "(" . $json . ")";
360 header("Content-Type: application/rss+xml");
361 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
364 header("Content-Type: application/atom+xml");
365 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
373 * Creates the XML from a JSON style array
376 * @param $root_element
379 protected static function createXml($data, $root_element)
381 return api_create_xml($data, $root_element);