Initialize public HG Inschrijvingen source

This commit is contained in:
parkel committed 2026-11-18 15:51:55 +01:00
commit c84fea26a0
23 files changed
+1623

No files matched your search

+79
View File
@@ -0,0 +1,79 @@
<?php
if (!defined('ABSPATH')) exit;
HG_Plugin_Admin::register(['slug'=>'hg-registrations','title'=>'HG Inschrijvingen','label'=>'Inschrijvingen','callback'=>'hgr_admin','version'=>HGR_VERSION,'description'=>'Activiteiten, geplande momenten, capaciteit en inschrijvingen beheren.']);
add_action('admin_enqueue_scripts',function($hook) { if ($hook===HG_Plugin_Admin::hook('hg-registrations')) wp_enqueue_style('hgr-admin',HGR_URL.'assets/admin.css',[],HGR_VERSION); });
add_filter('parent_file',function($parent) { return get_current_screen()?->post_type==='hgr_activity' ? 'hg-plugins' : $parent; });
add_filter('submenu_file',function($submenu) { return get_current_screen()?->post_type==='hgr_activity' ? 'hg-registrations' : $submenu; });
function hgr_admin_url($tab,$args=[]) { return add_query_arg(array_merge(['page'=>'hg-registrations','tab'=>$tab],$args),admin_url('admin.php')); }
function hgr_admin_field($label,$name,$value='',$type='text',$extra='') {
?><label class="hgr-admin-field"><span><?php echo esc_html($label); ?></span><input type="<?php echo esc_attr($type); ?>" name="<?php echo esc_attr($name); ?>" value="<?php echo esc_attr($value); ?>" <?php echo $extra; ?>></label><?php
}
function hgr_admin_form($operation) { ?><form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>"><input type="hidden" name="action" value="hgr_admin"><input type="hidden" name="operation" value="<?php echo esc_attr($operation); ?>"><?php wp_nonce_field('hgr_admin_'.$operation); }
function hgr_capacity_text($cap) { return "$cap[capacity] plaatsen · $cap[reserved] gereserveerd · $cap[confirmed] bevestigd · $cap[available] beschikbaar"; }
function hgr_admin() {
if (!current_user_can('manage_options')) return;
global $wpdb;
$tabs=['activities'=>'Activiteiten','moments'=>'Momenten','registrations'=>'Inschrijvingen','settings'=>'Instellingen','info'=>'Over deze plugin'];
$tab=sanitize_key($_GET['tab']??'activities');if (!isset($tabs[$tab])) $tab='activities';
?>
<div class="wrap hgr-admin"><header class="hgr-admin-header"><div><h1>HG Inschrijvingen</h1><p>Beheer activiteiten, geplande momenten en deelnemers.</p></div><span class="hgr-language-status">Reserveren → handmatig bevestigen</span></header>
<?php if (isset($_GET['notice'])) { $msg=get_transient('hgr_admin_notice_'.get_current_user_id().'_'.sanitize_key($_GET['notice']));if($msg): ?><div class="notice notice-<?php echo $msg['error']?'error':'success'; ?>"><p><?php echo esc_html($msg['message']); ?></p></div><?php endif; } ?>
<nav class="hgr-admin-tabs" aria-label="Pluginonderdelen"><?php foreach($tabs as $key=>$label): ?><a <?php if($key===$tab) echo 'class="is-active" aria-current="page"'; ?> href="<?php echo esc_url(hgr_admin_url($key)); ?>"><?php echo esc_html($label); ?></a><?php endforeach; ?></nav>
<?php
if ($tab==='activities') {
$activities=get_posts(['post_type'=>'hgr_activity','post_status'=>['publish','draft','pending','private'],'numberposts'=>-1]);
?><div class="hgr-panel-heading"><div><h2>Activiteiten</h2><p>Een activiteit beschrijft wat je aanbiedt. Plan de datums onder Momenten.</p></div><a class="button button-secondary" href="<?php echo esc_url(admin_url('post-new.php?post_type=hgr_activity')); ?>">Activiteit toevoegen</a></div><div class="hgr-admin-card"><table class="widefat striped"><thead><tr><th>Activiteit</th><th>Publicatie</th><th>Agenda op een pagina plaatsen</th></tr></thead><tbody><?php foreach($activities as $a): ?><tr><td><a href="<?php echo esc_url(get_edit_post_link($a->ID)); ?>"><?php echo esc_html($a->post_title); ?></a></td><td><?php echo esc_html(get_post_status_object($a->post_status)->label); ?></td><td><code>[hg_registrations activity="<?php echo (int)$a->ID; ?>"]</code></td></tr><?php endforeach; if(!$activities): ?><tr><td colspan="3">Er zijn nog geen activiteiten. Voeg eerst een activiteit toe.</td></tr><?php endif; ?></tbody></table><p class="hgr-admin-note">Plaats <code>[hg_registrations]</code> voor een overzicht van alle open momenten. Alleen gepubliceerde activiteiten zijn zichtbaar voor bezoekers.</p></div><?php
} elseif ($tab==='moments') {
$rows=$wpdb->get_results('SELECT * FROM '.hgr_table('moments').' ORDER BY starts_at DESC LIMIT 500');
?><div class="hgr-admin-card hgr-table"><h2>Geplande momenten</h2><table class="widefat striped"><thead><tr><th>Activiteit en datum</th><th>Locatie</th><th>Capaciteit</th><th>Status</th><th></th></tr></thead><tbody><?php foreach($rows as $m): ?><tr><td><?php echo esc_html(get_the_title($m->activity_id)); ?><br><?php echo esc_html(hgr_local_time($m->starts_at)); ?></td><td><?php echo esc_html($m->location); ?></td><td><?php echo esc_html(hgr_capacity_text(hgr_capacity($m->id))); ?></td><td><?php echo esc_html(['draft'=>'Concept','open'=>'Open','closed'=>'Gesloten'][$m->state]??$m->state); ?></td><td><a href="<?php echo esc_url(hgr_admin_url('moments',['moment_id'=>$m->id])); ?>">Bewerken</a></td></tr><?php endforeach;if(!$rows): ?><tr><td colspan="5">Er zijn nog geen geplande momenten.</td></tr><?php endif; ?></tbody></table></div><?php
$edit=isset($_GET['moment_id'])?hgr_moment(absint($_GET['moment_id'])):null;
$activities=get_posts(['post_type'=>'hgr_activity','post_status'=>['publish','draft'],'numberposts'=>-1]);
hgr_admin_form('moment'); ?>
<div class="hgr-admin-card"><h2><?php echo $edit?'Moment bewerken':'Moment toevoegen'; ?></h2><input type="hidden" name="id" value="<?php echo (int)($edit->id??0); ?>"><div class="hgr-admin-grid">
<label class="hgr-admin-field"><span>Activiteit</span><select name="activity_id" required><option value="">Kies een activiteit</option><?php foreach($activities as $a): ?><option value="<?php echo $a->ID; ?>" <?php selected($edit->activity_id??0,$a->ID); ?>><?php echo esc_html($a->post_title); ?></option><?php endforeach; ?></select></label>
<?php hgr_admin_field('Locatie','location',$edit->location??'','text','required maxlength="250"');
foreach(['starts_at'=>'Begindatum en tijd','ends_at'=>'Einddatum en tijd'] as $name=>$label) hgr_admin_field($label,$name,$edit?wp_date('Y-m-d\TH:i',strtotime($edit->$name.' UTC')):'','datetime-local','required');
hgr_admin_field('Aantal plaatsen','capacity',$edit->capacity??12,'number','min="1" max="10000" required'); ?>
<label class="hgr-admin-field"><span>Status</span><select name="state"><?php foreach(['draft'=>'Concept','open'=>'Open voor inschrijving','closed'=>'Gesloten'] as $key=>$label): ?><option value="<?php echo $key; ?>" <?php selected($edit->state??'draft',$key); ?>><?php echo esc_html($label); ?></option><?php endforeach; ?></select></label></div>
<p class="hgr-admin-note">Datums gebruiken de tijdzone van deze website: <?php echo esc_html(wp_timezone_string()); ?>. Gereserveerde en bevestigde deelnemers tellen beide mee. Met bestaande aanvragen kun je de datum, activiteit en locatie niet wijzigen.</p></div>
<div class="hgr-save-bar"><?php submit_button('Moment opslaan','primary','submit',false); ?><a href="<?php echo esc_url(hgr_admin_url('moments')); ?>">Nieuw moment</a><span>Wijzigingen worden pas actief na opslaan.</span></div></form><?php
} elseif ($tab==='registrations') {
$rows=$wpdb->get_results('SELECT * FROM '.hgr_table('registrations').' ORDER BY created_at DESC LIMIT 500');
?><div class="hgr-panel-heading"><div><h2>Inschrijvingen</h2><p>Reserveringen blijven staan totdat je ze behandelt. Er is geen automatisch verloop.</p></div><a class="button button-secondary" href="<?php echo esc_url(wp_nonce_url(admin_url('admin-post.php?action=hgr_export'),'hgr_export')); ?>">Deelnemers exporteren</a></div><div class="hgr-admin-card hgr-table"><table class="widefat striped"><thead><tr><th>Aanvraag</th><th>Contactpersoon</th><th>Activiteit en moment</th><th>Deelnemers</th><th>Status</th><th>E-mail</th></tr></thead><tbody><?php foreach($rows as $r): $m=hgr_moment($r->moment_id); ?><tr><td><a href="<?php echo esc_url(hgr_admin_url('registrations',['registration_id'=>$r->id])); ?>">#<?php echo (int)$r->id; ?></a><br><?php echo esc_html(hgr_local_time($r->created_at)); ?></td><td><?php echo esc_html($r->contact_name); ?><br><?php echo esc_html($r->organization); ?></td><td><?php echo esc_html($m?get_the_title($m->activity_id):''); ?><br><?php echo esc_html($m?hgr_local_time($m->starts_at):''); ?></td><td><?php echo (int)$r->seats; ?></td><td><span class="hgr-badge hgr-<?php echo esc_attr($r->status); ?>"><?php echo esc_html(hgr_statuses()[$r->status]??$r->status); ?></span></td><td><?php echo esc_html(['pending'=>'Nog versturen','sent'=>'Verstuurd','failed'=>'Verzending mislukt'][$r->notice_state]??$r->notice_state); ?></td></tr><?php endforeach;if(!$rows): ?><tr><td colspan="6">Er zijn nog geen inschrijvingen.</td></tr><?php endif; ?></tbody></table></div><?php
if (isset($_GET['registration_id']) && ($r=hgr_registration(absint($_GET['registration_id'])))) {
$m=hgr_moment($r->moment_id);hgr_admin_form('status'); ?>
<div class="hgr-admin-card"><h2>Inschrijving #<?php echo (int)$r->id; ?></h2><p><?php echo esc_html(get_the_title($m->activity_id).' · '.hgr_local_time($m->starts_at).' · '.$m->location); ?></p><p class="hgr-admin-note"><?php echo esc_html(hgr_capacity_text(hgr_capacity($m->id))); ?></p>
<div class="hgr-admin-grid"><div><h3>Contactpersoon</h3><p><?php echo esc_html($r->contact_name); ?><br><?php echo esc_html($r->contact_email); ?><br><?php echo esc_html($r->phone); ?><br><?php echo esc_html($r->organization); ?></p></div><div><h3>Deelnemers</h3><ol><?php foreach(json_decode($r->participants,true)?:[] as $name): ?><li><?php echo esc_html($name); ?></li><?php endforeach; ?></ol></div></div>
<input type="hidden" name="id" value="<?php echo (int)$r->id; ?>"><label class="hgr-admin-field"><span>Status</span><select name="status"><?php foreach(hgr_statuses() as $key=>$label): ?><option value="<?php echo $key; ?>" <?php selected($r->status,$key); ?>><?php echo esc_html($label); ?></option><?php endforeach; ?></select></label><p>Bij een statuswijziging ontvangt de contactpersoon een bericht. Afwijzen of annuleren geeft de plaatsen vrij.</p></div><div class="hgr-save-bar"><?php submit_button('Status opslaan en berichten versturen','primary','submit',false); ?></div></form><?php
if ($r->notice_state!=='sent') { hgr_admin_form('resend'); ?><input type="hidden" name="id" value="<?php echo (int)$r->id; ?>"><p><?php submit_button('Mislukte meldingen opnieuw versturen','secondary','submit',false); ?></p></form><?php }
}
} elseif ($tab==='settings') {
$s=hgr_settings();hgr_admin_form('settings'); ?><div class="hgr-admin-card"><h2>Algemeen en e-mail</h2><div class="hgr-admin-grid"><?php hgr_admin_field('Ontvangstadres organisatie','recipient',$s['recipient'],'email','required');hgr_admin_field('Maximaal deelnemers per aanvraag','max_participants',$s['max_participants'],'number','min="1" max="100" required');hgr_admin_field('Naam voor activiteit','activity_label',$s['activity_label'],'text','required maxlength="60"');hgr_admin_field('Naam voor gepland moment','moment_label',$s['moment_label'],'text','required maxlength="60"'); ?></div><p class="hgr-admin-note">Mailaflevering volgt de mailvoorziening van de website. Een gereserveerde plaats is nog geen bevestigde deelname. Zorg dat er een passende privacyverklaring is voor de gegevens die je verzamelt.</p></div><div class="hgr-save-bar"><?php submit_button('Wijzigingen opslaan','primary','submit',false); ?><span>Wijzigingen worden pas actief na opslaan.</span></div></form><?php
} else { ?><div class="hgr-admin-card"><h2>HG Inschrijvingen</h2><p>Versie <?php echo esc_html(HGR_VERSION); ?> · WordPress en PHP 8.1+</p><p>Herbruikbaar voor trainingen, workshops en andere activiteiten. Klantinstellingen staan uitsluitend in de website. Reserveringen en bevestigingen delen dezelfde capaciteitscontrole.</p><h3>Onderhoud en gegevens</h3><p>Gebruik databaseback-ups. Deactiveren verwijdert geen inschrijvingen. Er is geen automatische verwijdering of bewaartermijn; spreek deze vóór livegang af. Exports bevatten persoonsgegevens en zijn alleen beschikbaar voor beheerders.</p><p>Basis-antispam: honeypot, ondertekend formulier, wachttijd en verzendlimiet. Cache de inschrijfpagina niet langdurig. Er is geen online betaling of wachtlijst.</p></div><?php }
?></div><?php
}
function hgr_admin_action() {
if (!current_user_can('manage_options')) wp_die('Geen toegang.', '', ['response'=>403]);
$input=wp_unslash($_POST);$op=sanitize_key($input['operation']??'');check_admin_referer('hgr_admin_'.$op);
$tab='registrations';$args=[];$error=false;$message='Wijzigingen opgeslagen.';
if ($op==='moment') { $tab='moments';$result=hgr_save_moment($input);if(!is_wp_error($result))$args['moment_id']=$result; }
elseif ($op==='status') { $args['registration_id']=absint($input['id']??0);$result=hgr_set_status($args['registration_id'],$input['status']??'');if($result===true && !hgr_notify($args['registration_id'])) $message='Status opgeslagen, maar niet alle e-mails zijn verstuurd. Probeer opnieuw vanuit de aanvraag.'; }
elseif ($op==='resend') { $args['registration_id']=absint($input['id']??0);$result=hgr_notify($args['registration_id']);$message=$result?'Meldingen verstuurd.':'Verzending is niet gelukt. Controleer de mailvoorziening.';$error=!$result; }
elseif ($op==='settings') {
$tab='settings';$s=hgr_settings();$recipient=sanitize_email($input['recipient']??'');$max=filter_var($input['max_participants']??null,FILTER_VALIDATE_INT,['options'=>['min_range'=>1,'max_range'=>100]]);
$activity=sanitize_text_field($input['activity_label']??'');$moment=sanitize_text_field($input['moment_label']??'');
if (!is_email($recipient)||!$max||!$activity||!$moment||strlen($activity)>60||strlen($moment)>60) $result=new WP_Error('settings','Controleer de instellingen.');
else { update_option('hgr_settings',array_merge($s,['recipient'=>$recipient,'max_participants'=>$max,'activity_label'=>$activity,'moment_label'=>$moment]));$result=true; }
} else $result=new WP_Error('operation','Ongeldige actie.');
if (is_wp_error($result)) { $error=true;$message=$result->get_error_message(); }
$key=str_replace('-','',wp_generate_uuid4());set_transient('hgr_admin_notice_'.get_current_user_id().'_'.$key,['error'=>$error,'message'=>$message],5*MINUTE_IN_SECONDS);
wp_safe_redirect(hgr_admin_url($tab,array_merge($args,['notice'=>$key])));exit;
}
add_action('admin_post_hgr_admin','hgr_admin_action');
add_action('admin_post_hgr_export',function() {
if (!current_user_can('manage_options')) wp_die('Geen toegang.','',['response'=>403]);check_admin_referer('hgr_export');
global $wpdb;nocache_headers();header('Content-Type: text/csv; charset=utf-8');header('Content-Disposition: attachment; filename="inschrijvingen-'.gmdate('Y-m-d').'.csv"');
$out=fopen('php://output','w');fwrite($out,"\xEF\xBB\xBF");fputcsv($out,['Nummer','Activiteit','Datum','Locatie','Status','Deelnemer','Contactpersoon','E-mail','Telefoon','Organisatie'],';', '"','');
// One participant per row; neutralize spreadsheet formulas in user supplied values.
$offset=0;do { $rows=$wpdb->get_results($wpdb->prepare('SELECT * FROM '.hgr_table('registrations').' ORDER BY id LIMIT 200 OFFSET %d',$offset));foreach($rows as $r) { $m=hgr_moment($r->moment_id);foreach(json_decode($r->participants,true)?:[] as $person) { $row=[$r->id,get_the_title($m->activity_id),hgr_local_time($m->starts_at),$m->location,hgr_statuses()[$r->status],$person,$r->contact_name,$r->contact_email,$r->phone,$r->organization];$row=array_map(fn($v)=>preg_match('/^[\s]*[=+@-]/u',(string)$v)?"'".$v:$v,$row);fputcsv($out,$row,';', '"',''); } }$offset+=200; } while(count($rows)===200);fclose($out);exit;
});
+62
View File
@@ -0,0 +1,62 @@
<?php
if (!defined('ABSPATH')) exit;
function hgr_form_token($id,$issued=null,$uuid=null) {
$payload=$id.'.'.($issued??time()).'.'.($uuid??wp_generate_uuid4());
return $payload.'.'.hash_hmac('sha256',$payload,wp_salt('nonce'));
}
function hgr_check_token($token,$id) {
if (!is_string($token) || strlen($token)>200) return false;
$bits=explode('.',$token);
if (count($bits)!==4 || !ctype_digit($bits[0]) || !ctype_digit($bits[1]) || (int)$bits[0]!==$id || !preg_match('/^[a-f0-9-]{36}$/',$bits[2])) return false;
$age=time()-(int)$bits[1];
return $age>=3 && $age<=7200 && hash_equals(hash_hmac('sha256',implode('.',array_slice($bits,0,3)),wp_salt('nonce')),$bits[3]);
}
add_shortcode('hg_registrations',function($attrs) {
global $wpdb;
$attrs=shortcode_atts(['activity'=>'0'],$attrs,'hg_registrations');$activity=absint($attrs['activity']);
$sql=$wpdb->prepare('SELECT m.* FROM '.hgr_table('moments')." m INNER JOIN $wpdb->posts p ON p.ID=m.activity_id WHERE m.state='open' AND m.starts_at>%s AND p.post_status='publish' AND p.post_type='hgr_activity'",current_time('mysql',true));
if ($activity) $sql.=$wpdb->prepare(' AND m.activity_id=%d',$activity);
$rows=$wpdb->get_results($sql.' ORDER BY m.starts_at LIMIT 100');
wp_enqueue_style('hgr-frontend',HGR_URL.'assets/frontend.css',[],HGR_VERSION);
wp_enqueue_script('hgr-frontend',HGR_URL.'assets/frontend.js',[],HGR_VERSION,true);
if (!headers_sent()) { nocache_headers(); }
ob_start(); ?>
<section class="hgr" aria-label="<?php echo esc_attr(hgr_settings()['moment_label']); ?>">
<?php if (isset($_GET['hgr_reserved'])): ?><div class="hgr-notice" role="status"><strong>Je aanvraag is ontvangen.</strong> De plaatsen zijn gereserveerd. Je deelname is pas definitief nadat de organisatie deze heeft bevestigd.</div><?php endif; ?>
<?php if (isset($_GET['hgr_error']) && is_scalar($_GET['hgr_error'])): $message=get_transient('hgr_error_'.sanitize_key(wp_unslash($_GET['hgr_error'])));if($message): ?><div class="hgr-notice hgr-error" role="alert"><?php echo esc_html($message); ?></div><?php endif;endif; ?>
<?php if (!$rows): ?><p class="hgr-empty">Er zijn momenteel geen geplande momenten waarvoor je kunt inschrijven.</p><?php endif; ?>
<?php foreach($rows as $m): $cap=hgr_capacity($m->id);$title=get_the_title($m->activity_id);$max=min($cap['available'],(int)hgr_settings()['max_participants']); ?>
<article class="hgr-moment"><div class="hgr-moment-head"><div><h3><?php echo esc_html($title); ?></h3><p><?php echo esc_html(hgr_local_time($m->starts_at)); ?> – <?php echo esc_html(wp_date('H:i',strtotime($m->ends_at.' UTC'))); ?><br><?php echo esc_html($m->location); ?></p></div><div class="hgr-capacity"><strong><?php echo (int)$cap['available']; ?> beschikbaar</strong><span>van <?php echo (int)$cap['capacity']; ?> plaatsen</span></div></div>
<?php if (!$max): ?><p class="hgr-full">Volgeboekt</p><?php else: ?>
<details class="hgr-details"><summary>Plaatsen reserveren</summary>
<form method="post" action="<?php echo esc_url(admin_url('admin-post.php')); ?>" class="hgr-form" data-max="<?php echo $max; ?>">
<input type="hidden" name="action" value="hgr_reserve"><input type="hidden" name="moment_id" value="<?php echo (int)$m->id; ?>"><input type="hidden" name="hgr_token" value="<?php echo esc_attr(hgr_form_token((int)$m->id)); ?>"><input type="hidden" name="return_url" value="<?php echo esc_url(get_permalink()); ?>">
<?php wp_nonce_field('hgr_reserve','hgr_nonce'); ?>
<div class="hgr-honey" aria-hidden="true"><label>Website<input name="website" tabindex="-1" autocomplete="off"></label></div>
<div class="hgr-fields"><label>Naam contactpersoon <span aria-hidden="true">*</span><input name="contact_name" autocomplete="name" required maxlength="150"></label><label>E-mailadres <span aria-hidden="true">*</span><input type="email" name="contact_email" autocomplete="email" required maxlength="254"></label><label>Telefoonnummer<input type="tel" name="phone" autocomplete="tel" maxlength="60"></label><label>Organisatie<input name="organization" autocomplete="organization" maxlength="150"></label></div>
<fieldset class="hgr-participants"><legend>Deelnemers</legend><div class="hgr-person"><label>Naam deelnemer 1 <span aria-hidden="true">*</span><input name="participants[]" required maxlength="150"></label><button type="button" class="hgr-remove" hidden>Verwijderen</button></div></fieldset>
<button type="button" class="hgr-add">Deelnemer toevoegen</button><p class="hgr-count" aria-live="polite">1 deelnemer</p>
<label class="hgr-consent"><input type="checkbox" name="consent" value="1" required> Ik ga akkoord met verwerking van deze gegevens voor mijn inschrijving.</label>
<p class="hgr-help">Je reserveert plaatsen. De organisatie bevestigt je deelname afzonderlijk. Vul geen medische of andere gevoelige gegevens in.</p>
<button type="submit" class="hgr-submit">Reservering aanvragen</button>
</form></details><?php endif; ?></article><?php endforeach; ?></section>
<?php return ob_get_clean();
});
function hgr_submission() {
$input=wp_unslash($_POST);$id=absint($input['moment_id']??0);
$return=wp_validate_redirect(is_scalar($input['return_url']??null)?$input['return_url']: '',home_url('/'));
$return=remove_query_arg(['hgr_error','hgr_reserved'],$return);
$error=null;
if (!wp_verify_nonce(is_scalar($input['hgr_nonce']??null)?$input['hgr_nonce']:'','hgr_reserve') || !hgr_check_token($input['hgr_token']??null,$id) || !empty($input['website']) || ($input['consent']??'')!=='1') $error='Controleer het formulier. Vernieuw de pagina als deze lang open heeft gestaan.';
$ip=hash_hmac('sha256',$_SERVER['REMOTE_ADDR']??'',wp_salt('auth'));$rate='hgr_rate_'.$ip;
if (!$error && (int)get_transient($rate)>=10) $error='Er zijn te veel aanvragen verstuurd. Probeer het over enkele minuten opnieuw.';
if (!$error) {
$result=hgr_reserve($id,$input,hash('sha256',$input['hgr_token']));
if (is_wp_error($result)) $error=$result->get_error_message();
else { if ($result['new']) { set_transient($rate,(int)get_transient($rate)+1,10*MINUTE_IN_SECONDS);hgr_notify($result['id']); } wp_safe_redirect(add_query_arg('hgr_reserved','1',$return));exit; }
}
$key=str_replace('-','',wp_generate_uuid4());set_transient('hgr_error_'.$key,$error,5*MINUTE_IN_SECONDS);
wp_safe_redirect(add_query_arg('hgr_error',$key,$return));exit;
}
add_action('admin_post_hgr_reserve','hgr_submission');
add_action('admin_post_nopriv_hgr_reserve','hgr_submission');
+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);
}
+33
View File
@@ -0,0 +1,33 @@
<?php
if (!defined('ABSPATH')) exit;
function hgr_notify($id) {
global $wpdb;
$r=hgr_registration($id);if (!$r) return false;
$m=hgr_moment($r->moment_id);if (!$m) return false;
$version=(int)$r->notice_version;
// Serialize sends and re-read state so duplicate HTTP/admin requests cannot double-send.
$lock='hgr-mail-'.md5(hgr_table('registrations').':'.$id);
if ((int)$wpdb->get_var($wpdb->prepare('SELECT GET_LOCK(%s, 0)',$lock))!==1) return false;
try {
$r=hgr_registration($id);$version=(int)$r->notice_version;
if ($r->notice_state==='sent') return true;
$activity=get_the_title($m->activity_id);$status=hgr_statuses()[$r->status];
$people=implode("\n",array_map(fn($name)=>'- '.$name,json_decode($r->participants,true)?:[]));
$details="Activiteit: $activity\nDatum: ".hgr_local_time($m->starts_at)."\nLocatie: $m->location\nContactpersoon: $r->contact_name\nE-mail: $r->contact_email\nTelefoon: $r->phone\nOrganisatie: $r->organization\nAantal deelnemers: $r->seats\nStatus: $status\n\nDeelnemers:\n$people\n";
$link=admin_url('admin.php?page=hg-registrations&tab=registrations&registration_id='.$id);
$customer_sent=(int)$r->customer_notice_version===$version;
if (!$customer_sent) {
$customer_sent=wp_mail(hgr_settings()['recipient'],"[$activity] Inschrijving #$id — $status",$details."\nBehandelen in WordPress: $link\n");
if ($customer_sent) $wpdb->update(hgr_table('registrations'),['customer_notice_version'=>$version],['id'=>$id,'notice_version'=>$version]);
}
$intro=match($r->status){'reserved'=>'Je aanvraag is ontvangen. De plaatsen zijn gereserveerd; de organisatie bevestigt je deelname afzonderlijk.','confirmed'=>'Je deelname is bevestigd.','declined'=>'Je aanvraag is afgewezen. De gereserveerde plaatsen zijn vrijgegeven.','cancelled'=>'Je inschrijving is geannuleerd. De plaatsen zijn vrijgegeven.'};
$participant_sent=(int)$r->participant_notice_version===$version;
if (!$participant_sent) {
$participant_sent=wp_mail($r->contact_email,"[$activity] $status — inschrijving #$id",$intro."\n\n".$details);
if ($participant_sent) $wpdb->update(hgr_table('registrations'),['participant_notice_version'=>$version],['id'=>$id,'notice_version'=>$version]);
}
$sent=$customer_sent && $participant_sent;
$wpdb->update(hgr_table('registrations'),['notice_state'=>$sent?'sent':'failed'],['id'=>$id,'notice_version'=>$version]);
return $sent;
} finally { $wpdb->get_var($wpdb->prepare('SELECT RELEASE_LOCK(%s)',$lock)); }
}
+145
View File
@@ -0,0 +1,145 @@
<?php
if (!defined('ABSPATH')) exit;
function hgr_table($name) { global $wpdb; return $wpdb->prefix . 'hgr_' . $name; }
function hgr_install() {
global $wpdb;
require_once ABSPATH . 'wp-admin/includes/upgrade.php';
$collate=$wpdb->get_charset_collate();
dbDelta('CREATE TABLE '.hgr_table('moments')." (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
activity_id bigint(20) unsigned NOT NULL,
starts_at datetime NOT NULL,
ends_at datetime NOT NULL,
location varchar(250) NOT NULL DEFAULT '',
capacity int unsigned NOT NULL,
state varchar(20) NOT NULL DEFAULT 'draft',
created_at datetime NOT NULL,
PRIMARY KEY (id),
KEY activity_start (activity_id,starts_at)
) ENGINE=InnoDB $collate;");
dbDelta('CREATE TABLE '.hgr_table('registrations')." (
id bigint(20) unsigned NOT NULL AUTO_INCREMENT,
moment_id bigint(20) unsigned NOT NULL,
request_key char(64) NOT NULL,
contact_name varchar(150) NOT NULL,
contact_email varchar(254) NOT NULL,
phone varchar(60) NOT NULL DEFAULT '',
organization varchar(150) NOT NULL DEFAULT '',
participants longtext NOT NULL,
seats int unsigned NOT NULL,
status varchar(20) NOT NULL DEFAULT 'reserved',
created_at datetime NOT NULL,
updated_at datetime NOT NULL,
notice_state varchar(20) NOT NULL DEFAULT 'pending',
notice_version int unsigned NOT NULL DEFAULT 1,
customer_notice_version int unsigned NOT NULL DEFAULT 0,
participant_notice_version int unsigned NOT NULL DEFAULT 0,
PRIMARY KEY (id),
UNIQUE KEY request_key (request_key),
KEY moment_status (moment_id,status)
) ENGINE=InnoDB $collate;");
update_option('hgr_schema', HGR_VERSION);
}
function hgr_settings() {
return array_replace(['recipient'=>get_option('admin_email'),'activity_label'=>'Activiteit','moment_label'=>'Moment','max_participants'=>20], (array)get_option('hgr_settings',[]));
}
function hgr_statuses() { return ['reserved'=>'Gereserveerd','confirmed'=>'Bevestigd','declined'=>'Afgewezen','cancelled'=>'Geannuleerd']; }
function hgr_moment($id, $lock=false) {
global $wpdb;
return $wpdb->get_row($wpdb->prepare('SELECT * FROM '.hgr_table('moments').' WHERE id=%d'.($lock?' FOR UPDATE':''),$id));
}
function hgr_registration($id) { global $wpdb; return $wpdb->get_row($wpdb->prepare('SELECT * FROM '.hgr_table('registrations').' WHERE id=%d',$id)); }
function hgr_capacity($id) {
global $wpdb;
$m=hgr_moment($id);
if (!$m) return ['capacity'=>0,'reserved'=>0,'confirmed'=>0,'available'=>0];
$counts=$wpdb->get_results($wpdb->prepare('SELECT status,SUM(seats) AS seats FROM '.hgr_table('registrations')." WHERE moment_id=%d AND status IN ('reserved','confirmed') GROUP BY status",$id),OBJECT_K);
$reserved=(int)($counts['reserved']->seats??0);$confirmed=(int)($counts['confirmed']->seats??0);
return ['capacity'=>(int)$m->capacity,'reserved'=>$reserved,'confirmed'=>$confirmed,'available'=>max(0,(int)$m->capacity-$reserved-$confirmed)];
}
function hgr_local_time($date) { return wp_date('j F Y, H:i', strtotime($date.' UTC')); }
function hgr_begin() { global $wpdb; if ($wpdb->query('START TRANSACTION')===false) throw new RuntimeException('Transactie kon niet starten.'); }
function hgr_commit() { global $wpdb; if ($wpdb->query('COMMIT')===false) throw new RuntimeException('Opslaan is niet gelukt.'); }
function hgr_clean_registration($input) {
foreach (['contact_name','contact_email','phone','organization'] as $field) {
if (isset($input[$field]) && !is_scalar($input[$field])) return new WP_Error('contact','Controleer de contactgegevens.');
}
$name=sanitize_text_field($input['contact_name']??'');$email=sanitize_email($input['contact_email']??'');
if (!$name || strlen($name)>150 || !is_email($email) || strlen($email)>254) return new WP_Error('contact','Vul een geldige naam en e-mailadres in.');
$names=$input['participants']??[];$participants=[];
if (!is_array($names) || count($names)<1 || count($names)>(int)hgr_settings()['max_participants']) return new WP_Error('participants','Controleer het aantal deelnemers.');
foreach ($names as $person) {
if (!is_scalar($person)) return new WP_Error('participants','Vul voor iedere deelnemer een naam in.');
$person=sanitize_text_field($person);
if (!$person || strlen($person)>150) return new WP_Error('participants','Vul voor iedere deelnemer een naam in (maximaal 150 tekens).');
$participants[]=$person;
}
$phone=sanitize_text_field($input['phone']??'');$organization=sanitize_text_field($input['organization']??'');
if (strlen($phone)>60 || strlen($organization)>150) return new WP_Error('contact','Telefoon of organisatie is te lang.');
return ['contact_name'=>$name,'contact_email'=>$email,'phone'=>$phone,'organization'=>$organization,'participants'=>wp_json_encode($participants),'seats'=>count($participants)];
}
function hgr_reserve($moment_id,$input,$key) {
global $wpdb;
$data=hgr_clean_registration($input);if (is_wp_error($data)) return $data;
if (!preg_match('/^[a-f0-9]{64}$/',$key)) return new WP_Error('key','Ongeldige aanvraag.');
try {
hgr_begin();$m=hgr_moment($moment_id,true);
if (!$m) throw new RuntimeException('Dit moment bestaat niet.');
$existing=$wpdb->get_row($wpdb->prepare('SELECT id,moment_id FROM '.hgr_table('registrations').' WHERE request_key=%s',$key));
if ($existing) { if ((int)$existing->moment_id !== (int)$moment_id) throw new RuntimeException('Ongeldige aanvraag.'); hgr_commit();return ['id'=>(int)$existing->id,'new'=>false]; }
if ($m->state!=='open' || strtotime($m->starts_at.' UTC')<=time() || get_post_status($m->activity_id)!=='publish') throw new RuntimeException('Dit moment is niet open voor inschrijvingen.');
$cap=hgr_capacity($moment_id);
if ($data['seats']>$cap['available']) throw new RuntimeException('Er zijn niet genoeg plaatsen beschikbaar. Kies minder deelnemers of een ander moment.');
$now=current_time('mysql',true);
$data=array_merge($data,['moment_id'=>$moment_id,'request_key'=>$key,'created_at'=>$now,'updated_at'=>$now,'status'=>'reserved']);
if (!$wpdb->insert(hgr_table('registrations'),$data)) throw new RuntimeException('Opslaan is niet gelukt. Probeer het opnieuw.');
$id=(int)$wpdb->insert_id;hgr_commit();return ['id'=>$id,'new'=>true];
} catch (Throwable $e) { $wpdb->query('ROLLBACK');return new WP_Error('reservation',$e->getMessage()); }
}
function hgr_set_status($id,$status) {
global $wpdb;
if (!isset(hgr_statuses()[$status])) return new WP_Error('status','Ongeldige status.');
$initial=hgr_registration($id);if (!$initial) return new WP_Error('missing','Inschrijving niet gevonden.');
try {
hgr_begin();$m=hgr_moment($initial->moment_id,true);
$r=$wpdb->get_row($wpdb->prepare('SELECT * FROM '.hgr_table('registrations').' WHERE id=%d FOR UPDATE',$id));
if (!$m || !$r) throw new RuntimeException('Inschrijving niet gevonden.');
if ($r->status===$status) { hgr_commit();return false; }
$active=['reserved','confirmed'];
if (in_array($status,$active,true) && !in_array($r->status,$active,true)) {
if (strtotime($m->starts_at.' UTC')<=time() || $r->seats>hgr_capacity($m->id)['available']) throw new RuntimeException('Geen ruimte om deze inschrijving opnieuw te activeren.');
}
if ($wpdb->update(hgr_table('registrations'),['status'=>$status,'updated_at'=>current_time('mysql',true),'notice_state'=>'pending','notice_version'=>(int)$r->notice_version+1],['id'=>$id])===false) throw new RuntimeException('Opslaan is niet gelukt.');
hgr_commit();return true;
} catch(Throwable $e) { $wpdb->query('ROLLBACK');return new WP_Error('status',$e->getMessage()); }
}
function hgr_save_moment($input) {
global $wpdb;
$id=absint($input['id']??0);$activity=absint($input['activity_id']??0);
if (get_post_type($activity)!=='hgr_activity' || get_post_status($activity)==='trash') return new WP_Error('activity','Kies een geldige activiteit.');
$dates=[];
foreach(['starts_at','ends_at'] as $field) {
$value=(string)($input[$field]??'');
$date=DateTimeImmutable::createFromFormat('!Y-m-d\TH:i',$value,wp_timezone());
if (!$date || $date->format('Y-m-d\TH:i')!==$value) return new WP_Error('date','Vul een geldige datum en tijd in.');
$dates[$field]=$date->setTimezone(new DateTimeZone('UTC'))->format('Y-m-d H:i:s');
}
if ($dates['ends_at']<=$dates['starts_at']) return new WP_Error('date','De eindtijd moet na de begintijd liggen.');
$capacity=filter_var($input['capacity']??null,FILTER_VALIDATE_INT,['options'=>['min_range'=>1,'max_range'=>10000]]);
$state=$input['state']??'draft';$location=sanitize_text_field($input['location']??'');
if (!$capacity || !in_array($state,['draft','open','closed'],true) || !$location || strlen($location)>250) return new WP_Error('moment','Controleer capaciteit, locatie en status.');
try {
hgr_begin();$old=$id?hgr_moment($id,true):null;
if ($id && !$old) throw new RuntimeException('Moment niet gevonden.');
if ($old) {
$cap=hgr_capacity($id);
if ($capacity<$cap['reserved']+$cap['confirmed']) throw new RuntimeException('Capaciteit kan niet lager zijn dan het aantal gereserveerde en bevestigde deelnemers.');
$registrations=(int)$wpdb->get_var($wpdb->prepare('SELECT COUNT(*) FROM '.hgr_table('registrations').' WHERE moment_id=%d',$id));
if ($registrations && ($old->activity_id!=$activity || $old->starts_at!==$dates['starts_at'] || $old->ends_at!==$dates['ends_at'] || $old->location!==$location)) throw new RuntimeException('Dit moment heeft inschrijvingen. Maak voor een gewijzigde datum, locatie of activiteit een nieuw moment aan en behandel bestaande aanvragen apart.');
}
$data=array_merge($dates,['activity_id'=>$activity,'location'=>$location,'capacity'=>$capacity,'state'=>$state]);
$ok=$old?$wpdb->update(hgr_table('moments'),$data,['id'=>$id]):$wpdb->insert(hgr_table('moments'),array_merge($data,['created_at'=>current_time('mysql',true)]));
if ($ok===false) throw new RuntimeException('Opslaan is niet gelukt.');
$saved=$old?$id:(int)$wpdb->insert_id;hgr_commit();return $saved;
} catch(Throwable $e) { $wpdb->query('ROLLBACK');return new WP_Error('moment',$e->getMessage()); }
}