-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathjetonomy.php
More file actions
881 lines (806 loc) · 33.5 KB
/
Copy pathjetonomy.php
File metadata and controls
881 lines (806 loc) · 33.5 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
<?php
/**
* Plugin Name: Jetonomy
* Plugin URI: https://store.wbcomdesigns.com/jetonomy/
* Description: Next-gen discussion platform for WordPress - forums, Q&A, and more.
* Version: 1.9.1
* Requires at least: 6.7
* Requires PHP: 8.1
* Author: Wbcom Designs
* Author URI: https://wbcomdesigns.com/
* License: GPL v2 or later
* License URI: https://www.gnu.org/licenses/gpl-2.0.html
* Text Domain: jetonomy
* Domain Path: /languages
*/
defined( 'ABSPATH' ) || exit;
define( 'JETONOMY_VERSION', '1.9.1' );
// Schema milestone, deliberately ahead of JETONOMY_VERSION, and it has to be.
//
// The rule_lookup index is now in CREATE TABLE, so a fresh install gets it from
// dbDelta and needs no migration. An install already running 1.9.0 does not:
// dbDelta only runs for it through the version-change path, and if this
// constant read 1.9.0 too, run() would compare 1.9.0 against a stored 1.9.0,
// decide there was nothing to do, and leave that site doing a full table scan
// on every course and account pageview - silently, because nothing errors.
//
// So both routes are covered: CREATE TABLE for new sites, migration 1_9_1 for
// existing ones. The two constants are independent; the plugin version is a
// release number and stays at 1.9.0 where the release rule puts it.
define( 'JETONOMY_DB_VERSION', '1.9.2' );
define( 'JETONOMY_FILE', __FILE__ );
define( 'JETONOMY_DIR', plugin_dir_path( __FILE__ ) );
define( 'JETONOMY_URL', plugin_dir_url( __FILE__ ) );
// Action Scheduler — bundled in free so Pro extensions (email digest, badges,
// AI, reply-by-email, web-push, webhooks) and any future cron-heavy work get
// reliable background processing instead of WP-Cron's "next page view" model.
// AS self-resolves to the highest registered version when multiple plugins ship it.
// JETONOMY_SMOKE_TEST guard: tools/smoke-test.php boots with a minimal WP stub
// that doesn't carry AS's required functions/constants (EP_NONE, register_post_type
// with full args, etc.). Real WordPress always has these, so this is smoke-only.
if ( ! defined( 'JETONOMY_SMOKE_TEST' ) ) {
require_once JETONOMY_DIR . 'libs/action-scheduler/action-scheduler.php';
}
require_once JETONOMY_DIR . 'includes/class-autoloader.php';
Jetonomy\Autoloader::register();
// functions.php defines Jetonomy\table(), Jetonomy\now(), Jetonomy\base_url() — plain
// functions that the autoloader can't pick up. Must load BEFORE class-jetonomy so
// Migrator runs (fired on plugins_loaded -> init) can call these helpers.
require_once JETONOMY_DIR . 'includes/functions.php';
// Public global helpers for templates (jetonomy_post_title_or_excerpt etc.).
// Kept separate from functions.php because functions.php is namespaced
// (Jetonomy\*) while helpers.php exposes global functions that templates and
// child themes can call without namespace imports.
require_once JETONOMY_DIR . 'includes/helpers.php';
require_once JETONOMY_DIR . 'includes/class-jetonomy.php';
function jetonomy(): Jetonomy\Jetonomy {
return Jetonomy\Jetonomy::instance();
}
jetonomy();
// Multisite-aware activation helpers -- declared in the Jetonomy namespace.
require_once JETONOMY_DIR . 'includes/functions-multisite.php';
// EDD Software Licensing SDK — free plugin auto-updates with preset key.
add_action(
'edd_sl_sdk_registry',
function ( $registry ) {
$registry->register(
array(
'id' => 'jetonomy',
'url' => 'https://wbcomdesigns.com',
'item_id' => 1660320,
'version' => JETONOMY_VERSION,
'file' => JETONOMY_FILE,
'license' => 'wbcomfreec7e2a9b45d8f1c3e6a0b9d2f7c4e8a11',
)
);
}
);
// SDK lives at libs/ (committed, ships in zip). Pro reads it via the same path.
//
// Load the vendored EDD SL SDK only when the package is COMPLETE. A partial
// build or extract that keeps the entry file but drops libs/edd-sl-sdk/src
// would fatal inside the SDK the moment it instantiates a src class — the
// entry file registers callbacks against \EasyDigitalDownloads\Updater\Versions
// with no guard of its own, so requiring it half-present white-screened every
// page (Basecamp 10163871548; the WB Listora 1.2.1 stripped-SDK shape). Guard
// on the source being present and degrade to "updates disabled" with a soft
// admin notice instead — licensing only gates updates, never features, so the
// community keeps working. Mirrors BuddyNext (the portfolio reference for this
// SDK's loading) and Learnomy 1.9.1.
if ( file_exists( JETONOMY_DIR . 'libs/edd-sl-sdk/edd-sl-sdk.php' )
&& file_exists( JETONOMY_DIR . 'libs/edd-sl-sdk/src/Versions.php' ) ) {
require_once JETONOMY_DIR . 'libs/edd-sl-sdk/edd-sl-sdk.php';
} elseif ( is_admin() ) {
add_action(
'admin_notices',
static function () {
echo '<div class="notice notice-warning"><p>'
. esc_html__( 'Jetonomy: the bundled licensing and update SDK is incomplete, so automatic updates are turned off. Reinstall the plugin from a complete package to restore them. Every other feature works normally.', 'jetonomy' )
. '</p></div>';
}
);
}
// Update-screen icon. WordPress only auto-resolves icons for wp.org-hosted
// plugins; a self-hosted update renders a broken placeholder unless the update
// object carries icon URLs. The store response MAY provide them — this bundled
// SVG guarantees the row renders branded even when it does not (asset ships in
// the zip and is served from the customer's own site, so it can never 404 on a
// store outage). Store-provided icons win: we only fill the key when empty.
add_filter(
'site_transient_update_plugins',
function ( $transient ) {
if ( ! is_object( $transient ) ) {
return $transient;
}
$basename = plugin_basename( JETONOMY_FILE );
$icon_1x = plugins_url( 'assets/images/update-icon-128.png', JETONOMY_FILE );
$icon_2x = plugins_url( 'assets/images/update-icon-256.png', JETONOMY_FILE );
foreach ( array( 'response', 'no_update' ) as $bucket ) {
if ( isset( $transient->{$bucket}[ $basename ] ) && empty( $transient->{$bucket}[ $basename ]->icons ) ) {
$transient->{$bucket}[ $basename ]->icons = array(
'1x' => $icon_1x,
'2x' => $icon_2x,
'default' => $icon_2x,
);
}
}
return $transient;
}
);
// Auto-activate the preset license key on first load so downloads work.
add_action(
'admin_init',
function () {
// Owner opt-out: define JETONOMY_NO_LICENSE_PHONE_HOME to disable the
// store call entirely (air-gapped / privacy-strict installs).
if ( defined( 'JETONOMY_NO_LICENSE_PHONE_HOME' ) && JETONOMY_NO_LICENSE_PHONE_HOME ) {
return;
}
$preset_key = 'wbcomfreec7e2a9b45d8f1c3e6a0b9d2f7c4e8a11';
$option = 'jetonomy_license_key';
$activated = 'jetonomy_preset_activated';
// Already activated for this domain — skip.
if ( get_option( $activated ) ) {
return;
}
// Back off after any attempt so a server that can't reach the store does
// NOT repeat a blocking request on every admin pageview (the previous
// behaviour: 15s hang per page whenever egress failed). At most one
// attempt per 12h until activation succeeds.
if ( get_transient( 'jetonomy_preset_activation_backoff' ) ) {
return;
}
set_transient( 'jetonomy_preset_activation_backoff', 1, 12 * HOUR_IN_SECONDS );
// Store the key so the SDK can find it.
update_option( $option, $preset_key, false );
// Activate with the EDD store. Short timeout so a slow/unreachable store
// can't stall the admin for 15 seconds.
$response = wp_remote_post(
'https://wbcomdesigns.com',
array(
'timeout' => 5,
'body' => array(
'edd_action' => 'activate_license',
'license' => $preset_key,
'item_id' => 1660320,
'url' => home_url(),
),
)
);
if ( ! is_wp_error( $response ) ) {
$body = json_decode( wp_remote_retrieve_body( $response ), true );
if ( 'valid' === ( $body['license'] ?? '' ) ) {
update_option( $activated, 1, false );
// NOTE: usage tracking is NOT auto-enabled here. Enrolling a site
// in tracking without explicit consent is a privacy overreach;
// the owner opts in via the settings toggle instead.
}
}
}
);
/**
* Render an SVG icon from assets/icons/.
*
* @param string $name Icon slug (filename without .svg).
* @param int $size Width/height in px (default 24).
* @return string Sanitized SVG markup.
*/
function jetonomy_icon( string $name, int $size = 24 ): string {
static $cache = array();
if ( isset( $cache[ $name ] ) ) {
$svg = $cache[ $name ];
} else {
$file = JETONOMY_DIR . 'assets/icons/' . sanitize_file_name( $name ) . '.svg';
if ( ! file_exists( $file ) ) {
return '';
}
$svg = (string) file_get_contents( $file ); // phpcs:ignore WordPress.WP.AlternativeFunctions.file_get_contents_file_get_contents
$cache[ $name ] = $svg;
}
$svg = str_replace( '<svg ', '<svg width="' . $size . '" height="' . $size . '" ', $svg );
return $svg;
}
/**
* Echo an SVG icon.
*
* @param string $name Icon slug.
* @param int $size Width/height in px.
*/
function jetonomy_echo_icon( string $name, int $size = 24 ): void {
echo jetonomy_icon( $name, $size ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- SVG from trusted local file.
}
/**
* Render a space icon (Lucide-only contract, 1.4.0).
*
* The plugin contract is "Lucide icons only — no emoji in shipped UI."
* Existing Space rows store whatever the admin (or the demo seeder)
* pasted in the icon field, including unicode emoji. This helper:
*
* - empty / null → renders the default `users` icon
* - matches one of the SVGs in `assets/icons/` → renders that Lucide icon
* - starts with `dashicons-` → renders the dashicon (legacy compat)
* - anything else (emoji, free-text, unknown name) → renders the
* default `users` icon, NEVER the raw value
*
* Output is always wrapped in a span carrying the supplied class so
* existing CSS selectors keep working without changes.
*
* @param mixed $icon The space's `icon` column value.
* @param int $size Pixel size.
* @param string $class_name Wrapper class name.
*/
function jetonomy_render_space_icon( $icon, int $size = 24, string $class_name = 'jt-space-card-icon', string $type_fallback = '' ): void {
$icon = is_string( $icon ) ? trim( $icon ) : '';
if ( '' !== $icon && 0 === strpos( $icon, 'dashicons-' ) ) {
echo '<span class="' . esc_attr( $class_name ) . ' dashicons ' . esc_attr( $icon ) . '" aria-hidden="true"></span>';
return;
}
$lucide = '';
if ( '' !== $icon && preg_match( '/^[a-z0-9][a-z0-9-]{0,40}$/', $icon ) ) {
$svg_path = JETONOMY_DIR . 'assets/icons/' . $icon . '.svg';
if ( file_exists( $svg_path ) ) {
$lucide = $icon;
}
}
// When the stored icon is missing / emoji / unknown, pick a default
// based on space type so customers don't see the same icon on every
// card. The defaults are picked for breadth — a cluster of icon-less
// spaces reads visually varied without admin work.
//
// 1.4.1: qa default flipped from `help-circle` to `book-open`.
// help-circle reads as a literal question-mark glyph and looked
// repetitive on customer sites that ran several support-style Q&A
// spaces side by side. `book-open` carries the same "answers /
// knowledge" intent without the on-the-nose question-mark visual.
if ( '' === $lucide ) {
$type_defaults = array(
'qa' => 'book-open',
'ideas' => 'lightbulb',
'feed' => 'hash',
'forum' => 'message-circle',
);
$lucide = $type_defaults[ $type_fallback ] ?? 'users';
}
echo '<span class="' . esc_attr( $class_name ) . '" aria-hidden="true">';
echo jetonomy_icon( $lucide, $size ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted local SVG.
echo '</span>';
}
/**
* Map legacy emoji-byte strings stored in `wp_jt_pro_badges.icon` to the
* Lucide slug they should render as today.
*
* Used by the badge icon helper (fallback resolution) AND by the one-shot
* upgrade migration that normalises saved rows. Returning null means the
* input wasn't a known legacy emoji — caller decides the default.
*
* @param string $icon Raw stored value (may be UTF-8 emoji, a Lucide slug, or empty).
* @return string|null Lucide slug to render, or null when the input isn't a recognised legacy emoji.
*/
function jetonomy_map_legacy_badge_emoji( string $icon ): ?string {
$map = array(
"\xE2\x9C\x8D\xEF\xB8\x8F" => 'edit',
"\xF0\x9F\x93\x9D" => 'edit',
"\xF0\x9F\x92\xAC" => 'message-circle',
"\xF0\x9F\x8F\x86" => 'award',
"\xE2\x9C\x85" => 'check-circle',
"\xE2\xAD\x90" => 'star',
"\xF0\x9F\x8C\x9F" => 'star',
"\xF0\x9F\x8E\x96\xEF\xB8\x8F" => 'award',
"\xF0\x9F\x96\x90\xEF\xB8\x8F" => 'hand',
"\xF0\x9F\x9A\xA9" => 'flag',
);
return $map[ $icon ] ?? null;
}
/**
* Render a badge icon — Lucide-only, with graceful fallback.
*
* Mirrors {@see jetonomy_render_space_icon()} but tuned for the small badge
* display sizes used in the admin table and the my-badges profile card.
* Resolution order: stored Lucide slug → emoji-byte mapping → 'award' default.
*
* @param mixed $icon The badge's `icon` column value.
* @param int $size Pixel size for the SVG.
* @param string $class_name Wrapper class name.
*/
function jetonomy_render_badge_icon( $icon, int $size = 24, string $class_name = 'jt-badge-icon' ): void {
$icon = is_string( $icon ) ? trim( $icon ) : '';
$lucide = '';
if ( '' !== $icon && preg_match( '/^[a-z0-9][a-z0-9-]{0,40}$/', $icon ) ) {
$svg_path = JETONOMY_DIR . 'assets/icons/' . $icon . '.svg';
if ( file_exists( $svg_path ) ) {
$lucide = $icon;
}
}
if ( '' === $lucide && '' !== $icon ) {
$mapped = jetonomy_map_legacy_badge_emoji( $icon );
if ( null !== $mapped ) {
$svg_path = JETONOMY_DIR . 'assets/icons/' . $mapped . '.svg';
if ( file_exists( $svg_path ) ) {
$lucide = $mapped;
}
}
}
if ( '' === $lucide ) {
$lucide = 'award';
}
echo '<span class="' . esc_attr( $class_name ) . '" aria-hidden="true">';
echo jetonomy_icon( $lucide, $size ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped -- trusted local SVG.
echo '</span>';
}
/**
* Format post/reply content with @mention and #hashtag auto-linking.
*
* Expects already-sanitized HTML (via wp_kses_post). Applies regex only
* to text segments outside HTML tags to avoid mangling existing markup.
* Individual replacement values are escaped with esc_html/esc_url.
*
* @param string $content Sanitized HTML content string.
* @return string Processed content with mention and tag links.
*/
/**
* Resolve whether voting is enabled on a given space.
*
* Mirrors the server-side gate in `Permission_Engine::can()` (the
* 'vote' branch). The admin checkbox stores `'1'` for enabled; an
* unset key defaults to allowed so spaces seeded before this feature
* existed don't suddenly lose voting. Used at every frontend render
* site that draws vote controls so the UI never shows an affordance
* the server will refuse.
*
* @param object|null $space Space object (or null when no space context).
* @return bool True when voting is allowed on the space.
*/
function jetonomy_space_allows_voting( $space ): bool {
if ( ! $space || empty( $space->id ) ) {
return true;
}
$settings = \Jetonomy\Models\Space::get_settings( (int) $space->id );
if ( ! isset( $settings['allow_voting'] ) ) {
return true;
}
return '1' === (string) $settings['allow_voting'];
}
/**
* May THIS viewer cast a vote in this space?
*
* Note that jetonomy_space_allows_voting() answers a different question -
* whether the space has voting switched on at all - and it is still the right
* gate for whether the vote column exists. Templates were then using "is
* someone logged in" to decide whether to render the BUTTONS, which is not the
* same as being allowed to press them: a member admitted by a Read-grant rule
* got working vote buttons, and clicking one returned 403 with nothing on
* screen.
*
* Permission_Engine::can() already accounts for the rule's grant level, the
* space's allow_voting setting, bans and silences, so a template that asks this
* cannot drift out of step with what the server will accept.
*
* Returning false does not hide the score - the templates already have a
* read-only branch for logged-out visitors, and this simply routes read-only
* members into it. Counts stay visible; only the controls go.
*
* @param object|null $space Space row.
* @return bool
*/
function jetonomy_viewer_can_vote( $space ): bool {
if ( ! is_user_logged_in() || ! jetonomy_space_allows_voting( $space ) ) {
return false;
}
return \Jetonomy\Permissions\Permission_Engine::can(
get_current_user_id(),
'vote',
( $space && ! empty( $space->id ) ) ? (int) $space->id : null
);
}
/**
* Resolve a customer-facing label for an idea roadmap status enum value.
*
* Mirrors the column labels in `templates/views/space-roadmap.php`. Used
* on idea cards in space listings and on the single-post page when the
* post belongs to a `type=ideas` space. Unknown values fall back to
* "Submitted" so a stale enum never renders an empty pill.
*
* @param string $status One of Post::valid_idea_statuses(), or empty.
* @return string Translated label.
*/
function jetonomy_idea_status_label( string $status ): string {
$labels = array(
'planned' => __( 'Planned', 'jetonomy' ),
'in_progress' => __( 'In Progress', 'jetonomy' ),
'shipped' => __( 'Shipped', 'jetonomy' ),
'declined' => __( 'Declined', 'jetonomy' ),
);
return $labels[ $status ] ?? '';
}
/**
* Render an idea-status pill for a post on a `type=ideas` space.
*
* Echoes a small <span class="jt-idea-pill jt-idea-pill-{status}"> so
* the listing card and the post header both look the same. Status colors
* come from CSS so themes can override them without inline-style fights.
*
* @param string $status One of Post::valid_idea_statuses(), or empty.
*/
function jetonomy_render_idea_status_pill( string $status ): void {
if ( '' === $status || ! in_array( $status, \Jetonomy\Models\Post::valid_idea_statuses(), true ) ) {
return;
}
echo '<span class="jt-idea-pill jt-idea-pill-' . esc_attr( $status ) . '">'
. esc_html( jetonomy_idea_status_label( $status ) )
. '</span>';
}
/**
* Customer-facing label for a space `type` enum value.
*
* Mirrors the schema enum in `class-schema.php` (forum | qa | ideas | feed).
* Unknown values fall back to "Forum" so the badge never renders empty —
* matches the schema DEFAULT.
*
* @param string $type Space type enum value.
* @return string Translated label.
*/
function jetonomy_space_type_label( string $type ): string {
switch ( $type ) {
case 'qa':
return _x( 'Q&A', 'space type label', 'jetonomy' );
case 'ideas':
return _x( 'Ideas', 'space type label', 'jetonomy' );
case 'feed':
return _x( 'Feed', 'space type label', 'jetonomy' );
case 'forum':
default:
return _x( 'Forum', 'space type label', 'jetonomy' );
}
}
/**
* Lucide icon name to pair with a space `type` badge.
*
* Kept in one place so the directory cards, the space header, and any
* future admin chip all show the same glyph for a given type.
*/
function jetonomy_space_type_icon( string $type ): string {
switch ( $type ) {
case 'qa':
return 'book-open';
case 'ideas':
return 'lightbulb';
case 'feed':
return 'rss';
case 'forum':
default:
return 'message-circle';
}
}
/**
* Customer-facing label for a space `join_policy` enum value.
*
* Mirrors the schema enum in `class-schema.php` (open | approval | invite).
* "Open" returns an empty string by design — the default policy is the
* implicit zero state and we don't want every card to carry a noisy
* "Open" pill.
*/
function jetonomy_space_join_policy_label( string $join_policy ): string {
switch ( $join_policy ) {
case 'approval':
return __( 'Approval required', 'jetonomy' );
case 'invite':
return __( 'Invite only', 'jetonomy' );
case 'open':
default:
return '';
}
}
/**
* Render the type + join-policy badges on a space directory card.
*
* Pairs with the existing "Hidden" badge in `home.php` and `category.php`
* so all three pieces of space metadata sit in the same horizontal strip.
*
* - Type badge always renders. Default `forum` is shown explicitly so
* mixed-type listings stay visually consistent (every card carries
* exactly one type chip; readers don't have to infer the absence as
* "this one is the default").
* - Join-policy badge only renders for `approval` / `invite` (the
* default `open` is left implicit per the label helper above).
*
* Echoes nothing when `$space` is missing the relevant fields, so the
* helper is safe to drop into any template that already received a
* Space model row.
*
* @param object|null $space Space model row (or null/missing fields).
*/
function jetonomy_render_space_meta_badges( $space ): void {
if ( ! is_object( $space ) ) {
return;
}
$type = isset( $space->type ) ? (string) $space->type : '';
$join_policy = isset( $space->join_policy ) ? (string) $space->join_policy : '';
if ( '' !== $type ) {
$icon = jetonomy_space_type_icon( $type );
$label = jetonomy_space_type_label( $type );
echo '<span class="jt-space-card-badge jt-space-card-badge-type jt-space-card-badge-type-' . esc_attr( $type ) . '">';
jetonomy_echo_icon( $icon, 12 );
echo esc_html( $label );
echo '</span>';
}
$policy_label = jetonomy_space_join_policy_label( $join_policy );
if ( '' !== $policy_label ) {
$icon = 'invite' === $join_policy ? 'key' : 'user-check';
echo '<span class="jt-space-card-badge jt-space-card-badge-policy jt-space-card-badge-policy-' . esc_attr( $join_policy ) . '" aria-label="' . esc_attr( $policy_label ) . '">';
jetonomy_echo_icon( $icon, 12 );
echo esc_html( $policy_label );
echo '</span>';
}
}
/**
* wp_kses variant for rendered post/reply content.
*
* Extends the default "post" allowed-tags list with the attributes that
* oEmbed HTML needs to survive the outer sanitization pass in single-post.php
* and reply-card.php:
*
* - `<iframe>` for YouTube/Vimeo/Spotify/SoundCloud embeds.
* - `<blockquote class=... data-*>` + inner `<section>` / `<p>` / `<a target>`
* for TikTok, Instagram, and Twitter embeds. These providers ship a
* blockquote fallback plus a hydration script (see
* jetonomy_maybe_enqueue_embed_scripts()) that swaps the blockquote for
* the real player at runtime. If we strip the blockquote's `class`
* (`tiktok-embed` / `instagram-media` / `twitter-tweet`) or its
* `data-video-id` / `data-instgrm-permalink` attributes, the script has no
* hook to attach to and the visitor only sees the plain caption fallback.
*
* @param string $content HTML content to sanitize.
* @return string
*/
function jetonomy_kses_embedded_content( string $content ): string {
$allowed = wp_kses_allowed_html( 'post' );
$allowed['iframe'] = array(
'src' => true,
'width' => true,
'height' => true,
'frameborder' => true,
'allow' => true,
'allowfullscreen' => true,
'referrerpolicy' => true,
'loading' => true,
'title' => true,
'name' => true,
'class' => true,
'id' => true,
'style' => true,
);
// Provider embed blockquote — TikTok, Instagram, Twitter. Keep the
// class hook and the data-* attributes the hydration script reads.
$allowed['blockquote'] = array_merge(
$allowed['blockquote'] ?? array(),
array(
'class' => true,
'cite' => true,
'style' => true,
'data-video-id' => true,
'data-embed-from' => true,
'data-instgrm-permalink' => true,
'data-instgrm-version' => true,
'data-instgrm-captioned' => true,
'data-lang' => true,
'data-theme' => true,
)
);
// TikTok wraps the fallback caption in <section>; also allow the
// attributes Instagram/Twitter put on inner links.
$allowed['section'] = array(
'class' => true,
'style' => true,
);
foreach ( array( 'a', 'p' ) as $tag ) {
if ( isset( $allowed[ $tag ] ) && is_array( $allowed[ $tag ] ) ) {
$allowed[ $tag ]['target'] = true;
$allowed[ $tag ]['rel'] = true;
}
}
return wp_kses( $content, $allowed );
}
/**
* Enqueue provider hydration scripts when content contains a TikTok,
* Instagram, or Twitter embed blockquote.
*
* These providers return oEmbed HTML as `<blockquote class="..." …>` plus a
* `<script async src="…">` tag. `wp_filter_oembed_result()` strips the
* script (only iframes survive core's oEmbed sanitizer), so the blockquote
* renders as a plain caption without the script loading — visitors see the
* fallback text but no video player.
*
* We detect the blockquote marker in the sanitized, ready-to-echo content
* and enqueue the corresponding provider script server-side. The script
* runs once per page and rewrites every matching blockquote to an iframe
* player.
*
* Safe to call multiple times per request — wp_enqueue_script() dedupes by
* handle. Does nothing on feed / REST / admin contexts.
*
* @param string $content Rendered content about to be echoed.
*/
function jetonomy_maybe_enqueue_embed_scripts( string $content ): void {
if ( is_admin() || is_feed() || wp_doing_ajax() ) {
return;
}
if ( false !== strpos( $content, 'class="tiktok-embed"' ) || false !== strpos( $content, "class='tiktok-embed'" ) ) {
wp_enqueue_script( 'jetonomy-tiktok-embed', 'https://www.tiktok.com/embed.js', array(), null, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
}
if ( false !== strpos( $content, 'class="instagram-media"' ) || false !== strpos( $content, "class='instagram-media'" ) ) {
wp_enqueue_script( 'jetonomy-instagram-embed', 'https://www.instagram.com/embed.js', array(), null, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
}
if ( false !== strpos( $content, 'class="twitter-tweet"' ) || false !== strpos( $content, "class='twitter-tweet'" ) ) {
wp_enqueue_script( 'jetonomy-twitter-embed', 'https://platform.twitter.com/widgets.js', array(), null, true ); // phpcs:ignore WordPress.WP.EnqueuedResourceParameters.MissingVersion
}
}
/**
* Normalize contenteditable "div soup" into real paragraphs.
*
* The composer authors into a contenteditable div and submits its innerHTML.
* Chromium/WebKit wrap every Enter-separated block in a bare `<div>` (an empty
* line is `<div><br></div>`); Firefox-style editors separate blocks with
* `<br><br>`. wpautop() skips block-level tags, so those divs were stored and
* rendered as-is - and because the CSS spacing contract targets
* `.jt-post-body p`, consecutive paragraphs collided with 0px between them
* (Basecamp 10138808747, measured: p->div 12px, div->div 0px).
*
* Called at BOTH ends, one implementation:
* - write time (posts/replies create + update, before wp_kses_post) so new
* content is stored as canonical `<p>` markup on every surface incl. REST;
* - display time (jetonomy_format_content) so content already stored as div
* soup on customer sites renders correctly without a migration.
*
* The div transform only runs when the content contains NO attributed
* `<div ...>` - with attributed divs present (embed wrappers etc.), a bare
* `</div>` is ambiguous and the content is left exactly as before. Composer
* output never contains attributed divs, so the reported case is always
* covered; literal `<div>` text inside code blocks is entity-escaped in
* storage and never matches.
*
* @param string $content Editor-submitted or stored HTML.
* @return string Content with paragraphs as `<p>` blocks.
*/
function jetonomy_normalize_editor_html( string $content ): string {
// Fast path: nothing a contenteditable would have mangled.
if ( false === stripos( $content, '<div' ) && false === stripos( $content, '<br' ) ) {
return $content;
}
// ANY attributed <div> makes BOTH rewrites unsafe, so such content passes
// through byte-identical. The div transform can't tell whose </div> it is,
// and the <br><br> rewrite would have wpautop close paragraphs INSIDE the
// wrapper, tearing the embed
// (`<div class="embed">one<br><br>two</div>` -> `...one</p><p>two</p></div>`).
// The detection is whitespace-class based - `<div\tclass=...>` and
// `<div\nclass=...>` count, not just the literal "<div " (QA probe,
// Basecamp 10138808747 reopen). Composer output never contains attributed
// divs, so the reported case is always still covered.
if ( preg_match( '/<div\s+[^>]/i', $content ) ) {
return $content;
}
$had_soup = false;
if ( false !== stripos( $content, '<div' ) ) {
// Every div is bare, so open/close pairs are unambiguous regardless of
// nesting: treat each boundary as a paragraph break and let wpautop
// re-wrap. `<div><br></div>` is the editor's empty line - drop the br
// so it doesn't survive into the middle of a paragraph gap.
$content = preg_replace( '#<div>\s*(?:<br\s*/?>)?\s*</div>#i', "\n\n", $content );
$content = str_ireplace( array( '<div>', '</div>' ), array( "\n\n", "\n\n" ), $content );
$had_soup = true;
}
// Two or more consecutive <br>s is a paragraph break in every editor
// dialect; a single <br> stays a deliberate line break.
$replaced = preg_replace( '#(?:<br\s*/?>\s*){2,}#i', "\n\n", $content );
if ( $replaced !== $content ) {
$content = $replaced;
$had_soup = true;
}
if ( ! $had_soup ) {
return $content;
}
// Canonicalize immediately: downstream consumers (REST payloads, the app,
// title derivation) read stored content raw, so the paragraph structure
// must live in the markup, not wait for a display-side wpautop.
return trim( wpautop( trim( $content ) ) );
}
/**
* THE sanitize pipeline for member-authored body content: normalize
* contenteditable div soup into real paragraphs, then kses.
*
* Post::create/update and Reply::create/update run every 'content' write
* through this, so every writer - REST, wp-admin AJAX, CLI journeys,
* Abilities, the importers, Pro reply-by-email - shares ONE choke point
* (Basecamp 10138808747: per-writer sanitizing let div soup persist via
* the paths that forgot the normalize half). Idempotent: normalized clean
* HTML passes through byte-identical, so pre-sanitized callers lose nothing.
*
* @param string $content Raw editor/imported HTML.
* @return string Normalized, kses-safe HTML.
*/
function jetonomy_sanitize_editor_content( string $content ): string {
return wp_kses_post( jetonomy_normalize_editor_html( $content ) );
}
/**
* The first paragraph of a content blob, as plain text.
*
* The feed-space derived title used to strip the WHOLE body and take the
* first 60 characters, so a multi-paragraph status ran its paragraphs
* together in the headline and the slug (Basecamp 10138808747 reopen). A
* headline is the first paragraph, not the first 60 bytes of everything.
*
* @param string $content Stored/normalized HTML or plain text.
* @return string First non-empty plain-text paragraph, '' if none.
*/
function jetonomy_first_paragraph_text( string $content ): string {
// Block-level closers become newlines BEFORE tags are stripped, so
// `<p>a</p><p>b</p>` splits even without literal newlines in the source.
$text = preg_replace( '#</(p|div|li|h[1-6]|blockquote)>#i', "\n", $content );
$text = trim( wp_strip_all_tags( (string) $text ) );
foreach ( preg_split( '/\n+/', $text ) as $line ) {
$line = trim( $line );
if ( '' !== $line ) {
return $line;
}
}
return '';
}
function jetonomy_format_content( string $content ): string {
$base = \Jetonomy\base_url();
// Repair div-soup that older releases stored verbatim (see
// jetonomy_normalize_editor_html) - a no-op for clean content.
$content = jetonomy_normalize_editor_html( $content );
// Normalize paragraphs: wpautop converts \n\n to <p>…</p> for plain-text
// storage, and is a no-op when content is already block-wrapped. This is
// the single display-side paragraph layer (mirrors core's `the_content`).
$content = wpautop( $content );
// Resolve every @mention in this content to a profile URL in ONE query,
// BEFORE splitting into segments. Mention linkifying itself lives in
// Mentions::linkify() — the single implementation — so mention links honour
// the `jetonomy_profile_url` filter and only render for real users.
$mention_urls = \Jetonomy\Mentions::link_map( $content );
// Split content into HTML tags and text segments, process only text segments.
$parts = preg_split( '/(<[^>]*>)/u', $content, -1, PREG_SPLIT_DELIM_CAPTURE );
if ( false === $parts ) {
return $content;
}
$inside_a = 0;
foreach ( $parts as $i => $part ) {
// Track whether we're inside an <a> tag to avoid nesting links.
if ( preg_match( '/<a[\s>]/i', $part ) ) {
++$inside_a;
continue;
}
if ( preg_match( '/<\/a>/i', $part ) ) {
--$inside_a;
continue;
}
// Skip HTML tags and text inside anchor tags.
if ( isset( $part[0] ) && '<' === $part[0] ) {
continue;
}
if ( $inside_a > 0 ) {
continue;
}
// @mentions → profile links, from the map resolved above.
$part = \Jetonomy\Mentions::linkify( $part, $mention_urls );
// #hashtags → tag page links. Same lookbehind so URL fragments
// (`foo.com#section`) don't get linkified as tags.
$part = preg_replace_callback(
'/(?<![\w\/.:-])#([a-zA-Z0-9_-]+)/u',
function ( $matches ) use ( $base ) {
$tag = $matches[1];
$slug = sanitize_title( $tag );
$url = $base . '/tag/' . $slug . '/';
return '<a href="' . esc_url( $url ) . '" class="jt-tag-link">#' . esc_html( $tag ) . '</a>';
},
$part
);
$parts[ $i ] = $part;
}
return implode( '', $parts );
}
if ( defined( 'WP_CLI' ) && WP_CLI ) {
require_once JETONOMY_DIR . 'includes/class-cli.php';
\WP_CLI::add_command( 'jetonomy', 'Jetonomy\\CLI' );
\Jetonomy\CLI\CLI_Dispatcher::register();
}