diff --git a/README.md b/README.md index 65f2677..6d8f13f 100644 --- a/README.md +++ b/README.md @@ -2,11 +2,11 @@ Connects a WordPress site to Altimiser. It implements Altimiser's receiver protocol, which is kept with Altimiser itself, and it is held to that document rather than to the [Statamic receiver](https://github.com/alt-design/altimiser-statamic), with which it shares no code. -It applies the changes Altimiser sends to titles, meta descriptions and Open Graph text, by writing to Yoast SEO's own fields. Without Yoast SEO active a site can still connect, but `GET /health` advertises none of those checks, Altimiser reports the gap as `receiver.no_seo_plugin`, and none of those fields is changed. +It applies the changes Altimiser sends to titles, meta descriptions and Open Graph text, by writing to Yoast SEO's own fields. It also writes image alt text, links a page to another it already names, and fixes robots.txt. Without Yoast SEO active a site can still connect and take those three, but `GET /health` advertises none of the Yoast checks, Altimiser reports the gap as `receiver.no_seo_plugin`, and no title, description or social text is changed. ## Requirements -WordPress 6.8 or newer, PHP 8.1 or newer, and Yoast SEO 24.0 or newer for titles, descriptions and Open Graph text. The tests run against Yoast SEO 24.0 as well as the latest release. The plugin has no runtime Composer dependencies, because vendor classes in a plugin can collide with another plugin's copies. +WordPress 6.8 or newer, PHP 8.1 or newer, and Yoast SEO 24.0 or newer for titles, descriptions and Open Graph text. The tests run against Yoast SEO 24.0 as well as the latest release. Advanced Custom Fields is optional: where it is active, links also go into its editor fields. The plugin has no runtime Composer dependencies, because vendor classes in a plugin can collide with another plugin's copies. ## Installing @@ -45,7 +45,7 @@ php artisan altimiser:connect https://example.com https://example.com/wp-json/al Use the address the site actually answers at, including `https` and any `www`. Altimiser follows redirects, which works for this `GET`, but a `POST` that gets redirected arrives as a `GET` and fails later on. -A successful connection shows the receiver as `wordpress` with the plugin's version and the WordPress version. Without Yoast SEO active a warning appears: "advertises no checks". +A successful connection shows the receiver as `wordpress` with the plugin's version and the WordPress version. Without Yoast SEO active, Altimiser raises `receiver.no_seo_plugin` on the next scan. Connect again after activating Yoast SEO, so Altimiser reads what the site can now apply. @@ -61,6 +61,29 @@ Connect again after activating Yoast SEO, so Altimiser reads what the site can n These are written to the post, page, custom post type or taxonomy term the URL belongs to, as long as its type has public pages. A shared template is never edited and a meta title is never written to `post_title`. +| Checks | Where it is written | +| --- | --- | +| `image.alt_missing`, `alt_empty`, `alt_too_long` | The image's alt text in the media library, and the page's own copy of it | +| `link.opportunity` | The first mention in the page's content, or in an ACF editor field | +| `site.robots_missing` | A new `robots.txt` at the root of the site | +| `sitemap.not_declared_in_robots` | The `robots.txt` file, or what WordPress prints at `/robots.txt` when there is no file | + +### Alt text + +WordPress keeps alt text in two places. The media library holds the image's own, which featured images, most themes and page builders print, and the editor copies it into a post when the image is inserted. From then on the post's copy is what that post shows. Each is written where it still holds what the scan saw, so wording an editor gave either one is left alone. A cover block keeps its alt text in the block's settings as well as its markup, and both are written, so the editor does not flag the block as broken. + +The image is found from the address the scan saw, which may be a resized copy, on a CDN, or of an image WordPress scaled down on upload. An image that is not in the media library, such as one in the theme, is refused as `no_match`. + +### Links + +The plugin turns the first mention of another page's heading into a link to it, adding no words. It reads the page's content first, then any ACF editor fields, including those inside groups, repeaters and flexible content. ACF text areas are left alone, because themes commonly escape them and the link would show as markup. Only a path on this site or an address on its own host is linked to. A mention inside a heading, code, a form control, a summary, an SVG, a script or a shortcode's settings is passed over, and the content is saved without WordPress's filtering of untrusted HTML, so embeds, scripts and forms on the page stay as they were. + +A revert takes the link off again and restores the words as they were. + +### robots.txt + +A missing `robots.txt` is created with no `Disallow` rules and the site's sitemap, Yoast SEO's where it makes one. A missing sitemap line is added to the file where there is one, and otherwise to what WordPress prints, through the `robots_txt` filter, which keeps the rules WordPress and other plugins print there. Neither is reverted. A site not at the root of its domain has no `robots.txt` of its own, so both are refused there. On a multisite network every site is served from one folder, so a file there would answer for all of them: no file is created or edited, and a sitemap goes only into what WordPress prints for that site. A site set to discourage search engines is not given a file that lets them in. The sitemap address has to be a single http or https address on the site's own host. + `canonical.missing` is left to a developer. Yoast SEO prints a canonical itself except on noindex pages, so a missing one points to something else on the site. A change is refused rather than guessed at, and the finding goes to a person: @@ -71,7 +94,13 @@ A change is refused rather than guessed at, and the finding goes to a person: | `ambiguous` | The page has no value of its own and its template does not produce what the scan saw. A renamed page does this, and so does a `wpseo_title` or `wpseo_metadesc` filter, so a site using those filters gets inherited values refused | | `not_found` | Nothing editable answers to the URL. This covers a blog home listing latest posts, post type and author archives, term pages on plain permalinks, a type with no pages of its own such as a menu item, and a page's address with a query on the end, such as a search or a campaign link | | `no_suggestion` | There is no replacement value, as with `og:image` | -| `no_field` | Yoast SEO has no text field for that tag | +| `no_field` | Yoast SEO has no text field for that tag, or the site has no `robots.txt` of its own to write, because it is not at the root of its domain or is on a multisite network | +| `search_discouraged` | The site is set to discourage search engines, so a `robots.txt` that lets them in was not written | +| `no_match` | The image is not in the media library | +| `already_linked` | The first mention to link already links somewhere else, which somebody chose | +| `mention_not_found` | The words to link are not in the page's content, usually because the theme prints them | +| `page_builder` | The page is built with Elementor, Beaver Builder, Divi, WPBakery, Avada, Oxygen, Bricks or SiteOrigin, or its content holds another builder's shortcodes. These keep the page in their own data or in shortcode settings, where an edit would be lost or break the layout. Alt text still goes into the media library, which they print | +| `invalid_change` | A link change arrived without the words to link or where to link them, or pointing off the site, or a sitemap address that is not on the site | If Yoast SEO is not active when one of its changes arrives, nothing is attempted and the change comes back as `failed` with the reason `seo_plugin_inactive`. That keeps its approval, so it goes out again on the next apply. @@ -81,7 +110,7 @@ Each request attempts up to 10 changes within 45 seconds and hands the rest back ## Page caches -A request that applies something, or finds it already in place, purges the pages it changed, once, during the request, after Yoast has rebuilt what the page prints. A dry run never does. +A request that applies something, or finds it already in place, purges the pages it changed, once, during the request, after Yoast has rebuilt what the page prints. Alt text written to the media library shows wherever the image does, so that clears the whole cache instead. A dry run never purges anything. | Plugin | What is purged | How it was checked | | --- | --- | --- | @@ -109,6 +138,8 @@ This is optional. Add Altimiser's address on **Settings > Altimiser**, or in `wp define('ALTIMISER_URL', 'https://altimiser.example.com'); ``` +The address has to start with `https://`, except for `localhost` or a `.test` address on a development machine. + Each editor connects their own Altimiser account once, from that page. **Connect** opens Altimiser, which asks them to sign in and to approve the connection, then sends them back. Altimiser decides what they can do in the queue from their account, so an editor without an account, or whose account has not been given the site, gets no further than the **Connect** button. A connection lasts twelve hours for an agency account and thirty days for a client account, after which the page offers to connect again. **Disconnect** forgets it straight away. Connecting needs wp-admin to be on the same address as the site's URL. Once connected, the page shows the queue in a frame that fills the space beside the menu. Altimiser only allows framing by the origin of the site's URL, so the queue will not load for an admin served from another origin, or in a browser that refuses the frame. The frame's link is signed on the server with the site secret and with the editor's connection, and expires. Reloading the page gets a new one. @@ -142,7 +173,7 @@ To publish a release, change `Version` in `altimiser.php` on `main`, then push a ## Uninstalling -Deleting the plugin removes its settings, the counts it keeps and every editor's connection, on every site of a network. Changes it applied are the site's content by then, and stay. +Deleting the plugin removes its settings, the counts it keeps and every editor's connection, on every site of a network. Changes it applied are the site's content by then, and stay, except a sitemap declared in the `robots.txt` WordPress prints, which only the plugin printed. ## When the connection fails @@ -165,7 +196,7 @@ Two common security plugins need nothing doing. From reading their source, and n ## Testing -The tests run against a real WordPress, which Composer installs into `wordpress/`, and a real Yoast SEO from wpackagist, in `vendor/wp-plugins/`. They need MySQL as `root` with no password, at `127.0.0.1` unless `WP_TESTS_DB_HOST` says otherwise, in a database named `altimiser_wordpress_tests` unless `WP_TESTS_DB_NAME` says otherwise. +The tests run against a real WordPress, which Composer installs into `wordpress/`, and real Yoast SEO and Advanced Custom Fields from wpackagist, in `vendor/wp-plugins/`. They need MySQL as `root` with no password, at `127.0.0.1` unless `WP_TESTS_DB_HOST` says otherwise, in a database named `altimiser_wordpress_tests` unless `WP_TESTS_DB_NAME` says otherwise. ```bash composer install diff --git a/altimiser.php b/altimiser.php index a67303e..14eb11b 100644 --- a/altimiser.php +++ b/altimiser.php @@ -17,6 +17,7 @@ use AltDesign\Altimiser\ControlPanel; use AltDesign\Altimiser\Receiver; use AltDesign\Altimiser\ReviewQueuePage; +use AltDesign\Altimiser\RobotsApplier; use AltDesign\Altimiser\Settings; use AltDesign\Altimiser\SettingsPage; use AltDesign\Altimiser\Updater; @@ -39,6 +40,7 @@ add_action('add_option_'.Settings::$option, [Settings::class, 'keepOutOfAutoload']); add_action('update_option_'.Settings::$option, [Settings::class, 'keepOutOfAutoload']); +add_filter('robots_txt', [RobotsApplier::class, 'declareSitemap']); add_action('plugins_loaded', static function (): void { if (is_admin()) { diff --git a/composer.json b/composer.json index f9cae2c..b471bec 100644 --- a/composer.json +++ b/composer.json @@ -12,7 +12,8 @@ "wp-phpunit/wp-phpunit": ">=6.8", "yoast/phpunit-polyfills": "^2.0", "composer/installers": "^2.3", - "wpackagist-plugin/wordpress-seo": "*" + "wpackagist-plugin/wordpress-seo": "*", + "wpackagist-plugin/advanced-custom-fields": "*" }, "extra": { "wordpress-install-dir": "wordpress", diff --git a/src/AltTextApplier.php b/src/AltTextApplier.php new file mode 100644 index 0000000..f36188d --- /dev/null +++ b/src/AltTextApplier.php @@ -0,0 +1,202 @@ +checks(), true); + } + + public function apply(ChangeRequest $change, bool $dryRun): array + { + $suggested = trim($change->suggestedValue ?? ''); + + if ($suggested === '') { + return ChangeResult::skipped($change->id, 'no_suggestion', 'There is no alt text to write.'); + } + + $source = (string) ($change->target['match'] ?? ''); + $attachmentId = $this->attachment($source); + + if ($attachmentId === 0) { + return ChangeResult::skipped( + $change->id, + 'no_match', + "No image in the media library matches {$source}, so there is nowhere to keep its alt text. It may come from the theme or another site.", + ); + } + + $current = trim($change->currentValue ?? ''); + $stored = trim((string) get_post_meta($attachmentId, $this->metaKey, true)); + $post = $this->editablePost($change->url); + $copy = $post === null + ? ['html' => '', 'changed' => false, 'already' => false] + : $this->rewrite($post->post_content, $attachmentId, $source, $current, $suggested); + $writesLibrary = $stored === $current && $stored !== $suggested; + + if (! $writesLibrary && ! $copy['changed']) { + return $stored === $suggested || $copy['already'] + ? ChangeResult::alreadyApplied($change->id, $this->libraryLocation($attachmentId), 'This image already has this alt text.') + : ChangeResult::skipped( + $change->id, + 'value_changed', + "Neither the media library nor this page's copy of the image holds the alt text the scan saw, so somebody has changed it since.", + ); + } + + $location = $this->location($attachmentId, $writesLibrary, $copy['changed'] ? $post : null); + + if ($dryRun) { + return ChangeResult::applied($change->id, $location, $change->currentValue, $suggested); + } + + if ($writesLibrary && ! update_post_meta($attachmentId, $this->metaKey, wp_slash($suggested))) { + return ChangeResult::failed($change->id, 'write_failed', 'WordPress did not save the alt text in the media library.'); + } + + if ($copy['changed'] && ! $this->writer->updatePost($post->ID, ['post_content' => $copy['html']])) { + return ChangeResult::failed($change->id, 'write_failed', "WordPress did not save this page's copy of the image's alt text."); + } + + return ChangeResult::applied($change->id, $location, $change->currentValue, $suggested); + } + + private function editablePost(string $url): ?WP_Post + { + $post = $this->content->find($url); + + if (! $post instanceof WP_Post) { + return null; + } + + return $this->writer->pageBuilder($post->ID) === null ? $post : null; + } + + /** + * An image block's alt is read from its markup, but a cover block keeps its own + * in the block's attributes as well, and the editor flags the block as broken when + * the two disagree. + * + * @return array{html: string, changed: bool, already: bool} + */ + private function rewrite(string $html, int $attachmentId, string $source, string $current, string $suggested): array + { + $tags = new WP_HTML_Tag_Processor($html); + $sourcePath = $this->path($source); + $changed = false; + $already = false; + + while ($tags->next_tag('img')) { + if (! $tags->has_class("wp-image-{$attachmentId}") && $this->path((string) $tags->get_attribute('src')) !== $sourcePath) { + continue; + } + + $alt = $tags->get_attribute('alt'); + $alt = is_string($alt) ? trim($alt) : ''; + $already = $already || $alt === $suggested; + + if ($alt === $current && $alt !== $suggested) { + $tags->set_attribute('alt', $suggested); + $changed = true; + } + } + + $html = preg_replace_callback( + '//s', + static function (array $comment) use ($attachmentId, $current, $suggested, &$changed): string { + $attributes = json_decode($comment[1], true); + + if (! is_array($attributes) || ($attributes['id'] ?? null) !== $attachmentId || trim((string) ($attributes['alt'] ?? '')) !== $current || $current === $suggested) { + return $comment[0]; + } + + $attributes['alt'] = $suggested; + $changed = true; + + return '"; + }, + $tags->get_updated_html(), + ) ?? $html; + + return ['html' => $html, 'changed' => $changed, 'already' => $already]; + } + + /** + * attachment_url_to_postid() only knows an image by its original file on this + * site's uploads address. The scan sees a resized copy, often on a CDN, and an + * image WordPress scaled down on upload is filed under its -scaled name while its + * sizes are named after the original. + */ + private function attachment(string $source): int + { + $uploads = wp_get_upload_dir(); + $root = parse_url($uploads['baseurl'], PHP_URL_PATH).'/'; + $path = rawurldecode((string) parse_url($source, PHP_URL_PATH)); + $at = strpos($path, $root); + + if ($source === '' || $at === false) { + return 0; + } + + $file = substr($path, $at + strlen($root)); + $original = (string) preg_replace('/-\d+x\d+(?=\.\w+$)/', '', $file); + $unscaled = (string) preg_replace('/-scaled(?=\.\w+$)/', '', $original); + $scaled = (string) preg_replace('/(?=\.\w+$)/', '-scaled', $unscaled, 1); + + foreach (array_unique([$file, $original, $unscaled, $scaled]) as $candidate) { + $attachmentId = attachment_url_to_postid("{$uploads['baseurl']}/{$candidate}"); + + if ($attachmentId !== 0) { + return $attachmentId; + } + } + + return 0; + } + + private function path(string $url): string + { + return rawurldecode((string) parse_url($url, PHP_URL_PATH)); + } + + /** + * @return array + */ + private function location(int $attachmentId, bool $writesLibrary, ?WP_Post $post): array + { + $page = $post === null ? [] : ['id' => $post->ID, 'collection' => $post->post_type]; + + return $writesLibrary + ? [...$this->libraryLocation($attachmentId), ...$page] + : ['type' => 'post', ...$page, 'field' => 'post_content']; + } + + /** + * @return array + */ + private function libraryLocation(int $attachmentId): array + { + return ['type' => 'asset', 'asset' => $attachmentId, 'field' => $this->metaKey]; + } +} diff --git a/src/ChangeDispatcher.php b/src/ChangeDispatcher.php index e1aca69..7f763df 100644 --- a/src/ChangeDispatcher.php +++ b/src/ChangeDispatcher.php @@ -57,8 +57,9 @@ public function dispatch(array $changes, bool $dryRun): array } /** - * 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. + * A change stored as a default shows on every page of its kind, and alt text in the + * media library on every page that prints the image, so either clears the whole + * cache. Anything else clears the page it was made for. * * @param array}> $landed */ @@ -69,7 +70,7 @@ private function purge(array $landed): void } foreach ($landed as [, $location]) { - if (($location['default'] ?? false) === true) { + if (($location['default'] ?? false) === true || ($location['type'] ?? null) === 'asset') { $this->pageCache->purgeEverything(); return; diff --git a/src/ContentWriter.php b/src/ContentWriter.php new file mode 100644 index 0000000..5bbc54f --- /dev/null +++ b/src/ContentWriter.php @@ -0,0 +1,85 @@ + $fields + */ + public function updatePost(int $postId, array $fields): bool + { + $filtered = has_filter('content_save_pre', 'wp_filter_post_kses') !== false; + + kses_remove_filters(); + + try { + $result = wp_update_post(wp_slash(['ID' => $postId, ...$fields]), true); + } finally { + if ($filtered) { + kses_init_filters(); + } + } + + return ! is_wp_error($result) && $result === $postId; + } + + /** + * ACF unslashes on save as WordPress does, expecting what a form posts. It answers + * false for a group or flexible content field whose sub fields were saved, because + * the parent's own stored value did not change, so what was written is read back. + */ + public function updateField(string $fieldKey, mixed $value, int $postId): bool + { + return update_field($fieldKey, wp_slash($value), $postId) + || $this->leaves(get_field($fieldKey, $postId, false)) === $this->leaves($value); + } + + /** + * Rows read back may be keyed by field key where they were written by name, so only + * the values are compared. + * + * @return array + */ + private function leaves(mixed $value): array + { + $leaves = []; + $value = is_array($value) ? $value : [$value]; + + array_walk_recursive($value, static function (mixed $leaf) use (&$leaves): void { + $leaves[] = (string) $leaf; + }); + + sort($leaves); + + return $leaves; + } + + /** + * A page builder keeps the page in its own data and leaves post_content as a copy + * it overwrites on the next save, or keeps the page as shortcodes whose attributes + * carry text, so an edit would show nowhere or break the layout. A builder's own + * shortcodes in the content are taken as a sign of one whose setting is missing. + */ + public function pageBuilder(int $postId): ?string + { + $meta = static fn (string $key): mixed => get_post_meta($postId, $key, true); + + return match (true) { + $meta('_elementor_edit_mode') === 'builder' => 'Elementor', + (bool) $meta('_fl_builder_enabled') => 'Beaver Builder', + $meta('_et_pb_use_builder') === 'on' => 'Divi', + $meta('_wpb_vc_js_status') === 'true' => 'WPBakery', + $meta('fusion_builder_status') === 'active' => 'Avada', + ! empty($meta('ct_builder_shortcodes')) || ! empty($meta('ct_builder_json')) => 'Oxygen', + ! empty($meta('_bricks_page_content_2')) => 'Bricks', + ! empty($meta('panels_data')) => 'SiteOrigin Page Builder', + preg_match('/\[(?:et_pb_|vc_|fusion_)/', (string) get_post_field('post_content', $postId)) === 1 => 'a page builder', + default => null, + }; + } +} diff --git a/src/LinkApplier.php b/src/LinkApplier.php new file mode 100644 index 0000000..dcec246 --- /dev/null +++ b/src/LinkApplier.php @@ -0,0 +1,277 @@ +target['anchor'] ?? '')); + $href = trim((string) ($change->target['href'] ?? '')); + + if ($anchor === '' || $href === '') { + return ChangeResult::skipped( + $change->id, + 'invalid_change', + 'A link change needs the words to link and the page they link to. Scan the site again and send it once more.', + ); + } + + if (! $this->onThisSite($href)) { + return ChangeResult::skipped($change->id, 'invalid_change', 'A link change can only point to a page on this site.'); + } + + $post = $this->content->find($change->url); + + if (! $post instanceof WP_Post) { + return ChangeResult::skipped($change->id, 'not_found', "No post or page answers to {$change->url}, and only their content is linked."); + } + + $builder = $this->writer->pageBuilder($post->ID); + + if ($builder !== null) { + return ChangeResult::skipped($change->id, 'page_builder', "This page is built with {$builder}, which keeps its content where this plugin does not write."); + } + + $removing = trim((string) $change->suggestedValue) === $anchor; + $rewrite = fn (string $html): array => $removing + ? $this->linker->unlink($html, $anchor, $href) + : $this->linker->link($html, $anchor, $href); + $edit = $this->edit($post, $rewrite); + $location = ['type' => 'post', 'id' => $post->ID, 'collection' => $post->post_type, 'field' => $edit['field'] ?? 'post_content']; + + if ($edit['outcome'] !== 'changed') { + return $this->unchanged($edit['outcome'], $change, $location, $anchor, $href, $removing); + } + + if ($dryRun) { + return ChangeResult::applied($change->id, $location, $change->currentValue, $change->suggestedValue); + } + + if (! $edit['save']()) { + return ChangeResult::failed($change->id, 'write_failed', "WordPress did not save {$location['field']} on this page."); + } + + return ChangeResult::applied($change->id, $location, $change->currentValue, $change->suggestedValue); + } + + /** + * A path from the root, or an http address on this site's host. A leading "//" or + * "/\" is another host to a browser, so a backslash or whitespace anywhere is + * refused rather than guessed at. + */ + private function onThisSite(string $href): bool + { + if (preg_match('/[\s\\\\\x00-\x1f\x7f]/', $href) === 1) { + return false; + } + + if (preg_match('#^/(?!/)#', $href) === 1) { + return true; + } + + if (! in_array(strtolower((string) parse_url($href, PHP_URL_SCHEME)), ['http', 'https'], true)) { + return false; + } + + return strtolower((string) parse_url($href, PHP_URL_HOST)) === strtolower((string) parse_url(home_url(), PHP_URL_HOST)); + } + + /** + * @param array $location + * @return array + */ + private function unchanged(string $outcome, ChangeRequest $change, array $location, string $anchor, string $href, bool $removing): array + { + if ($removing) { + return ChangeResult::alreadyApplied($change->id, $location, "There is no link to {$href} on \"{$anchor}\" on this page, so there was nothing to take off."); + } + + return match ($outcome) { + 'already' => ChangeResult::alreadyApplied($change->id, $location, "The first mention of \"{$anchor}\" already links to {$href}."), + 'inside_link' => ChangeResult::skipped( + $change->id, + 'already_linked', + "The first mention of \"{$anchor}\" already links somewhere else. Somebody chose that link, so it was left alone.", + ), + default => ChangeResult::skipped( + $change->id, + 'mention_not_found', + "\"{$anchor}\" is not in this page's content as written, so there is nothing to link. It may come from the theme, a widget or another post shown on the page.", + ), + }; + } + + /** + * The first field that answers, with a way to save what changed in it. + * + * @param callable(string): array{outcome: string, html: string} $rewrite + * @return array{outcome: string, field?: string, save?: callable(): bool} + */ + private function edit(WP_Post $post, callable $rewrite): array + { + $found = $rewrite($post->post_content); + + if ($found['outcome'] !== 'not_found') { + return [ + 'outcome' => $found['outcome'], + 'field' => 'post_content', + 'save' => fn (): bool => $this->writer->updatePost($post->ID, ['post_content' => $found['html']]), + ]; + } + + foreach ($this->acfFields($post->ID) as $field) { + $value = $field['value']; + $outcome = $this->visit($value, $field, $rewrite); + + if ($outcome !== null) { + return [ + 'outcome' => $outcome, + 'field' => $field['name'], + 'save' => fn (): bool => $this->writer->updateField($field['key'], $value, $post->ID), + ]; + } + } + + return ['outcome' => 'not_found']; + } + + /** + * @return array> + */ + private function acfFields(int $postId): array + { + if (! function_exists('get_field_objects')) { + return []; + } + + return array_values(get_field_objects($postId, false) ?: []); + } + + /** + * @param array $field + * @param callable(string): array{outcome: string, html: string} $rewrite + */ + private function visit(mixed &$value, array $field, callable $rewrite): ?string + { + $type = $field['type'] ?? null; + + if ($type === 'wysiwyg') { + return is_string($value) ? $this->rewriteProse($value, $rewrite) : null; + } + + if (! is_array($value)) { + return null; + } + + if ($type === 'group') { + return $this->visitRow($value, $field['sub_fields'] ?? [], $rewrite); + } + + if (! in_array($type, ['repeater', 'flexible_content'], true)) { + return null; + } + + foreach (array_keys($value) as $index) { + if (! is_array($value[$index])) { + continue; + } + + $subFields = $type === 'repeater' ? ($field['sub_fields'] ?? []) : $this->layoutFields($field, $value[$index]); + $outcome = $this->visitRow($value[$index], $subFields, $rewrite); + + if ($outcome !== null) { + return $outcome; + } + } + + return null; + } + + /** + * @param callable(string): array{outcome: string, html: string} $rewrite + */ + private function rewriteProse(string &$value, callable $rewrite): ?string + { + $found = $rewrite($value); + + if ($found['outcome'] === 'not_found') { + return null; + } + + $value = $found['html']; + + return $found['outcome']; + } + + /** + * Unformatted rows are keyed by field key, but a row saved by code may be keyed by + * name, so a sub field is looked for under both. + * + * @param array $row + * @param array> $subFields + * @param callable(string): array{outcome: string, html: string} $rewrite + */ + private function visitRow(array &$row, array $subFields, callable $rewrite): ?string + { + foreach ($subFields as $subField) { + $key = array_key_exists($subField['key'] ?? '', $row) ? $subField['key'] : ($subField['name'] ?? ''); + + if (! array_key_exists($key, $row)) { + continue; + } + + $outcome = $this->visit($row[$key], $subField, $rewrite); + + if ($outcome !== null) { + return $outcome; + } + } + + return null; + } + + /** + * @param array $field + * @param array $row + * @return array> + */ + private function layoutFields(array $field, array $row): array + { + foreach ($field['layouts'] ?? [] as $layout) { + if (($layout['name'] ?? null) === ($row['acf_fc_layout'] ?? false)) { + return $layout['sub_fields'] ?? []; + } + } + + return []; + } +} diff --git a/src/MentionLinker.php b/src/MentionLinker.php new file mode 100644 index 0000000..ee95817 --- /dev/null +++ b/src/MentionLinker.php @@ -0,0 +1,195 @@ +" inside an attribute does not end one. A + * mention inside a link's text is the first mention, + * and is answered for rather than passed over: somebody chose that link, and linking + * a later mention instead would put two destinations on one name. + */ +class MentionLinker +{ + private static string $attributes = '(?:[^>"\']|"[^"]*"|\'[^\']*\')*'; + + /** + * @return array{outcome: string, html: string} outcome is changed, already, inside_link or not_found + */ + public function link(string $html, string $anchor, string $href): array + { + $mention = $this->expression($anchor); + $attributes = self::$attributes; + $markup = $this->spans("/|<{$attributes}>|\[\/?[a-z_][^\]]*\]/isu", $html); + $passedOver = $this->spans("/<(script|style|textarea|select|option|button|label|summary|code|pre|svg|math|title|iframe|noscript|h[1-6])\b{$attributes}>.*?<\/\\1\s*>/isu", $html); + $links = $this->links($html); + + preg_match_all("/{$mention}/iu", $html, $matches, PREG_OFFSET_CAPTURE); + + foreach ($matches[0] as [$text, $offset]) { + $end = $offset + strlen($text); + + if ($this->within($markup, $offset, $end)) { + continue; + } + + foreach ($links as $link) { + if ($offset >= $link['start'] && $end <= $link['end']) { + return ['outcome' => $this->samePlace($link['href'], $href) ? 'already' : 'inside_link', 'html' => $html]; + } + } + + if ($this->within($passedOver, $offset, $end)) { + continue; + } + + $linked = sprintf('%s', esc_url($href), $text); + + return ['outcome' => 'changed', 'html' => substr_replace($html, $linked, $offset, strlen($text))]; + } + + return ['outcome' => 'not_found', 'html' => $html]; + } + + /** + * @return array{outcome: string, html: string} outcome is changed or not_found + */ + public function unlink(string $html, string $anchor, string $href): array + { + $wholly = '/^\s*'.$this->expression($anchor).'\s*$/iu'; + + foreach ($this->links($html) as $link) { + if ($this->samePlace($link['href'], $href) && preg_match($wholly, $link['text']) === 1) { + return [ + 'outcome' => 'changed', + 'html' => substr_replace($html, $link['text'], $link['start'], $link['end'] - $link['start']), + ]; + } + } + + return ['outcome' => 'not_found', 'html' => $html]; + } + + /** + * Whole words only, ignoring case and how the spaces between them were typed, so + * "loft conversion" never links half of "loft conversions". + */ + private function expression(string $anchor): string + { + $words = preg_split('/\s+/u', trim($anchor)) ?: []; + $quoted = implode('(?:[\s\x{00A0}]| |�*160;)+', array_map($this->word(...), $words)); + + return "(? preg_match('/[\p{L}\p{N}]/u', $character) === 1 + ? preg_quote($character, '/') + : '(?:'.implode('|', $this->forms($character)).')', + mb_str_split($word), + )); + } + + /** + * @return array + */ + private function forms(string $character): array + { + $alike = array_values(array_filter( + [["'", '’', '‘'], ['"', '“', '”'], ['-', '–', '—']], + static fn (array $group): bool => in_array($character, $group, true), + ))[0] ?? [$character]; + + $forms = []; + + foreach ($alike as $one) { + $named = htmlentities($one, ENT_QUOTES | ENT_HTML5); + $forms[] = preg_quote($one, '/'); + $forms[] = sprintf('�*%d;|�*%x;', mb_ord($one), mb_ord($one)); + + if ($named !== $one) { + $forms[] = preg_quote($named, '/'); + } + } + + return $forms; + } + + /** + * @return array + */ + private function links(string $html): array + { + $attributes = self::$attributes; + + preg_match_all("/(.*?)<\/a\s*>/isu", $html, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE); + + return array_map(static function (array $match): array { + preg_match('/\bhref\s*=\s*(["\'])(.*?)\1/i', $match[1][0], $href); + + return [ + 'start' => $match[0][1], + 'end' => $match[0][1] + strlen($match[0][0]), + 'href' => html_entity_decode($href[2] ?? '', ENT_QUOTES | ENT_HTML5), + 'text' => $match[2][0], + ]; + }, $matches); + } + + /** + * @return array + */ + private function spans(string $pattern, string $html): array + { + preg_match_all($pattern, $html, $matches, PREG_OFFSET_CAPTURE); + + return array_map(static fn (array $match): array => [$match[1], $match[1] + strlen($match[0])], $matches[0]); + } + + /** + * @param array $spans + */ + private function within(array $spans, int $start, int $end): bool + { + foreach ($spans as [$spanStart, $spanEnd]) { + if ($start < $spanEnd && $end > $spanStart) { + return true; + } + } + + return false; + } + + /** + * Compared as paths, so a full address on this site and a root relative one are the + * same place. An address on another site never is. + */ + private function samePlace(string $existing, string $wanted): bool + { + return $this->pathOf($existing) === $this->pathOf($wanted); + } + + private function pathOf(string $href): string + { + $host = parse_url($href, PHP_URL_HOST); + + if (is_string($host) && $host !== parse_url(home_url(), PHP_URL_HOST)) { + return $href; + } + + return '/'.trim((string) parse_url($href, PHP_URL_PATH), '/'); + } +} diff --git a/src/Receiver.php b/src/Receiver.php index 28882ff..00c31e5 100644 --- a/src/Receiver.php +++ b/src/Receiver.php @@ -32,7 +32,8 @@ public function registerRoutes(): void /** * A refused request that carried a signature is logged, because it is most likely * Altimiser with the wrong secret or a clock out of step. Ones without are left out, - * since anything probing the route would fill the log. + * and at most one a minute is logged, since anything can send the header and a + * caller sending many would otherwise fill the log. */ public function verifySignature(WP_REST_Request $request): bool|WP_Error { @@ -43,12 +44,22 @@ public function verifySignature(WP_REST_Request $request): bool|WP_Error } if ($request->get_header('X-Altimiser-Signature') !== null) { - error_log("Altimiser refused a signed request to {$request->get_route()}: {$refusal}"); + $this->logRefusal("Altimiser refused a signed request to {$request->get_route()}: {$refusal}"); } return new WP_Error('altimiser_refused', $refusal, ['status' => 401]); } + private function logRefusal(string $message): void + { + if (get_transient('altimiser_refusal_logged') !== false) { + return; + } + + set_transient('altimiser_refusal_logged', 1, MINUTE_IN_SECONDS); + error_log($message); + } + private function refusal(WP_REST_Request $request): ?string { $secret = Settings::secret(); @@ -179,9 +190,13 @@ public function changes(WP_REST_Request $request): WP_REST_Response|WP_Error private function appliers(): array { $content = new ContentResolver(); + $writer = new ContentWriter(); return [ $this->yoast === null ? new InactiveSeoPlugin() : new YoastApplier($this->yoast, $content), + new AltTextApplier($content, $writer), + new LinkApplier($content, new MentionLinker(), $writer), + new RobotsApplier(), ]; } diff --git a/src/RobotsApplier.php b/src/RobotsApplier.php new file mode 100644 index 0000000..2d7f672 --- /dev/null +++ b/src/RobotsApplier.php @@ -0,0 +1,252 @@ +checks(), true); + } + + public static function declareSitemap(string $output): string + { + $sitemap = (string) get_option(self::$option, ''); + + if ($sitemap === '' || preg_match(self::$sitemapLine, $output) === 1) { + return $output; + } + + return rtrim($output, "\n")."\n\nSitemap: {$sitemap}\n"; + } + + public function apply(ChangeRequest $change, bool $dryRun): array + { + $sitePath = trim((string) parse_url(home_url(), PHP_URL_PATH), '/'); + + if ($sitePath !== '') { + return ChangeResult::skipped( + $change->id, + 'no_field', + "Crawlers only read robots.txt at the root of a domain, and this site is at /{$sitePath}, so it has no robots.txt of its own.", + ); + } + + $sitemap = $this->sitemap($change->suggestedValue); + + if ($sitemap === null) { + return ChangeResult::skipped( + $change->id, + 'invalid_change', + 'The sitemap address is not a single http or https address on this site, so it was not written to robots.txt.', + ); + } + + $root = $this->root ?? self::webRoot(); + + if ($root === null) { + return ChangeResult::skipped( + $change->id, + 'no_field', + 'WordPress is installed somewhere that does not match the site address, so there is no telling where the root of the site is.', + ); + } + + $file = trailingslashit($root).'robots.txt'; + $existing = is_file($file) ? (string) file_get_contents($file) : null; + + return $change->check === 'site.robots_missing' + ? $this->create($change, $file, $existing, $sitemap, $dryRun) + : $this->declare($change, $file, $existing, $sitemap, $dryRun); + } + + /** + * @return array + */ + private function create(ChangeRequest $change, string $file, ?string $existing, string $sitemap, bool $dryRun): array + { + if ($existing !== null) { + return ChangeResult::alreadyApplied($change->id, $this->fileLocation(), 'This site already has a robots.txt file.'); + } + + if (is_multisite()) { + return ChangeResult::skipped( + $change->id, + 'no_field', + 'Every site on this network is served from one folder, so a robots.txt file there would answer for all of them. WordPress prints one for each site instead.', + ); + } + + if ((string) get_option('blog_public', '1') === '0') { + return ChangeResult::skipped( + $change->id, + 'search_discouraged', + 'This site is set to discourage search engines (Settings, Reading), so a robots.txt that lets them in was not written.', + ); + } + + $contents = "User-agent: *\nDisallow:\n".($sitemap === '' ? '' : "\nSitemap: {$sitemap}\n"); + + return $this->write($change, $file, $contents, $dryRun); + } + + /** + * @return array + */ + private function declare(ChangeRequest $change, string $file, ?string $existing, string $sitemap, bool $dryRun): array + { + if ($sitemap === '') { + return ChangeResult::skipped($change->id, 'no_suggestion', 'There is no sitemap address to declare, and this site does not publish one of its own.'); + } + + if ($existing !== null) { + return $this->declareInFile($change, $file, $existing, $sitemap, $dryRun); + } + + $location = ['type' => 'setting', 'field' => self::$option]; + $printed = (string) apply_filters('robots_txt', "User-agent: *\n", (string) get_option('blog_public', '1') !== '0'); + + if (preg_match(self::$sitemapLine, $printed) === 1) { + return ChangeResult::alreadyApplied($change->id, $location, 'The robots.txt WordPress prints already declares a sitemap.'); + } + + if (! $dryRun && ! update_option(self::$option, $sitemap, false)) { + return ChangeResult::failed($change->id, 'write_failed', 'WordPress did not save the sitemap address.'); + } + + return ChangeResult::applied($change->id, $location, null, "Sitemap: {$sitemap}"); + } + + /** + * @return array + */ + private function declareInFile(ChangeRequest $change, string $file, string $existing, string $sitemap, bool $dryRun): array + { + if (preg_match(self::$sitemapLine, $existing) === 1) { + return ChangeResult::alreadyApplied($change->id, $this->fileLocation(), 'robots.txt already declares a sitemap.'); + } + + if (is_multisite()) { + return ChangeResult::skipped( + $change->id, + 'no_field', + 'The robots.txt file answers for every site on this network, so the plugin leaves it to whoever looks after the network.', + ); + } + + return $this->write($change, $file, rtrim($existing, "\n")."\n\nSitemap: {$sitemap}\n", $dryRun); + } + + /** + * @return array + */ + private function write(ChangeRequest $change, string $file, string $contents, bool $dryRun): array + { + if ($dryRun) { + return ChangeResult::applied($change->id, $this->fileLocation(), null, $contents); + } + + $writable = is_file($file) ? is_writable($file) : is_writable(dirname($file)); + + if (! $writable || file_put_contents($file, $contents) === false) { + return ChangeResult::failed($change->id, 'write_failed', 'The web server cannot write robots.txt at the root of this site.'); + } + + return ChangeResult::applied($change->id, $this->fileLocation(), null, $contents); + } + + /** + * Altimiser sends a whole Sitemap: line, or nothing when it found no robots.txt to + * read. The site's own sitemap is used then, Yoast's where it makes one. Null means + * the address sent is not one to put in front of crawlers. + */ + private function sitemap(?string $suggested): ?string + { + $sitemap = trim((string) preg_replace('/^\s*sitemap:\s*/i', '', (string) $suggested)); + + if ($sitemap !== '') { + return $this->onThisSite($sitemap) ? $sitemap : null; + } + + if (class_exists('WPSEO_Options') && WPSEO_Options::get('enable_xml_sitemap')) { + return home_url('/sitemap_index.xml'); + } + + return (string) get_sitemap_url('index'); + } + + /** + * One http or https address with nothing that would start another line, on this + * site's host with or without www. + */ + private function onThisSite(string $url): bool + { + if (preg_match('#^https?://[^\s\x00-\x1f\x7f]+$#i', $url) !== 1) { + return false; + } + + $host = static fn (string $address): string => (string) preg_replace('/^www\./', '', strtolower((string) parse_url($address, PHP_URL_HOST))); + + return $host($url) === $host(home_url()); + } + + /** + * The folder the site is served from. With WordPress in a folder of its own, the + * site address ends in that folder and so does ABSPATH. Core's get_home_path() + * works it out from the script being run instead, which during a REST request is + * the root index.php, so it answers "/". + */ + public static function webRoot(): ?string + { + $home = untrailingslashit((string) parse_url(home_url(), PHP_URL_PATH)); + $site = untrailingslashit((string) parse_url(site_url(), PHP_URL_PATH)); + $wordPress = untrailingslashit(str_replace('\\', '/', ABSPATH)); + + if ($site === $home) { + return trailingslashit($wordPress); + } + + $folder = substr($site, strlen($home)); + + if (! str_starts_with($site, "{$home}/") || ! str_ends_with($wordPress, $folder)) { + return null; + } + + return trailingslashit(substr($wordPress, 0, -strlen($folder))); + } + + /** + * @return array + */ + private function fileLocation(): array + { + return ['type' => 'file', 'file' => 'robots.txt']; + } +} diff --git a/src/Settings.php b/src/Settings.php index ed79808..589f371 100644 --- a/src/Settings.php +++ b/src/Settings.php @@ -22,7 +22,26 @@ public static function altimiserUrl(): ?string { $url = self::read('ALTIMISER_URL', 'altimiser_url'); - return $url === null ? null : rtrim($url, '/'); + if ($url === null || ! self::isSecureAddress($url)) { + return null; + } + + return rtrim($url, '/'); + } + + /** + * The review link carries a signature and the editor's address, so plain http is + * only accepted for a development machine. + */ + public static function isSecureAddress(string $url): bool + { + $host = strtolower((string) parse_url($url, PHP_URL_HOST)); + + if (strtolower((string) parse_url($url, PHP_URL_SCHEME)) === 'https') { + return true; + } + + return in_array($host, ['localhost', '127.0.0.1'], true) || str_ends_with($host, '.test'); } public static function secretIsLongEnough(string $secret): bool diff --git a/src/SettingsPage.php b/src/SettingsPage.php index 6ea6ae1..b7ffbbb 100644 --- a/src/SettingsPage.php +++ b/src/SettingsPage.php @@ -43,7 +43,8 @@ public function registerSetting(): void public function sanitise(mixed $input): array { $input = is_array($input) ? $input : []; - $saved = Settings::stored()['secret'] ?? ''; + $stored = Settings::stored(); + $saved = $stored['secret'] ?? ''; $secret = trim((string) ($input['secret'] ?? '')); if ($secret !== '' && ! Settings::secretIsLongEnough($secret)) { @@ -56,8 +57,16 @@ public function sanitise(mixed $input): array $secret = ''; } + $url = esc_url_raw(trim((string) ($input['altimiser_url'] ?? '')), ['https', 'http']); + + if ($url !== '' && ! Settings::isSecureAddress($url)) { + add_settings_error(Settings::$option, 'altimiser_url_not_https', __('The Altimiser address needs to start with https://, so it was not changed.', 'altimiser')); + + $url = $stored['altimiser_url'] ?? ''; + } + return array_filter([ - 'altimiser_url' => esc_url_raw(trim((string) ($input['altimiser_url'] ?? '')), ['https', 'http']), + 'altimiser_url' => $url, 'secret' => $secret === '' ? $saved : $secret, ]); } diff --git a/tests/AltTextTest.php b/tests/AltTextTest.php new file mode 100644 index 0000000..29393a3 --- /dev/null +++ b/tests/AltTextTest.php @@ -0,0 +1,222 @@ +set_permalink_structure('/%postname%/'); + + $this->uploads = wp_get_upload_dir()['baseurl']; + $this->imageId = $this->image('2026/11/harbour.jpg'); + $this->pageId = self::factory()->post->create([ + 'post_type' => 'page', + 'post_name' => 'moorings', + 'post_content' => $this->imageBlock($this->imageId, "{$this->uploads}/2026/11/harbour-300x200.jpg", ''), + ]); + } + + public function test_writes_alt_text_to_the_media_library_and_to_the_page(): void + { + $result = $this->sendAlt(['target' => $this->target('https://cdn.example.net/wp-content/uploads/2026/11/harbour-300x200.jpg')]); + + $this->assertSame('applied', $result['status']); + $this->assertSame(['type' => 'asset', 'asset' => $this->imageId, 'field' => '_wp_attachment_image_alt', 'id' => $this->pageId, 'collection' => 'page'], $result['location']); + $this->assertSame('Boats moored in the harbour at dusk', get_post_meta($this->imageId, '_wp_attachment_image_alt', true)); + $this->assertStringContainsString('alt="Boats moored in the harbour at dusk"', get_post($this->pageId)->post_content); + } + + public function test_clears_every_cached_page_when_the_media_library_is_written(): void + { + $purged = []; + $record = static function (array $urls, bool $everything) use (&$purged): void { + $purged[] = $everything; + }; + + add_action('altimiser_purge_urls', $record, 10, 2); + $this->sendAlt(['target' => $this->target("{$this->uploads}/2026/11/harbour-300x200.jpg")]); + remove_action('altimiser_purge_urls', $record); + + $this->assertSame([true], $purged); + } + + public function test_finds_an_image_wordpress_scaled_down_on_upload(): void + { + $scaledId = $this->image('2026/11/estuary-scaled.jpg'); + + $result = $this->sendAlt(['target' => $this->target("{$this->uploads}/2026/11/estuary-1024x683.jpg")]); + + $this->assertSame('applied', $result['status']); + $this->assertSame('Boats moored in the harbour at dusk', get_post_meta($scaledId, '_wp_attachment_image_alt', true)); + } + + public function test_writes_only_the_page_where_the_media_library_has_its_own_wording(): void + { + update_post_meta($this->imageId, '_wp_attachment_image_alt', 'The harbour'); + + $result = $this->sendAlt(); + + $this->assertSame('applied', $result['status']); + $this->assertSame(['type' => 'post', 'id' => $this->pageId, 'collection' => 'page', 'field' => 'post_content'], $result['location']); + $this->assertSame('The harbour', get_post_meta($this->imageId, '_wp_attachment_image_alt', true)); + } + + public function test_leaves_an_editors_own_wording_alone(): void + { + update_post_meta($this->imageId, '_wp_attachment_image_alt', 'The harbour'); + $this->setContent($this->imageBlock($this->imageId, "{$this->uploads}/2026/11/harbour.jpg", 'The harbour in winter')); + + $result = $this->sendAlt(); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('value_changed', $result['reason']); + $this->assertStringContainsString('alt="The harbour in winter"', get_post($this->pageId)->post_content); + } + + public function test_counts_alt_text_already_in_place_as_done(): void + { + update_post_meta($this->imageId, '_wp_attachment_image_alt', 'Boats moored in the harbour at dusk'); + $this->setContent($this->imageBlock($this->imageId, "{$this->uploads}/2026/11/harbour.jpg", 'Boats moored in the harbour at dusk')); + + $this->assertSame('already_applied', $this->sendAlt()['status']); + } + + public function test_counts_a_change_to_the_wording_already_there_as_done(): void + { + update_post_meta($this->imageId, '_wp_attachment_image_alt', 'The harbour'); + $this->setContent($this->imageBlock($this->imageId, "{$this->uploads}/2026/11/harbour.jpg", 'The harbour')); + + $this->assertSame('already_applied', $this->sendAlt(['check' => 'image.alt_too_long', 'current_value' => 'The harbour', 'suggested_value' => 'The harbour'])['status']); + } + + public function test_keeps_a_cover_block_valid_by_writing_its_attribute_as_well(): void + { + $url = "{$this->uploads}/2026/11/harbour.jpg"; + $this->setContent( + "\n" + ."
imageId}\" alt=\"\" src=\"{$url}\" data-object-fit=\"cover\"/>" + ."
\n", + ); + + $result = $this->sendAlt(); + $content = get_post($this->pageId)->post_content; + + $this->assertSame('applied', $result['status']); + $this->assertSame('Boats moored in the harbour at dusk', parse_blocks($content)[0]['attrs']['alt']); + $this->assertStringContainsString('alt="Boats moored in the harbour at dusk" src=', $content); + } + + public function test_puts_the_earlier_wording_back_on_a_revert(): void + { + $this->sendAlt(['check' => 'image.alt_too_long', 'current_value' => '', 'suggested_value' => 'Boats moored in the harbour at dusk']); + + $result = $this->sendAlt(['check' => 'image.alt_too_long', 'current_value' => 'Boats moored in the harbour at dusk', 'suggested_value' => 'The harbour']); + + $this->assertSame('applied', $result['status']); + $this->assertSame('The harbour', get_post_meta($this->imageId, '_wp_attachment_image_alt', true)); + $this->assertStringContainsString('alt="The harbour"', get_post($this->pageId)->post_content); + } + + public function test_keeps_backslashes_and_quotes_in_the_alt_text(): void + { + $this->sendAlt(['suggested_value' => 'The "Sea\\Wolf" at her mooring']); + + $this->assertSame('The "Sea\\Wolf" at her mooring', get_post_meta($this->imageId, '_wp_attachment_image_alt', true)); + $this->assertStringContainsString('alt="The "Sea\\Wolf" at her mooring"', get_post($this->pageId)->post_content); + } + + public function test_skips_an_image_that_is_not_in_the_media_library(): void + { + $result = $this->sendAlt(['target' => $this->target(home_url('/wp-content/themes/harbour/logo.png'))]); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('no_match', $result['reason']); + } + + public function test_skips_a_change_with_no_alt_text_to_write(): void + { + $this->assertSame('no_suggestion', $this->sendAlt(['suggested_value' => null])['reason']); + } + + public function test_writes_nothing_on_a_dry_run(): void + { + $result = $this->send([$this->altChange()], true)[0]; + + $this->assertSame('applied', $result['status']); + $this->assertSame('', get_post_meta($this->imageId, '_wp_attachment_image_alt', true)); + $this->assertStringContainsString('alt=""', get_post($this->pageId)->post_content); + } + + public function test_writes_only_the_media_library_on_a_page_built_with_elementor(): void + { + update_post_meta($this->pageId, '_elementor_edit_mode', 'builder'); + + $result = $this->sendAlt(); + + $this->assertSame('applied', $result['status']); + $this->assertSame(['type' => 'asset', 'asset' => $this->imageId, 'field' => '_wp_attachment_image_alt'], $result['location']); + $this->assertStringContainsString('alt=""', get_post($this->pageId)->post_content); + } + + private function image(string $file): int + { + return self::factory()->attachment->create_object(['file' => $file, 'post_mime_type' => 'image/jpeg']); + } + + private function imageBlock(int $imageId, string $src, string $alt): string + { + return "\n
\"{$alt}\"
\n"; + } + + private function setContent(string $content): void + { + wp_update_post(wp_slash(['ID' => $this->pageId, 'post_content' => $content])); + } + + /** + * @return array + */ + private function target(string $match): array + { + return ['selector' => 'img', 'attribute' => 'alt', 'match' => $match]; + } + + /** + * @param array $overrides + * @return array + */ + private function altChange(array $overrides = []): array + { + return $this->change([ + 'check' => 'image.alt_missing', + 'url' => home_url('/moorings/'), + 'target' => $this->target("{$this->uploads}/2026/11/harbour-300x200.jpg"), + 'current_value' => '', + 'suggested_value' => 'Boats moored in the harbour at dusk', + ...$overrides, + ]); + } + + /** + * @param array $overrides + * @return array + */ + private function sendAlt(array $overrides = []): array + { + return $this->send([$this->altChange($overrides)])[0]; + } +} diff --git a/tests/HealthTest.php b/tests/HealthTest.php index d792f98..6cde556 100644 --- a/tests/HealthTest.php +++ b/tests/HealthTest.php @@ -43,8 +43,14 @@ public function test_advertises_what_it_can_write_through_yoast(): void 'meta_description.irrelevant', 'meta_description.duplicate', 'open_graph.missing', + 'image.alt_missing', + 'image.alt_empty', + 'image.alt_too_long', + 'link.opportunity', + 'site.robots_missing', + 'sitemap.not_declared_in_robots', ], $health['checks']); - $this->assertSame(['content.update'], $health['capabilities']); + $this->assertSame(['content.update', 'content.link'], $health['capabilities']); $this->assertSame(['installed' => true, 'version' => WPSEO_VERSION], $health['integrations']['yoast']); } @@ -60,14 +66,20 @@ public function test_withholds_social_tags_when_yoast_is_set_not_to_print_them() $this->assertContains('title.too_long', $checks); } - public function test_advertises_nothing_without_a_supported_seo_plugin(): void + public function test_withholds_what_yoast_would_write_without_a_supported_seo_plugin(): void { $receiver = new AltDesign\Altimiser\Receiver(dirname(__DIR__).'/altimiser.php', null); $health = $receiver->health()->get_data(); - $this->assertSame([], $health['checks']); - $this->assertSame([], $health['capabilities']); + $this->assertEqualsCanonicalizing([ + 'image.alt_missing', + 'image.alt_empty', + 'image.alt_too_long', + 'link.opportunity', + 'site.robots_missing', + 'sitemap.not_declared_in_robots', + ], $health['checks']); $this->assertSame(['installed' => false], $health['integrations']['yoast']); } diff --git a/tests/LinkTest.php b/tests/LinkTest.php new file mode 100644 index 0000000..021b680 --- /dev/null +++ b/tests/LinkTest.php @@ -0,0 +1,309 @@ +set_permalink_structure('/%postname%/'); + + $this->original = "\n

The restrictive covenant clause

\n\n\n" + ."\n

Read the restrictive covenant clause before you sign.

\n\n\n" + ."\n\n" + ."\n
\n"; + + kses_remove_filters(); + + $this->pageId = self::factory()->post->create([ + 'post_type' => 'page', + 'post_name' => 'rachel-adams', + 'post_content' => wp_slash($this->original), + ]); + + kses_init_filters(); + } + + public function test_links_the_first_mention_outside_a_heading(): void + { + $result = $this->sendLink(); + $content = get_post($this->pageId)->post_content; + + $this->assertSame('applied', $result['status']); + $this->assertSame(['type' => 'post', 'id' => $this->pageId, 'collection' => 'page', 'field' => 'post_content'], $result['location']); + $this->assertStringContainsString('

Read the restrictive covenant clause before you sign.

', $content); + $this->assertStringContainsString('

The restrictive covenant clause

', $content); + } + + public function test_leaves_embeds_scripts_forms_and_backslashes_as_they_were(): void + { + $this->sendLink(); + + $content = get_post($this->pageId)->post_content; + + $this->assertStringContainsString('', $content); + $this->assertStringContainsString('', $content); + $this->assertStringContainsString('
', $content); + $this->assertCount(count(parse_blocks($this->original)), parse_blocks($content)); + } + + public function test_takes_the_link_off_again_on_a_revert(): void + { + $this->sendLink(); + + $result = $this->sendLink([ + 'current_value' => 'https://example.org/insights/restrictive-covenant-clause', + 'suggested_value' => 'The restrictive covenant clause', + ]); + + $this->assertSame('applied', $result['status']); + $this->assertSame($this->original, get_post($this->pageId)->post_content); + } + + public function test_counts_a_revert_with_no_link_left_to_take_off_as_done(): void + { + $result = $this->sendLink(['suggested_value' => 'The restrictive covenant clause']); + + $this->assertSame('already_applied', $result['status']); + $this->assertSame($this->original, get_post($this->pageId)->post_content); + } + + public function test_counts_a_mention_already_linked_there_as_done(): void + { + $this->setContent('

Read the restrictive covenant clause.

'); + + $this->assertSame('already_applied', $this->sendLink()['status']); + } + + public function test_leaves_a_mention_somebody_linked_elsewhere(): void + { + $this->setContent('

Read the restrictive covenant clause. The restrictive covenant clause matters.

'); + + $result = $this->sendLink(); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('already_linked', $result['reason']); + } + + public function test_matches_whole_words_only(): void + { + $this->setContent('

The restrictive covenant clauses in this lease.

'); + + $this->assertSame('mention_not_found', $this->sendLink()['reason']); + } + + public function test_reports_words_the_page_does_not_contain(): void + { + $this->setContent('

Nothing about covenants here.

'); + + $result = $this->sendLink(); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('mention_not_found', $result['reason']); + } + + public function test_links_a_mention_in_an_acf_editor_field_inside_a_repeater(): void + { + $this->setContent('

Nothing about covenants here.

'); + $this->registerSections(); + update_field('field_altimiser_sections', [['field_altimiser_body' => '

The restrictive covenant clause, explained.

']], $this->pageId); + + $result = $this->sendLink(); + + $this->assertSame('applied', $result['status']); + $this->assertSame('sections', $result['location']['field']); + $this->assertSame( + '

The restrictive covenant clause, explained.

', + get_field('sections', $this->pageId, false)[0]['field_altimiser_body'], + ); + } + + public function test_finds_a_mention_stored_with_entities_or_typed_with_straight_quotes(): void + { + $this->setContent("

Read our Terms & Conditions and the children's guide.

"); + $mentionOf = static fn (string $anchor, string $href): array => [ + 'target' => ['selector' => "a[href=\"{$href}\"]", 'attribute' => 'href', 'anchor' => $anchor, 'href' => $href], + 'current_value' => $anchor, + 'suggested_value' => home_url($href), + ]; + + $terms = $this->sendLink($mentionOf('Terms & Conditions', '/terms')); + $guide = $this->sendLink($mentionOf('children’s guide', '/guide')); + + $this->assertSame(['applied', 'applied'], [$terms['status'], $guide['status']]); + $this->assertSame( + "

Read our Terms & Conditions and the children's guide.

", + get_post($this->pageId)->post_content, + ); + } + + public function test_counts_a_link_written_inside_an_acf_group_as_written(): void + { + $this->setContent('

Nothing about covenants here.

'); + acf_add_local_field_group([ + 'key' => 'group_altimiser_intro', + 'title' => 'Introduction', + 'fields' => [[ + 'key' => 'field_altimiser_intro', + 'name' => 'intro', + 'type' => 'group', + 'sub_fields' => [['key' => 'field_altimiser_intro_text', 'name' => 'text', 'type' => 'wysiwyg']], + ]], + 'location' => [[['param' => 'post_type', 'operator' => '==', 'value' => 'page']]], + ]); + update_field('field_altimiser_intro', ['field_altimiser_intro_text' => '

The restrictive covenant clause, explained.

'], $this->pageId); + + $result = $this->sendLink(); + + $this->assertSame('applied', $result['status']); + $this->assertSame('intro', $result['location']['field']); + $this->assertSame( + '

The restrictive covenant clause, explained.

', + get_field('intro', $this->pageId, false)['field_altimiser_intro_text'], + ); + } + + public function test_leaves_a_page_built_with_elementor_alone(): void + { + update_post_meta($this->pageId, '_elementor_edit_mode', 'builder'); + + $result = $this->sendLink(); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('page_builder', $result['reason']); + $this->assertSame($this->original, get_post($this->pageId)->post_content); + } + + public function test_refuses_a_destination_that_is_not_a_page_on_this_site(): void + { + foreach (['javascript:alert(1)', '//other.example/covenants', '/\\other.example/covenants', 'https://other.example/covenants', "/insights\n/covenants"] as $href) { + $result = $this->sendLink(['target' => [...$this->linkChange()['target'], 'href' => $href]]); + + $this->assertSame('invalid_change', $result['reason'], $href); + } + + $this->assertSame($this->original, get_post($this->pageId)->post_content); + } + + public function test_links_to_a_full_address_on_this_site(): void + { + $result = $this->sendLink(['target' => [...$this->linkChange()['target'], 'href' => home_url('/insights/restrictive-covenant-clause/')]]); + + $this->assertSame('applied', $result['status']); + $this->assertStringContainsString('the restrictive', get_post($this->pageId)->post_content); + } + + public function test_passes_over_shortcodes_quoted_attributes_and_summaries(): void + { + $this->setContent( + '[gallery title="The restrictive covenant clause"]' + .'a > b' + .'
The restrictive covenant clause
' + .'

The restrictive covenant clause applies.

', + ); + + $this->assertSame('applied', $this->sendLink()['status']); + $this->assertSame( + '[gallery title="The restrictive covenant clause"]' + .'a > b' + .'
The restrictive covenant clause
' + .'

The restrictive covenant clause applies.

', + get_post($this->pageId)->post_content, + ); + } + + public function test_leaves_a_page_built_with_divi_or_with_another_builders_shortcodes_alone(): void + { + update_post_meta($this->pageId, '_et_pb_use_builder', 'on'); + + $this->assertSame('page_builder', $this->sendLink()['reason']); + + delete_post_meta($this->pageId, '_et_pb_use_builder'); + $this->setContent('[vc_row][vc_column_text]

The restrictive covenant clause applies.

[/vc_column_text][/vc_row]'); + + $this->assertSame('page_builder', $this->sendLink()['reason']); + } + + public function test_skips_a_link_change_with_no_words_to_link(): void + { + $result = $this->sendLink(['target' => ['selector' => 'a', 'attribute' => 'href', 'href' => '/insights/restrictive-covenant-clause']]); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('invalid_change', $result['reason']); + } + + public function test_writes_nothing_on_a_dry_run(): void + { + $result = $this->send([$this->linkChange()], true)[0]; + + $this->assertSame('applied', $result['status']); + $this->assertSame($this->original, get_post($this->pageId)->post_content); + } + + private function setContent(string $content): void + { + kses_remove_filters(); + wp_update_post(wp_slash(['ID' => $this->pageId, 'post_content' => $content])); + kses_init_filters(); + } + + private function registerSections(): void + { + acf_add_local_field_group([ + 'key' => 'group_altimiser_sections', + 'title' => 'Sections', + 'fields' => [[ + 'key' => 'field_altimiser_sections', + 'name' => 'sections', + 'type' => 'repeater', + 'sub_fields' => [[ + 'key' => 'field_altimiser_body', + 'name' => 'body', + 'type' => 'wysiwyg', + ]], + ]], + 'location' => [[['param' => 'post_type', 'operator' => '==', 'value' => 'page']]], + ]); + } + + /** + * @param array $overrides + * @return array + */ + private function linkChange(array $overrides = []): array + { + return $this->change([ + 'check' => 'link.opportunity', + 'url' => home_url('/rachel-adams/'), + 'target' => [ + 'selector' => 'a[href="https://example.org/insights/restrictive-covenant-clause"]', + 'attribute' => 'href', + 'anchor' => 'The restrictive covenant clause', + 'href' => '/insights/restrictive-covenant-clause', + ], + 'current_value' => 'The restrictive covenant clause', + 'suggested_value' => 'https://example.org/insights/restrictive-covenant-clause', + ...$overrides, + ]); + } + + /** + * @param array $overrides + * @return array + */ + private function sendLink(array $overrides = []): array + { + return $this->send([$this->linkChange($overrides)])[0]; + } +} diff --git a/tests/RobotsTest.php b/tests/RobotsTest.php new file mode 100644 index 0000000..352d105 --- /dev/null +++ b/tests/RobotsTest.php @@ -0,0 +1,181 @@ +set_permalink_structure('/%postname%/'); + $this->root = sys_get_temp_dir().'/altimiser-robots-'.uniqid(); + + mkdir($this->root); + } + + public function tear_down(): void + { + WPSEO_Options::set('enable_xml_sitemap', true); + @unlink("{$this->root}/robots.txt"); + rmdir($this->root); + + parent::tear_down(); + } + + public function test_creates_a_permissive_robots_txt_naming_the_sites_sitemap(): void + { + $result = $this->apply('site.robots_missing', null); + + $this->assertSame('applied', $result['status']); + $this->assertSame(['type' => 'file', 'file' => 'robots.txt'], $result['location']); + $this->assertArrayNotHasKey('from', $result); + $this->assertSame("User-agent: *\nDisallow:\n\nSitemap: ".home_url('/sitemap_index.xml')."\n", $this->robots()); + } + + public function test_leaves_a_robots_txt_that_is_already_there(): void + { + file_put_contents("{$this->root}/robots.txt", "User-agent: *\nDisallow: /private/\n"); + + $this->assertSame('already_applied', $this->apply('site.robots_missing', null)['status']); + $this->assertSame("User-agent: *\nDisallow: /private/\n", $this->robots()); + } + + public function test_adds_the_sitemap_to_a_robots_txt_file_keeping_its_rules(): void + { + file_put_contents("{$this->root}/robots.txt", "User-agent: *\nDisallow: /private/\n"); + + $result = $this->apply('sitemap.not_declared_in_robots', 'Sitemap: https://example.org/sitemap.xml'); + + $this->assertSame('applied', $result['status']); + $this->assertSame("User-agent: *\nDisallow: /private/\n\nSitemap: https://example.org/sitemap.xml\n", $this->robots()); + } + + public function test_counts_a_file_that_declares_a_sitemap_as_done(): void + { + file_put_contents("{$this->root}/robots.txt", "Sitemap: https://example.org/other.xml\n"); + + $this->assertSame('already_applied', $this->apply('sitemap.not_declared_in_robots', 'Sitemap: https://example.org/sitemap.xml')['status']); + } + + public function test_adds_the_sitemap_to_what_wordpress_prints_when_there_is_no_file(): void + { + $this->printNoSitemap(); + + $result = $this->apply('sitemap.not_declared_in_robots', 'Sitemap: https://example.org/sitemap.xml'); + + $this->assertSame('applied', $result['status']); + $this->assertSame(['type' => 'setting', 'field' => 'altimiser_robots_sitemap'], $result['location']); + $this->assertFileDoesNotExist("{$this->root}/robots.txt"); + $this->assertStringContainsString("Disallow: /wp-admin/\n\nSitemap: https://example.org/sitemap.xml\n", apply_filters('robots_txt', "User-agent: *\nDisallow: /wp-admin/\n", true)); + $this->assertSame('already_applied', $this->apply('sitemap.not_declared_in_robots', 'Sitemap: https://example.org/sitemap.xml')['status']); + } + + public function test_writes_nothing_on_a_dry_run(): void + { + $this->printNoSitemap(); + + $this->assertSame('applied', $this->apply('site.robots_missing', null, true)['status']); + $this->assertSame('applied', $this->apply('sitemap.not_declared_in_robots', 'Sitemap: https://example.org/sitemap.xml', true)['status']); + $this->assertFileDoesNotExist("{$this->root}/robots.txt"); + $this->assertFalse(get_option('altimiser_robots_sitemap')); + } + + public function test_refuses_a_sitemap_value_that_adds_lines_or_names_another_site(): void + { + file_put_contents("{$this->root}/robots.txt", "User-agent: *\nDisallow: /private/\n"); + + foreach (["Sitemap: https://example.org/sitemap.xml\nDisallow: /", 'Sitemap: https://other.example/sitemap.xml', 'Sitemap: javascript:alert(1)'] as $suggested) { + $this->assertSame('invalid_change', $this->apply('sitemap.not_declared_in_robots', $suggested)['reason'], $suggested); + } + + $this->assertSame("User-agent: *\nDisallow: /private/\n", $this->robots()); + } + + public function test_accepts_the_sitemap_on_the_www_form_of_the_sites_host(): void + { + file_put_contents("{$this->root}/robots.txt", "User-agent: *\n"); + + $this->assertSame('applied', $this->apply('sitemap.not_declared_in_robots', 'Sitemap: https://www.example.org/sitemap.xml')['status']); + } + + public function test_writes_no_file_letting_crawlers_in_on_a_site_that_discourages_them(): void + { + update_option('blog_public', '0'); + + $result = $this->apply('site.robots_missing', null); + + $this->assertSame('skipped', $result['status']); + $this->assertSame('search_discouraged', $result['reason']); + $this->assertFileDoesNotExist("{$this->root}/robots.txt"); + } + + public function test_skips_a_site_that_is_not_at_the_root_of_its_domain(): void + { + update_option('home', 'http://example.org/blog'); + + $result = $this->apply('site.robots_missing', null); + + $this->assertSame('skipped', $result['status']); + $this->assertFileDoesNotExist("{$this->root}/robots.txt"); + } + + private function printNoSitemap(): void + { + WPSEO_Options::set('enable_xml_sitemap', false); + add_filter('wp_sitemaps_enabled', '__return_false'); + } + + public function test_finds_the_web_root_above_wordpress_in_a_folder_of_its_own(): void + { + $wordPress = untrailingslashit(ABSPATH); + $folder = basename($wordPress); + + $this->assertSame(trailingslashit(ABSPATH), RobotsApplier::webRoot()); + + update_option('siteurl', home_url("/{$folder}")); + + $this->assertSame(trailingslashit(dirname($wordPress)), RobotsApplier::webRoot()); + } + + public function test_refuses_to_guess_where_robots_txt_goes_when_wordpress_is_somewhere_it_cannot_place(): void + { + update_option('siteurl', home_url('/not-where-wordpress-is')); + + $result = (new RobotsApplier())->apply(ChangeRequest::fromPayload($this->change([ + 'check' => 'site.robots_missing', + 'url' => home_url('/'), + 'target' => ['selector' => null, 'attribute' => null], + 'current_value' => null, + 'suggested_value' => null, + ])), false); + + $this->assertNull(RobotsApplier::webRoot()); + $this->assertSame('skipped', $result['status']); + $this->assertSame('no_field', $result['reason']); + } + + /** + * @return array + */ + private function apply(string $check, ?string $suggested, bool $dryRun = false): array + { + $change = ChangeRequest::fromPayload($this->change([ + 'check' => $check, + 'url' => home_url('/'), + 'target' => ['selector' => null, 'attribute' => null], + 'current_value' => null, + 'suggested_value' => $suggested, + ])); + + return (new RobotsApplier($this->root))->apply($change, $dryRun); + } + + private function robots(): string + { + return (string) file_get_contents("{$this->root}/robots.txt"); + } +} diff --git a/tests/SettingsPageTest.php b/tests/SettingsPageTest.php index 6ccb10c..9eed6cb 100644 --- a/tests/SettingsPageTest.php +++ b/tests/SettingsPageTest.php @@ -33,6 +33,41 @@ public function test_saves_a_secret_long_enough_and_the_address(): void $this->assertSame(['altimiser_url' => 'https://altimiser.example.com', 'secret' => $this->longSecret], $saved); } + public function test_turns_away_a_plain_http_address_except_for_a_development_machine(): void + { + $refused = (new SettingsPage())->sanitise(['altimiser_url' => 'http://altimiser.example.com']); + + $this->assertArrayNotHasKey('altimiser_url', $refused); + $this->assertSame('altimiser_url_not_https', get_settings_errors(Settings::$option)[0]['code']); + $this->assertSame(['altimiser_url' => 'http://altimiser.test'], (new SettingsPage())->sanitise(['altimiser_url' => 'http://altimiser.test'])); + } + + public function test_keeps_the_saved_address_when_a_plain_http_one_is_turned_away(): void + { + update_option(Settings::$option, ['altimiser_url' => 'https://altimiser.example.com', 'secret' => $this->longSecret]); + + $saved = (new SettingsPage())->sanitise(['altimiser_url' => 'http://altimiser.example.com', 'secret' => '']); + + $this->assertSame(['altimiser_url' => 'https://altimiser.example.com', 'secret' => $this->longSecret], $saved); + $this->assertSame('altimiser_url_not_https', get_settings_errors(Settings::$option)[0]['code']); + } + + public function test_clears_the_address_when_the_field_is_emptied(): void + { + update_option(Settings::$option, ['altimiser_url' => 'https://altimiser.example.com', 'secret' => $this->longSecret]); + + $saved = (new SettingsPage())->sanitise(['altimiser_url' => '', 'secret' => '']); + + $this->assertSame(['secret' => $this->longSecret], $saved); + } + + public function test_ignores_a_plain_http_address_set_in_wp_config(): void + { + define('ALTIMISER_URL', 'http://altimiser.example.com'); + + $this->assertNull(Settings::altimiserUrl()); + } + public function test_keeps_the_saved_secret_when_the_field_is_left_blank(): void { update_option(Settings::$option, ['secret' => $this->longSecret]); @@ -103,6 +138,7 @@ public function test_uninstalling_removes_the_settings_the_kept_count_and_every_ update_option(Settings::$option, ['secret' => $this->longSecret]); set_transient('altimiser_summary', ['summary' => ['awaiting_review' => 1]], 300); Connections::put($editor, ['connection' => 'c', 'token' => 't', 'expires_at' => time() + 60, 'account_email' => '']); + update_option('altimiser_robots_sitemap', 'https://example.org/sitemap.xml'); define('WP_UNINSTALL_PLUGIN', 'altimiser/altimiser.php'); require dirname(__DIR__).'/uninstall.php'; @@ -110,6 +146,7 @@ public function test_uninstalling_removes_the_settings_the_kept_count_and_every_ $this->assertFalse(get_option(Settings::$option)); $this->assertFalse(get_transient('altimiser_summary')); $this->assertFalse(get_user_option(Connections::$option, $editor)); + $this->assertFalse(get_option('altimiser_robots_sitemap')); } public function test_shows_nothing_to_someone_who_cannot_manage_options(): void diff --git a/tests/SignatureTest.php b/tests/SignatureTest.php index 95d1278..96020d1 100644 --- a/tests/SignatureTest.php +++ b/tests/SignatureTest.php @@ -22,13 +22,14 @@ public function test_signs_the_worked_examples_in_the_protocol_document_as_writt ); } - public function test_logs_a_refused_request_that_carried_a_signature_and_not_one_without(): void + public function test_logs_one_refused_signed_request_a_minute_and_none_without_a_signature(): void { $log = (string) tempnam(sys_get_temp_dir(), 'altimiser'); $previous = ini_set('error_log', $log); $this->dispatch($this->request()); $this->dispatch($this->signedRequest(secret: 'not-the-secret')); + $this->dispatch($this->signedRequest(secret: 'not-the-secret-either')); ini_set('error_log', (string) $previous); $logged = (string) file_get_contents($log); diff --git a/tests/bootstrap.php b/tests/bootstrap.php index f927847..293e6a7 100644 --- a/tests/bootstrap.php +++ b/tests/bootstrap.php @@ -14,6 +14,7 @@ tests_add_filter('muplugins_loaded', static function () use ($pluginDirectory): void { require "{$pluginDirectory}/vendor/wp-plugins/wordpress-seo/wp-seo.php"; + require "{$pluginDirectory}/vendor/wp-plugins/advanced-custom-fields/acf.php"; require "{$pluginDirectory}/altimiser.php"; }); diff --git a/uninstall.php b/uninstall.php index 7008f0c..38d71e9 100644 --- a/uninstall.php +++ b/uninstall.php @@ -2,15 +2,18 @@ /** * Removes what the plugin keeps for itself. Changes it applied are the site's content - * by now, and stay. + * by now, and stay. A sitemap it declared in the robots.txt WordPress prints goes with + * it, because only the plugin's filter printed it. */ defined('WP_UNINSTALL_PLUGIN') || exit; $forgetThisSite = static function (): void { delete_option('altimiser_settings'); + delete_option('altimiser_robots_sitemap'); delete_transient('altimiser_summary'); delete_transient('altimiser_summary_lock'); + delete_transient('altimiser_refusal_logged'); delete_metadata('user', 0, $GLOBALS['wpdb']->get_blog_prefix().'altimiser_connection', '', true); };