Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
da90e1dbbe | ||
|
|
46b7c5af2c |
No files matched your search
@@ -1,57 +1,36 @@
|
|||||||
# Flux RSS - Commune de Silly
|
# Flux RSS - Commune de Silly
|
||||||
|
|
||||||
Genere trois flux RSS/Atom pour la commune de Silly (Belgique) : actualites,
|
## Actualités et agenda : flux officiels
|
||||||
agenda et page Facebook, a deployer sur un hebergement PHP mutualise
|
|
||||||
(extensions `curl` et `dom` uniquement, aucun cron ni conf serveur : chaque
|
|
||||||
flux se regenere a la demande et est mis en cache).
|
|
||||||
|
|
||||||
Depuis le 14/10/2026, www.silly.be est passe de Plone (`imio.smartweb`) a
|
Depuis la refonte du site sous WordPress (14/10/2026), la commune publie
|
||||||
WordPress. L'ancienne API JSON n'existe plus ; la variante Python
|
ses propres flux. Il suffit de s'y abonner directement :
|
||||||
(`silly_rss.py`) et ses fichiers de deploiement (nginx/cron) qui en
|
|
||||||
dependaient ont ete supprimes (historique git). Nouvelles sources :
|
|
||||||
|
|
||||||
| Flux | Source | Cache |
|
- Actualités : `https://www.silly.be/actualites/feed/`
|
||||||
| --- | --- | --- |
|
- Agenda (événements à venir) : `https://www.silly.be/agenda/feed/`
|
||||||
| `actualites.php` | flux RSS WordPress `https://www.silly.be/actualites/feed/` (50 derniers articles via `?paged=1..5`, texte complet), re-servi tel quel avec `atom:link rel="self"` corrige | 15 min |
|
|
||||||
| `agenda.php` | iCal officiel `https://www.silly.be/agenda/?ics=1`, converti en RSS (guid = UID, link = URL, description = dates + lieu + texte) | 12 h |
|
|
||||||
| `facebook.php` | proxy du flux [FetchRSS](https://fetchrss.com) | 15 min |
|
|
||||||
|
|
||||||
Limites de l'agenda : l'iCal ne liste que les evenements a venir, et les
|
Les scripts `actualites.php` et `agenda.php` (relais du flux WordPress et
|
||||||
regles de recurrence (`RRULE`) ne sont pas developpees. L'API REST
|
conversion de l'iCal `?ics=1` en RSS) ont été retirés au profit de ces flux
|
||||||
`/wp-json/wp/v2/evenement` expose davantage d'evenements (passes inclus) mais
|
officiels, tout comme `silly_rss.py`, qui dépendait de l'API de l'ancien site
|
||||||
sans aucune date (champ `acf` vide), donc inutilisable pour un agenda.
|
Plone. Tout reste consultable dans l'historique git.
|
||||||
|
|
||||||
## Deploiement (hebergement perso — sillycone-village.be)
|
## Page Facebook : relais FetchRSS
|
||||||
|
|
||||||
1. Copier tout le dossier [php/](php/) sur l'hebergement (FTP/SFTP), dans
|
La page Facebook (`communedesilly`) n'a pas de flux officiel. Le flux est
|
||||||
`silly-rss/` a la racine du site (Apache, confirme actif sur
|
généré par [FetchRSS](https://fetchrss.com) et relayé par
|
||||||
`sillycone-village.be`).
|
[php/facebook.php](php/facebook.php), qui :
|
||||||
2. Verifier que PHP a les extensions `curl` et `dom` activees (quasi toujours le cas en
|
|
||||||
mutualise standard).
|
|
||||||
3. Le dossier `php/cache/` doit etre inscriptible par PHP (permissions par
|
|
||||||
defaut suffisent generalement sur du mutualise ; sinon `chmod 775`).
|
|
||||||
4. Les flux sont alors accessibles en :
|
|
||||||
- `https://sillycone-village.be/silly-rss/actualites.php`
|
|
||||||
- `https://sillycone-village.be/silly-rss/agenda.php`
|
|
||||||
- `https://sillycone-village.be/silly-rss/facebook.php` (proxy/cache du
|
|
||||||
flux [FetchRSS](https://fetchrss.com) de la page Facebook, pour avoir
|
|
||||||
une URL stable sur votre propre domaine)
|
|
||||||
5. Ajouter ces 3 URLs comme sources dans FreshRSS (Administration > Flux
|
|
||||||
RSS > Ajouter un flux), sur `https://akbar.nohost.me/rss`.
|
|
||||||
|
|
||||||
Note CSP : `sillycone-village.be` sert ses pages HTML avec un
|
- le sert sous notre propre domaine, avec une URL stable à partager ;
|
||||||
`Content-Security-Policy` strict (`connect-src 'self' ...`). Cela ne
|
- le met en cache 15 minutes (dossier `php/cache/`) ;
|
||||||
concerne que le JS execute dans le navigateur sur ce site — sans impact ici
|
- corrige deux erreurs du flux FetchRSS signalées par le validateur W3C
|
||||||
puisque FreshRSS recupere les flux XML cote serveur.
|
(`<id>` d'entrée qui n'est pas une URL, lien `self` qui pointe vers
|
||||||
|
FetchRSS).
|
||||||
|
|
||||||
Teste avec PHP 8.3 CLI (16/10/2026) : les 3 scripts produisent du XML bien forme
|
URL publique : `https://sillycone-village.be/silly-rss/facebook.php`
|
||||||
avec de vraies donnees (10 actualites, 4 evenements).
|
|
||||||
|
|
||||||
## Facebook (page communedesilly)
|
### Déploiement
|
||||||
|
|
||||||
Pas de solution fiable trouvee en scraping direct : le HTML de
|
1. Copier le contenu de [php/](php/) dans `silly-rss/` sur l'hébergement
|
||||||
facebook.com est vide de contenu exploitable sans authentification, et
|
(FTP/SFTP), y compris `cache/.htaccess`.
|
||||||
l'instance RSS-Bridge testee (`FacebookBridge`) renvoie une erreur 400.
|
2. Prérequis PHP : extensions `curl` et `dom` (php-xml).
|
||||||
Solution retenue : [FetchRSS](https://fetchrss.com) (service tiers),
|
3. Le dossier `cache/` doit être inscriptible par PHP (`755` ou `775`, pas
|
||||||
reproxifie sous votre propre domaine (`facebook.php`) pour avoir 3 URLs
|
`777`).
|
||||||
stables et partageables.
|
|
||||||
@@ -1,82 +0,0 @@
|
|||||||
<?php
|
|
||||||
require __DIR__ . '/common.php';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Proxy/cache du flux RSS WordPress natif de silly.be (articles complets
|
|
||||||
* dans content:encoded, categories, 10 derniers articles). On le re-sert
|
|
||||||
* sous notre domaine pour garder une URL stable et on corrige atom:link
|
|
||||||
* rel="self" (il pointe sinon vers silly.be) pour le validateur W3C.
|
|
||||||
*
|
|
||||||
* WordPress limite le flux a 10 articles (reglage du site, non modifiable
|
|
||||||
* d'ici) mais accepte ?paged=N : on concatene NEWS_PAGES pages pour
|
|
||||||
* obtenir jusqu'a 50 articles.
|
|
||||||
*/
|
|
||||||
const NEWS_FEED_URL = 'https://www.silly.be/actualites/feed/';
|
|
||||||
const NEWS_PAGES = 5; // 5 x 10 = 50 articles
|
|
||||||
const SELF_URL = 'https://sillycone-village.be/silly-rss/actualites.php';
|
|
||||||
|
|
||||||
function build_news_feed(): string
|
|
||||||
{
|
|
||||||
$raw = http_get(NEWS_FEED_URL, ['Accept: application/rss+xml, application/xml']);
|
|
||||||
|
|
||||||
$doc = new DOMDocument();
|
|
||||||
if (!@$doc->loadXML($raw)) {
|
|
||||||
throw new RuntimeException('Flux WordPress illisible (XML invalide)');
|
|
||||||
}
|
|
||||||
|
|
||||||
$xpath = new DOMXPath($doc);
|
|
||||||
$xpath->registerNamespace('atom', 'http://www.w3.org/2005/Atom');
|
|
||||||
$selfLinks = $xpath->query('/rss/channel/atom:link[@rel="self"]');
|
|
||||||
if ($selfLinks->length === 0) {
|
|
||||||
throw new RuntimeException('Reponse inattendue : pas un flux RSS');
|
|
||||||
}
|
|
||||||
foreach ($selfLinks as $selfLink) {
|
|
||||||
$selfLink->setAttribute('href', SELF_URL);
|
|
||||||
}
|
|
||||||
|
|
||||||
// WordPress emet <sy:updatePeriod>\n\thourly\t</sy:updatePeriod> : on retire
|
|
||||||
// les blancs parasites autour des valeurs.
|
|
||||||
$xpath->registerNamespace('sy', 'http://purl.org/rss/1.0/modules/syndication/');
|
|
||||||
foreach ($xpath->query('/rss/channel/sy:*') as $node) {
|
|
||||||
$node->textContent = trim($node->textContent);
|
|
||||||
}
|
|
||||||
|
|
||||||
// Pages suivantes : un echec (ou une page vide) arrete simplement la
|
|
||||||
// pagination, la premiere page suffit a servir un flux valide.
|
|
||||||
$channel = $xpath->query('/rss/channel')->item(0);
|
|
||||||
$seen = [];
|
|
||||||
foreach ($xpath->query('/rss/channel/item/guid') as $g) {
|
|
||||||
$seen[trim($g->textContent)] = true;
|
|
||||||
}
|
|
||||||
for ($page = 2; $page <= NEWS_PAGES; $page++) {
|
|
||||||
try {
|
|
||||||
$more = new DOMDocument();
|
|
||||||
$raw = http_get(NEWS_FEED_URL . '?paged=' . $page, ['Accept: application/rss+xml, application/xml']);
|
|
||||||
if (!@$more->loadXML($raw)) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} catch (Throwable $e) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
$added = 0;
|
|
||||||
$moreXpath = new DOMXPath($more);
|
|
||||||
foreach ($moreXpath->query('/rss/channel/item') as $item) {
|
|
||||||
// Le tri de WordPress n'est pas stable entre articles de meme
|
|
||||||
// date : on dedoublonne par guid aux jonctions de pages.
|
|
||||||
$guid = trim($moreXpath->evaluate('string(guid)', $item));
|
|
||||||
if ($guid === '' || isset($seen[$guid])) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$seen[$guid] = true;
|
|
||||||
$channel->appendChild($doc->importNode($item, true));
|
|
||||||
$added++;
|
|
||||||
}
|
|
||||||
if ($added === 0) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return $doc->saveXML();
|
|
||||||
}
|
|
||||||
|
|
||||||
serve_cached_feed('actualites', 'build_news_feed');
|
|
||||||
-188
@@ -1,188 +0,0 @@
|
|||||||
<?php
|
|
||||||
require __DIR__ . '/common.php';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Agenda : conversion de l'iCal officiel de silly.be en flux RSS.
|
|
||||||
* Le calendrier annonce un TTL de 12 h (X-PUBLISHED-TTL:PT12H), on cache
|
|
||||||
* donc aussi 12 h. Il ne contient que les evenements a venir (quelques
|
|
||||||
* uns) ; l'API REST /wp-json/wp/v2/evenement liste plus d'evenements mais
|
|
||||||
* sans aucune date (champ acf vide), donc inutilisable pour un agenda.
|
|
||||||
* Les regles de recurrence (RRULE) ne sont pas developpees.
|
|
||||||
*/
|
|
||||||
const ICAL_URL = 'https://www.silly.be/agenda/?ics=1';
|
|
||||||
const AGENDA_SELF_URL = 'https://sillycone-village.be/silly-rss/agenda.php';
|
|
||||||
const AGENDA_TTL_SECONDS = 43200; // 12 heures
|
|
||||||
const DISPLAY_TZ = 'Europe/Brussels';
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Parse un texte iCal : deplie les lignes (RFC 5545 §3.1) et renvoie la
|
|
||||||
* liste des VEVENT, chacun sous la forme NOM => [['params' => [...], 'value' => ...], ...].
|
|
||||||
*/
|
|
||||||
function parse_ical_events(string $ical): array
|
|
||||||
{
|
|
||||||
$ical = str_replace(["\r\n", "\r"], "\n", $ical);
|
|
||||||
$ical = preg_replace('/\n[ \t]/', '', $ical);
|
|
||||||
|
|
||||||
$events = [];
|
|
||||||
$current = null;
|
|
||||||
foreach (explode("\n", $ical) as $line) {
|
|
||||||
$line = rtrim($line);
|
|
||||||
if ($line === 'BEGIN:VEVENT') {
|
|
||||||
$current = [];
|
|
||||||
} elseif ($line === 'END:VEVENT') {
|
|
||||||
if ($current !== null) {
|
|
||||||
$events[] = $current;
|
|
||||||
}
|
|
||||||
$current = null;
|
|
||||||
} elseif ($current !== null && $line !== '') {
|
|
||||||
// NOM[;PARAM=VAL...]:valeur (les valeurs de parametres peuvent
|
|
||||||
// etre entre guillemets et contenir ':' ; on coupe sur le 1er
|
|
||||||
// ':' hors guillemets)
|
|
||||||
if (!preg_match('/^([A-Za-z0-9-]+)((?:;(?:[^:;"]|"[^"]*")*)*):(.*)$/s', $line, $m)) {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$params = [];
|
|
||||||
foreach (explode(';', ltrim($m[2], ';')) as $p) {
|
|
||||||
if (strpos($p, '=') !== false) {
|
|
||||||
[$k, $v] = explode('=', $p, 2);
|
|
||||||
$params[strtoupper($k)] = trim($v, '"');
|
|
||||||
}
|
|
||||||
}
|
|
||||||
$current[strtoupper($m[1])][] = ['params' => $params, 'value' => $m[3]];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
return $events;
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Deséchappe une valeur TEXT iCal : \\ \, \; \n. */
|
|
||||||
function ical_unescape(string $text): string
|
|
||||||
{
|
|
||||||
return preg_replace_callback('/\\\\([nN,;\\\\])/', function ($m) {
|
|
||||||
return ($m[1] === 'n' || $m[1] === 'N') ? "\n" : $m[1];
|
|
||||||
}, $text);
|
|
||||||
}
|
|
||||||
|
|
||||||
function ical_text(array $event, string $name): string
|
|
||||||
{
|
|
||||||
return isset($event[$name][0]) ? trim(ical_unescape($event[$name][0]['value'])) : '';
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Renvoie [DateTimeImmutable|null, bool $allDay] pour DTSTART/DTEND/CREATED. */
|
|
||||||
function ical_date(array $event, string $name): array
|
|
||||||
{
|
|
||||||
if (!isset($event[$name][0])) {
|
|
||||||
return [null, false];
|
|
||||||
}
|
|
||||||
$prop = $event[$name][0];
|
|
||||||
$value = trim($prop['value']);
|
|
||||||
$display = new DateTimeZone(DISPLAY_TZ);
|
|
||||||
try {
|
|
||||||
if (($prop['params']['VALUE'] ?? '') === 'DATE' || preg_match('/^\d{8}$/', $value)) {
|
|
||||||
return [new DateTimeImmutable($value, $display), true];
|
|
||||||
}
|
|
||||||
if (substr($value, -1) === 'Z') {
|
|
||||||
$dt = new DateTimeImmutable(substr($value, 0, -1), new DateTimeZone('UTC'));
|
|
||||||
} else {
|
|
||||||
$tz = new DateTimeZone($prop['params']['TZID'] ?? DISPLAY_TZ);
|
|
||||||
$dt = new DateTimeImmutable($value, $tz);
|
|
||||||
}
|
|
||||||
return [$dt->setTimezone($display), false];
|
|
||||||
} catch (Exception $e) {
|
|
||||||
return [null, false];
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function format_event_dates(?DateTimeImmutable $start, ?DateTimeImmutable $end, bool $allDay): string
|
|
||||||
{
|
|
||||||
if (!$start) {
|
|
||||||
return '';
|
|
||||||
}
|
|
||||||
if ($allDay) {
|
|
||||||
// En iCal, DTEND d'un evenement "journee entiere" est exclusif.
|
|
||||||
$last = $end ? $end->modify('-1 day') : $start;
|
|
||||||
if ($last <= $start) {
|
|
||||||
return 'Le ' . $start->format('d/m/Y');
|
|
||||||
}
|
|
||||||
return 'Du ' . $start->format('d/m/Y') . ' au ' . $last->format('d/m/Y');
|
|
||||||
}
|
|
||||||
if (!$end || $end == $start) {
|
|
||||||
return 'Le ' . $start->format('d/m/Y à H:i');
|
|
||||||
}
|
|
||||||
if ($end->format('Y-m-d') === $start->format('Y-m-d')) {
|
|
||||||
return 'Le ' . $start->format('d/m/Y') . ' de ' . $start->format('H:i') . ' à ' . $end->format('H:i');
|
|
||||||
}
|
|
||||||
return 'Du ' . $start->format('d/m/Y à H:i') . ' au ' . $end->format('d/m/Y à H:i');
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Texte brut -> HTML : paragraphes sur lignes vides, <br> sur retours simples, URLs cliquables. */
|
|
||||||
function text_to_html(string $text): string
|
|
||||||
{
|
|
||||||
$html = '';
|
|
||||||
foreach (preg_split('/\n{2,}/', trim($text)) as $para) {
|
|
||||||
$para = trim($para);
|
|
||||||
if ($para === '') {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
$safe = htmlspecialchars($para, ENT_QUOTES, 'UTF-8');
|
|
||||||
$safe = preg_replace('#(https?://[^\s<]+)#', '<a href="$1">$1</a>', $safe);
|
|
||||||
$html .= '<p>' . nl2br($safe, false) . '</p>';
|
|
||||||
}
|
|
||||||
return $html;
|
|
||||||
}
|
|
||||||
|
|
||||||
function build_events_feed(): string
|
|
||||||
{
|
|
||||||
$ical = http_get(ICAL_URL, ['Accept: text/calendar, */*']);
|
|
||||||
if (strpos($ical, 'BEGIN:VCALENDAR') === false) {
|
|
||||||
throw new RuntimeException('Reponse inattendue : pas un calendrier iCal');
|
|
||||||
}
|
|
||||||
|
|
||||||
$entries = [];
|
|
||||||
$seen = [];
|
|
||||||
foreach (parse_ical_events($ical) as $event) {
|
|
||||||
[$start, $allDay] = ical_date($event, 'DTSTART');
|
|
||||||
[$end] = ical_date($event, 'DTEND');
|
|
||||||
[$created] = ical_date($event, 'CREATED');
|
|
||||||
|
|
||||||
$title = ical_text($event, 'SUMMARY') ?: '(sans titre)';
|
|
||||||
$uid = ical_text($event, 'UID') ?: $title . '-' . ($start ? $start->format('c') : '');
|
|
||||||
$url = ical_text($event, 'URL');
|
|
||||||
$location = ical_text($event, 'LOCATION');
|
|
||||||
|
|
||||||
$guid = $uid;
|
|
||||||
if (isset($seen[$guid])) { // occurrence d'un evenement repete : meme UID
|
|
||||||
$guid .= '-' . ($start ? $start->format('YmdHi') : count($seen));
|
|
||||||
}
|
|
||||||
$seen[$guid] = true;
|
|
||||||
|
|
||||||
$meta = format_event_dates($start, $end, $allDay);
|
|
||||||
if ($location !== '') {
|
|
||||||
$meta .= ($meta !== '' ? ' — ' : '') . 'Lieu : ' . $location;
|
|
||||||
}
|
|
||||||
$description = ($meta !== '' ? '<p>' . htmlspecialchars($meta, ENT_QUOTES, 'UTF-8') . '</p>' : '')
|
|
||||||
. text_to_html(ical_text($event, 'DESCRIPTION'));
|
|
||||||
|
|
||||||
$pub = $created ?? $start;
|
|
||||||
$entries[] = [
|
|
||||||
'sort' => $start ? $start->getTimestamp() : PHP_INT_MAX,
|
|
||||||
'item' => [
|
|
||||||
'title' => $title,
|
|
||||||
'link' => $url !== '' ? $url : 'https://www.silly.be/agenda/',
|
|
||||||
'guid' => $guid,
|
|
||||||
'pubDate' => $pub ? $pub->format('c') : null,
|
|
||||||
'description' => $description,
|
|
||||||
],
|
|
||||||
];
|
|
||||||
}
|
|
||||||
usort($entries, fn($a, $b) => $a['sort'] <=> $b['sort']);
|
|
||||||
|
|
||||||
return build_rss(
|
|
||||||
'Silly.be - Agenda',
|
|
||||||
'https://www.silly.be/agenda/',
|
|
||||||
'Agenda / événements de la commune de Silly (Belgique)',
|
|
||||||
array_column($entries, 'item'),
|
|
||||||
AGENDA_SELF_URL
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
serve_cached_feed('agenda', 'build_events_feed', AGENDA_TTL_SECONDS);
|
|
||||||
+2
-101
@@ -1,27 +1,16 @@
|
|||||||
<?php
|
<?php
|
||||||
/**
|
|
||||||
* Fonctions communes aux 3 flux RSS (actualites.php, agenda.php, facebook.php).
|
|
||||||
*
|
|
||||||
* Depuis le 14/10/2026, www.silly.be tourne sous WordPress (l'ancienne API
|
|
||||||
* JSON Plone / imio.smartweb n'existe plus). Les sources sont desormais :
|
|
||||||
* le flux RSS WordPress natif (actualites) et l'iCal officiel (agenda).
|
|
||||||
*/
|
|
||||||
|
|
||||||
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
const USER_AGENT = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
|
||||||
const CACHE_DIR = __DIR__ . '/cache';
|
const CACHE_DIR = __DIR__ . '/cache';
|
||||||
const CACHE_TTL_SECONDS = 900; // 15 minutes
|
const CACHE_TTL_SECONDS = 900; // 15 minutes
|
||||||
|
|
||||||
/**
|
function http_get(string $url, array $extraHeaders = []): string
|
||||||
* Recupere une URL via curl (necessaire pour passer le WAF Cloudflare
|
|
||||||
* de silly.be) et renvoie le corps de la reponse en texte.
|
|
||||||
*/
|
|
||||||
function http_get(string $url, array $headers = ['Accept: */*']): string
|
|
||||||
{
|
{
|
||||||
$ch = curl_init($url);
|
$ch = curl_init($url);
|
||||||
curl_setopt_array($ch, [
|
curl_setopt_array($ch, [
|
||||||
CURLOPT_RETURNTRANSFER => true,
|
CURLOPT_RETURNTRANSFER => true,
|
||||||
CURLOPT_USERAGENT => USER_AGENT,
|
CURLOPT_USERAGENT => USER_AGENT,
|
||||||
CURLOPT_HTTPHEADER => $headers,
|
CURLOPT_HTTPHEADER => $extraHeaders,
|
||||||
CURLOPT_TIMEOUT => 20,
|
CURLOPT_TIMEOUT => 20,
|
||||||
CURLOPT_FOLLOWLOCATION => true,
|
CURLOPT_FOLLOWLOCATION => true,
|
||||||
CURLOPT_MAXREDIRS => 3,
|
CURLOPT_MAXREDIRS => 3,
|
||||||
@@ -40,91 +29,3 @@ function http_get(string $url, array $headers = ['Accept: */*']): string
|
|||||||
}
|
}
|
||||||
return $body;
|
return $body;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Sert un contenu XML depuis un cache fichier, en le regenerant via
|
|
||||||
* $builder() si le cache est absent ou perime. Evite de solliciter
|
|
||||||
* silly.be / fetchrss.com a chaque poll de chaque abonne FreshRSS.
|
|
||||||
*/
|
|
||||||
function serve_cached_feed(string $cacheKey, callable $builder, int $ttl = CACHE_TTL_SECONDS): void
|
|
||||||
{
|
|
||||||
// text/xml plutot que application/rss+xml : les navigateurs affichent
|
|
||||||
// ce type en ligne (arbre XML) au lieu de forcer un telechargement,
|
|
||||||
// ce qui est plus rassurant pour un visiteur qui clique le lien
|
|
||||||
// directement depuis le site. FreshRSS et les autres lecteurs RSS
|
|
||||||
// detectent le format en lisant le contenu, pas ce header.
|
|
||||||
header('Content-Type: text/xml; charset=utf-8');
|
|
||||||
|
|
||||||
if (!is_dir(CACHE_DIR)) {
|
|
||||||
mkdir(CACHE_DIR, 0775, true);
|
|
||||||
}
|
|
||||||
$cacheFile = CACHE_DIR . '/' . $cacheKey . '.xml';
|
|
||||||
|
|
||||||
if (is_file($cacheFile) && (time() - filemtime($cacheFile)) < $ttl) {
|
|
||||||
readfile($cacheFile);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
$xml = $builder();
|
|
||||||
file_put_contents($cacheFile, $xml);
|
|
||||||
echo $xml;
|
|
||||||
} catch (Throwable $e) {
|
|
||||||
// En cas d'erreur (site source indisponible, etc.), on sert le
|
|
||||||
// cache perime plutot que de casser le flux chez les abonnes.
|
|
||||||
if (is_file($cacheFile)) {
|
|
||||||
readfile($cacheFile);
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
http_response_code(502);
|
|
||||||
header('Content-Type: text/plain; charset=utf-8');
|
|
||||||
echo "Erreur de generation du flux : " . $e->getMessage();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
function rfc822(?string $isoDate): string
|
|
||||||
{
|
|
||||||
try {
|
|
||||||
$dt = $isoDate ? new DateTime($isoDate) : new DateTime('now', new DateTimeZone('UTC'));
|
|
||||||
} catch (Exception $e) {
|
|
||||||
$dt = new DateTime('now', new DateTimeZone('UTC'));
|
|
||||||
}
|
|
||||||
return $dt->format(DateTime::RSS);
|
|
||||||
}
|
|
||||||
|
|
||||||
function xml_escape(string $text): string
|
|
||||||
{
|
|
||||||
return htmlspecialchars($text, ENT_XML1 | ENT_QUOTES, 'UTF-8');
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Construit un flux RSS 2.0 complet a partir d'une liste d'items deja
|
|
||||||
* formates (chacun un tableau title/link/guid/pubDate/description).
|
|
||||||
* $selfUrl est l'URL du flux lui-meme (atom:link rel="self", recommande
|
|
||||||
* par le validateur W3C).
|
|
||||||
*/
|
|
||||||
function build_rss(string $title, string $link, string $description, array $items, string $selfUrl): string
|
|
||||||
{
|
|
||||||
$now = rfc822(null);
|
|
||||||
$xml = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
|
|
||||||
$xml .= '<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom">' . "\n <channel>\n";
|
|
||||||
$xml .= ' <title>' . xml_escape($title) . "</title>\n";
|
|
||||||
$xml .= ' <link>' . xml_escape($link) . "</link>\n";
|
|
||||||
$xml .= ' <atom:link href="' . xml_escape($selfUrl) . '" rel="self" type="application/rss+xml" />' . "\n";
|
|
||||||
$xml .= ' <description>' . xml_escape($description) . "</description>\n";
|
|
||||||
$xml .= " <language>fr-be</language>\n";
|
|
||||||
$xml .= " <lastBuildDate>$now</lastBuildDate>\n";
|
|
||||||
|
|
||||||
foreach ($items as $item) {
|
|
||||||
$xml .= " <item>\n";
|
|
||||||
$xml .= ' <title>' . xml_escape($item['title']) . "</title>\n";
|
|
||||||
$xml .= ' <link>' . xml_escape($item['link']) . "</link>\n";
|
|
||||||
$xml .= ' <guid isPermaLink="false">' . xml_escape($item['guid']) . "</guid>\n";
|
|
||||||
$xml .= ' <pubDate>' . rfc822($item['pubDate'] ?? null) . "</pubDate>\n";
|
|
||||||
$xml .= ' <description>' . xml_escape($item['description']) . "</description>\n";
|
|
||||||
$xml .= " </item>\n";
|
|
||||||
}
|
|
||||||
|
|
||||||
$xml .= " </channel>\n</rss>\n";
|
|
||||||
return $xml;
|
|
||||||
}
|
|
||||||
Reference in new issue
Block a user