diff --git a/assets/admin/rules.js b/assets/admin/rules.js index 940547d..72185e2 100644 --- a/assets/admin/rules.js +++ b/assets/admin/rules.js @@ -42,7 +42,8 @@ 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'; + var note = c.max_timer_seconds != null ? ' (the timer never goes above ' + duration( c.max_timer_seconds ) + ')' : ''; + return ( d > 0 ? 'Timer: +' + duration( d ) : 'Timer: no time added' ) + note; } if ( rule.type === 'counter' ) { if ( ! c.per_minor ) { return null; } @@ -74,6 +75,7 @@ /* 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' ); @@ -93,7 +95,8 @@ 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 } }; + var clock = parseInt( val( g, 'max_timer_minutes' ), 10 ); + return { type: type, config: { seconds_per_unit: n * mult, unit_minor: unit, cap_seconds_per_donation: cap > 0 ? cap * 60 : null, max_timer_seconds: clock > 0 ? clock * 60 : null } }; } if ( type === 'counter' ) { var step = parseInt( val( g, 'step' ), 10 ); diff --git a/assets/donate/donate.js b/assets/donate/donate.js index 4b88671..abed65f 100644 --- a/assets/donate/donate.js +++ b/assets/donate/donate.js @@ -41,7 +41,8 @@ var s = document.createElement('script'); s.id = 'sg-paypal-sdk'; s.src = 'https://www.paypal.com/sdk/js?client-id=' + encodeURIComponent(C.clientId) + - '¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons'; + '¤cy=' + encodeURIComponent(currency) + '&intent=capture&components=buttons' + + ((C.disableFunding && C.disableFunding.length) ? '&disable-funding=' + encodeURIComponent(C.disableFunding.join(',')) : ''); s.onload = function () { window.paypal ? resolve(window.paypal) : reject(new Error(T.sdkError)); }; s.onerror = function () { reject(new Error(T.sdkError)); }; document.head.appendChild(s); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 6861b63..fa0fb9c 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -37,9 +37,9 @@ Rules engine entry point (Agent 2 implements, Agent 1 calls after a capture is r Rules\Engine::applyDonation(Donation $d): void; // idempotent via sg_rule_events UNIQUE Rules\Engine::reverseDonation(Donation $d): void; // honors per-rule "reverse on refund" ``` -Rule `config` examples: +Rule `config` examples (`max_total_seconds` caps what one rule has added over time; `max_timer_seconds` caps how long the timer can ever get, null = uncapped): ```json -{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"basis":"base"} +{"type":"add_time","seconds_per_unit":60,"unit_minor":100,"cap_seconds_per_donation":null,"max_total_seconds":null,"max_timer_seconds":null,"basis":"base"} {"type":"counter","step":1,"per_minor":1000,"carry_over":true,"basis":"base","label":"Pies"} {"type":"bonus","min_minor":5000,"event":"big_donation"} ``` diff --git a/includes/Admin/GoalsPage.php b/includes/Admin/GoalsPage.php index 919cfb0..8f51570 100644 --- a/includes/Admin/GoalsPage.php +++ b/includes/Admin/GoalsPage.php @@ -249,9 +249,10 @@ final class GoalsPage { echo ''; } echo ' to the timer for every ' . esc_html( $cur ) . ' donated.

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

'; echo '

'; + echo '

Leave empty for no limit. For example, 1440 means the clock never shows more than 24 hours.

'; echo '

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

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

'; diff --git a/includes/Admin/RuleConfig.php b/includes/Admin/RuleConfig.php index e0e6072..cba5536 100644 --- a/includes/Admin/RuleConfig.php +++ b/includes/Admin/RuleConfig.php @@ -46,6 +46,7 @@ final class RuleConfig { } $cap = self::optionalMinutes( $in['cap_minutes'] ?? '', 'The per-donation limit', $errors ); $max = self::optionalMinutes( $in['max_total_minutes'] ?? '', 'The total limit', $errors ); + $clk = self::optionalMinutes( $in['max_timer_minutes'] ?? '', 'The longest the timer can get', $errors ); if ( $errors ) { return array( 'config' => null, 'errors' => $errors ); } @@ -59,6 +60,7 @@ final class RuleConfig { 'unit_minor' => $unit, 'cap_seconds_per_donation' => $cap, 'max_total_seconds' => $max, + 'max_timer_seconds' => $clk, 'basis' => $basis, ), 'errors' => array(), @@ -128,6 +130,9 @@ final class RuleConfig { if ( isset( $c['max_total_seconds'] ) ) { $s .= ', ' . Format::duration( (int) $c['max_total_seconds'] ) . ' in total'; } + if ( isset( $c['max_timer_seconds'] ) ) { + $s .= ', up to ' . Format::duration( (int) $c['max_timer_seconds'] ) . ' on the clock'; + } return $s; case 'counter': $label = (string) ( $c['label'] ?? '' ); @@ -158,6 +163,9 @@ final class RuleConfig { 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'; + if ( isset( $cfg['max_timer_seconds'] ) ) { + $lines[ count( $lines ) - 1 ] .= ' (the timer never goes above ' . Format::duration( (int) $cfg['max_timer_seconds'] ) . ')'; + } } elseif ( 'counter' === $type ) { $res = CounterRule::fromConfig( $cfg )->apply( $d, 0, 0 ); $lbl = (string) ( $cfg['label'] ?? '' ); @@ -182,6 +190,7 @@ final class RuleConfig { $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 ) : ''; + $f['max_timer_minutes'] = isset( $c['max_timer_seconds'] ) ? (string) intdiv( (int) $c['max_timer_seconds'], 60 ) : ''; } elseif ( 'counter' === $type ) { $f['step'] = (int) ( $c['step'] ?? 1 ); $f['unit_amount'] = Format::decimal( (int) ( $c['per_minor'] ?? 1000 ), $currency ); diff --git a/includes/Admin/SettingsPage.php b/includes/Admin/SettingsPage.php index 5e9afa9..37f8c58 100644 --- a/includes/Admin/SettingsPage.php +++ b/includes/Admin/SettingsPage.php @@ -47,6 +47,17 @@ final class SettingsPage { echo ''; echo '


'; + echo '

Checkout buttons

'; + + echo '

Advanced

'; + 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 ''; @@ -93,6 +104,14 @@ final class SettingsPage { } else { $upd['anonymity_policy'] = $pol; } + $ipMode = isset( $post['visitor_ip_header'] ) && is_string( $post['visitor_ip_header'] ) ? $post['visitor_ip_header'] : ''; + if ( ! array_key_exists( $ipMode, \StreamGoals\Core\ClientIp::MODES ) ) { + $errors[] = 'Please choose a visitor IP option.'; + } else { + $upd['visitor_ip_header'] = $ipMode; + } + $upd['funding_card'] = ! empty( $post['funding_card'] ); + $upd['funding_paylater'] = ! empty( $post['funding_paylater'] ); $upd['moderate_messages'] = ! empty( $post['moderate_messages'] ); $upd['profanity_filter'] = ! empty( $post['profanity_filter'] ); $upd['profanity_use_builtin'] = ! empty( $post['profanity_use_builtin'] ); diff --git a/includes/Admin/Templates.php b/includes/Admin/Templates.php index b11e60a..d5392b1 100644 --- a/includes/Admin/Templates.php +++ b/includes/Admin/Templates.php @@ -28,7 +28,7 @@ final class Templates { $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', + 'seconds_per_unit' => 60, 'unit_minor' => $one, 'cap_seconds_per_donation' => null, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base', ) ); } elseif ( 'counter' === $key ) { $rules[] = array( 'type' => 'counter', 'config' => array( diff --git a/includes/Core/ClientIp.php b/includes/Core/ClientIp.php new file mode 100644 index 0000000..7767ef8 --- /dev/null +++ b/includes/Core/ClientIp.php @@ -0,0 +1,56 @@ + 'Not behind a proxy or CDN (most sites)', + self::MODE_CLOUDFLARE => 'Cloudflare (CF-Connecting-IP)', + self::MODE_REAL_IP => 'X-Real-IP header', + self::MODE_FORWARDED => 'X-Forwarded-For header (one proxy in front)', + ); + + /** @param array $server $_SERVER-style values (already unslashed). */ + public static function resolve( array $server, string $mode = self::MODE_DIRECT ): string { + $remote = self::valid( $server['REMOTE_ADDR'] ?? null ); + $fromHeader = null; + switch ( $mode ) { + case self::MODE_CLOUDFLARE: + $fromHeader = self::valid( $server['HTTP_CF_CONNECTING_IP'] ?? null ); + break; + case self::MODE_REAL_IP: + $fromHeader = self::valid( $server['HTTP_X_REAL_IP'] ?? null ); + break; + case self::MODE_FORWARDED: + $raw = $server['HTTP_X_FORWARDED_FOR'] ?? null; + if ( is_string( $raw ) && '' !== trim( $raw ) ) { + $parts = array_map( 'trim', explode( ',', $raw ) ); + $fromHeader = self::valid( end( $parts ) ); // the entry our proxy appended; earlier ones are client-supplied + } + break; + } + return $fromHeader ?? $remote ?? 'unknown'; + } + + private static function valid( mixed $v ): ?string { + if ( ! is_string( $v ) ) { + return null; + } + $v = trim( $v ); + return false !== filter_var( $v, FILTER_VALIDATE_IP ) ? $v : null; + } +} diff --git a/includes/Core/Settings.php b/includes/Core/Settings.php index d0924de..070a7fc 100644 --- a/includes/Core/Settings.php +++ b/includes/Core/Settings.php @@ -35,6 +35,9 @@ final class Settings { 'message_max_length' => 200, 'min_donation_minor' => 100, 'overlay_token' => '', + 'visitor_ip_header' => '', // '' | cloudflare | real_ip | forwarded (see Core\ClientIp) + 'funding_paylater' => false, // show PayPal "Pay Later" button + 'funding_card' => true, // show the Debit/Credit Card button ); } diff --git a/includes/Rest/DonateController.php b/includes/Rest/DonateController.php index d3ac3ec..54039ce 100644 --- a/includes/Rest/DonateController.php +++ b/includes/Rest/DonateController.php @@ -179,6 +179,7 @@ final class DonateController { 'policy' => (string) $s['anonymity_policy'], 'minMinor' => \StreamGoals\Core\Settings::effectiveMin( (int) $s['min_donation_minor'] ), 'messageMax' => min( 500, (int) $s['message_max_length'] ), + 'disableFunding' => array_values( array_filter( array( empty( $s['funding_paylater'] ) ? 'paylater' : '', empty( $s['funding_card'] ) ? 'card' : '' ) ) ), 'goals' => $goals, 'i18n' => array( 'goal' => __( 'Goal', 'streamgoals-donate' ), @@ -231,7 +232,13 @@ final class DonateController { } private static function limit( string $bucket, int $max, int $window ): ?\WP_Error { - $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : 'unknown'; + $server = array(); + foreach ( array( 'REMOTE_ADDR', 'HTTP_CF_CONNECTING_IP', 'HTTP_X_REAL_IP', 'HTTP_X_FORWARDED_FOR' ) as $k ) { + if ( isset( $_SERVER[ $k ] ) && is_string( $_SERVER[ $k ] ) ) { + $server[ $k ] = sanitize_text_field( wp_unslash( $_SERVER[ $k ] ) ); + } + } + $ip = \StreamGoals\Core\ClientIp::resolve( $server, (string) \StreamGoals\Core\Settings::get( 'visitor_ip_header', '' ) ); if ( ( new RateLimiter( new WpCache() ) )->allow( $bucket . '|' . $ip, $max, $window ) ) { return null; } diff --git a/includes/Rules/AddTimeRule.php b/includes/Rules/AddTimeRule.php index 9b37991..79cf154 100644 --- a/includes/Rules/AddTimeRule.php +++ b/includes/Rules/AddTimeRule.php @@ -6,7 +6,8 @@ namespace StreamGoals\Rules; /** * Adds seconds to a goal timer. Proportional: seconds = floor(amount * seconds_per_unit / unit_minor). * cap_seconds_per_donation limits one donation; max_total_seconds limits the cumulative seconds - * this rule may ever add (net of reversals). The timer is an absolute ends_at timestamp. + * this rule may ever add (net of reversals). maxTimer caps the remaining time on the clock (ends_at - now); + * null = uncapped. A timer already above the cap is never shortened, it just gets 0 added. The timer is an absolute ends_at timestamp. */ final class AddTimeRule { @@ -15,9 +16,10 @@ final class AddTimeRule { public readonly int $unitMinor, public readonly ?int $capPerDonation = null, public readonly ?int $maxTotal = null, - public readonly string $basis = 'base' + public readonly string $basis = 'base', + public readonly ?int $maxTimer = null ) { - if ( $unitMinor <= 0 || $secondsPerUnit < 0 ) { + if ( $unitMinor <= 0 || $secondsPerUnit < 0 || ( null !== $maxTimer && $maxTimer < 1 ) ) { throw new \InvalidArgumentException( 'Invalid add_time config.' ); } } @@ -28,7 +30,8 @@ final class AddTimeRule { (int) ( $c['unit_minor'] ?? 0 ), isset( $c['cap_seconds_per_donation'] ) ? (int) $c['cap_seconds_per_donation'] : null, isset( $c['max_total_seconds'] ) ? (int) $c['max_total_seconds'] : null, - 'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base' + 'total' === ( $c['basis'] ?? 'base' ) ? 'total' : 'base', + isset( $c['max_timer_seconds'] ) ? (int) $c['max_timer_seconds'] : null ); } @@ -41,14 +44,18 @@ final class AddTimeRule { if ( null !== $this->maxTotal ) { $delta = min( $delta, max( 0, $this->maxTotal - $addedTotal ) ); } + // Expired (or never started) timers restart from now. + $start = max( $endsAt, $now ); + if ( null !== $this->maxTimer ) { + $delta = min( $delta, max( 0, $this->maxTimer - ( $start - $now ) ) ); + } $delta = max( 0, $delta ); if ( 0 === $delta ) { return array( 'delta' => 0, 'ends_at' => $endsAt, 'added_total' => $addedTotal ); } - // Expired (or never started) timers restart from now. return array( 'delta' => $delta, - 'ends_at' => max( $endsAt, $now ) + $delta, + 'ends_at' => $start + $delta, 'added_total' => $addedTotal + $delta, ); } diff --git a/tests/Unit/AdminLogicTest.php b/tests/Unit/AdminLogicTest.php index a653c03..81aee5c 100644 --- a/tests/Unit/AdminLogicTest.php +++ b/tests/Unit/AdminLogicTest.php @@ -52,7 +52,7 @@ final class AdminLogicTest extends TestCase { $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' ), + array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => null, 'basis' => 'base' ), $r['config'] ); } @@ -92,8 +92,23 @@ final class AdminLogicTest extends TestCase { $this->assertSame( array( 'Timer: +25 minutes', 'Pies: +2', 'Bonus "big" does not trigger' ), RuleConfig::preview( $rules, 2500, 'USD' ) ); } + public function test_max_timer_validation_and_summary(): void { + $base = array( 'time_amount' => '1', 'time_unit' => 'minutes', 'unit_amount' => '1.00' ); + $this->assertNull( RuleConfig::sanitize( 'add_time', $base, 'USD' )['config']['max_timer_seconds'] ); + $this->assertNull( RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => ' ' ), 'USD' )['config']['max_timer_seconds'] ); + $this->assertSame( 86400, RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => '1440' ), 'USD' )['config']['max_timer_seconds'] ); + foreach ( array( '0', '-5', 'abc', '1.5' ) as $bad ) { + $r = RuleConfig::sanitize( 'add_time', $base + array( 'max_timer_minutes' => $bad ), 'USD' ); + $this->assertNotEmpty( $r['errors'], $bad ); + $this->assertNull( $r['config'] ); + } + $this->assertSame( 'Adds 1 minute for every $1.00, up to 1 day on the clock', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 86400 ), 'USD' ) ); + $this->assertSame( 'Adds 1 minute for every $1.00', RuleConfig::summary( 'add_time', array( 'seconds_per_unit' => 60, 'unit_minor' => 100 ), 'USD' ) ); + $this->assertSame( array( 'Timer: +25 minutes (the timer never goes above 1 hour)' ), RuleConfig::preview( array( array( 'type' => 'add_time', 'config' => array( 'seconds_per_unit' => 60, 'unit_minor' => 100, 'max_timer_seconds' => 3600 ) ) ), 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' ); + $cfg = array( 'seconds_per_unit' => 120, 'unit_minor' => 250, 'cap_seconds_per_donation' => 600, 'max_total_seconds' => null, 'max_timer_seconds' => 86400, 'basis' => 'base' ); $form = RuleConfig::toForm( 'add_time', $cfg, 'USD' ); $back = RuleConfig::sanitize( 'add_time', $form, 'USD' ); $this->assertSame( $cfg, $back['config'] ); diff --git a/tests/Unit/ClientIpTest.php b/tests/Unit/ClientIpTest.php new file mode 100644 index 0000000..6721e29 --- /dev/null +++ b/tests/Unit/ClientIpTest.php @@ -0,0 +1,59 @@ + self::CLIENT, 'HTTP_CF_CONNECTING_IP' => '1.2.3.4', 'HTTP_X_FORWARDED_FOR' => '5.6.7.8' ); + $this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_DIRECT ) ); + $this->assertSame( self::CLIENT, ClientIp::resolve( $srv ) ); + } + + public function test_cloudflare_mode_uses_cf_header(): void { + $srv = array( 'REMOTE_ADDR' => self::PROXY, 'HTTP_CF_CONNECTING_IP' => self::CLIENT ); + $this->assertSame( self::CLIENT, ClientIp::resolve( $srv, ClientIp::MODE_CLOUDFLARE ) ); + } + + public function test_cloudflare_mode_without_header_falls_back_to_remote_addr(): void { + $this->assertSame( self::PROXY, ClientIp::resolve( array( 'REMOTE_ADDR' => self::PROXY ), ClientIp::MODE_CLOUDFLARE ) ); + } + + public function test_invalid_header_values_are_ignored(): void { + foreach ( array( 'not-an-ip', '999.1.1.1', '', '1.2.3.4, 5.6.7.8', '