-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.php
More file actions
1568 lines (1369 loc) · 48.7 KB
/
Copy pathfunctions.php
File metadata and controls
1568 lines (1369 loc) · 48.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Rondo Club Theme Functions
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
/**
* Reconstruct Authorization header from PHP_AUTH_* variables.
*
* Some Apache/CGI configurations strip the Authorization header before it reaches PHP,
* but still populate PHP_AUTH_USER and PHP_AUTH_PW. WordPress REST API Application
* Password authentication only looks for the Authorization header, not these variables.
*
* This fix reconstructs the header so WordPress can authenticate REST API requests.
*/
if ( ! isset( $_SERVER['HTTP_AUTHORIZATION'] ) && isset( $_SERVER['PHP_AUTH_USER'], $_SERVER['PHP_AUTH_PW'] ) ) {
$_SERVER['HTTP_AUTHORIZATION'] = 'Basic ' . base64_encode( $_SERVER['PHP_AUTH_USER'] . ':' . $_SERVER['PHP_AUTH_PW'] );
}
// Load Composer autoloader for PSR-4 classes
if ( file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
require_once __DIR__ . '/vendor/autoload.php';
}
/**
* Register a fallback autoloader for Rondo classes.
*
* Composer classmaps can become stale on deployments where autoload regeneration
* fails. This loader lazily builds a class map from includes/class-*.php and only
* resolves Rondo classes that Composer did not load.
*/
function rondo_register_fallback_autoloader() {
spl_autoload_register(
static function ( $class ) {
if ( strpos( $class, 'Rondo\\' ) !== 0 ) {
return;
}
static $classmap = null;
if ( $classmap === null ) {
$classmap = [];
$files = glob( __DIR__ . '/includes/class-*.php' );
if ( $files === false ) {
$files = [];
}
foreach ( $files as $file ) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$contents = file_get_contents( $file );
if ( $contents === false ) {
continue;
}
if ( ! preg_match( '/^\s*namespace\s+([^;]+);/m', $contents, $namespace_match ) ) {
continue;
}
$namespace = trim( $namespace_match[1] );
if ( $namespace !== 'Rondo' && strpos( $namespace, 'Rondo\\' ) !== 0 ) {
continue;
}
if ( preg_match_all( '/^\s*(?:final\s+|abstract\s+)?class\s+([A-Za-z_][A-Za-z0-9_]*)/m', $contents, $class_matches ) ) {
foreach ( $class_matches[1] as $short_name ) {
$classmap[ $namespace . '\\' . $short_name ] = $file;
}
}
if ( preg_match_all( '/^\s*interface\s+([A-Za-z_][A-Za-z0-9_]*)/m', $contents, $interface_matches ) ) {
foreach ( $interface_matches[1] as $short_name ) {
$classmap[ $namespace . '\\' . $short_name ] = $file;
}
}
if ( preg_match_all( '/^\s*trait\s+([A-Za-z_][A-Za-z0-9_]*)/m', $contents, $trait_matches ) ) {
foreach ( $trait_matches[1] as $short_name ) {
$classmap[ $namespace . '\\' . $short_name ] = $file;
}
}
if ( preg_match_all( '/^\s*enum\s+([A-Za-z_][A-Za-z0-9_]*)/m', $contents, $enum_matches ) ) {
foreach ( $enum_matches[1] as $short_name ) {
$classmap[ $namespace . '\\' . $short_name ] = $file;
}
}
}
}
if ( isset( $classmap[ $class ] ) && file_exists( $classmap[ $class ] ) ) {
require_once $classmap[ $class ];
}
}
);
}
rondo_register_fallback_autoloader();
// PSR-4 namespaced class imports
use Rondo\Core\PostTypes;
use Rondo\Core\Taxonomies;
use Rondo\Core\AutoTitle;
use Rondo\Core\PhoneNormalizer;
use Rondo\Core\VolunteerStatus;
use Rondo\Core\AccessControl;
use Rondo\Core\UserRoles;
use Rondo\REST\Api;
use Rondo\REST\People;
use Rondo\REST\Teams;
use Rondo\REST\Commissies;
use Rondo\REST\Todos;
use Rondo\REST\Feedback as RESTFeedback;
use Rondo\REST\Invoices as RESTInvoices;
use Rondo\REST\MembershipPasses as RESTMembershipPasses;
use Rondo\REST\Clothing as RESTClothing;
use Rondo\Notifications\EmailChannel;
use Rondo\Notifications\LettermintMailer;
use Rondo\Notifications\LettermintWebhook;
use Rondo\Collaboration\CommentTypes;
use Rondo\Collaboration\MentionNotifications;
use Rondo\Collaboration\Reminders;
use Rondo\Export\VCard as VCardExport;
use Rondo\Data\InverseRelationships;
use Rondo\Data\PersonDeletionGuard;
use Rondo\Data\TodoMigration;
use Rondo\CustomFields\Manager as CustomFieldsManager;
use Rondo\CustomFields\Validation as CustomFieldsValidation;
use Rondo\REST\CustomFields as RESTCustomFields;
use Rondo\REST\UserSettings as RESTUserSettings;
use Rondo\REST\Users as RESTUsers;
use Rondo\REST\Reminders as RESTReminders;
use Rondo\REST\Vog as RESTVog;
use Rondo\REST\Volunteer as RESTVolunteer;
use Rondo\REST\MemberShifts as RESTMemberShifts;
use Rondo\REST\Fees as RESTFees;
use Rondo\REST\Lettermint as RESTLettermint;
use Rondo\REST\Capabilities as RESTCapabilities;
use Rondo\REST\FinanceSettings as RESTFinanceSettings;
use Rondo\VOG\VOGEmail;
use Rondo\Fees\FeeCacheInvalidator;
use Rondo\Config\ClubConfig;
use Rondo\Config\FinanceConfig;
use Rondo\Finance\InvoiceNumbering;
use Rondo\Finance\InvoicePdfGenerator;
use Rondo\Finance\InvoiceEmailSender;
use Rondo\Finance\RabobankOAuth;
use Rondo\Finance\RabobankPayment;
use Rondo\Finance\MolliePayment;
use Rondo\Finance\MollieWebhook;
use Rondo\Finance\InstallmentPaymentService;
use Rondo\Finance\InstallmentEmailSender;
use Rondo\Finance\InstallmentScheduler;
use Rondo\Finance\InvoiceReminderScheduler;
use Rondo\Finance\InvoiceScheduledSendScheduler;
use Rondo\Finance\PublicPaymentPage;
use Rondo\Finance\BulkInvoiceCreator;
use Rondo\Finance\QrCodeGenerator;
use Rondo\Demo\DemoExport;
use Rondo\Demo\DemoAnonymizer;
use Rondo\Demo\DemoImport;
use Rondo\Demo\DemoProtection;
use Rondo\Passes\PublicMembershipPassPage;
use Rondo\Volunteer\PublicTaakuitlegPage;
define( 'RONDO_THEME_DIR', get_template_directory() );
define( 'RONDO_THEME_URL', get_template_directory_uri() );
define( 'RONDO_THEME_VERSION', wp_get_theme()->get( 'Version' ) );
// Plugin constants (now part of theme)
define( 'RONDO_VERSION', RONDO_THEME_VERSION );
define( 'RONDO_PLUGIN_DIR', RONDO_THEME_DIR . '/includes' );
define( 'RONDO_PLUGIN_URL', RONDO_THEME_URL . '/includes' );
/**
* Check for required dependencies
*/
function rondo_check_dependencies() {
$missing = [];
// Check for ACF Pro
if ( ! class_exists( 'ACF' ) ) {
$missing[] = 'Advanced Custom Fields Pro';
}
if ( ! empty( $missing ) ) {
add_action(
'admin_notices',
function () use ( $missing ) {
$message = sprintf(
// translators: %s is a comma-separated list of plugin names.
__( 'Rondo Club requires the following plugins: %s', 'rondo' ),
implode( ', ', $missing )
);
echo '<div class="notice notice-error"><p>' . esc_html( $message ) . '</p></div>';
}
);
return false;
}
return true;
}
/**
* Backward compatibility class aliases.
*
* Only aliases that are still referenced in production code or tests are kept.
* Unused aliases were removed in v32.6.0.
*/
// Core classes — used in tests and production code
class_alias( PostTypes::class, 'RONDO_Post_Types' );
class_alias( Taxonomies::class, 'RONDO_Taxonomies' );
class_alias( AccessControl::class, 'RONDO_Access_Control' );
class_alias( UserRoles::class, 'RONDO_User_Roles' );
// REST classes — used in tests
class_alias( Api::class, 'RONDO_REST_API' );
class_alias( People::class, 'RONDO_REST_People' );
class_alias( Teams::class, 'RONDO_REST_Teams' );
class_alias( Todos::class, 'RONDO_REST_Todos' );
// Notifications — used in class-reminders.php
class_alias( EmailChannel::class, 'RONDO_Email_Channel' );
class_alias( MentionNotifications::class, 'RONDO_Mention_Notifications' );
class_alias( Reminders::class, 'RONDO_Reminders' );
// Collaboration — used in class-comment-types.php
class_alias( \Rondo\Collaboration\Mentions::class, 'RONDO_Mentions' );
/**
* Check if current request is a REST API request
*/
function rondo_is_rest_request() {
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return true;
}
// Check for REST API URL pattern before REST_REQUEST is defined
$rest_prefix = rest_get_url_prefix();
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '';
return strpos( $request_uri, '/' . $rest_prefix . '/' ) !== false;
}
/**
* Determine whether a REST error is unexpected enough to log.
*
* Authentication failures, permission denials, business-rule warnings, and a
* client probing beyond the final collection page are normal 4xx responses.
* Validation and server errors remain visible in debug.log.
*
* @param WP_Error $error REST callback error.
* @return bool Whether the error should be logged.
*/
function rondo_should_log_rest_error( $error ) {
if ( ! is_wp_error( $error ) ) {
return false;
}
$expected_codes = [
'overlap_warning',
'rest_cannot_edit',
'rest_forbidden',
'rest_forbidden_age_group',
'rest_forbidden_context',
'rest_not_logged_in',
'rest_post_invalid_page_number',
'rondo_invalid_shift_copy_date',
'rondo_shift_copy_date_in_past',
'rondo_shift_copy_same_date',
'rondo_shift_copy_source_empty',
];
return ! in_array( $error->get_error_code(), $expected_codes, true );
}
/**
* Initialize the CRM functionality with conditional class loading
*/
function rondo_init() {
// Prevent double initialization
static $initialized = false;
if ( $initialized ) {
return;
}
if ( ! rondo_check_dependencies() ) {
return;
}
// Core classes - always needed for WordPress integration
new PostTypes();
new Taxonomies();
new AccessControl();
new PersonDeletionGuard();
new UserRoles();
new LettermintMailer();
new DemoProtection();
// Must load on every request: core password-reset mail is addressed to user_email,
// which for a household member is an undeliverable placeholder.
new \Rondo\Users\ContactEmailRouter();
// Lets members sign in with their KNVB-ID or real email instead of a generated username.
new \Rondo\Users\LoginResolver();
// Skip loading heavy classes for non-relevant requests
$is_admin = is_admin();
$is_rest = rondo_is_rest_request();
$is_cron = defined( 'DOING_CRON' ) && DOING_CRON;
// Classes needed for content creation/editing (admin, REST, or cron)
if ( $is_admin || $is_rest || $is_cron ) {
new AutoTitle();
new PhoneNormalizer();
new VolunteerStatus();
new InverseRelationships();
new CommentTypes();
new MentionNotifications();
// Initialize custom field validation (unique constraint).
new CustomFieldsValidation();
// Initialize fee cache invalidation hooks
new FeeCacheInvalidator();
// Seed volunteer-policy fixtures (dienst_types + pool commissies).
new \Rondo\Volunteer\VolunteerSeeder();
// Hourly shift-completion cron + no-show → boete wiring.
new \Rondo\Volunteer\ShiftScheduler();
// Hourly member reminders and post-shift survey emails.
new \Rondo\Volunteer\ShiftEmailScheduler();
// Enforce the audited, mail-aware cancellation flow for assigned shifts.
new \Rondo\Volunteer\ShiftCancellationService();
// Daily template-expander cron (rolling three-month window).
new \Rondo\Volunteer\ShiftTemplateExpander();
// Invalidate eligibility + relationship cache on person mutations.
new \Rondo\Volunteer\VolunteerCacheInvalidator();
}
// REST API classes - only for REST requests
if ( $is_rest ) {
new Api();
new People();
new Teams();
new Commissies();
new Todos();
new RESTCustomFields();
new RESTFeedback();
new RESTInvoices();
new RESTMembershipPasses();
new RESTClothing();
new RESTUserSettings();
new RESTUsers();
new RESTReminders();
new RESTVog();
new RESTVolunteer();
new RESTMemberShifts();
new \Rondo\Volunteer\ShiftDayCopier();
new RESTFees();
new RESTLettermint();
new RESTCapabilities();
new RESTFinanceSettings();
new RabobankOAuth();
new RabobankPayment();
new MollieWebhook();
new LettermintWebhook();
// Log actionable REST API errors to debug.log.
add_filter(
'rest_request_after_callbacks',
function ( $response, $handler, $request ) {
if ( rondo_should_log_rest_error( $response ) ) {
error_log(
sprintf(
'REST API error: %s %s — %s (code: %s)',
$request->get_method(),
$request->get_route(),
$response->get_error_message(),
$response->get_error_code()
)
);
}
return $response;
},
10,
3
);
}
// Reminders - only for admin or cron
if ( $is_admin || $is_cron ) {
new Reminders();
}
// Bulk invoice creator — registers WP-Cron hook for batch processing
new BulkInvoiceCreator();
// Public payment page - register rewrite rules and template_redirect handler
new PublicPaymentPage();
// Public membership pass landing page - /lidpas/{token}
new PublicMembershipPassPage();
// Public self-service account activation - /activeren
new \Rondo\Users\ActivationPage();
add_action( 'rondo_retry_guardian_notification', [ \Rondo\Users\GuardianAccountService::class, 'retry_notification' ] );
// Public taakuitleg landing page - /uitleg/{slug} (QR target, no auth)
new PublicTaakuitlegPage();
// Installment scheduler — daily cron sweeper for installment emails and reminders
new InstallmentScheduler();
// Invoice reminder scheduler — daily cron sweeper for membership and discipline invoice reminders
new InvoiceReminderScheduler();
// Invoice scheduled-send sweeper — daily cron that sends drafts queued for a future date
new InvoiceScheduledSendScheduler();
$initialized = true;
}
// Initialize early for REST API requests, but also check on plugins_loaded
// in case ACF Pro isn't loaded yet (plugins load after themes)
add_action( 'after_setup_theme', 'rondo_init', 5 );
add_action( 'plugins_loaded', 'rondo_init', 5 );
/**
* Track when an authenticated user was last active.
*
* Stores a UTC datetime and throttles writes to once per 5 minutes per user
* to avoid excessive database writes on frequent requests.
*
* @return void
*/
function rondo_track_user_last_active() {
if ( ! is_user_logged_in() ) {
return;
}
if ( wp_doing_cron() || ( defined( 'WP_CLI' ) && WP_CLI ) ) {
return;
}
$user_id = get_current_user_id();
if ( $user_id <= 0 ) {
return;
}
$now_ts = time();
$last_seen_ts = (int) get_user_meta( $user_id, 'rondo_last_active_ts', true );
// Update at most once every 5 minutes per user.
if ( $last_seen_ts > 0 && ( $now_ts - $last_seen_ts ) < 300 ) {
return;
}
update_user_meta( $user_id, 'rondo_last_active', gmdate( 'Y-m-d H:i:s', $now_ts ) );
update_user_meta( $user_id, 'rondo_last_active_ts', $now_ts );
}
add_action( 'init', 'rondo_track_user_last_active', 20 );
/**
* Allow membership pass config uploads (.p12 and .json) for financial users.
*
* @param array $mimes Existing mime map.
* @return array
*/
function rondo_membership_pass_upload_mimes( $mimes ) {
if ( current_user_can( 'financieel' ) || current_user_can( 'manage_options' ) ) {
$mimes['p12'] = 'application/x-pkcs12';
$mimes['json'] = 'application/json';
}
return $mimes;
}
add_filter( 'upload_mimes', 'rondo_membership_pass_upload_mimes' );
/**
* Migrate WordPress options from stadion_ prefix to rondo_ prefix.
*
* Runs once after the v1.1 rebrand. Copies old option values to new option names
* (only if the new option doesn't already have a value), then deletes the old options.
*/
function rondo_migrate_options() {
if ( get_option( 'rondo_options_migrated' ) ) {
return;
}
$option_map = [
'stadion_vog_from_email' => 'rondo_vog_from_email',
'stadion_vog_from_name' => 'rondo_vog_from_name',
'stadion_vog_template_new' => 'rondo_vog_template_new',
'stadion_vog_template_renewal' => 'rondo_vog_template_renewal',
'stadion_vog_exempt_commissies' => 'rondo_vog_exempt_commissies',
'stadion_club_name' => 'rondo_club_name',
'stadion_freescout_url' => 'rondo_freescout_url',
];
foreach ( $option_map as $old_key => $new_key ) {
$old_value = get_option( $old_key );
if ( $old_value !== false ) {
// Only copy if the new option doesn't already have a value.
$new_value = get_option( $new_key );
if ( $new_value === false || $new_value === '' ) {
update_option( $new_key, $old_value );
}
delete_option( $old_key );
}
}
// Migrate user meta keys from stadion_ to rondo_.
$user_meta_keys = [
'stadion_linked_person_id' => 'rondo_linked_person_id',
'stadion_notification_channels' => 'rondo_notification_channels',
'stadion_notification_time' => 'rondo_notification_time',
'stadion_mention_notifications' => 'rondo_mention_notifications',
'stadion_color_scheme' => 'rondo_color_scheme',
'stadion_dashboard_visible_cards' => 'rondo_dashboard_visible_cards',
'stadion_dashboard_card_order' => 'rondo_dashboard_card_order',
'stadion_people_list_preferences' => 'rondo_people_list_preferences',
'stadion_people_list_column_order' => 'rondo_people_list_column_order',
'stadion_people_list_column_widths' => 'rondo_people_list_column_widths',
];
$user_ids = get_users( [ 'fields' => 'ID' ] );
foreach ( $user_ids as $uid ) {
foreach ( $user_meta_keys as $old_meta => $new_meta ) {
$old_value = get_user_meta( $uid, $old_meta, true );
if ( $old_value !== '' && $old_value !== false ) {
$new_value = get_user_meta( $uid, $new_meta, true );
if ( $new_value === '' || $new_value === false ) {
update_user_meta( $uid, $new_meta, $old_value );
}
delete_user_meta( $uid, $old_meta );
}
}
}
update_option( 'rondo_options_migrated', '1' );
}
add_action( 'admin_init', 'rondo_migrate_options' );
add_action( 'rest_api_init', 'rondo_migrate_options' );
// Load WP-CLI commands if WP-CLI is available
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once RONDO_PLUGIN_DIR . '/class-wp-cli.php';
new TodoMigration();
// Class alias for backward compatibility
if ( ! class_exists( 'RONDO_Demo_Export' ) ) {
class_alias( DemoExport::class, 'RONDO_Demo_Export' );
}
if ( ! class_exists( 'RONDO_Demo_Anonymizer' ) ) {
class_alias( DemoAnonymizer::class, 'RONDO_Demo_Anonymizer' );
}
if ( ! class_exists( 'RONDO_Demo_Import' ) ) {
class_alias( DemoImport::class, 'RONDO_Demo_Import' );
}
}
/**
* Theme setup
*/
function rondo_theme_setup() {
// Add theme support
add_theme_support( 'title-tag' );
add_theme_support( 'post-thumbnails' );
add_theme_support(
'html5',
[
'search-form',
'comment-form',
'comment-list',
'gallery',
'caption',
'style',
'script',
]
);
// Register nav menus (optional, React handles navigation)
register_nav_menus(
[
'primary' => __( 'Primary Menu', 'rondo' ),
]
);
}
add_action( 'after_setup_theme', 'rondo_theme_setup' );
/**
* Set default page title for SPA (React will update it dynamically)
*/
function rondo_theme_document_title_parts( $title ) {
// Only modify title on frontend (not admin)
if ( is_admin() ) {
return $title;
}
// Set a default title - React will update it when routes change
$club_name = \Rondo\Config\ClubConfig::get_club_name();
$title['title'] = ! empty( $club_name ) ? $club_name : 'Rondo Club';
$title['site'] = '';
return $title;
}
add_filter( 'document_title_parts', 'rondo_theme_document_title_parts', 20 );
/**
* Enqueue scripts and styles
*/
function rondo_theme_enqueue_assets() {
$dist_dir = RONDO_THEME_DIR . '/dist';
$dist_url = RONDO_THEME_URL . '/dist';
// Check if we have built assets (Vite puts manifest in .vite subdirectory)
$manifest_path = $dist_dir . '/.vite/manifest.json';
if ( ! file_exists( $manifest_path ) ) {
// Fallback to root dist directory
$manifest_path = $dist_dir . '/manifest.json';
}
if ( file_exists( $manifest_path ) ) {
// phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$manifest = json_decode( file_get_contents( $manifest_path ), true );
// Enqueue the main JS file
if ( isset( $manifest['src/main.jsx'] ) ) {
$main_js = $manifest['src/main.jsx'];
if ( isset( $main_js['css'] ) ) {
foreach ( $main_js['css'] as $css_file ) {
wp_enqueue_style(
'prm-theme-style',
$dist_url . '/' . $css_file,
[],
RONDO_THEME_VERSION
);
}
}
if ( isset( $main_js['file'] ) ) {
wp_enqueue_script(
'prm-theme-script',
$dist_url . '/' . $main_js['file'],
[],
null, // Don't add version query string - Vite hashes filenames for cache busting. Query strings break ES module deduplication.
true
);
// Localize script with WordPress data
wp_localize_script( 'prm-theme-script', 'rondoConfig', rondo_get_js_config() );
}
}
} elseif ( defined( 'WP_DEBUG' ) && WP_DEBUG ) {
// Development mode - load from Vite dev server.
add_action(
'wp_head',
function () {
// Vite HMR requires direct script tags, cannot use wp_enqueue_script.
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
echo '<script type="module" src="http://localhost:5173/@vite/client"></script>';
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
echo '<script type="module" src="http://localhost:5173/src/main.jsx"></script>';
}
);
} else {
// Production mode but no build found - show error.
add_action(
'wp_head',
function () {
// phpcs:ignore WordPress.WP.EnqueuedResources.NonEnqueuedScript, WordPress.Security.EscapeOutput.OutputNotEscaped
echo '<script>console.error("Rondo Club: Build files not found. Please run npm run build.");</script>';
}
);
}
}
add_action( 'wp_enqueue_scripts', 'rondo_theme_enqueue_assets' );
/**
* Get JavaScript configuration
*/
function rondo_get_js_config() {
$user = wp_get_current_user();
$user_id = get_current_user_id();
// Get build time from manifest file modification time.
// This ensures every build produces a unique timestamp.
$build_time = null;
$manifest_path = RONDO_THEME_DIR . '/dist/.vite/manifest.json';
if ( file_exists( $manifest_path ) ) {
$build_time = gmdate( 'c', filemtime( $manifest_path ) );
} else {
// Fallback to current time for dev mode (Vite dev server).
$build_time = gmdate( 'c' );
}
// Get user's linked person ID (for filtering current user from attendee lists)
$linked_person_id = $user_id ? (int) get_user_meta( $user_id, 'rondo_linked_person_id', true ) : null;
// Club configuration
$club_settings = \Rondo\Config\ClubConfig::get_all_settings();
return [
'apiUrl' => rest_url(),
'nonce' => wp_create_nonce( 'wp_rest' ),
'siteUrl' => home_url(),
'siteName' => get_bloginfo( 'name' ),
'userId' => $user_id,
'userLogin' => $user ? $user->user_login : '',
'isLoggedIn' => is_user_logged_in(),
'isAdmin' => current_user_can( 'manage_options' ),
'loginUrl' => wp_login_url(),
'logoutUrl' => wp_logout_url( home_url() ),
'adminUrl' => admin_url(),
'themeUrl' => RONDO_THEME_URL,
'version' => wp_get_theme()->get( 'Version' ),
'buildTime' => $build_time,
'currentUserPersonId' => $linked_person_id ?: null,
'clubName' => $club_settings['club_name'],
'volunteerSignupInfo' => $club_settings['volunteer_signup_info'],
'freescoutUrl' => $club_settings['freescout_url'],
'isDemo' => (bool) get_option( 'rondo_is_demo_site', false ),
'isDemoUser' => (bool) get_option( 'rondo_is_demo_site', false ) && $user && $user->user_login === 'demo',
];
}
/**
* Add config to head for initial page load
*/
function rondo_theme_add_config_to_head() {
$config = rondo_get_js_config();
echo '<script>window.rondoConfig = ' . wp_json_encode( $config ) . ';</script>';
}
add_action( 'wp_head', 'rondo_theme_add_config_to_head', 0 );
/**
* Preload the dashboard API endpoint so the browser starts fetching before JS boots.
*
* Fires an authenticated fetch (with X-WP-Nonce) inline in <head> and stashes the
* promise on window.__dashboardPreload for the React app to consume.
*/
function rondo_preload_dashboard_api() {
if ( ! is_user_logged_in() ) {
return;
}
// WordPress renders the SPA shell for every client-side route. Avoid an
// expensive dashboard request when the visitor opened another route
// directly (for example /people/123 or /vrijwilligers).
$request_path = isset( $_SERVER['REQUEST_URI'] ) ? wp_parse_url( wp_unslash( $_SERVER['REQUEST_URI'] ), PHP_URL_PATH ) : '';
$home_path = wp_parse_url( home_url( '/' ), PHP_URL_PATH );
$request_path = '/' . trim( (string) $request_path, '/' );
$home_path = '/' . trim( (string) $home_path, '/' );
if ( $request_path !== $home_path ) {
return;
}
$dashboard_url = rest_url( 'rondo/v1/dashboard' );
$nonce = wp_create_nonce( 'wp_rest' );
echo '<script>window.__dashboardPreload = fetch(' . wp_json_encode( $dashboard_url ) . ', { headers: { "X-WP-Nonce": ' . wp_json_encode( $nonce ) . ' } });</script>' . "\n";
}
add_action( 'wp_head', 'rondo_preload_dashboard_api', 1 );
/**
* Output PWA meta tags for iOS and Android support
*
* vite-plugin-pwa handles manifest generation, but we need to manually
* inject meta tags since WordPress uses PHP templates, not index.html.
*/
function rondo_pwa_meta_tags() {
$theme_url = RONDO_THEME_URL;
// Fixed brand color (electric-cyan from Phase 162)
$brand_color_light = '#0891b2';
$brand_color_dark = '#06b6d4';
?>
<!-- PWA Meta Tags -->
<meta name="mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="default">
<meta name="apple-mobile-web-app-title" content="Rondo Club">
<!-- Apple Touch Icon -->
<link rel="apple-touch-icon" href="<?php echo esc_url( $theme_url . '/public/icons/apple-touch-icon-180x180.png' ); ?>">
<!-- Manifest -->
<link rel="manifest" href="<?php echo esc_url( $theme_url . '/dist/manifest.webmanifest' ); ?>">
<!-- Theme Color (fixed brand colors) -->
<meta name="theme-color" media="(prefers-color-scheme: light)" content="<?php echo $brand_color_light; ?>">
<meta name="theme-color" media="(prefers-color-scheme: dark)" content="<?php echo $brand_color_dark; ?>">
<?php
}
add_action( 'wp_head', 'rondo_pwa_meta_tags', 2 );
/**
* Add Rondo favicon to frontend pages.
*/
function rondo_site_favicon() {
$icon_url = RONDO_THEME_URL . '/public/icons/rondo-logo.png';
echo '<link rel="icon" type="image/png" sizes="192x192" href="' . esc_url( $icon_url ) . '">' . "\n";
echo '<link rel="icon" type="image/svg+xml" href="' . esc_url( RONDO_THEME_URL . '/favicon.svg' ) . '">' . "\n";
}
add_action( 'wp_head', 'rondo_site_favicon', 3 );
/**
* Hide admin bar on frontend - it interferes with the SPA interface
*/
function rondo_theme_remove_admin_bar() {
if ( ! is_admin() ) {
show_admin_bar( false );
}
}
add_action( 'after_setup_theme', 'rondo_theme_remove_admin_bar' );
/**
* Block non-admin users from accessing wp-admin.
*
* Redirects users without manage_options capability to the app home page.
* Exempts AJAX requests, WP-CLI, and cron to avoid breaking functionality.
*/
function rondo_block_wp_admin() {
if ( wp_doing_ajax() ) {
return;
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
return;
}
if ( defined( 'DOING_CRON' ) && DOING_CRON ) {
return;
}
if ( current_user_can( 'manage_options' ) ) {
return;
}
wp_safe_redirect( home_url( '/' ) );
exit;
}
add_action( 'admin_init', 'rondo_block_wp_admin' );
/**
* Redirect WordPress backend URLs to SPA frontend routes
*
* Handles URLs like ?post_type=person&p=123 → /people/123
*/
function rondo_redirect_backend_urls() {
// Don't redirect admin, login, or API requests.
if ( is_admin() || $GLOBALS['pagenow'] === 'wp-login.php' ) {
return;
}
// Check for post_type and p query parameters (WordPress backend URL format)
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$post_type = isset( $_GET['post_type'] ) ? sanitize_key( $_GET['post_type'] ) : '';
// phpcs:ignore WordPress.Security.NonceVerification.Recommended
$post_id = isset( $_GET['p'] ) ? absint( $_GET['p'] ) : 0;
if ( ! $post_type || ! $post_id ) {
return;
}
// Map post types to frontend routes
$route_map = [
'person' => 'people',
'team' => 'teams',
'commissie' => 'commissies',
];
if ( ! isset( $route_map[ $post_type ] ) ) {
return;
}
// Build the SPA URL
$spa_path = '/' . $route_map[ $post_type ] . '/' . $post_id;
$redirect_url = home_url( $spa_path );
// Perform the redirect (301 permanent)
wp_redirect( $redirect_url, 301 );
exit;
}
add_action( 'template_redirect', 'rondo_redirect_backend_urls', 0 ); // Priority 0 to run before other redirects
/**
* Redirect all frontend requests to index.php (SPA)
*/
function rondo_theme_template_redirect() {
// Don't redirect admin, login, or API requests.
if ( is_admin() || $GLOBALS['pagenow'] === 'wp-login.php' ) {
return;
}
// Don't redirect REST API requests
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {
return;
}
// Don't redirect AJAX requests
if ( wp_doing_ajax() ) {
return;
}
// Get the request URI
$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? parse_url( $_SERVER['REQUEST_URI'], PHP_URL_PATH ) : '';
// Remove query string for matching
$path = trim( $request_uri, '/' );
// If this is a request for our app routes, serve index.php
// This includes: /, /people, /people/:id, /teams, /teams/:id, /dates, /dates/:id, /settings, /login
$app_routes = [
'people',
'teams',
'commissies',
'dates',
'settings',
'login',
];
$is_app_route = false;
// Check if it's the root path.
if ( empty( $path ) || $path === '/' ) {
$is_app_route = true;
}
// Check if it starts with any of our app route prefixes.
foreach ( $app_routes as $route ) {
if ( $route === $path || strpos( $path, $route . '/' ) === 0 ) {
$is_app_route = true;
break;
}
}
// Also handle 404s on frontend (WordPress might return 404 for our routes)
if ( $is_app_route || ( is_404() && ! is_admin() ) ) {
// Set status to 200 so React Router can handle it
status_header( 200 );
// Clear any 404 query flags
global $wp_query;
$wp_query->is_404 = false;
// Load index.php for React Router
include get_template_directory() . '/index.php';
exit;
}
}
add_action( 'template_redirect', 'rondo_theme_template_redirect', 1 );
/**
* Handle client-side routing - return index.php for all routes
*/
function rondo_theme_rewrite_rules() {
add_rewrite_rule( '^app/?', 'index.php', 'top' );
add_rewrite_rule( '^app/(.+)/?', 'index.php', 'top' );
}
add_action( 'init', 'rondo_theme_rewrite_rules' );
/**
* Flush rewrite rules once after a deploy that adds new public routes.
*
* Rewrite rules are normally only flushed on theme activation. A plain rsync
* deploy (the usual path) does not re-activate the theme, so new rewrite rules
* — like the /uitleg/{slug} taakuitleg page — would 404 until someone visits
* Settings → Permalinks. Bumping this version flushes exactly once on the first
* request after deploy, mirroring rondo_maybe_add_postmeta_indexes().
*
* Runs late on `init` so every add_rewrite_rule() call has already registered.
*/
function rondo_maybe_flush_rewrite_rules() {
$rewrite_version = '2'; // Bump when adding/changing a rewrite rule.
if ( get_option( 'rondo_rewrite_rules_version' ) === $rewrite_version ) {
return;
}
flush_rewrite_rules();
update_option( 'rondo_rewrite_rules_version', $rewrite_version, true );
}
add_action( 'init', 'rondo_maybe_flush_rewrite_rules', 99 );
add_action( 'init', 'rondo_maybe_add_postmeta_indexes' );
/**
* Theme activation - includes CRM initialization
*/
function rondo_theme_activation() {
// Trigger post type registration (Composer autoloader handles class loading)
$post_types = new PostTypes();
$post_types->register_post_types();
$taxonomies = new Taxonomies();
$taxonomies->register_taxonomies();