diff --git a/classes/factories/FrmCaptchaFactory.php b/classes/factories/FrmCaptchaFactory.php index b20aa33421..5d6901acac 100644 --- a/classes/factories/FrmCaptchaFactory.php +++ b/classes/factories/FrmCaptchaFactory.php @@ -13,7 +13,7 @@ class FrmCaptchaFactory { * * @since 6.8.4 * - * @param string $captcha_type Either 'active', 'recaptcha', 'hcaptcha' or 'turnstile'. If active, the global setting will be used. + * @param string $captcha_type Either 'active', 'recaptcha', 'hcaptcha', 'turnstile' or 'infopeak'. If active, the global setting will be used. * * @return FrmFieldCaptchaSettings */ @@ -41,6 +41,7 @@ private static function get_settings_class( $active_captcha ) { 'recaptcha' => 'FrmRecaptchaSettings', 'hcaptcha' => 'FrmHcaptchaSettings', 'turnstile' => 'FrmTurnstileSettings', + 'infopeak' => 'FrmInfopeakSettings', ); if ( ! isset( $settings_classes[ $active_captcha ] ) ) { diff --git a/classes/models/FrmInfopeakSettings.php b/classes/models/FrmInfopeakSettings.php new file mode 100644 index 0000000000..9591c19a13 --- /dev/null +++ b/classes/models/FrmInfopeakSettings.php @@ -0,0 +1,135 @@ +endpoint = 'https://captcha.infopeak.io/siteverify'; + } + + /** + * @since x.x + * + * @return string + */ + public function get_name() { + return 'InfoPeak Captcha'; + } + + /** + * @since x.x + * + * @return string + */ + public function get_element_class_name() { + return 'infopeak-captcha'; + } + + /** + * @since x.x + * + * @return string + */ + public function get_documentation_url() { + return 'https://accounts.infopeak.io/signup?plan=captcha'; + } + + /** + * InfoPeak Captcha global settings are saved as infopeak_pubkey and infopeak_privkey. + * + * @since x.x + * + * @return string + */ + public function get_settings_prefix() { + return 'infopeak_'; + } + + /** + * @since x.x + * + * @return string + */ + public function get_site_key_tooltip() { + return __( + 'InfoPeak Captcha is an EU-hosted captcha without cookies or image puzzles. The visitor\'s browser solves a small proof-of-work challenge while the form is filled in.', + 'formidable' + ); + } + + /** + * The widget has a single size and theme, so the data-size and data-theme attributes are not used. + * + * @since x.x + * + * @param array $attributes + * @param array $field + * + * @return array + */ + public function add_front_end_element_attributes( $attributes, $field ) { + return $attributes; + } + + /** + * @since x.x + * + * @return bool + */ + public function should_show_captcha_size() { + return false; + } + + /** + * @since x.x + * + * @return bool + */ + public function should_show_captcha_theme() { + return false; + } + + /** + * Add the error codes that are specific to InfoPeak Captcha. + * + * @since x.x + * + * @return array + */ + public function get_error_code_messages() { + return array_merge( + parent::get_error_code_messages(), + array( + 'quota-exceeded' => __( 'The monthly verification quota for this InfoPeak Captcha site key is used up.', 'formidable' ), + ) + ); + } + + /** + * A used up quota cannot be fixed by the person filling out the form. + * + * @since x.x + * + * @return array + */ + public function get_configuration_error_codes() { + return array_merge( + parent::get_configuration_error_codes(), + array( + 'quota-exceeded', + ) + ); + } +} diff --git a/classes/models/FrmSettings.php b/classes/models/FrmSettings.php index 1986d6083e..e50a6d814d 100644 --- a/classes/models/FrmSettings.php +++ b/classes/models/FrmSettings.php @@ -158,6 +158,24 @@ class FrmSettings { */ public $turnstile_privkey; + /** + * Settings for InfoPeak Captcha. + */ + + /** + * @since x.x + * + * @var string + */ + public $infopeak_pubkey; + + /** + * @since x.x + * + * @var string|null + */ + public $infopeak_privkey; + /** * @var bool */ @@ -476,6 +494,10 @@ private function fill_captcha_settings() { $this->turnstile_privkey = ''; } + if ( ! isset( $this->infopeak_privkey ) ) { + $this->infopeak_privkey = ''; + } + if ( ! isset( $this->pubkey ) ) { // Get the options from the database. $recaptcha_opt = is_multisite() ? get_site_option( 'recaptcha' ) : get_option( 'recaptcha' ); @@ -519,6 +541,7 @@ private function set_supported_captcha() { 'recaptcha' => '', 'hcaptcha' => 'hcaptcha_', 'turnstile' => 'turnstile_', + 'infopeak' => 'infopeak_', ); if ( array_key_exists( $this->active_captcha, $prefixes ) ) { @@ -648,6 +671,8 @@ private function update_settings( $params ) { $this->hcaptcha_privkey = trim( $params['frm_hcaptcha_privkey'] ); $this->turnstile_pubkey = trim( $params['frm_turnstile_pubkey'] ); $this->turnstile_privkey = trim( $params['frm_turnstile_privkey'] ); + $this->infopeak_pubkey = trim( $params['frm_infopeak_pubkey'] ); + $this->infopeak_privkey = trim( $params['frm_infopeak_privkey'] ); $this->load_style = $params['frm_load_style']; $this->custom_css = $params['frm_custom_css']; $this->default_email = $params['frm_default_email']; diff --git a/classes/models/fields/FrmFieldCaptcha.php b/classes/models/fields/FrmFieldCaptcha.php index 2ef0bf68d8..1c54a77a51 100644 --- a/classes/models/fields/FrmFieldCaptcha.php +++ b/classes/models/fields/FrmFieldCaptcha.php @@ -221,6 +221,10 @@ protected function api_url() { return $this->hcaptcha_api_url(); } + if ( 'infopeak' === $active_mode ) { + return $this->infopeak_api_url(); + } + return $this->turnstile_api_url(); } @@ -305,6 +309,25 @@ protected function turnstile_api_url() { ); } + /** + * The InfoPeak Captcha script renders every .infopeak-captcha element on the page. + * It also renders new elements when it runs again, which happens when a form page is loaded with AJAX. + * + * @since x.x + * + * @return string + */ + protected function infopeak_api_url() { + /** + * Allows updating the InfoPeak Captcha js api url. + * + * @since x.x + * + * @param string $api_js_url + */ + return apply_filters( 'frm_infopeak_js_url', 'https://captcha.infopeak.io/infopeak-captcha.js' ); + } + /** * @param FrmSettings $frm_settings * diff --git a/classes/views/frm-settings/captcha/captcha.php b/classes/views/frm-settings/captcha/captcha.php index 29970d3dc3..61f9493180 100644 --- a/classes/views/frm-settings/captcha/captcha.php +++ b/classes/views/frm-settings/captcha/captcha.php @@ -8,21 +8,26 @@

- active_captcha, 'recaptcha' ); ?> /> + active_captcha, 'recaptcha' ); ?> /> - active_captcha, 'hcaptcha' ); ?> /> + active_captcha, 'hcaptcha' ); ?> /> - active_captcha, 'turnstile' ); ?> /> + active_captcha, 'turnstile' ); ?> /> + active_captcha, 'infopeak' ); ?> /> +
@@ -151,6 +156,30 @@
+ 'infopeak_settings', + 'role' => 'tabpanel', + 'aria-labelledby' => 'frm-infopeak-tab', +); + +if ( 'infopeak' !== $frm_settings->active_captcha ) { + $captcha_settings_attrs['class'] = 'frm_hidden'; +} +?> +> + +
+ +
+ + +

spam_handling ); diff --git a/images/infopeak.png b/images/infopeak.png new file mode 100644 index 0000000000..af0ca3c03c Binary files /dev/null and b/images/infopeak.png differ diff --git a/js/formidable.js b/js/formidable.js index 429d4f8029..12480272c8 100644 --- a/js/formidable.js +++ b/js/formidable.js @@ -1389,6 +1389,11 @@ function frmFrontFormJS() { ); } + // InfoPeak Captcha tokens can only be used once, so get a new one for the next submit. + if ( window.infopeakCaptcha ) { + object.querySelectorAll( '.infopeak-captcha' ).forEach( captchaEl => window.infopeakCaptcha.reset( captchaEl ) ); + } + jQuery( document ).trigger( 'frmFormErrors', [ object, response ] ); fieldsets.forEach( field => field.classList.remove( 'frm_doing_ajax' ) ); diff --git a/js/formidable.min.js b/js/formidable.min.js index bab3dc0235..7480741e7b 100644 --- a/js/formidable.min.js +++ b/js/formidable.min.js @@ -43,33 +43,34 @@ formID);const delay=maybeSlideOut(replaceContent,response.content);setTimeout(fu "";const tempDiv=document.createElement("div");tempDiv.innerHTML=response.content;const formReturnedInput=tempDiv.querySelector('input[name="form_id"]');const formReturned=formReturnedInput?formReturnedInput.value:"";frmThemeOverride_frmAfterSubmit(formReturned,pageOrder,response.content,object)}afterFormSubmitted(object,response)},delay)}else if(response.errors!==undefined&&Object.keys(response.errors).length){removeSubmitLoading(jQuery(object),"enable");let contSubmit=true;removeAllErrors();let $fieldCont= null;const formErrors={};for(const key in response.errors){const fieldContEl=object.querySelector(`#frm_field_${key}_container`);$fieldCont=fieldContEl?jQuery(fieldContEl):jQuery();if(!fieldContEl&&isFormLevelErrorKey(key)){formErrors[key]=response.errors[key];contSubmit=false;continue}if($fieldCont.length){if(!$fieldCont.is(":visible")){const inCollapsedSection=$fieldCont.closest(".frm_toggle_container");if(inCollapsedSection.length){let frmTrigger=inCollapsedSection.prev();if(!frmTrigger.hasClass("frm_trigger"))frmTrigger= frmTrigger.prev(".frm_trigger");frmTrigger.trigger("click")}}if($fieldCont.is(":visible")){addFieldError($fieldCont,key,response.errors);contSubmit=false}}}object.querySelectorAll(".frm-g-recaptcha, .g-recaptcha, .h-captcha").forEach(function(captchaEl){const recaptchaID=captchaEl.dataset.rid;if(typeof grecaptcha!=="undefined"&&grecaptcha)if(recaptchaID)grecaptcha.reset(recaptchaID);else grecaptcha.reset();if(typeof hcaptcha!=="undefined"&&hcaptcha)hcaptcha.reset()});if(window.turnstile)object.querySelectorAll(".frm-cf-turnstile").forEach(turnstileField=> -turnstileField.dataset.rid&&turnstile.reset(turnstileField.dataset.rid));jQuery(document).trigger("frmFormErrors",[object,response]);fieldsets.forEach(field=>field.classList.remove("frm_doing_ajax"));scrollToFirstField(object);if(contSubmit)object.submit();else{if(response.error_message)object.insertAdjacentHTML("afterbegin",response.error_message);addFormLevelErrors(object,formErrors);if(Object.keys(formErrors).length){const errorSummary=object.querySelector("[data-frm-error-summary]");if(errorSummary)frmFrontForm.scrollMsg(jQuery(errorSummary), -object,true)}checkForErrorsAndMaybeSetFocus()}}else if(!willRedirect){showFileLoading(object);object.submit()}};const error=function(){object.querySelectorAll('input[type="submit"], input[type="button"]').forEach(button=>button.disabled=false);object.submit()};postToAjaxUrl(object,data,success,error)}function isFormLevelErrorKey(key){return!/^\d/.test(key)}function addFormLevelErrors(form,formErrors){const summary=form.querySelector("[data-frm-error-summary]");if(!summary)return;Object.keys(formErrors).forEach(key=> -{summary.insertAdjacentHTML("beforeend",`
${formErrors[key]}
`)})}function postToAjaxUrl(form,data,success,error){let ajaxUrl=frm_js.ajax_url;const action=form.getAttribute("action");if("string"===typeof action&&action.includes("?action=frm_forms_preview"))ajaxUrl=action.split("?action=frm_forms_preview")[0];const ajaxParams={type:"POST",url:ajaxUrl,data,success};if("function"===typeof error)ajaxParams.error=error;jQuery.ajax(ajaxParams)}function focusFormMessage(insertedContent){let message; -for(const node of insertedContent.get()){if(node.nodeType!==1)continue;message=node.matches(".frm_message")?node:node.querySelector(".frm_message");if(message)break}if(message)focusInput(message)}function afterFormSubmitted(object,response){const tempDiv=document.createElement("div");tempDiv.innerHTML=response.content;const formCompleted=tempDiv.querySelector(".frm_message");if(formCompleted)jQuery(document).trigger("frmFormComplete",[object,response]);else jQuery(document).trigger("frmPageChanged", -[object,response])}function afterFormSubmittedBeforeReplace(object,response){const tempDiv=document.createElement("div");tempDiv.innerHTML=response.content;const formCompleted=tempDiv.querySelector(".frm_message");if(formCompleted)triggerCustomEvent(document,"frmFormCompleteBeforeReplace",{object,response})}function removeAddedScripts(formContainer,formID){const endReplace=document.querySelectorAll(`.frm_end_ajax_${formID}`);if(endReplace.length){formContainer.nextUntil(`.frm_end_ajax_${formID}`).remove(); -endReplace.forEach(el=>el.remove())}}function maybeSlideOut(oldContent,newContent){let c;let newClass="frm_slideout";if(newContent.includes(" frm_slide")){c=oldContent.children();if(newContent.includes(" frm_going_back"))newClass+=" frm_going_back";c.removeClass("frm_going_back");c.addClass(newClass);return 300}return 0}function addUrlParam(response){let url;if(history.pushState&&response.page!==undefined){url=addQueryVar("frm_page",response.page);window.history.pushState({html:response.html},"", -`?${url}`)}}function addQueryVar(key,value){key=encodeURI(key);value=encodeURI(value);const kvp=document.location.search.substr(1).split("&");let i=kvp.length;while(i--){const x=kvp[i].split("=");if(x[0]==key){x[1]=value;kvp[i]=x.join("=");break}}if(i<0)kvp[kvp.length]=[key,value].join("=");return kvp.join("&")}function getErrorConfigForForm(formEl){const fallback={includeAlertRole:!!frm_js.include_alert_role,focusFirstError:!!frm_js.focus_first_error,focusErrorSummary:false};if(!formEl||!formEl.dataset.frmErrorConfig)return fallback; -if(!formEl.frmErrorConfigCache)try{formEl.frmErrorConfigCache=JSON.parse(formEl.dataset.frmErrorConfig)}catch(e){formEl.frmErrorConfigCache=fallback}return formEl.frmErrorConfigCache}function insertErrorHtml(container,errorHtml){const template=document.createElement("template");template.innerHTML=errorHtml;Array.from(template.content.children).forEach(el=>el.setAttribute("data-frm-error",""));container.append(template.content)}function addFieldError($fieldCont,key,jsErrors){const container=$fieldCont instanceof -jQuery?$fieldCont.get(0):$fieldCont;if(!container||container.offsetParent===null)return;container.classList.add("frm_blank_field");const allInputs=container.querySelectorAll("input, select, textarea");const htmlId="string"===typeof jsErrors[key]&&jsErrors[key].includes("!hasClass(input,"frm_optional")||input.closest(".frm_form_field")===container); -let describedBy;if(typeof frmThemeOverride_frmPlaceError==="function")frmThemeOverride_frmPlaceError(key,jsErrors);else if(""===jsErrors[key]);else{let errorHtml;if(jsErrors[key].includes("${jsErrors[key]}`}insertErrorHtml(container,errorHtml);inputs.forEach(input=>{describedBy= -input.getAttribute("aria-describedby");if(!describedBy)describedBy=id;else if(!describedBy.includes(id)&&!describedBy.includes("frm_error_field_")){const {errorFirst}=input.dataset;if(errorFirst==="0")describedBy=`${describedBy} ${id}`;else describedBy=`${id} ${describedBy}`}input.setAttribute("aria-describedby",describedBy)})}inputs.forEach(input=>{if(["radio","checkbox"].includes(input.type)){const group=input.closest('[role="radiogroup"], [role="group"]');if(group)group.setAttribute("aria-invalid", -"true")}else input.setAttribute("aria-invalid","true")});jQuery(document).trigger("frmAddFieldError",[jQuery(container),key,jsErrors])}function getErrorElementId(key,input){if(isNaN(key)||!input||!input.id)return`frm_error_field_${key}`;return`frm_error_${input.id}`}function removeFieldError(fieldCont){const container=fieldCont instanceof jQuery?fieldCont.get(0):fieldCont;if(!container)return;const errorMessages=container.querySelectorAll(".frm_error, [data-frm-error]");const input=container.querySelector("input, select, textarea"); -container.classList.remove("frm_blank_field","has-error");if(input)if("true"===input.getAttribute("aria-invalid"))input.setAttribute("aria-invalid","false");else if(["radio","checkbox"].includes(input.type)){const group=input.closest('[role="radiogroup"], [role="group"]');if(group)group.setAttribute("aria-invalid","false")}errorMessages.forEach(errorMessage=>{removeElementFromInputDescribedBy(errorMessage);errorMessage.remove()})}function removeElementFromInputDescribedBy(el){document.querySelectorAll(`[aria-describedby*="${el.id}"]`).forEach(input=> -{let ariaDescribedBy=input.getAttribute("aria-describedby").split(" ");ariaDescribedBy=ariaDescribedBy.filter(value=>{const trimmedValue=value.trim();return trimmedValue&&trimmedValue!==el.id});if(ariaDescribedBy.length){input.setAttribute("aria-describedby",ariaDescribedBy.join(" "));return}input.removeAttribute("aria-describedby")})}function removeAllErrors(){document.querySelectorAll(".form-field").forEach(field=>{field.classList.remove("frm_blank_field","has-error")});document.querySelectorAll(".form-field .frm_error, .form-field [data-frm-error]").forEach(el=> -{removeElementFromInputDescribedBy(el);el.remove()});document.querySelectorAll(".frm_error_style").forEach(error=>error.remove())}function scrollToFirstField(object){if("function"===typeof object.get)object=object.get(0);const field=object.querySelector(".frm_blank_field");if(field)frmFrontForm.scrollMsg(jQuery(field),object,true)}function showSubmitLoading($object){showLoadingIndicator($object);disableSubmitButton($object);disableSaveDraft($object)}function showLoadingIndicator($object){if(!$object.hasClass("frm_loading_form")&& -!$object.hasClass("frm_loading_prev")){addLoadingClass($object);$object.trigger("frmStartFormLoading")}}function addLoadingClass($object){const loadingClass=isGoingToPrevPage($object)?"frm_loading_prev":"frm_loading_form";$object.addClass(loadingClass)}function isGoingToPrevPage($object){return typeof frmProForm!=="undefined"&&frmProForm.goingToPreviousPage($object)}function removeSubmitLoading(_,enable,processesRunning){if(processesRunning>0)return;document.querySelectorAll(".frm_loading_form").forEach(function(form){form.classList.remove("frm_loading_form", -"frm_loading_prev");jQuery(form).trigger("frmEndFormLoading");if(enable==="enable"){enableSubmitButton(form);enableSaveDraft(form)}})}function showFileLoading(object){const loading=document.getElementById("frm_loading");if(!loading)return;const fileInput=object.querySelector("input[type=file]");const fileval=fileInput?fileInput.value:"";if(fileval!=="")setTimeout(function(){jQuery(loading).fadeIn("slow")},2E3)}function confirmClick(){const message=this.dataset.frmconfirm;return confirm(message)}function onHoneypotFieldChange(){const css= -window.getComputedStyle(this).boxShadow;if(css?.match(/inset/))this.remove()}function changeFocusWhenClickComboFieldLabel(){let label;const comboInputsContainer=document.querySelectorAll(".frm_combo_inputs_container");comboInputsContainer.forEach(function(inputsContainer){if(!inputsContainer.closest(".frm_form_field"))return;label=inputsContainer.closest(".frm_form_field").querySelector(".frm_primary_label");if(!label)return;label.addEventListener("click",function(){inputsContainer.querySelector(".frm_form_field:first-child input, .frm_form_field:first-child select, .frm_form_field:first-child textarea").focus()})})} -function maybeFocusOnComboSubField(element){if("FIELDSET"!==element.nodeName)return false;if(!element.querySelector(".frm_combo_inputs_container"))return false;const comboSubfield=element.querySelector('[aria-invalid="true"]');if(comboSubfield){focusInput(comboSubfield);return true}return false}function checkForErrorsAndMaybeSetFocus(){const errors=document.querySelectorAll(".frm_form_field .frm_error, .frm_form_field [data-frm-error]");if(!errors.length)return;const formContainer=errors[0].closest(".frm-show-form"); -const config=getErrorConfigForForm(formContainer);if(config.focusErrorSummary){const summary=formContainer?formContainer.querySelector("[data-frm-error-summary]"):null;if(summary){summary.focus();return}}if(!config.focusFirstError&&!config.focusErrorSummary)return;let element=errors[0];let timeoutCallback;do{element=element.previousSibling;if(!element)break;if(["input","select","textarea"].includes(element.nodeName.toLowerCase())){focusInput(element);break}if(maybeFocusOnComboSubField(element))break; -if(element.classList!==undefined){if(element.classList.contains("html-active"))timeoutCallback=function(){const textarea=element.querySelector("textarea");if(null!==textarea)textarea.focus()};else if(element.classList.contains("tmce-active"))timeoutCallback=function(){tinyMCE.activeEditor.focus()};else if(element.classList.contains("frm_opt_container")){const firstInput=element.querySelector("input");if(firstInput){focusInput(firstInput);break}}if("function"===typeof timeoutCallback){setTimeout(timeoutCallback, -0);break}}}while(element.previousSibling)}function focusInput(input){if(input.offsetParent!==null)input.focus();else triggerCustomEvent(document,"frmMaybeDelayFocus",{input})}function focusFieldFromErrorLink(event){const href=this.getAttribute("href");if(!href||!href.startsWith("#"))return;const container=document.getElementById(href.substring(1));if(!container)return;event.preventDefault();container.scrollIntoView({behavior:"smooth",block:"center"});const input=getFocusableInputInField(container); -if(input){focusInput(input);return}container.setAttribute("tabindex","-1");focusInput(container)}function getFocusableInputInField(container){const inputs=Array.from(container.querySelectorAll(FOCUSABLE_FIELD_SELECTOR)).filter(inputCanTakeFocus);if(!inputs.length)return null;const invalidInput=inputs.find(input=>"true"===input.getAttribute("aria-invalid"));if(invalidInput)return invalidInput;return inputs.find(fieldInputIsEmpty)||inputs[0]}function fieldInputIsEmpty(input){if("BUTTON"===input.nodeName|| -["button","checkbox","file","radio","submit"].includes(input.type))return false;return""===String(input.value||"").trim()}function inputCanTakeFocus(input){if(input.disabled||"hidden"===input.type)return false;const rect=input.getBoundingClientRect();if(!rect.width&&!rect.height)return false;return"hidden"!==getComputedStyle(input).visibility}function documentOn(event,selector,handler,options){if(options===undefined)options=false;document.addEventListener(event,function(e){let target;for(target=e.target;target&& -target!=this;target=target.parentNode)if(target.matches&&target.matches(selector)){handler.call(target,e);break}},options)}function initFloatingLabels(){const selector=".frm-show-form .frm_inside_container input, .frm-show-form .frm_inside_container select, .frm-show-form .frm_inside_container textarea";const floatClass="frm_label_float_top";const checkFloatLabel=function(input){const container=input.closest(".frm_inside_container");if(!container)return;const shouldFloatTop=input.value||document.activeElement=== -input;container.classList.toggle(floatClass,shouldFloatTop);if("SELECT"===input.tagName){const firstOpt=input.querySelector("option:first-child");if(shouldFloatTop){if(firstOpt.hasAttribute("data-label")){firstOpt.textContent=firstOpt.getAttribute("data-label");firstOpt.removeAttribute("data-label")}}else if(firstOpt.textContent){firstOpt.setAttribute("data-label",firstOpt.textContent);firstOpt.textContent=""}}};const checkDropdownLabel=function(){document.querySelectorAll(`.frm-show-form .frm_inside_container:not(.${floatClass}) select`).forEach(function(input){const firstOpt= -input.querySelector("option:first-child");if(firstOpt.textContent){firstOpt.setAttribute("data-label",firstOpt.textContent);firstOpt.textContent=""}})};["focus","blur","change"].forEach(function(eventName){documentOn(eventName,selector,function(event){checkFloatLabel(event.target)},true)});const runOnLoad=function(firstLoad){if(firstLoad&&document.activeElement&&["INPUT","SELECT","TEXTAREA"].includes(document.activeElement.tagName))checkFloatLabel(document.activeElement);else if(firstLoad)document.querySelectorAll(".frm_inside_container").forEach(function(container){const input= +turnstileField.dataset.rid&&turnstile.reset(turnstileField.dataset.rid));if(window.infopeakCaptcha)object.querySelectorAll(".infopeak-captcha").forEach(captchaEl=>window.infopeakCaptcha.reset(captchaEl));jQuery(document).trigger("frmFormErrors",[object,response]);fieldsets.forEach(field=>field.classList.remove("frm_doing_ajax"));scrollToFirstField(object);if(contSubmit)object.submit();else{if(response.error_message)object.insertAdjacentHTML("afterbegin",response.error_message);addFormLevelErrors(object, +formErrors);if(Object.keys(formErrors).length){const errorSummary=object.querySelector("[data-frm-error-summary]");if(errorSummary)frmFrontForm.scrollMsg(jQuery(errorSummary),object,true)}checkForErrorsAndMaybeSetFocus()}}else if(!willRedirect){showFileLoading(object);object.submit()}};const error=function(){object.querySelectorAll('input[type="submit"], input[type="button"]').forEach(button=>button.disabled=false);object.submit()};postToAjaxUrl(object,data,success,error)}function isFormLevelErrorKey(key){return!/^\d/.test(key)} +function addFormLevelErrors(form,formErrors){const summary=form.querySelector("[data-frm-error-summary]");if(!summary)return;Object.keys(formErrors).forEach(key=>{summary.insertAdjacentHTML("beforeend",`
${formErrors[key]}
`)})}function postToAjaxUrl(form,data,success,error){let ajaxUrl=frm_js.ajax_url;const action=form.getAttribute("action");if("string"===typeof action&&action.includes("?action=frm_forms_preview"))ajaxUrl=action.split("?action=frm_forms_preview")[0];const ajaxParams= +{type:"POST",url:ajaxUrl,data,success};if("function"===typeof error)ajaxParams.error=error;jQuery.ajax(ajaxParams)}function focusFormMessage(insertedContent){let message;for(const node of insertedContent.get()){if(node.nodeType!==1)continue;message=node.matches(".frm_message")?node:node.querySelector(".frm_message");if(message)break}if(message)focusInput(message)}function afterFormSubmitted(object,response){const tempDiv=document.createElement("div");tempDiv.innerHTML=response.content;const formCompleted= +tempDiv.querySelector(".frm_message");if(formCompleted)jQuery(document).trigger("frmFormComplete",[object,response]);else jQuery(document).trigger("frmPageChanged",[object,response])}function afterFormSubmittedBeforeReplace(object,response){const tempDiv=document.createElement("div");tempDiv.innerHTML=response.content;const formCompleted=tempDiv.querySelector(".frm_message");if(formCompleted)triggerCustomEvent(document,"frmFormCompleteBeforeReplace",{object,response})}function removeAddedScripts(formContainer, +formID){const endReplace=document.querySelectorAll(`.frm_end_ajax_${formID}`);if(endReplace.length){formContainer.nextUntil(`.frm_end_ajax_${formID}`).remove();endReplace.forEach(el=>el.remove())}}function maybeSlideOut(oldContent,newContent){let c;let newClass="frm_slideout";if(newContent.includes(" frm_slide")){c=oldContent.children();if(newContent.includes(" frm_going_back"))newClass+=" frm_going_back";c.removeClass("frm_going_back");c.addClass(newClass);return 300}return 0}function addUrlParam(response){let url; +if(history.pushState&&response.page!==undefined){url=addQueryVar("frm_page",response.page);window.history.pushState({html:response.html},"",`?${url}`)}}function addQueryVar(key,value){key=encodeURI(key);value=encodeURI(value);const kvp=document.location.search.substr(1).split("&");let i=kvp.length;while(i--){const x=kvp[i].split("=");if(x[0]==key){x[1]=value;kvp[i]=x.join("=");break}}if(i<0)kvp[kvp.length]=[key,value].join("=");return kvp.join("&")}function getErrorConfigForForm(formEl){const fallback= +{includeAlertRole:!!frm_js.include_alert_role,focusFirstError:!!frm_js.focus_first_error,focusErrorSummary:false};if(!formEl||!formEl.dataset.frmErrorConfig)return fallback;if(!formEl.frmErrorConfigCache)try{formEl.frmErrorConfigCache=JSON.parse(formEl.dataset.frmErrorConfig)}catch(e){formEl.frmErrorConfigCache=fallback}return formEl.frmErrorConfigCache}function insertErrorHtml(container,errorHtml){const template=document.createElement("template");template.innerHTML=errorHtml;Array.from(template.content.children).forEach(el=> +el.setAttribute("data-frm-error",""));container.append(template.content)}function addFieldError($fieldCont,key,jsErrors){const container=$fieldCont instanceof jQuery?$fieldCont.get(0):$fieldCont;if(!container||container.offsetParent===null)return;container.classList.add("frm_blank_field");const allInputs=container.querySelectorAll("input, select, textarea");const htmlId="string"===typeof jsErrors[key]&&jsErrors[key].includes("!hasClass(input,"frm_optional")||input.closest(".frm_form_field")===container);let describedBy;if(typeof frmThemeOverride_frmPlaceError==="function")frmThemeOverride_frmPlaceError(key,jsErrors);else if(""===jsErrors[key]);else{let errorHtml;if(jsErrors[key].includes("${jsErrors[key]}`}insertErrorHtml(container,errorHtml);inputs.forEach(input=>{describedBy=input.getAttribute("aria-describedby");if(!describedBy)describedBy=id;else if(!describedBy.includes(id)&&!describedBy.includes("frm_error_field_")){const {errorFirst}=input.dataset;if(errorFirst==="0")describedBy=`${describedBy} ${id}`;else describedBy=`${id} ${describedBy}`}input.setAttribute("aria-describedby",describedBy)})}inputs.forEach(input=> +{if(["radio","checkbox"].includes(input.type)){const group=input.closest('[role="radiogroup"], [role="group"]');if(group)group.setAttribute("aria-invalid","true")}else input.setAttribute("aria-invalid","true")});jQuery(document).trigger("frmAddFieldError",[jQuery(container),key,jsErrors])}function getErrorElementId(key,input){if(isNaN(key)||!input||!input.id)return`frm_error_field_${key}`;return`frm_error_${input.id}`}function removeFieldError(fieldCont){const container=fieldCont instanceof jQuery? +fieldCont.get(0):fieldCont;if(!container)return;const errorMessages=container.querySelectorAll(".frm_error, [data-frm-error]");const input=container.querySelector("input, select, textarea");container.classList.remove("frm_blank_field","has-error");if(input)if("true"===input.getAttribute("aria-invalid"))input.setAttribute("aria-invalid","false");else if(["radio","checkbox"].includes(input.type)){const group=input.closest('[role="radiogroup"], [role="group"]');if(group)group.setAttribute("aria-invalid", +"false")}errorMessages.forEach(errorMessage=>{removeElementFromInputDescribedBy(errorMessage);errorMessage.remove()})}function removeElementFromInputDescribedBy(el){document.querySelectorAll(`[aria-describedby*="${el.id}"]`).forEach(input=>{let ariaDescribedBy=input.getAttribute("aria-describedby").split(" ");ariaDescribedBy=ariaDescribedBy.filter(value=>{const trimmedValue=value.trim();return trimmedValue&&trimmedValue!==el.id});if(ariaDescribedBy.length){input.setAttribute("aria-describedby",ariaDescribedBy.join(" ")); +return}input.removeAttribute("aria-describedby")})}function removeAllErrors(){document.querySelectorAll(".form-field").forEach(field=>{field.classList.remove("frm_blank_field","has-error")});document.querySelectorAll(".form-field .frm_error, .form-field [data-frm-error]").forEach(el=>{removeElementFromInputDescribedBy(el);el.remove()});document.querySelectorAll(".frm_error_style").forEach(error=>error.remove())}function scrollToFirstField(object){if("function"===typeof object.get)object=object.get(0); +const field=object.querySelector(".frm_blank_field");if(field)frmFrontForm.scrollMsg(jQuery(field),object,true)}function showSubmitLoading($object){showLoadingIndicator($object);disableSubmitButton($object);disableSaveDraft($object)}function showLoadingIndicator($object){if(!$object.hasClass("frm_loading_form")&&!$object.hasClass("frm_loading_prev")){addLoadingClass($object);$object.trigger("frmStartFormLoading")}}function addLoadingClass($object){const loadingClass=isGoingToPrevPage($object)?"frm_loading_prev": +"frm_loading_form";$object.addClass(loadingClass)}function isGoingToPrevPage($object){return typeof frmProForm!=="undefined"&&frmProForm.goingToPreviousPage($object)}function removeSubmitLoading(_,enable,processesRunning){if(processesRunning>0)return;document.querySelectorAll(".frm_loading_form").forEach(function(form){form.classList.remove("frm_loading_form","frm_loading_prev");jQuery(form).trigger("frmEndFormLoading");if(enable==="enable"){enableSubmitButton(form);enableSaveDraft(form)}})}function showFileLoading(object){const loading= +document.getElementById("frm_loading");if(!loading)return;const fileInput=object.querySelector("input[type=file]");const fileval=fileInput?fileInput.value:"";if(fileval!=="")setTimeout(function(){jQuery(loading).fadeIn("slow")},2E3)}function confirmClick(){const message=this.dataset.frmconfirm;return confirm(message)}function onHoneypotFieldChange(){const css=window.getComputedStyle(this).boxShadow;if(css?.match(/inset/))this.remove()}function changeFocusWhenClickComboFieldLabel(){let label;const comboInputsContainer= +document.querySelectorAll(".frm_combo_inputs_container");comboInputsContainer.forEach(function(inputsContainer){if(!inputsContainer.closest(".frm_form_field"))return;label=inputsContainer.closest(".frm_form_field").querySelector(".frm_primary_label");if(!label)return;label.addEventListener("click",function(){inputsContainer.querySelector(".frm_form_field:first-child input, .frm_form_field:first-child select, .frm_form_field:first-child textarea").focus()})})}function maybeFocusOnComboSubField(element){if("FIELDSET"!== +element.nodeName)return false;if(!element.querySelector(".frm_combo_inputs_container"))return false;const comboSubfield=element.querySelector('[aria-invalid="true"]');if(comboSubfield){focusInput(comboSubfield);return true}return false}function checkForErrorsAndMaybeSetFocus(){const errors=document.querySelectorAll(".frm_form_field .frm_error, .frm_form_field [data-frm-error]");if(!errors.length)return;const formContainer=errors[0].closest(".frm-show-form");const config=getErrorConfigForForm(formContainer); +if(config.focusErrorSummary){const summary=formContainer?formContainer.querySelector("[data-frm-error-summary]"):null;if(summary){summary.focus();return}}if(!config.focusFirstError&&!config.focusErrorSummary)return;let element=errors[0];let timeoutCallback;do{element=element.previousSibling;if(!element)break;if(["input","select","textarea"].includes(element.nodeName.toLowerCase())){focusInput(element);break}if(maybeFocusOnComboSubField(element))break;if(element.classList!==undefined){if(element.classList.contains("html-active"))timeoutCallback= +function(){const textarea=element.querySelector("textarea");if(null!==textarea)textarea.focus()};else if(element.classList.contains("tmce-active"))timeoutCallback=function(){tinyMCE.activeEditor.focus()};else if(element.classList.contains("frm_opt_container")){const firstInput=element.querySelector("input");if(firstInput){focusInput(firstInput);break}}if("function"===typeof timeoutCallback){setTimeout(timeoutCallback,0);break}}}while(element.previousSibling)}function focusInput(input){if(input.offsetParent!== +null)input.focus();else triggerCustomEvent(document,"frmMaybeDelayFocus",{input})}function focusFieldFromErrorLink(event){const href=this.getAttribute("href");if(!href||!href.startsWith("#"))return;const container=document.getElementById(href.substring(1));if(!container)return;event.preventDefault();container.scrollIntoView({behavior:"smooth",block:"center"});const input=getFocusableInputInField(container);if(input){focusInput(input);return}container.setAttribute("tabindex","-1");focusInput(container)} +function getFocusableInputInField(container){const inputs=Array.from(container.querySelectorAll(FOCUSABLE_FIELD_SELECTOR)).filter(inputCanTakeFocus);if(!inputs.length)return null;const invalidInput=inputs.find(input=>"true"===input.getAttribute("aria-invalid"));if(invalidInput)return invalidInput;return inputs.find(fieldInputIsEmpty)||inputs[0]}function fieldInputIsEmpty(input){if("BUTTON"===input.nodeName||["button","checkbox","file","radio","submit"].includes(input.type))return false;return""=== +String(input.value||"").trim()}function inputCanTakeFocus(input){if(input.disabled||"hidden"===input.type)return false;const rect=input.getBoundingClientRect();if(!rect.width&&!rect.height)return false;return"hidden"!==getComputedStyle(input).visibility}function documentOn(event,selector,handler,options){if(options===undefined)options=false;document.addEventListener(event,function(e){let target;for(target=e.target;target&&target!=this;target=target.parentNode)if(target.matches&&target.matches(selector)){handler.call(target, +e);break}},options)}function initFloatingLabels(){const selector=".frm-show-form .frm_inside_container input, .frm-show-form .frm_inside_container select, .frm-show-form .frm_inside_container textarea";const floatClass="frm_label_float_top";const checkFloatLabel=function(input){const container=input.closest(".frm_inside_container");if(!container)return;const shouldFloatTop=input.value||document.activeElement===input;container.classList.toggle(floatClass,shouldFloatTop);if("SELECT"===input.tagName){const firstOpt= +input.querySelector("option:first-child");if(shouldFloatTop){if(firstOpt.hasAttribute("data-label")){firstOpt.textContent=firstOpt.getAttribute("data-label");firstOpt.removeAttribute("data-label")}}else if(firstOpt.textContent){firstOpt.setAttribute("data-label",firstOpt.textContent);firstOpt.textContent=""}}};const checkDropdownLabel=function(){document.querySelectorAll(`.frm-show-form .frm_inside_container:not(.${floatClass}) select`).forEach(function(input){const firstOpt=input.querySelector("option:first-child"); +if(firstOpt.textContent){firstOpt.setAttribute("data-label",firstOpt.textContent);firstOpt.textContent=""}})};["focus","blur","change"].forEach(function(eventName){documentOn(eventName,selector,function(event){checkFloatLabel(event.target)},true)});const runOnLoad=function(firstLoad){if(firstLoad&&document.activeElement&&["INPUT","SELECT","TEXTAREA"].includes(document.activeElement.tagName))checkFloatLabel(document.activeElement);else if(firstLoad)document.querySelectorAll(".frm_inside_container").forEach(function(container){const input= container.querySelector("input, select, textarea");if(input&&""!==input.value)checkFloatLabel(input)});checkDropdownLabel();calcProductsTotal()};runOnLoad(true);jQuery(document).on("frmPageChanged",function(event){runOnLoad()});document.addEventListener("frm_after_start_over",function(event){runOnLoad()})}function shouldUpdateValidityMessage(target){if("INPUT"!==target.nodeName)return false;if(!target.dataset.invmsg)return false;if("text"!==target.getAttribute("type"))return false;if(target.classList.contains("frm_verify"))return false; return true}function maybeClearCustomValidityMessage(event,field){let key;let isInvalid=false;if(!shouldUpdateValidityMessage(field))return;for(key in field.validity){if("customError"===key)continue;if("valid"!==key&&field.validity[key]===true){isInvalid=true;break}}if(!isInvalid)field.setCustomValidity("")}function initInlineSubmitAlignment(){let frameRequested=false;const scheduleAlignment=function(){if(frameRequested)return;frameRequested=true;window.requestAnimationFrame(function(){frameRequested= false;alignInlineSubmitButtons()})};alignInlineSubmitButtons();window.addEventListener("load",scheduleAlignment);window.addEventListener("resize",scheduleAlignment);const observed=new Set;const resizeObserver=new ResizeObserver(scheduleAlignment);const observeFields=()=>{for(const element of observed)if(!element.isConnected){resizeObserver.unobserve(element);observed.delete(element)}document.querySelectorAll(".frm_inline_form .frm_fields_container > *").forEach(element=>{if(!observed.has(element)){observed.add(element); diff --git a/tests/phpunit/fields/test_FrmCaptchaSpam.php b/tests/phpunit/fields/test_FrmCaptchaSpam.php index 9eae361951..218aca494f 100644 --- a/tests/phpunit/fields/test_FrmCaptchaSpam.php +++ b/tests/phpunit/fields/test_FrmCaptchaSpam.php @@ -413,4 +413,44 @@ public function test_front_end_only_bypasses_captcha_when_saving_spam() { $this->assertStringContainsString( 'data-save-as-spam="1"', $html, 'Saving spam should allow CAPTCHA errors to reach server validation.' ); } + + public function test_infopeak_sends_token_to_siteverify_and_explains_used_up_quota() { + $settings = FrmAppHelper::get_settings(); + $settings->active_captcha = 'infopeak'; + $settings->infopeak_pubkey = 'test-site-key'; + $settings->infopeak_privkey = 'test-secret-key'; + $_POST = array( 'infopeak-captcha-response' => 'test-token' ); + $requests = array(); + $record_request = function ( $preempt, $args, $url ) use ( &$requests ) { + $requests[] = array( $url, $args['body'] ); + return $preempt; + }; + add_filter( 'pre_http_request', $record_request, 9, 3 ); + $failed_codes = array(); + $record_codes = function ( $reason, $error_codes ) use ( &$failed_codes ) { + $failed_codes = $error_codes; + }; + add_action( 'frm_captcha_validation_failed', $record_codes, 10, 2 ); + + $this->response = array( 'body' => wp_json_encode( array( 'success' => true ) ) ); + $this->assertSame( array(), $this->validate_captcha(), 'A verified InfoPeak Captcha token should pass.' ); + + $this->response = array( + 'body' => wp_json_encode( + array( + 'success' => false, + 'error-codes' => array( 'quota-exceeded' ), + ) + ), + ); + $errors = $this->validate_captcha(); + remove_filter( 'pre_http_request', $record_request, 9 ); + remove_action( 'frm_captcha_validation_failed', $record_codes ); + + $this->assertSame( 'https://captcha.infopeak.io/siteverify', $requests[0][0], 'The token should be verified by InfoPeak Captcha.' ); + $this->assertSame( 'test-secret-key', $requests[0][1]['secret'], 'The InfoPeak Captcha secret key should be sent.' ); + $this->assertSame( 'test-token', $requests[0][1]['response'], 'The InfoPeak Captcha token should be sent.' ); + $this->assertStringContainsString( 'not set up correctly', $errors[ 'field' . $this->captcha->id ], 'A used up quota cannot be fixed by trying again.' ); + $this->assertSame( array( 'quota-exceeded' ), $failed_codes, 'The quota error code should be recorded.' ); + } } diff --git a/tests/phpunit/settings/test_FrmCaptchaFallback.php b/tests/phpunit/settings/test_FrmCaptchaFallback.php index 529e239f23..beba335c88 100644 --- a/tests/phpunit/settings/test_FrmCaptchaFallback.php +++ b/tests/phpunit/settings/test_FrmCaptchaFallback.php @@ -38,6 +38,7 @@ private function load_settings( $active, $configured ) { 'recaptcha' => '', 'hcaptcha' => 'hcaptcha_', 'turnstile' => 'turnstile_', + 'infopeak' => 'infopeak_', ); foreach ( $prefixes as $type => $prefix ) { @@ -52,7 +53,7 @@ private function load_settings( $active, $configured ) { } public function test_unsupported_selection_uses_first_configured_provider() { - $providers = array( 'recaptcha', 'hcaptcha', 'turnstile' ); + $providers = array( 'recaptcha', 'hcaptcha', 'turnstile', 'infopeak' ); foreach ( $providers as $expected ) { $settings = $this->load_settings( 'altcha', $providers ); @@ -64,8 +65,8 @@ public function test_unsupported_selection_uses_first_configured_provider() { } public function test_supported_selection_is_preserved() { - foreach ( array( 'recaptcha', 'hcaptcha', 'turnstile' ) as $type ) { - $settings = $this->load_settings( $type, array( 'recaptcha', 'hcaptcha', 'turnstile' ) ); + foreach ( array( 'recaptcha', 'hcaptcha', 'turnstile', 'infopeak' ) as $type ) { + $settings = $this->load_settings( $type, array( 'recaptcha', 'hcaptcha', 'turnstile', 'infopeak' ) ); $this->assertSame( $type, $settings->active_captcha ); } } @@ -94,6 +95,7 @@ public function test_fallback_renders_matching_captcha_and_loads_matching_script 'recaptcha' => array( 'g-recaptcha', 'https://www.google.com/recaptcha/api.js' ), 'hcaptcha' => array( 'h-captcha', 'https://js.hcaptcha.com/1/api.js' ), 'turnstile' => array( 'cf-turnstile', 'https://challenges.cloudflare.com/turnstile/v0/api.js' ), + 'infopeak' => array( 'infopeak-captcha', 'https://captcha.infopeak.io/infopeak-captcha.js' ), ); foreach ( $providers as $type => $expected ) {