Files
elwig-www/www/format.inc

49 lines
1.4 KiB
PHP

<?php
date_default_timezone_set('Europe/Vienna');
function get_fmt(): string {
$fmt = _get_fmt();
if ($fmt === 'ascii') {
header('Status: 303');
header('Location: ?format=text');
exit();
} else if ($fmt !== 'json' && $fmt !== 'html' && $fmt !== 'text') {
header('Status: 300');
header('Content-Type: text/html; charset=UTF-8');
echo "<!DOCTYPE html><html><head></head><body>\n<a href='?format=html'>HTML</a><br/>\n<a href='?format=json'>JSON</a><br/>\n<a href='?format=text'>Text</a>\n</body></html>\n";
exit();
}
return $fmt;
}
function _get_fmt(): string {
if (!empty($_GET['format'])) return $_GET['format'];
$fmts = [];
foreach (explode(',', $_SERVER['HTTP_ACCEPT']) as $acc) {
$acc = explode(';', trim($acc));
$q = 1;
if (sizeof($acc) > 1) {
$qv = trim($acc[1]);
if (str_starts_with($qv, 'q=')) {
$q = (double)substr($qv, 2);
}
}
$fmts[trim($acc[0])] = $q;
}
arsort($fmts, SORT_NUMERIC);
array_filter($fmts, function($k) {
return str_contains($k, '/json') || $k === 'text/html' || $k === 'text/plain' || str_contains($k, 'text/*');
});
$type = sizeof($fmts) > 0 ? array_key_first($fmts) : null;
if (str_contains($type, '/json')) {
return 'json';
} else if ($type === 'text/html') {
return 'html';
} else {
return 'text';
}
}