diff --git a/assets/admin/admin.css b/assets/admin/admin.css new file mode 100644 index 0000000..91b0513 --- /dev/null +++ b/assets/admin/admin.css @@ -0,0 +1,46 @@ +.sg-admin .sg-lead { font-size: 15px; max-width: 70ch; } +.sg-admin .sg-card { background: #fff; border: 1px solid #c3c4c7; border-radius: 6px; padding: 8px 20px 16px; margin: 16px 0; max-width: 960px; } +.sg-admin .sg-card h2 { margin-top: 12px; } +.sg-admin .sg-inline { display: inline-block; margin: 0 4px 4px 0; } +.sg-admin .sg-ok { color: #00700f; font-weight: 600; } +.sg-admin .sg-warn { color: #8a4b00; font-weight: 600; } +.sg-admin .sg-steps { max-width: 80ch; line-height: 1.6; } +.sg-admin .sg-steps li { margin-bottom: 6px; } +.sg-admin .sg-progress { display: flex; flex-wrap: wrap; gap: 8px; list-style: none; padding: 0; margin: 12px 0; counter-reset: sg; } +.sg-admin .sg-progress li { counter-increment: sg; padding: 6px 14px; border-radius: 999px; background: #f0f0f1; color: #50575e; } +.sg-admin .sg-progress li::before { content: counter(sg) ". "; } +.sg-admin .sg-progress li.is-done { background: #d7f0dc; } +.sg-admin .sg-progress li.is-current { background: #2271b1; color: #fff; font-weight: 600; } +.sg-admin .sg-progress li.is-current a { color: #fff; } +.sg-admin .sg-tabs { display: flex; flex-wrap: wrap; gap: 10px; margin: 10px 0 4px; } +.sg-admin .sg-tab { border: 2px solid #c3c4c7; border-radius: 6px; padding: 8px 14px; cursor: pointer; background: #fff; } +.sg-admin .sg-tab:has(input:checked) { border-color: #2271b1; background: #f0f6fc; } +.sg-admin .sg-templates { display: grid; gap: 10px; margin: 10px 0; } +.sg-admin .sg-template { border: 2px solid #c3c4c7; border-radius: 6px; padding: 10px 14px; cursor: pointer; display: block; } +.sg-admin .sg-template:has(input:checked) { border-color: #2271b1; background: #f0f6fc; } +.sg-admin .sg-template span { color: #50575e; margin-left: 24px; } +.sg-admin .sg-copy { display: flex; gap: 8px; align-items: center; max-width: 720px; } +.sg-admin .sg-copy input { flex: 1; min-width: 0; } +.sg-admin .sg-overlay-card { border-top: 1px solid #dcdcde; padding: 4px 0 10px; } +.sg-admin .sg-overlay-card:first-of-type { border-top: 0; } +.sg-admin .sg-preview { overflow: auto; max-width: 100%; margin-top: 6px; border: 1px solid #c3c4c7; background: repeating-conic-gradient(#e6e6e6 0% 25%, #fafafa 0% 50%) 50% / 20px 20px; } +.sg-admin .sg-preview iframe { border: 0; display: block; max-width: none; } +.sg-admin .sg-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(200px, 1fr)); gap: 12px; } +.sg-admin .sg-grid label { display: flex; flex-direction: column; gap: 4px; font-weight: 600; } +.sg-admin .sg-grid input[type="color"] { padding: 0; height: 32px; width: 64px; } +.sg-admin .sg-table td, .sg-admin .sg-table th { vertical-align: top; } +.sg-admin .sg-actions { white-space: normal; } +.sg-admin .sg-badge { display: inline-block; padding: 1px 8px; border-radius: 999px; font-size: 12px; background: #f0f0f1; } +.sg-admin .sg-active { background: #d7f0dc; } +.sg-admin .sg-paused, .sg-admin .sg-pending { background: #fcf0c3; } +.sg-admin .sg-complete { background: #dbe7f7; } +.sg-admin .sg-test { background: #f4d6f5; font-weight: 700; } +.sg-admin .sg-rejected { background: #f7d5d5; } +.sg-admin .sg-bar { height: 6px; background: #e0e0e0; border-radius: 3px; margin-top: 4px; max-width: 180px; overflow: hidden; } +.sg-admin .sg-bar span { display: block; height: 100%; background: #2271b1; } +.sg-admin tr.sg-off td { opacity: .55; } +.sg-admin .sg-preview-list { font-size: 14px; list-style: disc; margin-left: 20px; } +.sg-admin .sg-form-preview { color: #00700f; font-weight: 600; min-height: 1.4em; } +.sg-admin .sg-filter { display: inline-block; margin: 8px 8px 8px 0; } +.sg-admin .sg-table { max-width: 100%; } +@media (max-width: 782px) { .sg-admin .sg-copy { flex-direction: column; align-items: stretch; } } diff --git a/assets/admin/admin.js b/assets/admin/admin.js new file mode 100644 index 0000000..0ce64de --- /dev/null +++ b/assets/admin/admin.js @@ -0,0 +1,59 @@ +/* StreamGoals admin: copy buttons and confirm prompts. No dependencies. */ +( function () { + 'use strict'; + + function flash( btn, text ) { + var old = btn.getAttribute( 'data-label' ) || btn.textContent; + btn.setAttribute( 'data-label', old ); + btn.textContent = text; + window.setTimeout( function () { btn.textContent = old; }, 1500 ); + } + + function copyText( text, btn, input ) { + function fallback() { + var el = input; + var temp = null; + if ( ! el ) { + temp = el = document.createElement( 'textarea' ); + el.value = text; + el.style.position = 'fixed'; + el.style.opacity = '0'; + document.body.appendChild( el ); + } + el.select(); + var ok = false; + try { ok = document.execCommand( 'copy' ); } catch ( e ) { ok = false; } + if ( temp ) { document.body.removeChild( temp ); } + flash( btn, ok ? 'Copied!' : 'Press Ctrl+C' ); + } + if ( navigator.clipboard && window.isSecureContext ) { + navigator.clipboard.writeText( text ).then( function () { flash( btn, 'Copied!' ); }, fallback ); + } else { + fallback(); + } + } + + document.addEventListener( 'click', function ( e ) { + var btn = e.target.closest ? e.target.closest( '[data-sg-copy],[data-sg-copy-text]' ) : null; + if ( ! btn ) { return; } + e.preventDefault(); + if ( btn.hasAttribute( 'data-sg-copy-text' ) ) { + copyText( btn.getAttribute( 'data-sg-copy-text' ), btn, null ); + return; + } + var input = btn.parentNode.querySelector( 'input' ); + if ( input ) { copyText( input.value, btn, input ); } + } ); + + document.addEventListener( 'focusin', function ( e ) { + if ( e.target.classList && e.target.classList.contains( 'sg-url' ) ) { e.target.select(); } + } ); + + document.addEventListener( 'submit', function ( e ) { + var form = e.target; + if ( ! form.classList || ! form.classList.contains( 'sg-confirm' ) ) { return; } + var src = e.submitter || form.querySelector( '[data-confirm]' ); + var msg = src && src.getAttribute( 'data-confirm' ); + if ( msg && ! window.confirm( msg ) ) { e.preventDefault(); } + } ); +}() ); diff --git a/assets/admin/overlays.js b/assets/admin/overlays.js new file mode 100644 index 0000000..f6f7e32 --- /dev/null +++ b/assets/admin/overlays.js @@ -0,0 +1,77 @@ +/* StreamGoals overlay style builder: keeps every overlay URL and preview in sync with the style form. */ +( function () { + 'use strict'; + var form = document.getElementById( 'sg-style' ); + if ( ! form ) { return; } + var cards = Array.prototype.slice.call( document.querySelectorAll( '.sg-overlay-card' ) ); + var COLORS = [ 'color', 'accent', 'accent2', 'track', 'bg' ]; + var timer = null; + + function params() { + var q = []; + function add( k, v ) { q.push( encodeURIComponent( k ) + '=' + encodeURIComponent( v ) ); } + var theme = form.elements.theme.value; + if ( theme && theme !== 'dark' ) { add( 'theme', theme ); } + var font = form.elements.font.value; + var customBox = form.querySelector( '.sg-custom-font' ); + if ( font === '__custom' ) { + var f = ( form.elements.font_custom.value || '' ).trim(); + if ( /^[A-Za-z0-9][A-Za-z0-9 \-]{0,39}$/.test( f ) ) { add( 'font', f ); } + if ( customBox ) { customBox.hidden = false; } + } else { + if ( customBox ) { customBox.hidden = true; } + if ( font && font !== 'sans' ) { add( 'font', font ); } + } + var scale = parseFloat( form.elements.scale.value ); + if ( isFinite( scale ) && scale >= 0.5 && scale <= 3 && scale !== 1 ) { add( 'scale', String( Math.round( scale * 100 ) / 100 ) ); } + COLORS.forEach( function ( k ) { + if ( form.elements[ 'use_' + k ].checked ) { add( k, form.elements[ k ].value.replace( '#', '' ) ); } + } ); + return q.join( '&' ); + } + + function previewSrc( card ) { + var base = card.getAttribute( 'data-base' ); + var sep = card.getAttribute( 'data-sep' ); + var q = params(); + return q ? base + sep + q : base; + } + + function refresh() { + cards.forEach( function ( card ) { + var url = previewSrc( card ); + var input = card.querySelector( '.sg-url' ); + if ( input ) { input.value = url; } + var wrap = card.querySelector( '.sg-preview' ); + var frame = wrap && wrap.querySelector( 'iframe' ); + if ( frame && ! wrap.hidden ) { frame.src = url; } + } ); + } + + function schedule() { + window.clearTimeout( timer ); + timer = window.setTimeout( refresh, 250 ); + } + + form.addEventListener( 'input', schedule ); + form.addEventListener( 'change', schedule ); + + cards.forEach( function ( card ) { + var btn = card.querySelector( '[data-sg-preview]' ); + if ( ! btn ) { return; } + btn.addEventListener( 'click', function () { + var wrap = card.querySelector( '.sg-preview' ); + var frame = wrap.querySelector( 'iframe' ); + if ( wrap.hidden ) { + wrap.hidden = false; + frame.src = previewSrc( card ); + btn.textContent = 'Hide preview'; + } else { + wrap.hidden = true; + frame.removeAttribute( 'src' ); + btn.textContent = 'Show live preview'; + } + } ); + } ); + refresh(); +}() ); diff --git a/assets/admin/rules.js b/assets/admin/rules.js new file mode 100644 index 0000000..940547d --- /dev/null +++ b/assets/admin/rules.js @@ -0,0 +1,122 @@ +/* StreamGoals rules editor: show the right fields per type and preview what a donation would do. */ +( function () { + 'use strict'; + var dataEl = document.getElementById( 'sg-rules-data' ); + var form = document.querySelector( '.sg-rule-form' ); + var cfg = { currency: 'USD', exp: 2, rules: [] }; + try { if ( dataEl ) { cfg = JSON.parse( dataEl.textContent ); } } catch ( e ) { /* keep defaults */ } + + /* Parse "1,000.50" into minor units using string maths only (no float rounding). Returns null if invalid. */ + function toMinor( raw ) { + var s = String( raw == null ? '' : raw ).replace( /[,\s$€£¥]/g, '' ); + var m = /^(\d+)(?:\.(\d+))?$/.exec( s ); + if ( ! m ) { return null; } + var frac = m[ 2 ] || ''; + if ( frac.length > cfg.exp ) { return null; } + while ( frac.length < cfg.exp ) { frac += '0'; } + var n = parseInt( m[ 1 ] + frac, 10 ); + return isFinite( n ) ? n : null; + } + + function money( minor ) { + var s = String( minor ); + if ( cfg.exp === 0 ) { return cfg.currency + ' ' + s; } + while ( s.length < 3 ) { s = '0' + s; } + return cfg.currency + ' ' + s.slice( 0, -2 ) + '.' + s.slice( -2 ); + } + + function duration( secs ) { + var parts = []; + [ [ 'day', 86400 ], [ 'hour', 3600 ], [ 'minute', 60 ], [ 'second', 1 ] ].forEach( function ( u ) { + var n = Math.floor( secs / u[ 1 ] ); + secs -= n * u[ 1 ]; + if ( n > 0 ) { parts.push( n + ' ' + u[ 0 ] + ( n === 1 ? '' : 's' ) ); } + } ); + return parts.length ? parts.join( ' ' ) : '0 seconds'; + } + + /* Same maths as the PHP Rules classes (integer division, caps). */ + function effect( rule, amount ) { + var c = rule.config || {}; + if ( rule.type === 'add_time' ) { + if ( ! c.unit_minor ) { return null; } + var d = Math.floor( amount * c.seconds_per_unit / c.unit_minor ); + if ( c.cap_seconds_per_donation != null ) { d = Math.min( d, c.cap_seconds_per_donation ); } + return d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added'; + } + if ( rule.type === 'counter' ) { + if ( ! c.per_minor ) { return null; } + return ( c.label || 'Counter' ) + ': +' + ( Math.floor( amount / c.per_minor ) * c.step ); + } + if ( rule.type === 'bonus' ) { + return 'Bonus "' + c.event + '" ' + ( amount >= c.min_minor ? 'triggers' : 'does not trigger' ); + } + return null; + } + + var amountEl = document.getElementById( 'sg-preview-amount' ); + var out = document.getElementById( 'sg-preview-out' ); + function renderPreview() { + if ( ! amountEl || ! out ) { return; } + var amt = toMinor( amountEl.value ); + out.textContent = ''; + var lines = []; + if ( amt === null ) { + lines.push( 'Enter an amount like 25.00' ); + } else { + lines.push( 'A ' + money( amt ) + ' donation:' ); + cfg.rules.forEach( function ( r ) { var l = effect( r, amt ); if ( l ) { lines.push( l ); } } ); + if ( ! cfg.rules.length ) { lines.push( 'No rules are on, so it only fills the goal bar.' ); } + } + lines.forEach( function ( l ) { var li = document.createElement( 'li' ); li.textContent = l; out.appendChild( li ); } ); + } + if ( amountEl ) { amountEl.addEventListener( 'input', renderPreview ); renderPreview(); } + + /* Type switch + preview of the rule being edited. */ + if ( ! form ) { return; } + var typeSel = document.getElementById( 'sg-rule-type' ); + var typeHidden = form.querySelector( 'input[name="type"]' ); + var formPrev = document.getElementById( 'sg-form-preview' ); + + function currentType() { return typeSel ? typeSel.value : ( typeHidden ? typeHidden.value : 'add_time' ); } + function val( group, f ) { + var el = group.querySelector( '[data-f="' + f + '"]' ); + if ( ! el ) { return ''; } + return el.type === 'checkbox' ? el.checked : el.value; + } + function buildRule( type ) { + var g = form.querySelector( '.sg-rule-group[data-type="' + type + '"]' ); + if ( ! g ) { return null; } + var unit = toMinor( val( g, 'unit_amount' ) ); + if ( type === 'add_time' ) { + var mult = { seconds: 1, minutes: 60, hours: 3600 }[ val( g, 'time_unit' ) ] || 60; + var n = parseInt( val( g, 'time_amount' ), 10 ); + if ( ! unit || ! n ) { return null; } + var cap = parseInt( val( g, 'cap_minutes' ), 10 ); + return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null } }; + } + if ( type === 'counter' ) { + var step = parseInt( val( g, 'step' ), 10 ); + if ( ! unit || ! step ) { return null; } + return { type: type, config: { step: step, per_minor: unit, label: val( g, 'label' ) } }; + } + var min = toMinor( val( g, 'min_amount' ) ); + if ( ! min ) { return null; } + return { type: type, config: { min_minor: min, event: val( g, 'event' ) || 'big_donation' } }; + } + function update() { + var type = currentType(); + Array.prototype.forEach.call( form.querySelectorAll( '.sg-rule-group' ), function ( g ) { + g.hidden = g.getAttribute( 'data-type' ) !== type; + } ); + if ( ! formPrev ) { return; } + var amt = amountEl ? toMinor( amountEl.value ) : null; + var rule = buildRule( type ); + var line = ( rule && amt !== null ) ? effect( rule, amt ) : null; + formPrev.textContent = line ? 'With this rule, a ' + money( amt ) + ' donation gives: ' + line : ''; + } + form.addEventListener( 'input', update ); + form.addEventListener( 'change', update ); + if ( amountEl ) { amountEl.addEventListener( 'input', update ); } + update(); +}() ); diff --git a/includes/Admin/Admin.php b/includes/Admin/Admin.php new file mode 100644 index 0000000..4ed953c --- /dev/null +++ b/includes/Admin/Admin.php @@ -0,0 +1,176 @@ + [class, method]. */ + private const HANDLERS = array( + 'sg_paypal_connect' => array( PayPalConnector::class, 'handle' ), + 'sg_wizard_goal' => array( SetupPage::class, 'handleGoal' ), + 'sg_wizard_page' => array( SetupPage::class, 'handlePage' ), + 'sg_goal_save' => array( GoalsPage::class, 'handleSave' ), + 'sg_goal_status' => array( GoalsPage::class, 'handleStatus' ), + 'sg_goal_delete' => array( GoalsPage::class, 'handleDelete' ), + 'sg_rule_save' => array( GoalsPage::class, 'handleRuleSave' ), + 'sg_rule_toggle' => array( GoalsPage::class, 'handleRuleToggle' ), + 'sg_rule_delete' => array( GoalsPage::class, 'handleRuleDelete' ), + 'sg_export_csv' => array( DonationsPage::class, 'handleExport' ), + 'sg_moderate' => array( DonationsPage::class, 'handleModerate' ), + 'sg_test_donation' => array( OverlaysPage::class, 'handleTestDonation' ), + 'sg_delete_tests' => array( OverlaysPage::class, 'handleDeleteTests' ), + 'sg_regen_token' => array( OverlaysPage::class, 'handleRegenerate' ), + 'sg_settings_save' => array( SettingsPage::class, 'handleSave' ), + ); + + public static function register(): void { + add_action( 'admin_menu', array( self::class, 'menu' ) ); + add_action( 'admin_init', array( self::class, 'maybe_flush_rewrites' ) ); + add_action( 'admin_enqueue_scripts', array( self::class, 'assets' ) ); + foreach ( self::HANDLERS as $action => $cb ) { + add_action( 'admin_post_' . $action, $cb ); + } + } + + /* ------------------------------------------------------------------ menu */ + + public static function menu(): void { + $connected = PayPalConnector::isConnected(); + add_menu_page( 'StreamGoals', 'StreamGoals', self::CAP, self::HOME, array( self::class, 'page_home' ), 'dashicons-heart', 58 ); + add_submenu_page( self::HOME, $connected ? 'Goals' : 'Setup', $connected ? 'Goals' : 'Setup', self::CAP, self::HOME, array( self::class, 'page_home' ) ); + if ( $connected ) { + add_submenu_page( self::HOME, 'Setup guide', 'Setup guide', self::CAP, 'streamgoals-setup', array( SetupPage::class, 'render' ) ); + } + add_submenu_page( self::HOME, 'Donations', 'Donations', self::CAP, 'streamgoals-donations', array( DonationsPage::class, 'render' ) ); + $pending = Store::pendingModerationCount(); + if ( Settings::get( 'moderate_messages' ) || $pending > 0 ) { + $badge = $pending > 0 ? ' ' . (int) $pending . '' : ''; + add_submenu_page( self::HOME, 'Moderation', 'Moderation' . $badge, self::CAP, 'streamgoals-moderation', array( DonationsPage::class, 'renderModeration' ) ); + } + add_submenu_page( self::HOME, 'Overlays', 'Overlays', self::CAP, 'streamgoals-overlays', array( OverlaysPage::class, 'render' ) ); + add_submenu_page( self::HOME, 'Settings', 'Settings', self::CAP, 'streamgoals-settings', array( SettingsPage::class, 'render' ) ); + } + + /** First screen: the setup wizard until PayPal is connected, then the goals list. */ + public static function page_home(): void { + if ( PayPalConnector::isConnected() ) { + GoalsPage::render(); + } else { + SetupPage::render(); + } + } + + /** Overlay rewrite rules (registered by Overlay\Router on init) need a one-off flush. */ + public static function maybe_flush_rewrites(): void { + if ( current_user_can( self::CAP ) && class_exists( \StreamGoals\Overlay\Router::class ) && \StreamGoals\Overlay\Router::flush_rules_needed() ) { + flush_rewrite_rules( false ); + \StreamGoals\Overlay\Router::mark_flushed(); + } + } + + /* ---------------------------------------------------------------- assets */ + + public static function assets( string $hook ): void { + $page = isset( $_GET['page'] ) ? sanitize_key( wp_unslash( $_GET['page'] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification + if ( 0 !== strpos( $page, 'streamgoals' ) ) { + return; + } + wp_enqueue_style( 'streamgoals-admin', STREAMGOALS_URL . 'assets/admin/admin.css', array(), STREAMGOALS_VERSION ); + wp_enqueue_script( 'streamgoals-admin', STREAMGOALS_URL . 'assets/admin/admin.js', array(), STREAMGOALS_VERSION, true ); + if ( self::HOME === $page ) { + wp_enqueue_script( 'streamgoals-rules', STREAMGOALS_URL . 'assets/admin/rules.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true ); + } + if ( 'streamgoals-overlays' === $page ) { + wp_enqueue_script( 'streamgoals-overlays', STREAMGOALS_URL . 'assets/admin/overlays.js', array( 'streamgoals-admin' ), STREAMGOALS_VERSION, true ); + } + } + + /* --------------------------------------------------------------- helpers */ + + /** Capability + nonce check for every admin-post handler. Dies on failure. */ + public static function guard( string $action ): void { + if ( ! current_user_can( self::CAP ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'streamgoals-donate' ), 403 ); + } + check_admin_referer( $action ); + } + + /** Echo an opening
posting to admin-post.php with the nonce for $action. */ + public static function form( string $action, array $hidden = array(), string $class = '' ): void { + echo ''; + echo ''; + wp_nonce_field( $action ); + foreach ( $hidden as $k => $v ) { + echo ''; + } + } + + public static function url( string $page = self::HOME, array $args = array() ): string { + return add_query_arg( array_merge( array( 'page' => $page ), $args ), admin_url( 'admin.php' ) ); + } + + /** Redirect back with a one-time notice shown on the next screen load. */ + public static function redirect( string $url, string $type, string $message ): void { + set_transient( 'sg_notice_' . get_current_user_id(), array( 'type' => $type, 'msg' => $message ), 120 ); + wp_safe_redirect( $url ); + exit; + } + + public static function notices(): void { + $key = 'sg_notice_' . get_current_user_id(); + $n = get_transient( $key ); + if ( is_array( $n ) && isset( $n['msg'] ) ) { + delete_transient( $key ); + $cls = in_array( $n['type'] ?? '', array( 'success', 'error', 'warning', 'info' ), true ) ? $n['type'] : 'info'; + echo '

' . esc_html( (string) $n['msg'] ) . '

'; + } + } + + public static function currency(): string { + return Format::currency( get_option( 'sg_currency', 'USD' ) ); + } + + /** Start a screen: capability check, wrapper and flash notices. */ + public static function open( string $title ): void { + if ( ! current_user_can( self::CAP ) ) { + wp_die( esc_html__( 'You do not have permission to view this page.', 'streamgoals-donate' ), 403 ); + } + echo '

' . esc_html( $title ) . '

'; + self::notices(); + if ( PayPalConnector::isConnected() && '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) { + echo '

' . esc_html( 'PayPal is connected, but the webhook is not set up yet, so refunds/reversals will not be noticed. Open Settings and press "Save and test connection" to register it.' ) . '

'; + } + } + + public static function close(): void { + echo '
'; + } + + /** Safe int from $_GET. */ + public static function get_int( string $key ): int { + return isset( $_GET[ $key ] ) ? absint( wp_unslash( $_GET[ $key ] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification + } + + public static function get_str( string $key ): string { + return isset( $_GET[ $key ] ) && is_scalar( $_GET[ $key ] ) ? sanitize_key( wp_unslash( $_GET[ $key ] ) ) : ''; // phpcs:ignore WordPress.Security.NonceVerification + } + + /** Safe string from $_POST (already nonce-checked by guard()). */ + public static function post_str( string $key, int $max = 200 ): string { + return isset( $_POST[ $key ] ) && is_scalar( $_POST[ $key ] ) ? Input::text( wp_unslash( $_POST[ $key ] ), $max ) : ''; // phpcs:ignore WordPress.Security.NonceVerification + } + + public static function post_raw(): array { + return is_array( $_POST ) ? wp_unslash( $_POST ) : array(); // phpcs:ignore WordPress.Security.NonceVerification + } +} diff --git a/includes/Admin/Csv.php b/includes/Admin/Csv.php new file mode 100644 index 0000000..b0fed3e --- /dev/null +++ b/includes/Admin/Csv.php @@ -0,0 +1,30 @@ + $status, 'search' => $search, 'tests' => $tests ), $page, self::PER_PAGE ); + + echo ''; + echo ' '; + echo ' '; + echo '
'; + Admin::form( 'sg_export_csv', array(), 'sg-inline' ); + echo ''; + + echo '

Donors who chose to be anonymous are shown as "Anonymous". Their name is never stored. Test donations are marked TEST and left out of the CSV and your totals.

'; + + if ( ! $res['rows'] ) { + echo '

No donations found.

'; + Admin::close(); + return; + } + $goals = array(); + foreach ( Store::goals()->all() as $g ) { + $goals[ (int) $g['id'] ] = (string) $g['title']; + } + echo ''; + foreach ( $res['rows'] as $r ) { + $cur = Format::currency( $r['currency'] ); + $test = Format::isTest( $r ); + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
DateDonorAmountFeeTotal paidGoalStatusMessage
' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '' . esc_html( Format::donorName( $r ) ) . ( $test ? ' TEST' : '' ) . '' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '' . esc_html( Format::money( (int) $r['fee_minor'], $cur ) ) . '' . esc_html( Format::money( (int) $r['total_minor'], $cur ) ) . '' . esc_html( $test ? '(test)' : ( $goals[ (int) $r['goal_id'] ] ?? '#' . (int) $r['goal_id'] ) ) . '' . esc_html( ucfirst( (string) $r['status'] ) ) . ( 'approved' === $r['moderation'] ? '' : ' message ' . esc_html( (string) $r['moderation'] ) . '' ) . '' . esc_html( (string) $r['message'] ) . '
'; + $pages = (int) ceil( $res['total'] / self::PER_PAGE ); + if ( $pages > 1 ) { + echo '
' . wp_kses_post( (string) paginate_links( array( + 'base' => add_query_arg( 'paged', '%#%' ), + 'format' => '', + 'current' => $page, + 'total' => $pages, + 'prev_text' => '«', + 'next_text' => '»', + ) ) ) . '
'; + } + echo '

' . (int) $res['total'] . ' donation(s).

'; + Admin::close(); + } + + public static function renderModeration(): void { + Admin::open( 'Message moderation' ); + if ( ! Settings::get( 'moderate_messages' ) ) { + echo '

Message moderation is currently off in Settings, so new messages are shown without review. Anything still waiting below was submitted while it was on.

'; + } + echo '

Approved messages can appear in alerts. Rejected messages are hidden. The donation itself still counts towards your goal either way.

'; + $res = Store::searchDonations( array( 'status' => 'completed', 'moderation' => 'pending' ), 1, 100 ); + if ( ! $res['rows'] ) { + echo '

Nothing waiting for review.

'; + Admin::close(); + return; + } + echo ''; + foreach ( $res['rows'] as $r ) { + $cur = Format::currency( $r['currency'] ); + echo ''; + echo ''; + } + echo '
DateDonorAmountMessageDecision
' . esc_html( self::fmtDate( (string) $r['created_at'] ) ) . '' . esc_html( Format::donorName( $r ) ) . '' . esc_html( Format::money( (int) $r['base_minor'], $cur ) ) . '' . esc_html( (string) $r['message'] ) . ''; + foreach ( array( 'approved' => 'Approve', 'rejected' => 'Reject' ) as $to => $lbl ) { + Admin::form( 'sg_moderate', array( 'donation_id' => (int) $r['id'], 'decision' => $to ), 'sg-inline' ); + echo ' '; + } + echo '
'; + Admin::close(); + } + + public static function handleModerate(): void { + Admin::guard( 'sg_moderate' ); + $post = Admin::post_raw(); + $id = isset( $post['donation_id'] ) ? absint( $post['donation_id'] ) : 0; + $to = isset( $post['decision'] ) && is_string( $post['decision'] ) ? $post['decision'] : ''; + $ok = $id && Store::setModeration( $id, $to ); + Admin::redirect( Admin::url( 'streamgoals-moderation' ), $ok ? 'success' : 'error', $ok ? ( 'approved' === $to ? 'Message approved.' : 'Message rejected.' ) : 'That message could not be updated (it may already be reviewed).' ); + } + + public static function handleExport(): void { + Admin::guard( 'sg_export_csv' ); + $goals = array(); + foreach ( Store::goals()->all() as $g ) { + $goals[ (int) $g['id'] ] = (string) $g['title']; + } + nocache_headers(); + header( 'Content-Type: text/csv; charset=utf-8' ); + header( 'Content-Disposition: attachment; filename="streamgoals-donations-' . gmdate( 'Y-m-d' ) . '.csv"' ); + header( 'X-Content-Type-Options: nosniff' ); + echo "\xEF\xBB\xBF"; // UTF-8 BOM so Excel reads accents correctly + echo Csv::line( array( 'ID', 'Date (UTC)', 'Goal', 'Donor', 'Amount', 'Fee covered', 'Total paid', 'Currency', 'Status', 'Message status', 'Message', 'PayPal order', 'PayPal capture' ) ); // phpcs:ignore WordPress.Security.EscapeOutput -- CSV, not HTML + $after = 0; + do { + $rows = Store::exportBatch( $after, 500 ); + foreach ( $rows as $r ) { + $after = (int) $r['id']; + $cur = Format::currency( $r['currency'] ); + echo Csv::line( array( // phpcs:ignore WordPress.Security.EscapeOutput + $r['id'], + $r['created_at'], + $goals[ (int) $r['goal_id'] ] ?? '', + Format::donorName( $r ), + Format::decimal( (int) $r['base_minor'], $cur ), + Format::decimal( (int) $r['fee_minor'], $cur ), + Format::decimal( (int) $r['total_minor'], $cur ), + $cur, + $r['status'], + $r['moderation'], + $r['message'], + $r['paypal_order_id'], + $r['paypal_capture_id'], + ) ); + } + } while ( count( $rows ) === 500 ); + exit; + } +} diff --git a/includes/Admin/Format.php b/includes/Admin/Format.php new file mode 100644 index 0000000..aaa9bb1 --- /dev/null +++ b/includes/Admin/Format.php @@ -0,0 +1,64 @@ + 'US Dollar', 'EUR' => 'Euro', 'GBP' => 'British Pound', 'CAD' => 'Canadian Dollar', 'AUD' => 'Australian Dollar', + 'NZD' => 'New Zealand Dollar', 'CHF' => 'Swiss Franc', 'SEK' => 'Swedish Krona', 'NOK' => 'Norwegian Krone', 'DKK' => 'Danish Krone', + 'PLN' => 'Polish Zloty', 'CZK' => 'Czech Koruna', 'HUF' => 'Hungarian Forint', 'JPY' => 'Japanese Yen', 'SGD' => 'Singapore Dollar', + 'HKD' => 'Hong Kong Dollar', 'MXN' => 'Mexican Peso', 'BRL' => 'Brazilian Real', 'PHP' => 'Philippine Peso', 'TWD' => 'New Taiwan Dollar', + 'THB' => 'Thai Baht', 'ILS' => 'Israeli Shekel', 'MYR' => 'Malaysian Ringgit', 'CNY' => 'Chinese Yuan', + ); + + public static function currency( mixed $c ): string { + $c = is_string( $c ) ? strtoupper( trim( $c ) ) : ''; + return isset( self::CURRENCIES[ $c ] ) ? $c : 'USD'; + } + + public static function money( int $minor, string $currency ): string { + return Payloads::money( $minor, $currency ); + } + + /** Plain decimal for form inputs, e.g. 1050 USD -> "10.50". */ + public static function decimal( int $minor, string $currency ): string { + return ( new \StreamGoals\Core\Money( max( 0, $minor ), $currency ) )->toDecimalString(); + } + + public static function duration( int $seconds ): string { + $seconds = max( 0, $seconds ); + if ( 0 === $seconds ) { + return '0 seconds'; + } + $parts = array(); + foreach ( array( 'day' => 86400, 'hour' => 3600, 'minute' => 60, 'second' => 1 ) as $name => $size ) { + $n = intdiv( $seconds, $size ); + $seconds %= $size; + if ( $n > 0 ) { + $parts[] = $n . ' ' . $name . ( 1 === $n ? '' : 's' ); + } + } + return implode( ' ', $parts ); + } + + public static function isTest( array $row ): bool { + return str_starts_with( (string) ( $row['paypal_order_id'] ?? '' ), self::TEST_PREFIX ); + } + + /** The real name is shown only for non-anonymous donors. Anonymous names are not stored at all. */ + public static function donorName( array $row ): string { + if ( ! empty( $row['is_anonymous'] ) || '' === trim( (string) ( $row['donor_name'] ?? '' ) ) ) { + return 'Anonymous'; + } + return (string) $row['donor_name']; + } +} diff --git a/includes/Admin/GoalsPage.php b/includes/Admin/GoalsPage.php new file mode 100644 index 0000000..919cfb0 --- /dev/null +++ b/includes/Admin/GoalsPage.php @@ -0,0 +1,318 @@ + 'Active', 'paused' => 'Paused', 'complete' => 'Complete' ); + + public static function render(): void { + $view = Admin::get_str( 'view' ); + $id = Admin::get_int( 'goal' ); + if ( in_array( $view, array( 'new', 'edit' ), true ) ) { + self::renderForm( 'edit' === $view ? $id : 0 ); + } elseif ( 'rules' === $view && $id ) { + self::renderRules( $id ); + } else { + self::renderList(); + } + } + + /* ------------------------------------------------------------------ list */ + + private static function renderList(): void { + Admin::open( 'Goals' ); + echo '

Add new goal

'; + echo '

Overlays and the donation form use your newest active goal(s). Pause a goal to stop accepting donations; mark it complete when you are done. A goal that has donations cannot be deleted (complete it instead), so your records stay intact.

'; + $goals = Store::goals()->all(); + if ( ! $goals ) { + echo '

No goals yet. Create your first goal or run the setup guide.

'; + Admin::close(); + return; + } + echo ''; + foreach ( $goals as $g ) { + $gid = (int) $g['id']; + $cur = Format::currency( $g['currency'] ); + $raised = Store::goals()->raised_minor( $gid ); + $target = (int) $g['target_minor']; + $pct = $target > 0 ? min( 100, intdiv( $raised * 100, $target ) ) : 0; + echo ''; + echo ''; + echo ''; + echo ''; + } + echo '
GoalStatusRaisedDatesActions
' . esc_html( (string) $g['title'] ) . '
ID ' . $gid . ' · [streamgoals_donate goal="' . $gid . '"]
' . esc_html( self::STATUSES[ $g['status'] ] ?? (string) $g['status'] ) . '' . esc_html( Format::money( $raised, $cur ) . ' of ' . Format::money( $target, $cur ) ) . ' (' . (int) $pct . '%)
' . esc_html( self::dateLabel( $g['starts_at'] ?? null, 'Starts' ) ) . '
' . esc_html( self::dateLabel( $g['ends_at'] ?? null, 'Ends' ) ) . '
'; + echo 'Edit '; + echo 'Rules '; + foreach ( array( 'active' => array( 'paused', 'Pause' ), 'paused' => array( 'active', 'Resume' ), 'complete' => array( 'active', 'Reopen' ) ) as $from => [ $to, $lbl ] ) { + if ( $g['status'] === $from ) { + Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => $to ), 'sg-inline' ); + echo ' '; + } + } + if ( 'complete' !== $g['status'] ) { + Admin::form( 'sg_goal_status', array( 'goal_id' => $gid, 'status' => 'complete' ), 'sg-inline' ); + echo ' '; + } + Admin::form( 'sg_goal_delete', array( 'goal_id' => $gid ), 'sg-inline sg-confirm' ); + echo ''; + echo '
'; + Admin::close(); + } + + private static function dateLabel( ?string $utc, string $prefix ): string { + return $utc ? $prefix . ': ' . get_date_from_gmt( $utc, 'Y-m-d H:i' ) : $prefix . ': no date'; + } + + /* ------------------------------------------------------------------ form */ + + private static function renderForm( int $id ): void { + $g = $id ? Store::goals()->find( $id ) : null; + if ( $id && ! $g ) { + Admin::open( 'Goal not found' ); + echo '

Back to goals

'; + Admin::close(); + return; + } + $cur = $g ? Format::currency( $g['currency'] ) : Admin::currency(); + Admin::open( $g ? 'Edit goal' : 'New goal' ); + Admin::form( 'sg_goal_save', array( 'goal_id' => $id ) ); + echo ''; + echo ''; + echo ''; + echo ''; + $fmt = static fn( ?string $utc ): string => $utc ? get_date_from_gmt( $utc, 'Y-m-d\TH:i' ) : ''; + echo ''; + echo ''; + echo ''; + echo '

Cancel

'; + Admin::close(); + } + + /** 'Y-m-d\TH:i' in the site time zone -> UTC 'Y-m-d H:i:s', or null when empty/invalid. */ + private static function toUtc( string $local ): ?string { + if ( ! preg_match( '/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}$/', $local ) ) { + return null; + } + $utc = get_gmt_from_date( str_replace( 'T', ' ', $local ) . ':00' ); + return $utc ?: null; + } + + public static function handleSave(): void { + Admin::guard( 'sg_goal_save' ); + $post = Admin::post_raw(); + $id = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0; + $back = Admin::url( Admin::HOME, $id ? array( 'view' => 'edit', 'goal' => $id ) : array( 'view' => 'new' ) ); + $old = $id ? Store::goals()->find( $id ) : null; + if ( $id && ! $old ) { + Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' ); + } + $cur = $old ? Format::currency( $old['currency'] ) : Admin::currency(); + $title = Input::text( $post['title'] ?? '', 190 ); + $tgt = Input::amountToMinor( $post['target'] ?? '', $cur ); + if ( '' === $title ) { + Admin::redirect( $back, 'error', 'Please give the goal a title.' ); + } + if ( null === $tgt || $tgt <= 0 ) { + Admin::redirect( $back, 'error', 'Please enter a target greater than zero, for example 250.00.' ); + } + $startRaw = Input::text( $post['starts_at'] ?? '', 20 ); + $endRaw = Input::text( $post['ends_at'] ?? '', 20 ); + $start = '' === $startRaw ? null : self::toUtc( $startRaw ); + $end = '' === $endRaw ? null : self::toUtc( $endRaw ); + if ( ( '' !== $startRaw && null === $start ) || ( '' !== $endRaw && null === $end ) ) { + Admin::redirect( $back, 'error', 'That date is not valid.' ); + } + if ( $start && $end && strtotime( $end . ' UTC' ) <= strtotime( $start . ' UTC' ) ) { + Admin::redirect( $back, 'error', 'The end must be after the start.' ); + } + $data = array( 'title' => $title, 'target_minor' => $tgt, 'starts_at' => $start, 'ends_at' => $end, 'counts_fees' => empty( $post['counts_fees'] ) ? 0 : 1 ); + if ( $id ) { + Store::goals()->update( $id, $data ); + } else { + $data['currency'] = $cur; + $data['status'] = 'active'; + $id = Store::goals()->create( $data ); + if ( $id <= 0 ) { + Admin::redirect( $back, 'error', 'The goal could not be saved.' ); + } + Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $id ) ), 'success', 'Goal created. Add rules below if you want a timer or counter.' ); + } + Admin::redirect( Admin::url(), 'success', 'Goal saved.' ); + } + + public static function handleStatus(): void { + Admin::guard( 'sg_goal_status' ); + $post = Admin::post_raw(); + $id = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0; + $status = isset( $post['status'] ) && is_string( $post['status'] ) ? $post['status'] : ''; + if ( ! $id || ! isset( self::STATUSES[ $status ] ) || ! Store::goals()->find( $id ) ) { + Admin::redirect( Admin::url(), 'error', 'Could not change that goal.' ); + } + Store::goals()->update( $id, array( 'status' => $status ) ); + Admin::redirect( Admin::url(), 'success', 'Goal is now ' . strtolower( self::STATUSES[ $status ] ) . '.' ); + } + + public static function handleDelete(): void { + Admin::guard( 'sg_goal_delete' ); + $id = isset( $_POST['goal_id'] ) ? absint( wp_unslash( $_POST['goal_id'] ) ) : 0; // phpcs:ignore WordPress.Security.NonceVerification + if ( ! $id || ! Store::goals()->find( $id ) ) { + Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' ); + } + if ( ! Store::deleteGoal( $id ) ) { + Admin::redirect( Admin::url(), 'error', 'This goal has donations, so it cannot be deleted. Mark it complete instead.' ); + } + Admin::redirect( Admin::url(), 'success', 'Goal deleted.' ); + } + + /* ----------------------------------------------------------------- rules */ + + private static function renderRules( int $goalId ): void { + $g = Store::goals()->find( $goalId ); + if ( ! $g ) { + Admin::open( 'Goal not found' ); + echo '

Back to goals

'; + Admin::close(); + return; + } + $cur = Format::currency( $g['currency'] ); + $rules = Store::rules( $goalId ); + Admin::open( 'Rules for "' . (string) $g['title'] . '"' ); + echo '

← Back to goals

'; + echo '

Rules decide what each donation does besides filling the progress bar: add time to a subathon timer, bump a counter, or fire a bonus alert.

'; + + $editId = Admin::get_int( 'rule' ); + $editRule = $editId ? Store::rule( $editId, $goalId ) : null; + + echo '

Current rules

'; + if ( ! $rules ) { + echo '

No rules yet. The goal bar works without any rules.

'; + } else { + echo ''; + foreach ( $rules as $r ) { + $rid = (int) $r['id']; + echo ''; + echo ''; + } + echo '
RuleWhat it doesActions
' . esc_html( RuleConfig::TYPES[ $r['type'] ] ?? (string) $r['type'] ) . ( $r['enabled'] ? '' : ' (off)' ) . '' . esc_html( RuleConfig::summary( (string) $r['type'], $r['config'], $cur ) ) . ''; + echo 'Edit '; + Admin::form( 'sg_rule_toggle', array( 'goal_id' => $goalId, 'rule_id' => $rid, 'enabled' => $r['enabled'] ? 0 : 1 ), 'sg-inline' ); + echo ' '; + Admin::form( 'sg_rule_delete', array( 'goal_id' => $goalId, 'rule_id' => $rid ), 'sg-inline sg-confirm' ); + echo '
'; + } + echo '
'; + + // Live preview of saved, enabled rules. + $data = array( + 'currency' => $cur, + 'exp' => Money::exponent( $cur ), + 'rules' => array_values( array_map( static fn( $r ) => array( 'type' => $r['type'], 'config' => $r['config'] ), array_filter( $rules, static fn( $r ) => (bool) $r['enabled'] ) ) ), + ); + echo '

What would a donation do?

'; + echo ''; + echo '

Based on your enabled rules, for a single donation on its own. Carry-over from earlier donations and total limits are not included.

'; + echo '
'; + + self::renderRuleForm( $goalId, $cur, $editRule ); + Admin::close(); + } + + private static function renderRuleForm( int $goalId, string $cur, ?array $edit ): void { + $type = $edit ? (string) $edit['type'] : 'add_time'; + $vals = $edit ? RuleConfig::toForm( $type, $edit['config'], $cur ) : array(); + $v = static fn( string $t, string $k, string $d = '' ): string => esc_attr( (string) ( $type === $t && isset( $vals[ $k ] ) ? $vals[ $k ] : $d ) ); + $basisOpts = static function ( string $t ) use ( $type, $vals ): string { + $cur = $type === $t ? ( $vals['basis'] ?? 'base' ) : 'base'; + return ''; + }; + echo '

' . ( $edit ? 'Edit rule' : 'Add a rule' ) . '

'; + Admin::form( 'sg_rule_save', array( 'goal_id' => $goalId, 'rule_id' => $edit ? (int) $edit['id'] : 0 ), 'sg-rule-form' ); + if ( $edit ) { + echo '

' . esc_html( RuleConfig::TYPES[ $type ] ?? $type ) . '

'; + } else { + echo '

'; + } + // add_time + echo '

Add '; + echo ' to the timer for every ' . esc_html( $cur ) . ' donated.

'; + echo 'Limits (optional)'; + echo '

'; + echo '

'; + echo '

'; // phpcs:ignore WordPress.Security.EscapeOutput -- built from escaped parts + // counter + echo '

Add to the counter for every ' . esc_html( $cur ) . ' donated.

'; + echo '

'; + echo '

'; + echo '
Advanced

'; // phpcs:ignore WordPress.Security.EscapeOutput + // bonus + echo '

Trigger a bonus when a single donation is at least ' . esc_html( $cur ) . ' .

'; + echo '

Letters, numbers, _ and - only.

'; + echo '
Advanced

'; // phpcs:ignore WordPress.Security.EscapeOutput + echo '

'; + echo '

'; + if ( $edit ) { + echo ' Cancel'; + } + echo '

'; + } + + public static function handleRuleSave(): void { + Admin::guard( 'sg_rule_save' ); + $post = Admin::post_raw(); + $goalId = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0; + $ruleId = isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0; + $g = $goalId ? Store::goals()->find( $goalId ) : null; + $back = Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $goalId ) ); + if ( ! $g ) { + Admin::redirect( Admin::url(), 'error', 'That goal no longer exists.' ); + } + $type = isset( $post['type'] ) && is_string( $post['type'] ) ? $post['type'] : ''; + if ( ! isset( RuleConfig::TYPES[ $type ] ) ) { + Admin::redirect( $back, 'error', 'Please choose a rule type.' ); + } + $existing = null; + if ( $ruleId ) { + $existing = Store::rule( $ruleId, $goalId ); + if ( ! $existing || $existing['type'] !== $type ) { + Admin::redirect( $back, 'error', 'That rule no longer exists.' ); + } + } + $input = isset( $post['rule'][ $type ] ) && is_array( $post['rule'][ $type ] ) ? $post['rule'][ $type ] : array(); + $res = RuleConfig::sanitize( $type, $input, Format::currency( $g['currency'] ) ); + if ( null === $res['config'] ) { + Admin::redirect( $back . ( $ruleId ? '&rule=' . $ruleId : '' ), 'error', implode( ' ', $res['errors'] ) ); + } + Store::saveRule( $goalId, $type, $res['config'], $existing ? $ruleId : null ); + Admin::redirect( $back, 'success', 'Rule saved: ' . RuleConfig::summary( $type, $res['config'], Format::currency( $g['currency'] ) ) . '.' ); + } + + public static function handleRuleToggle(): void { + Admin::guard( 'sg_rule_toggle' ); + $post = Admin::post_raw(); + $gid = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0; + Store::setRuleEnabled( isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0, $gid, ! empty( $post['enabled'] ) ); + Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ), 'success', 'Rule updated.' ); + } + + public static function handleRuleDelete(): void { + Admin::guard( 'sg_rule_delete' ); + $post = Admin::post_raw(); + $gid = isset( $post['goal_id'] ) ? absint( $post['goal_id'] ) : 0; + Store::deleteRule( isset( $post['rule_id'] ) ? absint( $post['rule_id'] ) : 0, $gid ); + Admin::redirect( Admin::url( Admin::HOME, array( 'view' => 'rules', 'goal' => $gid ) ), 'success', 'Rule deleted.' ); + } +} diff --git a/includes/Admin/Input.php b/includes/Admin/Input.php new file mode 100644 index 0000000..495598c --- /dev/null +++ b/includes/Admin/Input.php @@ -0,0 +1,95 @@ +minor; + } catch ( \InvalidArgumentException ) { + return null; + } + return $minor > 99999999999 ? null : $minor; + } + + /** "3.49" (percent) -> 349 basis points; null when invalid or outside 0..30%. */ + public static function percentToBps( mixed $raw ): ?int { + if ( ! is_scalar( $raw ) ) { + return null; + } + $s = rtrim( trim( str_replace( ',', '.', (string) $raw ) ), '%' ); + if ( ! preg_match( '/^\d{1,2}(\.\d{1,2})?$/', $s ) ) { + return null; + } + [ $w, $f ] = array_pad( explode( '.', $s, 2 ), 2, '' ); + $bps = (int) $w * 100 + (int) str_pad( $f, 2, '0' ); + return $bps <= 3000 ? $bps : null; + } + + /** Whole number within [min,max], else null. Empty string -> null. */ + public static function int( mixed $raw, int $min, int $max ): ?int { + if ( ! is_scalar( $raw ) || ! preg_match( '/^\s*\d{1,12}\s*$/', (string) $raw ) ) { + return null; + } + $n = (int) trim( (string) $raw ); + return ( $n >= $min && $n <= $max ) ? $n : null; + } + + /** Normalise a "one word per line" textarea: trimmed, lowercase, deduplicated, bounded. */ + public static function words( string $text ): string { + $out = array(); + foreach ( preg_split( '/\r\n|\r|\n|,/', $text ) ?: array() as $w ) { + $w = preg_replace( '/[\x00-\x1F\x7F<>]/u', '', trim( $w ) ) ?? ''; + $w = function_exists( 'mb_strtolower' ) ? mb_strtolower( $w ) : strtolower( $w ); + if ( '' === $w || ( function_exists( 'mb_strlen' ) ? mb_strlen( $w ) : strlen( $w ) ) > 40 ) { + continue; + } + $out[ $w ] = true; + if ( count( $out ) >= 500 ) { + break; + } + } + return implode( "\n", array_keys( $out ) ); + } + + /** Event name slug: [a-z0-9_-], max 40, falling back to $default. */ + public static function slug( mixed $raw, string $default = 'big_donation' ): string { + $s = is_scalar( $raw ) ? strtolower( trim( (string) $raw ) ) : ''; + $s = preg_replace( '/[^a-z0-9_-]+/', '_', $s ) ?? ''; + $s = substr( trim( $s, '_-' ), 0, 40 ); + return '' === $s ? $default : $s; + } + + /** Plain single-line text with control chars and tags removed, bounded in length. */ + public static function text( mixed $raw, int $max ): string { + $s = is_scalar( $raw ) ? strip_tags( (string) $raw ) : ''; + $s = preg_replace( '/[\x00-\x1F\x7F]/u', '', $s ) ?? ''; + $s = trim( $s ); + return function_exists( 'mb_substr' ) ? mb_substr( $s, 0, $max ) : substr( $s, 0, $max ); + } + + /** Mask for showing that a secret exists without revealing it. */ + public static function maskSecret( string $secret ): string { + return '' === $secret ? '' : str_repeat( "\u{2022}", 12 ); + } + + /** True when the submitted value is the untouched placeholder or empty (=> keep the stored secret). */ + public static function secretUnchanged( string $submitted ): bool { + $t = trim( $submitted ); + return '' === $t || 1 === preg_match( '/^[\x{2022}*]+$/u', $t ); + } +} diff --git a/includes/Admin/OverlaysPage.php b/includes/Admin/OverlaysPage.php new file mode 100644 index 0000000..fac3624 --- /dev/null +++ b/includes/Admin/OverlaysPage.php @@ -0,0 +1,112 @@ + array( 'Goal bar', 800, 120, 'Progress bar towards your active goal.' ), + 'timer' => array( 'Subathon timer', 400, 120, 'Countdown that grows with donations (needs an "Add time" rule).' ), + 'counter' => array( 'Counter', 400, 120, 'A running count (needs a "Counter" rule).' ), + 'alerts' => array( 'Donation alerts', 600, 300, 'Pop-up alert for each new donation.' ), + ); + + /** @return array{url:string,base:string,sep:string} */ + public static function widgetUrl( string $widget ): array { + $token = OverlayController::token(); + if ( get_option( 'permalink_structure' ) ) { + $base = home_url( '/streamgoals-overlay/' . rawurlencode( $token ) . '/' . rawurlencode( $widget ) . '/' ); + return array( 'url' => $base, 'base' => $base, 'sep' => '?' ); + } + $base = add_query_arg( array( 'sg_overlay_token' => $token, 'sg_overlay_widget' => $widget ), home_url( '/' ) ); + return array( 'url' => $base, 'base' => $base, 'sep' => '&' ); + } + + /** Used by the wizard and this screen: one copy-able link per widget. */ + public static function urlList( bool $withPreview = false ): void { + foreach ( self::WIDGETS as $w => [ $label, $width, $height, $desc ] ) { + $u = self::widgetUrl( $w ); + echo '
'; + echo '

' . esc_html( $label ) . '

' . esc_html( $desc ) . ' OBS size: ' . (int) $width . ' x ' . (int) $height . '

'; + echo '
'; + if ( $withPreview ) { + echo '

'; + echo ''; + } + echo '
'; + } + if ( ! get_option( 'permalink_structure' ) ) { + echo '

Your site uses "Plain" permalinks, so the links use the longer form. They work the same.

'; + } + } + + public static function render(): void { + Admin::open( 'Overlays' ); + $fonts = array( 'sans' => 'Clean sans-serif', 'serif' => 'Serif', 'mono' => 'Monospace', 'rounded' => 'Rounded', 'condensed' => 'Condensed' ); + echo '

Paste these links into OBS as Browser Sources. Use the style builder to change how they look: all links update as you go.

'; + echo '

Style

'; + echo ''; + echo ''; + echo ''; + echo ''; + foreach ( array( 'color' => 'Text color', 'accent' => 'Accent color', 'accent2' => 'Second accent', 'track' => 'Bar background', 'bg' => 'Panel background' ) as $k => $l ) { + echo ''; + } + echo '

Tick a box to override that color; unticked colors come from the theme.

'; + + echo '

Links

'; + self::urlList( true ); + echo '
'; + + echo '

Send a test donation

'; + echo '

Shows a fake donation on the Donation alerts overlay so you can check your OBS setup. Open the alerts preview above (or have OBS running) first, then press the button; the alert appears within a few seconds.

'; + echo '

How tests are kept out of your numbers: test donations are not attached to any goal, so they never count towards raised totals, timers or counters. They are excluded from the CSV export, and marked TEST in the Donations list. Test donations are kept in the database until you delete them below.

'; + Admin::form( 'sg_test_donation', array(), 'sg-inline' ); + echo ' '; + echo ' '; + Admin::form( 'sg_delete_tests', array(), 'sg-inline' ); + echo '
'; + + echo '

Security

The links contain a secret token. If a link was shown on stream or shared by mistake, make new links. The old ones stop working immediately and you will need to paste the new ones into OBS.

'; + Admin::form( 'sg_regen_token', array(), 'sg-confirm' ); + echo '
'; + Admin::close(); + } + + public static function handleTestDonation(): void { + Admin::guard( 'sg_test_donation' ); + $cur = Admin::currency(); + $amt = Input::amountToMinor( Admin::post_str( 'amount', 30 ), $cur ); + if ( null === $amt || $amt <= 0 || $amt > 99999999 ) { + Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'error', 'Please enter a valid test amount, for example 5.00.' ); + } + $id = Store::insertTestDonation( $amt, $cur ); + Admin::redirect( Admin::url( 'streamgoals-overlays' ), $id ? 'success' : 'error', $id ? 'Test donation sent. Watch your alerts overlay.' : 'The test donation could not be saved.' ); + } + + public static function handleDeleteTests(): void { + Admin::guard( 'sg_delete_tests' ); + $n = Store::deleteTestDonations(); + Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', $n . ' test donation(s) deleted.' ); + } + + public static function handleRegenerate(): void { + Admin::guard( 'sg_regen_token' ); + Settings::update( array( 'overlay_token' => bin2hex( random_bytes( 16 ) ) ) ); + Admin::redirect( Admin::url( 'streamgoals-overlays' ), 'success', 'New overlay links created. Update them in OBS.' ); + } +} diff --git a/includes/Admin/PayPalConnector.php b/includes/Admin/PayPalConnector.php new file mode 100644 index 0000000..59c3cd8 --- /dev/null +++ b/includes/Admin/PayPalConnector.php @@ -0,0 +1,125 @@ + +
+ + +
+

Start with Sandbox to try everything for free. When you are ready, create a Live app the same way and switch here. Sandbox and Live use different Client IDs and Secrets.

+ + + + + + + + + + + +
    +
  1. You need a PayPal Business account (free). A personal account cannot receive donations this way. Create one or upgrade your existing account in PayPal settings.
  2. +
  3. Open developer.paypal.com/dashboard/applications and log in with that Business account.
  4. +
  5. At the top, pick Sandbox (to practise) or Live (real money) and click Create App.
  6. +
  7. Give it any name (for example "My stream"), keep the type Merchant, and click Create App.
  8. +
  9. On the next page, copy the Client ID. Under Secret key 1 click Show and copy the Secret.
  10. +
  11. Choose the same mode below (Sandbox or Live), paste both values, and press the button. We will check them and set up payment notifications (the webhook) for you.
  12. +
+

Webhook note: PayPal can only send notifications to a public https:// website. On a local test site the webhook step will fail, which is fine for trying things out.

+ 'settings' === $from ? Admin::url( 'streamgoals-settings' ) : SetupPage::url( $step ); + + $old = Settings::all(); + $post = Admin::post_raw(); + $mode = ( $post['paypal_mode'] ?? '' ) === 'live' ? 'live' : 'sandbox'; + $cid = Input::text( $post['paypal_client_id'] ?? '', 200 ); + $sec = Input::secretUnchanged( (string) ( $post['paypal_client_secret'] ?? '' ) ) ? (string) $old['paypal_client_secret'] : Input::text( $post['paypal_client_secret'], 300 ); + + if ( '' === $cid || '' === $sec ) { + Admin::redirect( $to( 1 ), 'error', 'Please enter both the Client ID and the Secret from your PayPal app.' ); + } + $changed = $mode !== $old['paypal_mode'] || $cid !== $old['paypal_client_id'] || $sec !== $old['paypal_client_secret']; + $update = array( 'paypal_mode' => $mode, 'paypal_client_id' => $cid, 'paypal_client_secret' => $sec ); + if ( $changed ) { + $update['paypal_webhook_id'] = ''; // a webhook belongs to one specific app/mode + delete_option( self::VERIFIED ); + } + Settings::update( $update ); + + $client = new Client( new WpTransport(), new WpCache(), $mode, $cid, $sec ); + $err = $client->testConnection(); + if ( null !== $err ) { + Admin::redirect( $to( 1 ), 'error', 'Connection failed. ' . self::scrub( $err, $sec ) . ' Double-check that you copied the right values and that the mode (Sandbox/Live) matches the app.' ); + } + update_option( self::VERIFIED, self::fingerprint( Settings::all() ), false ); + + $msg = 'Connected to PayPal (' . ( 'live' === $mode ? 'Live' : 'Sandbox' ) . ').'; + $type = 'success'; + if ( '' === (string) Settings::get( 'paypal_webhook_id', '' ) ) { + try { + $id = $client->createWebhook( self::webhookUrl() ); + Settings::update( array( 'paypal_webhook_id' => $id ) ); + $msg .= ' Payment notifications (webhook) were set up automatically.'; + } catch ( PayPalException $e ) { + $type = 'warning'; + $msg .= ' However, the webhook could not be registered automatically: ' . self::scrub( $e->getMessage(), $sec ) + . ' Webhooks need a public https:// site, and a webhook for this address may already exist in your PayPal app (delete it there and try again).'; + } + } + Admin::redirect( $to( 2 ), $type, $msg ); + } + + /** Defensive: make sure an error text can never contain the secret or client id. */ + public static function scrub( string $text, string $secret ): string { + $text = '' !== $secret ? str_replace( $secret, '[hidden]', $text ) : $text; + return Input::text( $text, 400 ); + } +} diff --git a/includes/Admin/RuleConfig.php b/includes/Admin/RuleConfig.php new file mode 100644 index 0000000..e0e6072 --- /dev/null +++ b/includes/Admin/RuleConfig.php @@ -0,0 +1,196 @@ + 'Add time to the timer', + 'counter' => 'Counter', + 'bonus' => 'Big-donation bonus alert', + ); + + private const UNIT_SECONDS = array( 'seconds' => 1, 'minutes' => 60, 'hours' => 3600 ); + + /** + * @param array $in Raw (already wp_unslash'ed) form fields. + * @return array{config:?array,errors:string[]} + */ + public static function sanitize( string $type, array $in, string $currency ): array { + $errors = array(); + $basis = ( $in['basis'] ?? 'base' ) === 'total' ? 'total' : 'base'; + $unit = Input::amountToMinor( $in['unit_amount'] ?? '', $currency ); + + switch ( $type ) { + case 'add_time': + $mult = self::UNIT_SECONDS[ (string) ( $in['time_unit'] ?? 'minutes' ) ] ?? null; + $n = Input::int( $in['time_amount'] ?? '', 1, 1000000 ); + if ( null === $mult ) { + $errors[] = 'Choose seconds, minutes or hours.'; + } + if ( null === $n ) { + $errors[] = 'Enter how much time to add (a whole number, 1 or more).'; + } + if ( null === $unit || $unit <= 0 ) { + $errors[] = 'Enter the donation amount that earns that time (for example 1.00).'; + } + $cap = self::optionalMinutes( $in['cap_minutes'] ?? '', 'The per-donation limit', $errors ); + $max = self::optionalMinutes( $in['max_total_minutes'] ?? '', 'The total limit', $errors ); + if ( $errors ) { + return array( 'config' => null, 'errors' => $errors ); + } + $secs = $n * $mult; + if ( $secs > 31536000 ) { + return array( 'config' => null, 'errors' => array( 'That is too much time per unit (more than a year).' ) ); + } + return array( + 'config' => array( + 'seconds_per_unit' => $secs, + 'unit_minor' => $unit, + 'cap_seconds_per_donation' => $cap, + 'max_total_seconds' => $max, + 'basis' => $basis, + ), + 'errors' => array(), + ); + + case 'counter': + $step = Input::int( $in['step'] ?? '', 1, 1000000 ); + if ( null === $step ) { + $errors[] = 'Enter how much the counter goes up each time (a whole number, 1 or more).'; + } + if ( null === $unit || $unit <= 0 ) { + $errors[] = 'Enter the donation amount that earns each step (for example 10.00).'; + } + if ( $errors ) { + return array( 'config' => null, 'errors' => $errors ); + } + return array( + 'config' => array( + 'step' => $step, + 'per_minor' => $unit, + 'carry_over' => ! empty( $in['carry_over'] ), + 'basis' => $basis, + 'label' => Input::text( $in['label'] ?? '', 40 ), + ), + 'errors' => array(), + ); + + case 'bonus': + $min = Input::amountToMinor( $in['min_amount'] ?? '', $currency ); + if ( null === $min || $min <= 0 ) { + $errors[] = 'Enter the smallest single donation that triggers the bonus (for example 50.00).'; + return array( 'config' => null, 'errors' => $errors ); + } + return array( + 'config' => array( + 'min_minor' => $min, + 'event' => Input::slug( $in['event'] ?? '' ), + 'basis' => $basis, + ), + 'errors' => array(), + ); + } + return array( 'config' => null, 'errors' => array( 'Unknown rule type.' ) ); + } + + private static function optionalMinutes( mixed $raw, string $what, array &$errors ): ?int { + if ( ! is_scalar( $raw ) || '' === trim( (string) $raw ) ) { + return null; + } + $m = Input::int( $raw, 1, 525600 ); + if ( null === $m ) { + $errors[] = $what . ' must be a whole number of minutes (or leave it empty for no limit).'; + return null; + } + return $m * 60; + } + + /** Human-readable one-liner, e.g. "Adds 1 minute for every $1.00". */ + public static function summary( string $type, array $c, string $currency ): string { + $basisNote = 'total' === ( $c['basis'] ?? 'base' ) ? ' (including fees the donor covers)' : ''; + switch ( $type ) { + case 'add_time': + $s = 'Adds ' . Format::duration( (int) ( $c['seconds_per_unit'] ?? 0 ) ) . ' for every ' . Format::money( (int) ( $c['unit_minor'] ?? 0 ), $currency ) . $basisNote; + if ( isset( $c['cap_seconds_per_donation'] ) ) { + $s .= ', at most ' . Format::duration( (int) $c['cap_seconds_per_donation'] ) . ' per donation'; + } + if ( isset( $c['max_total_seconds'] ) ) { + $s .= ', ' . Format::duration( (int) $c['max_total_seconds'] ) . ' in total'; + } + return $s; + case 'counter': + $label = (string) ( $c['label'] ?? '' ); + $s = 'Adds ' . (int) ( $c['step'] ?? 1 ) . ( '' !== $label ? ' to "' . $label . '"' : ' to the counter' ) + . ' for every ' . Format::money( (int) ( $c['per_minor'] ?? 0 ), $currency ) . $basisNote; + return $s . ( ! empty( $c['carry_over'] ) ? ' (leftover amounts carry over to the next donation)' : ' (leftover amounts are not carried over)' ); + case 'bonus': + return 'Triggers the "' . (string) ( $c['event'] ?? 'bonus' ) . '" bonus for any single donation of ' + . Format::money( (int) ( $c['min_minor'] ?? 0 ), $currency ) . ' or more' . $basisNote; + } + return 'Unknown rule'; + } + + /** + * What would a donation of $baseMinor (plus optional covered fee) do against these rules, + * assuming a fresh state (no carry-over, no accumulated caps)? + * + * @param array $rules + * @return string[] + */ + public static function preview( array $rules, int $baseMinor, string $currency, int $feeMinor = 0 ): array { + $d = new Donation( 0, 0, $baseMinor, $feeMinor, $baseMinor + $feeMinor, $currency ); + $lines = array(); + foreach ( $rules as $r ) { + $type = (string) ( $r['type'] ?? '' ); + $cfg = (array) ( $r['config'] ?? array() ); + try { + if ( 'add_time' === $type ) { + $res = AddTimeRule::fromConfig( $cfg )->apply( $d, 0, 0, 0 ); + $lines[] = $res['delta'] > 0 ? 'Timer: +' . Format::duration( $res['delta'] ) : 'Timer: no time added'; + } elseif ( 'counter' === $type ) { + $res = CounterRule::fromConfig( $cfg )->apply( $d, 0, 0 ); + $lbl = (string) ( $cfg['label'] ?? '' ); + $lines[] = ( '' !== $lbl ? $lbl : 'Counter' ) . ': +' . $res['delta']; + } elseif ( 'bonus' === $type ) { + $b = BonusRule::fromConfig( $cfg ); + $lines[] = $b->apply( $d ) ? 'Bonus "' . $b->event . '" triggers' : 'Bonus "' . $b->event . '" does not trigger'; + } + } catch ( \InvalidArgumentException ) { + $lines[] = 'A rule is misconfigured and will be skipped.'; + } + } + return $lines; + } + + /** Reverse of sanitize(): config -> editable form values. */ + public static function toForm( string $type, array $c, string $currency ): array { + $f = array( 'basis' => 'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base' ); + if ( 'add_time' === $type ) { + $s = (int) ( $c['seconds_per_unit'] ?? 60 ); + [ $f['time_amount'], $f['time_unit'] ] = 0 === $s % 3600 && $s > 0 ? array( $s / 3600, 'hours' ) : ( 0 === $s % 60 && $s > 0 ? array( $s / 60, 'minutes' ) : array( $s, 'seconds' ) ); + $f['unit_amount'] = Format::decimal( (int) ( $c['unit_minor'] ?? 100 ), $currency ); + $f['cap_minutes'] = isset( $c['cap_seconds_per_donation'] ) ? (string) intdiv( (int) $c['cap_seconds_per_donation'], 60 ) : ''; + $f['max_total_minutes'] = isset( $c['max_total_seconds'] ) ? (string) intdiv( (int) $c['max_total_seconds'], 60 ) : ''; + } elseif ( 'counter' === $type ) { + $f['step'] = (int) ( $c['step'] ?? 1 ); + $f['unit_amount'] = Format::decimal( (int) ( $c['per_minor'] ?? 1000 ), $currency ); + $f['carry_over'] = ! empty( $c['carry_over'] ); + $f['label'] = (string) ( $c['label'] ?? '' ); + } else { + $f['min_amount'] = Format::decimal( (int) ( $c['min_minor'] ?? 5000 ), $currency ); + $f['event'] = (string) ( $c['event'] ?? 'big_donation' ); + } + return $f; + } +} diff --git a/includes/Admin/SettingsPage.php b/includes/Admin/SettingsPage.php new file mode 100644 index 0000000..a24d042 --- /dev/null +++ b/includes/Admin/SettingsPage.php @@ -0,0 +1,109 @@ + 'Donors choose: they can give a name or stay anonymous', + 'require_name' => 'Donors must give a name', + 'force_anonymous' => 'Everyone is anonymous (no names are collected or stored)', + ); + + public static function render(): void { + Admin::open( 'StreamGoals settings' ); + $s = Settings::all(); + $cur = Admin::currency(); + + echo '

PayPal connection

'; + echo PayPalConnector::isConnected() ? '

Connected (' . esc_html( 'live' === $s['paypal_mode'] ? 'Live' : 'Sandbox' ) . ').

' : '

Not connected yet. Follow the steps in the setup guide.

'; + Admin::form( 'sg_paypal_connect', array( 'return' => 'settings' ) ); + PayPalConnector::fields(); + echo '

Webhook address (registered automatically): ' . esc_html( PayPalConnector::webhookUrl() ) . '
Webhook status: ' . ( '' !== (string) $s['paypal_webhook_id'] ? 'registered' : 'not registered' ) . '

'; + echo '

'; + + Admin::form( 'sg_settings_save' ); + echo '

Donations

'; + echo ''; + echo ''; + echo ''; + echo '
'; + + echo '

Messages

'; + echo ''; + echo '
'; + + echo '

PayPal fee estimate

'; + echo '

When a donor chooses "cover the fees", the form adds the estimated PayPal fee so you receive the amount they intended. The defaults (3.49% + $0.49) are US domestic estimates. Fees for international (cross-border) payments and currency conversion are higher and are not included, so you may receive slightly less than expected in those cases. Check PayPal\'s current fee page for your country and adjust.

'; + echo ''; + echo '
'; + echo '

'; + Admin::close(); + } + + public static function handleSave(): void { + Admin::guard( 'sg_settings_save' ); + $post = Admin::post_raw(); + $back = Admin::url( 'streamgoals-settings' ); + $errors = array(); + $cur = Format::currency( $post['currency'] ?? 'USD' ); + $upd = array(); + + $min = Input::amountToMinor( $post['min_donation'] ?? '', $cur ); + if ( null === $min || $min < 1 ) { + $errors[] = 'Minimum donation must be an amount greater than zero.'; + } else { + $upd['min_donation_minor'] = $min; + } + $len = Input::int( $post['message_max_length'] ?? '', 0, 500 ); + if ( null === $len ) { + $errors[] = 'Longest message must be a number from 0 to 500.'; + } else { + $upd['message_max_length'] = $len; + } + $pct = Input::percentToBps( $post['fee_percent'] ?? '' ); + if ( null === $pct ) { + $errors[] = 'Percentage fee must be between 0 and 30 (for example 3.49).'; + } else { + $upd['fee_percent_bps'] = $pct; + } + $fix = Input::amountToMinor( $post['fee_fixed'] ?? '', $cur ); + if ( null === $fix || $fix > 10000 ) { + $errors[] = 'Fixed fee must be a small amount (for example 0.49).'; + } else { + $upd['fee_fixed_minor'] = $fix; + } + $pol = isset( $post['anonymity_policy'] ) && is_string( $post['anonymity_policy'] ) ? $post['anonymity_policy'] : ''; + if ( ! isset( self::POLICIES[ $pol ] ) ) { + $errors[] = 'Please choose a names option.'; + } else { + $upd['anonymity_policy'] = $pol; + } + $upd['moderate_messages'] = ! empty( $post['moderate_messages'] ); + $upd['profanity_filter'] = ! empty( $post['profanity_filter'] ); + $upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] ); + $upd['profanity_words'] = Input::words( isset( $post['profanity_words'] ) && is_string( $post['profanity_words'] ) ? $post['profanity_words'] : '' ); + + Settings::update( $upd ); + update_option( 'sg_currency', $cur, false ); // Settings has no currency key, so it lives in its own option. + + if ( $errors ) { + Admin::redirect( $back, 'warning', 'Some settings were not saved: ' . implode( ' ', $errors ) . ' Everything else was saved.' ); + } + Admin::redirect( $back, 'success', 'Settings saved.' ); + } +} diff --git a/includes/Admin/SetupPage.php b/includes/Admin/SetupPage.php new file mode 100644 index 0000000..b46db75 --- /dev/null +++ b/includes/Admin/SetupPage.php @@ -0,0 +1,147 @@ + 'PayPal', 2 => 'First goal', 3 => 'Donation page', 4 => 'Overlays' ); + + public static function url( int $step = 1 ): string { + $page = PayPalConnector::isConnected() ? 'streamgoals-setup' : Admin::HOME; + return Admin::url( $page, array( 'step' => $step ) ); + } + + public static function render(): void { + Admin::open( 'StreamGoals setup' ); + $connected = PayPalConnector::isConnected(); + $step = Admin::get_int( 'step' ); + $step = isset( self::STEPS[ $step ] ) ? $step : 1; + if ( ! $connected ) { + $step = 1; // nothing else works before PayPal is connected + } + echo '

Welcome! Four quick steps and you are ready to collect donations on stream.

'; + echo '
    '; + foreach ( self::STEPS as $n => $label ) { + $cls = $n === $step ? 'is-current' : ( $n < $step || ( $connected && $n > 1 ) ? 'is-done' : '' ); + echo '
  1. ' . ( $connected ? '' : '' ) . esc_html( $label ) . ( $connected ? '' : '' ) . '
  2. '; + } + echo '
'; + match ( $step ) { + 2 => self::step2(), + 3 => self::step3(), + 4 => self::step4(), + default => self::step1( $connected ), + }; + echo '
'; + Admin::close(); + } + + private static function step1( bool $connected ): void { + echo '

Step 1: Connect PayPal

'; + if ( $connected ) { + echo '

PayPal is connected. You can continue, or paste new credentials below to change them.

'; + echo '

Continue to step 2

'; + } + PayPalConnector::instructions(); + Admin::form( 'sg_paypal_connect', array( 'return' => 'setup' ) ); + PayPalConnector::fields(); + echo '

'; + } + + private static function step2(): void { + $cur = Admin::currency(); + echo '

Step 2: Create your first goal

Pick a starting point. You can change everything later on the Goals screen.

'; + Admin::form( 'sg_wizard_goal' ); + echo '
'; + $first = true; + foreach ( Templates::LABELS as $key => [ $label, $desc ] ) { + echo ''; + $first = false; + } + echo '
'; + echo ''; + echo ''; + echo '

'; + } + + private static function step3(): void { + echo '

Step 3: Add a donation page

'; + $id = (int) get_option( 'sg_donate_page_id', 0 ); + $post = $id ? get_post( $id ) : null; + if ( $post && 'trash' !== $post->post_status ) { + echo '

Your donation page exists: ' . esc_html( get_the_title( $post ) ) . ' (edit).

'; + } else { + echo '

Viewers donate through a page on your site. We can create it for you now. It simply contains this shortcode:

'; + } + echo '

[streamgoals_donate]

'; + echo '

You can paste that shortcode into any page or post. To show only one goal use [streamgoals_donate goal="ID"].

'; + if ( ! $post || 'trash' === $post->post_status ) { + Admin::form( 'sg_wizard_page', array( 'mode' => 'create' ), 'sg-inline' ); + echo ' '; + } + Admin::form( 'sg_wizard_page', array( 'mode' => 'skip' ), 'sg-inline' ); + echo ''; + } + + private static function step4(): void { + echo '

Step 4: Add the overlays to OBS

'; + echo '

Overlays are small web pages OBS shows on top of your stream. Each one has its own link. Keep these links private: anyone with a link can see your live overlay (not your donor details or money info).

'; + OverlaysPage::urlList(); + echo '

How to add one in OBS

    '; + echo '
  1. In OBS, under Sources click + and choose Browser.
  2. '; + echo '
  3. Name it (for example "Goal bar") and click OK.
  4. '; + echo '
  5. Paste the link into the URL box. Do not tick "Local file".
  6. '; + echo '
  7. Set Width and Height to the recommended size shown next to the link. Leave the custom CSS box as it is.
  8. '; + echo '
  9. Click OK, then move and resize it on your canvas. The background is transparent automatically.
  10. '; + echo '
  11. Want different colors or fonts? Open the Overlays screen, which builds the link for you and lets you send a test donation.
'; + echo '

Finish setup

'; + } + + public static function handleGoal(): void { + Admin::guard( 'sg_wizard_goal' ); + $cur = Admin::currency(); + $key = Admin::post_str( 'template', 20 ); + $tgt = Input::amountToMinor( Admin::post_str( 'target', 30 ), $cur ); + if ( ! Templates::exists( $key ) ) { + Admin::redirect( self::url( 2 ), 'error', 'Please choose a goal template.' ); + } + if ( null === $tgt || $tgt <= 0 ) { + Admin::redirect( self::url( 2 ), 'error', 'Please enter a target amount greater than zero, for example 100.00.' ); + } + $built = Templates::build( $key, $cur, $tgt, Admin::post_str( 'title', 190 ) ); + $built['goal']['starts_at'] = null; + $built['goal']['ends_at'] = null; + $id = Store::goals()->create( $built['goal'] ); + if ( $id <= 0 ) { + Admin::redirect( self::url( 2 ), 'error', 'The goal could not be saved. Please try again.' ); + } + foreach ( $built['rules'] as $r ) { + Store::saveRule( $id, $r['type'], $r['config'] ); + } + update_option( 'sg_wizard_goal_id', $id, false ); + Admin::redirect( self::url( 3 ), 'success', 'Goal created.' ); + } + + public static function handlePage(): void { + Admin::guard( 'sg_wizard_page' ); + if ( 'create' === Admin::post_str( 'mode', 10 ) ) { + if ( ! current_user_can( 'publish_pages' ) ) { + wp_die( esc_html__( 'You do not have permission to do that.', 'streamgoals-donate' ), 403 ); + } + $id = wp_insert_post( array( + 'post_type' => 'page', + 'post_status' => 'publish', + 'post_title' => 'Donate', + 'post_content' => '[streamgoals_donate]', + ), true ); + if ( is_wp_error( $id ) ) { + Admin::redirect( self::url( 3 ), 'error', 'The page could not be created. You can add the shortcode to any page yourself.' ); + } + update_option( 'sg_donate_page_id', (int) $id, false ); + Admin::redirect( self::url( 4 ), 'success', 'Donate page created and published.' ); + } + Admin::redirect( self::url( 4 ), 'info', 'Skipped. Remember to add [streamgoals_donate] to a page.' ); + } +} diff --git a/includes/Admin/Store.php b/includes/Admin/Store.php new file mode 100644 index 0000000..f8bc0bb --- /dev/null +++ b/includes/Admin/Store.php @@ -0,0 +1,185 @@ +prefix . 'sg_' . $name; + } + + public static function goals(): GoalRepository { + return new GoalRepository(); + } + + public static function donations(): DonationRepository { + return new DonationRepository(); + } + + /** @return array[] all rules (enabled or not) with decoded config. */ + public static function rules( int $goalId ): array { + global $wpdb; + $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT * FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d ORDER BY sort ASC, id ASC', $goalId ), ARRAY_A ); + foreach ( (array) $rows as &$r ) { + $cfg = json_decode( (string) $r['config'], true ); + $r['config'] = is_array( $cfg ) ? $cfg : array(); + } + return (array) $rows; + } + + public static function rule( int $ruleId, int $goalId ): ?array { + foreach ( self::rules( $goalId ) as $r ) { + if ( (int) $r['id'] === $ruleId ) { + return $r; + } + } + return null; + } + + public static function saveRule( int $goalId, string $type, array $config, ?int $ruleId = null ): void { + global $wpdb; + $json = wp_json_encode( $config ); + if ( null === $ruleId ) { + $sort = (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COALESCE(MAX(sort),0)+1 FROM ' . self::t( 'rules' ) . ' WHERE goal_id = %d', $goalId ) ); + $wpdb->insert( self::t( 'rules' ), array( 'goal_id' => $goalId, 'type' => $type, 'config' => $json, 'enabled' => 1, 'sort' => $sort ), array( '%d', '%s', '%s', '%d', '%d' ) ); + } else { + $wpdb->update( self::t( 'rules' ), array( 'config' => $json ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%s' ), array( '%d', '%d' ) ); + } + } + + public static function setRuleEnabled( int $ruleId, int $goalId, bool $on ): void { + global $wpdb; + $wpdb->update( self::t( 'rules' ), array( 'enabled' => $on ? 1 : 0 ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%d' ), array( '%d', '%d' ) ); + } + + /** Deleting a rule keeps its event history rows out of the way (they are only idempotency markers). */ + public static function deleteRule( int $ruleId, int $goalId ): void { + global $wpdb; + if ( ! self::rule( $ruleId, $goalId ) ) { + return; + } + $wpdb->delete( self::t( 'rules' ), array( 'id' => $ruleId, 'goal_id' => $goalId ), array( '%d', '%d' ) ); + $wpdb->delete( self::t( 'rule_events' ), array( 'rule_id' => $ruleId ), array( '%d' ) ); + $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::t( 'state' ) . ' WHERE goal_id = %d AND skey LIKE %s', $goalId, '%:' . $ruleId ) ); + } + + public static function donationCountForGoal( int $goalId ): int { + global $wpdb; + return (int) $wpdb->get_var( $wpdb->prepare( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . ' WHERE goal_id = %d', $goalId ) ); + } + + /** Only possible when the goal has no donations (otherwise donations would be orphaned). */ + public static function deleteGoal( int $goalId ): bool { + global $wpdb; + if ( self::donationCountForGoal( $goalId ) > 0 ) { + return false; + } + foreach ( self::rules( $goalId ) as $r ) { + self::deleteRule( (int) $r['id'], $goalId ); + } + $wpdb->delete( self::t( 'state' ), array( 'goal_id' => $goalId ), array( '%d' ) ); + return self::goals()->delete( $goalId ); + } + + /** + * @param array{status?:string,search?:string,tests?:string,moderation?:string} $f + * @return array{rows:array[],total:int} + */ + public static function searchDonations( array $f, int $page, int $perPage ): array { + global $wpdb; + [ $where, $args ] = self::donationWhere( $f ); + $t = self::t( 'donations' ); + $total = (int) $wpdb->get_var( $args ? $wpdb->prepare( "SELECT COUNT(*) FROM {$t} WHERE {$where}", ...$args ) : "SELECT COUNT(*) FROM {$t} WHERE {$where}" ); + $a2 = array_merge( $args, array( $perPage, max( 0, ( $page - 1 ) * $perPage ) ) ); + $rows = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM {$t} WHERE {$where} ORDER BY id DESC LIMIT %d OFFSET %d", ...$a2 ), ARRAY_A ); + return array( 'rows' => (array) $rows, 'total' => $total ); + } + + /** @return array{0:string,1:array} */ + private static function donationWhere( array $f ): array { + global $wpdb; + $w = array( '1=1' ); + $args = array(); + $st = $f['status'] ?? ''; + if ( in_array( $st, array( 'pending', 'completed', 'refunded', 'reversed' ), true ) ) { + $w[] = 'status = %s'; + $args[] = $st; + } + if ( in_array( $f['moderation'] ?? '', array( 'pending', 'approved', 'rejected' ), true ) ) { + $w[] = 'moderation = %s'; + $args[] = $f['moderation']; + } + if ( 'hide' === ( $f['tests'] ?? '' ) ) { + $w[] = 'paypal_order_id NOT LIKE %s'; + $args[] = $wpdb->esc_like( Format::TEST_PREFIX ) . '%'; + } + $s = trim( (string) ( $f['search'] ?? '' ) ); + if ( '' !== $s ) { + $like = '%' . $wpdb->esc_like( $s ) . '%'; + // Names of anonymous donors are never stored, and are never searchable. + $w[] = '( ( is_anonymous = 0 AND donor_name LIKE %s ) OR message LIKE %s OR paypal_order_id LIKE %s OR paypal_capture_id LIKE %s )'; + array_push( $args, $like, $like, $like, $like ); + } + return array( implode( ' AND ', $w ), $args ); + } + + /** Real donations only (test donations excluded). Streams in batches to bound memory. */ + public static function exportBatch( int $afterId, int $limit ): array { + global $wpdb; + return (array) $wpdb->get_results( + $wpdb->prepare( + 'SELECT * FROM ' . self::t( 'donations' ) . ' WHERE id > %d AND paypal_order_id NOT LIKE %s AND goal_id > 0 ORDER BY id ASC LIMIT %d', + $afterId, + $wpdb->esc_like( Format::TEST_PREFIX ) . '%', + $limit + ), + ARRAY_A + ); + } + + public static function pendingModerationCount(): int { + global $wpdb; + return (int) $wpdb->get_var( 'SELECT COUNT(*) FROM ' . self::t( 'donations' ) . " WHERE status = 'completed' AND moderation = 'pending'" ); + } + + public static function setModeration( int $id, string $to ): bool { + global $wpdb; + if ( ! in_array( $to, array( 'approved', 'rejected' ), true ) ) { + return false; + } + $n = $wpdb->query( $wpdb->prepare( 'UPDATE ' . self::t( 'donations' ) . " SET moderation = %s WHERE id = %d AND moderation = 'pending'", $to, $id ) ); + return 1 === $n; + } + + /** + * Test donations: goal_id = 0 (so every per-goal SUM and the rules engine ignore them), + * paypal_order_id/capture id start with TEST-, and the message is flagged. Excluded from CSV. + */ + public static function insertTestDonation( int $amountMinor, string $currency ): ?int { + return self::donations()->insert( array( + 'goal_id' => 0, + 'paypal_order_id' => Format::TEST_PREFIX . bin2hex( random_bytes( 6 ) ), + 'paypal_capture_id' => Format::TEST_PREFIX . bin2hex( random_bytes( 8 ) ), + 'base_minor' => $amountMinor, + 'fee_minor' => 0, + 'total_minor' => $amountMinor, + 'currency' => $currency, + 'donor_name' => 'Test Donor', + 'is_anonymous' => 0, + 'message' => '[TEST] This is a test alert from StreamGoals.', + 'status' => 'completed', + 'moderation' => 'approved', + ) ); + } + + public static function deleteTestDonations(): int { + global $wpdb; + return (int) $wpdb->query( $wpdb->prepare( 'DELETE FROM ' . self::t( 'donations' ) . ' WHERE goal_id = 0 AND paypal_order_id LIKE %s', $wpdb->esc_like( Format::TEST_PREFIX ) . '%' ) ); + } +} diff --git a/includes/Admin/Templates.php b/includes/Admin/Templates.php new file mode 100644 index 0000000..b11e60a --- /dev/null +++ b/includes/Admin/Templates.php @@ -0,0 +1,40 @@ + array( 'Simple goal', 'A progress bar towards a fundraising target. Nothing else.' ), + 'subathon' => array( 'Subathon timer: +1 min per $1', 'A countdown that gets longer with every donation (1 minute added for every $1).' ), + 'counter' => array( 'Counter: +1 per $10', 'A counter that goes up by 1 for every $10 donated (for example "pies thrown").' ), + ); + + public static function exists( string $key ): bool { + return isset( self::LABELS[ $key ] ); + } + + /** + * @return array{goal:array,rules:array} + */ + public static function build( string $key, string $currency, int $targetMinor, string $title = '' ): array { + $one = 10 ** Money::exponent( $currency ); // one whole currency unit, in minor units + $name = '' !== trim( $title ) ? trim( $title ) : ( 'subathon' === $key ? 'Subathon' : ( 'counter' === $key ? 'Donation counter' : 'My first goal' ) ); + $goal = array( 'title' => $name, 'target_minor' => $targetMinor, 'currency' => $currency, 'status' => 'active', 'counts_fees' => 0 ); + $rules = array(); + if ( 'subathon' === $key ) { + $rules[] = array( 'type' => 'add_time', 'config' => array( + 'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'basis' => 'base', + ) ); + } elseif ( 'counter' === $key ) { + $rules[] = array( 'type' => 'counter', 'config' => array( + 'step' => 1, 'per_minor' => 10 * $one, 'carry_over' => true, 'basis' => 'base', 'label' => 'Count', + ) ); + } + return array( 'goal' => $goal, 'rules' => $rules ); + } +} diff --git a/tests/Unit/AdminLogicTest.php b/tests/Unit/AdminLogicTest.php new file mode 100644 index 0000000..a653c03 --- /dev/null +++ b/tests/Unit/AdminLogicTest.php @@ -0,0 +1,121 @@ +assertSame( "'" . $v, Csv::cell( $v ) ); + } + $this->assertSame( 'hello', Csv::cell( 'hello' ) ); + $this->assertSame( '10.00', Csv::cell( '10.00' ) ); + $this->assertSame( '', Csv::cell( null ) ); + $this->assertSame( "\"a\",\"'=b\",\"say \"\"hi\"\"\"\r\n", Csv::line( array( 'a', '=b', 'say "hi"' ) ) ); + } + + public function test_amount_parsing(): void { + $this->assertSame( 100, Input::amountToMinor( '1', 'USD' ) ); + $this->assertSame( 100050, Input::amountToMinor( '$1,000.50', 'USD' ) ); + $this->assertSame( 500, Input::amountToMinor( '500', 'JPY' ) ); + $this->assertNull( Input::amountToMinor( '1.234', 'USD' ) ); + $this->assertNull( Input::amountToMinor( '-5', 'USD' ) ); + $this->assertNull( Input::amountToMinor( 'abc', 'USD' ) ); + $this->assertNull( Input::amountToMinor( '', 'USD' ) ); + $this->assertNull( Input::amountToMinor( array( '1' ), 'USD' ) ); + } + + public function test_percent_and_misc_input(): void { + $this->assertSame( 349, Input::percentToBps( '3.49' ) ); + $this->assertSame( 350, Input::percentToBps( '3.5%' ) ); + $this->assertSame( 0, Input::percentToBps( '0' ) ); + $this->assertNull( Input::percentToBps( '31' ) ); + $this->assertNull( Input::percentToBps( 'x' ) ); + $this->assertSame( "bad\nword", Input::words( " Bad\r\nword\nBAD" ) ); + $this->assertSame( 'big_donation', Input::slug( '!!!' ) ); + $this->assertSame( 'mega_win', Input::slug( 'Mega Win' ) ); + $this->assertTrue( Input::secretUnchanged( Input::maskSecret( 'abc' ) ) ); + $this->assertTrue( Input::secretUnchanged( '' ) ); + $this->assertFalse( Input::secretUnchanged( 'newsecret' ) ); + $this->assertSame( '', Input::maskSecret( '' ) ); + } + + public function test_add_time_sanitize_uses_exact_config_keys(): void { + $r = RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00', 'cap_minutes' => '10', 'max_total_minutes' => '' ), 'USD' ); + $this->assertSame( array(), $r['errors'] ); + $this->assertSame( + array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' ), + $r['config'] + ); + } + + public function test_sanitize_validation_errors(): void { + $this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array(), 'USD' )['errors'] ); + $this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '0', 'time_unit' => 'minutes', 'unit_amount' => '1' ), 'USD' )['errors'] ); + $this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '0' ), 'USD' )['errors'] ); + $this->assertNotEmpty( RuleConfig::sanitize( 'add_time', array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1', 'cap_minutes' => 'x' ), 'USD' )['errors'] ); + $this->assertNotEmpty( RuleConfig::sanitize( 'counter', array( 'step' => '1' ), 'USD' )['errors'] ); + $this->assertNotEmpty( RuleConfig::sanitize( 'bonus', array( 'min_amount' => '0' ), 'USD' )['errors'] ); + $this->assertNotEmpty( RuleConfig::sanitize( 'nope', array(), 'USD' )['errors'] ); + $this->assertNull( RuleConfig::sanitize( 'nope', array(), 'USD' )['config'] ); + } + + public function test_counter_and_bonus_sanitize(): void { + $c = RuleConfig::sanitize( 'counter', array( 'step' => '1', 'unit_amount' => '10', 'carry_over' => '1', 'label' => 'Pies' ), 'USD' ); + $this->assertSame( array( 'step' => 1, 'per_minor' => 1000, 'carry_over' => true, 'basis' => 'base', 'label' => 'Pies' ), $c['config'] ); + $b = RuleConfig::sanitize( 'bonus', array( 'min_amount' => '50', 'event' => 'Big Donation', 'basis' => 'total' ), 'USD' ); + $this->assertSame( array( 'min_minor' => 5000, 'event' => 'big_donation', 'basis' => 'total' ), $b['config'] ); + } + + public function test_summaries(): void { + $this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) ); + $this->assertStringContainsString( 'at most 10 minutes per donation', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600 ), 'USD' ) ); + $this->assertStringContainsString( 'Adds 1 to "Pies" for every $10.00', RuleConfig::summary( 'counter', array( 'step' => 1, 'per_minor' => 1000, 'label' => 'Pies', 'carry_over' => true ), 'USD' ) ); + $this->assertStringContainsString( '$50.00 or more', RuleConfig::summary( 'bonus', array( 'min_minor' => 5000, 'event' => 'big' ), 'USD' ) ); + $this->assertSame( '1 hour 1 minute 1 second', Format::duration( 3661 ) ); + } + + public function test_preview_for_25_dollars(): void { + $rules = array( + array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ) ), + array( 'type' => 'counter', 'config' => array( 'step' => 1, 'per_minor' => 1000, 'label' => 'Pies' ) ), + array( 'type' => 'bonus', 'config' => array( 'min_minor' => 5000, 'event' => 'big' ) ), + ); + $this->assertSame( array( 'Timer: +25 minutes', 'Pies: +2', 'Bonus "big" does not trigger' ), RuleConfig::preview( $rules, 2500, 'USD' ) ); + } + + public function test_form_roundtrip(): void { + $cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'basis' => 'base' ); + $form = RuleConfig::toForm( 'add_time', $cfg, 'USD' ); + $back = RuleConfig::sanitize( 'add_time', $form, 'USD' ); + $this->assertSame( $cfg, $back['config'] ); + } + + public function test_templates(): void { + $t = Templates::build( 'subathon', 'USD', 100000 ); + $this->assertSame( 60, $t['rules'][0]['config']['seconds_per_unit'] ); + $this->assertSame( 100, $t['rules'][0]['config']['unit_minor'] ); + $c = Templates::build( 'counter', 'USD', 5000, 'Pies' ); + $this->assertSame( 1000, $c['rules'][0]['config']['per_minor'] ); + $this->assertSame( 'Pies', $c['goal']['title'] ); + $this->assertSame( 10, Templates::build( 'counter', 'JPY', 5000 )['rules'][0]['config']['per_minor'] ); + $this->assertSame( array(), Templates::build( 'simple', 'USD', 5000 )['rules'] ); + $this->assertFalse( Templates::exists( 'x' ) ); + } + + public function test_donor_name_and_test_flag(): void { + $this->assertSame( 'Anonymous', Format::donorName( array( 'is_anonymous' => 1, 'donor_name' => 'Secret' ) ) ); + $this->assertSame( 'Anonymous', Format::donorName( array( 'is_anonymous' => 0, 'donor_name' => '' ) ) ); + $this->assertSame( 'Sam', Format::donorName( array( 'is_anonymous' => 0, 'donor_name' => 'Sam' ) ) ); + $this->assertTrue( Format::isTest( array( 'paypal_order_id' => 'TEST-abc' ) ) ); + $this->assertFalse( Format::isTest( array( 'paypal_order_id' => '5O1234' ) ) ); + } +}