Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ All notable changes are listed here. The format follows [Keep a Changelog](https
- Revalidation: signed notifications of changes (posts, terms, menus, site options, files) to the front end, merged, off the request (Action Scheduler or WP-Cron), with retries; `wp headless revalidate ping`.
- Site manifest: `GET /wp-json/headless/v1/site` (site, languages, menus as trees, locations, front page, content types and taxonomies).
- Redirects: rules managed with `wp headless redirect`, the old slugs of renamed posts, `GET /wp-json/headless/v1/redirects` and `/redirects/resolve`.
- Media: `GET /wp-json/headless/v1/media/{id}` (one shape for every kind, with the focal point of `pollora/media`), the `headless_featured_media` field, and `media.cdn_url` to serve the uploads from a CDN.
- mu-plugin loader (`stubs/pollora-headless.php`) and a Pollora service provider discovered by Composer.
16 changes: 16 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ It works on a classic WordPress, on Bedrock and inside a [Pollora](https://pollo
| Revalidation | When a post is published, updated, unpublished or deleted, or a term, a menu, a site option or a file changes, the front end is told: one signed POST, merged with the other changes of the last seconds, sent off the request, tried again if it fails. See [Revalidation](#telling-your-front-end-what-changed). |
| Site manifest | `GET /wp-json/headless/v1/site`: the site and its languages, the menus as trees with front-end paths, the menu locations, the front page and the content types with their REST routes, in one public, cacheable answer. |
| Redirects | The redirects of the site for a front end: the ones you manage (`wp headless redirect add /old/ /new/`, patterns, 410 for a page that is gone) and the old addresses WordPress remembers for renamed posts, at `GET /wp-json/headless/v1/redirects` (every rule) and `/redirects/resolve?path=/old/` (one path). |
| Media | A file of the library in one shape whatever its kind (`GET /wp-json/headless/v1/media/{id}`: url, sizes, srcset, alt, caption, the focal point set with `pollora/media`), the featured image of a post in full without a second request, and the uploads served from a CDN. |
| URL mapper | `UrlMapper::toFront()` turns a URL of the WordPress site into the URL of the same page on the front end. It is the one place every URL the package hands out goes through. |

Nothing changes on the public site until you set the front-end URL: a site that is not told where its front end lives is never locked.
Expand Down Expand Up @@ -172,6 +173,21 @@ const { redirect } = await (await fetch(`https://cms.example.com/wp-json/headles

An exact rule wins over a pattern, and the rules you write win over the old slugs. A rule is checked when it is made (a path, a destination that is a path or an absolute http(s) URL, a status of 301, 302, 307, 308 or 410, a pattern that compiles, no loop). Changing the rules is announced to the front end with the `option:headless_redirects` tag.

## Media

```js
const image = await (await fetch('https://cms.example.com/wp-json/headless/v1/media/42')).json();
// { id, kind: 'image', mime, url, title, alt, caption, description, width, height, filesize, duration,
// focal_point: { x: 0.25, y: 0.75 } | null, sizes: { medium: { url, width, height }, …, full: {…} }, srcset, modified_gmt }

// The featured image of a post, in the same request (a field that costs something is computed only when you name it)
const post = await (await fetch('https://cms.example.com/wp-json/wp/v2/posts/12?_fields=id,title,headless_featured_media')).json();
```

`focal_point` is the part of the image to keep whatever the crop (use it as `object-position: 25% 75%`); it comes from [`pollora/media`](https://github.com/Pollora/media) and is `null` without it. A file attached to a draft answers 404 to a visitor.

To serve the uploads from a CDN or an image proxy, set `media.cdn_url` (or `HEADLESS_MEDIA_CDN_URL` on Pollora): `https://cdn.example.com` replaces `https://cms.example.com/wp-content/uploads` in the address of every file, in `srcset` and in the HTML of the content. The administration keeps the WordPress addresses, so that an editor sees a file they have just uploaded.

## Roadmap

`0.1` core · `0.2` CORS, REST security and speed, URL mapping, Polylang and WPML, API tokens · `0.3` content preview · `0.4` revalidation webhooks (this release) · `0.5` site manifest, media, blocks as JSON, redirects · `0.6` SEO (Yoast, Rank Math, AIOSEO, SEOPress, The SEO Framework) · `0.7` optional WPGraphQL, schema snapshots, forms and search · `0.8` doctor, end-to-end tests · `1.0` frozen contract.
Expand Down
3 changes: 2 additions & 1 deletion api-surface.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"surface": {
"config:headless": "unreadable without the application",
"hook:pollora/headless/flush": "hook",
"hook:pollora/headless/retry": "hook"
"hook:pollora/headless/retry": "hook",
"hook:pollora/media/focal_point": "filter"
}
}
9 changes: 9 additions & 0 deletions config/headless.php
Original file line number Diff line number Diff line change
Expand Up @@ -129,4 +129,13 @@
'enabled' => true,
'old_slugs' => true,
],

// GET /wp-json/headless/v1/media/{id}: a file in one shape (url, sizes, srcset, alt, focal point from pollora/media…), and the
// field `headless_featured_media` of a post when _fields asks for it. `cdn_url` serves the uploads from a CDN or an image proxy:
// https://cdn.example.com replaces https://cms.example.com/wp-content/uploads in the addresses of files, in srcset and in the content
// (not in the administration). The routes are active once a front-end URL is set; the CDN once its address is.
'media' => [
'enabled' => true,
'cdn_url' => env('HEADLESS_MEDIA_CDN_URL', ''),
],
];
37 changes: 37 additions & 0 deletions src/Domain/Media/FocalPoint.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Media;

/**
* The part of an image an editor wants kept whatever the crop: `x` and `y`, fractions of the original from 0 to 1.
*/
final readonly class FocalPoint
{
public function __construct(
public float $x,
public float $y,
) {}

/** Reads what is stored (`['x' => 0.25, 'y' => 0.75]`); anything else is no point. */
public static function tryFrom(mixed $stored): ?self
{
if (! is_array($stored) || ! is_numeric($stored['x'] ?? null) || ! is_numeric($stored['y'] ?? null)) {
return null;
}

$x = (float) $stored['x'];
$y = (float) $stored['y'];

return $x >= 0.0 && $x <= 1.0 && $y >= 0.0 && $y <= 1.0 ? new self($x, $y) : null;
}

/**
* @return array{x: float, y: float}
*/
public function toArray(): array
{
return ['x' => $this->x, 'y' => $this->y];
}
}
16 changes: 16 additions & 0 deletions src/Domain/Media/MediaCatalog.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Media;

/**
* Where the files of the media library are read in their normalised shape.
*/
interface MediaCatalog
{
/**
* @return array<string, mixed>|null null when there is no such file, or the visitor may not see it
*/
public function for(int $id): ?array;
}
26 changes: 26 additions & 0 deletions src/Domain/Media/MediaKind.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Media;

/**
* What a front end does with a file: shows it as an image, plays it, or links to it.
*/
enum MediaKind: string
{
case Image = 'image';
case Video = 'video';
case Audio = 'audio';
case File = 'file';

public static function fromMime(string $mime): self
{
return match (strtolower(strstr($mime, '/', true) ?: '')) {
'image' => self::Image,
'video' => self::Video,
'audio' => self::Audio,
default => self::File,
};
}
}
54 changes: 54 additions & 0 deletions src/Domain/Media/MediaUrls.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Domain\Media;

/**
* Moves the address of an uploaded file from the WordPress host to a CDN (or an image proxy) that serves the
* `uploads` directory: `https://cms.example.com/wp-content/uploads/a.jpg` becomes `https://cdn.example.com/a.jpg`
* when the CDN's root is the uploads directory, or `https://cdn.example.com/uploads/a.jpg` when it mirrors the site.
*
* Only the start of an address is replaced, whatever its scheme: a file anywhere else is left alone.
*/
final readonly class MediaUrls
{
private string $uploads;

private string $cdn;

/**
* @param string $uploadsBase the uploads directory's address, such as https://cms.example.com/wp-content/uploads
* @param string $cdnBase where the same files are served, such as https://cdn.example.com
*/
public function __construct(string $uploadsBase, string $cdnBase)
{
$this->uploads = rtrim((string) preg_replace('#\Ahttps?:#i', '', $uploadsBase), '/');
$this->cdn = rtrim($cdnBase, '/');
}

public function toCdn(string $url): string
{
$bare = (string) preg_replace('#\Ahttps?:#i', '', $url);

if ($this->uploads === '' || ($bare !== $this->uploads && ! str_starts_with($bare, $this->uploads.'/'))) {
return $url;
}

return $this->cdn.substr($bare, strlen($this->uploads));
}

/** Every address of an uploaded file in a piece of HTML (an image, a link, a source set). */
public function rewriteHtml(string $html): string
{
if ($this->uploads === '' || ! str_contains($html, ltrim($this->uploads, '/'))) {
return $html;
}

return (string) preg_replace_callback(
'#https?:'.preg_quote($this->uploads, '#').'(?=[/"\'\s,?]|\z)#i',
fn (): string => $this->cdn,
$html,
);
}
}
23 changes: 23 additions & 0 deletions src/Infrastructure/Config/Settings.php
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,8 @@ private function __construct(
public bool $manifest,
public bool $redirects,
public bool $oldSlugRedirects,
public bool $mediaRoutes,
public ?string $mediaCdn,
) {}

/**
Expand All @@ -73,6 +75,7 @@ public static function fromArray(array $config, string $backendUrl): self
$backend = Origin::fromUrl($backendUrl);
$preview = is_array($config['preview'] ?? null) ? $config['preview'] : [];
$revalidation = is_array($config['revalidation'] ?? null) ? $config['revalidation'] : [];
$media = is_array($config['media'] ?? null) ? $config['media'] : [];
$frontUrl = self::string($config, 'frontend_url');
$front = $frontUrl === '' ? null : Origin::fromUrl($frontUrl);

Expand Down Expand Up @@ -122,6 +125,8 @@ public static function fromArray(array $config, string $backendUrl): self
manifest: $front instanceof Origin && self::bool(is_array($config['manifest'] ?? null) ? $config['manifest'] : [], 'enabled', true),
redirects: $front instanceof Origin && self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'enabled', true),
oldSlugRedirects: self::bool(is_array($config['redirects'] ?? null) ? $config['redirects'] : [], 'old_slugs', true),
mediaRoutes: $front instanceof Origin && self::bool($media, 'enabled', true),
mediaCdn: self::mediaCdn($media),
);
}

Expand Down Expand Up @@ -249,6 +254,24 @@ private static function targets(array $config): array
return $targets;
}

/**
* The address the CDN serves the uploads from, without its trailing slash; null when there is none.
*
* @param array<string, mixed> $config
*/
private static function mediaCdn(array $config): ?string
{
$url = rtrim(self::string($config, 'cdn_url'), '/');

if ($url === '') {
return null;
}

Origin::fromUrl($url);

return $url;
}

private static function mode(string $value, bool $hasFront): FrontMode
{
if ($value === '') {
Expand Down
9 changes: 9 additions & 0 deletions src/Infrastructure/WordPress/Bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
use Pollora\Headless\Domain\Front\UrlMapper;
use Pollora\Headless\Domain\Language\Languages;
use Pollora\Headless\Domain\Language\LanguageUrls;
use Pollora\Headless\Domain\Media\MediaUrls;
use Pollora\Headless\Infrastructure\Config\Settings;
use Pollora\Headless\Infrastructure\Config\SettingsLoader;
use Pollora\Headless\Infrastructure\Language\LanguagesFactory;
Expand Down Expand Up @@ -108,6 +109,14 @@ public static function modules(Settings $settings, ?Languages $languages = null)
$modules[] = new RedirectRoutes(new RedirectCatalog([new OptionRedirectStore, ...($settings->oldSlugRedirects ? [new OldSlugRedirects($urls)] : [])]));
}

if ($settings->mediaRoutes) {
$modules[] = new MediaRoutes(new NormalizedMedia);
}

if ($settings->mediaCdn !== null) {
$modules[] = new MediaCdn(new MediaUrls((string) (wp_upload_dir(null, false)['baseurl'] ?? ''), $settings->mediaCdn));
}

if ($settings->restCache instanceof RestCachePolicy || $settings->perPageMax !== null) {
$modules[] = new RestPerformance($settings->restCache, $settings->perPageMax);
}
Expand Down
49 changes: 49 additions & 0 deletions src/Infrastructure/WordPress/MediaCdn.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Infrastructure\WordPress;

use Pollora\Headless\Domain\Media\MediaUrls;

/**
* Serves the uploaded files from a CDN: the address of a file, the sources of its `srcset` and the files named in
* a post's HTML are moved to the CDN. The administration keeps the WordPress addresses, so that an editor sees
* a file they have just uploaded before the CDN has fetched it.
*/
final readonly class MediaCdn implements Module
{
public function __construct(private MediaUrls $urls) {}

public function register(HookRegistrar $hooks): void
{
$hooks->addFilter('wp_get_attachment_url', [$this, 'url']);
$hooks->addFilter('wp_calculate_image_srcset', [$this, 'srcset']);
$hooks->addFilter('the_content', [$this, 'html'], 20);
}

public function url(mixed $url): mixed
{
return is_string($url) && ! is_admin() ? $this->urls->toCdn($url) : $url;
}

public function srcset(mixed $sources): mixed
{
if (! is_array($sources) || is_admin()) {
return $sources;
}

foreach ($sources as $width => $source) {
if (is_array($source) && is_string($source['url'] ?? null)) {
$sources[$width]['url'] = $this->urls->toCdn($source['url']);
}
}

return $sources;
}

public function html(mixed $html): mixed
{
return is_string($html) && ! is_admin() ? $this->urls->rewriteHtml($html) : $html;
}
}
73 changes: 73 additions & 0 deletions src/Infrastructure/WordPress/MediaRoutes.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,73 @@
<?php

declare(strict_types=1);

namespace Pollora\Headless\Infrastructure\WordPress;

use Pollora\Headless\Domain\Media\MediaCatalog;

/**
* Files of the media library in one shape (see NormalizedMedia):
*
* - `GET /wp-json/headless/v1/media/{id}`.
* - the field `headless_featured_media` of a post, when `_fields` asks for it: the featured image in full, with no second request.
*/
final readonly class MediaRoutes implements Module
{
public const string NAMESPACE = 'headless/v1';

public const string FIELD = 'headless_featured_media';

public function __construct(private MediaCatalog $media) {}

public function register(HookRegistrar $hooks): void
{
$hooks->addAction('rest_api_init', [$this, 'routes']);
}

public function routes(): void
{
register_rest_route(self::NAMESPACE, '/media/(?P<id>\d+)', [
'methods' => 'GET',
'callback' => [$this, 'show'],
// Public on purpose: a file a visitor can already see on the front end. A file attached to a post they may not read answers 404.
'permission_callback' => '__return_true',
'args' => ['id' => ['type' => 'integer', 'required' => true]],
]);

foreach (get_post_types(['show_in_rest' => true, 'public' => true]) as $type) {
if (post_type_supports($type, 'thumbnail')) {
register_rest_field($type, self::FIELD, [
'get_callback' => [$this, 'featured'],
'schema' => ['description' => 'The featured image in full (ask for it in _fields).', 'type' => ['object', 'null'], 'context' => ['view', 'edit']],
]);
}
}
}

/**
* @param \WP_REST_Request<array<string, mixed>> $request
*/
public function show(\WP_REST_Request $request): \WP_REST_Response|\WP_Error
{
$media = $this->media->for((int) $request->get_param('id'));

return $media === null ? new \WP_Error('media_not_found', 'No such file.', ['status' => 404]) : rest_ensure_response($media);
}

/**
* @param array<string, mixed> $post the post as the REST controller prepared it
* @param \WP_REST_Request<array<string, mixed>> $request
* @return array<string, mixed>|null
*/
public function featured(array $post, string $field, \WP_REST_Request $request): ?array
{
if (! OptInField::requested($request, self::FIELD)) {
return null;
}

$id = (int) get_post_thumbnail_id((int) ($post['id'] ?? 0));

return $id > 0 ? $this->media->for($id) : null;
}
}
Loading
Loading