index-soutien/includes/cache.php

47 lines
1.4 KiB
PHP
Raw Normal View History

<?php
require_once __DIR__ . '/config.php';
function getContent(string $lang = 'fr'): array {
$cacheFile = CACHE_DIR . "/content.{$lang}.json";
// Serve cache if fresh
if (file_exists($cacheFile) && (time() - filemtime($cacheFile)) < CACHE_TTL) {
return json_decode(file_get_contents($cacheFile), true) ?: [];
}
// Fetch from Kirby API
$url = KIRBY_API_URL . '?lang=' . urlencode($lang);
if (SUPPORT_API_TOKEN) {
$url .= '&token=' . urlencode(SUPPORT_API_TOKEN);
}
$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 5,
CURLOPT_REFERER => 'https://soutenir.index.ngo',
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_SSL_VERIFYPEER => true,
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($response !== false && $httpCode === 200) {
$data = json_decode($response, true);
if ($data && !isset($data['error'])) {
@file_put_contents($cacheFile, $response, LOCK_EX);
return $data;
}
}
// Fallback: serve stale cache rather than nothing
if (file_exists($cacheFile)) {
return json_decode(file_get_contents($cacheFile), true) ?: [];
}
return [];
}