diff --git a/add-ons/super-forms-calculator/assets/js/frontend/calculator.js b/add-ons/super-forms-calculator/assets/js/frontend/calculator.js index 60265bdd..d1ec8b86 100644 --- a/add-ons/super-forms-calculator/assets/js/frontend/calculator.js +++ b/add-ons/super-forms-calculator/assets/js/frontend/calculator.js @@ -187,7 +187,7 @@ // @since 1.5.0 - skip if parent column or element is hidden (conditionally hidden) if(typeof doNotSkip === 'undefined') { - if(SUPER.has_hidden_parent(target)){ + if(SUPER.has_hidden_parent(target, false, false)){ continue; } } @@ -388,7 +388,7 @@ } // Check if parent column or element is hidden (conditionally hidden) - if(SUPER.has_hidden_parent(element)){ + if(SUPER.has_hidden_parent(element, false, false)){ // Exclude conditionally // Lets just replace the field name with 0 as a value numericMath = target.dataset.superNumericMath.replace('{'+oldName+'}', 0); diff --git a/assets/js/common.js b/assets/js/common.js index 40bf4b1e..bb38b39d 100644 --- a/assets/js/common.js +++ b/assets/js/common.js @@ -1036,8 +1036,13 @@ function SUPERreCaptcha(){ } return value; }; - SUPER.has_hidden_parent = function(changedField, includeMultiParts){ + // includeInvisibleColumns (default true): a field inside an invisible column counts as hidden. + // Only validate_form relies on the default (the visitor can never see such an error); payload + // collection, conditional logic, math, tabbing and auto-step pass false to keep these fields. + SUPER.has_hidden_parent = function(changedField, includeMultiParts, includeInvisibleColumns){ + if(typeof includeInvisibleColumns === 'undefined') includeInvisibleColumns = true; if(changedField[0]) changedField = changedField[0]; + if(includeInvisibleColumns && changedField.parentNode && changedField.parentNode.closest('.super-invisible')) return true; var p, parent; parent = changedField.closest('.super-shortcode'); @@ -1899,7 +1904,7 @@ function SUPERreCaptcha(){ $continue = true; continue; } - $skip = SUPER.has_hidden_parent($shortcode_field); + $skip = SUPER.has_hidden_parent($shortcode_field, false, false); $parent = $shortcode_field.closest('.super-shortcode'); } if(v.and_method!==''){ @@ -1918,7 +1923,7 @@ function SUPERreCaptcha(){ $continue_and = true; continue; } - $skip_and = SUPER.has_hidden_parent($shortcode_field_and); + $skip_and = SUPER.has_hidden_parent($shortcode_field_and, false, false); $parent_and = $shortcode_field_and.closest('.super-shortcode'); } if(v.and_method==='or' && !$continue_and){ @@ -2799,7 +2804,7 @@ function SUPERreCaptcha(){ if($element){ if($element[0]) $element = $element[0]; // Check if parent column or element is hidden (conditionally hidden) - if( SUPER.has_hidden_parent($element) ) { + if( SUPER.has_hidden_parent($element, false, false) ) { // Exclude conditionally // Lets just replace the field name with 0 as a value args.value = args.value.replace('{'+$old_name+'}', $default_value); @@ -3963,7 +3968,7 @@ function SUPERreCaptcha(){ totalFields = 0; nodes = activeMultipart.querySelectorAll('.super-shortcode-field'); for (i = 0; i < nodes.length; ++i) { - if(!SUPER.has_hidden_parent(nodes[i])){ + if(!SUPER.has_hidden_parent(nodes[i], false, false)){ // Also exclude any hidden fields, because `has_hidden_parent()` doesn't check for this if(nodes[i].type=='hidden'){ if(nodes[i].closest('.super-shortcode').classList.contains('super-hidden')){ @@ -3976,7 +3981,7 @@ function SUPERreCaptcha(){ counter = 1; nodes = activeMultipart.querySelectorAll('.super-shortcode-field'); for (i = 0; i < nodes.length; ++i) { - if(!SUPER.has_hidden_parent(nodes[i])){ + if(!SUPER.has_hidden_parent(nodes[i], false, false)){ if(totalFields==counter){ if(nodes[i].name==args.el.name){ setTimeout(function (){ @@ -4300,7 +4305,7 @@ function SUPERreCaptcha(){ // Only Super Forms hiding excludes a field: conditional logic (the same rule validation // uses) and the hide-on-mobile column settings. A column hidden by theme/custom CSS // is submitted like a visible one (D1); the server enforces those fields. - $hidden = ($parent.length>0 && SUPER.has_hidden_parent($this[0])) || $this.parents('.super-hide-mobile, .super-hide-mobile-window').filter(function(){ + $hidden = ($parent.length>0 && SUPER.has_hidden_parent($this[0], false, false)) || $this.parents('.super-hide-mobile, .super-hide-mobile-window').filter(function(){ return $(this).css('display')=='none'; }).length>0; diff --git a/assets/js/frontend/elements.js b/assets/js/frontend/elements.js index 5358d102..f1292e4b 100644 --- a/assets/js/frontend/elements.js +++ b/assets/js/frontend/elements.js @@ -98,9 +98,9 @@ for( i = 0; i < nodes.length; i++ ) { field = nodes[i].querySelector('.super-shortcode-field'); if(field){ // This is a field - if(!SUPER.has_hidden_parent(field)) skip = false; + if(!SUPER.has_hidden_parent(field, false, false)) skip = false; }else{ // This is either a HTML element or something else without a field - if(!SUPER.has_hidden_parent(nodes[i])) skip = false; + if(!SUPER.has_hidden_parent(nodes[i], false, false)) skip = false; } if(skip===false) return false; } @@ -194,7 +194,7 @@ } } } - if(SUPER.has_hidden_parent(nextField)){ + if(SUPER.has_hidden_parent(nextField, false, false)){ // Exclude conditionally nextField = SUPER.nextTabField(e, field, form, nextTabIndex+incNext); } @@ -1391,7 +1391,7 @@ // the form became focus via regular tab, so we must focus the first field nodes = form.querySelectorAll('.super-field:not('+super_common_i18n.tab_index_exclusion+')'); for (i = 0; i < nodes.length; i++) { - if(SUPER.has_hidden_parent(nodes[i])) continue; + if(SUPER.has_hidden_parent(nodes[i], false, false)) continue; visibleNodes.push(nodes[i]); break; } @@ -1407,7 +1407,7 @@ // the form became focus via shift+tab, so we must focus the last field nodes = form.querySelectorAll('.super-field:not('+super_common_i18n.tab_index_exclusion+')'); for (i = 0; i < nodes.length; i++) { - if(SUPER.has_hidden_parent(nodes[i])) continue; + if(SUPER.has_hidden_parent(nodes[i], false, false)) continue; visibleNodes.push(nodes[i]); } field = visibleNodes[visibleNodes.length-1]; @@ -1711,7 +1711,7 @@ nodes = document.querySelectorAll('.super-form .super-tabs-contents'); for (i = 0; i < nodes.length; i++) { field = nodes[i].closest('.super-shortcode'); - if(!SUPER.has_hidden_parent(field, true)){ // Also include Multi-part for this check + if(!SUPER.has_hidden_parent(field, true, false)){ // Also include Multi-part for this check // Only if no focussed field is found // First get the currently active TAB var activeTab = field.querySelector('.super-tabs-contents > .super-tabs-content.super-active'); @@ -1745,7 +1745,7 @@ nodes = form.querySelectorAll('.super-field:not('+super_common_i18n.tab_index_exclusion+')'); var visibleNodes = []; for (i = 0; i < nodes.length; i++) { - if(SUPER.has_hidden_parent(nodes[i])) continue; + if(SUPER.has_hidden_parent(nodes[i], false, false)) continue; visibleNodes.push(nodes[i]); } // if we shift+tab from second visible field to first visible field, we must set tabindex on form to -1 @@ -1795,7 +1795,7 @@ SUPER.firstFocussedField = true; nodes = form.querySelectorAll('.super-field:not('+super_common_i18n.tab_index_exclusion+')'); for (i = 0; i < nodes.length; i++) { - if(SUPER.has_hidden_parent(nodes[i])) continue; + if(SUPER.has_hidden_parent(nodes[i], false, false)) continue; SUPER.focusNextTabField(e, nodes[i], form, nodes[i]); e.preventDefault(); return false; diff --git a/docs/changelog.md b/docs/changelog.md index a89f0e5f..1890d7cc 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -10,6 +10,7 @@ ## Unreleased +- **Fix:** A required or validated field inside a column set to Invisible no longer blocks the form with an error the visitor cannot see; the field's value is still submitted, and the server no longer requires it either. - **Fix:** Pressing Enter in a field no longer submits the form when the submit button is hidden by conditional logic. If another submit button is visible, that one is used. - **Fix:** In a multi-part form, pressing Enter in a field of any step except the last now does the same as clicking that step's Next button (including the step's validation) instead of submitting the whole form and skipping the remaining steps. If that Next button is hidden by conditional logic, or the step has none, Enter does nothing. On the last step Enter submits the form as before. - **Security fix:** The form builder's preview, language switch, undo/redo, element settings and element HTML requests now require an administrator and a valid security token, so other logged-in users can no longer load form markup or settings. diff --git a/includes/class-ajax.php b/includes/class-ajax.php index 39373923..9256be38 100644 --- a/includes/class-ajax.php +++ b/includes/class-ajax.php @@ -3679,6 +3679,10 @@ private static function collect_required_fields( $elements, $ctx = null ) { foreach( $elements as $element ) { $edata = ( isset( $element['data'] ) && is_array( $element['data'] ) ) ? $element['data'] : array(); $tag = isset( $element['tag'] ) ? $element['tag'] : ''; + // An invisible column hides its whole subtree from browser validation: common.js + // has_hidden_parent() defaults includeInvisibleColumns to true and validate_form skips + // such fields, while the payload still submits them. Never enroll them as required. + if( $tag === 'column' && isset( $edata['invisible'] ) && $edata['invisible'] === 'true' ) continue; // An element (or ancestor) that can hide/repeat its subtree "locks" the fields below // it: the front-end may legitimately omit them, so they can never be presence-enforced. // Conditional logic is not evaluable server-side; repeaters vary per diff --git a/tests/test-invisible-column-client.cjs b/tests/test-invisible-column-client.cjs new file mode 100644 index 00000000..12d49a2b --- /dev/null +++ b/tests/test-invisible-column-client.cjs @@ -0,0 +1,147 @@ +// A required/validated field inside an invisible column can never show its error to the visitor, +// so browser validation must skip it (like 6.4), while the payload keeps submitting it. +// Executes the shipped common.js validate_form/has_hidden_parent against a minimal DOM. +const {test} = require('node:test'); +const assert = require('node:assert/strict'); +const fs = require('node:fs'); +const path = require('node:path'); +const vm = require('node:vm'); +const root = path.join(__dirname, '..'); +const pick = rel => fs.existsSync(path.join(root, 'src', rel)) ? path.join(root, 'src', rel) : path.join(root, rel); +const clientSource = pick('assets/js/common.js'); + +// Minimal element: compound selectors of .class, :not(.class) and [attr="value"], comma lists. +function matchesCompound(el, sel) { + const re = /:not\(\.([\w-]+)\)|\.([\w-]+)|\[([\w-]+)="([^"]*)"\]/g; + let m, ok = true; + while ((m = re.exec(sel)) !== null) { + if (m[1]) ok = ok && !el.classList.contains(m[1]); + else if (m[2]) ok = ok && el.classList.contains(m[2]); + else { + const v = m[3].startsWith('data-') ? el.dataset[m[3].slice(5).replace(/-([a-z])/g, (_, l) => l.toUpperCase())] : el[m[3]]; + ok = ok && v === m[4]; + } + } + return ok; +} +const matches = (el, selector) => selector.split(',').some(s => matchesCompound(el, s.trim())); +class El { + constructor(classes, props = {}) { + this.classList = new Set(classes.split(' ').filter(Boolean)); + this.classList.contains = this.classList.has; + this.classList.add = c => Set.prototype.add.call(this.classList, c); + this.classList.remove = c => Set.prototype.delete.call(this.classList, c); + this.dataset = {}; this.style = {}; this.children = []; this.parentElement = null; + Object.assign(this, props); + } + get parentNode() { return this.parentElement; } + append(...kids) { for (const k of kids) { k.parentElement = this; this.children.push(k); } return this; } + closest(sel) { for (let n = this; n; n = n.parentElement) if (matches(n, sel)) return n; return null; } + querySelectorAll(sel) { + const out = []; + const walk = n => { for (const c of n.children) { if (matches(c, sel)) out.push(c); walk(c); } }; + walk(this); + return out; + } + querySelector(sel) { return this.querySelectorAll(sel)[0] || null; } +} + +function client() { + const chain = new Proxy({}, {get: (_, key) => key === 'length' ? 0 : () => chain}); + const jq = () => chain; + jq.extend = Object.assign; + jq.ajax = () => { throw Error('Unexpected network'); }; + function Element() {} + function CharacterData() {} + function DocumentType() {} + const ctx = {SUPER: {}, jQuery: jq, Element, CharacterData, DocumentType, console, Promise, + document: {documentElement: {classList: {contains: () => false}}}, + super_common_i18n: {ajaxurl: '/no-network'}, setTimeout: () => 0, clearTimeout: () => {}}; + ctx.window = ctx; + vm.runInNewContext(fs.readFileSync(clientSource, 'utf8'), ctx); + return ctx.SUPER; +} + +// form > column[.super-invisible?] > shortcode wrapper > .super-field > input (empty, required) +function form(invisible, nested = false) { + const input = new El('super-shortcode-field', {name: 'amount', value: '', type: 'text'}); + input.dataset.validation = 'empty'; + const wrapper = new El('super-shortcode super-field super-text').append(new El('super-field-wrapper').append(input)); + let column = new El('super-shortcode super-column' + (invisible ? ' super-invisible' : '')).append(wrapper); + if (nested) column = new El('super-shortcode super-column super-invisible').append(column); + const f = new El('super-form').append(column); + return {form: f, input}; +} + +function validate(S, f) { + const validated = []; + let scrolledToError = false; + Object.assign(S, { + resetFocussedFields() {}, conditional_logic() {}, before_validating_form_hook() {}, + before_submit_button_click_hook: () => false, after_validating_form_hook() {}, + handle_validations: args => { validated.push(args.el.name); return args.el.value === ''; }, + scrollToError: () => { scrolledToError = true; } + }); + const blocked = S.validate_form({form: f, submitButton: new El('super-form-button'), validateMultipart: true}) !== true; + return {blocked, validated, scrolledToError}; +} + +test('empty validated field in a visible column still blocks validation', () => { + const r = validate(client(), form(false).form); + assert.deepEqual(r.validated, ['amount']); + assert.equal(r.blocked, true); + assert.equal(r.scrolledToError, true); +}); + +test('empty validated field in an invisible column no longer blocks validation', () => { + for (const nested of [false, true]) { + const r = validate(client(), form(!nested, nested).form); + assert.deepEqual(r.validated, [], 'nested=' + nested); + assert.equal(r.blocked, false, 'nested=' + nested); + assert.equal(r.scrolledToError, false, 'nested=' + nested); + } +}); + +test('has_hidden_parent: invisible column counts as hidden only when asked (default yes)', () => { + const S = client(); + const {input} = form(true); + assert.equal(S.has_hidden_parent(input), true); + assert.equal(S.has_hidden_parent(input, false), true); + assert.equal(S.has_hidden_parent(input, false, true), true); + assert.equal(S.has_hidden_parent(input, false, false), false, 'payload/conditions keep invisible-column fields'); + assert.equal(S.has_hidden_parent(form(false).input), false); + // Conditional hiding is unaffected by the new argument. + const hidden = form(false); + const col = hidden.input.closest('.super-column'); + col.dataset.conditionalAction = 'show'; + assert.equal(S.has_hidden_parent(hidden.input, false, false), true); +}); + +// Every caller except validate_form must keep today's behaviour (invisible-column fields are +// still submitted, counted by conditional logic/math, tabbed to, auto-stepped, calculated). +test('only validate_form relies on the invisible-column default', () => { + const files = ['assets/js/common.js', 'assets/js/frontend/elements.js', 'add-ons/super-forms-calculator/assets/js/frontend/calculator.js'].map(pick); + const relying = []; + for (const file of files) { + const src = fs.readFileSync(file, 'utf8'); + const vStart = src.indexOf('SUPER.validate_form = function'), vEnd = src.indexOf('SUPER.scrollToError = function'); + const re = /SUPER\.has_hidden_parent\(/g; + let m; + while ((m = re.exec(src)) !== null) { + if (src.slice(m.index, m.index + 40).startsWith('SUPER.has_hidden_parent = ')) continue; + let depth = 1, i = re.lastIndex, args = ['']; + for (; depth > 0; i++) { + const ch = src[i]; + if (ch === '(') depth++; + if (ch === ')' && --depth === 0) break; + if (ch === ',' && depth === 1) args.push(''); else args[args.length - 1] += ch; + } + const line = src.slice(0, m.index).split('\n').length; + if (args.length < 3 || args[2].trim() !== 'false') { + relying.push(path.relative(root, file) + ':' + line + (file === clientSource && m.index > vStart && m.index < vEnd ? ' (validate_form)' : '')); + } + } + } + assert.equal(relying.length, 1, relying.join('\n')); + assert.match(relying[0], /\(validate_form\)$/); +}); diff --git a/tests/test-security-required-fields-invisible-column.php b/tests/test-security-required-fields-invisible-column.php new file mode 100644 index 00000000..48b53d60 --- /dev/null +++ b/tests/test-security-required-fields-invisible-column.php @@ -0,0 +1,60 @@ +setAccessible( true ); + return $method->invoke( null, $elements ); + } + + private function field( $data = array(), $tag = 'text' ) { + return array( 'tag' => $tag, 'data' => array_merge( array( 'name' => 'amount', 'validation' => 'numeric' ), $data ) ); + } + + private function column( $inner, $invisible ) { + return array( 'tag' => 'column', 'data' => array( 'size' => '1/1', 'invisible' => $invisible ), 'inner' => $inner ); + } + + public function test_validated_field_in_invisible_column_is_not_required() { + $this->assertArrayNotHasKey( 'amount', $this->collect( array( $this->column( array( $this->field() ), 'true' ) ) ) ); + $this->assertArrayNotHasKey( 'amount', $this->collect( array( $this->column( array( $this->field( array( 'validation' => 'email' ) ) ), 'true' ) ) ) ); + } + + public function test_validated_field_in_visible_column_is_required() { + $required = $this->collect( array( $this->column( array( $this->field() ), '' ) ) ); + $this->assertArrayHasKey( 'amount', $required ); + $this->assertTrue( $required['amount']['always_present'] ); + } + + public function test_visible_column_nested_in_invisible_column_is_not_required() { + $elements = array( $this->column( array( $this->column( array( $this->field() ), '' ) ), 'true' ) ); + $this->assertArrayNotHasKey( 'amount', $this->collect( $elements ) ); + } + + public function test_hidden_field_is_not_required() { + $this->assertArrayNotHasKey( 'amount', $this->collect( array( $this->field( array( 'validation' => 'none' ), 'hidden' ) ) ) ); + $this->assertArrayNotHasKey( 'amount', $this->collect( array( $this->column( array( $this->field( array(), 'hidden' ) ), '' ) ) ) ); + } + + public function test_may_be_empty_settings_are_unchanged() { + foreach( array( 'true', 'conditions' ) as $may_be_empty ) { + $this->assertArrayNotHasKey( 'amount', $this->collect( array( $this->column( array( $this->field( array( 'may_be_empty' => $may_be_empty ) ) ), '' ) ) ), $may_be_empty ); + } + $required = $this->collect( array( $this->column( array( $this->field( array( 'may_be_empty' => 'false' ) ) ), '' ) ) ); + $this->assertTrue( $required['amount']['always_present'] ); + } +}