'$', '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 ) ) ); } /** * @param array>|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 { 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 ); if ( $tiers ) { return self::tieredGoal( $goal, $raised, $cur, $tiers ); } 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 ), ); } /** * 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, ), ); } /** * @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> $rows * @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. */ public static function alerts( array $rows, ?int $since, int $limit = 10, bool $recent = false, ?callable $mediaFor = null ): array { $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'] ); if ( $recent ) { $safe = array_slice( $safe, -max( 1, $limit ) ); $alerts = array_map( static fn( array $r ): array => self::alert( $r, $mediaFor ), $safe ); return array( 'alerts' => $alerts, 'last_id' => $alerts ? (int) end( $alerts )['id'] : 0 ); } $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; } $alerts[] = self::alert( $r, $mediaFor ); } $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 ); } /** * @param array $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 { $cur = strtoupper( (string) ( $r['currency'] ?? 'USD' ) ); $anon = ! empty( $r['is_anonymous'] ); $name = trim( (string) ( $r['donor_name'] ?? '' ) ); $pub = ( $anon || '' === $name ) ? self::ANON_NAME : $name; $disp = self::money( (int) $r['base_minor'], $cur ); return array( 'id' => (int) $r['id'], 'name' => $pub, 'amount_minor' => (int) $r['base_minor'], 'amount_display' => $disp, 'currency' => $cur, 'message' => (string) ( $r['message'] ?? '' ), 'bonuses' => self::bonuses( $r['bonuses'] ?? array() ), 'actions' => self::actionEvents( $r['actions'] ?? array() ), 'tiers' => self::tierEvents( $r['tiers'] ?? array() ), 'media' => $mediaFor ? $mediaFor( $r, $pub, $disp ) : null, ); } /** * 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; } /** 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 */ 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; } /** * 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 */ 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; } /** * The on-stream reward menu for the active goal. Empty list means "render nothing". * * @param array|null $goal * @param array> $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 ); } /** 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 { unset( $payload['server_now'] ); return '"' . md5( $salt . (string) json_encode( $payload, JSON_UNESCAPED_UNICODE ) ) . '"'; } 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; } }