friendica/include/api.php

6179 lines
177 KiB
PHP
Raw Normal View History

2016-09-25 18:50:08 +02:00
<?php
/**
* @copyright Copyright (C) 2020, Friendica
*
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*
2016-09-25 18:50:08 +02:00
* Friendica implementation of statusnet/twitter API
*
2017-12-24 03:20:50 +01:00
* @file include/api.php
2016-09-25 18:50:08 +02:00
* @todo Automatically detect if incoming data is HTML or BBCode
*/
use Friendica\App;
use Friendica\Content\ContactSelector;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
use Friendica\Core\Hook;
2018-10-29 22:20:46 +01:00
use Friendica\Core\Logger;
use Friendica\Core\Protocol;
use Friendica\Core\Session;
use Friendica\Core\System;
2017-11-05 13:15:53 +01:00
use Friendica\Core\Worker;
use Friendica\Database\DBA;
use Friendica\DI;
2017-12-07 15:04:24 +01:00
use Friendica\Model\Contact;
2017-12-09 19:45:17 +01:00
use Friendica\Model\Group;
use Friendica\Model\Item;
use Friendica\Model\Mail;
use Friendica\Model\Notify;
use Friendica\Model\Photo;
use Friendica\Model\User;
use Friendica\Model\UserItem;
use Friendica\Network\FKOAuth1;
2017-11-24 05:48:15 +01:00
use Friendica\Network\HTTPException;
use Friendica\Network\HTTPException\BadRequestException;
use Friendica\Network\HTTPException\ExpectationFailedException;
2017-11-24 05:48:15 +01:00
use Friendica\Network\HTTPException\ForbiddenException;
use Friendica\Network\HTTPException\InternalServerErrorException;
use Friendica\Network\HTTPException\MethodNotAllowedException;
use Friendica\Network\HTTPException\NotFoundException;
use Friendica\Network\HTTPException\NotImplementedException;
use Friendica\Network\HTTPException\TooManyRequestsException;
use Friendica\Network\HTTPException\UnauthorizedException;
use Friendica\Object\Image;
use Friendica\Protocol\Activity;
use Friendica\Protocol\Diaspora;
use Friendica\Util\DateTimeFormat;
use Friendica\Util\Images;
2018-01-27 05:09:48 +01:00
use Friendica\Util\Network;
use Friendica\Util\Proxy as ProxyUtils;
use Friendica\Util\Strings;
use Friendica\Util\XML;
require_once __DIR__ . '/../mod/share.php';
require_once __DIR__ . '/../mod/item.php';
require_once __DIR__ . '/../mod/wall_upload.php';
define('API_METHOD_ANY', '*');
define('API_METHOD_GET', 'GET');
define('API_METHOD_POST', 'POST,PUT');
define('API_METHOD_DELETE', 'POST,DELETE');
2018-12-30 21:42:56 +01:00
define('API_LOG_PREFIX', 'API {action} - ');
$API = [];
$called_api = [];
/**
2020-01-19 07:05:23 +01:00
* Auth API user
*
* It is not sufficient to use local_user() to check whether someone is allowed to use the API,
* because this will open CSRF holes (just embed an image with src=friendicasite.com/api/statuses/update?status=CSRF
* into a page, and visitors will post something without noticing it).
*/
function api_user()
{
if (!empty($_SESSION['allow_api'])) {
return local_user();
}
2016-09-25 18:50:08 +02:00
return false;
}
/**
2020-01-19 07:05:23 +01:00
* Get source name from API client
*
* Clients can send 'source' parameter to be show in post metadata
* as "sent via <source>".
* Some clients doesn't send a source param, we support ones we know
* (only Twidere, atm)
*
* @return string
2019-01-07 18:24:01 +01:00
* Client source name, default to "api" if unset/unknown
* @throws Exception
*/
function api_source()
{
if (requestdata('source')) {
return requestdata('source');
2016-09-25 18:50:08 +02:00
}
// Support for known clients that doesn't send a source name
if (!empty($_SERVER['HTTP_USER_AGENT'])) {
if(strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
return "Twidere";
}
2016-09-25 18:50:08 +02:00
2018-12-30 21:42:56 +01:00
Logger::info(API_LOG_PREFIX . 'Unrecognized user-agent', ['module' => 'api', 'action' => 'source', 'http_user_agent' => $_SERVER['HTTP_USER_AGENT']]);
} else {
2018-12-30 21:42:56 +01:00
Logger::info(API_LOG_PREFIX . 'Empty user-agent', ['module' => 'api', 'action' => 'source']);
}
2016-09-25 18:50:08 +02:00
return "api";
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Format date for API
*
* @param string $str Source date, as UTC
* @return string Date in UTC formatted as "D M d H:i:s +0000 Y"
2019-01-07 18:24:01 +01:00
* @throws Exception
*/
function api_date($str)
{
// Wed May 23 06:01:13 +0000 2007
return DateTimeFormat::utc($str, "D M d H:i:s +0000 Y");
}
/**
2017-12-24 03:20:50 +01:00
* Register a function to be the endpoint for defined API path.
*
* @param string $path API URL path, relative to DI::baseUrl()
* @param string $func Function name to call on path request
* @param bool $auth API need logged user
* @param string $method HTTP method reqiured to call this endpoint.
* One of API_METHOD_ANY, API_METHOD_GET, API_METHOD_POST.
* Default to API_METHOD_ANY
*/
function api_register_func($path, $func, $auth = false, $method = API_METHOD_ANY)
{
global $API;
$API[$path] = [
'func' => $func,
'auth' => $auth,
'method' => $method,
];
// Workaround for hotot
$path = str_replace("api/", "api/1.1/", $path);
$API[$path] = [
'func' => $func,
'auth' => $auth,
'method' => $method,
];
}
2016-09-25 18:50:08 +02:00
/**
* Log in user via OAuth1 or Simple HTTP Auth.
* Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
*
2019-01-07 18:24:01 +01:00
* @param App $a App
* @throws ForbiddenException
2019-01-07 18:24:01 +01:00
* @throws InternalServerErrorException
* @throws UnauthorizedException
* @hook 'authenticate'
* array $addon_auth
* 'username' => username from login form
* 'password' => password from login form
* 'authenticated' => return status,
* 'user_record' => return authenticated user record
*/
function api_login(App $a)
{
$oauth1 = new FKOAuth1();
// login with oauth
try {
$request = OAuthRequest::from_request();
list($consumer, $token) = $oauth1->verify_request($request);
if (!is_null($token)) {
$oauth1->loginUser($token->uid);
Session::set('allow_api', true);
return;
2016-09-25 18:50:08 +02:00
}
echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
var_dump($consumer, $token);
die();
} catch (Exception $e) {
2018-12-30 21:42:56 +01:00
Logger::warning(API_LOG_PREFIX . 'error', ['module' => 'api', 'action' => 'login', 'exception' => $e->getMessage()]);
}
2016-09-25 18:50:08 +02:00
// workaround for HTTP-auth in CGI mode
if (!empty($_SERVER['REDIRECT_REMOTE_USER'])) {
$userpass = base64_decode(substr($_SERVER["REDIRECT_REMOTE_USER"], 6));
if (strlen($userpass)) {
list($name, $password) = explode(':', $userpass);
$_SERVER['PHP_AUTH_USER'] = $name;
$_SERVER['PHP_AUTH_PW'] = $password;
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
if (empty($_SERVER['PHP_AUTH_USER'])) {
2018-12-30 21:42:56 +01:00
Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
header('WWW-Authenticate: Basic realm="Friendica"');
throw new UnauthorizedException("This API requires login");
}
2016-09-25 18:50:08 +02:00
$user = $_SERVER['PHP_AUTH_USER'] ?? '';
$password = $_SERVER['PHP_AUTH_PW'] ?? '';
2016-09-25 18:50:08 +02:00
// allow "user@server" login (but ignore 'server' part)
$at = strstr($user, "@", true);
if ($at) {
$user = $at;
}
2016-09-25 18:50:08 +02:00
// next code from mod/auth.php. needs better solution
$record = null;
2016-09-25 18:50:08 +02:00
$addon_auth = [
'username' => trim($user),
'password' => trim($password),
'authenticated' => 0,
'user_record' => null,
];
2016-09-25 18:50:08 +02:00
/*
* An addon indicates successful login by setting 'authenticated' to non-zero value and returning a user record
* Addons should never set 'authenticated' except to indicate success - as hooks may be chained
* and later addons should not interfere with an earlier one that succeeded.
*/
Hook::callAll('authenticate', $addon_auth);
2017-12-23 00:10:32 +01:00
if ($addon_auth['authenticated'] && count($addon_auth['user_record'])) {
$record = $addon_auth['user_record'];
} else {
$user_id = User::authenticate(trim($user), trim($password), true);
if ($user_id !== false) {
$record = DBA::selectFirst('user', [], ['uid' => $user_id]);
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
2018-07-21 14:46:04 +02:00
if (!DBA::isResult($record)) {
2018-12-30 21:42:56 +01:00
Logger::debug(API_LOG_PREFIX . 'failed', ['module' => 'api', 'action' => 'login', 'parameters' => $_SERVER]);
header('WWW-Authenticate: Basic realm="Friendica"');
//header('HTTP/1.0 401 Unauthorized');
//die('This api requires login');
throw new UnauthorizedException("This API requires login");
}
2016-09-25 18:50:08 +02:00
DI::auth()->setForUser($a, $record);
2016-09-25 18:50:08 +02:00
$_SESSION["allow_api"] = true;
2016-09-25 18:50:08 +02:00
Hook::callAll('logged_in', $a->user);
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Check HTTP method of called API
*
* API endpoints can define which HTTP method to accept when called.
* This function check the current HTTP method agains endpoint
* registered method.
*
* @param string $method Required methods, uppercase, separated by comma
* @return bool
*/
function api_check_method($method)
{
if ($method == "*") {
return true;
2016-09-25 18:50:08 +02:00
}
return (stripos($method, $_SERVER['REQUEST_METHOD'] ?? 'GET') !== false);
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Main API entry point
*
2020-01-19 07:05:23 +01:00
* Authenticate user, call registered API function, set HTTP headers
2017-12-24 03:20:50 +01:00
*
2019-01-07 18:24:01 +01:00
* @param App $a App
* @param App\Arguments $args The app arguments (optional, will retrieved by the DI-Container in case of missing)
2018-04-09 19:34:02 +02:00
* @return string|array API call result
2019-01-07 18:24:01 +01:00
* @throws Exception
*/
function api_call(App $a, App\Arguments $args = null)
{
global $API, $called_api;
2016-09-25 18:50:08 +02:00
if ($args == null) {
$args = DI::args();
}
$type = "json";
if (strpos($args->getQueryString(), ".xml") > 0) {
$type = "xml";
}
if (strpos($args->getQueryString(), ".json") > 0) {
$type = "json";
}
if (strpos($args->getQueryString(), ".rss") > 0) {
$type = "rss";
}
if (strpos($args->getQueryString(), ".atom") > 0) {
$type = "atom";
}
try {
foreach ($API as $p => $info) {
if (strpos($args->getQueryString(), $p) === 0) {
if (!api_check_method($info['method'])) {
throw new MethodNotAllowedException();
}
2016-09-25 18:50:08 +02:00
$called_api = explode("/", $p);
if (!empty($info['auth']) && api_user() === false) {
api_login($a);
}
2016-09-25 18:50:08 +02:00
2018-12-30 21:42:56 +01:00
Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username']]);
Logger::debug(API_LOG_PREFIX . 'parameters', ['module' => 'api', 'action' => 'call', 'parameters' => $_REQUEST]);
2016-09-25 18:50:08 +02:00
$stamp = microtime(true);
2018-01-04 02:54:35 +01:00
$return = call_user_func($info['func'], $type);
$duration = floatval(microtime(true) - $stamp);
2018-12-30 21:42:56 +01:00
Logger::info(API_LOG_PREFIX . 'username {username}', ['module' => 'api', 'action' => 'call', 'username' => $a->user['username'], 'duration' => round($duration, 2)]);
2016-09-25 18:50:08 +02:00
DI::profiler()->saveLog(DI::logger(), API_LOG_PREFIX . 'performance');
2018-01-04 02:54:35 +01:00
if (false === $return) {
/*
* api function returned false withour throw an
* exception. This should not happend, throw a 500
*/
throw new InternalServerErrorException();
}
2016-09-25 18:50:08 +02:00
switch ($type) {
case "xml":
header("Content-Type: text/xml");
break;
case "json":
header("Content-Type: application/json");
if (!empty($return)) {
$json = json_encode(end($return));
if (!empty($_GET['callback'])) {
$json = $_GET['callback'] . "(" . $json . ")";
}
$return = $json;
2017-12-24 00:27:45 +01:00
}
break;
case "rss":
header("Content-Type: application/rss+xml");
2018-01-04 02:54:35 +01:00
$return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
break;
case "atom":
header("Content-Type: application/atom+xml");
2018-01-04 02:54:35 +01:00
$return = '<?xml version="1.0" encoding="UTF-8"?>' . "\n" . $return;
break;
2016-09-25 18:50:08 +02:00
}
2018-01-04 02:54:35 +01:00
return $return;
2016-09-25 18:50:08 +02:00
}
}
Logger::warning(API_LOG_PREFIX . 'not implemented', ['module' => 'api', 'action' => 'call', 'query' => DI::args()->getQueryString()]);
throw new NotImplementedException();
} catch (HTTPException $e) {
header("HTTP/1.1 {$e->getCode()} {$e->httpdesc}");
return api_error($type, $e, $args);
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Format API error string
*
* @param string $type Return type (xml, json, rss, as)
* @param object $e HTTPException Error object
* @param App\Arguments $args The App arguments
2018-04-09 19:34:02 +02:00
* @return string|array error message formatted as $type
*/
function api_error($type, $e, App\Arguments $args)
{
$error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
/// @TODO: https://dev.twitter.com/overview/api/response-codes
$error = ["error" => $error,
"code" => $e->getCode() . " " . $e->httpdesc,
"request" => $args->getQueryString()];
$return = api_format_data('status', $type, ['status' => $error]);
switch ($type) {
case "xml":
header("Content-Type: text/xml");
break;
case "json":
header("Content-Type: application/json");
2018-01-04 02:54:35 +01:00
$return = json_encode($return);
break;
case "rss":
header("Content-Type: application/rss+xml");
break;
case "atom":
header("Content-Type: application/atom+xml");
break;
}
2018-01-04 02:54:35 +01:00
return $return;
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Set values for RSS template
*
2019-01-07 18:24:01 +01:00
* @param App $a
* @param array $arr Array to be passed to template
* @param array $user_info User info
* @return array
2019-01-07 18:24:01 +01:00
* @throws BadRequestException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws UnauthorizedException
* @todo find proper type-hints
*/
function api_rss_extra(App $a, $arr, $user_info)
{
if (is_null($user_info)) {
$user_info = api_get_user($a);
}
2016-09-25 18:50:08 +02:00
$arr['$user'] = $user_info;
$arr['$rss'] = [
'alternate' => $user_info['url'],
'self' => DI::baseUrl() . "/" . DI::args()->getQueryString(),
'base' => DI::baseUrl(),
'updated' => api_date(null),
'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'language' => $user_info['lang'],
'logo' => DI::baseUrl() . "/images/friendica-32.png",
];
2016-09-25 18:50:08 +02:00
return $arr;
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Unique contact to contact url.
*
* @param int $id Contact id
* @return bool|string
2019-01-07 18:24:01 +01:00
* Contact url or False if contact id is unknown
* @throws Exception
*/
2017-12-17 12:11:28 +01:00
function api_unique_id_to_nurl($id)
{
$r = DBA::selectFirst('contact', ['nurl'], ['id' => $id]);
2018-07-21 14:46:04 +02:00
if (DBA::isResult($r)) {
2017-12-17 12:11:28 +01:00
return $r["nurl"];
} else {
return false;
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
/**
2020-01-19 07:05:23 +01:00
* Get user info array.
*
2019-01-07 18:24:01 +01:00
* @param App $a App
* @param int|string $contact_id Contact ID or URL
2019-01-21 17:36:01 +01:00
* @return array|bool
2019-01-07 18:24:01 +01:00
* @throws BadRequestException
* @throws ImagickException
* @throws InternalServerErrorException
* @throws UnauthorizedException
*/
function api_get_user(App $a, $contact_id = null)
{
global $called_api;
$user = null;
$extra_query = "";
$url = "";
2018-12-30 21:42:56 +01:00
Logger::info(API_LOG_PREFIX . 'Fetching data for user {user}', ['module' => 'api', 'action' => 'get_user', 'user' => $contact_id]);
2016-09-25 18:50:08 +02:00
// Searching for contact URL
if (!is_null($contact_id) && (intval($contact_id) == 0)) {
$user = DBA::escape(Strings::normaliseLink($contact_id));
$url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
2016-09-25 18:50:08 +02:00
}
// Searching for contact id with uid = 0
if (!is_null($contact_id) && (intval($contact_id) != 0)) {
2018-07-21 15:10:13 +02:00
$user = DBA::escape(api_unique_id_to_nurl(intval($contact_id)));
2016-09-25 18:50:08 +02:00
if ($user == "") {
2018-06-03 11:55:41 +02:00
throw new BadRequestException("User ID ".$contact_id." not found.");
}
$url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
2016-09-25 18:50:08 +02:00
}
if (is_null($user) && !empty($_GET['user_id'])) {
2018-07-21 15:10:13 +02:00
$user = DBA::escape(api_unique_id_to_nurl($_GET['user_id']));
2016-09-25 18:50:08 +02:00
if ($user == "") {
2018-06-03 11:55:41 +02:00
throw new BadRequestException("User ID ".$_GET['user_id']." not found.");
2016-09-25 18:50:08 +02:00
}
$url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
if (is_null($user) && !empty($_GET['screen_name'])) {
2018-07-21 15:10:13 +02:00
$user = DBA::escape($_GET['screen_name']);
$extra_query = "AND `contact`.`nick` = '%s' ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=".intval(api_user());
}
}
2016-09-25 18:50:08 +02:00
if (is_null($user) && !empty($_GET['profileurl'])) {
$user = DBA::escape(Strings::normaliseLink($_GET['profileurl']));
$extra_query = "AND `contact`.`nurl` = '%s' ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=".intval(api_user());
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
// $called_api is the API path exploded on / and is expected to have at least 2 elements
if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
$argid = count($called_api);
2018-07-08 11:37:05 +02:00
if (!empty($a->argv[$argid])) {
2018-09-02 10:01:13 +02:00