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;
33 require_once __DIR__ . '/../../include/api.php';
35 class BaseApi extends BaseModule
38 * @var string json|xml|rss|atom
40 protected static $format = 'json';
44 protected static $current_user_id;
46 public static function init(array $parameters = [])
48 $arguments = DI::args();
50 if (substr($arguments->getCommand(), -4) === '.xml') {
51 self::$format = 'xml';
53 if (substr($arguments->getCommand(), -4) === '.rss') {
54 self::$format = 'rss';
56 if (substr($arguments->getCommand(), -4) === '.atom') {
57 self::$format = 'atom';
61 public static function delete(array $parameters = [])
64 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
69 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
70 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
74 public static function patch(array $parameters = [])
77 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
82 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
83 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
87 public static function post(array $parameters = [])
90 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
95 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
96 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
100 public static function put(array $parameters = [])
103 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
108 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
109 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
113 public static function unsupported(string $method = 'all')
115 $path = DI::args()->getQueryString();
116 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
117 $error = DI::l10n()->t('API endpoint %s %s is not implemented', strtoupper($method), $path);
118 $error_description = DI::l10n()->t('The API endpoint is currently not implemented but might be in the future.');;
119 $errorobj = new \Friendica\Object\Api\Mastodon\Error($error, $error_description);
120 System::jsonError(501, $errorobj->toArray());
124 * Log in user via OAuth1 or Simple HTTP Auth.
126 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
128 * @return bool Was a user authenticated?
129 * @throws HTTPException\ForbiddenException
130 * @throws HTTPException\UnauthorizedException
131 * @throws HTTPException\InternalServerErrorException
132 * @hook 'authenticate'
134 * 'username' => username from login form
135 * 'password' => password from login form
136 * 'authenticated' => return status,
137 * 'user_record' => return authenticated user record
139 protected static function login()
141 if (empty(self::$current_user_id)) {
142 self::$current_user_id = self::getUserByBearer();
145 if (empty(self::$current_user_id)) {
146 api_login(DI::app());
149 self::$current_user_id = api_user();
151 return (bool)self::$current_user_id;
155 * Get current user id, returns 0 if not logged in
157 * @return int User ID
159 protected static function getCurrentUserID()
161 if (empty(self::$current_user_id)) {
162 self::$current_user_id = self::getUserByBearer();
165 if (empty(self::$current_user_id)) {
166 api_login(DI::app(), false);
168 self::$current_user_id = api_user();
171 return (int)self::$current_user_id;
174 private static function getUserByBearer()
176 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
177 $authorization = $_SERVER['AUTHORIZATION'] ?? $authorization;
179 if (substr($authorization, 0, 7) != 'Bearer ') {
183 $bearer = trim(substr($authorization, 7));
184 $condition = ['access_token' => $bearer];
185 $token = DBA::selectFirst('application-token', ['uid'], $condition);
186 if (!DBA::isResult($token)) {
187 Logger::warning('Token not found', $condition);
190 Logger::info('Token found', $token);
191 return $token['uid'];
194 public static function getApplication()
196 $redirect_uri = !isset($_REQUEST['redirect_uri']) ? '' : $_REQUEST['redirect_uri'];
197 $client_id = !isset($_REQUEST['client_id']) ? '' : $_REQUEST['client_id'];
199 if (empty($redirect_uri) || empty($client_id)) {
200 Logger::warning('Incomplete request');
204 $condition = ['redirect_uri' => $redirect_uri, 'client_id' => $client_id];
205 $application = DBA::selectFirst('application', [], $condition);
206 if (!DBA::isResult($application)) {
207 Logger::warning('Application not found', $condition);
213 public static function getTokenForUser(array $application, int $uid)
215 $code = bin2hex(random_bytes(32));
216 $access_token = bin2hex(random_bytes(32));
218 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
219 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
223 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
226 * Get user info array.
228 * @param int|string $contact_id Contact ID or URL
230 * @throws HTTPException\BadRequestException
231 * @throws HTTPException\InternalServerErrorException
232 * @throws HTTPException\UnauthorizedException
233 * @throws \ImagickException
235 protected static function getUser($contact_id = null)
237 return api_get_user(DI::app(), $contact_id);
241 * Formats the data according to the data type
243 * @param string $root_element
244 * @param array $data An array with a single element containing the returned result
245 * @return false|string
247 protected static function format(string $root_element, array $data)
249 $return = api_format_data($root_element, self::$format, $data);
251 switch (self::$format) {
253 header("Content-Type: text/xml");
256 header("Content-Type: application/json");
257 if (!empty($return)) {
258 $json = json_encode(end($return));
259 if (!empty($_GET['callback'])) {
260 $json = $_GET['callback'] . "(" . $json . ")";
266 header("Content-Type: application/rss+xml");
267 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
270 header("Content-Type: application/atom+xml");
271 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
279 * Creates the XML from a JSON style array
282 * @param $root_element
285 protected static function createXml($data, $root_element)
287 return api_create_xml($data, $root_element);