From 4cec93067c472d8647a545bf6ff5e3a7e375ac8d Mon Sep 17 00:00:00 2001 From: Josh Knapp Date: Sun, 15 Nov 2026 11:53:42 -0800 Subject: [PATCH] Add in-WordPress updater: checks Gitea releases, one-click and auto updates - Update\ReleaseParser (pure, host-pinned, https only) and Update\Updater (WP hooks, cached, failure-safe) - Settings: optional access token for a private repo, 'Check for updates now' Co-Authored-By: Claude Sonnet 5.5 --- README.md | 6 + includes/Admin/SettingsPage.php | 14 ++ includes/Core/Plugin.php | 1 + includes/Core/Settings.php | 1 + includes/Update/ReleaseParser.php | 137 +++++++++++++++++ includes/Update/Updater.php | 201 +++++++++++++++++++++++++ tests/Unit/UpdateReleaseParserTest.php | 93 ++++++++++++ 7 files changed, 453 insertions(+) create mode 100644 includes/Update/ReleaseParser.php create mode 100644 includes/Update/Updater.php create mode 100644 tests/Unit/UpdateReleaseParserTest.php diff --git a/README.md b/README.md index 5928b86..cdce8cf 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,12 @@ with the Live credentials and switch the mode to Live in Settings. - **Refunds and chargebacks are not tracked.** If you refund someone in PayPal, goal totals, timers and counters are not adjusted. +## Updates +New versions appear in WordPress automatically (Dashboard > Updates and the Plugins screen). If the update +repository is private, paste an access token with read access to releases in +StreamGoals > Settings > Advanced > Plugin updates. You can switch automatic updates on or off for this plugin +on the Plugins screen. + ## Development ``` composer install diff --git a/includes/Admin/SettingsPage.php b/includes/Admin/SettingsPage.php index 2d03681..113ab00 100644 --- a/includes/Admin/SettingsPage.php +++ b/includes/Admin/SettingsPage.php @@ -60,11 +60,21 @@ final class SettingsPage { self::ipDiagnostics( (string) $s['visitor_ip_header'] ); echo ''; + $rel = \StreamGoals\Update\Updater::latest(); + echo '

Plugin updates

'; + echo ''; + echo ''; + echo '
'; + echo '

PayPal fee estimate

'; echo '

When a donor chooses "cover the fees", the form adds the estimated PayPal fee so you receive the amount they intended. The defaults (3.49% + $0.49) are US domestic estimates. Fees for international (cross-border) payments and currency conversion are higher and are not included, so you may receive slightly less than expected in those cases. Check PayPal\'s current fee page for your country and adjust.

'; echo ''; echo '
'; echo '

'; + echo '
'; + wp_nonce_field( \StreamGoals\Update\Updater::ACTION_CHECK ); + echo '
'; Admin::close(); } @@ -129,6 +139,10 @@ final class SettingsPage { } else { $upd['visitor_ip_header'] = $ipMode; } + $tok = $post['update_token'] ?? ''; + if ( ! Input::secretUnchanged( is_string( $tok ) ? $tok : '' ) ) { + $upd['update_token'] = Input::text( $tok, 300 ); + } $upd['funding_card'] = ! empty( $post['funding_card'] ); $upd['funding_paylater'] = ! empty( $post['funding_paylater'] ); $upd['moderate_messages'] = ! empty( $post['moderate_messages'] ); diff --git a/includes/Core/Plugin.php b/includes/Core/Plugin.php index 114f409..54d5298 100644 --- a/includes/Core/Plugin.php +++ b/includes/Core/Plugin.php @@ -14,6 +14,7 @@ final class Plugin { \StreamGoals\Rest\WebhookController::class, \StreamGoals\Rest\OverlayController::class, \StreamGoals\Admin\Admin::class, + \StreamGoals\Update\Updater::class, ); public static function boot(): void { diff --git a/includes/Core/Settings.php b/includes/Core/Settings.php index 070a7fc..3c4635c 100644 --- a/includes/Core/Settings.php +++ b/includes/Core/Settings.php @@ -37,6 +37,7 @@ final class Settings { 'overlay_token' => '', 'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp) 'funding_paylater' => false, // show PayPal "Pay Later" button + 'update_token' => '', // optional Gitea read token (only while the update repo is private) 'funding_card' => true, // show the Debit/Credit Card button ); } diff --git a/includes/Update/ReleaseParser.php b/includes/Update/ReleaseParser.php new file mode 100644 index 0000000..7393fec --- /dev/null +++ b/includes/Update/ReleaseParser.php @@ -0,0 +1,137 @@ + $version, + 'package' => $package, + 'url' => is_string( $url ) && self::isAllowedUrl( $url, $host ) ? $url : '', + 'notes' => is_string( $release['body'] ?? null ) ? $release['body'] : '', + 'published' => is_string( $release['published_at'] ?? null ) ? $release['published_at'] : '', + ); + } + + public static function normalizeVersion( mixed $tag ): ?string { + if ( ! is_string( $tag ) ) { + return null; + } + $t = trim( $tag ); + if ( '' !== $t && ( 'v' === $t[0] || 'V' === $t[0] ) ) { + $t = substr( $t, 1 ); + } + return 1 === preg_match( self::DATE_TAG, $t ) || 1 === preg_match( self::SEMVER, $t ) ? $t : null; + } + + public static function isNewer( string $remote, string $current ): bool { + $r = self::normalizeVersion( $remote ); + if ( null === $r ) { + return false; + } + return version_compare( $r, ltrim( $current, 'vV' ), '>' ); + } + + /** https URL on exactly the configured host (no userinfo tricks). */ + public static function isAllowedUrl( string $url, string $host ): bool { + $p = parse_url( $url ); + if ( ! is_array( $p ) || ! isset( $p['scheme'], $p['host'] ) || isset( $p['user'] ) || isset( $p['pass'] ) ) { + return false; + } + return 'https' === strtolower( $p['scheme'] ) && '' !== $host && strtolower( $p['host'] ) === strtolower( $host ); + } + + private static function pickPackage( array $assets, string $host ): ?string { + $exact = null; + $first = null; + foreach ( $assets as $a ) { + if ( ! is_array( $a ) || ! is_string( $a['name'] ?? null ) || ! is_string( $a['browser_download_url'] ?? null ) ) { + continue; + } + if ( ! self::isAllowedUrl( $a['browser_download_url'], $host ) ) { + continue; + } + if ( self::ASSET_NAME === $a['name'] ) { + $exact = $exact ?? $a['browser_download_url']; + } elseif ( null === $first && str_ends_with( strtolower( $a['name'] ), '.zip' ) ) { + $first = $a['browser_download_url']; + } + } + return $exact ?? $first; + } + + /** Minimal markdown to safe HTML: everything is escaped first; only paragraphs, headings (as

) and lists. */ + public static function changelogHtml( string $markdown ): string { + $lines = preg_split( '/\r\n|\r|\n/', $markdown ) ?: array(); + $out = ''; + $list = false; + $para = array(); + $flush = static function () use ( &$out, &$para ): void { + if ( $para ) { + $out .= '

' . implode( ' ', $para ) . '

'; + $para = array(); + } + }; + foreach ( $lines as $line ) { + $t = trim( $line ); + if ( 1 === preg_match( '/^[*\-+]\s+(.*)$/', $t, $m ) ) { + $flush(); + if ( ! $list ) { + $out .= '
    '; + $list = true; + } + $out .= '
  • ' . self::esc( $m[1] ) . '
  • '; + continue; + } + if ( $list ) { + $out .= '
'; + $list = false; + } + if ( '' === $t ) { + $flush(); + } elseif ( 1 === preg_match( '/^#{1,6}\s+(.*)$/', $t, $m ) ) { + $flush(); + $out .= '

' . self::esc( $m[1] ) . '

'; + } else { + $para[] = self::esc( $t ); + } + } + $flush(); + if ( $list ) { + $out .= ''; + } + return $out; + } + + private static function esc( string $s ): string { + return htmlspecialchars( $s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8' ); + } +} diff --git a/includes/Update/Updater.php b/includes/Update/Updater.php new file mode 100644 index 0000000..33bba7a --- /dev/null +++ b/includes/Update/Updater.php @@ -0,0 +1,201 @@ + self::BASE_URL, 'owner' => self::OWNER, 'repo' => self::REPO ) ); + $r = is_array( $r ) ? $r : array(); + $base = rtrim( is_string( $r['base'] ?? null ) ? $r['base'] : self::BASE_URL, '/' ); + $host = parse_url( $base, PHP_URL_HOST ); + return array( + 'base' => $base, + 'owner' => is_string( $r['owner'] ?? null ) ? $r['owner'] : self::OWNER, + 'repo' => is_string( $r['repo'] ?? null ) ? $r['repo'] : self::REPO, + 'host' => is_string( $host ) ? strtolower( $host ) : '', + ); + } + + /** + * Cached latest release (parsed) or null. Failures are cached briefly so WP never re-hits a broken endpoint. + * + * @return array{version:string,package:string,url:string,notes:string,published:string}|null + */ + public static function latest( bool $force = false ): ?array { + try { + if ( ! $force ) { + $c = get_site_transient( self::CACHE_KEY ); + if ( is_array( $c ) && array_key_exists( 'release', $c ) ) { + return is_array( $c['release'] ) ? $c['release'] : null; + } + } + $release = self::fetch(); + set_site_transient( self::CACHE_KEY, array( 'release' => $release ), null === $release ? self::CACHE_FAIL : self::CACHE_OK ); + return $release; + } catch ( \Throwable $e ) { + return null; + } + } + + public static function clearCache(): void { + delete_site_transient( self::CACHE_KEY ); + } + + private static function fetch(): ?array { + $repo = self::repo(); + if ( '' === $repo['host'] || 'https' !== strtolower( (string) parse_url( $repo['base'], PHP_URL_SCHEME ) ) ) { + return null; + } + $url = $repo['base'] . '/api/v1/repos/' . rawurlencode( $repo['owner'] ) . '/' . rawurlencode( $repo['repo'] ) . '/releases/latest'; + $resp = wp_remote_get( $url, array( 'timeout' => self::TIMEOUT, 'redirection' => 2, 'headers' => array( 'Accept' => 'application/json' ) ) ); + if ( is_wp_error( $resp ) || 200 !== (int) wp_remote_retrieve_response_code( $resp ) ) { + return null; + } + $data = json_decode( (string) wp_remote_retrieve_body( $resp ), true ); + return is_array( $data ) ? ReleaseParser::parse( $data, $repo['host'] ) : null; + } + + public static function pluginFile(): string { + return plugin_basename( STREAMGOALS_FILE ); + } + + private static function entry( array $rel ): object { + $e = new \stdClass(); + $e->id = $rel['url'] ?: self::BASE_URL; + $e->slug = self::SLUG; + $e->plugin = self::pluginFile(); + $e->new_version = $rel['version']; + $e->url = $rel['url']; + $e->package = $rel['package']; + $e->requires = '6.8'; + $e->requires_php = '8.1'; + return $e; + } + + public static function inject( mixed $transient ): mixed { + try { + if ( ! is_object( $transient ) ) { + return $transient; + } + $rel = self::latest(); + $file = self::pluginFile(); + unset( $transient->response[ $file ], $transient->no_update[ $file ] ); + if ( null === $rel ) { + return $transient; + } + $entry = self::entry( $rel ); + if ( ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ) { + $transient->response = is_array( $transient->response ?? null ) ? $transient->response : array(); + $transient->response[ $file ] = $entry; + } else { + $entry->new_version = STREAMGOALS_VERSION; + $transient->no_update = is_array( $transient->no_update ?? null ) ? $transient->no_update : array(); + $transient->no_update[ $file ] = $entry; + } + } catch ( \Throwable $e ) { + // Never break the Updates screen. + } + return $transient; + } + + public static function pluginInfo( mixed $result, mixed $action = '', mixed $args = null ): mixed { + try { + if ( 'plugin_information' !== $action || ! is_object( $args ) || ( $args->slug ?? '' ) !== self::SLUG ) { + return $result; + } + $rel = self::latest(); + if ( null === $rel ) { + return $result; + } + $i = new \stdClass(); + $i->name = 'StreamGoals Donate'; + $i->slug = self::SLUG; + $i->version = $rel['version']; + $i->author = 'StreamGoals'; + $i->homepage = $rel['url']; + $i->requires = '6.8'; + $i->requires_php = '8.1'; + $i->last_updated = $rel['published']; + $i->download_link = $rel['package']; + $i->sections = array( + 'description' => 'PayPal donations with multiple goals, fee coverage, and OBS stream overlays.', + 'changelog' => '' !== $rel['notes'] ? ReleaseParser::changelogHtml( $rel['notes'] ) : '

No release notes.

', + ); + return $i; + } catch ( \Throwable $e ) { + return $result; + } + } + + /** Adds the token ONLY for https requests to the configured Gitea host. */ + public static function authorize( mixed $args, mixed $url ): mixed { + try { + if ( ! is_array( $args ) || ! is_string( $url ) ) { + return $args; + } + $token = trim( (string) Settings::get( 'update_token', '' ) ); + $host = self::repo()['host']; + if ( '' === $token || ! ReleaseParser::isAllowedUrl( $url, $host ) ) { + return $args; + } + $args['headers'] = is_array( $args['headers'] ?? null ) ? $args['headers'] : array(); + $args['headers']['Authorization'] = 'token ' . $token; + } catch ( \Throwable $e ) { + // Fall through without credentials. + } + return $args; + } + + public static function afterUpgrade( mixed $upgrader, mixed $options ): void { + if ( is_array( $options ) && ( $options['type'] ?? '' ) === 'plugin' ) { + self::clearCache(); + } + } + + public static function handleCheck(): void { + Admin::guard( self::ACTION_CHECK ); + self::clearCache(); + delete_site_transient( 'update_plugins' ); + $rel = self::latest( true ); + $back = Admin::url( 'streamgoals-settings' ); + if ( null === $rel ) { + Admin::redirect( $back, 'warning', 'Could not read the latest release. Check your connection and, if the update repository is private, the access token.' ); + } + Admin::redirect( $back, 'success', ReleaseParser::isNewer( $rel['version'], STREAMGOALS_VERSION ) ? 'Version ' . $rel['version'] . ' is available. See Dashboard > Updates.' : 'You are up to date.' ); + } +} diff --git a/tests/Unit/UpdateReleaseParserTest.php b/tests/Unit/UpdateReleaseParserTest.php new file mode 100644 index 0000000..1929b7e --- /dev/null +++ b/tests/Unit/UpdateReleaseParserTest.php @@ -0,0 +1,93 @@ + '2026.11.15-1941', + 'draft' => false, + 'prerelease' => false, + 'body' => "## What's New\n\n* one\n* two", + 'html_url' => 'https://repo.anhonesthost.net/wp-plugins/wp-donations/releases/tag/2026.11.15-1941', + 'published_at' => '2026-11-15T19:41:00Z', + 'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) ), + ), + $over + ); + } + + public function test_valid_release(): void { + $r = ReleaseParser::parse( $this->release(), self::HOST ); + $this->assertSame( '2026.11.15-1941', $r['version'] ); + $this->assertSame( self::ZIP, $r['package'] ); + $this->assertSame( '2026-11-15T19:41:00Z', $r['published'] ); + $this->assertStringContainsString( 'releases/tag', $r['url'] ); + } + + public function test_draft_and_prerelease_ignored(): void { + $this->assertNull( ReleaseParser::parse( $this->release( array( 'draft' => true ) ), self::HOST ) ); + $this->assertNull( ReleaseParser::parse( $this->release( array( 'prerelease' => true ) ), self::HOST ) ); + } + + public function test_bad_tag(): void { + foreach ( array( 'nightly', '2026.1.15-1941', '', null, array() ) as $t ) { + $this->assertNull( ReleaseParser::parse( $this->release( array( 'tag_name' => $t ) ), self::HOST ) ); + } + } + + public function test_v_prefix_and_semver(): void { + $this->assertSame( '2026.11.15-1941', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v2026.11.15-1941' ) ), self::HOST )['version'] ); + $this->assertSame( '1.2.3', ReleaseParser::parse( $this->release( array( 'tag_name' => 'v1.2.3' ) ), self::HOST )['version'] ); + } + + public function test_wrong_host_and_non_https_rejected(): void { + foreach ( array( 'https://evil.example/streamgoals-donate.zip', 'http://repo.anhonesthost.net/x.zip', 'https://repo.anhonesthost.net@evil.example/x.zip', 'https://repo.anhonesthost.net.evil.example/x.zip', '//repo.anhonesthost.net/x.zip' ) as $u ) { + $rel = $this->release( array( 'assets' => array( array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => $u ) ) ) ); + $this->assertNull( ReleaseParser::parse( $rel, self::HOST ), $u ); + } + } + + public function test_missing_asset(): void { + $this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array() ) ), self::HOST ) ); + $this->assertNull( ReleaseParser::parse( $this->release( array( 'assets' => array( array( 'name' => 'notes.txt', 'browser_download_url' => self::ZIP ) ) ) ), self::HOST ) ); + $this->assertNull( ReleaseParser::parse( array( 'tag_name' => '1.0.0' ), self::HOST ) ); + } + + public function test_picks_right_asset(): void { + $other = 'https://repo.anhonesthost.net/dl/other.zip'; + $a = array( array( 'name' => 'source.zip', 'browser_download_url' => $other ), array( 'name' => 'streamgoals-donate.zip', 'browser_download_url' => self::ZIP ) ); + $this->assertSame( self::ZIP, ReleaseParser::parse( $this->release( array( 'assets' => $a ) ), self::HOST )['package'] ); + $this->assertSame( $other, ReleaseParser::parse( $this->release( array( 'assets' => array( $a[0] ) ) ), self::HOST )['package'] ); + } + + public function test_version_comparison(): void { + $this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1830', '2026.11.15-0930' ) ); + $this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-1830' ) ); + $this->assertFalse( ReleaseParser::isNewer( '2026.11.15-0930', '2026.11.15-0930' ) ); + $this->assertTrue( ReleaseParser::isNewer( 'v2026.11.16-0001', '2026.11.15-2359' ) ); + $this->assertTrue( ReleaseParser::isNewer( '2026.11.15-1941', '0.1.0' ) ); + $this->assertFalse( ReleaseParser::isNewer( 'garbage', '0.1.0' ) ); + } + + public function test_changelog_escapes_html(): void { + $h = ReleaseParser::changelogHtml( "\n\n* bold & \"q\"\n* two" ); + $this->assertStringNotContainsString( 'assertStringNotContainsString( '', $h ); + $this->assertStringContainsString( '<script>', $h ); + $this->assertStringContainsString( '
  • <b>bold</b> & "q"
  • two
', $h ); + } + + public function test_changelog_paragraphs_and_headings(): void { + $this->assertSame( '

What's New

a b

  • x
', ReleaseParser::changelogHtml( "## What's New\n\na\nb\n\n- x" ) ); + } +}