friendica/include/api.php

6230 lines
176 KiB
PHP
Raw Normal View History

2016-09-25 18:50:08 +02:00
<?php
/**
* 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\Feature;
use Friendica\Content\Text\BBCode;
use Friendica\Content\Text\HTML;
use Friendica\Core\Addon;
2017-04-30 06:01:26 +02:00
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\NotificationsManager;
2017-12-18 20:39:35 +01:00
use Friendica\Core\PConfig;
use Friendica\Core\System;
2017-11-05 13:15:53 +01:00
use Friendica\Core\Worker;
2017-11-08 04:57:46 +01:00
use Friendica\Database\DBM;
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\Photo;
use Friendica\Model\User;
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\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\Diaspora;
use Friendica\Util\DateTimeFormat;
2018-01-27 05:09:48 +01:00
use Friendica\Util\Network;
use Friendica\Util\XML;
require_once 'include/conversation.php';
require_once 'mod/share.php';
require_once 'mod/item.php';
require_once 'include/security.php';
require_once 'mod/wall_upload.php';
require_once 'mod/proxy.php';
define('API_METHOD_ANY', '*');
define('API_METHOD_GET', 'GET');
define('API_METHOD_POST', 'POST,PUT');
define('API_METHOD_DELETE', 'POST,DELETE');
$API = [];
$called_api = [];
/**
* 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).
2017-12-24 03:20:50 +01:00
*
* @brief Auth API user
*/
function api_user()
{
if (x($_SESSION, 'allow_api')) {
return local_user();
}
2016-09-25 18:50:08 +02:00
return false;
}
/**
* 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)
*
2017-12-24 03:20:50 +01:00
* @brief Get source name from API client
*
* @return string
* Client source name, default to "api" if unset/unknown
*/
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 (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
return "Twidere";
}
2016-09-25 18:50:08 +02:00
logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
2016-09-25 18:50:08 +02:00
return "api";
}
2016-09-25 18:50:08 +02:00
/**
* @brief 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"
*/
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.
*
2017-12-24 03:20:50 +01:00
* @brief Register API endpoint
*
* @param string $path API URL path, relative to System::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
*
2017-12-24 03:20:50 +01:00
* @brief Login API user
*
* @param object $a App
* @hook 'authenticate'
* array $addon_auth
* 'username' => username from login form
* 'password' => password from login form
* 'authenticated' => return status,
* 'user_record' => return authenticated user record
* @hook 'logged_in'
* array $user logged user record
*/
function api_login(App $a)
{
$oauth1 = new FKOAuth1();
// login with oauth
try {
list($consumer, $token) = $oauth1->verify_request(OAuthRequest::from_request());
if (!is_null($token)) {
$oauth1->loginUser($token->uid);
Addon::callHooks('logged_in', $a->user);
return;
2016-09-25 18:50:08 +02:00
}
echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
var_dump($consumer, $token);
die();
} catch (Exception $e) {
logger($e);
}
2016-09-25 18:50:08 +02:00
// workaround for HTTP-auth in CGI mode
if (x($_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 (!x($_SERVER, 'PHP_AUTH_USER')) {
2017-12-24 00:27:45 +01:00
logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
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.
*/
Addon::callHooks('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));
if ($user_id !== false) {
2018-01-10 14:36:02 +01:00
$record = dba::selectFirst('user', [], ['uid' => $user_id]);
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
2018-01-13 09:22:40 +01:00
if (!DBM::is_result($record)) {
logger('API_login failure: ' . print_r($_SERVER, true), LOGGER_DEBUG);
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
authenticate_success($record);
2016-09-25 18:50:08 +02:00
$_SESSION["allow_api"] = true;
2016-09-25 18:50:08 +02:00
Addon::callHooks('logged_in', $a->user);
}
2016-09-25 18:50:08 +02:00
/**
* API endpoints can define which HTTP method to accept when called.
* This function check the current HTTP method agains endpoint
* registered method.
*
2017-12-24 03:20:50 +01:00
* @brief Check HTTP method of called API
*
* @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 (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
}
2016-09-25 18:50:08 +02:00
/**
* Authenticate user, call registered API function, set HTTP headers
*
2017-12-24 03:20:50 +01:00
* @brief Main API entry point
*
* @param object $a App
2018-04-09 19:34:02 +02:00
* @return string|array API call result
*/
function api_call(App $a)
{
global $API, $called_api;
2016-09-25 18:50:08 +02:00
$type = "json";
if (strpos($a->query_string, ".xml") > 0) {
$type = "xml";
}
if (strpos($a->query_string, ".json") > 0) {
$type = "json";
}
if (strpos($a->query_string, ".rss") > 0) {
$type = "rss";
}
if (strpos($a->query_string, ".atom") > 0) {
$type = "atom";
}
try {
foreach ($API as $p => $info) {
if (strpos($a->query_string, $p) === 0) {
if (!api_check_method($info['method'])) {
throw new MethodNotAllowedException();
}
2016-09-25 18:50:08 +02:00
$called_api = explode("/", $p);
//unset($_SERVER['PHP_AUTH_USER']);
/// @TODO should be "true ==[=] $info['auth']", if you miss only one = character, you assign a variable (only with ==). Let's make all this even.
if ($info['auth'] === true && api_user() === false) {
api_login($a);
}
2016-09-25 18:50:08 +02:00
logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
logger('API parameters: ' . print_r($_REQUEST, true));
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 = (float) (microtime(true) - $stamp);
logger("API call duration: " . round($duration, 2) . "\t" . $a->query_string, LOGGER_DEBUG);
2016-09-25 18:50:08 +02:00
if (Config::get("system", "profiler")) {
$duration = microtime(true)-$a->performance["start"];
/// @TODO round() really everywhere?
logger(
parse_url($a->query_string, PHP_URL_PATH) . ": " . sprintf(
"Database: %s/%s, Cache %s/%s, Network: %s, I/O: %s, Other: %s, Total: %s",
round($a->performance["database"] - $a->performance["database_write"], 3),
round($a->performance["database_write"], 3),
round($a->performance["cache"], 3),
round($a->performance["cache_write"], 3),
round($a->performance["network"], 2),
round($a->performance["file"], 2),
round($duration - ($a->performance["database"]
+ $a->performance["cache"] + $a->performance["cache_write"]
+ $a->performance["network"] + $a->performance["file"]), 2),
round($duration, 2)
),
LOGGER_DEBUG
);
if (Config::get("rendertime", "callstack")) {
$o = "Database Read:\n";
foreach ($a->callstack["database"] as $func => $time) {
$time = round($time, 3);
if ($time > 0) {
$o .= $func . ": " . $time . "\n";
}
}
$o .= "\nDatabase Write:\n";
foreach ($a->callstack["database_write"] as $func => $time) {
$time = round($time, 3);
if ($time > 0) {
$o .= $func . ": " . $time . "\n";
}
}
$o = "Cache Read:\n";
foreach ($a->callstack["cache"] as $func => $time) {
$time = round($time, 3);
if ($time > 0) {
$o .= $func . ": " . $time . "\n";
}
}
$o .= "\nCache Write:\n";
foreach ($a->callstack["cache_write"] as $func => $time) {
$time = round($time, 3);
if ($time > 0) {
$o .= $func . ": " . $time . "\n";
}
}
$o .= "\nNetwork:\n";
foreach ($a->callstack["network"] as $func => $time) {
$time = round($time, 3);
if ($time > 0) {
$o .= $func . ": " . $time . "\n";
}
}
logger($o, LOGGER_DEBUG);
}
}
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");
$json = json_encode(end($return));
2017-12-24 00:27:45 +01:00
if (x($_GET, 'callback')) {
$json = $_GET['callback'] . "(" . $json . ")";
}
2018-01-04 02:54:35 +01:00
$return = $json;
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('API call not implemented: ' . $a->query_string);
throw new NotImplementedException();
} catch (HTTPException $e) {
header("HTTP/1.1 {$e->httpcode} {$e->httpdesc}");
return api_error($type, $e);
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
/**
* @brief Format API error string
*
* @param string $type Return type (xml, json, rss, as)
* @param object $e HTTPException Error object
2018-04-09 19:34:02 +02:00
* @return string|array error message formatted as $type
*/
function api_error($type, $e)
{
$a = get_app();
$error = ($e->getMessage() !== "" ? $e->getMessage() : $e->httpdesc);
/// @TODO: https://dev.twitter.com/overview/api/response-codes
$error = ["error" => $error,
"code" => $e->httpcode . " " . $e->httpdesc,
"request" => $a->query_string];
$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
/**
* @brief Set values for RSS template
*
* @param App $a
* @param array $arr Array to be passed to template
* @param array $user_info User info
* @return array
* @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' => System::baseUrl() . "/" . $a->query_string,
'base' => System::baseUrl(),
'updated' => api_date(null),
'atom_updated' => DateTimeFormat::utcNow(DateTimeFormat::ATOM),
'language' => $user_info['language'],
'logo' => System::baseUrl() . "/images/friendica-32.png",
];
2016-09-25 18:50:08 +02:00
return $arr;
}
2016-09-25 18:50:08 +02:00
/**
* @brief Unique contact to contact url.
*
* @param int $id Contact id
* @return bool|string
* Contact url or False if contact id is unknown
*/
2017-12-17 12:11:28 +01:00
function api_unique_id_to_nurl($id)
{
$r = dba::selectFirst('contact', ['nurl'], ['uid' => 0, 'id' => $id]);
if (DBM::is_result($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
/**
* @brief Get user info array.
*
* @param object $a App
* @param int|string $contact_id Contact ID or URL
*/
function api_get_user(App $a, $contact_id = null)
{
global $called_api;
$user = null;
$extra_query = "";
$url = "";
logger("api_get_user: Fetching user data for user ".$contact_id, LOGGER_DEBUG);
2016-09-25 18:50:08 +02:00
// Searching for contact URL
if (!is_null($contact_id) && (intval($contact_id) == 0)) {
$user = dbesc(normalise_link($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)) {
$user = dbesc(api_unique_id_to_nurl(intval($contact_id)));
2016-09-25 18:50:08 +02:00
if ($user == "") {
throw new BadRequestException("User 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) && x($_GET, 'user_id')) {
2017-12-17 12:11:28 +01:00
$user = dbesc(api_unique_id_to_nurl($_GET['user_id']));
2016-09-25 18:50:08 +02:00
if ($user == "") {
throw new BadRequestException("User 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) && x($_GET, 'screen_name')) {
$user = dbesc($_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) && x($_GET, 'profileurl')) {
$user = dbesc(normalise_link($_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
if (is_null($user) && ($a->argc > (count($called_api) - 1)) && (count($called_api) > 0)) {
$argid = count($called_api);
list($user, $null) = explode(".", $a->argv[$argid]);
if (is_numeric($user)) {
$user = dbesc(api_unique_id_to_nurl(intval($user)));
2016-09-25 18:50:08 +02:00
if ($user != "") {
$url = $user;
$extra_query = "AND `contact`.`nurl` = '%s' ";
if (api_user() !== false) {
$extra_query .= "AND `contact`.`uid`=" . intval(api_user());
}
}
} else {
$user = dbesc($user);
2016-09-25 18:50:08 +02:00
$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
}
}
}
2016-09-25 18:50:08 +02:00
logger("api_get_user: user ".$user, LOGGER_DEBUG);
2016-09-25 18:50:08 +02:00
if (!$user) {
if (api_user() === false) {
api_login($a);
return false;
} else {
$user = $_SESSION['uid'];
$extra_query = "AND `contact`.`uid` = %d AND `contact`.`self` ";
2016-09-25 18:50:08 +02:00
}
}
2016-09-25 18:50:08 +02:00
logger('api_user: ' . $extra_query . ', user: ' . $user);
2016-09-25 18:50:08 +02:00
// user info
$uinfo = q(
"SELECT *, `contact`.`id` AS `cid` FROM `contact`
WHERE 1
$extra_query",
$user
);
2016-09-25 18:50:08 +02:00
// Selecting the id by priority, friendica first
if (is_array($uinfo)) {
api_best_nickname($uinfo);
}
// if the contact wasn't found, fetch it from the contacts with uid = 0
if (!DBM::is_result($uinfo)) {
$r = [];
2016-09-25 18:50:08 +02:00
if ($url != "") {
$r = q("SELECT * FROM `contact` WHERE `uid` = 0 AND `nurl` = '%s' LIMIT 1", dbesc(normalise_link($url)));
2016-09-25 18:50:08 +02:00
}