2026-11-15 08:45:17 -08:00
<? php
declare ( strict_types = 1 );
namespace StreamGoals\Overlay ;
use StreamGoals\Core\Money ;
2026-11-15 13:09:18 -08:00
use StreamGoals\Tiers\TierPolicy ;
2026-11-15 08:45:17 -08:00
/**
* Pure, WordPress-free payload builders. Everything returned here is public-safe.
*/
final class Payloads {
public const ANON_NAME = 'Anonymous' ;
private const SYMBOLS = array ( 'USD' => '$' , 'EUR' => '€' , 'GBP' => '£' , 'JPY' => '¥' , 'CAD' => 'CA$' , 'AUD' => 'A$' );
public static function money ( int $minor , string $currency ) : string {
$m = new Money ( max ( 0 , $minor ), strtoupper ( $currency ) );
$amount = $m -> toDecimalString ();
[ $whole , $frac ] = array_pad ( explode ( '.' , $amount , 2 ), 2 , null );
$whole = preg_replace ( '/\B(?=(\d{3})+(?!\d))/' , ',' , $whole );
$amount = null === $frac ? $whole : $whole . '.' . $frac ;
$cur = strtoupper ( $currency );
return isset ( self :: SYMBOLS [ $cur ] ) ? self :: SYMBOLS [ $cur ] . $amount : $cur . ' ' . $amount ;
}
public static function percent ( int $raised , int $target ) : int {
if ( $target <= 0 ) {
return 0 ;
}
return max ( 0 , min ( 100 , intdiv ( max ( 0 , $raised ) * 100 , $target ) ) );
}
2026-11-15 13:09:18 -08:00
/**
* @param array<int,array<string,mixed>>|null $tiers Raw sg_goal_tiers rows; null/empty = an ordinary (untiered) goal, payload unchanged.
*/
public static function goal ( ? array $goal , int $raised , ? array $tiers = null ) : array {
2026-11-15 08:45:17 -08:00
if ( null === $goal ) {
return array ( 'active' => false , 'title' => '' , 'raised_minor' => 0 , 'target_minor' => 0 , 'percent' => 0 ,
'currency' => 'USD' , 'raised_display' => '' , 'target_display' => '' );
}
$cur = strtoupper ( ( string ) ( $goal [ 'currency' ] ?? 'USD' ) );
$target = max ( 0 , ( int ) ( $goal [ 'target_minor' ] ?? 0 ) );
$raised = max ( 0 , $raised );
2026-11-15 13:09:18 -08:00
if ( $tiers ) {
return self :: tieredGoal ( $goal , $raised , $cur , $tiers );
}
2026-11-15 08:45:17 -08:00
return array (
'active' => true ,
'title' => ( string ) ( $goal [ 'title' ] ?? '' ),
'raised_minor' => $raised ,
'target_minor' => $target ,
'percent' => self :: percent ( $raised , $target ),
'currency' => $cur ,
'raised_display' => self :: money ( $raised , $cur ),
'target_display' => self :: money ( $target , $cur ),
);
}
2026-11-15 13:09:18 -08:00
/**
* Tiered goal: raised stays cumulative; target/percent describe the CURRENT tier (percent is within the tier).
* When every tier is reached the bar is full at the top tier's target.
*/
private static function tieredGoal ( array $goal , int $raised , string $cur , array $tiers ) : array {
$sorted = TierPolicy :: sorted ( $tiers );
$current = TierPolicy :: currentTier ( $sorted );
$all = null === $current ;
$target = $all ? TierPolicy :: derivedGoalTarget ( $sorted ) : max ( 0 , ( int ) $current [ 'target_minor' ] );
$floor = TierPolicy :: floorMinor ( $sorted );
return array (
'active' => true ,
'title' => ( string ) ( $goal [ 'title' ] ?? '' ),
'raised_minor' => $raised ,
'target_minor' => $target ,
'percent' => TierPolicy :: percentFor ( $sorted , $raised ),
'currency' => $cur ,
'raised_display' => self :: money ( $raised , $cur ),
'target_display' => self :: money ( $target , $cur ),
'tiers' => array (
'count' => count ( $sorted ),
'index' => TierPolicy :: currentIndex ( $sorted ),
'current' => $all ? null : array (
'title' => self :: text ( $current [ 'title' ] ?? '' , 120 ),
'description' => self :: text ( $current [ 'description' ] ?? '' , 255 ),
'target_minor' => $target ,
'target_display' => self :: money ( $target , $cur ),
'floor_minor' => $floor ,
),
'all_reached' => $all ,
),
);
}
2026-11-15 08:45:17 -08:00
/**
* @param string|null $endsAt sg_state `timer_ends_at` (epoch seconds, or a UTC datetime string).
* @param string|null $pausedRemaining sg_state `paused_remaining` seconds; non-null means paused.
*/
public static function timer ( ? string $endsAt , ? string $pausedRemaining , int $now ) : array {
$ends = self :: toEpoch ( $endsAt );
if ( null !== $pausedRemaining && '' !== $pausedRemaining && is_numeric ( $pausedRemaining ) ) {
$rem = max ( 0 , ( int ) $pausedRemaining );
return array ( 'active' => true , 'paused' => true , 'ends_at' => $now + $rem , 'remaining_seconds' => $rem , 'server_now' => $now );
}
if ( null === $ends ) {
return array ( 'active' => false , 'paused' => false , 'ends_at' => 0 , 'remaining_seconds' => 0 , 'server_now' => $now );
}
// remaining_seconds is only meaningful when paused; a running timer's value would change every second and defeat 304s.
return array ( 'active' => true , 'paused' => false , 'ends_at' => $ends , 'remaining_seconds' => 0 , 'server_now' => $now );
}
public static function counter ( string $label , int $value ) : array {
return array ( 'label' => $label , 'value' => $value );
}
/**
* @param array<int,array<string,mixed>> $rows
2026-11-15 12:26:03 -08:00
* @param int|null $since Null means "first poll": no alerts, just a baseline last_id.
* @param bool $recent Recent mode: ignore $since and return the newest $limit approved alerts (ascending id),
* so a message approved after newer donations still shows up. The client dedupes by id.
2026-11-15 08:45:17 -08:00
*/
2026-11-15 13:01:31 -08:00
public static function alerts ( array $rows , ? int $since , int $limit = 10 , bool $recent = false , ? callable $mediaFor = null ) : array {
2026-11-15 08:45:17 -08:00
$safe = array ();
foreach ( $rows as $r ) {
if ( 'completed' !== ( $r [ 'status' ] ?? '' ) || 'approved' !== ( $r [ 'moderation' ] ?? '' ) ) {
continue ;
}
$safe [] = $r ;
}
usort ( $safe , static fn ( $a , $b ) => ( int ) $a [ 'id' ] <=> ( int ) $b [ 'id' ] );
2026-11-15 12:26:03 -08:00
if ( $recent ) {
$safe = array_slice ( $safe , - max ( 1 , $limit ) );
2026-11-15 13:01:31 -08:00
$alerts = array_map ( static fn ( array $r ) : array => self :: alert ( $r , $mediaFor ), $safe );
2026-11-15 12:26:03 -08:00
return array ( 'alerts' => $alerts , 'last_id' => $alerts ? ( int ) end ( $alerts )[ 'id' ] : 0 );
}
2026-11-15 08:45:17 -08:00
$lastId = $since ?? 0 ;
foreach ( $safe as $r ) {
$lastId = max ( $lastId , ( int ) $r [ 'id' ] );
}
if ( null === $since ) {
return array ( 'alerts' => array (), 'last_id' => $lastId );
}
$alerts = array ();
foreach ( $safe as $r ) {
if ( ( int ) $r [ 'id' ] <= $since ) {
continue ;
}
2026-11-15 13:01:31 -08:00
$alerts [] = self :: alert ( $r , $mediaFor );
2026-11-15 08:45:17 -08:00
}
$alerts = array_slice ( $alerts , 0 , max ( 1 , $limit ) );
if ( $alerts ) {
$lastId = max ( $since , ( int ) end ( $alerts )[ 'id' ] ); // don't skip rows beyond the limit
}
return array ( 'alerts' => $alerts , 'last_id' => $lastId );
}
2026-11-15 13:01:31 -08:00
/**
* @param array<string,mixed> $r
* @param (callable(array,string,string):?array)|null $mediaFor Builds the `media` block from (row, public name, amount display).
*/
private static function alert ( array $r , ? callable $mediaFor = null ) : array {
2026-11-15 12:26:03 -08:00
$cur = strtoupper ( ( string ) ( $r [ 'currency' ] ?? 'USD' ) );
$anon = ! empty ( $r [ 'is_anonymous' ] );
$name = trim ( ( string ) ( $r [ 'donor_name' ] ?? '' ) );
2026-11-15 13:01:31 -08:00
$pub = ( $anon || '' === $name ) ? self :: ANON_NAME : $name ;
$disp = self :: money ( ( int ) $r [ 'base_minor' ], $cur );
2026-11-15 12:26:03 -08:00
return array (
'id' => ( int ) $r [ 'id' ],
2026-11-15 13:01:31 -08:00
'name' => $pub ,
2026-11-15 12:26:03 -08:00
'amount_minor' => ( int ) $r [ 'base_minor' ],
2026-11-15 13:01:31 -08:00
'amount_display' => $disp ,
2026-11-15 12:26:03 -08:00
'currency' => $cur ,
'message' => ( string ) ( $r [ 'message' ] ?? '' ),
'bonuses' => self :: bonuses ( $r [ 'bonuses' ] ?? array () ),
2026-11-15 12:36:28 -08:00
'actions' => self :: actionEvents ( $r [ 'actions' ] ?? array () ),
2026-11-15 13:09:18 -08:00
'tiers' => self :: tierEvents ( $r [ 'tiers' ] ?? array () ),
2026-11-15 13:01:31 -08:00
'media' => $mediaFor ? $mediaFor ( $r , $pub , $disp ) : null ,
2026-11-15 12:26:03 -08:00
);
}
2026-11-15 12:07:06 -08:00
/**
* Display-safe bonus labels. Stored events should be [A-Za-z0-9_-] only; anything else is stripped
* anyway, then humanized ("big_donation" -> "Big donation"). Empty/duplicate results are dropped.
*
* @param mixed $events
* @return string[]
*/
public static function bonuses ( mixed $events ) : array {
$out = array ();
foreach ( is_array ( $events ) ? $events : array () as $e ) {
if ( ! is_string ( $e ) ) {
continue ;
}
$clean = substr ( ( string ) preg_replace ( '/[^A-Za-z0-9_-]/' , '' , $e ), 0 , 40 );
$label = trim ( ( string ) preg_replace ( '/[_-]+/' , ' ' , $clean ) );
if ( '' === $label ) {
continue ;
}
$label = ucfirst ( strtolower ( $label ) );
if ( ! in_array ( $label , $out , true ) ) {
$out [] = $label ;
}
if ( count ( $out ) >= 5 ) {
break ;
}
}
return $out ;
}
2026-11-15 12:36:28 -08:00
/** Display-safe single line: no tags, control chars or runs of whitespace; capped at $max characters. */
public static function text ( mixed $v , int $max ) : string {
if ( ! is_scalar ( $v ) ) {
return '' ;
}
$s = strip_tags ( ( string ) $v );
$s = ( string ) preg_replace ( '/[\x00-\x1F\x7F\x{200B}-\x{200F}\x{202A}-\x{202E}\x{2066}-\x{2069}\x{FEFF}]+/u' , ' ' , $s );
$s = trim ( ( string ) preg_replace ( '/\s+/u' , ' ' , $s ) );
return mb_substr ( $s , 0 , $max );
}
/**
* Triggered actions for one alert: [ {title, times} ]. At most 5, titles capped at 80 chars, times clamped to 1..999.
*
* @param mixed $events
* @return array<int,array{title:string,times:int}>
*/
public static function actionEvents ( mixed $events ) : array {
$out = array ();
foreach ( is_array ( $events ) ? $events : array () as $e ) {
if ( ! is_array ( $e ) ) {
continue ;
}
$title = self :: text ( $e [ 'title' ] ?? '' , 80 );
if ( '' === $title ) {
continue ;
}
$out [] = array ( 'title' => $title , 'times' => max ( 1 , min ( 999 , ( int ) ( $e [ 'times' ] ?? 1 ) ) ) );
if ( count ( $out ) >= 5 ) {
break ;
}
}
return $out ;
}
2026-11-15 13:09:18 -08:00
/**
* Tiers a donation unlocked, for the "TIER UNLOCKED" pill: [ {title} ]. At most 5, titles capped at 80 chars, blanks dropped.
*
* @param mixed $events
* @return array<int,array{title:string}>
*/
public static function tierEvents ( mixed $events ) : array {
$out = array ();
foreach ( is_array ( $events ) ? $events : array () as $e ) {
$title = self :: text ( is_array ( $e ) ? ( $e [ 'title' ] ?? '' ) : '' , 80 );
if ( '' === $title ) {
continue ;
}
$out [] = array ( 'title' => $title );
if ( count ( $out ) >= 5 ) {
break ;
}
}
return $out ;
}
2026-11-15 12:36:28 -08:00
/**
* The on-stream reward menu for the active goal. Empty list means "render nothing".
*
* @param array<string,mixed>|null $goal
* @param array<int,array<string,mixed>> $rows Raw sg_actions rows, already ordered.
*/
public static function actionsMenu ( ? array $goal , array $rows ) : array {
$cur = strtoupper ( ( string ) ( $goal [ 'currency' ] ?? 'USD' ) );
$list = array ();
foreach ( $goal ? $rows : array () as $r ) {
$amount = ( int ) ( $r [ 'amount_minor' ] ?? 0 );
$title = self :: text ( $r [ 'title' ] ?? '' , 120 );
if ( $amount <= 0 || '' === $title ) {
continue ;
}
$list [] = array (
'title' => $title ,
'description' => self :: text ( $r [ 'description' ] ?? '' , 255 ),
'amount_minor' => $amount ,
'amount_display' => self :: money ( $amount , $cur ),
'mode' => 'every' === ( $r [ 'mode' ] ?? '' ) ? 'every' : 'exact' ,
);
if ( count ( $list ) >= 50 ) {
break ;
}
}
return array ( 'active' => ( bool ) $list , 'currency' => $cur , 'actions' => $list );
}
2026-11-15 13:01:31 -08:00
/** Strong ETag over the payload (plus an optional salt, e.g. a hash of media definitions), ignoring the volatile server_now so unchanged data yields 304s. */
public static function etag ( array $payload , string $salt = '' ) : string {
2026-11-15 08:45:17 -08:00
unset ( $payload [ 'server_now' ] );
2026-11-15 13:01:31 -08:00
return '"' . md5 ( $salt . ( string ) json_encode ( $payload , JSON_UNESCAPED_UNICODE ) ) . '"' ;
2026-11-15 08:45:17 -08:00
}
private static function toEpoch ( ? string $v ) : ? int {
if ( null === $v || '' === $v ) {
return null ;
}
if ( ctype_digit ( $v ) ) {
return ( int ) $v ;
}
$t = strtotime ( $v . ' UTC' );
return false === $t ? null : $t ;
}
}