Files
nolimit-discounts/includes/class-updater.php
T
kristianwindandClaude Opus 5 eca2851d35 Test against the newest WordPress and WooCommerce, and ship updates
Three things this repository could not do: prove the plugin still works on a
WordPress or WooCommerce released after it, get a fix onto a shop without
someone uploading a zip, and do either of those for the next plugin without
starting over.

ci/ is the test harness. ci/site-test.sh builds a throwaway WordPress +
WooCommerce in containers at any versions you name — including `nightly` and
`beta` — installs exactly the files the release zip will contain, and runs
tests/smoke.php inside it with wp eval-file. Real cart, real coupons, real
WC_Shipping_Rate objects: a mocked cart keeps passing after WooCommerce has
changed underneath it, which is the one failure worth catching here. WP_DEBUG
is on and any notice logged from this plugin's directory fails the build,
because that is the shape an upgrade actually breaks in — nothing fails, a
notice appears, and two releases later it is a fatal.

compat.yml runs that weekly against today's releases, the next WordPress and
the next WooCommerce, the oldest PHP the header promises and the newest PHP.
When it is green it opens a PR bumping "Tested up to" and "WC tested up to" —
only when green, because WooCommerce shows that second value to the shop owner
as an untested-plugin banner, and that banner is what they read before deciding
whether to press update.

includes/class-updater.php is the distribution half. It hooks
update_plugins_{hostname} for the host in the new "Update URI" header and reads
the Gitea release API, so WordPress handles the notice, the download, the
"Enable auto-updates" link and wp plugin update with no further code. Update
URI earns its place twice: since 5.8 a plugin that declares one is never asked
about on wordpress.org, so a .org plugin sharing this slug cannot be pushed
onto a shop running this one. The check sends nothing about the site and
overrides WordPress's default user agent, which carries the site's own URL.

release.yml tags, tests, builds, publishes — then reads the feed back with no
credentials. A private repository and a release with no zip attached both leave
a page that looks perfect to anyone logged in and an update no shop is ever
offered.

Measured before committing, all green: WP 7.1 + WC 11.1 on PHP 8.3 and 7.4,
WP 7.2-alpha on 8.3, and the beta cell falling back to stable on 8.4. No
deprecations from this plugin on any of them.

Three guards are there because the bug they catch is invisible without them:
the annotated tag is re-fetched before its message is read (checkout turns it
into a lightweight tag pointing at the merge commit), the two workflow roots
are kept in sync (.gitea/workflows hides .github/workflows entirely), and every
file the code loads must be in the release zip — which caught class-updater.php
being referenced and uncommitted while every local test passed.

docs/REUSE.md is the port to the next plugin: copy ci/, rewrite five lines.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-16 10:34:38 +02:00

243 lines
7.1 KiB
PHP

<?php
/**
* Updates from the plugin's own release feed.
*
* WordPress only offers updates for plugins it knows a source for. This is
* that source: the Gitea repository named in the plugin header's "Update URI".
*
* It hooks `update_plugins_{$hostname}` rather than rewriting the update
* transient by hand. That filter is the supported path since WordPress 5.8 and
* it brings one guarantee worth more than the tidiness: a plugin with an
* "Update URI" pointing away from wordpress.org is never asked about there, so
* a .org plugin that happens to share this slug can never be pushed onto a
* shop running this one.
*
* Nothing about the site is sent. The request is a plain unauthenticated GET
* for a file every visitor to that repository can read, and the user agent is
* overridden because WordPress's default one carries the site's own URL in it.
*
* @package WC_Email_Discount_Manager
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Offers releases from the repository named in the plugin header.
*/
class WC_EDM_Updater {
/**
* Where the answer is cached between checks.
*/
const TRANSIENT = 'wc_edm_release_feed';
/**
* How long that cache lives. WordPress checks for updates twice a day; a
* shorter window would only add requests, a longer one would delay a fix.
*/
const TTL = 6 * HOUR_IN_SECONDS;
/**
* Hook into the update check for our own host only.
*/
public function __construct() {
$host = $this->host();
if ( ! $host ) {
return;
}
add_filter( "update_plugins_{$host}", array( $this, 'offer_update' ), 10, 2 );
// Without this the old answer is served for up to six hours after an
// update, and the plugins screen keeps offering a version already
// installed.
add_action( 'upgrader_process_complete', array( $this, 'forget' ), 10, 0 );
}
/**
* The repository this plugin updates from, as stated in its own header.
*
* @return string
*/
public static function update_uri() {
$data = get_file_data( WC_EDM_PLUGIN_FILE, array( 'uri' => 'Update URI' ) );
return isset( $data['uri'] ) ? trim( $data['uri'] ) : '';
}
/**
* Hostname of the update URI, or an empty string when there is none.
*
* @return string
*/
private function host() {
$host = wp_parse_url( self::update_uri(), PHP_URL_HOST );
return is_string( $host ) ? $host : '';
}
/**
* Answer WordPress's update check for this plugin.
*
* Always returns what the feed says, even when it is the version already
* installed: WordPress compares the versions itself, and a plugin that
* answers "no update" by returning false never appears in the no_update
* list — which is what the "Enable auto-updates" link on the plugins
* screen is built from. Staying silent here is how a plugin ends up
* unable to auto-update while looking perfectly configured.
*
* @param array|false $update Update offered so far.
* @param array $plugin_data Headers of the installed plugin.
* @return array|false
*/
public function offer_update( $update, $plugin_data ) {
$release = $this->latest_release();
if ( ! $release ) {
return $update;
}
return array(
'slug' => dirname( plugin_basename( WC_EDM_PLUGIN_FILE ) ),
'version' => $release['version'],
'package' => $release['package'],
'url' => $release['url'],
'tested' => $release['tested'],
'requires' => isset( $plugin_data['RequiresWP'] ) ? $plugin_data['RequiresWP'] : '',
'requires_php' => isset( $plugin_data['RequiresPHP'] ) ? $plugin_data['RequiresPHP'] : '',
);
}
/**
* Drop the cached feed.
*/
public function forget() {
delete_transient( self::TRANSIENT );
}
/**
* Read the newest release from the repository.
*
* @return array|null { version, package, url, tested }, or null.
*/
private function latest_release() {
$cached = get_transient( self::TRANSIENT );
if ( is_array( $cached ) ) {
return $cached;
}
if ( 'none' === $cached ) {
// A failure is cached too, briefly. Otherwise an unreachable host
// turns every admin page load into a blocking HTTP request.
return null;
}
$uri = self::update_uri();
$api = $this->api_url( $uri );
if ( ! $api ) {
return null;
}
$response = wp_remote_get(
$api,
array(
'timeout' => 10,
'headers' => array( 'Accept' => 'application/json' ),
// WordPress's default user agent is
// "WordPress/6.8; https://the-shop.example" — it would tell
// the update host which shops are running this plugin. This
// plugin does not report that anywhere, so it must not leak
// it here either.
'user-agent' => 'wc-email-discount-manager updater',
)
);
if ( is_wp_error( $response ) || 200 !== (int) wp_remote_retrieve_response_code( $response ) ) {
set_transient( self::TRANSIENT, 'none', 15 * MINUTE_IN_SECONDS );
return null;
}
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( ! is_array( $body ) || empty( $body['tag_name'] ) ) {
set_transient( self::TRANSIENT, 'none', 15 * MINUTE_IN_SECONDS );
return null;
}
$package = '';
$tested = '';
foreach ( isset( $body['assets'] ) ? $body['assets'] : array() as $asset ) {
if ( empty( $asset['name'] ) || empty( $asset['browser_download_url'] ) ) {
continue;
}
if ( substr( $asset['name'], -4 ) === '.zip' ) {
$package = $asset['browser_download_url'];
}
}
// The release notes carry the compatibility line the release workflow
// writes, so wp-admin can show what this version was actually tested
// against instead of what the previous one claimed.
if ( ! empty( $body['body'] ) && preg_match( '/^Tested up to:\s*(\S+)/mi', $body['body'], $m ) ) {
$tested = $m[1];
}
if ( '' === $package ) {
// A release with no zip attached is a half-finished release.
// Offering it would hand WordPress a download it cannot install.
set_transient( self::TRANSIENT, 'none', 15 * MINUTE_IN_SECONDS );
return null;
}
$release = array(
'version' => ltrim( $body['tag_name'], 'vV' ),
'package' => $package,
'url' => ! empty( $body['html_url'] ) ? $body['html_url'] : $uri,
'tested' => $tested,
);
set_transient( self::TRANSIENT, $release, self::TTL );
return $release;
}
/**
* Turn the repository's web address into its "latest release" API address.
*
* https://gitea.example/owner/repo
* -> https://gitea.example/api/v1/repos/owner/repo/releases/latest
*
* Derived rather than configured, so the plugin header stays the single
* place that says where updates come from.
*
* @param string $uri Repository web address.
* @return string Empty when the address is not a repository address.
*/
private function api_url( $uri ) {
$parts = wp_parse_url( $uri );
if ( empty( $parts['scheme'] ) || empty( $parts['host'] ) || empty( $parts['path'] ) ) {
return '';
}
$segments = array_values( array_filter( explode( '/', $parts['path'] ) ) );
if ( count( $segments ) < 2 ) {
return '';
}
return sprintf(
'%s://%s/api/v1/repos/%s/%s/releases/latest',
$parts['scheme'],
$parts['host'],
rawurlencode( $segments[0] ),
rawurlencode( $segments[1] )
);
}
}