Initialize HG shared code and release repository

This commit is contained in:
parkel committed 2026-11-18 15:31:21 +01:00
commit bd66360fb9
10 files changed
+830

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
/* HG navigation only; leave the rest of the WordPress admin color scheme intact. */
#adminmenu #toplevel_page_hg-plugins>a.menu-top{background:#173b37;color:#d8fff3;box-shadow:inset 3px 0 #56d5bb}
#adminmenu #toplevel_page_hg-plugins .wp-menu-image::before{color:#80e9d1}
#adminmenu #toplevel_page_hg-plugins:hover>a.menu-top,#adminmenu #toplevel_page_hg-plugins>a.menu-top:focus{background:#20574e;color:#fff}
#adminmenu #toplevel_page_hg-plugins.wp-has-current-submenu>a.menu-top,#adminmenu #toplevel_page_hg-plugins.current>a.menu-top{background:#126151;color:#fff}
#adminmenu #toplevel_page_hg-plugins .wp-submenu{background:#16332f}
#adminmenu #toplevel_page_hg-plugins .wp-submenu a{color:#d0e6de}
#adminmenu #toplevel_page_hg-plugins .wp-submenu a:hover,#adminmenu #toplevel_page_hg-plugins .wp-submenu a:focus{color:#fff;background:#24584e}
#adminmenu #toplevel_page_hg-plugins .wp-submenu li.current a{color:#fff;font-weight:600;background:#205147}
#adminmenu #toplevel_page_hg-plugins .wp-submenu .wp-submenu-head{color:#fff;background:#126151}
.hg-suite{max-width:1100px}.hg-suite-header{display:flex;align-items:center;gap:18px;margin:28px 0}.hg-suite-header h1{padding:0;font-size:26px}.hg-suite-header p{margin:7px 0 0;color:#50575e}.hg-suite-mark{display:grid;place-items:center;width:58px;height:58px;background:#126151;color:#fff;border-radius:10px;font-weight:750;font-size:21px;letter-spacing:-1px}.hg-suite-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:22px}.hg-suite-card{background:#fff;border:1px solid #dcdcde;border-radius:8px;padding:26px}.hg-suite-card h2{margin:12px 0;font-size:20px}.hg-suite-card p{color:#50575e;font-size:14px;line-height:1.7;min-height:48px}.hg-suite-version{display:inline-block;padding:4px 9px;border-radius:5px;color:#145c4c;background:#e9f5ee;font-size:12px}.hg-suite-card .button{margin-top:12px}@media(max-width:782px){.hg-suite-grid{grid-template-columns:1fr}.hg-suite-header{gap:14px}.hg-suite-card{padding:22px}}
+52
View File
@@ -0,0 +1,52 @@
<?php
/**
* HG admin navigation, bundled identically in each standalone HG plugin.
* Shared component version: 1.0.0. Update both copies together.
*/
if (!defined('ABSPATH')) exit;
if (!class_exists('HG_Plugin_Admin', false)) {
final class HG_Plugin_Admin {
private static array $plugins = [];
private static array $hooks = [];
public static function register(array $plugin): void {
self::$plugins[$plugin['slug']] = $plugin;
}
public static function hook(string $slug): string {
return self::$hooks[$slug] ?? '';
}
public static function menu(): void {
if (!self::$plugins) return;
add_menu_page('HG Plugins', 'HG Plugins', 'manage_options', 'hg-plugins', [self::class, 'overview'], 'dashicons-screenoptions', 58);
add_submenu_page('hg-plugins', 'HG Plugins', 'Overzicht', 'manage_options', 'hg-plugins', [self::class, 'overview']);
uasort(self::$plugins, fn($a, $b) => strcasecmp($a['label'], $b['label']));
foreach (self::$plugins as $slug => $plugin) {
self::$hooks[$slug] = (string) add_submenu_page('hg-plugins', $plugin['title'], $plugin['label'], 'manage_options', $slug, $plugin['callback']);
}
}
public static function styles(): void {
if (!self::$plugins || !current_user_can('manage_options')) return;
wp_enqueue_style('hg-admin-menu', plugins_url('../assets/hg-admin-menu.css', __FILE__), [], '1.0.0');
}
public static function overview(): void {
if (!current_user_can('manage_options')) wp_die('Geen toegang.', '', ['response' => 403]);
?>
<div class="wrap hg-suite">
<header class="hg-suite-header"><span class="hg-suite-mark" aria-hidden="true">HG</span><div><h1>HG Plugins</h1><p>De Hippogrief-modules op deze website.</p></div></header>
<div class="hg-suite-grid">
<?php foreach (self::$plugins as $slug => $plugin): ?>
<section class="hg-suite-card"><span class="hg-suite-version">Versie <?php echo esc_html($plugin['version']); ?></span><h2><?php echo esc_html($plugin['title']); ?></h2><p><?php echo esc_html($plugin['description']); ?></p><a class="button button-primary" href="<?php echo esc_url(add_query_arg('page', $slug, admin_url('admin.php'))); ?>">Beheren</a></section>
<?php endforeach; ?>
</div>
</div>
<?php
}
}
add_action('admin_menu', [HG_Plugin_Admin::class, 'menu'], 20);
add_action('admin_enqueue_scripts', [HG_Plugin_Admin::class, 'styles']);
}
+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);
}
+68
View File
@@ -0,0 +1,68 @@
#!/usr/bin/env python3
"""Sync or verify the shared HG files bundled by a standalone plugin."""
import argparse
import hashlib
import json
from pathlib import Path
import re
import subprocess
SOURCE_URL = 'https://code.hosting.hippogrief.nl/hippogrief/wp-plugins'
SHARED_FILES = (
'assets/hg-admin-menu.css',
'includes/hg-admin-menu.php',
'includes/hg-plugin-updates.php',
'scripts/sync_shared.py',
)
def verify_shared(root: Path) -> None:
try:
lock = json.loads((root / 'shared.lock.json').read_text())
if lock['source'] != SOURCE_URL or not re.fullmatch(r'[0-9a-f]{40}', lock['commit']):
raise ValueError('invalid source or commit')
if set(lock['sha256']) != set(SHARED_FILES):
raise ValueError('unexpected shared file list')
for name in SHARED_FILES:
checksum = hashlib.sha256((root / name).read_bytes()).hexdigest()
if checksum != lock['sha256'][name]:
raise ValueError(f'checksum differs for {name}')
except (OSError, ValueError, TypeError, KeyError) as error:
raise SystemExit(f'HG shared files failed verification: {error}') from error
def sync_shared(root: Path, source: Path, ref: str) -> None:
git = ['git', '-C', str(source)]
commit = subprocess.check_output(
git + ['rev-parse', '--verify', '--end-of-options', f'{ref}^{{commit}}'],
text=True,
).strip()
shared_paths = {name: f'shared/{name}' for name in SHARED_FILES}
shared_paths['scripts/sync_shared.py'] = 'shared/sync_shared.py'
files = {
name: subprocess.check_output(git + ['show', f'{commit}:{remote_path}'])
for name, remote_path in shared_paths.items()
}
for name, contents in files.items():
(root / name).write_bytes(contents)
lock = {
'source': SOURCE_URL,
'commit': commit,
'sha256': {name: hashlib.sha256(contents).hexdigest() for name, contents in files.items()},
}
(root / 'shared.lock.json').write_text(json.dumps(lock, indent=2) + '\n')
if __name__ == '__main__':
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--source', type=Path, help='Path to a checkout of wp-plugins')
parser.add_argument('--ref', help='Tag or commit to copy from the shared checkout')
options = parser.parse_args()
if bool(options.source) != bool(options.ref):
parser.error('--source and --ref must be supplied together')
plugin_root = Path(__file__).resolve().parents[1]
if options.source:
sync_shared(plugin_root, options.source, options.ref)
verify_shared(plugin_root)