Merge pull request #14422 from annando/issue-14370

Issue 14370: Improved content negogiation
This commit is contained in:
Tobias Diekershoff 2024-09-07 08:28:29 +02:00 committed by GitHub
commit c8dbafad83
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -34,22 +34,14 @@ class Xrd extends BaseModule
} }
$uri = urldecode(trim($_GET['uri'])); $uri = urldecode(trim($_GET['uri']));
if (strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/jrd+json') !== false) { $mode = self::getAcceptedContentType($_SERVER['HTTP_ACCEPT'] ?? '', Response::TYPE_JSON);
$mode = Response::TYPE_JSON;
} else {
$mode = Response::TYPE_XML;
}
} else { } else {
if (empty($_GET['resource'])) { if (empty($_GET['resource'])) {
throw new BadRequestException(); throw new BadRequestException();
} }
$uri = urldecode(trim($_GET['resource'])); $uri = urldecode(trim($_GET['resource']));
if (strpos($_SERVER['HTTP_ACCEPT'] ?? '', 'application/xrd+xml') !== false) { $mode = self::getAcceptedContentType($_SERVER['HTTP_ACCEPT'] ?? '', Response::TYPE_XML);
$mode = Response::TYPE_XML;
} else {
$mode = Response::TYPE_JSON;
}
} }
if (substr($uri, 0, 4) === 'http') { if (substr($uri, 0, 4) === 'http') {
@ -67,7 +59,7 @@ class Xrd extends BaseModule
} }
if (!empty($host) && $host !== DI::baseUrl()->getHost()) { if (!empty($host) && $host !== DI::baseUrl()->getHost()) {
DI::logger()->notice('Invalid host name for xrd query',['host' => $host, 'uri' => $uri]); DI::logger()->notice('Invalid host name for xrd query', ['host' => $host, 'uri' => $uri]);
throw new NotFoundException('Invalid host name for xrd query: ' . $host); throw new NotFoundException('Invalid host name for xrd query: ' . $host);
} }
@ -102,6 +94,36 @@ class Xrd extends BaseModule
} }
} }
/**
* Detect the accepted content type.
* @todo Handle priorities (see "application/xrd+xml,text/xml;q=0.9")
*
* @param string $accept
* @param string $default
* @return string
*/
private function getAcceptedContentType(string $accept, string $default): string
{
$parts = [];
foreach (explode(',', $accept) as $part) {
$parts[] = current(explode(';', $part));
}
if (empty($parts)) {
return $default;
} elseif (in_array('application/jrd+json', $parts) && !in_array('application/xrd+xml', $parts)) {
return Response::TYPE_JSON;
} elseif (!in_array('application/jrd+json', $parts) && in_array('application/xrd+xml', $parts)) {
return Response::TYPE_XML;
} elseif (in_array('application/json', $parts) && !in_array('text/xml', $parts)) {
return Response::TYPE_JSON;
} elseif (!in_array('application/json', $parts) && in_array('text/xml', $parts)) {
return Response::TYPE_XML;
} else {
return $default;
}
}
private function printSystemJSON(array $owner) private function printSystemJSON(array $owner)
{ {
$baseURL = (string)$this->baseUrl; $baseURL = (string)$this->baseUrl;