Skip to content
Open
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
19 changes: 16 additions & 3 deletions .github/workflows/release.yml
Original file line number Diff line number Diff line change
Expand Up @@ -5,20 +5,33 @@ on:
tags: ['v*']

permissions:
contents: write
contents: read

jobs:
tests:
uses: ./.github/workflows/tests.yml

release:
needs: tests
runs-on: ubuntu-latest

permissions:
contents: write

steps:
- uses: actions/checkout@v4
with:
fetch-depth: 0

- name: Check the tag is on main
run: git merge-base --is-ancestor "$GITHUB_SHA" origin/main

- name: Check the tag matches the plugin's version
run: grep -Fxq " * Version: ${GITHUB_REF_NAME#v}" altimiser.php
run: |
grep -Fxq " * Version: ${GITHUB_REF_NAME#v}" altimiser.php

- name: Build the zip
run: git archive --prefix=altimiser/ -o altimiser.zip HEAD altimiser.php src README.md
run: git archive --prefix=altimiser/ -o altimiser.zip HEAD altimiser.php uninstall.php src README.md

- name: Publish the release
run: gh release create "$GITHUB_REF_NAME" altimiser.zip --generate-notes
Expand Down
7 changes: 7 additions & 0 deletions .github/workflows/tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ on:
push:
branches: [main]
pull_request:
workflow_call:

permissions:
contents: read
Expand All @@ -21,6 +22,11 @@ jobs:
matrix:
php: ['8.1', '8.2', '8.3', '8.4']
wordpress: ['6.8.*', '*']
yoast: ['*']
include:
- php: '8.1'
wordpress: '6.8.*'
yoast: '24.0'

services:
mysql:
Expand Down Expand Up @@ -51,6 +57,7 @@ jobs:
composer require --dev --no-interaction --no-progress --prefer-dist --with-all-dependencies
"roots/wordpress:${{ matrix.wordpress }}"
"wp-phpunit/wp-phpunit:${{ matrix.wordpress }}"
"wpackagist-plugin/wordpress-seo:${{ matrix.yoast }}"

- name: Run tests
run: vendor/bin/phpunit
103 changes: 69 additions & 34 deletions README.md

Large diffs are not rendered by default.

31 changes: 20 additions & 11 deletions altimiser.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,37 +10,46 @@
* Author: Alt Design
* Author URI: https://alt-design.net
* Update URI: https://github.com/alt-design/altimiser-wordpress
* Text Domain: altimiser
*/

use AltDesign\Altimiser\ConnectionFlow;
use AltDesign\Altimiser\ControlPanel;
use AltDesign\Altimiser\Receiver;
use AltDesign\Altimiser\ReviewQueuePage;
use AltDesign\Altimiser\Settings;
use AltDesign\Altimiser\SettingsPage;
use AltDesign\Altimiser\Updater;
use AltDesign\Altimiser\Yoast;

defined('ABSPATH') || exit;

require_once __DIR__.'/src/ChangeDispatcher.php';
require_once __DIR__.'/src/ChangeRequest.php';
require_once __DIR__.'/src/ChangeResult.php';
require_once __DIR__.'/src/ContentResolver.php';
require_once __DIR__.'/src/ControlPanel.php';
require_once __DIR__.'/src/PageCache.php';
require_once __DIR__.'/src/Receiver.php';
require_once __DIR__.'/src/ReviewQueuePage.php';
require_once __DIR__.'/src/Updater.php';
require_once __DIR__.'/src/Yoast.php';
require_once __DIR__.'/src/YoastApplier.php';
spl_autoload_register(static function (string $class): void {
$namespace = 'AltDesign\\Altimiser\\';
$file = __DIR__.'/src/'.str_replace('\\', '/', substr($class, strlen($namespace))).'.php';

if (str_starts_with($class, $namespace) && is_file($file)) {
require $file;
}
});

add_action('rest_api_init', static function (): void {
(new Receiver(__FILE__, defined('WPSEO_VERSION') ? new Yoast() : null))->registerRoutes();
});

add_action('add_option_'.Settings::$option, [Settings::class, 'keepOutOfAutoload']);
add_action('update_option_'.Settings::$option, [Settings::class, 'keepOutOfAutoload']);

add_action('plugins_loaded', static function (): void {
if (is_admin()) {
(new SettingsPage())->register();
}

$controlPanel = ControlPanel::configured();

if ($controlPanel !== null) {
(new ReviewQueuePage($controlPanel))->register();
(new ConnectionFlow($controlPanel))->register();
}
});

Expand Down
20 changes: 20 additions & 0 deletions src/Applier.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
<?php

namespace AltDesign\Altimiser;

interface Applier
{
/**
* The checks advertised on /health, which is everything Altimiser will send.
*
* @return array<int, string>
*/
public function checks(): array;

public function supports(string $check): bool;

/**
* @return array<string, mixed>
*/
public function apply(ChangeRequest $change, bool $dryRun): array;
}
64 changes: 45 additions & 19 deletions src/ChangeDispatcher.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
class ChangeDispatcher
{
/**
* @param array<int, YoastApplier> $appliers
* @param array<int, Applier> $appliers
*/
public function __construct(private array $appliers, private PageCache $pageCache) {}

Expand All @@ -18,8 +18,9 @@ public function __construct(private array $appliers, private PageCache $pageCach
*
* The purge happens here and not at the end of the request because W3 Total Cache
* carries a flush out on the shutdown action, so one asked for later is not acted on.
* A change already in place purges too: the request that wrote it may have died before
* getting this far, and being sent the change again is the only chance left to do it.
* A change already in place purges its page too: the request that wrote it may have
* died before getting this far, and being sent the change again is the only chance
* left to do it.
*
* @param array<int, ChangeRequest> $changes
* @return array<int, array<string, mixed>>
Expand All @@ -31,23 +32,53 @@ public function dispatch(array $changes, bool $dryRun): array
$budget = $this->timeBudget();
$results = [];

$landed = [];

foreach ($changes as $change) {
if ($results !== [] && $this->outOfRoom(count($results), $batchSize, $startedAt, $budget)) {
$results[] = ChangeResult::deferred($change->id);

continue;
}

$results[] = $this->applyOne($change, $dryRun);
$result = $this->applyOne($change, $dryRun);
$results[] = $result;

if (in_array($result['status'], ['applied', 'already_applied'], true)) {
$landed[] = [$change->url, $result['location'] ?? []];
}
}

if (! $dryRun && array_intersect(['applied', 'already_applied'], array_column($results, 'status')) !== []) {
$this->pageCache->purge();
if (! $dryRun) {
$this->purge($landed);
}

return $results;
}

/**
* A change stored as a default shows on every page of its kind, so it clears the
* whole cache. Anything else clears the page it was made for.
*
* @param array<int, array{0: string, 1: array<string, mixed>}> $landed
*/
private function purge(array $landed): void
{
if ($landed === []) {
return;
}

foreach ($landed as [, $location]) {
if (($location['default'] ?? false) === true) {
$this->pageCache->purgeEverything();

return;
}
}

$this->pageCache->purge(array_column($landed, 0));
}

/**
* Half the limit, because a request killed mid-change leaves it unrecorded, and
* one change can take a while once it has been started.
Expand All @@ -66,31 +97,26 @@ private function outOfRoom(int $attempted, int $batchSize, float $startedAt, flo
}

/**
* Failed rather than skipped with no applier, because Altimiser withdraws the
* approval on a skip, and this one comes out differently once Yoast SEO is back.
*
* @return array<string, mixed>
*/
private function applyOne(ChangeRequest $change, bool $dryRun): array
{
if ($this->appliers === []) {
return ChangeResult::failed(
$change->id,
'seo_plugin_inactive',
'Yoast SEO is not active on this site, so nothing was attempted. The change stays approved for the next apply.',
);
}

foreach ($this->appliers as $applier) {
if (! $applier->supports($change->check)) {
continue;
}

try {
return $applier->apply($change, $dryRun);
$result = $applier->apply($change, $dryRun);
} catch (Throwable $exception) {
return ChangeResult::failed($change->id, 'write_failed', $exception->getMessage());
$result = ChangeResult::failed($change->id, 'write_failed', $exception->getMessage());
}

if (($result['reason'] ?? null) === 'write_failed') {
error_log("Altimiser could not apply {$change->check} to {$change->url}: {$result['message']}");
}

return $result;
}

return ChangeResult::skipped(
Expand Down
128 changes: 128 additions & 0 deletions src/ConnectionFlow.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,128 @@
<?php

namespace AltDesign\Altimiser;

/**
* Connects an editor's Altimiser account, through the authorisation code flow the
* protocol describes. Each step answers with the address to send the browser to next.
*/
class ConnectionFlow
{
public function __construct(private ControlPanel $panel) {}

public function register(): void
{
foreach (['connect' => 'start', 'connected' => 'finish', 'disconnect' => 'disconnect'] as $action => $step) {
add_action("admin_post_altimiser_{$action}", function () use ($step): void {
wp_redirect($this->{$step}());
exit;
});
}
}

public function start(): string
{
if (! $this->allowed('altimiser_connect')) {
return self::back('error', __('That link has expired. Try connecting again.', 'altimiser'));
}

if (! $this->panel->isOnSiteOrigin(self::callbackUrl())) {
return self::back('error', __('Connecting needs wp-admin to be on the same address as the site itself. Open wp-admin at the site\'s own address and try again.', 'altimiser'));
}

$state = wp_generate_password(40, false);

set_transient(self::stateKey(), $state, 10 * MINUTE_IN_SECONDS);

return $this->panel->connectUrl($state, self::callbackUrl(), wp_get_current_user()->user_email, time() + 5 * MINUTE_IN_SECONDS);
}

public function finish(): string
{
$expected = get_transient(self::stateKey());
$state = self::query('state');

delete_transient(self::stateKey());

if (! current_user_can(ReviewQueuePage::$capability) || ! is_string($expected) || $state === null || ! hash_equals($expected, $state)) {
return self::back('error', __('That connection attempt could not be checked. Try connecting again.', 'altimiser'));
}

if (self::query('error') === 'access_denied') {
return self::back('error', __('Your Altimiser account was not connected. Either it was declined, or your account has not been given this site. Ask your agency if you expected it to be.', 'altimiser'));
}

$code = self::query('code');

if ($code === null) {
return self::back('error', __('Altimiser did not send back a code. Try connecting again.', 'altimiser'));
}

$connection = $this->panel->exchange($code, self::callbackUrl());

if (is_wp_error($connection)) {
/* translators: %s: Altimiser's reason, in English */
return self::back('error', sprintf(__('Your Altimiser account could not be connected: %s', 'altimiser'), $connection->get_error_message()));
}

Connections::put(get_current_user_id(), $connection);

return self::back('success', __('Your Altimiser account is connected.', 'altimiser'));
}

public function disconnect(): string
{
if (! $this->allowed('altimiser_disconnect')) {
return self::back('error', __('That link has expired. Try again.', 'altimiser'));
}

Connections::forget(get_current_user_id());

return self::back('success', __('Your Altimiser account is disconnected.', 'altimiser'));
}

/**
* The message the last step left for the review queue page, read once.
*
* @return ?array{level: string, message: string}
*/
public static function takeNotice(): ?array
{
$key = 'altimiser_notice_'.get_current_user_id();
$notice = get_transient($key);

delete_transient($key);

return is_array($notice) ? $notice : null;
}

private function allowed(string $action): bool
{
return current_user_can(ReviewQueuePage::$capability)
&& wp_verify_nonce(sanitize_text_field(wp_unslash($_REQUEST['_wpnonce'] ?? '')), $action) !== false;
}

private static function back(string $level, string $message): string
{
set_transient('altimiser_notice_'.get_current_user_id(), ['level' => $level, 'message' => $message], MINUTE_IN_SECONDS);

return admin_url('admin.php?page=altimiser');
}

private static function callbackUrl(): string
{
return admin_url('admin-post.php?action=altimiser_connected');
}

private static function stateKey(): string
{
return 'altimiser_connect_state_'.get_current_user_id();
}

private static function query(string $key): ?string
{
$value = $_GET[$key] ?? null;

return is_string($value) && $value !== '' ? sanitize_text_field(wp_unslash($value)) : null;
}
}
Loading
Loading