The CAP and browser XSLT transition note describes our approach: a public URL identifies a resource; HTTP content negotiation selects CAP XML or RSS XML for software, or an HTML page for people. HTML is generated on the server so people can continue reading alerts as browsers retire their built-in XSLT support.
This technical note shows how to apply content negotiation to PHP CAP publishing systems, using CAP Editor as a detailed worked example. The approach applies equally to other PHP publishers: identify the alert or feed with a stable URL, select a representation from the HTTP request, and render HTML on the server when requested.
In the CAP Editor use case, Linux, NGINX and PHP serve the public resources while S3 remains the storage and preservation container. A small PHP component reads the requested published object and either returns its original XML bytes or transforms a copy into HTML. Other publishers can adapt the same serving boundary to local files, another object store or a database. The examples are newly written adaptation material for Eliot and other PHP CAP publishers; they contain no application credentials or private configuration. These are proposed routes and integration changes, not a claim that they are deployed.
Download the example bundle, including the complete processor, NGINX snippet, dependency manifest and two small XSLT stylesheets. The complete processor also appears at the end of this note.
A URL identifies an alert or feed
The Web connects resources through links. A resource can be an alert or a feed; the server supplies a representation of it, such as CAP XML, RSS XML or HTML. W3C’s Architecture of the World Wide Web separates identification, interaction and representation. HTTP’s resource model lets a URL identify something implemented by a file, a stored object or application logic.
For a CAP publisher, link to the alert. Software can request CAP XML from that address; a browser can request an HTML view of the same alert. HTTP content negotiation provides the selection mechanism. Storage layout and the PHP script that handles the request remain implementation choices behind that public interface.
A .xml URL can also identify a resource. Removing an extension alone establishes neither stable identity nor negotiation: the server’s documented behaviour does. The useful design discipline is to choose public names for the data and maintain them as implementation changes. Tim Berners-Lee’s Cool URIs don’t change explains why exposing software names and filesystem organisation makes that harder.
Own the public resource address
For the CAP Editor worked example, the existing URLs are valid storage and publication addresses, and will remain available:
- Feed:
https://cap-sources.s3.amazonaws.com/do-indomet-es/rss.xml - Alert:
https://cap-sources.s3.amazonaws.com/do-indomet-es/2026-11-07-08-57-17.xml
New canonical links use the publisher-controlled entry point https://cap.alert-hub.org/public:
| Resource | Canonical public URL | Object retained in S3 |
|---|---|---|
| Source feed | https://cap.alert-hub.org/public/do-indomet-es/rss | do-indomet-es/rss.xml |
| Individual alert | https://cap.alert-hub.org/public/do-indomet-es/2026-11-07-08-57-17 | do-indomet-es/2026-11-07-08-57-17.xml |
The source name stays do-indomet-es in both places. Here the existing alert basename is retained as an opaque resource name; it is not assumed to be CAP’s identifier. The server appends .xml to locate today’s storage object. That lookup is an implementation detail that can change behind the public URL.
Technical advice: keep public URLs independent of the provider.
Following the W3C guidance on URI persistence, use a domain you control and paths that describe the data. Publishing a storage provider’s technical address as the main public URL can accidentally bind clients, bookmarks and documentation to that implementation—as happened with our S3 links. A managed resource URL lets storage and serving software change without changing the address people use. Retain old URLs for compatibility and preservation; make new canonical links independent of the provider.
Keeping S3 objects is part of preservation, rather than a complete preservation plan: retention, accidental-deletion protection and restoration still need operational ownership. This migration does not delete objects, remove public S3 access or redirect old clients.
The HTTP contract
The worked example implements the standard HTTP negotiation mechanism with the following publication policy. Machine-first defaults, fixed-format suffixes and strict 406 responses are choices for this implementation; HTTP does not prescribe this exact policy. The unsuffixed routes offer two representations each:
| Request | Feed response | Alert response |
|---|---|---|
Accept: text/html | HTML listing | HTML alert |
Accept: application/rss+xml | Original RSS XML | 406 |
Accept: application/cap+xml | 406 | Original CAP XML |
Missing Accept, or Accept: */* | RSS XML | CAP XML |
Accept: application/json | 406 | 406 |
Use the Accept field’s quality values and specificity rules, including explicit q=0 exclusions. Equal positive quality uses machine-first server order. Thus a normal browser preferring text/html receives HTML; curl with its usual wildcard receives XML. An exact text/html;q=0 must remain excluded even when */*;q=1 is present. This example offers the two concrete media types above; it does not add application/xml or text/xml aliases.
For explicit downloads, /public/{source}/rss.xml always returns RSS XML and /public/{source}/{alert}.xml always returns CAP XML, regardless of Accept. These are fixed-format resource URLs, not physical public files. This suffix-first rule is deliberate: a browser following “Download CAP XML” must receive XML with its ordinary browser header.
Every response has Vary: Accept. The example starts with Cache-Control: no-store, avoiding mixed HTML/XML cache entries during rollout. If caching is later enabled, follow HTTP caching rules for selecting negotiated responses: test variant selection at every proxy/CDN and use validators specific to the representation, including stylesheet revisions for HTML. Preserve other Vary values when integrating with existing middleware. GET and HEAD share selection and status behaviour; HEAD sends no body. Other methods return 405.
How NGINX reaches PHP
NGINX translates a public path into internal PHP parameters:
/public/do-indomet-es/rss
→ xsltprocessor.php?feed=do-indomet-es
/public/do-indomet-es/2026-11-07-08-57-17
→ xsltprocessor.php?feed=do-indomet-es&alert=2026-11-07-08-57-17
feed identifies the source. An absent alert selects its RSS collection. An .xml suffix adds format=xml. PHP then reads exactly one S3 object. It does not list the bucket or scan alert history.
This is an internal rewrite, not a browser redirect. The browser keeps the canonical address; PHP-FPM executes the component and NGINX returns its response. The last flag asks NGINX to select the new PHP location. The trailing ? in each replacement discards incoming query parameters: a visitor cannot append ?feed=another-source&format=xml to override the path. The exact PHP location is internal, so direct requests to /xsltprocessor.php are rejected. See NGINX’s rewrite documentation.
Adapt these paths and the FPM socket inside the existing HTTPS virtual host; preserve its TLS and editor configuration:
# Inside the existing HTTPS server for cap.alert-hub.org.
# Place before conflicting regex locations. Paths/socket are deployment examples.
location ^~ /public/ {
rewrite "^/public/([a-z0-9][a-z0-9-]{0,63})/rss\.xml$" /xsltprocessor.php?feed=$1&format=xml? last;
rewrite "^/public/([a-z0-9][a-z0-9-]{0,63})/rss$" /xsltprocessor.php?feed=$1? last;
rewrite "^/public/([a-z0-9][a-z0-9-]{0,63})/([A-Za-z0-9][A-Za-z0-9_-]{0,127})\.xml$" /xsltprocessor.php?feed=$1&alert=$2&format=xml? last;
rewrite "^/public/([a-z0-9][a-z0-9-]{0,63})/([A-Za-z0-9][A-Za-z0-9_-]{0,127})$" /xsltprocessor.php?feed=$1&alert=$2? last;
return 404;
}
location = /xsltprocessor.php {
internal;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /srv/cap-publication/xsltprocessor.php;
fastcgi_pass unix:/run/php/cap-publication.sock;
fastcgi_read_timeout 15s;
}
/public is the namespace entry point; the snippet handles resource paths beneath it. Add a small index separately if an entry-page listing is wanted. Source names follow the illustrated lower-case pattern; extend and test it if the actual source inventory needs more characters. rss is reserved as the collection name.
Store the example under /srv/cap-publication, outside the editor’s document root. Its directory contains xsltprocessor.php, vendor/, and styles/{rss,cap}.xsl. The NGINX configuration fixes the script filename rather than constructing an executable path from user input. Test the full virtual host with nginx -t; check inherited PHP locations and proxy/cache rules before reloading it.
Why restrict the PHP entry point
The public alert and feed remain available to everyone. NGINX’s internal directive rejects direct requests to the implementation script, while allowing the rewrite to reach it. This gives the component one public entry path. It is an enforced routing rule; it does not authenticate readers or make the alerts confidential.
| Control | Reason for including it |
|---|---|
Fixed SCRIPT_FILENAME and exact PHP location | Requests choose an alert, never which PHP program to execute. This endpoint needs no generic script discovery or PATH_INFO splitting. |
| Discard original query arguments | The path determines source, alert and format. Appended parameters cannot silently replace those decisions. |
| Validate source-name and alert-name syntax again in PHP | A future configuration change must not turn a URL parameter into an arbitrary bucket key or filesystem path. This follows OWASP’s allowlist validation guidance. |
| Deployment-owned stylesheet mapping | A document can request an approved presentation without instructing the server to fetch arbitrary URLs or open arbitrary local files. This addresses the boundary described in OWASP’s SSRF guidance. |
| Read-only storage credentials and bounded workers | Limit the damage a compromised or overloaded publication component can cause. Keep publishing permissions in the editor’s own execution context. |
These are small examples of defence in depth: each control constrains a different input or capability. A framework router or another server configuration can provide equivalent controls; these particular rewrite expressions are not a prerequisite for content negotiation.
Why patching remains essential
Real incidents illustrate the boundaries. In October 2026, Red Hat documented PHP request-handling memory corruption, CVE-2026-109618 and CVE-2026-109619. Runtime request processing can fail before application checks provide protection; that advisory identifies patching as the comprehensive solution. Earlier, the Canadian Cyber Centre reported active exploitation of CVE-2024-4577 in March 2025. That vulnerability concerns Windows PHP-CGI, so it does not establish exposure in this Linux PHP-FPM deployment.
For the hosting stack used here, NGINX’s account of CVE-2019-11043 is an older, directly relevant lesson: PHP-FPM’s handling of PATH_INFO, combined with particular NGINX configurations, could permit command execution. Our fixed handler avoids that unnecessary path-splitting mechanism. Neither this choice nor internal is a general remedy for PHP vulnerabilities.
Operate a supported PHP branch with current vendor security updates, update Composer dependencies and restart or replace affected workers as the vendor advises. “PHP 8.2+” in this example describes language compatibility, not a security patch level. Check the actual FPM runtime and package advisory status; a command-line PHP version may describe a different installation.
Choose the PHP processor and its boundaries
Use PHP’s native XSL extension, whose XSLTProcessor uses libxslt and supports XSLT 1.0. It is a suitable first choice for existing browser-era XSLT 1.0. Test the actual stylesheets and extensions they use before adopting them. XSLT 2.0/3.0 requires another engine. See PHP’s XSL installation guide.
Install DOM and XSL in the PHP-FPM runtime, and add the two Composer dependencies alongside the editor’s existing dependencies:
composer require aws/aws-sdk-php symfony/http-foundation:^7.4
composer check-platform-reqs --no-dev
The bundle targets PHP 8.2 or later. HttpFoundation supplies the Accept parser without requiring a Symfony application; its component documentation explains standalone use. Commit the deployment’s resolved Composer lock file and install from it. Linux package names vary by distribution and PHP version. Windows development needs the corresponding DOM/XSL extensions and an equivalent route to the same script; IIS URL Rewrite or a development router replaces NGINX’s routing, while the PHP contract stays the same.
Use the AWS SDK’s normal credential chain, preferably a workload role with read-only access to the public publication namespace. Never copy editor credentials into this script, the NGINX snippet or a blog example. Drafts and restricted alerts must live outside the exposed key space. Source-name validation checks syntax; it does not establish publication permission.
Sources are data, not a PHP list
The example has no hard-coded source list. Because public source names and S3 prefixes are the same, it validates {source} and reads exactly {source}/rss.xml or {source}/{alert}.xml from the publication bucket. Publishing a new source’s objects makes its URLs available without editing PHP or NGINX. An absent object returns 404 when S3 reports NoSuchKey; storage permission failures remain operational errors. There is no bucket listing, full source-table read or per-request scan.
This simple design relies on a clear storage contract: every object reachable through these patterns is intentionally public. If a publisher mixes private and public sources in storage, first perform an exact lookup in its authoritative source registry, using an indexed query such as WHERE source_id = :source AND publication_enabled = true. Use its trusted bucket/prefix result; do not load all sources and filter in PHP. Integrate that lookup with the existing source-registration workflow, rather than maintaining another list in source code. The public-bucket example needs no new database or duplicate registry.
Choose reviewed, local, self-contained stylesheets, deployed with the component. Do not fetch the stylesheet named by an incoming xml-stylesheet processing instruction. XML parsing rejects DTDs, disables external resolution and avoids entity substitution. Stylesheet imports/includes are rejected; file/network access is denied through XSLT security preferences. No PHP functions are registered. Approved stylesheets must also be reviewed for extension features, generated scripts and links.
The bundled stylesheets escape text, use only constructed same-source navigation links, and require no scripts or network assets. The RSS renderer recognises the illustrated old S3 item links and produces canonical HTML links without modifying stored XML. The CAP renderer includes all CAP 1.2 information blocks and their fields, including instructions, status, message type, times and areas. It is a deliberately plain adaptation baseline; replace raw field labels with reviewed translations and refine mobile text wrapping, reading order and presentation before public rollout. It does not validate CAP, verify a signature or infer whether an alert is still active.
The PHP example bounds S3 reads and output size. Its post-transform size check is not a hard transformation memory or CPU limit. Use a dedicated FPM pool with bounded workers and memory, and an enforceable request_terminate_timeout (for example 10 seconds); fastcgi_read_timeout alone does not terminate PHP work. Tune limits against actual feeds. Keep display_errors=Off, log failures privately, and monitor 502s and transformation duration. A rendering failure returns an error rather than presenting a partial warning as successful HTML.
What changes for publisher selected stylesheets
An XML document can name its preferred stylesheet through a processing instruction in its prolog:
<?xml-stylesheet type="text/xsl" href="alert-style.xsl"?>
The W3C xml-stylesheet specification defines this association, including relative references and multiple stylesheet choices. Previously, a supporting browser could use that reference to produce the publisher’s intended presentation.
The PHP example changes that behaviour. XML responses preserve the original bytes, including the instruction. HTML responses ignore it and use the deployed cap.xsl or rss.xsl. Moving transformation to the server and replacing the publisher’s stylesheet are separate decisions. Content negotiation requires neither replacement nor the loss of publisher-selected presentation; the fixed local stylesheets keep this teaching implementation small and its execution boundary explicit. They can change labels, layout, maps and language-specific presentation compared with the publisher’s original view.
Retaining the publisher’s presentation choice
A production extension can honour the reference through an approved stylesheet registry:
- Read the document’s
xml-stylesheetinstructions from the parsed XML prolog. Parse their pseudo-attributes using the W3C rules; define which XSLT types, media and alternate choices the service supports, and reject ambiguous or unsupported selections. - Resolve
hrefagainst a trusted, recorded source-document URL. For an existing S3 document, that means its original S3 address; resolving a relative reference against the new/publicaddress could select a different resource. Keep the original CAP bytes unchanged. - Look up the resolved reference and source identity in a deployment-controlled registry. Each entry identifies an approved local stylesheet, its content hash, version and supported document kind. An XML URL selects an entry; it does not grant permission to fetch or execute arbitrary code.
- Obtain and review stylesheet bytes outside the public request path, through controlled retrieval or administrative upload. Bound retrieval, validate destinations and redirects, and block private-network access. Approve exact bytes; changed content at the same URL requires fresh review. Keep the parser, processor, output and worker limits described above. The current example rejects imports/includes; stylesheets needing dependencies require a reviewed, pinned dependency bundle and a restricted resolver design.
- Transform with the approved local copy. Define what happens when a reference is absent, unapproved or fails: a reviewed default renderer with a visible fallback notice, or an explicit error. Record the choice and monitor fallback use. Include the approved stylesheet version in any HTML cache key or validator.
This preserves the publisher’s stylesheet selection within an explicit trust boundary. The complete processor still uses fixed bundled stylesheets by default; the optional helper below supplies a small opt-in extension. Compare the resulting HTML with the publisher’s view across languages, instructions, areas, updates and cancellations; processor compatibility and safe HTML output still need review.
A small approved mapping example
The optional approved-stylesheet.php helper below selects a reviewed local copy or falls back to the bundled renderer. It uses xmlDocument() from the complete processor and Guzzle’s URI resolver. The bundle declares guzzlehttp/psr7 as a direct Composer dependency for this optional helper; add that dependency if adapting the helper separately.
This deliberately supports one prolog instruction, explicit XSLT type, simple screen/all media and no alternate stylesheet sets. Missing, malformed, unsupported or unapproved associations fall back. It is a conservative subset of the W3C association syntax; it does not reproduce every browser selection rule.
<?php
// Optional extension: load after vendor/autoload.php; uses the existing xmlDocument().
declare(strict_types=1);
use GuzzleHttp\Psr7\Uri;
use GuzzleHttp\Psr7\UriResolver;
function publicationStylesheet(
DOMDocument $doc, string $source, string $kind, string $sourceUrl, array $approved
): array {
$fallback = static function () use ($kind): array {
error_log('CAP publication: using bundled stylesheet');
$bytes = file_get_contents(__DIR__ . '/styles/' . ($kind === 'rss' ? 'rss' : 'cap') . '.xsl');
if ($bytes === false) throw new RuntimeException('Missing bundled stylesheet');
return ['xml' => $bytes, 'fallback' => true];
};
// Conservative subset: exactly one prolog association; no alternate/style sets.
$instructions = [];
foreach ($doc->childNodes as $node) {
if ($node instanceof DOMElement) break;
if ($node instanceof DOMProcessingInstruction && $node->target === 'xml-stylesheet') {
$instructions[] = $node;
}
}
if (count($instructions) !== 1) return $fallback();
try {
// Reuse the DTD-free, non-expanding parser; reject markup/unknown attributes.
$association = xmlDocument('<association ' . $instructions[0]->data . '/>')->documentElement;
if ($association->tagName !== 'association' || $association->hasChildNodes()) return $fallback();
foreach ($association->attributes as $attribute) {
if (!in_array($attribute->name, ['href', 'type', 'media', 'alternate'], true)) return $fallback();
}
if (!in_array($association->getAttribute('type'), ['text/xsl', 'application/xslt+xml'], true)
|| !in_array($association->getAttribute('media'), ['', 'all', 'screen'], true)
|| !in_array($association->getAttribute('alternate'), ['', 'no'], true)
|| $association->getAttribute('href') === '') return $fallback();
$uri = UriResolver::resolve(new Uri($sourceUrl), new Uri($association->getAttribute('href')));
// Resolution is string processing, not an HTTP fetch.
if ($uri->getScheme() !== 'https' || $uri->getUserInfo() !== '' || $uri->getFragment() !== '') return $fallback();
$entry = $approved[$source][$kind][(string) $uri] ?? null;
if (!is_array($entry)) return $fallback();
// Paths and hashes come only from deployment-owned configuration.
$directory = realpath(__DIR__ . '/styles/approved');
$path = realpath($entry['file']);
if ($directory === false || $path === false
|| !str_starts_with($path, $directory . DIRECTORY_SEPARATOR)) return $fallback();
$bytes = @file_get_contents($path);
if ($bytes === false || strlen($bytes) > 512 * 1024
|| !hash_equals($entry['sha256'], hash('sha256', $bytes))) return $fallback();
return ['xml' => $bytes, 'fallback' => false];
} catch (Throwable $e) {
return $fallback();
}
}
After reviewing a publisher stylesheet, copy it into styles/approved/ and record its SHA-256 hash during deployment. The runtime account must not be able to modify these files or the mapping. For example, a deployment-owned configuration file can return:
return [
'do-indomet-es' => ['cap' => [
'https://cap-sources.s3.amazonaws.com/do-indomet-es/alert-style.xsl' => [
'file' => __DIR__ . '/styles/approved/do-indomet-es-alert-v1.xsl',
'sha256' => 'REPLACE_WITH_THE_REVIEWED_FILE_SHA256',
],
]],
];
The placeholder is intentionally unusable: approve the actual stylesheet and supply its hash before enabling that entry. Add RSS entries under rss in the same structure. Bind each approval to the source and document kind; the existence of a public stylesheet URL alone establishes no approval. This small array illustrates stylesheet approval, not source registration: new sources already work with bundled rendering and need no approval entry. At production scale, keep approvals in a managed registry keyed by source, document kind and resolved stylesheet URL, and retrieve only the matching entry. Add or revise an approval when stylesheet bytes are reviewed, rather than editing PHP for each new feed.
To opt in, load the helper after the autoloader, then replace the complete processor’s fixed stylesheet selection and file read with:
require_once __DIR__ . '/approved-stylesheet.php';
$approved = require __DIR__ . '/approved-stylesheets.php'; // Deployment-owned file.
$sourceUrl = 'https://cap-sources.s3.amazonaws.com/' . $key; // Trusted storage mapping.
$selection = publicationStylesheet($doc, $feed, $isFeed ? 'rss' : 'cap', $sourceUrl, $approved);
$style = $selection['xml'];
if ($selection['fallback']) {
header('X-CAP-Stylesheet: bundled-fallback');
}
// Continue with xmlDocument($style), stylesheet checks and the restricted processor.
The helper checks the selected bytes against the recorded hash before returning them; it never dereferences the publisher URL. Keep the existing import/include restrictions, resource limits and output review. The fallback is logged and indicated in a response header; a public deployment should also show a brief notice in its HTML template when publisher presentation could not be used. A broken transformation still follows the complete processor’s explicit 502 error path; it is not silently retried as a successful fallback. Test approved relative/absolute references, wrong sources, missing files, changed hashes, multiple instructions and attempts to select local or private-network resources.
Preserving the instruction alone also does not preserve relative-link behaviour for XML clients: at a new document URL, clients can resolve href differently. Retain the original S3 URLs, and provide compatible stylesheet routes at the new origin where required. The NGINX snippet above does not add those routes. Test this separately from the server’s approved-registry lookup.
Applying the pattern to CAP Editor publication
Keep saving CAP alerts and rss.xml to the same S3 keys. Change the links produced by the publisher so new consumers encounter the managed resources. In CAP Editor, the relevant integration points are the public URL construction in makeRssItem() and feed metadata in makeRssHeadAndTail() in publish.php, together with configuration and other screens that advertise those URLs.
A small helper can centralise naming:
function publicAlertUrl(string $source, string $basename): string {
// Call only after source/basename validation; basename excludes .xml.
return 'https://cap.alert-hub.org/public/'
. rawurlencode($source) . '/' . rawurlencode($basename);
}
$feedUrl = 'https://cap.alert-hub.org/public/' . rawurlencode($source) . '/rss';
$alertUrl = publicAlertUrl($source, $basename);
Build RSS with DOM methods such as createTextNode() and setAttribute() so headline text and URLs are escaped correctly. In particular:
- Set RSS item
linkto the negotiated alert URL. Offer typed Atom alternate links for the alert’s canonical CAP representation and fixed.xmldownload where useful. - Set the channel
linkto the negotiated feed URL. Set Atomrel="self", withtype="application/rss+xml", to the fixed feed URL ending/rss.xml. - Preserve existing item GUID values and CAP identity. If a GUID is an opaque CAP identifier, mark
isPermaLink="false"; never replace it with the new presentation URL. Check consumer deduplication before changing existing GUID metadata. - Update editor success pages, copy/share links, source configuration and subscription documentation to advertise the canonical URLs. Retain old S3 addresses and stored alerts.
Do not parse and reserialise CAP for the XML response or edit signed CAP to change a presentation link. Return its original bytes. HTML is a separate derived representation and carries no claim of the CAP signature. Existing stylesheet processing instructions can remain in preserved documents; the new endpoint performs HTML transformation explicitly on the server.
The processor returns stored RSS unchanged, too. Older feeds may therefore still contain S3 item links until the publisher regenerates them with the revised URL helper. Their HTML listing receives managed-domain links through the bundled RSS stylesheet. Test both paths rather than assuming that putting PHP in front of storage updates XML feed contents automatically.
Verify before advertising the new URLs
Against the staged service, request the same alert as both formats:
URL=https://cap.alert-hub.org/public/do-indomet-es/2026-11-07-08-57-17
curl -i -H 'Accept: text/html' "$URL"
curl -i -H 'Accept: application/cap+xml' "$URL"
curl -i -H 'Accept: */*' "$URL"
curl -i -H 'Accept: application/json' "$URL"
curl -i -H 'Accept: text/html;q=0, */*;q=1' "$URL"
curl -i -H 'Accept: application/cap+xml;q=0, */*;q=1' "$URL"
curl -i -H 'Accept: text/html' "$URL.xml"
curl -I -H 'Accept: text/html' "$URL"
Repeat for /public/do-indomet-es/rss using application/rss+xml. Check weighted preferences, missing headers, unsupported parameterised types, all-supported-types excluded, unknown sources, absent objects, rejected traversal, query override attempts, methods, and storage/render failures. Compare downloaded CAP bytes with the S3 object. With browser XSLT unavailable, check multilingual alerts, updates, cancellations, expired messages, multiple areas, empty feeds, and safe text containing markup. Follow item links from the RSS XML as well as from the HTML listing. Confirm existing S3 URLs still work.
Complete PHP processor example
The download bundle includes this processor and the required RSS stylesheet, CAP stylesheet, NGINX snippet and Composer manifest. Adapt the public-storage boundary, source-name syntax, deployment paths, workload permissions and reviewed presentation to your installation.
<?php
// Teaching implementation: PHP 8.2+, ext-dom, ext-xsl, Composer dependencies.
declare(strict_types=1);
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
use Symfony\Component\HttpFoundation\AcceptHeader;
require __DIR__ . '/vendor/autoload.php';
const ORIGIN = 'https://cap.alert-hub.org/public';
const MAX_XML = 2 * 1024 * 1024;
const MAX_HTML = 4 * 1024 * 1024;
function stop(int $status, string $message): never {
http_response_code($status);
header('Content-Type: text/plain; charset=utf-8');
if (($_SERVER['REQUEST_METHOD'] ?? 'GET') !== 'HEAD') echo $message . "\n";
exit;
}
function xmlDocument(string $bytes): DOMDocument {
$doc = new DOMDocument();
// Do not enable entity substitution, DTD loading, XInclude or PARSEHUGE.
$doc->resolveExternals = false;
$doc->substituteEntities = false;
$previous = libxml_use_internal_errors(true);
try {
if (!$doc->loadXML($bytes, LIBXML_NONET) || $doc->doctype !== null) {
throw new RuntimeException('Invalid XML or prohibited DTD');
}
} finally {
libxml_clear_errors();
libxml_use_internal_errors($previous);
}
return $doc;
}
header('Vary: Accept'); // This standalone endpoint owns Vary; merge in middleware if needed.
header('Cache-Control: no-store'); // Enable shared caching only after variant tests.
header('X-Content-Type-Options: nosniff');
header("Content-Security-Policy: default-src 'none'; base-uri 'none'; frame-ancestors 'none'; form-action 'none'");
$method = $_SERVER['REQUEST_METHOD'] ?? 'GET';
if (!in_array($method, ['GET', 'HEAD'], true)) {
header('Allow: GET, HEAD');
stop(405, 'Use GET or HEAD');
}
// All exposed objects must be published/public. Source names are storage prefixes.
// No per-source code/configuration list: publication creates the resource.
$feed = $_GET['feed'] ?? '';
$alert = $_GET['alert'] ?? '';
$format = $_GET['format'] ?? '';
if (!is_string($feed) || !preg_match('/\A[a-z0-9][a-z0-9-]{0,63}\z/D', $feed) || !is_string($alert)
|| !is_string($format) || !in_array($format, ['', 'xml'], true)) {
stop(404, 'Unknown resource');
}
$isFeed = $alert === '';
// Reserve rss for the collection. The resource name is opaque, not a CAP identifier.
if (!$isFeed && (!preg_match('/\A[A-Za-z0-9][A-Za-z0-9_-]{0,127}\z/D', $alert)
|| $alert === 'rss')) stop(404, 'Unknown resource');
$machineType = $isFeed ? 'application/rss+xml' : 'application/cap+xml';
$type = $machineType;
if ($format !== 'xml') {
$raw = $_SERVER['HTTP_ACCEPT'] ?? '*/*';
if (strlen($raw) > 8192) stop(400, 'Accept header too long');
$accept = AcceptHeader::fromString($raw);
$type = '';
$best = 0.0;
// Machine first is the documented tie-break. Exact q=0 overrides wildcards.
foreach ([$machineType, 'text/html'] as $candidate) {
$q = $accept->get($candidate)?->getQuality() ?? 0.0;
if ($q > $best) { $best = $q; $type = $candidate; }
}
if ($type === '') stop(406, 'Available: ' . $machineType . ', text/html');
}
$canonical = ORIGIN . '/' . rawurlencode($feed) . '/' . ($isFeed ? 'rss' : rawurlencode($alert));
$key = $feed . '/' . ($isFeed ? 'rss.xml' : $alert . '.xml');
try {
// Use an instance/workload role or the SDK default credential chain; no keys here.
$s3 = new S3Client([
'version' => 'latest',
'region' => getenv('AWS_REGION') ?: 'eu-west-1',
'http' => ['connect_timeout' => 2, 'timeout' => 8],
'retries' => 1,
]);
// One exact object, streamed and bounded. No bucket listing or history scan.
$result = $s3->getObject([
'Bucket' => 'cap-sources', 'Key' => $key,
'@http' => ['stream' => true],
]);
$stream = $result['Body'];
try {
$xml = '';
while (!$stream->eof()) {
$part = $stream->read(min(65536, MAX_XML + 1 - strlen($xml)));
if ($part === '' && !$stream->eof()) throw new RuntimeException('Incomplete read');
$xml .= $part;
if (strlen($xml) > MAX_XML) throw new RuntimeException('XML exceeds limit');
}
} finally { $stream->close(); }
$body = $xml; // Preserve original CAP bytes, including any signature.
if ($type === 'text/html') {
$doc = xmlDocument($xml);
$root = $doc->documentElement;
if ($isFeed ? ($root?->tagName !== 'rss') :
($root?->localName !== 'alert' || $root?->namespaceURI !== 'urn:oasis:names:tc:emergency:cap:1.2')) {
throw new RuntimeException('Unexpected XML root');
}
// Only deployment-reviewed, self-contained local XSLT. Ignore xml-stylesheet PIs.
$style = file_get_contents(__DIR__ . '/styles/' . ($isFeed ? 'rss.xsl' : 'cap.xsl'));
if ($style === false) throw new RuntimeException('Missing stylesheet');
$styleDoc = xmlDocument($style);
$xp = new DOMXPath($styleDoc);
$xp->registerNamespace('xsl', 'http://www.w3.org/1999/XSL/Transform');
if ($xp->query('//xsl:include | //xsl:import')->length > 0) {
throw new RuntimeException('Stylesheet must be self-contained');
}
$processor = new XSLTProcessor();
$processor->setSecurityPrefs(XSL_SECPREF_READ_FILE | XSL_SECPREF_WRITE_FILE
| XSL_SECPREF_CREATE_DIRECTORY | XSL_SECPREF_READ_NETWORK | XSL_SECPREF_WRITE_NETWORK);
// Never call registerPHPFunctions(). These stylesheets need no extensions.
if (!$processor->importStylesheet($styleDoc)) throw new RuntimeException('Invalid stylesheet');
$processor->setParameter('', 'canonical', $canonical);
$processor->setParameter('', 'download', $canonical . '.xml');
$processor->setParameter('', 'feedBase', ORIGIN . '/' . rawurlencode($feed) . '/');
$processor->setParameter('', 'storageBase', 'https://cap-sources.s3.amazonaws.com/' . rawurlencode($feed) . '/');
$body = $processor->transformToXML($doc);
if ($body === false || strlen($body) > MAX_HTML) throw new RuntimeException('Rendering failed');
}
header('Content-Type: ' . $type . ($type === 'text/html' ? '; charset=utf-8' : ''));
header('Link: <' . $canonical . '>; rel="canonical", <' . $canonical
. '.xml>; rel="alternate"; type="' . $machineType . '"');
if ($method !== 'HEAD') echo $body;
} catch (S3Exception $e) {
if ($e->getAwsErrorCode() === 'NoSuchKey') stop(404, 'Resource not found');
// Do not expose SDK messages, signed requests or configuration to the visitor.
error_log('CAP publication storage failure');
stop(502, 'Publication storage unavailable');
} catch (Throwable $e) {
error_log('CAP publication rendering or retrieval failure');
stop(502, 'Publication temporarily unavailable');
}