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;
49 protected static $current_token = [];
51 public static function init(array $parameters = [])
53 $arguments = DI::args();
55 if (substr($arguments->getCommand(), -4) === '.xml') {
56 self::$format = 'xml';
58 if (substr($arguments->getCommand(), -4) === '.rss') {
59 self::$format = 'rss';
61 if (substr($arguments->getCommand(), -4) === '.atom') {
62 self::$format = 'atom';
66 public static function delete(array $parameters = [])
69 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
74 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
75 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
79 public static function patch(array $parameters = [])
82 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
87 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
88 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
92 public static function post(array $parameters = [])
95 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
100 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
101 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
105 public static function put(array $parameters = [])
108 throw new HTTPException\UnauthorizedException(DI::l10n()->t('Permission denied.'));
113 if (!empty($a->user['uid']) && $a->user['uid'] != api_user()) {
114 throw new HTTPException\ForbiddenException(DI::l10n()->t('Permission denied.'));
119 * Quit execution with the message that the endpoint isn't implemented
121 * @param string $method
124 public static function unsupported(string $method = 'all')
126 $path = DI::args()->getQueryString();
127 Logger::info('Unimplemented API call', ['method' => $method, 'path' => $path, 'agent' => $_SERVER['HTTP_USER_AGENT'] ?? '', 'request' => $_REQUEST ?? []]);
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());
135 * Get post data that is transmitted as JSON
137 * @return array request data
139 public static function getJsonPostData()
141 $postdata = Network::postdata();
142 if (empty($postdata)) {
146 return json_decode($postdata, true);
150 * Get request data for put requests
152 * @return array request data
154 public static function getPutData()
156 $rawdata = Network::postdata();
157 if (empty($rawdata)) {
163 foreach (explode('&', $rawdata) as $value) {
164 $data = explode('=', $value);
165 if (count($data) == 2) {
166 $putdata[$data[0]] = urldecode($data[1]);
174 * Log in user via OAuth1 or Simple HTTP Auth.
176 * Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
178 * @return bool Was a user authenticated?
179 * @throws HTTPException\ForbiddenException
180 * @throws HTTPException\UnauthorizedException
181 * @throws HTTPException\InternalServerErrorException
182 * @hook 'authenticate'
184 * 'username' => username from login form
185 * 'password' => password from login form
186 * 'authenticated' => return status,
187 * 'user_record' => return authenticated user record
189 protected static function login()
191 if (empty(self::$current_user_id)) {
192 self::$current_token = self::getTokenByBearer();
193 if (!empty(self::$current_token['uid'])) {
194 self::$current_user_id = self::$current_token['uid'];
196 self::$current_user_id = 0;
200 if (empty(self::$current_user_id)) {
201 // The execution stops here if no one is logged in
202 api_login(DI::app());
205 self::$current_user_id = api_user();
207 return (bool)self::$current_user_id;
211 * Get current application
213 * @return array token
215 protected static function getCurrentApplication()
217 return self::$current_token;
221 * Get current user id, returns 0 if not logged in
223 * @return int User ID
225 protected static function getCurrentUserID()
227 if (empty(self::$current_user_id)) {
228 self::$current_token = self::getTokenByBearer();
229 if (!empty(self::$current_token['uid'])) {
230 self::$current_user_id = self::$current_token['uid'];
232 self::$current_user_id = 0;
237 if (empty(self::$current_user_id)) {
238 // Fetch the user id if logged in - but don't fail if not
239 api_login(DI::app(), false);
241 self::$current_user_id = api_user();
244 return (int)self::$current_user_id;
248 * Get the user token via the Bearer token
250 * @return array User Token
252 private static function getTokenByBearer()
254 $authorization = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
256 if (substr($authorization, 0, 7) != 'Bearer ') {
260 $bearer = trim(substr($authorization, 7));
261 $condition = ['access_token' => $bearer];
262 $token = DBA::selectFirst('application-view', ['uid', 'id', 'name', 'website', 'created_at', 'read', 'write', 'follow'], $condition);
263 if (!DBA::isResult($token)) {
264 Logger::warning('Token not found', $condition);
267 Logger::info('Token found', $token);
272 * Get the application record via the proved request header fields
274 * @param string $client_id
275 * @param string $client_secret
276 * @param string $redirect_uri
277 * @return array application record
279 public static function getApplication(string $client_id, string $client_secret, string $redirect_uri)
281 $condition = ['client_id' => $client_id];
282 if (!empty($client_secret)) {
283 $condition['client_secret'] = $client_secret;
285 if (!empty($redirect_uri)) {
286 $condition['redirect_uri'] = $redirect_uri;
289 $application = DBA::selectFirst('application', [], $condition);
290 if (!DBA::isResult($application)) {
291 Logger::warning('Application not found', $condition);
298 * Check if an token for the application and user exists
300 * @param array $application
301 * @param integer $uid
304 public static function existsTokenForUser(array $application, int $uid)
306 return DBA::exists('application-token', ['application-id' => $application['id'], 'uid' => $uid]);
310 * Fetch the token for the given application and user
312 * @param array $application
313 * @param integer $uid
314 * @return array application record
316 public static function getTokenForUser(array $application, int $uid)
318 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
322 * Create and fetch an token for the application and user
324 * @param array $application
325 * @param integer $uid
326 * @param string $scope
327 * @return array application record
329 public static function createTokenForUser(array $application, int $uid, string $scope)
331 $code = bin2hex(random_bytes(32));
332 $access_token = bin2hex(random_bytes(32));
334 $fields = ['application-id' => $application['id'], 'uid' => $uid, 'code' => $code, 'access_token' => $access_token, 'scopes' => $scope,
335 'read' => (stripos($scope, 'read') !== false), 'write' => (stripos($scope, 'write') !== false),
336 'follow' => (stripos($scope, 'follow') !== false), 'created_at' => DateTimeFormat::utcNow(DateTimeFormat::MYSQL)];
337 if (!DBA::insert('application-token', $fields, Database::INSERT_UPDATE)) {
341 return DBA::selectFirst('application-token', [], ['application-id' => $application['id'], 'uid' => $uid]);
345 * Get user info array.
347 * @param int|string $contact_id Contact ID or URL
349 * @throws HTTPException\BadRequestException
350 * @throws HTTPException\InternalServerErrorException
351 * @throws HTTPException\UnauthorizedException
352 * @throws \ImagickException
354 protected static function getUser($contact_id = null)
356 return api_get_user(DI::app(), $contact_id);
360 * Formats the data according to the data type
362 * @param string $root_element
363 * @param array $data An array with a single element containing the returned result
364 * @return false|string
366 protected static function format(string $root_element, array $data)
368 $return = api_format_data($root_element, self::$format, $data);
370 switch (self::$format) {
372 header("Content-Type: text/xml");
375 header("Content-Type: application/json");
376 if (!empty($return)) {
377 $json = json_encode(end($return));
378 if (!empty($_GET['callback'])) {
379 $json = $_GET['callback'] . "(" . $json . ")";
385 header("Content-Type: application/rss+xml");
386 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
389 header("Content-Type: application/atom+xml");
390 $return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
398 * Creates the XML from a JSON style array
401 * @param $root_element
404 protected static function createXml($data, $root_element)
406 return api_create_xml($data, $root_element);