Browse Source

feat(spip_loader): improve Last-Modified header

fix-api
JamesRezo 9 months ago
parent
commit
828d242c76
  1. 46
      action/api_spip_loader.php

46
action/api_spip_loader.php

@ -28,13 +28,49 @@ function action_api_spip_loader_dist(): void {
}
}
$lastModified = stat(find_in_path('data/releases.json'));
// $lastModified = stat(find_in_path('data/pre_releases.json')); // best date when alpha is out
$lastModified = $lastModified['mtime'] ?? null;
$lastModified = DateTime::createFromFormat('U', $lastModified, new DateTimeZone('UTC'));
header('Last-Modified: ' . $lastModified->format('D, d M Y H:i:s') . ' GMT');
$releases = get_mtime('data/releases.json');
$preReleases = get_mtime('data/pre_releases.json');
if (!($releases === 0 && $preReleases === 0) && $lastModifed = last_modified($releases, $preReleases)) {
header($lastModifed);
}
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
echo json_encode($reponse);
exit(0);
}
/**
* Gets the UNIX timestamp of the modified time of a file.
*
* @param string $filename relative filename to find in SPIP_PATH
* @return integer UNIX timestamp of the modified time or 0 if file not found
*/
function get_mtime(string $filename): int {
if ($path = (string) find_in_path($filename)) {
$stats = (array) stat($path);
if (isset($stats['mtime'])) {
return (int) $stats['mtime'];
}
}
return 0;
}
/**
* Gets the most recent modified time.
*
* @param integer $releases
* @param integer $preReleases
* @return string Formatted Last-Modified header
*/
function last_modified(int $releases, int $preReleases): string {
$lastModified = (int) max($releases, $preReleases);
$lastModified = DateTime::createFromFormat('U', (string) $lastModified, new DateTimeZone('UTC'));
$formatedLastModified = '';
if ($lastModified instanceof DateTime) {
$formatedLastModified = 'Last-Modified: ' . $lastModified->format('D, d M Y H:i:s') . ' GMT';
}
return $formatedLastModified;
}

Loading…
Cancel
Save