-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcrumb.php
More file actions
1190 lines (1067 loc) · 45.8 KB
/
Copy pathcrumb.php
File metadata and controls
1190 lines (1067 loc) · 45.8 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
/**
* Plugin Name: Crumb
* Plugin URI: https://wordpress.org/plugins/crumb/
* Description: Embeds the Crumb meeting finder widget on any page or post using a shortcode.
* Version: 1.8.5
* Author: bmltenabled
* Author URI: https://bmlt.app
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: crumb
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
define( 'CRUMB_VERSION', '1.8.5' );
class Crumb {
private static ?self $instance = null;
private static ?bool $shortcode_geolocation = null;
private static ?int $shortcode_geolocation_radius = null;
private static ?string $shortcode_language = null;
private static ?array $crouton_options = null;
private static array $compat_tags = [];
const DEFAULT_CDN_URL = 'https://cdn.aws.bmlt.app/crumb-widget.js';
const REWRITE_VERSION = '1';
/** Languages the widget supports (kept in sync with src/stores/localization.ts). */
const SUPPORTED_LANGUAGES = [ 'en', 'es', 'fr', 'de', 'pt', 'it', 'sv', 'da', 'el', 'fa', 'pl', 'ru', 'ja' ];
/**
* Tag → forced view for crouton-named shortcodes.
* Map-flavored tags become "both" (map + list) so users don't lose the list view
* they previously saw next to the map. Tabs become plain list.
*/
const CROUTON_VIEW_MAP = [
'crouton_map' => 'both',
'crouton_tabs' => 'list',
'bmlt_map' => 'both',
'bmlt_tabs' => 'list',
];
/**
* Crouton helper shortcodes with no crumb equivalent.
* Registered as empty-string stubs so pages don't show the literal shortcode
* text after crouton is deactivated.
*/
const CROUTON_NOOP_TAGS = [
'init_crouton',
'service_body_names',
'root_service_body',
'bmlt_handlebar',
];
/**
* Crouton count shortcodes → which count to render.
* Server-side; results cached in a transient.
*/
const CROUTON_COUNT_TAGS = [
'meeting_count' => 'meetings',
'bmlt_count' => 'meetings',
'group_count' => 'groups',
];
const COUNTS_CACHE_TTL = HOUR_IN_SECONDS;
const COUNTS_CACHE_TTL_FAILURE = MINUTE_IN_SECONDS;
const COUNTS_FETCH_TIMEOUT = 3;
public static function get_instance(): self {
if ( null === self::$instance ) {
self::$instance = new self();
}
return self::$instance;
}
private function __construct() {
add_shortcode( 'crumb', [ static::class, 'setup_shortcode' ] );
add_action( 'wp_enqueue_scripts', [ static::class, 'assets' ] );
add_action( 'wp_footer', [ static::class, 'localize_config' ], 1 );
add_action( 'admin_menu', [ static::class, 'admin_menu' ] );
add_action( 'admin_init', [ static::class, 'register_settings' ] );
add_action( 'init', [ static::class, 'init_rewrite_rules' ] );
// Priority 20 so this runs after crouton (if active) has registered its own shortcodes.
add_action( 'init', [ static::class, 'register_crouton_shortcodes' ], 20 );
add_filter( 'plugin_action_links_' . plugin_basename( __FILE__ ), [ static::class, 'settings_link' ] );
}
// -------------------------------------------------------------------------
// Activation / Deactivation
// -------------------------------------------------------------------------
public static function activate(): void {
$base_path = get_option( 'crumb_base_path', '' );
if ( ! empty( $base_path ) ) {
self::register_rewrite_rules( $base_path );
flush_rewrite_rules();
}
update_option( 'crumb_rewrite_version', self::REWRITE_VERSION );
}
public static function deactivate(): void {
flush_rewrite_rules();
delete_option( 'crumb_rewrite_version' );
}
// -------------------------------------------------------------------------
// Rewrite Rules
// -------------------------------------------------------------------------
private static function register_rewrite_rules( string $base_path ): void {
if ( empty( $base_path ) ) {
return;
}
$base_path = trim( $base_path, '/' );
add_rewrite_rule(
'^' . preg_quote( $base_path, '/' ) . '(/.*)?$',
'index.php?pagename=' . $base_path,
'top'
);
}
public static function init_rewrite_rules(): void {
$base_path = get_option( 'crumb_base_path', '' );
if ( ! empty( $base_path ) ) {
self::register_rewrite_rules( $base_path );
if ( get_option( 'crumb_rewrite_version' ) !== self::REWRITE_VERSION ) {
flush_rewrite_rules();
update_option( 'crumb_rewrite_version', self::REWRITE_VERSION );
}
}
}
// -------------------------------------------------------------------------
// Crouton Compatibility
//
// Lets sites running the crouton plugin switch to crumb without editing
// pages. Crouton-named shortcodes are mapped to [crumb] output, and crouton's
// saved settings (bmlt_tabs_options) are used as a fallback whenever the
// matching crumb_* option is empty.
// -------------------------------------------------------------------------
private static function crouton_options(): array {
if ( null === self::$crouton_options ) {
$opts = get_option( 'bmlt_tabs_options', [] );
self::$crouton_options = is_array( $opts ) ? $opts : [];
}
return self::$crouton_options;
}
/**
* Map a crumb option key to the matching value from crouton's bmlt_tabs_options.
* Returns '' if there is no equivalent or it's unset.
*/
private static function crouton_fallback_value( string $crumb_key ): string {
$opts = self::crouton_options();
switch ( $crumb_key ) {
case 'crumb_server':
return isset( $opts['root_server'] ) ? (string) $opts['root_server'] : '';
case 'crumb_service_body':
if ( ! empty( $opts['service_bodies'] ) && is_array( $opts['service_bodies'] ) ) {
// Crouton stores each entry as a 4-part CSV string built in
// crouton/js/bmlt_tabs_admin.js: "name,id,parent_id,parent_name".
// The service body ID lives at index [1]. Bare-integer entries
// (legacy / hand-edited) are treated as the ID directly.
$ids = [];
foreach ( $opts['service_bodies'] as $entry ) {
$entry = (string) $entry;
if ( false !== strpos( $entry, ',' ) ) {
$parts = explode( ',', $entry );
$id = isset( $parts[1] ) ? (int) trim( $parts[1] ) : 0;
} else {
$id = (int) trim( $entry );
}
if ( 0 !== $id ) {
$ids[] = $id;
}
}
if ( ! empty( $ids ) ) {
return implode( ',', $ids );
}
}
return isset( $opts['service_body'] ) ? (string) $opts['service_body'] : '';
case 'crumb_format_ids':
return isset( $opts['formats'] ) ? (string) $opts['formats'] : '';
case 'crumb_update_url':
return self::crouton_update_url_to_template(
isset( $opts['report_update_url'] ) ? (string) $opts['report_update_url'] : ''
);
case 'crumb_view':
// Crouton's "Companion Map" setting (bmlt_tabs_options['show_map']):
// '0' → No Map → list
// '1' → Show Map and Table → both
// 'embed' → Embed Map as Table Page → list (crumb has no separate "map tab"
// view; the widget's runtime toggle still
// lets the visitor switch to map)
if ( ! isset( $opts['show_map'] ) ) {
return '';
}
switch ( (string) $opts['show_map'] ) {
case '1':
return 'both';
case '0':
case 'embed':
return 'list';
}
return '';
}
return '';
}
/**
* Like get_option(), but falls back to the equivalent key in bmlt_tabs_options
* when the crumb option is empty/missing. Final fallback is $default.
*/
public static function get_option_or_crouton( string $crumb_key, string $default = '' ): string {
$value = get_option( $crumb_key, '' );
if ( '' !== trim( (string) $value ) ) {
return (string) $value;
}
$fallback = self::crouton_fallback_value( $crumb_key );
return '' !== $fallback ? $fallback : $default;
}
public static function register_crouton_shortcodes(): void {
foreach ( self::CROUTON_VIEW_MAP as $tag => $view ) {
if ( shortcode_exists( $tag ) ) {
continue;
}
self::$compat_tags[] = $tag;
add_shortcode(
$tag,
static function ( $atts ) use ( $view ) {
return self::crouton_compat_shortcode( $atts, $view );
}
);
}
// Helper shortcodes with no crumb equivalent — register as empty-string stubs
// so pages don't render the literal "[bmlt_count]" text after crouton is removed.
// These do NOT trigger widget enqueue, so they're kept out of $compat_tags.
foreach ( self::CROUTON_NOOP_TAGS as $tag ) {
if ( ! shortcode_exists( $tag ) ) {
add_shortcode( $tag, '__return_empty_string' );
}
}
// Count shortcodes — server-side, cached. Also kept out of $compat_tags so they
// don't enqueue the widget JS when used on a page without [crumb].
foreach ( self::CROUTON_COUNT_TAGS as $tag => $type ) {
if ( shortcode_exists( $tag ) ) {
continue;
}
add_shortcode(
$tag,
static function ( $atts ) use ( $tag, $type ) {
return self::count_shortcode( $atts, $tag, $type );
}
);
}
}
public static function crouton_compat_shortcode( $atts, string $view ): string {
$atts = is_array( $atts ) ? $atts : [];
$translated = [];
// View resolution for crouton-compat shortcodes:
// 1. Explicit show_map="1" on the shortcode → view=both (user wrote it, highest).
// 2. Admin Default View (or its crouton show_map fallback) when one is saved →
// let setup_shortcode resolve from the option by omitting `view` here.
// 3. Tag-implied default ('list' for *_tabs, 'both' for *_map) — last resort for
// migrating users who haven't configured a Default View yet.
if ( isset( $atts['show_map'] ) && '1' === (string) $atts['show_map'] ) {
$translated['view'] = 'both';
} elseif ( '' === self::get_option_or_crouton( 'crumb_view', '' ) ) {
$translated['view'] = $view;
}
if ( isset( $atts['root_server'] ) ) {
$translated['server'] = $atts['root_server'];
}
if ( isset( $atts['service_body'] ) ) {
$translated['service_body'] = $atts['service_body'];
} elseif ( isset( $atts['service_body_1'] ) ) {
$translated['service_body'] = $atts['service_body_1'];
}
if ( isset( $atts['formats'] ) ) {
$translated['format_ids'] = $atts['formats'];
}
if ( isset( $atts['report_update_url'] ) ) {
$translated['update_url'] = self::crouton_update_url_to_template( (string) $atts['report_update_url'] );
}
// Crouton's query_string is a raw BMLT query appended to searches; the equivalent in
// the Crumb widget is data-query, which routes through bmlt-query-client's rawQuery().
if ( isset( $atts['query_string'] ) ) {
$translated['query'] = $atts['query_string'];
}
// Crouton's has_areas / has_regions toggles surface the originating service body in
// the listing. Emit the default columns plus service_body so that information stays visible.
$wants_service_body = (
( isset( $atts['has_areas'] ) && filter_var( $atts['has_areas'], FILTER_VALIDATE_BOOLEAN ) ) ||
( isset( $atts['has_regions'] ) && filter_var( $atts['has_regions'], FILTER_VALIDATE_BOOLEAN ) )
);
if ( $wants_service_body && ! isset( $translated['columns'] ) ) {
$translated['columns'] = 'time,distance,name,location,address,service_body';
}
return self::setup_shortcode( $translated );
}
public static function compat_tags(): array {
return self::$compat_tags;
}
/**
* Translate a crouton-style report_update_url (a bare base URL) into a crumb
* update_url template by appending `?meeting_id={meeting_id}` (or
* `&meeting_id={meeting_id}` when the URL already has a query string).
*
* Crouton's templates hardcode `?meeting_id={id}` after the configured URL at
* render time, so the stored value never contains a `{token}` placeholder.
* Crumb requires at least one `{token}` (validated in the widget's
* validUpdateUrl) or the link is dropped — passing the raw crouton value
* through would always lose the link. Empty input returns empty (no
* migration). If the value already contains any `{token}`, it's returned
* unchanged so a deliberately-templated URL isn't double-decorated.
*/
public static function crouton_update_url_to_template( string $url ): string {
$url = trim( $url );
if ( '' === $url ) {
return '';
}
if ( preg_match( '/\{\w+\}/', $url ) ) {
return $url;
}
$separator = ( false === strpos( $url, '?' ) ) ? '?' : '&';
return $url . $separator . 'meeting_id={meeting_id}';
}
// -------------------------------------------------------------------------
// Count Shortcodes ([meeting_count], [bmlt_count], [group_count])
//
// Server-side counts fetched from BMLT GetSearchResults and cached in a
// transient. Output matches crouton's <span id='bmlt_tabs_*'>N</span>
// structure so themes that style those IDs keep working post-migration.
// -------------------------------------------------------------------------
public static function count_shortcode( $atts, string $tag, string $type ): string {
$atts = shortcode_atts(
[
'server' => null,
'service_body' => null,
'format_ids' => null,
],
is_array( $atts ) ? $atts : [],
$tag
);
$server = esc_url_raw( trim( (string) ( $atts['server'] ?? self::get_option_or_crouton( 'crumb_server', 'https://latest.aws.bmlt.app/main_server/' ) ) ) );
$service_body = trim( (string) ( $atts['service_body'] ?? self::get_option_or_crouton( 'crumb_service_body', '' ) ) );
$format_ids = trim( (string) ( $atts['format_ids'] ?? self::get_option_or_crouton( 'crumb_format_ids', '' ) ) );
if ( '' === $server ) {
return '';
}
$counts = self::fetch_counts( $server, $service_body, $format_ids );
$value = isset( $counts[ $type ] ) ? (int) $counts[ $type ] : 0;
return '<span id="bmlt_tabs_' . esc_attr( $tag ) . '">' . esc_html( (string) $value ) . '</span>';
}
/**
* Fetch meeting + group counts from BMLT, with transient caching.
*
* Group definition matches crouton: distinct tuples of
* (service_body_bigint, meeting_name, lat+lng for in-person/hybrid OR
* virtual_meeting_link + virtual_meeting_additional_info for virtual).
*
* @return array{meetings:int, groups:int}
*/
private static function fetch_counts( string $server, string $service_body, string $format_ids ): array {
$cache_key = 'crumb_counts_' . md5( $server . '|' . $service_body . '|' . $format_ids );
$cached = get_transient( $cache_key );
if ( is_array( $cached ) && isset( $cached['meetings'], $cached['groups'] ) ) {
return $cached;
}
$url = self::build_counts_url( $server, $service_body, $format_ids );
$result = wp_remote_get(
$url,
[
'timeout' => self::COUNTS_FETCH_TIMEOUT,
'user-agent' => 'Crumb/' . CRUMB_VERSION . '; ' . home_url(),
]
);
if ( is_wp_error( $result ) || 200 !== (int) wp_remote_retrieve_response_code( $result ) ) {
$counts = [
'meetings' => 0,
'groups' => 0,
];
set_transient( $cache_key, $counts, self::COUNTS_CACHE_TTL_FAILURE );
return $counts;
}
$meetings = json_decode( wp_remote_retrieve_body( $result ), true );
if ( ! is_array( $meetings ) ) {
$meetings = [];
}
$counts = [
'meetings' => count( $meetings ),
'groups' => self::count_groups( $meetings ),
];
set_transient( $cache_key, $counts, self::COUNTS_CACHE_TTL );
return $counts;
}
private static function build_counts_url( string $server, string $service_body, string $format_ids ): string {
// BMLT expects repeated `services[]=N` / `formats[]=N` params, which add_query_arg
// can't produce; build the query string manually.
$parts = [
'switcher=GetSearchResults',
'data_field_key=' . rawurlencode( 'service_body_bigint,meeting_name,venue_type,latitude,longitude,virtual_meeting_link,virtual_meeting_additional_info' ),
];
$service_ids = self::csv_to_ints( $service_body );
foreach ( $service_ids as $id ) {
$parts[] = 'services%5B%5D=' . $id;
}
// Match the widget: recurse into child service bodies whenever any are filtered.
if ( ! empty( $service_ids ) ) {
$parts[] = 'recursive=1';
}
foreach ( self::csv_to_ints( $format_ids ) as $id ) {
$parts[] = 'formats%5B%5D=' . $id;
}
return rtrim( $server, '/' ) . '/client_interface/json/?' . implode( '&', $parts );
}
private static function csv_to_ints( string $csv ): array {
if ( '' === $csv ) {
return [];
}
$ids = [];
foreach ( explode( ',', $csv ) as $part ) {
$n = (int) trim( $part );
if ( 0 !== $n ) {
$ids[] = $n;
}
}
return $ids;
}
private static function count_groups( array $meetings ): int {
$seen = [];
foreach ( $meetings as $m ) {
if ( ! is_array( $m ) ) {
continue;
}
$sb = $m['service_body_bigint'] ?? '';
$name = $m['meeting_name'] ?? '';
if ( 2 === (int) ( $m['venue_type'] ?? 0 ) ) {
$tail = ( $m['virtual_meeting_link'] ?? '' ) . '|' . ( $m['virtual_meeting_additional_info'] ?? '' );
} else {
$tail = number_format( (float) ( $m['latitude'] ?? 0 ), 6, '.', '' ) . '|' . number_format( (float) ( $m['longitude'] ?? 0 ), 6, '.', '' );
}
$seen[ $sb . '|' . $name . '|' . $tail ] = true;
}
return count( $seen );
}
// -------------------------------------------------------------------------
// Shortcode
// -------------------------------------------------------------------------
public static function setup_shortcode( array $atts ): string {
// Use null as sentinel so we can distinguish "not provided" from explicit empty string.
$atts = shortcode_atts(
[
'server' => null,
'service_body' => null,
'format_ids' => null,
'view' => null,
'geolocation' => null,
'geolocation_radius' => null,
'update_url' => null,
'columns' => null,
'show_formats' => null,
'inline_formats' => null,
'language' => null,
'query' => null,
],
$atts,
'crumb'
);
// Store geolocation for merging into CrumbWidgetConfig during wp_footer.
if ( null !== $atts['geolocation'] ) {
self::$shortcode_geolocation = filter_var( $atts['geolocation'], FILTER_VALIDATE_BOOLEAN );
}
if ( null !== $atts['geolocation_radius'] ) {
$radius = (int) $atts['geolocation_radius'];
if ( 0 !== $radius ) {
self::$shortcode_geolocation_radius = $radius;
}
}
// Language must be one of the codes the widget bundles; otherwise we drop it
// and let the widget auto-detect from navigator.language.
if ( null !== $atts['language'] ) {
$lang = strtolower( trim( (string) $atts['language'] ) );
if ( in_array( $lang, self::SUPPORTED_LANGUAGES, true ) ) {
self::$shortcode_language = $lang;
}
}
// Shortcode attribute takes precedence; fall back to saved option only when not provided.
// Crouton settings (bmlt_tabs_options) are used as a fallback when the crumb option is empty.
$server = esc_url( trim( $atts['server'] ?? self::get_option_or_crouton( 'crumb_server', 'https://latest.aws.bmlt.app/main_server/' ) ) );
if ( empty( $server ) ) {
return '<p style="color:red"><strong>Crumb:</strong> a <code>server</code> URL is required.</p>';
}
// null → not in shortcode, use saved option.
// '' → explicitly set to empty in shortcode, omit data-service-body (show all meetings).
$service_body = $atts['service_body'] ?? self::get_option_or_crouton( 'crumb_service_body', '' );
// null → not in shortcode, use saved option. '' → omit (no format lock).
$format_ids = $atts['format_ids'] ?? self::get_option_or_crouton( 'crumb_format_ids', '' );
// Resolve view: shortcode attr → saved option → omit (widget uses its own default).
$view_raw = $atts['view'] ?? self::get_option_or_crouton( 'crumb_view', '' );
$allowed_views = [ 'list', 'map', 'both' ];
$view = in_array( $view_raw, $allowed_views, true ) ? $view_raw : '';
$div = '<div id="crumb-widget" data-server="' . $server . '"';
if ( ! empty( $service_body ) ) {
$div .= ' data-service-body="' . esc_attr( trim( $service_body ) ) . '"';
}
if ( ! empty( $format_ids ) ) {
$div .= ' data-format-ids="' . esc_attr( trim( $format_ids ) ) . '"';
}
if ( ! empty( $view ) ) {
$div .= ' data-view="' . esc_attr( $view ) . '"';
}
$base_path = get_option( 'crumb_base_path', '' );
if ( '' !== $base_path ) {
$div .= ' data-path="/' . esc_attr( trim( $base_path, '/' ) ) . '"';
}
// null → not in shortcode, use saved option. '' → omit (no update link).
$update_url = $atts['update_url'] ?? self::get_option_or_crouton( 'crumb_update_url', '' );
if ( '' !== $update_url ) {
$div .= ' data-update-url="' . esc_attr( trim( $update_url ) ) . '"';
}
// Comma-separated list of columns; widget validates the values.
if ( null !== $atts['columns'] && '' !== trim( (string) $atts['columns'] ) ) {
$div .= ' data-columns="' . esc_attr( trim( (string) $atts['columns'] ) ) . '"';
}
// Show a comma-separated list of format codes (e.g. C, O, BT) beneath each meeting name.
// null → not in shortcode, use saved option. '' → omit (widget default: hidden).
$show_formats_raw = $atts['show_formats'] ?? get_option( 'crumb_show_formats', '' );
if ( null !== $show_formats_raw && '' !== trim( (string) $show_formats_raw ) ) {
$div .= ' data-show-formats="' . ( filter_var( $show_formats_raw, FILTER_VALIDATE_BOOLEAN ) ? '1' : '0' ) . '"';
}
// Comma-separated format key strings (e.g. M,W) highlighted inline next to each meeting name.
// null → not in shortcode, use saved option. '' → omit (no highlights).
$inline_formats = $atts['inline_formats'] ?? get_option( 'crumb_inline_formats', '' );
if ( ! empty( $inline_formats ) ) {
$div .= ' data-inline-formats="' . esc_attr( trim( (string) $inline_formats ) ) . '"';
}
// Raw BMLT query string. When set, the widget routes through rawQuery() and disables
// geolocation, so service_body / format_ids are ignored by the widget — the embedder's
// query string is authoritative. Shortcode-only (no admin setting).
if ( null !== $atts['query'] && '' !== trim( (string) $atts['query'] ) ) {
$div .= ' data-query="' . esc_attr( trim( (string) $atts['query'] ) ) . '"';
}
$div .= '></div>';
$template = get_option( 'crumb_css_template', '' );
if ( 'full_width' === $template ) {
return '<div class="crumb-full-width">' . $div . '</div>';
}
if ( 'full_width_force' === $template ) {
return '<div class="crumb-full-width-force">' . $div . '</div>';
}
return $div;
}
// -------------------------------------------------------------------------
// Assets
// -------------------------------------------------------------------------
public static function assets(): void {
global $post;
if ( ! $post ) {
return;
}
// Check for [crumb] plus any crouton-named tags this plugin actually registered.
// (Tags claimed by an active crouton plugin won't be in self::$compat_tags.)
$tags = array_merge( [ 'crumb' ], self::$compat_tags );
$found = false;
foreach ( $tags as $tag ) {
if ( has_shortcode( $post->post_content, $tag ) ) {
$found = true;
break;
}
}
if ( ! $found ) {
return;
}
wp_enqueue_script(
'crumb',
self::DEFAULT_CDN_URL,
[],
CRUMB_VERSION,
[
'strategy' => 'defer',
'in_footer' => true,
]
);
wp_register_style( 'crumb-style', false, [], CRUMB_VERSION );
wp_enqueue_style( 'crumb-style' );
wp_add_inline_style( 'crumb-style', wp_strip_all_tags( self::build_css() ) );
}
private static function build_css(): string {
$template = get_option( 'crumb_css_template', '' );
if ( 'full_width' === $template ) {
return '.crumb-full-width { width: 100%; }';
}
if ( 'full_width_force' === $template ) {
return '.crumb-full-width-force { width: 100vw !important; position: relative !important; left: 50% !important; margin-left: -50vw !important; box-sizing: border-box !important; max-width: none !important; }';
}
return '';
}
/**
* Output CrumbWidgetConfig via wp_localize_script.
*
* Hooked to wp_footer (priority 1) so it runs after shortcode processing
* but before the deferred script prints.
*/
public static function localize_config(): void {
if ( ! wp_script_is( 'crumb', 'enqueued' ) ) {
return;
}
// Build config: stored option → filter → shortcode geolocation override.
$config = self::get_config();
/**
* Filter the CrumbWidgetConfig passed to the widget.
*
* Add this to your theme's functions.php to configure the widget:
*
* add_filter( 'crumb_config', function( $config ) {
* return array_merge( $config, [
* 'language' => 'es',
* 'geolocation' => true,
* 'geolocationRadius' => -50,
* 'height' => 800,
* 'columns' => [ 'time', 'name', 'location', 'address', 'service_body' ],
* ] );
* } );
*
* See https://crumb.bmlt.app/ for all available options.
*
* @param array $config Configuration array passed to CrumbWidgetConfig.
*/
$config = (array) apply_filters( 'crumb_config', $config );
if ( null !== self::$shortcode_geolocation ) {
$config['geolocation'] = self::$shortcode_geolocation;
}
if ( null !== self::$shortcode_geolocation_radius ) {
$config['geolocationRadius'] = self::$shortcode_geolocation_radius;
}
// Shortcode language overrides; otherwise fall back to the saved option.
// Empty string in either path means "let the widget auto-detect".
if ( null !== self::$shortcode_language ) {
$config['language'] = self::$shortcode_language;
} elseif ( ! isset( $config['language'] ) ) {
$saved_language = get_option( 'crumb_language', '' );
if ( '' !== $saved_language && in_array( $saved_language, self::SUPPORTED_LANGUAGES, true ) ) {
$config['language'] = $saved_language;
}
}
if ( ! empty( $config ) ) {
wp_add_inline_script( 'crumb', 'var CrumbWidgetConfig = ' . wp_json_encode( $config ) . ';', 'before' );
}
}
private static function get_config(): array {
$config_json = get_option( 'crumb_widget_config', '' );
if ( ! empty( $config_json ) ) {
$decoded = json_decode( $config_json, true );
$config = ( json_last_error() === JSON_ERROR_NONE ) ? $decoded : [];
} else {
$config = [];
}
// Dedicated geolocation radius field — JSON config takes precedence if already set.
$radius_opt = get_option( 'crumb_geolocation_radius', '' );
if ( '' !== $radius_opt && ! isset( $config['geolocationRadius'] ) ) {
$config['geolocationRadius'] = (int) $radius_opt;
}
// Dedicated geolocation field — JSON config takes precedence if already set.
$geolocation_opt = get_option( 'crumb_geolocation', '' );
if ( '' !== $geolocation_opt && ! isset( $config['geolocation'] ) ) {
$config['geolocation'] = ( '1' === $geolocation_opt );
}
// Dedicated hide header field — JSON config takes precedence if already set.
$hide_header_opt = get_option( 'crumb_hide_header', '' );
if ( '' !== $hide_header_opt && ! isset( $config['hideHeader'] ) ) {
$config['hideHeader'] = ( '1' === $hide_header_opt );
}
return $config;
}
public static function sanitize_base_path( string $input ): string {
$old_value = get_option( 'crumb_base_path', '' );
$new_value = sanitize_text_field( trim( $input, '/' ) );
if ( $old_value !== $new_value ) {
update_option( 'crumb_rewrite_version', '' );
}
return $new_value;
}
public static function sanitize_geolocation_radius( string $input ): string {
$trimmed = trim( $input );
if ( '' === $trimmed ) {
return '';
}
$val = (int) $trimmed;
return ( 0 !== $val ) ? (string) $val : '';
}
public static function sanitize_geolocation( string $input ): string {
$trimmed = trim( $input );
if ( '' === $trimmed ) {
return '';
}
return filter_var( $trimmed, FILTER_VALIDATE_BOOLEAN ) ? '1' : '0';
}
public static function sanitize_hide_header( string $input ): string {
$trimmed = trim( $input );
if ( '' === $trimmed ) {
return '';
}
return filter_var( $trimmed, FILTER_VALIDATE_BOOLEAN ) ? '1' : '0';
}
public static function sanitize_show_formats( string $input ): string {
$trimmed = trim( $input );
if ( '' === $trimmed ) {
return '';
}
return filter_var( $trimmed, FILTER_VALIDATE_BOOLEAN ) ? '1' : '0';
}
public static function sanitize_language( string $input ): string {
$lang = strtolower( trim( $input ) );
return in_array( $lang, self::SUPPORTED_LANGUAGES, true ) ? $lang : '';
}
public static function sanitize_config( string $input ): string {
$input = trim( $input );
if ( '' === $input ) {
return '';
}
$decoded = json_decode( $input, true );
if ( json_last_error() !== JSON_ERROR_NONE ) {
add_settings_error(
'crumb_widget_config',
'invalid_json',
'Widget Configuration must be valid JSON. Your previous value has been preserved.',
'error'
);
return get_option( 'crumb_widget_config', '' );
}
return wp_json_encode( $decoded, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES );
}
// -------------------------------------------------------------------------
// Admin
// -------------------------------------------------------------------------
public static function settings_link( array $links ): array {
$settings_url = admin_url( 'options-general.php?page=crumb' );
$links[] = "<a href='{$settings_url}'>Settings</a>";
return $links;
}
public static function admin_menu(): void {
add_options_page(
'Crumb Settings',
'Crumb',
'manage_options',
'crumb',
[ static::class, 'settings_page' ]
);
}
public static function register_settings(): void {
$group = 'crumb-group';
register_setting( $group, 'crumb_server', 'esc_url_raw' );
register_setting( $group, 'crumb_service_body', 'sanitize_text_field' );
register_setting( $group, 'crumb_format_ids', 'sanitize_text_field' );
register_setting( $group, 'crumb_css_template', 'sanitize_text_field' );
register_setting( $group, 'crumb_view', 'sanitize_text_field' );
register_setting( $group, 'crumb_update_url', 'sanitize_text_field' );
register_setting( $group, 'crumb_inline_formats', 'sanitize_text_field' );
register_setting(
$group,
'crumb_show_formats',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_show_formats' ],
]
);
register_setting(
$group,
'crumb_language',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_language' ],
]
);
register_setting(
$group,
'crumb_geolocation',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_geolocation' ],
]
);
register_setting(
$group,
'crumb_geolocation_radius',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_geolocation_radius' ],
]
);
register_setting(
$group,
'crumb_hide_header',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_hide_header' ],
]
);
register_setting(
$group,
'crumb_base_path',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_base_path' ],
]
);
register_setting(
$group,
'crumb_widget_config',
[
'type' => 'string',
'sanitize_callback' => [ static::class, 'sanitize_config' ],
]
);
}
public static function settings_page(): void {
$example_config = wp_json_encode(
[
'language' => 'en',
'geolocation' => true,
'geolocationRadius' => -50,
'height' => 800,
'darkMode' => 'auto',
'nowOffset' => 10,
'hideHeader' => false,
'updateUrl' => 'https://example.org/meeting-update-form/?meeting_id={meeting_id}',
'columns' => [ 'time', 'name', 'location', 'address' ],
'showFormats' => false,
'inlineFormats' => [ 'M', 'W' ],
'map' => [
'tiles' => [
'url' => '...',
'attribution' => '...',
],
'markers' => [
'location' => [
'html' => '...',
'width' => 23,
'height' => 33,
],
],
],
],
JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES
);
?>
<div class="wrap">
<h1>Crumb Settings</h1>
<?php settings_errors(); ?>
<form method="post" action="options.php">
<?php settings_fields( 'crumb-group' ); ?>
<table class="form-table">
<tr>
<th scope="row"><label for="crumb_server">BMLT Server URL</label></th>
<td>
<input type="url" id="crumb_server" name="crumb_server"
value="<?php echo esc_attr( self::get_option_or_crouton( 'crumb_server', 'https://latest.aws.bmlt.app/main_server/' ) ); ?>"
class="regular-text" placeholder="https://your-server/main_server" />
<p class="description">Required. The full URL to your BMLT Server.</p>
</td>
</tr>
<tr>
<th scope="row"><label for="crumb_service_body">Service Body IDs</label></th>
<td>
<input type="text" id="crumb_service_body" name="crumb_service_body"
value="<?php echo esc_attr( self::get_option_or_crouton( 'crumb_service_body', '' ) ); ?>"
class="regular-text" placeholder="42 or 42,57,103" />
<p class="description">Optional. Single ID or comma-separated list. Leave empty to show all meetings. Child service bodies are always included.</p>
</td>
</tr>
<tr>
<th scope="row"><label for="crumb_format_ids">Format IDs</label></th>
<td>
<input type="text" id="crumb_format_ids" name="crumb_format_ids"
value="<?php echo esc_attr( self::get_option_or_crouton( 'crumb_format_ids', '' ) ); ?>"
class="regular-text" placeholder="17 or 17,54,78" />
<p class="description">Optional. Single ID or comma-separated list of BMLT format IDs to lock the widget to. Leave empty to show all formats. Can be overridden per-page via the shortcode <code>format_ids</code> attribute.</p>
</td>
</tr>
<tr>
<th scope="row"><label for="crumb_show_formats"><?php esc_html_e( 'Show Formats', 'crumb' ); ?></label></th>
<td>
<?php $current_show_formats = get_option( 'crumb_show_formats', '' ); ?>
<select id="crumb_show_formats" name="crumb_show_formats">
<option value="" <?php selected( $current_show_formats, '' ); ?>><?php esc_html_e( '— Widget Default (hidden) —', 'crumb' ); ?></option>
<option value="0" <?php selected( $current_show_formats, '0' ); ?>><?php esc_html_e( 'Hidden', 'crumb' ); ?></option>
<option value="1" <?php selected( $current_show_formats, '1' ); ?>><?php esc_html_e( 'Shown', 'crumb' ); ?></option>
</select>
<p class="description">Optional. Shows a comma-separated list of format codes (e.g. <code>C, O, BT</code>) beneath each meeting name in the list/cards view. Can be overridden per-page via the shortcode <code>show_formats</code> attribute.</p>
</td>
</tr>
<tr>
<th scope="row"><label for="crumb_inline_formats"><?php esc_html_e( 'Inline Formats', 'crumb' ); ?></label></th>
<td>
<input type="text" id="crumb_inline_formats" name="crumb_inline_formats"
value="<?php echo esc_attr( get_option( 'crumb_inline_formats', '' ) ); ?>"
class="regular-text" placeholder="M,W" />
<p class="description">Optional. Comma-separated BMLT format key strings (e.g. <code>M,W</code>) to highlight inline next to each meeting name, rendered as their localized names (e.g. "Men", "Women"). Keys vary by server and only show where used. Can be overridden per-page via the shortcode <code>inline_formats</code> attribute.</p>