1
0
Fork 0
friendica_2020-09-1_sharedH.../include/api.php
2018-03-07 16:34:17 -05:00

5989 lines
169 KiB
PHP
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

<?php
/**
* Friendica implementation of statusnet/twitter API
*
* @file include/api.php
* @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;
use Friendica\Core\Config;
use Friendica\Core\L10n;
use Friendica\Core\NotificationsManager;
use Friendica\Core\PConfig;
use Friendica\Core\System;
use Friendica\Core\Worker;
use Friendica\Database\DBM;
use Friendica\Model\Contact;
use Friendica\Model\Group;
use Friendica\Model\Item;
use Friendica\Model\Mail;
use Friendica\Model\Photo;
use Friendica\Model\User;
use Friendica\Network\FKOAuth1;
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;
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 = null;
/**
* 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).
*
* @brief Auth API user
*/
function api_user()
{
if (x($_SESSION, 'allow_api')) {
return local_user();
}
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)
*
* @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');
}
// Support for known clients that doesn't send a source name
if (strpos($_SERVER['HTTP_USER_AGENT'], "Twidere") !== false) {
return "Twidere";
}
logger("Unrecognized user-agent ".$_SERVER['HTTP_USER_AGENT'], LOGGER_DEBUG);
return "api";
}
/**
* @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");
}
/**
* Register a function to be the endpoint for defined API path.
*
* @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,
];
}
/**
* Log in user via OAuth1 or Simple HTTP Auth.
* Simple Auth allow username in form of <pre>user@server</pre>, ignoring server part
*
* @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;
}
echo __FILE__.__LINE__.__FUNCTION__ . "<pre>";
var_dump($consumer, $token);
die();
} catch (Exception $e) {
logger($e);
}
// 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;
}
}
if (!x($_SERVER, 'PHP_AUTH_USER')) {
logger('API_login: ' . print_r($_SERVER, true), LOGGER_DEBUG);
header('WWW-Authenticate: Basic realm="Friendica"');
throw new UnauthorizedException("This API requires login");
}
$user = $_SERVER['PHP_AUTH_USER'];
$password = $_SERVER['PHP_AUTH_PW'];
// allow "user@server" login (but ignore 'server' part)
$at = strstr($user, "@", true);
if ($at) {
$user = $at;
}
// next code from mod/auth.php. needs better solution
$record = null;
$addon_auth = [
'username' => trim($user),
'password' => trim($password),
'authenticated' => 0,
'user_record' => null,
];
/*
* 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);
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) {
$record = dba::selectFirst('user', [], ['uid' => $user_id]);
}
}
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");
}
authenticate_success($record);
$_SESSION["allow_api"] = true;
Addon::callHooks('logged_in', $a->user);
}
/**
* API endpoints can define which HTTP method to accept when called.
* This function check the current HTTP method agains endpoint
* registered method.
*
* @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;
}
return (strpos($method, $_SERVER['REQUEST_METHOD']) !== false);
}
/**
* Authenticate user, call registered API function, set HTTP headers
*
* @brief Main API entry point
*
* @param object $a App
* @return string API call result
*/
function api_call(App $a)
{
global $API, $called_api;
$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();
}
$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);
}
logger('API call for ' . $a->user['username'] . ': ' . $a->query_string);
logger('API parameters: ' . print_r($_REQUEST, true));
$stamp = microtime(true);
$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);
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";