updater options

This commit is contained in:
parkel committed 2026-11-18 01:46:55 +01:00
1 parent 54042efb44
commit 50a4dd2ad6
3 files changed
+324 -3

No files matched your search

+4 -2
View File
@@ -2,13 +2,15 @@
/**
* Plugin Name: HG Contactformulier
* Description: Configureerbaar contactformulier met workflows en talen vanuit de website, zonder inzendingen op te slaan.
* Version: 1.4.1
* Version: 1.4.2
* Update URI: https://code.hosting.hippogrief.nl/hippogrief/wp-plugins/src/branch/main/hg_contactform
* Requires at least: 6.5
* Requires PHP: 8.1
* Text Domain: hg-contactform
*/
if (!defined('ABSPATH')) { exit; }
define('HGCF_VERSION','1.4.1');
require_once __DIR__ . '/includes/hg-plugin-updates.php';
define('HGCF_VERSION','1.4.2');
define('HGCF_FILE',__FILE__);
require_once __DIR__.'/includes/hg-admin-menu.php';
require_once __DIR__.'/includes/settings.php';
+317
View File
@@ -0,0 +1,317 @@
<?php
/** HG release updates, bundled identically in each standalone HG plugin. */
if (!defined('ABSPATH')) exit;
if (!class_exists('HG_Plugin_Updates_1_0_0', false)) {
// Bump this class suffix and VERSION together when changing the bundled updater.
final class HG_Plugin_Updates_1_0_0 {
private const VERSION = '1.0.0';
private const REPOSITORY = 'https://code.hosting.hippogrief.nl/hippogrief/wp-plugins';
private const RELEASE_API = 'https://code.hosting.hippogrief.nl/api/v1/repos/hippogrief/wp-plugins/releases';
private const CACHE = 'hg_plugin_releases';
private const PAGE = 'hg-plugin-updates';
private const MODULES = [
'hg-contactform' => ['HG Contactformulier', 'hg-contactform'],
'hg-hephaestusaperture' => ['HG Hephaestus Aperture', 'hg-hephaestusaperture'],
'hg-registrations' => ['HG Inschrijvingen', 'hg-registrations'],
'hg-socialfeed' => ['HG Social Feed', 'hg_socialfeed'],
];
private static array $downloads = [];
public static function prefer(array $selected): array {
return version_compare(self::VERSION, $selected['version'], '>')
? ['class' => self::class, 'version' => self::VERSION]
: $selected;
}
public static function boot(): void {
$selected = apply_filters('hg_plugin_updates_implementation', ['class' => '', 'version' => '0']);
if ($selected['class'] !== self::class) return;
add_filter('update_plugins_code.hosting.hippogrief.nl', [self::class, 'native_update'], 10, 3);
add_filter('upgrader_pre_download', [self::class, 'verify_download'], 10, 4);
add_filter('upgrader_source_selection', [self::class, 'verify_package'], 9, 4);
add_filter('http_request_args', [self::class, 'download_args'], 10, 2);
add_action('admin_menu', [self::class, 'menu'], 21);
add_action('admin_post_hg_plugin_updates_refresh', [self::class, 'refresh']);
}
private static function package_base(): string {
return self::REPOSITORY . '/releases/download/';
}
private static function update_uri(string $slug): string {
return self::REPOSITORY . '/src/branch/main/' . str_replace('-', '_', $slug);
}
private static function module(string $file, array $data): ?string {
$slug = basename($file, '.php');
if (!isset(self::MODULES[$slug]) || dirname($file) === '.' || basename($file) !== "$slug.php" || validate_file($file) !== 0) {
return null;
}
$uri = $data['UpdateURI'] ?? '';
// Recognize installed releases from before the updater was bundled.
if ($uri === self::update_uri($slug) || ($uri === '' && ($data['Name'] ?? '') === self::MODULES[$slug][0])) {
return $slug;
}
return null;
}
private static function releases(bool $refresh = false): array {
$cached = get_site_transient(self::CACHE);
if (!$refresh && is_array($cached)) {
return $cached;
}
$result = self::fetch_releases();
set_site_transient(self::CACHE, $result, $result['error'] ? 5 * MINUTE_IN_SECONDS : 6 * HOUR_IN_SECONDS);
return $result;
}
private static function fetch_releases(): array {
$updates = [];
$limit = 50;
for ($page = 1; $page <= 20; $page++) {
$response = wp_safe_remote_get(add_query_arg(['limit' => $limit, 'page' => $page], self::RELEASE_API), [
'headers' => ['Accept' => 'application/json'],
'timeout' => 5,
'redirection' => 0,
'limit_response_size' => 2 * MB_IN_BYTES,
]);
$status = (int) wp_remote_retrieve_response_code($response);
$body = wp_remote_retrieve_body($response);
$releases = json_decode($body, true);
if ($status !== 200 || !is_array($releases) || !str_starts_with(ltrim($body), '[')) {
return ['error' => $status === 404 ? 'Ontoegankelijk' : 'Onbereikbaar', 'updates' => []];
}
foreach ($releases as $release) {
self::add_release($release, $updates);
}
$link = wp_remote_retrieve_header($response, 'link');
if (count($releases) < $limit && !str_contains(implode(',', (array) $link), 'rel="next"')) {
return ['error' => '', 'updates' => $updates];
}
}
return ['error' => 'Onbereikbaar', 'updates' => []];
}
private static function add_release(mixed $release, array &$updates): void {
if (!is_array($release) || ($release['draft'] ?? null) !== false || ($release['prerelease'] ?? null) !== false) {
return;
}
$tag = $release['tag_name'] ?? '';
$assets = $release['assets'] ?? null;
if (!is_string($tag) || !is_array($assets) || !preg_match('/^([a-z-]+)-v([0-9]+\.[0-9]+\.[0-9]+)$/D', $tag, $matches)) {
return;
}
[, $slug, $version] = $matches;
if (!isset(self::MODULES[$slug]) || (isset($updates[$slug]) && version_compare($version, $updates[$slug]['version'], '<='))) {
return;
}
$asset_urls = [];
foreach ($assets as $asset) {
$name = $asset['name'] ?? '';
if ($name !== "$slug-$version.zip" && $name !== "$slug.zip") continue;
$package = self::package_base() . "$tag/$name";
if (($asset['browser_download_url'] ?? '') === $package) {
$asset_urls[$name] = $package;
}
}
$package = $asset_urls["$slug-$version.zip"] ?? $asset_urls["$slug.zip"] ?? null;
if ($package) {
$updates[$slug] = [
'id' => self::update_uri($slug),
'slug' => $slug,
'version' => $version,
'new_version' => $version,
'url' => self::REPOSITORY . '/releases/tag/' . $tag,
'package' => $package,
];
}
}
public static function native_update($update, array $data, string $file) {
$slug = self::module($file, $data);
if (!$slug) return $update;
// WordPress can run its own update check during an anonymous admin-post request.
$can_fetch = wp_doing_cron() || current_user_can('update_plugins') || (defined('WP_CLI') && WP_CLI);
$releases = $can_fetch ? self::releases() : get_site_transient(self::CACHE);
return $releases['updates'][$slug] ?? $update;
}
private static function sync_updates(array $plugins, array $releases): void {
$transient = get_site_transient('update_plugins');
$transient = is_object($transient) ? clone $transient : new stdClass();
$previous = $transient->response ?? [];
$previous_no_update = $transient->no_update ?? [];
$transient->response = $previous;
$transient->no_update = $previous_no_update;
foreach ($plugins as $file => $data) {
$release = $releases[$data['slug']] ?? null;
if ($release && version_compare($release['version'], $data['Version'], '>')) {
$transient->response[$file] = (object) ($release + ['plugin' => $file]);
unset($transient->no_update[$file]);
} else {
unset($transient->response[$file]);
}
}
if ($previous != $transient->response || $previous_no_update != $transient->no_update) {
set_site_transient('update_plugins', $transient);
}
}
private static function installed(): array {
$installed = [];
foreach (get_plugins() as $file => $data) {
$slug = self::module($file, $data);
if ($slug) {
$installed[$file] = $data + ['slug' => $slug];
}
}
uasort($installed, static fn ($a, $b) => strcasecmp($a['Name'], $b['Name']));
return $installed;
}
public static function verify_download($reply, string $package, $upgrader, array $context) {
// WordPress bulk updates pass the plugin file without an action or type in this hook.
$file = $context['plugin'] ?? '';
if (is_wp_error($reply) || $file === '' || !str_starts_with($package, self::package_base())) {
return $reply;
}
$data = get_plugins()[$file] ?? [];
$slug = self::module($file, $data);
$release = $slug ? self::releases()['updates'][$slug] ?? null : null;
if (!$release || $package !== $release['package'] || !version_compare($release['version'], $data['Version'], '>')) {
return new WP_Error('hg_update_unavailable', 'Deze HG-update is niet meer beschikbaar. Controleer opnieuw op updates.');
}
// Keep a working installation active if native single-plugin validation rejects the update.
remove_filter('upgrader_pre_install', [$upgrader, 'deactivate_plugin_before_upgrade']);
self::$downloads[$file] = $release;
return $reply;
}
public static function download_args(array $args, string $url): array {
if (str_starts_with($url, self::package_base())) {
$args['redirection'] = 0;
}
return $args;
}
public static function verify_package($source, string $remote_source, $upgrader, array $context) {
global $wp_filesystem;
$file = $context['plugin'] ?? '';
$release = self::$downloads[$file] ?? null;
if (!$release || is_wp_error($source)) {
return $source;
}
unset(self::$downloads[$file]);
$slug = $release['slug'];
$source = trailingslashit($source);
$contents = $wp_filesystem->get_contents($source . basename($file));
$headers = str_replace("\r", "\n", substr((string) $contents, 0, 8 * KB_IN_BYTES));
$read = static function (string $field) use ($headers): string {
preg_match('/^(?:[ \t]*<\?php)?[ \t\/*#@]*' . $field . ':(.*)$/mi', $headers, $matches);
return _cleanup_header_comment($matches[1] ?? '');
};
if (basename($source) !== self::MODULES[$slug][1] || !$read('Plugin Name')
|| $read('Version') !== $release['version'] || $read('Update URI') !== $release['id']) {
return new WP_Error('hg_update_package', 'Het ZIP-bestand komt niet overeen met de gekozen HG-release.');
}
if (!is_php_version_compatible($read('Requires PHP')) || !is_wp_version_compatible($read('Requires at least'))) {
return new WP_Error('hg_update_requirements', 'Deze HG-release vereist een nieuwere versie van WordPress of PHP.');
}
// Keep the active plugin basename when an existing installation renamed its directory.
if (basename($source) !== dirname($file)) {
$destination = trailingslashit($remote_source) . dirname($file);
if (!$wp_filesystem->move(untrailingslashit($source), $destination)) {
return new WP_Error('hg_update_directory', 'De bestaande plug-inmap kon niet worden behouden.');
}
return trailingslashit($destination);
}
return $source;
}
public static function menu(): void {
add_submenu_page('hg-plugins', 'HG Plugin-updates', 'Updates', 'update_plugins', self::PAGE, [self::class, 'screen']);
}
private static function authorize(): void {
if (!current_user_can('manage_options') || !current_user_can('update_plugins')) {
wp_die('Geen toegang.', '', ['response' => 403]);
}
}
public static function refresh(): void {
self::authorize();
if (($_SERVER['REQUEST_METHOD'] ?? '') !== 'POST') {
wp_die('Ongeldig verzoek.', '', ['response' => 405]);
}
check_admin_referer('hg_plugin_updates_refresh');
$releases = self::releases(true);
self::sync_updates(self::installed(), $releases['updates']);
wp_safe_redirect(add_query_arg('page', self::PAGE, admin_url('admin.php')), 303);
exit;
}
public static function screen(): void {
self::authorize();
$plugins = self::installed();
$releases = self::releases();
self::sync_updates($plugins, $releases['updates']);
?>
<div class="wrap hg-suite">
<header class="hg-suite-header">
<span class="hg-suite-mark" aria-hidden="true">HG</span>
<div><h1>HG Plugin-updates</h1><p>Controleer de geïnstalleerde HG-plug-ins op nieuwe releases.</p></div>
</header>
<hr class="wp-header-end">
<?php if ($releases['error']) : ?>
<div class="notice notice-warning inline"><p><?php echo $releases['error'] === 'Ontoegankelijk'
? 'De releasebron is niet openbaar toegankelijk. Probeer het opnieuw zodra de repository en releases openbaar zijn.'
: 'De releases konden niet worden opgehaald. Probeer het later opnieuw.'; ?></p></div>
<?php endif; ?>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>">
<input type="hidden" name="action" value="hg_plugin_updates_refresh">
<?php wp_nonce_field('hg_plugin_updates_refresh'); ?>
<p><button type="submit" class="button button-primary">Op updates controleren</button>
<a class="button" href="<?php echo esc_url(self::REPOSITORY . '/releases'); ?>">Releases bekijken</a></p>
</form>
<div style="overflow-x:auto" role="region" aria-label="Geïnstalleerde HG-plug-ins" tabindex="0">
<table class="widefat striped">
<thead><tr><th scope="col">Plug-in</th><th scope="col">Geïnstalleerd</th><th scope="col">Laatste release</th><th scope="col">Status</th></tr></thead>
<tbody>
<?php foreach ($plugins as $file => $plugin) :
$release = $releases['updates'][$plugin['slug']] ?? null;
$available = $release && version_compare($release['version'], $plugin['Version'], '>');
?>
<tr>
<th scope="row"><?php echo esc_html($plugin['Name']); ?></th>
<td><?php echo esc_html($plugin['Version']); ?></td>
<td><?php if ($release) : ?><a href="<?php echo esc_url($release['url']); ?>"><?php echo esc_html($release['version']); ?></a><?php else : ?>—<?php endif; ?></td>
<td>
<?php if ($available) : ?>
<?php // The bulk upgrader keeps the active state even when updating one plugin. ?>
<a class="button" aria-label="<?php echo esc_attr($plugin['Name'] . ' bijwerken'); ?>" href="<?php echo esc_url(wp_nonce_url(add_query_arg([
'action' => 'update-selected', 'plugins' => $file,
], network_admin_url('update.php')), 'bulk-update-plugins')); ?>">Nu bijwerken</a>
<?php elseif ($release) : ?>Actueel
<?php elseif ($releases['error']) : ?>Onbekend
<?php else : ?>Geen installatiepakket
<?php endif; ?>
</td>
</tr>
<?php endforeach; ?>
</tbody>
</table>
</div>
</div>
<?php
}
}
add_filter('hg_plugin_updates_implementation', [HG_Plugin_Updates_1_0_0::class, 'prefer']);
add_action('plugins_loaded', [HG_Plugin_Updates_1_0_0::class, 'boot'], 5);
}
+3 -1
View File
@@ -1,7 +1,7 @@
=== HG Contactformulier ===
Requires at least: 6.5
Requires PHP: 8.1
Stable tag: 1.4.1
Stable tag: 1.4.2
License: GPLv2 or later
Contactformulier met workflows, talen en optionele lokaal gehoste ALTCHA-antispamcontrole.
@@ -10,6 +10,8 @@ Contactformulier met workflows, talen en optionele lokaal gehoste ALTCHA-antispa
Upload en activeer de plugin. Stel HG Plugins → Contactformulier in de beheerzijbalk in en plaats [hg_contactform] op een pagina.
== Changelog ==
= 1.4.2 =
Openbare releases controleren via HG Plugins → Updates.
= 1.4.1 =
Een actieve workflow vooraf kiezen via de contactlink; ongeldige keuzes vallen veilig terug op de standaard.
= 1.4.0 =